aboutsummaryrefslogtreecommitdiffhomepage
path: root/parser.cpp
blob: 72b46c9f8d65ceeb528645822d2cc47f81d5519a (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
/** \file parser.c

The fish parser. Contains functions for parsing and evaluating code.

*/

#include "config.h"

#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include <pwd.h>
#include <dirent.h>
#include <signal.h>
#include <algorithm>

#include "fallback.h"
#include "util.h"

#include "common.h"
#include "wutil.h"
#include "proc.h"
#include "parser.h"
#include "parser_keywords.h"
#include "tokenizer.h"
#include "exec.h"
#include "wildcard.h"
#include "function.h"
#include "builtin.h"
#include "env.h"
#include "expand.h"
#include "reader.h"
#include "sanity.h"
#include "env_universal.h"
#include "event.h"
#include "intern.h"
#include "parse_util.h"
#include "path.h"
#include "signal.h"
#include "complete.h"

/**
   Maximum number of function calls, i.e. recursion depth.
*/
#define MAX_RECURSION_DEPTH 128

/**
   Error message for unknown builtin
*/
#define UNKNOWN_BUILTIN_ERR_MSG _(L"Unknown builtin '%ls'")

/**
   Error message for improper use of the exec builtin
*/
#define EXEC_ERR_MSG _(L"This command can not be used in a pipeline")

/**
   Error message for tokenizer error. The tokenizer message is
   appended to this message.
*/
#define TOK_ERR_MSG _( L"Tokenizer error: '%ls'")

/**
   Error message for short circuit command error.
*/
#define COND_ERR_MSG _( L"An additional command is required" )

/**
   Error message on a function that calls itself immediately
*/
#define INFINITE_RECURSION_ERR_MSG _( L"The function calls itself immediately, which would result in an infinite loop.")

/**
   Error message on reaching maximum recursion depth
*/
#define OVERFLOW_RECURSION_ERR_MSG _( L"Maximum recursion depth reached. Accidental infinite loop?")

/**
   Error message used when the end of a block can't be located
*/
#define BLOCK_END_ERR_MSG _( L"Could not locate end of block. The 'end' command is missing, misspelled or a ';' is missing.")

/**
   Error message on reaching maximum number of block calls
*/
#define BLOCK_ERR_MSG _( L"Maximum number of nested blocks reached.")

/**
   Error message when a non-string token is found when expecting a command name
*/
#define CMD_ERR_MSG _( L"Expected a command name, got token of type '%ls'")

/**
   Error message when a non-string token is found when expecting a command name
*/
#define CMD_OR_ERR_MSG _( L"Expected a command name, got token of type '%ls'. Did you mean 'COMMAND; or COMMAND'? See the help section for the 'or' builtin command by typing 'help or'.")

/**
   Error message when a non-string token is found when expecting a command name
*/
#define CMD_AND_ERR_MSG _( L"Expected a command name, got token of type '%ls'. Did you mean 'COMMAND; and COMMAND'? See the help section for the 'and' builtin command by typing 'help and'.")

/**
   Error message when encountering an illegal command name
*/
#define ILLEGAL_CMD_ERR_MSG _( L"Illegal command name '%ls'")

/**
   Error message when encountering an illegal file descriptor
*/
#define ILLEGAL_FD_ERR_MSG _( L"Illegal file descriptor '%ls'")

/**
   Error message for wildcards with no matches
*/
#define WILDCARD_ERR_MSG _( L"No matches for wildcard '%ls'.")

/**
   Error when using case builtin outside of switch block
*/
#define INVALID_CASE_ERR_MSG _( L"'case' builtin not inside of switch block")

/**
   Error when using loop control builtins (break or continue) outside of loop
*/
#define INVALID_LOOP_ERR_MSG _( L"Loop control command while not inside of loop" )

/**
   Error when using return builtin outside of function definition
*/
#define INVALID_RETURN_ERR_MSG _( L"'return' builtin command outside of function definition" )

/**
   Error when using else builtin outside of if block
*/
#define INVALID_ELSE_ERR_MSG _( L"'%ls' builtin not inside of if block" )

/**
   Error when using 'else if' past a naked 'else'
*/
#define INVALID_ELSEIF_PAST_ELSE_ERR_MSG _( L"'%ls' used past terminating 'else'" )

/**
   Error when using end builtin outside of block
*/
#define INVALID_END_ERR_MSG _( L"'end' command outside of block")

/**
   Error message for Posix-style assignment: foo=bar
*/
#define COMMAND_ASSIGN_ERR_MSG _( L"Unknown command '%ls'. Did you mean 'set %ls %ls'? See the help section on the set command by typing 'help set'.")

/**
   Error for invalid redirection token
*/
#define REDIRECT_TOKEN_ERR_MSG _( L"Expected redirection specification, got token of type '%ls'")

/**
   Error when encountering redirection without a command
*/
#define INVALID_REDIRECTION_ERR_MSG _( L"Encountered redirection when expecting a command name. Fish does not allow a redirection operation before a command.")

/**
   Error for evaluating null pointer
*/
#define EVAL_NULL_ERR_MSG _( L"Tried to evaluate null pointer." )

/**
   Error for evaluating in illegal scope
*/
#define INVALID_SCOPE_ERR_MSG _( L"Tried to evaluate commands using invalid block type '%ls'" )


/**
   Error for wrong token type
*/
#define UNEXPECTED_TOKEN_ERR_MSG _( L"Unexpected token of type '%ls'")

/**
   While block description
*/
#define WHILE_BLOCK N_( L"'while' block" )

/**
   For block description
*/
#define FOR_BLOCK N_( L"'for' block" )

/**
   Breakpoint block
*/
#define BREAKPOINT_BLOCK N_( L"Block created by breakpoint" )



/**
   If block description
*/
#define IF_BLOCK N_( L"'if' conditional block" )


/**
   Function definition block description
*/
#define FUNCTION_DEF_BLOCK N_( L"function definition block" )


/**
   Function invocation block description
*/
#define FUNCTION_CALL_BLOCK N_( L"function invocation block" )

/**
   Function invocation block description
*/
#define FUNCTION_CALL_NO_SHADOW_BLOCK N_( L"function invocation block with no variable shadowing" )


/**
   Switch block description
*/
#define SWITCH_BLOCK N_( L"'switch' block" )


/**
   Fake block description
*/
#define FAKE_BLOCK N_( L"unexecutable block" )


/**
   Top block description
*/
#define TOP_BLOCK N_( L"global root block" )


/**
   Command substitution block description
*/
#define SUBST_BLOCK N_( L"command substitution block" )


/**
   Begin block description
*/
#define BEGIN_BLOCK N_( L"'begin' unconditional block" )


/**
   Source block description
*/
#define SOURCE_BLOCK N_( L"Block created by the . builtin" )

/**
   Source block description
*/
#define EVENT_BLOCK N_( L"event handler block" )


/**
   Unknown block description
*/
#define UNKNOWN_BLOCK N_( L"unknown/invalid block" )


/**
   Datastructure to describe a block type, like while blocks, command substitution blocks, etc.
*/
struct block_lookup_entry
{

    /**
       The block type id. The legal values are defined in parser.h.
    */
    block_type_t type;

    /**
       The name of the builtin that creates this type of block, if any.
    */
    const wchar_t *name;

    /**
       A description of this block type
    */
    const wchar_t *desc;
}
;

/**
   List of all legal block types
*/
static const struct block_lookup_entry block_lookup[]=
{
    { WHILE, L"while", WHILE_BLOCK },
    { FOR, L"for", FOR_BLOCK },
    { IF, L"if", IF_BLOCK },
    { FUNCTION_DEF, L"function", FUNCTION_DEF_BLOCK },
    { FUNCTION_CALL, 0, FUNCTION_CALL_BLOCK },
    { FUNCTION_CALL_NO_SHADOW, 0, FUNCTION_CALL_NO_SHADOW_BLOCK },
    { SWITCH, L"switch", SWITCH_BLOCK },
    { FAKE, 0, FAKE_BLOCK },
    { TOP, 0, TOP_BLOCK },
    { SUBST, 0, SUBST_BLOCK },
    { BEGIN, L"begin", BEGIN_BLOCK },
    { SOURCE, L".", SOURCE_BLOCK },
    { EVENT, 0, EVENT_BLOCK },
    { BREAKPOINT, L"breakpoint", BREAKPOINT_BLOCK },
    { (block_type_t)0, 0, 0 }
};

static bool job_should_skip_elseif(const job_t *job, const block_t *current_block);

parser_t::parser_t(enum parser_type_t type, bool errors) :
    parser_type(type),
    show_errors(errors),
    error_code(0),
    err_pos(0),
    current_tokenizer(NULL),
    current_tokenizer_pos(0),
    job_start_pos(0),
    eval_level(-1),
    current_block(NULL),
    block_io(shared_ptr<io_data_t>())
{

}

/* A pointer to the principal parser (which is a static local) */
static parser_t *s_principal_parser = NULL;

parser_t &parser_t::principal_parser(void)
{
    ASSERT_IS_NOT_FORKED_CHILD();
    ASSERT_IS_MAIN_THREAD();
    static parser_t parser(PARSER_TYPE_GENERAL, true);
    if (! s_principal_parser)
    {
        s_principal_parser = &parser;
    }
    return parser;
}

void parser_t::skip_all_blocks(void)
{
    /* Tell all blocks to skip */
    if (s_principal_parser)
    {
        //write(2, "Cancelling blocks\n", strlen("Cancelling blocks\n"));
        block_t *c = s_principal_parser->current_block;
        while (c)
        {
            c->skip = true;
            //fprintf(stderr, "   Cancelled %p\n", c);
            c = c->outer;
        }
    }
}

void parser_t::push_block(block_t *newv)
{
    const enum block_type_t type = newv->type();
    newv->src_lineno = parser_t::get_lineno();
    newv->src_filename = parser_t::current_filename()?intern(parser_t::current_filename()):0;

    newv->outer = current_block;
    if (current_block && current_block->skip)
        newv->mark_as_fake();

    /*
      New blocks should be skipped if the outer block is skipped,
      except TOP ans SUBST block, which open up new environments. Fake
      blocks should always be skipped. Rather complicated... :-(
    */
    newv->skip=current_block?current_block->skip:0;

    /*
      Type TOP and SUBST are never skipped
    */
    if (type == TOP || type == SUBST)
    {
        newv->skip = 0;
    }

    /*
      Fake blocks and function definition blocks are never executed
    */
    if (type == FAKE || type == FUNCTION_DEF)
    {
        newv->skip = 1;
    }

    newv->job = 0;
    newv->loop_status=LOOP_NORMAL;

    current_block = newv;

    if ((newv->type() != FUNCTION_DEF) &&
            (newv->type() != FAKE) &&
            (newv->type() != TOP))
    {
        env_push(type == FUNCTION_CALL);
        newv->wants_pop_env = true;
    }
}

void parser_t::pop_block()
{
    block_t *old = current_block;
    if (!current_block)
    {
        debug(1,
              L"function %s called on empty block stack.",
              __func__);
        bugreport();
        return;
    }

    current_block = current_block->outer;

    if (old->wants_pop_env)
        env_pop();

    delete old;
}

const wchar_t *parser_t::get_block_desc(int block) const
{
    for (size_t i=0; block_lookup[i].desc; i++)
    {
        if (block_lookup[i].type == block)
        {
            return _(block_lookup[i].desc);
        }
    }
    return _(UNKNOWN_BLOCK);
}

/**
   Returns 1 if the specified command is a builtin that may not be used in a pipeline
*/
static int parser_is_pipe_forbidden(const wcstring &word)
{
    return contains(word,
                    L"exec",
                    L"case",
                    L"break",
                    L"return",
                    L"continue");
}

/**
   Search the text for the end of the current block
*/
static const wchar_t *parser_find_end(const wchar_t * buff)
{
    int had_cmd=0;
    int count = 0;
    int error=0;
    int mark=0;

    CHECK(buff, 0);

    tokenizer_t tok(buff, 0);
    for (; tok_has_next(&tok) && !error; tok_next(&tok))
    {
        int last_type = tok_last_type(&tok);
        switch (last_type)
        {
            case TOK_STRING:
            {
                if (!had_cmd)
                {
                    if (wcscmp(tok_last(&tok), L"end")==0)
                    {
                        count--;
                    }
                    else if (parser_keywords_is_block(tok_last(&tok)))
                    {
                        count++;
                    }

                    if (count < 0)
                    {
                        error = 1;
                    }
                    had_cmd = 1;
                }
                break;
            }

            case TOK_END:
            {
                had_cmd = 0;
                break;
            }

            case TOK_PIPE:
            case TOK_BACKGROUND:
            {
                if (had_cmd)
                {
                    had_cmd = 0;
                }
                else
                {
                    error = 1;
                }
                break;

            }

            case TOK_ERROR:
                error = 1;
                break;

            default:
                break;

        }
        if (!count)
        {
            tok_next(&tok);
            mark = tok_get_pos(&tok);
            break;
        }

    }
    if (!count && !error)
    {

        return buff+mark;
    }
    return 0;

}


void parser_t::forbid_function(const wcstring &function)
{
    forbidden_function.push_back(function);
}

void parser_t::allow_function()
{
    /*
      if( al_peek( &forbidden_function) )
      debug( 2, L"Allow %ls\n", al_peek( &forbidden_function)  );
    */
    forbidden_function.pop_back();
}

void parser_t::error(int ec, int p, const wchar_t *str, ...)
{
    va_list va;

    CHECK(str,);

    error_code = ec;
    err_pos = p;

    va_start(va, str);
    err_buff = vformat_string(str, va);
    va_end(va);

}

/**
   Print profiling information to the specified stream
*/
static void print_profile(const std::vector<profile_item_t*> &items,
                          FILE *out)
{
    size_t pos;
    for (pos = 0; pos < items.size(); pos++)
    {
        const profile_item_t *me, *prev;
        size_t i;
        int my_time;

        me = items.at(pos);
        if (!me->skipped)
        {
            my_time=me->parse+me->exec;

            for (i=pos+1; i<items.size(); i++)
            {
                prev = items.at(i);
                if (prev->skipped)
                {
                    continue;
                }

                if (prev->level <= me->level)
                {
                    break;
                }

                if (prev->level > me->level+1)
                {
                    continue;
                }

                my_time -= prev->parse;
                my_time -= prev->exec;
            }

            if (me->cmd.size() > 0)
            {
                if (fwprintf(out, L"%d\t%d\t", my_time, me->parse+me->exec) < 0)
                {
                    wperror(L"fwprintf");
                    return;
                }

                for (i=0; i<me->level; i++)
                {
                    if (fwprintf(out, L"-") < 0)
                    {
                        wperror(L"fwprintf");
                        return;
                    }

                }
                if (fwprintf(out, L"> %ls\n", me->cmd.c_str()) < 0)
                {
                    wperror(L"fwprintf");
                    return;
                }

            }
            delete me;
        }
    }
}

void parser_t::destroy()
{
    if (profile)
    {
        /* Save profiling information. OK to not use CLO_EXEC here because this is called while fish is dying (and hence will not fork) */
        FILE *f = fopen(profile, "w");
        if (!f)
        {
            debug(1,
                  _(L"Could not write profiling information to file '%s'"),
                  profile);
        }
        else
        {
            if (fwprintf(f,
                         _(L"Time\tSum\tCommand\n"),
                         profile_items.size()) < 0)
            {
                wperror(L"fwprintf");
            }
            else
            {
                print_profile(profile_items, f);
            }

            if (fclose(f))
            {
                wperror(L"fclose");
            }
        }
    }

    lineinfo.clear();

    forbidden_function.clear();

}

/**
   Print error message to string if an error has occured while parsing

   \param target the buffer to write to
   \param prefix: The string token to prefix the each line with. Usually the name of the command trying to parse something.
*/
void parser_t::print_errors(wcstring &target, const wchar_t *prefix)
{
    CHECK(prefix,);

    if (error_code && ! err_buff.empty())
    {
        int tmp;

        append_format(target, L"%ls: %ls\n", prefix, err_buff.c_str());

        tmp = current_tokenizer_pos;
        current_tokenizer_pos = err_pos;

        append_format(target, L"%ls", this->current_line());

        current_tokenizer_pos=tmp;
    }
}

/**
   Print error message to stderr if an error has occured while parsing
*/
void parser_t::print_errors_stderr()
{
    if (error_code && ! err_buff.empty())
    {
        debug(0, L"%ls", err_buff.c_str());
        int tmp;

        tmp = current_tokenizer_pos;
        current_tokenizer_pos = err_pos;

        fwprintf(stderr, L"%ls", this->current_line());

        current_tokenizer_pos=tmp;
    }

}

int parser_t::eval_args(const wchar_t *line, std::vector<completion_t> &args)
{

    expand_flags_t eflags = 0;
    if (! show_errors)
        eflags |= EXPAND_NO_DESCRIPTIONS;
    if (this->parser_type != PARSER_TYPE_GENERAL)
        eflags |= EXPAND_SKIP_CMDSUBST;

    int do_loop=1;

    CHECK(line, 1);
//  CHECK( args, 1 );

    // PCA we need to suppress calling proc_push_interactive off of the main thread. I'm not sure exactly what it does.
    if (this->parser_type == PARSER_TYPE_GENERAL)
        proc_push_interactive(0);

    tokenizer_t tok(line, (show_errors ? 0 : TOK_SQUASH_ERRORS));

    /*
      eval_args may be called while evaulating another command, so we
      save the previous tokenizer and restore it on exit
    */
    scoped_push<tokenizer_t*> tokenizer_push(&current_tokenizer, &tok);
    scoped_push<int> tokenizer_pos_push(&current_tokenizer_pos, 0);

    error_code=0;

    for (; do_loop && tok_has_next(&tok) ; tok_next(&tok))
    {
        current_tokenizer_pos = tok_get_pos(&tok);
        switch (tok_last_type(&tok))
        {
            case TOK_STRING:
            {
                const wcstring tmp = tok_last(&tok);
                if (expand_string(tmp, args, eflags) == EXPAND_ERROR)
                {
                    err_pos=tok_get_pos(&tok);
                    do_loop=0;
                }
                break;
            }

            case TOK_END:
            {
                break;
            }

            case TOK_ERROR:
            {
                if (show_errors)
                    error(SYNTAX_ERROR,
                          tok_get_pos(&tok),
                          TOK_ERR_MSG,
                          tok_last(&tok));

                do_loop=0;
                break;
            }

            default:
            {
                if (show_errors)
                    error(SYNTAX_ERROR,
                          tok_get_pos(&tok),
                          UNEXPECTED_TOKEN_ERR_MSG,
                          tok_get_desc(tok_last_type(&tok)));

                do_loop=0;
                break;
            }
        }
    }

    if (show_errors)
        this->print_errors_stderr();

    if (this->parser_type == PARSER_TYPE_GENERAL)
        proc_pop_interactive();

    return 1;
}

void parser_t::stack_trace(block_t *b, wcstring &buff)
{
    /*
      Check if we should end the recursion
    */
    if (!b)
        return;

    if (b->type()==EVENT)
    {
        /*
          This is an event handler
        */
        const event_block_t *eb = static_cast<const event_block_t *>(b);
        wcstring description = event_get_desc(eb->event);
        append_format(buff, _(L"in event handler: %ls\n"), description.c_str());
        buff.append(L"\n");

        /*
          Stop recursing at event handler. No reason to believe that
          any other code is relevant.

          It might make sense in the future to continue printing the
          stack trace of the code that invoked the event, if this is a
          programmatic event, but we can't currently detect that.
        */
        return;
    }

    if (b->type() == FUNCTION_CALL || b->type()==SOURCE || b->type()==SUBST)
    {
        /*
          These types of blocks should be printed
        */

        int i;

        switch (b->type())
        {
            case SOURCE:
            {
                const source_block_t *sb = static_cast<const source_block_t*>(b);
                const wchar_t *source_dest = sb->source_file;
                append_format(buff, _(L"in . (source) call of file '%ls',\n"), source_dest);
                break;
            }
            case FUNCTION_CALL:
            {
                const function_block_t *fb = static_cast<const function_block_t*>(b);
                append_format(buff, _(L"in function '%ls',\n"), fb->name.c_str());
                break;
            }
            case SUBST:
            {
                append_format(buff, _(L"in command substitution\n"));
                break;
            }

            default: /* Can't get here */
                break;
        }

        const wchar_t *file = b->src_filename;

        if (file)
        {
            append_format(buff,
                          _(L"\tcalled on line %d of file '%ls',\n"),
                          b->src_lineno,
                          file);
        }
        else
        {
            append_format(buff,
                          _(L"\tcalled on standard input,\n"));
        }

        if (b->type() == FUNCTION_CALL)
        {
            const function_block_t *fb = static_cast<const function_block_t *>(b);
            const process_t * const process = fb->process;
            if (process->argv(1))
            {
                wcstring tmp;

                for (i=1; process->argv(i); i++)
                {
                    if (i > 1)
                        tmp.push_back(L' ');
                    tmp.append(process->argv(i));
                }
                append_format(buff, _(L"\twith parameter list '%ls'\n"), tmp.c_str());
            }
        }

        append_format(buff, L"\n");
    }

    /*
      Recursively print the next block
    */
    parser_t::stack_trace(b->outer, buff);
}

/**
   Returns the name of the currently evaluated function if we are
   currently evaluating a function, null otherwise. This is tested by
   moving down the block-scope-stack, checking every block if it is of
   type FUNCTION_CALL.
*/
const wchar_t *parser_t::is_function() const
{
    // PCA: Have to make this a string somehow
    ASSERT_IS_MAIN_THREAD();
    wcstring result;

    block_t *b = current_block;
    while (1)
    {
        if (!b)
        {
            return NULL;
        }
        if (b->type() == FUNCTION_CALL)
        {
            const function_block_t *fb = static_cast<const function_block_t *>(b);
            return fb->name.c_str();
        }
        b=b->outer;
    }
}


int parser_t::get_lineno() const
{
    int lineno;

    if (! current_tokenizer || ! tok_string(current_tokenizer))
        return -1;

    lineno = current_tokenizer->line_number_of_character_at_offset(current_tokenizer_pos);

    const wchar_t *function_name;
    if ((function_name = is_function()))
    {
        lineno += function_get_definition_offset(function_name);
    }

    return lineno;
}

int parser_t::line_number_of_character_at_offset(size_t idx) const
{
    if (! current_tokenizer)
        return -1;

    int result = current_tokenizer->line_number_of_character_at_offset(idx);
    //assert(result == parse_util_lineno(tok_string( current_tokenizer ), idx));
    return result;
}

const wchar_t *parser_t::current_filename() const
{
    /* We query a global array for the current file name, so it only makes sense to ask this on the principal parser. */
    ASSERT_IS_MAIN_THREAD();
    assert(this == &principal_parser());

    block_t *b = current_block;

    while (1)
    {
        if (!b)
        {
            return reader_current_filename();
        }
        if (b->type() == FUNCTION_CALL)
        {
            const function_block_t *fb = static_cast<const function_block_t *>(b);
            return function_get_definition_file(fb->name);
        }
        b=b->outer;
    }
}

/**
   Calculates the on-screen width of the specified substring of the
   specified string. This function takes into account the width and
   alignment of the tab character, but other wise behaves like
   repeatedly calling wcwidth.
*/
static int printed_width(const wchar_t *str, int len)
{
    int res=0;
    int i;

    CHECK(str, 0);

    for (i=0; str[i] && i<len; i++)
    {
        if (str[i] == L'\t')
        {
            res=(res+8)&~7;
        }
        else
        {
            res += fish_wcwidth(str[i]);
        }
    }
    return res;
}


const wchar_t *parser_t::current_line()
{
    int lineno=1;

    const wchar_t *file;
    const wchar_t *whole_str;
    const wchar_t *line;
    const wchar_t *line_end;
    int i;
    int offset;
    int current_line_width;
    const wchar_t *function_name=0;
    int current_line_start=0;

    if (!current_tokenizer)
    {
        return L"";
    }

    file = parser_t::current_filename();
    whole_str = tok_string(current_tokenizer);
    line = whole_str;

    if (!line)
        return L"";


    lineinfo.clear();

    /*
      Calculate line number, line offset, etc.
    */
    for (i=0; i<current_tokenizer_pos && whole_str[i]; i++)
    {
        if (whole_str[i] == L'\n')
        {
            lineno++;
            current_line_start=i+1;
            line = &whole_str[i+1];
        }
    }

//  lineno = current_tokenizer_pos;


    current_line_width=printed_width(whole_str+current_line_start,
                                     current_tokenizer_pos-current_line_start);

    if ((function_name = is_function()))
    {
        lineno += function_get_definition_offset(function_name);
    }

    /*
      Copy current line from whole string
    */
    line_end = wcschr(line, L'\n');
    if (!line_end)
        line_end = line+wcslen(line);

    line = wcsndup(line, line_end-line);

    /**
       If we are not going to print a stack trace, at least print the line number and filename
    */
    if (!get_is_interactive() || is_function())
    {
        int prev_width = my_wcswidth(lineinfo.c_str());
        if (file)
            append_format(lineinfo,
                          _(L"%ls (line %d): "),
                          file,
                          lineno);
        else
            append_format(lineinfo,
                          L"%ls: ",
                          _(L"Standard input"),
                          lineno);
        offset = my_wcswidth(lineinfo.c_str()) - prev_width;
    }
    else
    {
        offset=0;
    }

//  debug( 1, L"Current pos %d, line pos %d, file_length %d, is_interactive %d, offset %d\n", current_tokenizer_pos,  current_line_pos, wcslen(whole_str), is_interactive, offset);
    /*
      Skip printing character position if we are in interactive mode
      and the error was on the first character of the line.
    */
    if (!get_is_interactive() || is_function() || (current_line_width!=0))
    {
        // Workaround since it seems impossible to print 0 copies of a character using %*lc
        if (offset+current_line_width)
        {
            append_format(lineinfo,
                          L"%ls\n%*lc^\n",
                          line,
                          offset+current_line_width,
                          L' ');
        }
        else
        {
            append_format(lineinfo,
                          L"%ls\n^\n",
                          line);
        }
    }

    free((void *)line);
    parser_t::stack_trace(current_block, lineinfo);

    return lineinfo.c_str();
}

int parser_t::get_pos() const
{
    return tok_get_pos(current_tokenizer);
}

int parser_t::get_job_pos() const
{
    return job_start_pos;
}


void parser_t::set_pos(int p)
{
    tok_set_pos(current_tokenizer, p);
}

const wchar_t *parser_t::get_buffer() const
{
    return tok_string(current_tokenizer);
}


int parser_t::is_help(const wchar_t *s, int min_match) const
{
    CHECK(s, 0);

    size_t len = wcslen(s);

    min_match = maxi(min_match, 3);

    return (wcscmp(L"-h", s) == 0) ||
           (len >= (size_t)min_match && (wcsncmp(L"--help", s, len) == 0));
}

job_t *parser_t::job_create()
{
    job_t *res = new job_t(acquire_job_id(), this->block_io);
    this->my_job_list.push_front(res);

    job_set_flag(res,
                 JOB_CONTROL,
                 (job_control_mode==JOB_CONTROL_ALL) ||
                 ((job_control_mode == JOB_CONTROL_INTERACTIVE) && (get_is_interactive())));
    return res;
}

bool parser_t::job_remove(job_t *j)
{
    job_list_t::iterator iter = std::find(my_job_list.begin(), my_job_list.end(), j);
    if (iter != my_job_list.end())
    {
        my_job_list.erase(iter);
        return true;
    }
    else
    {
        debug(1, _(L"Job inconsistency"));
        sanity_lose();
        return false;
    }
}

void parser_t::job_promote(job_t *job)
{
    signal_block();

    job_list_t::iterator loc = std::find(my_job_list.begin(), my_job_list.end(), job);
    assert(loc != my_job_list.end());

    /* Move the job to the beginning */
    my_job_list.splice(my_job_list.begin(), my_job_list, loc);
    signal_unblock();
}

job_t *parser_t::job_get(job_id_t id)
{
    job_iterator_t jobs(my_job_list);
    job_t *job;
    while ((job = jobs.next()))
    {
        if (id <= 0 || job->job_id == id)
            return job;
    }
    return NULL;
}

job_t *parser_t::job_get_from_pid(int pid)
{
    job_iterator_t jobs;
    job_t *job;
    while ((job = jobs.next()))
    {
        if (job->pgid == pid)
            return job;
    }
    return 0;
}

/**
   Parse options for the specified job

   \param p the process to parse options for
   \param j the job to which the process belongs to
   \param tok the tokenizer to read options from
   \param args the argument list to insert options into
   \param args unskip whether we should ignore current_block->skip. Big hack because of our dumb handling of if statements.
*/
void parser_t::parse_job_argument_list(process_t *p,
                                       job_t *j,
                                       tokenizer_t *tok,
                                       std::vector<completion_t> &args,
                                       bool unskip)
{
    int is_finished=0;

    int proc_is_count=0;

    int matched_wildcard = 0, unmatched_wildcard = 0;

    wcstring unmatched;
    int unmatched_pos=0;

    /* The set of IO redirections that we construct for the process */
    io_chain_t process_io_chain;

    /*
      Test if this is the 'count' command. We need to special case
      count in the shell, since it should display a help message on
      'count -h', but not on 'set foo -h; count $foo'. This is an ugly
      workaround and a huge hack, but as near as I can tell, the
      alternatives are worse.
    */
    proc_is_count = (args.at(0).completion == L"count");

    while (1)
    {

        switch (tok_last_type(tok))
        {
            case TOK_PIPE:
            {
                wchar_t *end;

                if (p->type == INTERNAL_EXEC)
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(tok),
                          EXEC_ERR_MSG);
                    return;
                }

                errno = 0;
                p->pipe_write_fd = fish_wcstoi(tok_last(tok), &end, 10);
                if (p->pipe_write_fd < 0 || errno || *end)
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(tok),
                          ILLEGAL_FD_ERR_MSG,
                          tok_last(tok));
                    return;
                }

                p->set_argv(completions_to_wcstring_list(args));
                p->next = new process_t();

                tok_next(tok);

                /*
                  Don't do anything on failure. parse_job will notice
                  the error flag and report any errors for us
                */
                parse_job(p->next, j, tok);

                is_finished = 1;
                break;
            }

            case TOK_BACKGROUND:
            {
                job_set_flag(j, JOB_FOREGROUND, 0);
            }

            case TOK_END:
            {
                if (!p->get_argv())
                    p->set_argv(completions_to_wcstring_list(args));
                if (tok_has_next(tok))
                    tok_next(tok);

                is_finished = 1;

                break;
            }

            case TOK_STRING:
            {
                int skip=0;

                if (job_get_flag(j, JOB_SKIP))
                {
                    skip = 1;
                }
                else if (current_block->skip && ! unskip)
                {
                    /*
                      If this command should be skipped, we do not expand the arguments
                    */
                    skip=1;

                    /* But if this is in fact a case statement or an elseif statement, then it should be evaluated */
                    block_type_t type = current_block->type();
                    if (type == SWITCH && args.at(0).completion == L"case" && p->type == INTERNAL_BUILTIN)
                    {
                        skip=0;
                    }
                    else if (job_get_flag(j, JOB_ELSEIF) && ! job_should_skip_elseif(j, current_block))
                    {
                        skip=0;
                    }
                }
                else
                {
                    /* If this is an else if, and we should skip it, then don't expand any arguments */
                    if (job_get_flag(j, JOB_ELSEIF) && job_should_skip_elseif(j, current_block))
                    {
                        skip = 1;
                    }
                }

                if (!skip)
                {
                    if ((proc_is_count) &&
                            (args.size() == 1) &&
                            (parser_t::is_help(tok_last(tok), 0)) &&
                            (p->type == INTERNAL_BUILTIN))
                    {
                        /*
                          Display help for count
                        */
                        p->count_help_magic = 1;
                    }

                    switch (expand_string(tok_last(tok), args, 0))
                    {
                        case EXPAND_ERROR:
                        {
                            err_pos=tok_get_pos(tok);
                            if (error_code == 0)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(tok),
                                      _(L"Could not expand string '%ls'"),
                                      tok_last(tok));

                            }
                            break;
                        }

                        case EXPAND_WILDCARD_NO_MATCH:
                        {
                            unmatched_wildcard = 1;
                            if (unmatched.empty())
                            {
                                unmatched = tok_last(tok);
                                unmatched_pos = tok_get_pos(tok);
                            }

                            break;
                        }

                        case EXPAND_WILDCARD_MATCH:
                        {
                            matched_wildcard = 1;
                            break;
                        }

                        case EXPAND_OK:
                        {
                            break;
                        }

                    }

                }

                break;
            }

            case TOK_REDIRECT_OUT:
            case TOK_REDIRECT_IN:
            case TOK_REDIRECT_APPEND:
            case TOK_REDIRECT_FD:
            case TOK_REDIRECT_NOCLOB:
            {
                int type = tok_last_type(tok);
                shared_ptr<io_data_t> new_io;
                wcstring target;
                bool has_target = false;
                wchar_t *end;

                /*
                  Don't check redirections in skipped part

                  Otherwise, bogus errors may be the result. (Do check
                  that token is string, though)
                */
                if (current_block->skip && ! unskip)
                {
                    tok_next(tok);
                    if (tok_last_type(tok) != TOK_STRING)
                    {
                        error(SYNTAX_ERROR,
                              tok_get_pos(tok),
                              REDIRECT_TOKEN_ERR_MSG,
                              tok_get_desc(tok_last_type(tok)));
                    }

                    break;
                }


                errno = 0;
                int fd = fish_wcstoi(tok_last(tok),
                                     &end,
                                     10);
                if (fd < 0 || errno || *end)
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(tok),
                          ILLEGAL_FD_ERR_MSG,
                          tok_last(tok));
                }
                else
                {

                    tok_next(tok);

                    switch (tok_last_type(tok))
                    {
                        case TOK_STRING:
                        {
                            target = tok_last(tok);
                            has_target = expand_one(target, no_exec ? EXPAND_SKIP_VARIABLES : 0);

                            if (! has_target && error_code == 0)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(tok),
                                      REDIRECT_TOKEN_ERR_MSG,
                                      tok_last(tok));

                            }
                            break;
                        }

                        default:
                            error(SYNTAX_ERROR,
                                  tok_get_pos(tok),
                                  REDIRECT_TOKEN_ERR_MSG,
                                  tok_get_desc(tok_last_type(tok)));
                    }

                    if (! has_target || target.empty())
                    {
                        if (error_code == 0)
                            error(SYNTAX_ERROR,
                                  tok_get_pos(tok),
                                  _(L"Invalid IO redirection"));
                        tok_next(tok);
                    }
                    else if (type == TOK_REDIRECT_FD)
                    {
                        if (target == L"-")
                        {
                            new_io.reset(new io_close_t(fd));
                        }
                        else
                        {
                            wchar_t *end;

                            errno = 0;

                            int old_fd = fish_wcstoi(target.c_str(), &end, 10);

                            if (old_fd < 0 || errno || *end)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(tok),
                                      _(L"Requested redirection to something that is not a file descriptor %ls"),
                                      target.c_str());

                                tok_next(tok);
                            }
                            else
                            {
                                new_io.reset(new io_fd_t(fd, old_fd));
                            }
                        }
                    }
                    else
                    {
                        int flags = 0;
                        switch (type)
                        {
                            case TOK_REDIRECT_APPEND:
                                flags = O_CREAT | O_APPEND | O_WRONLY;
                                break;

                            case TOK_REDIRECT_OUT:
                                flags = O_CREAT | O_WRONLY | O_TRUNC;
                                break;

                            case TOK_REDIRECT_NOCLOB:
                                flags = O_CREAT | O_EXCL | O_WRONLY;
                                break;

                            case TOK_REDIRECT_IN:
                                flags = O_RDONLY;
                                break;

                        }
                        io_file_t *new_io_file = new io_file_t(fd, target, flags);
                        new_io.reset(new_io_file);
                    }
                }

                if (new_io.get() != NULL)
                {
                    process_io_chain.push_back(new_io);
                }

            }
            break;

            case TOK_ERROR:
            {
                error(SYNTAX_ERROR,
                      tok_get_pos(tok),
                      TOK_ERR_MSG,
                      tok_last(tok));

                return;
            }

            default:
                error(SYNTAX_ERROR,
                      tok_get_pos(tok),
                      UNEXPECTED_TOKEN_ERR_MSG,
                      tok_get_desc(tok_last_type(tok)));

                tok_next(tok);
                break;
        }

        if ((is_finished) || (error_code != 0))
            break;

        tok_next(tok);
    }

    if (!error_code)
    {
        if (unmatched_wildcard && !matched_wildcard)
        {
            job_set_flag(j, JOB_WILDCARD_ERROR, 1);
            proc_set_last_status(STATUS_UNMATCHED_WILDCARD);
            if (get_is_interactive() && !is_block)
            {
                int tmp;

                debug(1, WILDCARD_ERR_MSG, unmatched.c_str());
                tmp = current_tokenizer_pos;
                current_tokenizer_pos = unmatched_pos;

                fwprintf(stderr, L"%ls", parser_t::current_line());

                current_tokenizer_pos=tmp;
            }

        }
    }

    /* Store our IO chain. The existing chain should be empty. */
    assert(p->io_chain().empty());
    p->set_io_chain(process_io_chain);
}

/*
  static void print_block_stack( block_t *b )
  {
  if( !b )
  return;
  print_block_stack( b->outer );

  debug( 0, L"Block type %ls, skip: %d", parser_get_block_desc( b->type ), b->skip );
  }
*/

/**
   Fully parse a single job. Does not call exec on it, but any command substitutions in the job will be executed.

   \param p The process structure that should be used to represent the first process in the job.
   \param j The job structure to contain the parsed job
   \param tok tokenizer to read from
f
   \return 1 on success, 0 on error
*/
int parser_t::parse_job(process_t *p,
                        job_t *j,
                        tokenizer_t *tok)
{
    std::vector<completion_t> args; // The list that will become the argv array for the program
    int use_function = 1;   // May functions be considered when checking what action this command represents
    int use_builtin = 1;    // May builtins be considered when checking what action this command represents
    int use_command = 1;    // May commands be considered when checking what action this command represents
    int is_new_block=0;     // Does this command create a new block?
    bool unskip = false;    // Maybe we are an elseif inside an if block; if so we may want to evaluate this even if the if block is currently set to skip
    bool allow_bogus_command = false; // If we are an elseif that will not be executed, or an AND or OR that will have been short circuited, don't complain about non-existent commands

    block_t *prev_block = current_block;
    scoped_push<int> tokenizer_pos_push(&current_tokenizer_pos, tok_get_pos(tok));

    while (args.empty())
    {
        wcstring nxt;
        bool has_nxt = false;
        bool consumed = false; // Set to one if the command requires a second command, like e.g. while does
        int mark;         // Use to save the position of the beginning of the token

        switch (tok_last_type(tok))
        {
            case TOK_STRING:
            {
                nxt = tok_last(tok);
                has_nxt = expand_one(nxt, EXPAND_SKIP_CMDSUBST | EXPAND_SKIP_VARIABLES);

                if (! has_nxt)
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(tok),
                          ILLEGAL_CMD_ERR_MSG,
                          tok_last(tok));

                    return 0;
                }
                break;
            }

            case TOK_ERROR:
            {
                error(SYNTAX_ERROR,
                      tok_get_pos(tok),
                      TOK_ERR_MSG,
                      tok_last(tok));

                return 0;
            }

            case TOK_PIPE:
            {
                const wchar_t *str = tok_string(tok);
                if (tok_get_pos(tok)>0 && str[tok_get_pos(tok)-1] == L'|')
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(tok),
                          CMD_OR_ERR_MSG,
                          tok_get_desc(tok_last_type(tok)));
                }
                else
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(tok),
                          CMD_ERR_MSG,
                          tok_get_desc(tok_last_type(tok)));
                }

                return 0;
            }

            default:
            {
                error(SYNTAX_ERROR,
                      tok_get_pos(tok),
                      CMD_ERR_MSG,
                      tok_get_desc(tok_last_type(tok)));

                return 0;
            }
        }

        mark = tok_get_pos(tok);

        if (contains(nxt,
                     L"command",
                     L"builtin",
                     L"not",
                     L"and",
                     L"or",
                     L"exec"))
        {
            int sw;
            int is_exec = nxt == L"exec";

            if (is_exec && (p != j->first_process))
            {
                error(SYNTAX_ERROR,
                      tok_get_pos(tok),
                      EXEC_ERR_MSG);
                return 0;
            }

            tok_next(tok);
            sw = parser_keywords_is_switch(tok_last(tok));

            if (sw == ARG_SWITCH)
            {
                tok_set_pos(tok, mark);
            }
            else
            {
                if (sw == ARG_SKIP)
                {
                    tok_next(tok);
                }

                consumed = true;

                if (nxt == L"command" || nxt == L"builtin")
                {
                    use_function = 0;
                    if (nxt == L"command")
                    {
                        use_builtin = 0;
                        use_command = 1;
                    }
                    else
                    {
                        use_builtin = 1;
                        use_command = 0;
                    }
                }
                else if (nxt == L"not")
                {
                    job_set_flag(j, JOB_NEGATE, !job_get_flag(j, JOB_NEGATE));
                }
                else if (nxt == L"and")
                {
                    bool skip = (proc_get_last_status() != 0);
                    job_set_flag(j, JOB_SKIP, skip);
                    allow_bogus_command = skip;
                }
                else if (nxt == L"or")
                {
                    bool skip = (proc_get_last_status() == 0);
                    job_set_flag(j, JOB_SKIP, skip);
                    allow_bogus_command = skip;
                }
                else if (is_exec)
                {
                    use_function = 0;
                    use_builtin=0;
                    p->type=INTERNAL_EXEC;
                    tokenizer_pos_push.restore();
                }
            }
        }
        else if (nxt == L"while")
        {
            bool new_block = false;
            tok_next(tok);
            while_block_t *wb = NULL;

            if ((current_block->type() != WHILE))
            {
                new_block = true;
            }
            else if ((wb = static_cast<while_block_t*>(current_block))->status == WHILE_TEST_AGAIN)
            {
                wb->status = WHILE_TEST_FIRST;
            }
            else
            {
                new_block = true;
            }

            if (new_block)
            {
                while_block_t *wb = new while_block_t();
                wb->status = WHILE_TEST_FIRST;
                wb->tok_pos = mark;
                this->push_block(wb);
            }

            consumed = true;
            is_new_block=1;

        }
        else if (nxt == L"if")
        {
            tok_next(tok);

            if_block_t *ib = new if_block_t();
            this->push_block(ib);
            ib->tok_pos = mark;

            is_new_block=1;
            consumed = true;
        }
        else if (nxt == L"else")
        {
            /* Record where the else is for error reporting */
            const int else_pos = tok_get_pos(tok);
            /* See if we have any more arguments, that is, whether we're ELSE IF ... or just ELSE. */
            tok_next(tok);
            if (tok_last_type(tok) == TOK_STRING && current_block->type() == IF)
            {
                const if_block_t *ib = static_cast<const if_block_t *>(current_block);

                /* If we've already encountered an else, complain */
                if (ib->else_evaluated)
                {
                    error(SYNTAX_ERROR,
                          else_pos,
                          INVALID_ELSEIF_PAST_ELSE_ERR_MSG,
                          L"else if");

                }
                else
                {

                    job_set_flag(j, JOB_ELSEIF, 1);
                    consumed = true;

                    /* We're at the IF. Go past it. */
                    tok_next(tok);

                    /* We want to execute this ELSEIF if the IF expression was evaluated, it failed, and so has every other ELSEIF (if any) */
                    unskip = (ib->if_expr_evaluated && ! ib->any_branch_taken);

                    /* But if we're not executing it, don't complain about its command if it doesn't exist */
                    if (! unskip)
                        allow_bogus_command = true;
                }
            }
        }

        /*
          Test if we need another command
        */
        if (consumed)
        {
            /*
              Yes we do, around in the loop for another lap, then!
            */
            continue;
        }

        if (use_function && (unskip || ! current_block->skip))
        {
            bool nxt_forbidden=false;
            wcstring forbid;

            int is_function_call=0;

            /*
              This is a bit fragile. It is a test to see if we are
              inside of function call, but not inside a block in that
              function call. If, in the future, the rules for what
              block scopes are pushed on function invocation changes,
              then this check will break.
            */
            if ((current_block->type() == TOP) &&
                    (current_block->outer) &&
                    (current_block->outer->type() == FUNCTION_CALL))
                is_function_call = 1;

            /*
              If we are directly in a function, and this is the first
              command of the block, then the function we are executing
              may not be called, since that would mean an infinite
              recursion.
            */
            if (is_function_call && !current_block->had_command)
            {
                forbid = forbidden_function.empty() ? wcstring(L"") : forbidden_function.back();
                if (forbid == nxt)
                {
                    /* Infinite recursive loop */
                    nxt_forbidden = true;
                    error(SYNTAX_ERROR, tok_get_pos(tok), INFINITE_RECURSION_ERR_MSG);
                }
            }

            if (!nxt_forbidden && has_nxt && function_exists(nxt))
            {
                /*
                  Check if we have reached the maximum recursion depth
                */
                if (forbidden_function.size() > MAX_RECURSION_DEPTH)
                {
                    error(SYNTAX_ERROR, tok_get_pos(tok), OVERFLOW_RECURSION_ERR_MSG);
                }
                else
                {
                    p->type = INTERNAL_FUNCTION;
                }
            }
        }
        args.push_back(completion_t(nxt));
    }

    if (error_code == 0)
    {
        if (!p->type)
        {
            if (use_builtin &&
                    builtin_exists(args.at(0).completion))
            {
                p->type = INTERNAL_BUILTIN;
                is_new_block |= parser_keywords_is_block(args.at(0).completion);
            }
        }

        if ((!p->type || (p->type == INTERNAL_EXEC)))
        {
            /*
              If we are not executing the current block, allow
              non-existent commands.
            */
            if (current_block->skip && ! unskip)
                allow_bogus_command = true; //note this may already be true for other reasons

            if (allow_bogus_command)
            {
                p->actual_cmd.clear();
            }
            else
            {
                int err;
                bool has_command = path_get_path(args.at(0).completion, &p->actual_cmd);
                err = errno;

                bool use_implicit_cd = false;
                if (! has_command)
                {
                    /* If the specified command does not exist, try using an implicit cd. */
                    wcstring implicit_cd_path;
                    use_implicit_cd = path_can_be_implicit_cd(args.at(0).completion, &implicit_cd_path);
                    if (use_implicit_cd)
                    {
                        args.clear();
                        args.push_back(completion_t(L"cd"));
                        args.push_back(completion_t(implicit_cd_path));

                        /* If we have defined a wrapper around cd, use it, otherwise use the cd builtin */
                        if (use_function && function_exists(L"cd"))
                            p->type = INTERNAL_FUNCTION;
                        else
                            p->type = INTERNAL_BUILTIN;
                    }
                }

                // Disabled pending discussion in https://github.com/fish-shell/fish-shell/issues/367
#if 0
                if (! has_command && ! use_implicit_cd)
                {
                    if (fish_openSUSE_dbus_hack_hack_hack_hack(&args))
                    {
                        has_command = true;
                        p->type = INTERNAL_BUILTIN;
                    }
                }
#endif

                /* Check if the specified command exists */
                if (! has_command && ! use_implicit_cd)
                {

                    const wchar_t *cmd = args.at(0).completion.c_str();
                    
                    /*
                     We couldn't find the specified command.

                     What we want to happen now is that the
                     specified job won't get executed, and an
                     error message is printed on-screen, but
                     otherwise, the parsing/execution of the
                     file continues. Because of this, we don't
                     want to call error(), since that would stop
                     execution of the file. Instead we let
                     p->actual_command be 0 (null), which will
                     cause the job to silently not execute. We
                     also print an error message and set the
                     status to 127 (This is the standard number
                     for this, used by other shells like bash
                     and zsh).
                     */

                    const wchar_t * const equals_ptr = wcschr(cmd, L'=');
                    if (equals_ptr != NULL)
                    {
                        /* Try to figure out if this is a pure variable assignment (foo=bar), or if this appears to be running a command (foo=bar ruby...) */
                        
                        const wcstring name_str = wcstring(cmd, equals_ptr - cmd); //variable name, up to the =
                        const wcstring val_str = wcstring(equals_ptr + 1); //variable value, past the =
                        
                        wcstring next_str;
                        if (tok_peek_next(tok, &next_str) == TOK_STRING && ! next_str.empty())
                        {
                            wcstring ellipsis_str = wcstring(1, ellipsis_char);
                            if (ellipsis_str == L"$")
                                ellipsis_str = L"...";
                            
                            /* Looks like a command */
                            debug(0,
                                  _( L"Unknown command '%ls'. Did you mean to run %ls with a modified environment? Try 'env %ls=%ls %ls%ls'. See the help section on the set command by typing 'help set'."),
                                  cmd,
                                  next_str.c_str(),
                                  name_str.c_str(),
                                  val_str.c_str(),
                                  next_str.c_str(),
                                  ellipsis_str.c_str());
                        }
                        else
                        {
                            debug(0,
                                  COMMAND_ASSIGN_ERR_MSG,
                                  cmd,
                                  name_str.c_str(),
                                  val_str.c_str());
                        }
                    }
                    else if (cmd[0]==L'$' || cmd[0] == VARIABLE_EXPAND || cmd[0] == VARIABLE_EXPAND_SINGLE)
                    {

                        const env_var_t val_wstr = env_get_string(cmd+1);
                        const wchar_t *val = val_wstr.missing() ? NULL : val_wstr.c_str();
                        if (val)
                        {
                            debug(0,
                                  _(L"Variables may not be used as commands. Instead, define a function like 'function %ls; %ls $argv; end' or use the eval builtin instead, like 'eval %ls'. See the help section for the function command by typing 'help function'."),
                                  cmd+1,
                                  val,
                                  cmd,
                                  cmd);
                        }
                        else
                        {
                            debug(0,
                                  _(L"Variables may not be used as commands. Instead, define a function or use the eval builtin instead, like 'eval %ls'. See the help section for the function command by typing 'help function'."),
                                  cmd,
                                  cmd);
                        }
                    }
                    else if (wcschr(cmd, L'$'))
                    {
                        debug(0,
                              _(L"Commands may not contain variables. Use the eval builtin instead, like 'eval %ls'. See the help section for the eval command by typing 'help eval'."),
                              cmd,
                              cmd);
                    }
                    else if (err!=ENOENT)
                    {
                        debug(0,
                              _(L"The file '%ls' is not executable by this user"),
                              cmd?cmd:L"UNKNOWN");
                    }
                    else
                    {
                        /*
                         Handle unrecognized commands with standard
                         command not found handler that can make better
                         error messages
                         */

                        wcstring_list_t event_args;
                        event_args.push_back(args.at(0).completion);
                        event_fire_generic(L"fish_command_not_found", &event_args);
                    }

                    int tmp = current_tokenizer_pos;
                    current_tokenizer_pos = tok_get_pos(tok);

                    fwprintf(stderr, L"%ls", parser_t::current_line());

                    current_tokenizer_pos=tmp;

                    job_set_flag(j, JOB_SKIP, 1);

                    proc_set_last_status(err==ENOENT?STATUS_UNKNOWN_COMMAND:STATUS_NOT_EXECUTABLE);
                }
            }
        }

        if ((p->type == EXTERNAL) && !use_command)
        {
            error(SYNTAX_ERROR,
                  tok_get_pos(tok),
                  UNKNOWN_BUILTIN_ERR_MSG,
                  args.back().completion.c_str());
        }
    }


    if (is_new_block)
    {

        const wchar_t *end=parser_find_end(tok_string(tok) +
                                           current_tokenizer_pos);
        int make_sub_block = j->first_process != p;

        if (!end)
        {
            error(SYNTAX_ERROR,
                  tok_get_pos(tok),
                  BLOCK_END_ERR_MSG);

        }
        else
        {

            if (!make_sub_block)
            {
                int done=0;

                tokenizer_t subtok(end, 0);
                for (; ! done && tok_has_next(&subtok); tok_next(&subtok))
                {

                    switch (tok_last_type(&subtok))
                    {
                        case TOK_END:
                            done = 1;
                            break;

                        case TOK_REDIRECT_OUT:
                        case TOK_REDIRECT_NOCLOB:
                        case TOK_REDIRECT_APPEND:
                        case TOK_REDIRECT_IN:
                        case TOK_REDIRECT_FD:
                        case TOK_PIPE:
                        {
                            done = 1;
                            make_sub_block = 1;
                            break;
                        }

                        case TOK_STRING:
                        {
                            break;
                        }

                        default:
                        {
                            done = 1;
                            error(SYNTAX_ERROR,
                                  current_tokenizer_pos,
                                  BLOCK_END_ERR_MSG);
                        }
                    }
                }
            }

            if (make_sub_block)
            {

                long end_pos = end-tok_string(tok);
                const wcstring sub_block(tok_string(tok) + current_tokenizer_pos, end_pos - current_tokenizer_pos);

                p->type = INTERNAL_BLOCK;
                args.at(0) =  completion_t(sub_block);

                tok_set_pos(tok, (int)end_pos);

                while (prev_block != current_block)
                {
                    parser_t::pop_block();
                }

            }
            else tok_next(tok);
        }

    }
    else tok_next(tok);

    if (!error_code)
    {
        if (p->type == INTERNAL_BUILTIN && parser_keywords_skip_arguments(args.at(0).completion))
        {
            if (!p->get_argv())
                p->set_argv(completions_to_wcstring_list(args));
        }
        else
        {
            parse_job_argument_list(p, j, tok, args, unskip);
        }
    }

    if (!error_code)
    {
        if (!is_new_block)
        {
            current_block->had_command = true;
        }
    }

    if (error_code)
    {
        /*
          Make sure the block stack is consistent
        */
        while (prev_block != current_block)
        {
            parser_t::pop_block();
        }
    }
    return !error_code;
}

/**
   Do skipped execution of command. This means that only limited
   execution of block level commands such as end and switch should be
   preformed.

   \param j the job to execute

*/
void parser_t::skipped_exec(job_t * j)
{
    process_t *p;

    /* Handle other skipped guys */
    for (p = j->first_process; p; p=p->next)
    {
        if (p->type == INTERNAL_BUILTIN)
        {
            if ((wcscmp(p->argv0(), L"for")==0) ||
                    (wcscmp(p->argv0(), L"switch")==0) ||
                    (wcscmp(p->argv0(), L"begin")==0) ||
                    (wcscmp(p->argv0(), L"function")==0))
            {
                this->push_block(new fake_block_t());
            }
            else if (wcscmp(p->argv0(), L"end")==0)
            {
                if (!current_block->outer->skip)
                {
                    exec_job(*this, j);
                    return;
                }
                parser_t::pop_block();
            }
            else if (wcscmp(p->argv0(), L"else")==0)
            {
                if (current_block->type() == IF)
                {
                    /* Evaluate this ELSE if the IF expression failed, and so has every ELSEIF (if any) expression thus far */
                    const if_block_t *ib = static_cast<const if_block_t*>(current_block);
                    if (ib->if_expr_evaluated && ! ib->any_branch_taken)
                    {
                        exec_job(*this, j);
                        return;
                    }
                }
            }
            else if (wcscmp(p->argv0(), L"case")==0)
            {
                if (current_block->type() == SWITCH)
                {
                    exec_job(*this, j);
                    return;
                }
            }
        }
    }
    job_free(j);
}

/* Return whether we should skip the current block, if it is an elseif. */
static bool job_should_skip_elseif(const job_t *job, const block_t *current_block)
{
    if (current_block->type() != IF)
    {
        /* Not an IF block, so just honor the skip property */
        return current_block->skip;
    }
    else
    {
        /* We are an IF block */
        const if_block_t *ib = static_cast<const if_block_t *>(current_block);

        /* Execute this ELSEIF if the IF expression has been evaluated, it evaluated to false, and all ELSEIFs so far have evaluated to false. */
        bool execute_elseif = (ib->if_expr_evaluated && ! ib->any_branch_taken);

        /* Invert the sense */
        return ! execute_elseif;
    }
}

/**
   Evaluates a job from the specified tokenizer. First calls
   parse_job to parse the job and then calls exec to execute it.

   \param tok The tokenizer to read tokens from
*/

void parser_t::eval_job(tokenizer_t *tok)
{
    ASSERT_IS_MAIN_THREAD();

    int start_pos = job_start_pos = tok_get_pos(tok);
    long long t1=0, t2=0, t3=0;


    profile_item_t *profile_item = NULL;
    bool skip = false;
    int job_begin_pos;
    const bool do_profile = profile;

    if (do_profile)
    {
        profile_item = new profile_item_t();
        profile_item->skipped = 1;
        profile_items.push_back(profile_item);
        t1 = get_time();
    }

    switch (tok_last_type(tok))
    {
        case TOK_STRING:
        {
            job_t *j = this->job_create();
            job_set_flag(j, JOB_FOREGROUND, 1);
            job_set_flag(j, JOB_TERMINAL, job_get_flag(j, JOB_CONTROL));
            job_set_flag(j, JOB_TERMINAL, job_get_flag(j, JOB_CONTROL) \
                         && (!is_subshell && !is_event));
            job_set_flag(j, JOB_SKIP_NOTIFICATION, is_subshell \
                         || is_block \
                         || is_event \
                         || (!get_is_interactive()));

            current_block->job = j;

            if (get_is_interactive())
            {
                if (tcgetattr(0, &j->tmodes))
                {
                    tok_next(tok);
                    wperror(L"tcgetattr");
                    job_free(j);
                    break;
                }
            }

            j->first_process = new process_t();
            job_begin_pos = tok_get_pos(tok);

            if (parse_job(j->first_process, j, tok) &&
                    j->first_process->get_argv())
            {
                if (job_start_pos < tok_get_pos(tok))
                {
                    long stop_pos = tok_get_pos(tok);
                    const wchar_t *newline = wcschr(tok_string(tok)+start_pos, L'\n');
                    if (newline)
                        stop_pos = mini<long>(stop_pos, newline - tok_string(tok));

                    j->set_command(wcstring(tok_string(tok)+start_pos, stop_pos-start_pos));
                }
                else
                    j->set_command(L"");

                if (do_profile)
                {
                    t2 = get_time();
                    profile_item->cmd = j->command();
                    profile_item->skipped=current_block->skip;
                }

                /* If we're an ELSEIF, then we may want to unskip, if we're skipping because of an IF */
                if (job_get_flag(j, JOB_ELSEIF))
                {
                    bool skip_elseif = job_should_skip_elseif(j, current_block);

                    /* Record that we're entering an elseif */
                    if (! skip_elseif)
                    {
                        /* We must be an IF block here */
                        assert(current_block->type() == IF);
                        static_cast<if_block_t *>(current_block)->is_elseif_entry = true;
                    }

                    /* Record that in the block too. This is similar to what builtin_else does. */
                    current_block->skip = skip_elseif;
                }

                skip = skip || current_block->skip;
                skip = skip || job_get_flag(j, JOB_WILDCARD_ERROR);
                skip = skip || job_get_flag(j, JOB_SKIP);

                if (!skip)
                {
                    int was_builtin = 0;
                    if (j->first_process->type==INTERNAL_BUILTIN && !j->first_process->next)
                        was_builtin = 1;
                    scoped_push<int> tokenizer_pos_push(&current_tokenizer_pos, job_begin_pos);
                    exec_job(*this, j);

                    /* Only external commands require a new fishd barrier */
                    if (!was_builtin)
                        set_proc_had_barrier(false);
                }
                else
                {
                    this->skipped_exec(j);
                }

                if (do_profile)
                {
                    t3 = get_time();
                    profile_item->level=eval_level;
                    profile_item->parse = (int)(t2-t1);
                    profile_item->exec=(int)(t3-t2);
                }

                if (current_block->type() == WHILE)
                {
                    while_block_t *wb = static_cast<while_block_t *>(current_block);
                    switch (wb->status)
                    {
                        case WHILE_TEST_FIRST:
                        {
                            // PCA I added the 'wb->skip ||' part because we couldn't reliably
                            // control-C out of loops like this: while test 1 -eq 1; end
                            wb->skip = wb->skip || proc_get_last_status()!= 0;
                            wb->status = WHILE_TESTED;
                        }
                        break;
                    }
                }

                if (current_block->type() == IF)
                {
                    if_block_t *ib = static_cast<if_block_t *>(current_block);

                    if (ib->skip)
                    {
                        /* Nothing */
                    }
                    else if (! ib->if_expr_evaluated)
                    {
                        /* Execute the IF */
                        bool if_result = (proc_get_last_status() == 0);
                        ib->any_branch_taken = if_result;

                        /* Don't execute if the expression failed */
                        current_block->skip = ! if_result;
                        ib->if_expr_evaluated = true;
                    }
                    else if (ib->is_elseif_entry && ! ib->any_branch_taken)
                    {
                        /* Maybe mark an ELSEIF branch as taken */
                        bool elseif_taken = (proc_get_last_status() == 0);
                        ib->any_branch_taken = elseif_taken;
                        current_block->skip = ! elseif_taken;
                        ib->is_elseif_entry = false;
                    }
                }

            }
            else
            {
                /*
                  This job could not be properly parsed. We free it
                  instead, and set the status to 1. This should be
                  rare, since most errors should be detected by the
                  ahead of time validator.
                */
                job_free(j);

                proc_set_last_status(1);
            }
            current_block->job = 0;
            break;
        }

        case TOK_END:
        {
            if (tok_has_next(tok))
                tok_next(tok);
            break;
        }

        case TOK_BACKGROUND:
        {
            const wchar_t *str = tok_string(tok);
            if (tok_get_pos(tok)>0 && str[tok_get_pos(tok)-1] == L'&')
            {
                error(SYNTAX_ERROR,
                      tok_get_pos(tok),
                      CMD_AND_ERR_MSG,
                      tok_get_desc(tok_last_type(tok)));
            }
            else
            {
                error(SYNTAX_ERROR,
                      tok_get_pos(tok),
                      CMD_ERR_MSG,
                      tok_get_desc(tok_last_type(tok)));
            }

            return;
        }

        case TOK_ERROR:
        {
            error(SYNTAX_ERROR,
                  tok_get_pos(tok),
                  TOK_ERR_MSG,
                  tok_last(tok));

            return;
        }

        default:
        {
            error(SYNTAX_ERROR,
                  tok_get_pos(tok),
                  CMD_ERR_MSG,
                  tok_get_desc(tok_last_type(tok)));

            return;
        }
    }

    job_reap(0);

}

int parser_t::eval(const wcstring &cmdStr, const io_chain_t &io, enum block_type_t block_type)
{
    const wchar_t * const cmd = cmdStr.c_str();
    size_t forbid_count;
    int code;
    block_t *start_current_block = current_block;

    /* Record the current chain so we can put it back later */
    scoped_push<io_chain_t> block_io_push(&block_io, io);

    scoped_push<wcstring_list_t> forbidden_function_push(&forbidden_function);

    if (block_type == SUBST)
    {
        forbidden_function.clear();
    }

    CHECK_BLOCK(1);

    forbid_count = forbidden_function.size();

    job_reap(0);

    debug(4, L"eval: %ls", cmd);

    if (!cmd)
    {
        debug(1,
              EVAL_NULL_ERR_MSG);
        bugreport();
        return 1;
    }

    if ((block_type != TOP) &&
            (block_type != SUBST))
    {
        debug(1,
              INVALID_SCOPE_ERR_MSG,
              parser_t::get_block_desc(block_type));
        bugreport();
        return 1;
    }

    eval_level++;

    this->push_block(new scope_block_t(block_type));

    tokenizer_t local_tokenizer(cmd, 0);
    scoped_push<tokenizer_t *> tokenizer_push(&current_tokenizer, &local_tokenizer);

    error_code = 0;

    event_fire(NULL);

    while (tok_has_next(current_tokenizer) &&
            !error_code &&
            !sanity_check() &&
            !exit_status())
    {
        this->eval_job(current_tokenizer);
        event_fire(NULL);
    }

    parser_t::pop_block();

    while (start_current_block != current_block)
    {
        if (current_block == 0)
        {
            debug(0,
                  _(L"End of block mismatch. Program terminating."));
            bugreport();
            FATAL_EXIT();
            break;
        }

        if ((!error_code) && (!exit_status()) && (!proc_get_last_status()))
        {

            //debug( 2, L"Status %d\n", proc_get_last_status() );

            debug(1,
                  L"%ls", parser_t::get_block_desc(current_block->type()));
            debug(1,
                  BLOCK_END_ERR_MSG);
            fwprintf(stderr, L"%ls", parser_t::current_line());

            const wcstring h = builtin_help_get(*this, L"end");
            if (h.size())
                fwprintf(stderr, L"%ls", h.c_str());
            break;

        }
        parser_t::pop_block();
    }

    this->print_errors_stderr();

    tokenizer_push.restore();

    while (forbidden_function.size() > forbid_count)
        parser_t::allow_function();

    /*
      Restore previous eval state
    */
    eval_level--;

    code=error_code;
    error_code=0;

    job_reap(0);

    return code;
}


/**
   \return the block type created by the specified builtin, or -1 on error.
*/
block_type_t parser_get_block_type(const wcstring &cmd)
{
    for (size_t i=0; block_lookup[i].desc; i++)
    {
        if (block_lookup[i].name && cmd == block_lookup[i].name)
        {
            return block_lookup[i].type;
        }
    }
    return (block_type_t)-1;
}

/**
   \return the block command that createa the specified block type, or null on error.
*/
const wchar_t *parser_get_block_command(int type)
{
    for (size_t i=0; block_lookup[i].desc; i++)
    {
        if (block_lookup[i].type == type)
        {
            return block_lookup[i].name;
        }
    }
    return NULL;
}

/**
   Test if this argument contains any errors. Detected errors include
   syntax errors in command substitutions, improperly escaped
   characters and improper use of the variable expansion operator.
*/
int parser_t::parser_test_argument(const wchar_t *arg, wcstring *out, const wchar_t *prefix, int offset)
{
    wchar_t *unesc;
    wchar_t *pos;
    int err=0;

    wchar_t *paran_begin, *paran_end;
    wchar_t *arg_cpy;
    int do_loop = 1;

    CHECK(arg, 1);

    arg_cpy = wcsdup(arg);

    while (do_loop)
    {
        switch (parse_util_locate_cmdsubst(arg_cpy,
                                           &paran_begin,
                                           &paran_end,
                                           false))
        {
            case -1:
                err=1;
                if (out)
                {
                    error(SYNTAX_ERROR,
                          offset,
                          L"Mismatched parenthesis");
                    this->print_errors(*out, prefix);
                }
                free(arg_cpy);
                return err;

            case 0:
                do_loop = 0;
                break;

            case 1:
            {

                wchar_t *subst = wcsndup(paran_begin+1, paran_end-paran_begin-1);
                wcstring tmp;

                tmp.append(arg_cpy, paran_begin - arg_cpy);
                tmp.push_back(INTERNAL_SEPARATOR);
                tmp.append(paran_end+1);

//        debug( 1, L"%ls -> %ls %ls", arg_cpy, subst, tmp.buff );

                err |= parser_t::test(subst, 0, out, prefix);

                free(subst);
                free(arg_cpy);
                arg_cpy = wcsdup(tmp.c_str());

                /*
                  Do _not_ call sb_destroy on this stringbuffer - it's
                  buffer is used as the new 'arg_cpy'. It is free'd at
                  the end of the loop.
                */
                break;
            }
        }
    }

    unesc = unescape(arg_cpy, 1);
    if (!unesc)
    {
        if (out)
        {
            error(SYNTAX_ERROR,
                  offset,
                  L"Invalid token '%ls'", arg_cpy);
            print_errors(*out, prefix);
        }
        return 1;
    }
    else
    {
        /*
          Check for invalid variable expansions
        */
        for (pos = unesc; *pos; pos++)
        {
            switch (*pos)
            {
                case VARIABLE_EXPAND:
                case VARIABLE_EXPAND_SINGLE:
                {
                    wchar_t n = *(pos+1);

                    if (n != VARIABLE_EXPAND &&
                            n != VARIABLE_EXPAND_SINGLE &&
                            !wcsvarchr(n))
                    {
                        err=1;
                        if (out)
                        {
                            expand_variable_error(*this, unesc, pos-unesc, offset);
                            print_errors(*out, prefix);
                        }
                    }

                    break;
                }
            }
        }
    }

    free(arg_cpy);

    free(unesc);
    return err;

}

int parser_t::test_args(const  wchar_t * buff, wcstring *out, const wchar_t *prefix)
{
    int do_loop = 1;
    int err = 0;

    CHECK(buff, 1);

    tokenizer_t tok(buff, 0);
    scoped_push<tokenizer_t*> tokenizer_push(&current_tokenizer, &tok);
    scoped_push<int> tokenizer_pos_push(&current_tokenizer_pos);

    for (; do_loop && tok_has_next(&tok); tok_next(&tok))
    {
        current_tokenizer_pos = tok_get_pos(&tok);
        switch (tok_last_type(&tok))
        {

            case TOK_STRING:
            {
                err |= parser_test_argument(tok_last(&tok), out, prefix, tok_get_pos(&tok));
                break;
            }

            case TOK_END:
            {
                break;
            }

            case TOK_ERROR:
            {
                if (out)
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(&tok),
                          TOK_ERR_MSG,
                          tok_last(&tok));
                    print_errors(*out, prefix);
                }
                err=1;
                do_loop=0;
                break;
            }

            default:
            {
                if (out)
                {
                    error(SYNTAX_ERROR,
                          tok_get_pos(&tok),
                          UNEXPECTED_TOKEN_ERR_MSG,
                          tok_get_desc(tok_last_type(&tok)));
                    print_errors(*out, prefix);
                }
                err=1;
                do_loop=0;
                break;
            }
        }
    }

    error_code=0;

    return err;
}

// helper type used in parser::test below
struct block_info_t
{
    int position; //tokenizer position
    block_type_t type; //type of the block
    int indentation; //indentation associated with the block

    bool has_had_case; //if we are a switch, whether we've encountered a case
};

int parser_t::test(const wchar_t *buff, int *block_level, wcstring *out, const wchar_t *prefix)
{
    ASSERT_IS_MAIN_THREAD();

    /*
       Set to one if a command name has been given for the currently
       parsed process specification
    */
    int had_cmd=0;
    int err=0;
    int unfinished = 0;

    // These are very nearly stacks, but sometimes we have to inspect non-top elements (e.g. return)
    std::vector<struct block_info_t> block_infos;
    int indentation_sum = 0; //sum of indentation in block_infos
    int res = 0;

    /*
      Set to 1 if the current command is inside a pipeline
    */
    int is_pipeline = 0;

    /*
      Set to one if the currently specified process can not be used inside a pipeline
    */
    int forbid_pipeline = 0;

    /*
       Set to one if an additional process specification is needed
    */
    bool needs_cmd = false;

    /*
      Counter on the number of arguments this function has encountered
      so far. Is set to -1 when the count is unknown, i.e. after
      encountering an argument that contains substitutions that can
      expand to more/less arguemtns then 1.
    */
    int arg_count=0;

    /*
      The currently validated command.
    */
    wcstring command;
    bool has_command = false;

    CHECK(buff, 1);

    if (block_level)
    {
        size_t len = wcslen(buff);
        for (size_t i=0; i<len; i++)
        {
            block_level[i] = -1;
        }

    }

    tokenizer_t tok(buff, 0);

    scoped_push<tokenizer_t*> tokenizer_push(&current_tokenizer, &tok);
    scoped_push<int> tokenizer_pos_push(&current_tokenizer_pos);

    for (;; tok_next(&tok))
    {
        current_tokenizer_pos = tok_get_pos(&tok);

        int last_type = tok_last_type(&tok);
        int end_of_cmd = 0;

        switch (last_type)
        {
            case TOK_STRING:
            {
                if (!had_cmd)
                {
                    int mark = tok_get_pos(&tok);
                    had_cmd = 1;
                    arg_count=0;

                    command = tok_last(&tok);

                    // Pass SKIP_HOME_DIRECTORIES for https://github.com/fish-shell/fish-shell/issues/512
                    has_command = expand_one(command, EXPAND_SKIP_CMDSUBST | EXPAND_SKIP_VARIABLES | EXPAND_SKIP_HOME_DIRECTORIES);
                    if (! has_command)
                    {
                        command = L"";
                        err=1;
                        if (out)
                        {
                            error(SYNTAX_ERROR,
                                  tok_get_pos(&tok),
                                  ILLEGAL_CMD_ERR_MSG,
                                  tok_last(&tok));

                            print_errors(*out, prefix);
                        }
                        break;
                    }

                    if (needs_cmd)
                    {
                        /*
                          end is not a valid command when a followup
                          command is needed, such as after 'and' or
                          'while'
                        */
                        if (contains(command,
                                     L"end"))
                        {
                            err=1;
                            if (out)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(&tok),
                                      COND_ERR_MSG);

                                print_errors(*out, prefix);
                            }
                        }

                        needs_cmd = false;
                    }

                    /*
                      Decrement block count on end command
                    */
                    if (command == L"end")
                    {
                        tok_next(&tok);
                        tok_set_pos(&tok, mark);

                        /* Test that end is not used when not inside any block */
                        if (block_infos.empty())
                        {
                            err = 1;
                            if (out)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(&tok),
                                      INVALID_END_ERR_MSG);
                                print_errors(*out, prefix);
                                const wcstring h = builtin_help_get(*this, L"end");
                                if (! h.empty())
                                    append_format(*out, L"%ls", h.c_str());
                            }
                        }
                        else
                        {
                            indentation_sum -= block_infos.back().indentation;
                            block_infos.pop_back();

                        }
                    }

                    /*
                      Store the block level. This needs to be done
                      _after_ checking for end commands, but _before_
                      checking for block opening commands.
                    */
                    if (block_level != NULL)
                    {
                        int indentation_adjust = 0;
                        if (command == L"else")
                        {
                            // if or else if goes back
                            indentation_adjust = -1;
                        }
                        else if (command == L"case")
                        {
                            if (! block_infos.empty() && block_infos.back().type == SWITCH)
                            {
                                // mark that we've encountered a case, and increase the indentation
                                // by doing this now, we avoid overly indenting the first case as the user types it
                                if (! block_infos.back().has_had_case)
                                {
                                    block_infos.back().has_had_case = true;
                                    block_infos.back().indentation += 1;
                                    indentation_sum += 1;
                                }
                                // unindent this case
                                indentation_adjust = -1;
                            }
                        }

                        block_level[tok_get_pos(&tok)] = indentation_sum + indentation_adjust;
                    }

                    /*
                      Handle block commands
                    */
                    if (parser_keywords_is_block(command))
                    {
                        struct block_info_t info = {current_tokenizer_pos, parser_get_block_type(command), 1 /* indent */};
                        block_infos.push_back(info);
                        indentation_sum += info.indentation;
                        tok_next(&tok);
                        tok_set_pos(&tok, mark);
                    }

                    /*
                      If parser_keywords_is_subcommand is true, the command
                      accepts a second command as it's first
                      argument. If parser_skip_arguments is true, the
                      second argument is optional.
                    */
                    if (parser_keywords_is_subcommand(command) && !parser_keywords_skip_arguments(command))
                    {
                        needs_cmd = true;
                        had_cmd = 0;
                    }

                    if (contains(command,
                                 L"or",
                                 L"and"))
                    {
                        /*
                          'or' and 'and' can not be used inside pipelines
                        */
                        if (is_pipeline)
                        {
                            err=1;
                            if (out)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(&tok),
                                      EXEC_ERR_MSG);

                                print_errors(*out, prefix);

                            }
                        }
                    }

                    /*
                      There are a lot of situations where pipelines
                      are forbidden, including when using the exec
                      builtin.
                    */
                    if (parser_is_pipe_forbidden(command))
                    {
                        if (is_pipeline)
                        {
                            err=1;
                            if (out)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(&tok),
                                      EXEC_ERR_MSG);

                                print_errors(*out, prefix);

                            }
                        }
                        forbid_pipeline = 1;
                    }

                    /*
                      Test that the case builtin is only used directly in a switch block
                    */
                    if (command == L"case")
                    {
                        if (block_infos.empty() || block_infos.back().type != SWITCH)
                        {
                            err=1;

                            if (out)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(&tok),
                                      INVALID_CASE_ERR_MSG);

                                print_errors(*out, prefix);
                                const wcstring h = builtin_help_get(*this, L"case");
                                if (h.size())
                                    append_format(*out, L"%ls", h.c_str());
                            }
                        }
                    }

                    /*
                      Test that the return bultin is only used within function definitions
                    */
                    if (command == L"return")
                    {
                        bool found_func = false;
                        size_t block_idx = block_infos.size();
                        while (block_idx--)
                        {
                            if (block_infos.at(block_idx).type == FUNCTION_DEF)
                            {
                                found_func = true;
                                break;
                            }
                        }

                        if (!found_func)
                        {
                            /*
                              Peek to see if the next argument is
                              --help, in which case we'll allow it to
                              show the help.
                            */

                            int old_pos = tok_get_pos(&tok);
                            int is_help = 0;

                            tok_next(&tok);
                            if (tok_last_type(&tok) == TOK_STRING)
                            {
                                wcstring first_arg = tok_last(&tok);
                                if (expand_one(first_arg, EXPAND_SKIP_CMDSUBST) && parser_t::is_help(first_arg.c_str(), 3))
                                {
                                    is_help = 1;
                                }
                            }

                            tok_set_pos(&tok, old_pos);

                            if (!is_help)
                            {
                                err=1;

                                if (out)
                                {
                                    error(SYNTAX_ERROR,
                                          tok_get_pos(&tok),
                                          INVALID_RETURN_ERR_MSG);
                                    print_errors(*out, prefix);
                                }
                            }
                        }
                    }


                    /*
                      Test that break and continue are only used within loop blocks
                    */
                    if (contains(command, L"break", L"continue"))
                    {
                        bool found_loop = false;
                        size_t block_idx = block_infos.size();
                        while (block_idx--)
                        {
                            block_type_t type = block_infos.at(block_idx).type;
                            if (type == WHILE || type == FOR)
                            {
                                found_loop = true;
                                break;
                            }
                        }

                        if (!found_loop)
                        {
                            /*
                              Peek to see if the next argument is
                              --help, in which case we'll allow it to
                              show the help.
                            */

                            int old_pos = tok_get_pos(&tok);
                            int is_help = 0;

                            tok_next(&tok);
                            if (tok_last_type(&tok) == TOK_STRING)
                            {
                                wcstring first_arg = tok_last(&tok);
                                if (expand_one(first_arg, EXPAND_SKIP_CMDSUBST) && parser_t::is_help(first_arg.c_str(), 3))
                                {
                                    is_help = 1;
                                }
                            }

                            tok_set_pos(&tok, old_pos);

                            if (!is_help)
                            {
                                err=1;

                                if (out)
                                {
                                    error(SYNTAX_ERROR,
                                          tok_get_pos(&tok),
                                          INVALID_LOOP_ERR_MSG);
                                    print_errors(*out, prefix);
                                }
                            }
                        }
                    }

                    /*
                      Test that else and else-if are only used directly in an if-block
                    */
                    if (command == L"else")
                    {
                        if (block_infos.empty() || block_infos.back().type != IF)
                        {
                            err=1;
                            if (out)
                            {
                                error(SYNTAX_ERROR,
                                      tok_get_pos(&tok),
                                      INVALID_ELSE_ERR_MSG,
                                      command.c_str());

                                print_errors(*out, prefix);
                            }
                        }
                    }
                }
                else
                {
                    err |= parser_test_argument(tok_last(&tok), out, prefix, tok_get_pos(&tok));

                    /* If possible, keep track of number of supplied arguments */
                    if (arg_count >= 0 && expand_is_clean(tok_last(&tok)))
                    {
                        arg_count++;
                    }
                    else
                    {
                        arg_count = -1;
                    }

                    if (has_command)
                    {

                        /*
                          Try to make sure the second argument to 'for' is 'in'
                        */
                        if (command == L"for")
                        {
                            if (arg_count == 1)
                            {

                                if (wcsvarname(tok_last(&tok)))
                                {

                                    err = 1;

                                    if (out)
                                    {
                                        error(SYNTAX_ERROR,
                                              tok_get_pos(&tok),
                                              BUILTIN_FOR_ERR_NAME,
                                              L"for",
                                              tok_last(&tok));

                                        print_errors(*out, prefix);
                                    }
                                }

                            }
                            else if (arg_count == 2)
                            {
                                if (wcscmp(tok_last(&tok), L"in") != 0)
                                {
                                    err = 1;

                                    if (out)
                                    {
                                        error(SYNTAX_ERROR,
                                              tok_get_pos(&tok),
                                              BUILTIN_FOR_ERR_IN,
                                              L"for");

                                        print_errors(*out, prefix);
                                    }
                                }
                            }
                        }
                        else if (command == L"else")
                        {
                            if (arg_count == 1)
                            {
                                /* Any second argument must be "if" */
                                if (wcscmp(tok_last(&tok), L"if") != 0)
                                {
                                    err = 1;

                                    if (out)
                                    {
                                        error(SYNTAX_ERROR,
                                              tok_get_pos(&tok),
                                              BUILTIN_ELSEIF_ERR_ARGUMENT,
                                              L"else");
                                        print_errors(*out, prefix);
                                    }
                                }
                                else
                                {
                                    /* Successfully detected "else if". Now we need a new command. */
                                    needs_cmd = true;
                                    had_cmd = false;
                                }
                            }
                        }
                    }

                }

                break;
            }

            case TOK_REDIRECT_OUT:
            case TOK_REDIRECT_IN:
            case TOK_REDIRECT_APPEND:
            case TOK_REDIRECT_FD:
            case TOK_REDIRECT_NOCLOB:
            {
                if (!had_cmd)
                {
                    err = 1;
                    if (out)
                    {
                        error(SYNTAX_ERROR,
                              tok_get_pos(&tok),
                              INVALID_REDIRECTION_ERR_MSG);
                        print_errors(*out, prefix);
                    }
                }
                break;
            }

            case TOK_END:
            {
                if (needs_cmd && !had_cmd)
                {
                    err = 1;
                    if (out)
                    {
                        error(SYNTAX_ERROR,
                              tok_get_pos(&tok),
                              CMD_ERR_MSG,
                              tok_get_desc(tok_last_type(&tok)));
                        print_errors(*out, prefix);
                    }
                }
                needs_cmd = false;
                had_cmd = 0;
                is_pipeline=0;
                forbid_pipeline=0;
                end_of_cmd = 1;

                break;
            }

            case TOK_PIPE:
            {
                if (!had_cmd)
                {
                    err=1;
                    if (out)
                    {
                        if (tok_get_pos(&tok)>0 && buff[tok_get_pos(&tok)-1] == L'|')
                        {
                            error(SYNTAX_ERROR,
                                  tok_get_pos(&tok),
                                  CMD_OR_ERR_MSG,
                                  tok_get_desc(tok_last_type(&tok)));

                        }
                        else
                        {
                            error(SYNTAX_ERROR,
                                  tok_get_pos(&tok),
                                  CMD_ERR_MSG,
                                  tok_get_desc(tok_last_type(&tok)));
                        }

                        print_errors(*out, prefix);
                    }
                }
                else if (forbid_pipeline)
                {
                    err=1;
                    if (out)
                    {
                        error(SYNTAX_ERROR,
                              tok_get_pos(&tok),
                              EXEC_ERR_MSG);

                        print_errors(*out, prefix);
                    }
                }
                else
                {
                    needs_cmd = true;
                    is_pipeline=1;
                    had_cmd=0;
                    end_of_cmd = 1;

                }
                break;
            }

            case TOK_BACKGROUND:
            {
                if (!had_cmd)
                {
                    err = 1;
                    if (out)
                    {
                        if (tok_get_pos(&tok)>0 && buff[tok_get_pos(&tok)-1] == L'&')
                        {
                            error(SYNTAX_ERROR,
                                  tok_get_pos(&tok),
                                  CMD_AND_ERR_MSG,
                                  tok_get_desc(tok_last_type(&tok)));

                        }
                        else
                        {
                            error(SYNTAX_ERROR,
                                  tok_get_pos(&tok),
                                  CMD_ERR_MSG,
                                  tok_get_desc(tok_last_type(&tok)));
                        }

                        print_errors(*out, prefix);
                    }
                }

                had_cmd = 0;
                end_of_cmd = 1;

                break;
            }

            case TOK_ERROR:
            default:
                if (tok_get_error(&tok) == TOK_UNTERMINATED_QUOTE)
                {
                    unfinished = 1;
                }
                else
                {
                    // Only print errors once
                    if (out && ! err)
                    {
                        error(SYNTAX_ERROR,
                              tok_get_pos(&tok),
                              TOK_ERR_MSG,
                              tok_last(&tok));


                        print_errors(*out, prefix);
                    }
                    err = 1;
                }

                break;
        }

        if (end_of_cmd)
        {
            if (has_command && command == L"for")
            {
                if (arg_count >= 0 && arg_count < 2)
                {
                    /*
                      Not enough arguments to the for builtin
                    */
                    err = 1;

                    if (out)
                    {
                        error(SYNTAX_ERROR,
                              tok_get_pos(&tok),
                              BUILTIN_FOR_ERR_COUNT,
                              L"for",
                              arg_count);

                        print_errors(*out, prefix);
                    }
                }
            }
            else if (has_command && command == L"else")
            {
                if (arg_count == 1)
                {
                    /* If we have any arguments, we must have at least two...either "else" or "else if foo..." */
                    err = true;
                    if (out)
                    {
                        error(SYNTAX_ERROR,
                              tok_get_pos(&tok),
                              BUILTIN_ELSEIF_ERR_COUNT,
                              L"else",
                              arg_count);

                        print_errors(*out, prefix);

                    }
                }
            }

        }

        if (!tok_has_next(&tok))
            break;

    }

    if (needs_cmd)
    {
        err=1;
        if (out)
        {
            error(SYNTAX_ERROR,
                  tok_get_pos(&tok),
                  COND_ERR_MSG);

            print_errors(*out, prefix);
        }
    }


    if (out != NULL && ! block_infos.empty())
    {
        const wchar_t *cmd;
        int bad_pos = block_infos.back().position;
        block_type_t bad_type = block_infos.back().type;

        error(SYNTAX_ERROR, bad_pos, BLOCK_END_ERR_MSG);

        print_errors(*out, prefix);

        cmd = parser_get_block_command(bad_type);
        if (cmd)
        {
            const wcstring h = builtin_help_get(*this, cmd);
            if (h.size())
            {
                append_format(*out, L"%ls", h.c_str());
            }
        }


    }

    /*
      Fill in the unset block_level entries. Until now, only places
      where the block level _changed_ have been filled out. This fills
      in the rest.
    */

    if (block_level)
    {
        int last_level = 0;
        size_t i, len = wcslen(buff);
        for (i=0; i<len; i++)
        {
            if (block_level[i] >= 0)
            {
                last_level = block_level[i];
                /*
                  Make all whitespace before a token have the new
                  level. This avoid using the wrong indentation level
                  if a new line starts with whitespace.
                */
                size_t prev_char_idx = i;
                while (prev_char_idx--)
                {
                    if (!wcschr(L" \n\t\r", buff[prev_char_idx]))
                        break;
                    block_level[prev_char_idx] = last_level;
                }
            }
            block_level[i] = last_level;
        }

        /*
          Make all trailing whitespace have the block level that the
          validator had at exit. This makes sure a new line is
          correctly indented even if it is empty.
        */
        int last_indent = block_infos.empty() ? 0 : block_infos.back().indentation;
        size_t suffix_idx = len;
        while (suffix_idx--)
        {
            if (!wcschr(L" \n\t\r", buff[suffix_idx]))
                break;
            block_level[suffix_idx] = last_indent;
        }
    }

    /*
      Calculate exit status
    */
    if (! block_infos.empty())
        unfinished = 1;

    if (err)
        res |= PARSER_TEST_ERROR;

    if (unfinished)
        res |= PARSER_TEST_INCOMPLETE;

    /*
      Cleanup
    */

    error_code=0;


    return res;

}

block_t::block_t(block_type_t t) :
    block_type(t),
    made_fake(false),
    skip(),
    had_command(),
    tok_pos(),
    loop_status(),
    job(),
    src_filename(),
    src_lineno(),
    wants_pop_env(false),
    event_blocks(),
    outer(NULL)
{
}

block_t::~block_t()
{
}

/* Various block constructors */

if_block_t::if_block_t() :
    block_t(IF),
    if_expr_evaluated(false),
    is_elseif_entry(false),
    any_branch_taken(false),
    else_evaluated(false)
{
}

event_block_t::event_block_t(const event_t &evt) :
    block_t(EVENT),
    event(evt)
{
}

function_block_t::function_block_t(const process_t *p, const wcstring &n, bool shadows) :
    block_t(shadows ? FUNCTION_CALL : FUNCTION_CALL_NO_SHADOW),
    process(p),
    name(n)
{
}

source_block_t::source_block_t(const wchar_t *src) :
    block_t(SOURCE),
    source_file(src)
{
}

for_block_t::for_block_t(const wcstring &var) :
    block_t(FOR),
    variable(var),
    sequence()
{
}

while_block_t::while_block_t() :
    block_t(WHILE),
    status(0)
{
}

switch_block_t::switch_block_t(const wcstring &sv) :
    block_t(SWITCH),
    switch_taken(false),
    switch_value(sv)
{
}

fake_block_t::fake_block_t() :
    block_t(FAKE)
{
}

function_def_block_t::function_def_block_t() :
    block_t(FUNCTION_DEF),
    function_data()
{
}

scope_block_t::scope_block_t(block_type_t type) :
    block_t(type)
{
    assert(type == BEGIN || type == TOP || type == SUBST);
}

breakpoint_block_t::breakpoint_block_t() :
    block_t(BREAKPOINT)
{
}