aboutsummaryrefslogtreecommitdiff
path: root/libbuild2/script/parser.cxx
blob: 2a213ab73545848f551382766177509e2a9d93bd (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
// file      : libbuild2/script/parser.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbuild2/script/parser.hxx>

#include <cstring> // strchr()
#include <sstream>

#include <libbuild2/variable.hxx>

#include <libbuild2/script/run.hxx>             // exit, stream_reader
#include <libbuild2/script/lexer.hxx>
#include <libbuild2/script/builtin-options.hxx>

using namespace std;

namespace build2
{
  namespace script
  {
    using type = token_type;

    bool parser::
    need_cmdline_relex (const string& s)
    {
      for (auto i (s.begin ()), e (s.end ()); i != e; ++i)
      {
        char c (*i);

        if (c == '\\')
        {
          if (++i == e)
            return false;

          c = *i;

          if (c == '\\' || c == '\'' || c == '\"')
            return true;

          // Fall through.
        }

        if (strchr ("|<>&\"'", c) != nullptr)
          return true;
      }

      return false;
    }

    value parser::
    parse_variable_line (token& t, type& tt)
    {
      // enter: assignment
      // leave: newline or unknown token

      next_with_attributes (t, tt);

      // Parse value attributes if any. Note that it's ok not to have
      // anything after the attributes (e.g., foo=[null]).
      //
      attributes_push (t, tt, true);

      // @@ PAT: Should we expand patterns? Note that it will only be
      // simple ones since we have disabled {}. Also, what would be the
      // pattern base directory?
      //
      return tt != type::newline && start_names (tt)
        ? parse_value (t, tt,
                       pattern_mode::ignore,
                       "variable value",
                       nullptr)
        : value (names ());
    }

    // Parse the regular expression representation (non-empty string value
    // framed with introducer characters and optionally followed by flag
    // characters from the {di} set, for example '/foo/id') into
    // components. Also return end-of-parsing position if requested,
    // otherwise treat any unparsed characters left as an error.
    //
    struct regex_parts
    {
      string value;
      char   intro;
      string flags; // Combination of characters from {di} set.

      // Create a special empty object.
      //
      regex_parts (): intro ('\0') {}

      regex_parts (string v, char i, string f)
          : value (move (v)), intro (i), flags (move (f)) {}
    };

    static regex_parts
    parse_regex (const string& s,
                 const location& l,
                 const char* what,
                 size_t* end = nullptr)
    {
      if (s.empty ())
        fail (l) << "no introducer character in " << what;

      size_t p (s.find (s[0], 1)); // Find terminating introducer.

      if (p == string::npos)
        fail (l) << "no closing introducer character in " << what;

      size_t rn (p - 1); // Regex length.
      if (rn == 0)
        fail (l) << what << " is empty";

      // Find end-of-flags position.
      //
      size_t fp (++p); // Save flags starting position.
      for (char c; (c = s[p]) == 'd' || c == 'i'; ++p) ;

      // If string end is not reached then report invalid flags, unless
      // end-of-parsing position is requested (which means regex is just a
      // prefix).
      //
      if (s[p] != '\0' && end == nullptr)
        fail (l) << "junk at the end of " << what;

      if (end != nullptr)
        *end = p;

      return regex_parts (string (s, 1, rn), s[0], string (s, fp, p - fp));
    }

    optional<process_path> parser::
    parse_program (token& t, type& tt,
                   bool, bool,
                   names& ns, parse_names_result& pr)
    {
      pr = parse_names (t, tt,
                        ns,
                        pattern_mode::ignore,
                        true /* chunk */,
                        "command line",
                        nullptr);

      return nullopt;
    }

    parser::parse_command_expr_result parser::
    parse_command_expr (token& t, type& tt,
                        const redirect_aliases& ra,
                        optional<token>&& program)
    {
      // enter: first (or second, if program) token of the command line
      // leave: <newline> or unknown token

      command_expr expr;

      // OR-ed to an implied false for the first term.
      //
      if (!pre_parse_)
        expr.push_back ({expr_operator::log_or, command_pipe ()});

      command c; // Command being assembled.

      // Make sure the command makes sense.
      //
      auto check_command = [&c, this] (const location& l, bool last)
      {
        if (c.out && c.out->type == redirect_type::merge &&
            c.err && c.err->type == redirect_type::merge)
          fail (l) << "stdout and stderr redirected to each other";

        if (!last && c.out)
          fail (l) << "stdout is both redirected and piped";
      };

      // Check that the introducer character differs from '/' if the
      // portable path modifier is specified. Must be called before
      // parse_regex() (see below) to make sure its diagnostics is
      // meaningful.
      //
      // Note that the portable path modifier assumes '/' to be a valid
      // regex character and so makes it indistinguishable from the
      // terminating introducer.
      //
      auto check_regex_mod = [this] (const string& mod,
                                     const string& re,
                                     const location& l,
                                     const char* what)
      {
        // Handles empty regex properly.
        //
        if (mod.find ('/') != string::npos && re[0] == '/')
          fail (l) << "portable path modifier and '/' introducer in " << what;
      };

      // Pending positions where the next word should go.
      //
      enum class pending
      {
        none,
        program_first,
        program_next,
        in_string,
        in_document,
        in_file,
        out_merge,
        out_string,
        out_str_regex,
        out_document,
        out_doc_regex,
        out_file,
        err_merge,
        err_string,
        err_str_regex,
        err_document,
        err_doc_regex,
        err_file,
        clean
      };
      pending p (pending::program_first);
      string mod;   // Modifiers for pending in_* and out_* positions.
      here_docs hd; // Expected here-documents.

      // Add the next word to either one of the pending positions or to
      // program arguments by default.
      //
      auto add_word = [&c, &p, &mod, &check_regex_mod, this]
                      (string&& w, const location& l)
      {
        auto add_merge = [&l, this] (optional<redirect>& r,
                                     const string& w,
                                     int fd)
        {
          assert (r); // Must already be present.

          try
          {
            size_t n;
            if (stoi (w, &n) == fd && n == w.size ())
            {
              r->fd = fd;
              return;
            }
          }
          catch (const exception&) {} // Fall through.

          fail (l) << (fd == 1 ? "stderr" : "stdout") << " merge redirect "
                   << "file descriptor must be " << fd;
        };

        auto add_here_str = [] (optional<redirect>& r, string&& w)
        {
          assert (r); // Must already be present.

          if (r->modifiers ().find (':') == string::npos)
            w += '\n';
          r->str = move (w);
        };

        auto add_here_str_regex = [&l, &check_regex_mod] (
          optional<redirect>& r, int fd, string&& w)
        {
          assert (r); // Must already be present.

          const char* what (nullptr);
          switch (fd)
          {
          case 1: what = "stdout regex redirect"; break;
          case 2: what = "stderr regex redirect"; break;
          }

          check_regex_mod (r->modifiers (), w, l, what);

          regex_parts rp (parse_regex (w, l, what));

          regex_lines& re (r->regex);
          re.intro = rp.intro;

          re.lines.emplace_back (
            l.line, l.column, move (rp.value), move (rp.flags));

          // Add final blank line unless suppressed.
          //
          // Note that the position is synthetic, but that's ok as we don't
          // expect any diagnostics to refer this line.
          //
          if (r->modifiers ().find (':') == string::npos)
            re.lines.emplace_back (l.line, l.column, string (), false);
        };

        auto parse_path = [&l, this] (string&& w, const char* what) -> path
        {
          try
          {
            path p (move (w));

            if (!p.empty ())
            {
              p.normalize ();
              return p;
            }

            fail (l) << "empty " << what << endf;
          }
          catch (const invalid_path& e)
          {
            fail (l) << "invalid " << what << " '" << e.path << "'" << endf;
          }
        };

        auto add_file = [&parse_path] (optional<redirect>& r,
                                       int fd,
                                       string&& w)
        {
          assert (r); // Must already be present.

          const char* what (nullptr);
          switch (fd)
          {
          case 0: what = "stdin redirect path";  break;
          case 1: what = "stdout redirect path"; break;
          case 2: what = "stderr redirect path"; break;
          }

          r->file.path = parse_path (move (w), what);
        };

        switch (p)
        {
        case pending::none: c.arguments.push_back (move (w)); break;
        case pending::program_first:
        case pending::program_next:
          c.program = process_path (nullptr /* initial */,
                                    parse_path (move (w), "program path"),
                                    path () /* effect */);
          break;

        case pending::out_merge: add_merge (c.out, w, 2); break;
        case pending::err_merge: add_merge (c.err, w, 1); break;

        case pending::in_string:  add_here_str (c.in,  move (w)); break;
        case pending::out_string: add_here_str (c.out, move (w)); break;
        case pending::err_string: add_here_str (c.err, move (w)); break;

        case pending::out_str_regex:
          {
            add_here_str_regex (c.out, 1, move (w));
            break;
          }
        case pending::err_str_regex:
          {
            add_here_str_regex (c.err, 2, move (w));
            break;
          }

          // These are handled specially below.
          //
        case pending::in_document:
        case pending::out_document:
        case pending::err_document:
        case pending::out_doc_regex:
        case pending::err_doc_regex: assert (false); break;

        case pending::in_file:  add_file (c.in,  0, move (w)); break;
        case pending::out_file: add_file (c.out, 1, move (w)); break;
        case pending::err_file: add_file (c.err, 2, move (w)); break;

        case pending::clean:
          {
            cleanup_type t;
            switch (mod[0]) // Ok, if empty
            {
            case '!': t = cleanup_type::never;  break;
            case '?': t = cleanup_type::maybe;  break;
            default:  t = cleanup_type::always; break;
            }

            c.cleanups.push_back (
              {t, parse_path (move (w), "cleanup path")});
            break;
          }
        }

        p = pending::none;
        mod.clear ();
      };

      // Make sure we don't have any pending positions to fill.
      //
      auto check_pending = [&p, this] (const location& l)
      {
        const char* what (nullptr);

        switch (p)
        {
        case pending::none:                                             break;
        case pending::program_first:
        case pending::program_next:  what = "program";                  break;
        case pending::in_string:     what = "stdin here-string";        break;
        case pending::in_document:   what = "stdin here-document end";  break;
        case pending::in_file:       what = "stdin file";               break;
        case pending::out_merge:     what = "stdout file descriptor";   break;
        case pending::out_string:    what = "stdout here-string";       break;
        case pending::out_document:  what = "stdout here-document end"; break;
        case pending::out_file:      what = "stdout file";              break;
        case pending::err_merge:     what = "stderr file descriptor";   break;
        case pending::err_string:    what = "stderr here-string";       break;
        case pending::err_document:  what = "stderr here-document end"; break;
        case pending::err_file:      what = "stderr file";              break;
        case pending::clean:         what = "cleanup path";             break;

        case pending::out_str_regex:
          {
            what = "stdout here-string regex";
            break;
          }
        case pending::err_str_regex:
          {
            what = "stderr here-string regex";
            break;
          }
        case pending::out_doc_regex:
          {
            what = "stdout here-document regex end";
            break;
          }
        case pending::err_doc_regex:
          {
            what = "stderr here-document regex end";
            break;
          }
        }

        if (what != nullptr)
          fail (l) << "missing " << what;
      };

      // Parse the redirect operator.
      //
      // If the token type is the redirect alias then tt must contain the type
      // the alias resolves to and the token type otherwise. Note that this
      // argument defines the redirect semantics. Also note that the token is
      // saved into the redirect to keep the modifiers and the original
      // representation.
      //
      auto parse_redirect = [&c, &expr, &p, &mod, &hd, this]
                            (token&& t, type tt, const location& l)
      {
        // The redirect alias token type must be resolved.
        //
        assert (tt != type::in_l   &&
                tt != type::in_ll  &&
                tt != type::in_lll &&
                tt != type::out_g  &&
                tt != type::out_gg &&
                tt != type::out_ggg);

        // Our semantics is the last redirect seen takes effect.
        //
        assert (p == pending::none && mod.empty ());

        // See if we have the file descriptor.
        //
        unsigned long fd (3);
        if (!t.separated)
        {
          if (c.arguments.empty ())
            fail (l) << "missing redirect file descriptor";

          const string& s (c.arguments.back ());

          try
          {
            size_t n;
            fd = stoul (s, &n);

            if (n != s.size () || fd > 2)
              throw invalid_argument (string ());
          }
          catch (const exception&)
          {
            fail (l) << "invalid redirect file descriptor '" << s << "'";
          }

          c.arguments.pop_back ();
        }

        // Validate/set default file descriptor.
        //
        switch (tt)
        {
        case type::in_pass:
        case type::in_null:
        case type::in_str:
        case type::in_doc:
        case type::in_file:
          {
            if ((fd = fd == 3 ? 0 : fd) != 0)
              fail (l) << "invalid in redirect file descriptor " << fd;

            if (!expr.back ().pipe.empty ())
              fail (l) << "stdin is both piped and redirected";

            break;
          }
        case type::out_pass:
        case type::out_null:
        case type::out_trace:
        case type::out_merge:
        case type::out_str:
        case type::out_doc:
        case type::out_file_cmp:
        case type::out_file_ovr:
        case type::out_file_app:
          {
            if ((fd = fd == 3 ? 1 : fd) == 0)
              fail (l) << "invalid out redirect file descriptor " << fd;

            break;
          }
        }

        // Don't move as we will save the token into the redirect object.
        //
        mod = t.value;

        // Handle the none redirect (no data allowed) in the switch construct
        // if/when the respective syntax is invented.
        //
        redirect_type rt (redirect_type::none);
        switch (tt)
        {
        case type::in_pass:
        case type::out_pass:  rt = redirect_type::pass;  break;

        case type::in_null:
        case type::out_null:  rt = redirect_type::null;  break;

        case type::out_trace: rt = redirect_type::trace; break;

        case type::out_merge: rt = redirect_type::merge; break;

        case type::in_str:
        case type::out_str:
          {
            bool re (mod.find ('~') != string::npos);
            assert (tt == type::out_str || !re);

            rt = re
              ? redirect_type::here_str_regex
              : redirect_type::here_str_literal;

            break;
          }

        case type::in_doc:
        case type::out_doc:
          {
            bool re (mod.find ('~') != string::npos);
            assert (tt == type::out_doc || !re);

            rt = re
              ? redirect_type::here_doc_regex
              : redirect_type::here_doc_literal;

            break;
          }

        case type::in_file:
        case type::out_file_cmp:
        case type::out_file_ovr:
        case type::out_file_app: rt = redirect_type::file; break;
        }

        optional<redirect>& r (fd == 0 ? c.in  :
                               fd == 1 ? c.out :
                                         c.err);

        optional<redirect_type> overriden;

        if (r)
          overriden = r->type;

        r = redirect (rt);

        // Don't move as still may be used for pending here-document end
        // marker processing.
        //
        r->token = move (t);

        switch (rt)
        {
        case redirect_type::none:
          // Remove the assertion if/when the none redirect syntax is
          // invented.
          //
          assert (false);
          // Fall through.
        case redirect_type::pass:
        case redirect_type::null:
        case redirect_type::trace:
          break;
        case redirect_type::merge:
          switch (fd)
          {
          case 0: assert (false);         break;
          case 1: p = pending::out_merge; break;
          case 2: p = pending::err_merge; break;
          }
          break;
        case redirect_type::here_str_literal:
          switch (fd)
          {
          case 0: p = pending::in_string;  break;
          case 1: p = pending::out_string; break;
          case 2: p = pending::err_string; break;
          }
          break;
        case redirect_type::here_str_regex:
          switch (fd)
          {
          case 0: assert (false);             break;
          case 1: p = pending::out_str_regex; break;
          case 2: p = pending::err_str_regex; break;
          }
          break;
        case redirect_type::here_doc_literal:
          switch (fd)
          {
          case 0: p = pending::in_document;  break;
          case 1: p = pending::out_document; break;
          case 2: p = pending::err_document; break;
          }
          break;
        case redirect_type::here_doc_regex:
          switch (fd)
          {
          case 0: assert (false);             break;
          case 1: p = pending::out_doc_regex; break;
          case 2: p = pending::err_doc_regex; break;
          }
          break;
        case redirect_type::file:
          switch (fd)
          {
          case 0: p = pending::in_file;  break;
          case 1: p = pending::out_file; break;
          case 2: p = pending::err_file; break;
          }

          // Also sets for stdin, but this is harmless.
          //
          r->file.mode = tt == type::out_file_ovr ? redirect_fmode::overwrite :
                         tt == type::out_file_app ? redirect_fmode::append    :
                                                    redirect_fmode::compare;

          break;

        case redirect_type::here_doc_ref: assert (false); break;
        }

        // If we are overriding a here-document, then remove the reference
        // to this command redirect from the corresponding here_doc object.
        //
        if (!pre_parse_ &&
            overriden &&
            (*overriden == redirect_type::here_doc_literal ||
             *overriden == redirect_type::here_doc_regex))
        {
          size_t e (expr.size () - 1);
          size_t p (expr.back ().pipe.size ());
          int    f (static_cast<int> (fd));

          for (here_doc& d: hd)
          {
            small_vector<here_redirect, 2>& rs (d.redirects);

            auto i (find_if (rs.begin (), rs.end (),
                             [e, p, f] (const here_redirect& r)
                             {
                               return r.expr == e &&
                                 r.pipe == p &&
                                 r.fd   == f;
                             }));

            if (i != rs.end ())
            {
              rs.erase (i);
              break;
            }
          }
        }
      };

      // Set pending cleanup type.
      //
      auto parse_clean = [&p, &mod] (token& t)
      {
        p = pending::clean;
        mod = move (t.value);
      };

      const location ll (get_location (t)); // Line location.

      // Keep parsing chunks of the command line until we see one of the
      // "terminators" (newline or unknown/unexpected token).
      //
      location l (ll);
      names ns; // Reuse to reduce allocations.

      bool for_loop (false);

      if (program)
      {
        assert (program->type == type::word);

        // Note that here we skip all the parse_program() business since the
        // program can only be one of the specially-recognized names.
        //
        if (program->value == "for")
          for_loop = true;
        else
          assert (false); // Must be specially-recognized program.

        // Save the program name and continue parsing as a command.
        //
        add_word (move (program->value), get_location (*program));
      }

      for (bool done (false); !done; l = get_location (t))
      {
        tt = ra.resolve (tt);

        switch (tt)
        {
        case type::newline:
          {
            done = true;
            break;
          }

        case type::equal:
        case type::not_equal:
          {
            if (for_loop)
              fail (l) << "for-loop exit code cannot be checked";

            if (!pre_parse_)
              check_pending (l);

            c.exit = parse_command_exit (t, tt);

            // Only a limited set of things can appear after the exit status
            // so we check this here.
            //
            switch (tt)
            {
            case type::newline:

            case type::pipe:
            case type::log_or:
            case type::log_and:
              break;

            default:
              {
                // Bail out if this is one of the unknown/unexpected tokens.
                //
                done = true;
                break;
              }
            }

            break;
          }

        case type::pipe:
          if (for_loop)
            fail (l) << "for-loop must be last command in a pipe";
          // Fall through.

        case type::log_or:
        case type::log_and:
          if (for_loop)
            fail (l) << "command expression involving for-loop";
          // Fall through.

        case type::clean:
          if (for_loop)
            fail (l) << "cleanup in for-loop";
          // Fall through.

        case type::out_pass:
        case type::out_null:
        case type::out_trace:
        case type::out_merge:
        case type::out_str:
        case type::out_doc:
        case type::out_file_cmp:
        case type::out_file_ovr:
        case type::out_file_app:
          if (for_loop)
            fail (l) << "output redirect in for-loop";
          // Fall through.

        case type::in_pass:
        case type::in_null:
        case type::in_str:
        case type::in_doc:
        case type::in_file:
          {
            if (pre_parse_)
            {
              // The only things we need to handle here are the tokens that
              // introduce the next command, since we handle the command
              // leading name chunks specially, and the here-document and
              // here-document regex end markers, since we need to know how
              // many of them to pre-parse after the command.
              //
              switch (tt)
              {
              case type::pipe:
              case type::log_or:
              case type::log_and:
                p = pending::program_next;
                break;

              case type::in_doc:
              case type::out_doc:
                mod = move (t.value);

                bool re (mod.find ('~') != string::npos);
                const char* what (re
                                  ? "here-document regex end marker"
                                  : "here-document end marker");

                // We require the end marker to be a literal, unquoted word.
                // In particularm, we don't allow quoted because of cases
                // like foo"$bar" (where we will see word 'foo').
                //
                next (t, tt);

                // We require the end marker to be an unquoted or completely
                // quoted word. The complete quoting becomes important for
                // cases like foo"$bar" (where we will see word 'foo').
                //
                // For good measure we could have also required it to be
                // separated from the following token, but out grammar
                // allows one to write >>EOO;. The problematic sequence
                // would be >>FOO$bar -- on reparse it will be expanded
                // as a single word.
                //
                if (tt != type::word || t.value.empty ())
                  fail (t) << "expected " << what;

                peek ();
                const token& p (peeked ());
                if (!p.separated)
                {
                  switch (p.type)
                  {
                  case type::dollar:
                  case type::lparen:
                    fail (p) << what << " must be literal";
                  }
                }

                quote_type qt (t.qtype);
                switch (qt)
                {
                case quote_type::unquoted:
                  qt = quote_type::single; // Treat as single-quoted.
                  break;
                case quote_type::single:
                case quote_type::double_:
                  if (t.qcomp)
                    break;
                  // Fall through.
                case quote_type::mixed:
                  fail (t) << "partially-quoted " << what;
                }

                regex_parts r;
                string end (move (t.value));

                if (re)
                {
                  check_regex_mod (mod, end, l, what);

                  r = parse_regex (end, l, what);
                  end = move (r.value); // The "cleared" end marker.
                }

                bool literal (qt == quote_type::single);
                bool shared (false);

                for (const auto& d: hd)
                {
                  if (d.end == end)
                  {
                    auto check = [&t, &end, &re, this] (bool c,
                                                        const char* what)
                    {
                      if (!c)
                        fail (t) << "different " << what
                                 << " for shared here-document "
                                 << (re ? "regex '" : "'") << end << "'";
                    };

                    check (d.modifiers == mod, "modifiers");
                    check (d.literal == literal, "quoting");

                    if (re)
                    {
                      check (d.regex == r.intro, "introducers");
                      check (d.regex_flags == r.flags, "global flags");
                    }

                    shared = true;
                    break;
                  }
                }

                if (!shared)
                  hd.push_back (
                    here_doc {
                      {},
                      move (end),
                      literal,
                      move (mod),
                      r.intro, move (r.flags)});

                break;
              }

              next (t, tt);
              break;
            }

            // If this is one of the operators/separators, check that we
            // don't have any pending locations to be filled.
            //
            check_pending (l);

            // Note: there is another one in the inner loop below.
            //
            switch (tt)
            {
            case type::pipe:
            case type::log_or:
            case type::log_and:
              {
                // Check that the previous command makes sense.
                //
                check_command (l, tt != type::pipe);
                expr.back ().pipe.push_back (move (c));

                c = command ();
                p = pending::program_next;

                if (tt != type::pipe)
                {
                  expr_operator o (tt == type::log_or
                                   ? expr_operator::log_or
                                   : expr_operator::log_and);
                  expr.push_back ({o, command_pipe ()});
                }

                break;
              }

            case type::in_pass:
            case type::out_pass:

            case type::in_null:
            case type::out_null:

            case type::out_trace:

            case type::out_merge:

            case type::in_str:
            case type::in_doc:
            case type::out_str:
            case type::out_doc:

            case type::in_file:
            case type::out_file_cmp:
            case type::out_file_ovr:
            case type::out_file_app:
              {
                parse_redirect (move (t), tt, l);
                break;
              }

            case type::clean:
              {
                parse_clean (t);
                break;
              }

            default: assert (false); break;
            }

            next (t, tt);
            break;
          }
        case type::lsbrace:
          {
            // Recompose the attributes into a single command argument.
            //
            assert (!pre_parse_);

            attributes_push (t, tt, true /* standalone */);

            attributes as (attributes_pop ());
            assert (!as.empty ());

            ostringstream os;
            names storage;
            char c ('[');
            for (const attribute& a: as)
            {
              os << c << a.name;

              if (!a.value.null)
              {
                os << '=';

                storage.clear ();
                to_stream (os,
                           reverse (a.value, storage),
                           quote_mode::normal,
                           '@');
              }

              c = ',';
            }
            os << ']';

            add_word (os.str (), l);
            break;
          }
        default:
          {
            // Bail out if this is one of the unknown tokens.
            //
            if (!start_names (tt))
            {
              done = true;
              break;
            }

            // Here-document end markers are literal (we verified that above
            // during pre-parsing) and we need to know whether they were
            // quoted. So handle this case specially.
            //
            {
              int fd;
              switch (p)
              {
              case pending::in_document:   fd =  0; break;
              case pending::out_document:
              case pending::out_doc_regex: fd =  1; break;
              case pending::err_document:
              case pending::err_doc_regex: fd =  2; break;
              default:                     fd = -1; break;
              }

              if (fd != -1)
              {
                if (tt != type::word || t.value.empty ())
                  fail (t) << "expected here-document end marker";

                here_redirect rd {
                  expr.size () - 1, expr.back ().pipe.size (), fd};

                string end (move (t.value));

                regex_parts r;

                if (p == pending::out_doc_regex ||
                    p == pending::err_doc_regex)
                {
                  // We can't fail here as we already parsed all the end
                  // markers during pre-parsing stage, and so no need in the
                  // description.
                  //
                  r = parse_regex (end, l, "");
                  end = move (r.value); // The "cleared" end marker.
                }

                bool shared (false);
                for (auto& d: hd)
                {
                  // No need to check that redirects that share here-document
                  // have the same modifiers, etc. That have been done during
                  // pre-parsing.
                  //
                  if (d.end == end)
                  {
                    d.redirects.emplace_back (rd);
                    shared = true;
                    break;
                  }
                }

                if (!shared)
                  hd.push_back (
                    here_doc {
                      {rd},
                        move (end),
                          (t.qtype == quote_type::unquoted ||
                           t.qtype == quote_type::single),
                          move (mod),
                          r.intro, move (r.flags)});

                p = pending::none;
                mod.clear ();

                next (t, tt);
                break;
              }
            }

            bool prog (p == pending::program_first ||
                       p == pending::program_next);

            // Check if this is the env pseudo-builtin or the for-loop.
            //
            bool env (false);
            if (prog && tt == type::word)
            {
              if (t.value == "env")
              {
                parsed_env r (parse_env_builtin (t, tt));
                c.cwd       = move (r.cwd);
                c.variables = move (r.variables);
                c.timeout   = r.timeout;
                env = true;
              }
              else if (t.value == "for")
              {
                if (expr.size () > 1)
                  fail (l) << "command expression involving for-loop";

                for_loop = true;

                // Save 'for' as a program name and continue parsing as a
                // command.
                //
                add_word (move (t.value), l);
                next (t, tt);
                continue;
              }
            }

            // Parse the next chunk as names to get expansion, etc. Note that
            // we do it in the chunking mode to detect whether anything in
            // each chunk is quoted. If we are waiting for the command
            // program, then delegate the parsing to the derived parser, so it
            // can translate complex program names (targets, process_paths)
            // during execution and perform some static analysis during
            // pre-parsing.
            //
            // @@ PAT: should we support pattern expansion? This is even
            // fuzzier than the variable case above. Though this is the
            // shell semantics. Think what happens when we do rm *.txt?
            //
            reset_quoted (t);

            parse_names_result pr;
            if (prog)
            {
              optional<process_path> pp (
                parse_program (t, tt,
                               p == pending::program_first, env,
                               ns, pr));

              // During pre-parsing we are not interested in the
              // parse_program() call result, so just discard the potentially
              // unhandled program chunk names.
              //
              if (!pre_parse_)
              {
                if (pp)
                {
                  c.program = move (*pp);
                  p = pending::none;
                }
              }
              else
              {
                ns.clear ();
                p = pending::none;
              }
            }
            else
              pr = parse_names (t, tt,
                                ns,
                                pattern_mode::ignore,
                                true /* chunk */,
                                "command line",
                                nullptr);

            // Nothing else to do if we are pre-parsing (or if parse_program()
            // took care of this chunk).
            //
            if (pre_parse_ || ns.empty ())
              break;

            // Process what we got.
            //
            // First see if this is a value that should not be re-lexed. We
            // only re-lex values of the special `cmdline` type that
            // represents a canned command line.
            //
            // Otherwise, determine whether anything inside was quoted (note
            // that the current token is "next" and is not part of this).
            //
            bool lex (
              pr.value
              ? pr.type != nullptr && pr.type->is_a<cmdline> ()
              : (quoted () - (t.qtype != quote_type::unquoted ? 1 : 0)) == 0);

            for (name& n: ns)
            {
              string s;

              try
              {
                s = value_traits<string>::convert (move (n), nullptr);
              }
              catch (const invalid_argument&)
              {
                diag_record dr (fail (l));
                dr << "invalid string value ";
                to_stream (dr.os, n, quote_mode::normal);
              }

              // If it is a quoted chunk, then we add the word as is.
              // Otherwise we re-lex it. But if the word doesn't contain any
              // interesting characters (operators plus quotes/escapes),
              // then no need to re-lex.
              //
              if (!lex || !need_cmdline_relex (s))
                add_word (move (s), l);
              else
              {
                // If the chunk re-parsing results in error, our diagnostics
                // will look like this:
                //
                // <string>:1:4: error: stdout merge redirect file descriptor must be 2
                //   script:2:5: info: while parsing string '1>&a'
                //
                auto df = make_diag_frame (
                  [this, s, &l](const diag_record& dr)
                  {
                    dr << info (l) << "while parsing string '" << s << "'";
                  });

                // When re-lexing we do "effective escaping" and only for
                // ['"\] (quotes plus the backslash itself). In particular,
                // there is no way to escape redirects, operators, etc. The
                // idea is to prefer quoting except for passing literal
                // quotes, for example:
                //
                // args = \"&foo\"
                // cmd $args               # cmd &foo
                //
                // args = 'x=\"foo bar\"'
                // cmd $args               # cmd x="foo bar"
                //
                istringstream is (s);
                path_name in ("<string>");
                lexer lex (is, in,
                           lexer_mode::command_expansion,
                           ra,
                           "\'\"\\");

                // Treat the first "sub-token" as always separated from what
                // we saw earlier.
                //
                // Note that this is not "our" token so we cannot do
                // fail(t). Rather we should do fail(l).
                //
                token t (lex.next ());
                location l (build2::get_location (t, in));
                t.separated = true;

                string w;
                bool f (t.type == type::eos); // If the whole thing is empty.

                for (; t.type != type::eos; t = lex.next ())
                {
                  type tt (ra.resolve (t.type));
                  l = build2::get_location (t, in);

                  // Re-lexing double-quotes will recognize $, ( inside as
                  // tokens so we have to reverse them back. Since we don't
                  // treat spaces as separators we can be sure we will get
                  // it right.
                  //
                  switch (tt)
                  {
                  case type::dollar: w += '$'; continue;
                  case type::lparen: w += '('; continue;
                  }

                  // Retire the current word. We need to distinguish between
                  // empty and non-existent (e.g., > vs >"").
                  //
                  if (!w.empty () || f)
                  {
                    add_word (move (w), l);
                    f = false;
                  }

                  if (tt == type::word)
                  {
                    w = move (t.value);
                    f = true;
                    continue;
                  }

                  // If this is one of the operators/separators, check that
                  // we don't have any pending locations to be filled.
                  //
                  check_pending (l);

                  // Note: there is another one in the outer loop above.
                  //
                  switch (tt)
                  {
                  case type::pipe:
                    if (for_loop)
                      fail (l) << "for-loop must be last command in a pipe";
                    // Fall through.

                  case type::log_or:
                  case type::log_and:
                    {
                      if (for_loop)
                        fail (l) << "command expression involving for-loop";

                      // Check that the previous command makes sense.
                      //
                      check_command (l, tt != type::pipe);
                      expr.back ().pipe.push_back (move (c));

                      c = command ();
                      p = pending::program_next;

                      if (tt != type::pipe)
                      {
                        expr_operator o (tt == type::log_or
                                         ? expr_operator::log_or
                                         : expr_operator::log_and);
                        expr.push_back ({o, command_pipe ()});
                      }

                      break;
                    }

                  case type::clean:
                    {
                      if (for_loop)
                        fail (l) << "cleanup in for-loop";

                      parse_clean (t);
                      break;
                    }

                  case type::in_doc:
                  case type::out_doc:
                    {
                      fail (l) << "here-document redirect in expansion";
                      break;
                    }

                  case type::out_pass:
                  case type::out_null:
                  case type::out_trace:
                  case type::out_merge:
                  case type::out_str:
                  case type::out_file_cmp:
                  case type::out_file_ovr:
                  case type::out_file_app:
                    if (for_loop)
                      fail (l) << "output redirect in for-loop";
                    // Fall through.

                  case type::in_pass:
                  case type::in_null:
                  case type::in_str:
                  case type::in_file:
                    {
                      parse_redirect (move (t), tt, l);
                      break;
                    }
                  }
                }

                // Don't forget the last word.
                //
                if (!w.empty () || f)
                  add_word (move (w), l);
              }
            }

            ns.clear ();
            break;
          }
        }
      }

      if (!pre_parse_)
      {
        // Verify we don't have anything pending to be filled and the
        // command makes sense.
        //
        check_pending (l);
        check_command (l, true);

        expr.back ().pipe.push_back (move (c));
      }

      return parse_command_expr_result {move (expr), move (hd), for_loop};
    }

    parser::parsed_env parser::
    parse_env_builtin (token& t, token_type& tt)
    {
      // enter: 'env' word token
      // leave: first token of the program name

      next (t, tt); // Skip 'env'.

      // Note that an option name and value can belong to different name
      // chunks. That's why we parse the env builtin arguments in the chunking
      // mode into the argument/location pair list up to the '--' separator
      // and parse this list into the variable sets/unsets afterwards.
      //
      // Align the size with environment_vars (double because of -u <var>
      // which is two arguments).
      //
      using args = small_vector<pair<string, location>, 4>;

      args as;
      names ns; // Reuse to reduce allocations.
      while (tt != type::word || t.value != "--")
      {
        location l (get_location (t));

        if (!start_names (tt))
          fail (l) << "env: expected option, variable, or '--' separator "
                   << "instead of " << t;

        parse_names (t, tt,
                     ns,
                     pattern_mode::ignore,
                     true /* chunk */,
                     "env builtin argument",
                     nullptr);

        if (pre_parse_)
          continue;

        for (name& n: ns)
        {
          try
          {
            as.emplace_back (
              value_traits<string>::convert (move (n), nullptr), l);
          }
          catch (const invalid_argument&)
          {
            diag_record dr (fail (l));
            dr << "invalid string value ";
            to_stream (dr.os, n, quote_mode::normal);
          }
        }

        ns.clear ();
      }

      location l (get_location (t)); // '--' location.
      next (t, tt);                  // Skip '--'.

      if (tt == type::newline || tt == type::eos)
        fail (t) << "env: expected program name instead of " << t;

      // Parse the env builtin options and arguments.
      //
      parsed_env r;

      // Note: args is empty in the pre-parse mode.
      //
      auto i (as.begin ()), e (as.end ());

      // Parse options (the timeout and variable unsets).
      //
      for (; i != e; ++i)
      {
        string& o (i->first);

        // Bail out if the options and arguments separator is encountered.
        //
        if (o == "-")
        {
          ++i;
          break;
        }

        // We should probably switch to CLI if we need anything more
        // elaborate. Note however, that we will have no precise error
        // location then.
        //

        // If this is an option represented with its long or short name, then
        // return its value as string and nullopt otherwise. In the former
        // case strip the value assignment from the option, if it is in the
        // <name>=<value> form, and fail if the option value is empty.
        //
        auto str = [&i, &e, &o, &l, this] (const char* lo, const char* so)
        {
          optional<string> r;

          if (o == lo || o == so)
          {
            if (++i == e)
              fail (l) << "env: missing value for option '" << o << "'";

            r = move (i->first);
          }
          else
          {
            size_t n (string::traits_type::length (lo));

            if (o.compare (0, n, lo) == 0 && o[n] == '=')
            {
              r = string (o, n + 1);
              o.resize (n);
            }
          }

          if (r && r->empty ())
            fail (i->second) << "env: empty value for option '" << o << "'";

          return r;
        };

        auto bad = [&i, &o, this] (const string& v)
        {
          fail (i->second) << "env: invalid value '" << v << "' for option '"
                           << o << "'";
        };

        // As above but convert the option value to a number and fail on
        // error.
        //
        auto num = [&str, &bad] (const char* ln, const char* sn)
        {
          optional<uint64_t> r;
          if (optional<string> s = str (ln, sn))
          {
            r = parse_number (*s);

            if (!r)
              bad (*s);
          }

          return r;
        };

        // As above but convert the option value to a directory path and fail
        // on error.
        //
        auto dir = [&str, &bad] (const char* ln, const char* sn)
        {
          optional<dir_path> r;
          if (optional<string> s = str (ln, sn))
          try
          {
            // Note that we don't need to check that the path is not empty,
            // since str() fails for empty values.
            //
            r = dir_path (move (*s));
          }
          catch (const invalid_path& e)
          {
            bad (e.path);
          }

          return r;
        };

        // Parse a known option or bail out to parsing the variable sets.
        //
        if (optional<uint64_t> v = num ("--timeout", "-t"))
        {
          r.timeout = chrono::seconds (*v);
        }
        else if (optional<dir_path> v = dir ("--cwd", "-c"))
        {
          r.cwd = move (*v);
        }
        else if (optional<string> v = str ("--unset", "-u"))
        {
          verify_environment_var_name (*v, "env: ", i->second, o.c_str ());

          r.variables.add (move (*v));
        }
        else
          break;
      }

      // Parse arguments (variable sets).
      //
      for (; i != e; ++i)
      {
        string& a (i->first);
        verify_environment_var_assignment (a, "env: ", i->second);

        r.variables.add (move (a));
      }

      return r;
    }

    command_exit parser::
    parse_command_exit (token& t, type& tt)
    {
      // enter: equal/not_equal
      // leave: token after exit status (one parse_names() chunk)

      exit_comparison comp (tt == type::equal
                            ? exit_comparison::eq
                            : exit_comparison::ne);

      // The next chunk should be the exit status.
      //
      next (t, tt);
      location l (get_location (t));
      names ns (parse_names (t, tt,
                             pattern_mode::ignore,
                             true,
                             "exit status",
                             nullptr));
      unsigned long es (256);

      if (!pre_parse_)
      {
        try
        {
          if (ns.size () == 1 && ns[0].simple () && !ns[0].empty ())
            es = stoul (ns[0].value);
        }
        catch (const exception&) {} // Fall through.

        if (es > 255)
        {
          diag_record dr;

          dr << fail (l) << "expected exit status instead of ";
          to_stream (dr.os, ns, quote_mode::normal);

          dr << info << "exit status is an unsigned integer less than 256";
        }
      }

      return command_exit {comp, static_cast<uint8_t> (es)};
    }

    void parser::
    parse_here_documents (token& t, type& tt,
                          parse_command_expr_result& pr)
    {
      // enter: newline
      // leave: newline

      // Parse here-document fragments in the order they were mentioned on
      // the command line.
      //
      for (here_doc& h: pr.docs)
      {
        // Switch to the here-line mode which is like single/double-quoted
        // string but recognized the newline as a separator.
        //
        mode (h.literal
              ? lexer_mode::here_line_single
              : lexer_mode::here_line_double);
        next (t, tt);

        parsed_doc v (
          parse_here_document (t, tt, h.end, h.modifiers, h.regex));

        // If all the here-document redirects are overridden, then we just
        // drop the fragment.
        //
        if (!pre_parse_ && !h.redirects.empty ())
        {
          auto i (h.redirects.cbegin ());

          command& c (pr.expr[i->expr].pipe[i->pipe]);

          optional<redirect>& r (i->fd == 0 ? c.in  :
                                 i->fd == 1 ? c.out :
                                              c.err);

          assert (r); // Must be present since it is referred.

          if (v.re)
          {
            assert (r->type == redirect_type::here_doc_regex);

            r->regex = move (v.regex);
            r->regex.flags = move (h.regex_flags);
          }
          else
          {
            assert (r->type == redirect_type::here_doc_literal);

            r->str = move (v.str);
          }

          r->end        = move (h.end);
          r->end_line   = v.end_line;
          r->end_column = v.end_column;

          // Note that our references cannot be invalidated because the
          // command_expr/command-pipe vectors already contain all their
          // elements.
          //
          for (++i; i != h.redirects.cend (); ++i)
          {
            command& c (pr.expr[i->expr].pipe[i->pipe]);

            optional<redirect>& ir (i->fd == 0 ? c.in  :
                                    i->fd == 1 ? c.out :
                                                 c.err);

            // Must be present since it is referenced by here-doc.
            //
            assert (ir);

            // Note: preserve the original representation.
            //
            ir = redirect (redirect_type::here_doc_ref, *r, move (ir->token));
          }
        }

        expire_mode ();
      }
    }

    parser::parsed_doc parser::
    parse_here_document (token& t, type& tt,
                         const string& em,
                         const string& mod,
                         char re)
    {
      // enter: first token on first line
      // leave: newline (after end marker)

      // String literal. Note that when decide if to terminate the previously
      // added line with a newline, we need to distinguish a yet empty result
      // and the one that has a single blank line added.
      //
      optional<string> rs;

      regex_lines rre;

      // Here-documents can be indented. The leading whitespaces of the end
      // marker line (called strip prefix) determine the indentation. Every
      // other line in the here-document should start with this prefix which
      // is automatically stripped. The only exception is a blank line.
      //
      // The fact that the strip prefix is only known at the end, after
      // seeing all the lines, is rather inconvenient. As a result, the way
      // we implement this is a bit hackish (though there is also something
      // elegant about it): at the end of the pre-parse stage we are going
      // re-examine the sequence of tokens that comprise this here-document
      // and "fix up" the first token of each line by stripping the prefix.
      //
      string sp;

      // Remember the position of the first token in this here-document.
      //
      size_t ri (pre_parse_ ? replay_data_.size () - 1 : 0);

      // We will use the location of the first token on the line for the
      // regex diagnostics. At the end of the loop it will point to the
      // beginning of the end marker.
      //
      location l;

      while (tt != type::eos)
      {
        l = get_location (t);

        // Check if this is the end marker. For starters, it should be a
        // single, unquoted word followed by a newline.
        //
        if (tt == type::word &&
            t.qtype == quote_type::unquoted &&
            peek () == type::newline)
        {
          const string& v (t.value);

          size_t vn (v.size ());
          size_t en (em.size ());

          // Then check that it ends with the end marker.
          //
          if (vn >= en && v.compare (vn - en, en, em) == 0)
          {
            // Now check that the prefix only contains whitespaces.
            //
            size_t n (vn - en);

            if (v.find_first_not_of (" \t") >= n)
            {
              assert (pre_parse_ || n == 0); // Should have been stripped.

              if (n != 0)
                sp.assign (v, 0, n); // Save the strip prefix.

              next (t, tt); // Get the newline.
              break;
            }
          }
        }

        // Expand the line (can be blank).
        //
        // @@ PAT: one could argue that if we do it in variables, then we
        // should do it here as well. Though feels bizarre.
        //
        names ns (tt != type::newline
                  ? parse_names (t, tt,
                                 pattern_mode::ignore,
                                 false,
                                 "here-document line",
                                 nullptr)
                  : names ());

        if (!pre_parse_)
        {
          // What shall we do if the expansion results in multiple names?
          // For, example if the line contains just the variable expansion
          // and it is of type strings. Adding all the elements space-
          // separated seems like the natural thing to do.
          //
          string s;
          for (auto b (ns.begin ()), i (b); i != ns.end (); ++i)
          {
            string n;

            try
            {
              n = value_traits<string>::convert (move (*i), nullptr);
            }
            catch (const invalid_argument&)
            {
              fail (l) << "invalid string value '" << *i << "'";
            }

            if (i == b)
              s = move (n);
            else
            {
              s += ' ';
              s += n;
            }
          }

          if (!re)
          {
            // Add newline after previous line.
            //
            if (rs)
            {
              *rs += '\n';
              *rs += s;
            }
            else
              rs = move (s);
          }
          else
          {
            // Due to expansion we can end up with multiple lines. If empty
            // then will add a blank textual literal.
            //
            for (size_t p (0); p != string::npos; )
            {
              string ln;
              size_t np (s.find ('\n', p));

              if (np != string::npos)
              {
                ln = string (s, p, np - p);
                p = np + 1;
              }
              else
              {
                ln = string (s, p);
                p = np;
              }

              if (ln[0] != re) // Line doesn't start with regex introducer.
              {
                // This is a line-char literal (covers blank lines as well).
                //
                // Append textual literal.
                //
                rre.lines.emplace_back (l.line, l.column, move (ln), false);
              }
              else // Line starts with the regex introducer.
              {
                // This is a char-regex, or a sequence of line-regex syntax
                // characters or both (in this specific order). So we will
                // add regex (with optional special characters) or special
                // literal.
                //
                size_t p (ln.find (re, 1));
                if (p == string::npos)
                {
                  // No regex, just a sequence of syntax characters.
                  //
                  string spec (ln, 1);
                  if (spec.empty ())
                    fail (l) << "no syntax line characters";

                  // Append special literal.
                  //
                  rre.lines.emplace_back (
                    l.line, l.column, move (spec), true);
                }
                else
                {
                  // Regex (probably with syntax characters).
                  //
                  regex_parts re;

                  // Empty regex is a special case repesenting a blank line.
                  //
                  if (p == 1)
                    // Position to optional specal characters of an empty
                    // regex.
                    //
                    ++p;
                  else
                    // Can't fail as all the pre-conditions verified
                    // (non-empty with both introducers in place), so no
                    // description required.
                    //
                    re = parse_regex (ln, l, "", &p);

                  // Append regex with optional special characters.
                  //
                  rre.lines.emplace_back (l.line, l.column,
                                          move (re.value), move (re.flags),
                                          string (ln, p));
                }
              }
            }
          }
        }

        // We should expand the whole line at once so this would normally be
        // a newline but can also be an end-of-stream.
        //
        if (tt == type::newline)
          next (t, tt);
        else
          assert (tt == type::eos);
      }

      if (tt == type::eos)
        fail (t) << "missing here-document end marker '" << em << "'";

      if (pre_parse_)
      {
        // Strip the indentation prefix if there is one.
        //
        assert (replay_ == replay::save);

        if (!sp.empty ())
        {
          size_t sn (sp.size ());

          for (; ri != replay_data_.size (); ++ri)
          {
            token& rt (replay_data_[ri].token);

            if (rt.type == type::newline) // Blank
              continue;

            if (rt.type != type::word || rt.value.compare (0, sn, sp) != 0)
              fail (rt) << "unindented here-document line";

            // If the word is equal to the strip prefix then we have to drop
            // the token. Note that simply making it an empty word won't
            // have the same semantics. For instance, it would trigger
            // concatenated expansion.
            //
            if (rt.value.size () == sn)
              replay_data_.erase (replay_data_.begin () + ri);
            else
            {
              rt.value.erase (0, sn);
              rt.column += sn;
              ++ri;
            }

            // Skip until next newline.
            //
            for (; replay_data_[ri].token.type != type::newline; ++ri) ;
          }
        }
      }
      else
      {
        // Add final newline unless suppressed.
        //
        if (mod.find (':') == string::npos)
        {
          if (re)
            // Note that the position is synthetic, but that's ok as we don't
            // expect any diagnostics to refer this line.
            //
            rre.lines.emplace_back (l.line, l.column, string (), false);
          else if (rs)
            *rs += '\n';
          else
            rs = "\n";
        }

        // Finalize regex lines.
        //
        if (re)
        {
          // Empty regex matches nothing, so not of much use.
          //
          if (rre.lines.empty ())
            fail (l) << "empty here-document regex";

          rre.intro  = re;
        }
      }

      return re
        ? parsed_doc (move (rre), l.line, l.column)
        : parsed_doc (rs ? move (*rs) : string (), l.line, l.column);
    }

    size_t parser::
    quoted () const
    {
      size_t r (0);

      if (replay_ != replay::play)
        r = lexer_->quoted ();
      else
      {
        // Examine tokens we have replayed since last reset.
        //
        size_t ri (!peeked_ ? replay_i_ : replay_i_ - 1);
        for (size_t i (replay_quoted_); i != ri; ++i)
          if (replay_data_[i].token.qtype != quote_type::unquoted)
            ++r;
      }

      return r;
    }

    void parser::
    reset_quoted (token& cur)
    {
      if (replay_ != replay::play)
        lexer_->reset_quoted (cur.qtype != quote_type::unquoted ? 1 : 0);
      else
      {
        replay_quoted_ = replay_i_ - (!peeked_ ? 1 : 2);

        // Must be the same token.
        //
        assert (replay_data_[replay_quoted_].token.qtype == cur.qtype);
      }
    }

    void parser::
    set_lexer (lexer* l)
    {
      lexer_ = l;
      build2::parser::lexer_ = l;
    }

    static redirect_aliases no_redirect_aliases;

    void parser::
    apply_value_attributes (const variable* var,
                            value& lhs,
                            value&& rhs,
                            const string& attributes,
                            token_type kind,
                            const path_name& name)
    {
      path_ = &name;

      istringstream is (attributes);

      // Note that the redirect alias information is not used in the
      // attributes lexer mode.
      //
      lexer l (is, name, lexer_mode::attributes, no_redirect_aliases);

      set_lexer (&l);

      token t;
      type tt;

      next_with_attributes (t, tt); // Enable `[` recognition.

      if (tt != type::lsbrace && tt != type::eos)
        fail (t) << "expected '[' instead of " << t;

      attributes_push (t, tt, true);

      if (tt != type::eos)
        fail (t) << "trailing junk after ']'";

      build2::parser::apply_value_attributes (var, lhs, move (rhs), kind);
    }

    line_type parser::
    pre_parse_line_start (token& t, token_type& tt, lexer_mode stm)
    {
      replay_save (); // Start saving tokens from the current one.
      next (t, tt);

      // Decide whether this is a variable assignment or a command.
      //
      // It is an assignment if the first token is an unquoted name and
      // the next token is an assign/append/prepend operator. Assignment
      // to a computed variable name must use the set builtin.
      //
      // Note also that special commands take precedence over variable
      // assignments.
      //
      line_type r (line_type::cmd); // Default.

      if (tt == type::word && t.qtype == quote_type::unquoted)
      {
        const string& n (t.value);

        if      (n == "if")    r = line_type::cmd_if;
        else if (n == "if!")   r = line_type::cmd_ifn;
        else if (n == "elif")  r = line_type::cmd_elif;
        else if (n == "elif!") r = line_type::cmd_elifn;
        else if (n == "else")  r = line_type::cmd_else;
        else if (n == "while") r = line_type::cmd_while;
        else if (n == "for")   r = line_type::cmd_for_stream;
        else if (n == "end")   r = line_type::cmd_end;
        else
        {
          // Switch the recognition of leading variable assignments for
          // the next token. This is safe to do because we know we
          // cannot be in the quoted mode (since the current token is
          // not quoted).
          //
          type p (peek (stm));

          if (p == type::assign  || p == type::prepend || p == type::append)
          {
            r = line_type::var;

            // Note that the missing command program is detected later, by
            // parse_command_expr().
            //
            if (n.empty ())
              fail (t) << "missing variable name";
          }
        }
      }

      return r;
    }

    bool parser::
    exec_lines (lines::const_iterator i, lines::const_iterator e,
                const function<exec_set_function>& exec_set,
                const function<exec_cmd_function>& exec_cmd,
                const function<exec_cond_function>& exec_cond,
                const function<exec_for_function>& exec_for,
                const iteration_index* ii, size_t& li,
                variable_pool* var_pool)
    {
      try
      {
        token t;
        type tt;
        for (; i != e; ++i)
        {
          const line& ln (*i);
          line_type lt (ln.type);

          assert (path_ == nullptr);

          // Copy the tokens and start playing.
          //
          replay_data (replay_tokens (ln.tokens));

          // We don't really need to change the mode since we already know
          // the line type.
          //
          next (t, tt);
          const location ll (get_location (t));

          // If end is true, then find the flow control construct's end ('end'
          // line). Otherwise, find the flow control construct's block end
          // ('end', 'else', etc). If skip is true then increment the command
          // line index.
          //
          auto fcend = [e, &li] (lines::const_iterator j,
                                 bool end,
                                 bool skip) -> lines::const_iterator
          {
            // We need to be aware of nested flow control constructs.
            //
            size_t n (0);

            for (++j; j != e; ++j)
            {
              line_type lt (j->type);

              if (lt == line_type::cmd_if         ||
                  lt == line_type::cmd_ifn        ||
                  lt == line_type::cmd_while      ||
                  lt == line_type::cmd_for_stream ||
                  lt == line_type::cmd_for_args)
                ++n;

              // If we are nested then we just wait until we get back
              // to the surface.
              //
              if (n == 0)
              {
                switch (lt)
                {
                case line_type::cmd_elif:
                case line_type::cmd_elifn:
                case line_type::cmd_else:
                  if (end) break;
                  // Fall through.
                case line_type::cmd_end:  return j;
                default: break;
                }
              }

              if (lt == line_type::cmd_end)
                --n;

              if (skip)
              {
                // Note that we don't count else, end, and 'for x: ...' as
                // commands.
                //
                switch (lt)
                {
                case line_type::cmd:
                case line_type::cmd_if:
                case line_type::cmd_ifn:
                case line_type::cmd_elif:
                case line_type::cmd_elifn:
                case line_type::cmd_for_stream:
                case line_type::cmd_while:      ++li; break;
                default:                              break;
                }
              }
            }

            assert (false); // Missing end.
            return e;
          };

          switch (lt)
          {
          case line_type::var:
            {
              // Enter the variable into the pool if this is not done during
              // the script parsing. Note that in this case the pool is
              // expected to be provided.
              //
              const variable* var (ln.var);

              if (var == nullptr)
              {
                assert (var_pool != nullptr);

                var = &var_pool->insert (t.value);
              }

              exec_set (*var, t, tt, ll);

              replay_stop ();
              break;
            }
          case line_type::cmd:
            {
              bool single (false);

              if (li == 1)
              {
                lines::const_iterator j (i);
                for (++j; j != e && j->type == line_type::var; ++j) ;

                if (j == e) // We have no another command.
                  single = true;
              }

              exec_cmd (t, tt,
                        ii, li++, single,
                        nullptr /* command_function */,
                        ll);

              replay_stop ();
              break;
            }
          case line_type::cmd_if:
          case line_type::cmd_ifn:
          case line_type::cmd_elif:
          case line_type::cmd_elifn:
          case line_type::cmd_else:
            {
              next (t, tt); // Skip to start of command.

              bool take;
              if (lt != line_type::cmd_else)
              {
                take = exec_cond (t, tt, ii, li++, ll);

                if (lt == line_type::cmd_ifn || lt == line_type::cmd_elifn)
                  take = !take;
              }
              else
              {
                assert (tt == type::newline);
                take = true;
              }

              replay_stop ();

              // If we are taking this branch then we need to parse all the
              // lines until the next if-else line and then skip all the lines
              // until the end (unless we are already at the end).
              //
              // Otherwise, we need to skip all the lines until the next
              // if-else line and then continue parsing.
              //
              if (take)
              {
                // Find block end.
                //
                lines::const_iterator j (fcend (i, false, false));

                if (!exec_lines (i + 1, j,
                                 exec_set, exec_cmd, exec_cond, exec_for,
                                 ii, li,
                                 var_pool))
                  return false;

                // Find construct end.
                //
                i = j->type == line_type::cmd_end ? j : fcend (j, true, true);
              }
              else
              {
                // Find block end.
                //
                i = fcend (i, false, true);

                if (i->type != line_type::cmd_end)
                  --i; // Continue with this line (e.g., elif or else).
              }

              break;
            }
          case line_type::cmd_while:
            {
              // The while-loop construct end. Set on the first iteration.
              //
              lines::const_iterator we (e);

              size_t wli (li);

              for (iteration_index wi {1, ii};; wi.index++)
              {
                next (t, tt); // Skip to start of command.

                bool exec (exec_cond (t, tt, &wi, li++, ll));

                replay_stop ();

                // If the condition evaluates to true, then we need to parse
                // all the lines until the end line, prepare for the condition
                // reevaluation, and re-iterate.
                //
                // Otherwise, we need to skip all the lines until the end
                // line, bail out from the loop, and continue parsing.
                //
                if (exec)
                {
                  // Find the construct end, if it is not found yet.
                  //
                  if (we == e)
                    we = fcend (i, true, false);

                  if (!exec_lines (i + 1, we,
                                   exec_set, exec_cmd, exec_cond, exec_for,
                                   &wi, li,
                                   var_pool))
                    return false;

                  // Prepare for the condition reevaluation.
                  //
                  replay_data (replay_tokens (ln.tokens));
                  next (t, tt);
                  li = wli;
                }
                else
                {
                  // Position to the construct end, always incrementing the
                  // line index (skip is true).
                  //
                  i = fcend (i, true, true);
                  break; // Bail out from the while-loop.
                }
              }

              break;
            }
          case line_type::cmd_for_stream:
            {
              // The for-loop construct end. Set on the first iteration.
              //
              lines::const_iterator fe (e);

              // Let's "wrap up" all the required data into the single object
              // to rely on the "small function object" optimization.
              //
              struct
              {
                lines::const_iterator i;
                lines::const_iterator e;
                const function<exec_set_function>& exec_set;
                const function<exec_cmd_function>& exec_cmd;
                const function<exec_cond_function>& exec_cond;
                const function<exec_for_function>& exec_for;
                const iteration_index* ii;
                size_t& li;
                variable_pool* var_pool;
                decltype (fcend)& fce;
                lines::const_iterator& fe;
              } d {i, e,
                    exec_set, exec_cmd, exec_cond, exec_for,
                    ii, li,
                    var_pool,
                    fcend,
                    fe};

              function<command_function> cf (
                [&d, this]
                (environment& env,
                 const strings& args,
                 auto_fd in,
                 bool pipe,
                 const optional<deadline>& dl,
                 const command& deadline_cmd,
                 const location& ll)
                {
                  namespace cli = build2::build::cli;

                  try
                  {
                    // Parse arguments.
                    //
                    cli::vector_scanner scan (args);
                    for_options ops (scan);

                    // Note: diagnostics consistent with the set builtin.
                    //
                    if (ops.whitespace () && ops.newline ())
                      fail (ll) << "for: both -n|--newline and "
                                << "-w|--whitespace specified";

                    if (!scan.more ())
                      fail (ll) << "for: missing variable name";

                    string vname (scan.next ());
                    if (vname.empty ())
                      fail (ll) << "for: empty variable name";

                    // Detect patterns analogous to parse_variable_name() (so
                    // we diagnose `for x[string]`).
                    //
                    if (vname.find_first_of ("[*?") != string::npos)
                      fail (ll) << "for: expected variable name instead of "
                                << vname;

                    // Let's also diagnose the `... | for x:...` misuse which
                    // can probably be quite common.
                    //
                    if (vname.find (':') != string::npos)
                      fail (ll) << "for: ':' after variable name";

                    string attrs;
                    if (scan.more ())
                    {
                      attrs = scan.next ();

                      if (attrs.empty ())
                        fail (ll) << "for: empty variable attributes";

                      if (scan.more ())
                        fail (ll) << "for: unexpected argument '"
                                  << scan.next () << "'";
                    }

                    stream_reader sr (
                      move (in), pipe,
                      !ops.newline (), ops.newline (), ops.exact (),
                      dl, deadline_cmd,
                      ll);

                    // Since the command pipe is parsed, we can stop
                    // replaying. Note that we should do this before calling
                    // exec_lines() for the loop body. Also note that we
                    // should increment the line index before that.
                    //
                    replay_stop ();

                    size_t fli (++d.li);
                    iteration_index fi {1, d.ii};

                    for (optional<string> s; (s = sr.next ()); )
                    {
                      d.li = fli;

                      // Don't move from the variable name since it is used on
                      // each iteration.
                      //
                      env.set_variable (vname,
                                        names {name (move (*s))},
                                        attrs,
                                        ll);

                      // Find the construct end, if it is not found yet.
                      //
                      if (d.fe == d.e)
                        d.fe = d.fce (d.i, true, false);

                      if (!exec_lines (d.i + 1, d.fe,
                                       d.exec_set,
                                       d.exec_cmd,
                                       d.exec_cond,
                                       d.exec_for,
                                       &fi, d.li,
                                       d.var_pool))
                      {
                        throw exit (true);
                      }

                      fi.index++;
                    }
                  }
                  catch (const cli::exception& e)
                  {
                    fail (ll) << "for: " << e;
                  }
                });

              exec_cmd (t, tt, ii, li, false /* single */, cf, ll);

              // Position to construct end.
              //
              i = (fe != e ? fe : fcend (i, true, true));

              break;
            }
          case line_type::cmd_for_args:
            {
              // Parse the variable name.
              //
              next (t, tt);

              assert (tt == type::word && t.qtype == quote_type::unquoted);

              string vn (move (t.value));

              // Enter the variable into the pool if this is not done during
              // the script parsing (see the var line type handling for
              // details).
              //
              const variable* var (ln.var);

              if (var == nullptr)
              {
                assert (var_pool != nullptr);

                var = &var_pool->insert (move (vn));
              }

              // Parse the potential element attributes and skip the colon.
              //
              next_with_attributes (t, tt);
              attributes_push (t, tt);

              assert (tt == type::colon);

              // Save element attributes so that we can inject them on each
              // iteration.
              //
              attributes val_attrs (attributes_pop ());

              // Parse the value with the potential attributes.
              //
              // Note that we don't really need to change the mode since we
              // are replaying the tokens.
              //
              value val;
              apply_value_attributes (nullptr /* variable */,
                                      val,
                                      parse_variable_line (t, tt),
                                      type::assign);

              replay_stop ();

              // If the value is not NULL then iterate over its elements,
              // assigning them to the for-loop variable, and parsing all the
              // construct lines afterwards. Then position to the end line of
              // the construct and continue parsing.

              // The for-loop construct end. Set on the first iteration.
              //
              lines::const_iterator fe (e);

              if (val)
              {
                // If this value is a vector, then save its element type so
                // that we can typify each element below.
                //
                const value_type* etype (nullptr);

                if (val.type != nullptr)
                {
                  etype = val.type->element_type;
                  untypify (val);
                }

                size_t fli (li);
                iteration_index fi {1, ii};

                // @@ Handle pairs.
                //
                //    Do we need to always lex the variable values (for-loop
                //    and var lines) pair-character aware?
                //
                //    Can there be any harm if a value with pairs is
                //    substituted into the command line?
                //
                for (name& n: val.as<names> ())
                {
                  li = fli;

                  value v (names {move (n)}); // Untyped.

                  if (etype != nullptr)
                    typify (v, *etype, var);

                  exec_for (*var, move (v), val_attrs, ll);

                  // Find the construct end, if it is not found yet.
                  //
                  if (fe == e)
                    fe = fcend (i, true, false);

                  if (!exec_lines (i + 1, fe,
                                   exec_set, exec_cmd, exec_cond, exec_for,
                                   &fi, li,
                                   var_pool))
                    return false;

                  fi.index++;
                }
              }

              // Position to construct end.
              //
              i = (fe != e ? fe : fcend (i, true, true));

              break;
            }
          case line_type::cmd_end:
            {
              assert (false);
              break;
            }
          }
        }

        return true;
      }
      catch (const exit& e)
      {
        // Bail out if the script is exited with the failure status. Otherwise
        // exit the lines execution normally.
        //
        if (!e.status)
          throw failed ();

        replay_stop ();
        return false;
      }
    }

    // parser::parsed_doc
    //
    parser::parsed_doc::
    parsed_doc (string s, uint64_t l, uint64_t c)
        : str (move (s)), re (false), end_line (l), end_column (c)
    {
    }

    parser::parsed_doc::
    parsed_doc (regex_lines&& r, uint64_t l, uint64_t c)
        : regex (move (r)), re (true), end_line (l), end_column (c)
    {
    }

    parser::parsed_doc::
    parsed_doc (parsed_doc&& d)
        : re (d.re), end_line (d.end_line), end_column (d.end_column)
    {
      if (re)
        new (&regex) regex_lines (move (d.regex));
      else
        new (&str) string (move (d.str));
    }

    parser::parsed_doc::
    ~parsed_doc ()
    {
      if (re)
        regex.~regex_lines ();
      else
        str.~string ();
    }
  }
}