aboutsummaryrefslogtreecommitdiff
path: root/libbpkg/manifest.cxx
blob: ef91381d4463efc1512f8beb55ffc0ebd3bd89ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
// file      : libbpkg/manifest.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbpkg/manifest.hxx>

#include <string>
#include <ostream>
#include <sstream>
#include <cassert>
#include <cstring>   // strncmp(), strcmp()
#include <utility>   // move()
#include <cstdint>   // uint*_t, UINT16_MAX
#include <algorithm> // find(), find_if_not(), find_first_of(), replace()
#include <stdexcept> // invalid_argument

#include <libbutl/url.hxx>
#include <libbutl/path.hxx>
#include <libbutl/base64.hxx>
#include <libbutl/utility.hxx>             // icasecmp(), lcase(), alnum(),
                                           // digit(), xdigit(), next_word()
#include <libbutl/filesystem.hxx>          // dir_exist()
#include <libbutl/small-vector.hxx>
#include <libbutl/manifest-parser.hxx>
#include <libbutl/manifest-serializer.hxx>
#include <libbutl/standard-version.hxx>

using namespace std;
using namespace butl;

namespace bpkg
{
  using parser = manifest_parser;
  using parsing = manifest_parsing;
  using serializer = manifest_serializer;
  using serialization = manifest_serialization;
  using name_value = manifest_name_value;

  using butl::optional;
  using butl::nullopt;

  // Utility functions
  //
  static const strings priority_names ({"low", "medium", "high", "security"});
  static const strings repository_role_names (
    {"base", "prerequisite", "complement"});

  static const string spaces (" \t");

  inline static bool
  space (char c) noexcept
  {
    return c == ' ' || c == '\t';
  }

  inline static bool
  valid_sha256 (const string& s) noexcept
  {
    if (s.size () != 64)
      return false;

    for (char c: s)
    {
      if ((c < 'a' || c > 'f' ) && !digit (c))
        return false;
    }

    return true;
  }

  inline static bool
  valid_fingerprint (const string& s) noexcept
  {
    size_t n (s.size ());
    if (n != 32 * 3 - 1)
      return false;

    for (size_t i (0); i != n; ++i)
    {
      char c (s[i]);
      if ((i + 1) % 3 == 0) // Must be the colon,
      {
        if (c != ':')
          return false;
      }
      else if (!xdigit (c)) // Must be a hex digit.
        return false;
    }

    return true;
  }

  template <typename T>
  static string
  concatenate (const T& s, const char* delim = ", ")
  {
    ostringstream o;
    for (auto b (s.begin ()), i (b), e (s.end ()); i != e; ++i)
    {
      if (i != b)
        o << delim;

      o << *i;
    }

    return o.str ();
  }

  // list_parser
  //
  class list_parser
  {
  public:
    using iterator = string::const_iterator;

  public:
    list_parser (iterator b, iterator e, char d = ',')
        : pos_ (b), end_ (e), delim_ (d) {}

    string
    next ();

  private:
    iterator pos_;
    iterator end_;
    char delim_;
  };

  string list_parser::
  next ()
  {
    string r;

    // Continue until get non empty list item.
    //
    while (pos_ != end_ && r.empty ())
    {
      // Skip spaces.
      //
      for (; pos_ != end_ && space (*pos_); ++pos_);

      iterator i (pos_);
      iterator e (pos_); // End of list item.

      for (char c; i != end_ && (c = *i) != delim_; ++i)
      {
        if (!space (c))
          e = i + 1;
      }

      if (e - pos_ > 0)
        r.assign (pos_, e);

      pos_ = i == end_ ? i : i + 1;
    }

    return r;
  }

  // version
  //
  version::
  version (uint16_t e,
           std::string u,
           optional<std::string> l,
           optional<uint16_t> r,
           uint32_t i)
      : epoch (e),
        upstream (move (u)),
        release (move (l)),
        revision (r),
        iteration (i),
        canonical_upstream (
          data_type (upstream.c_str (),
                     data_type::parse::upstream,
                     false /* fold_zero_revision */).
            canonical_upstream),
        canonical_release (
          data_type (release ? release->c_str () : nullptr,
                     data_type::parse::release,
                     false /* fold_zero_revision */).
            canonical_release)
  {
    // Check members constrains.
    //
    if (upstream.empty ()) // Constructing empty version.
    {
      if (epoch != 0)
        throw invalid_argument ("epoch for empty version");

      if (!release || !release->empty ())
        throw invalid_argument ("not-empty release for empty version");

      if (revision)
        throw invalid_argument ("revision for empty version");

      if (iteration != 0)
        throw invalid_argument ("iteration for empty version");
    }
    // Empty release signifies the earliest possible release. Revision and/or
    // iteration are meaningless in such a context.
    //
    else if (release && release->empty () && (revision || iteration != 0))
      throw invalid_argument ("revision for earliest possible release");
  }

  // Builder of the upstream or release version part canonical representation.
  //
  struct canonical_part: string
  {
    string
    final () const {return substr (0, len_);}

    void
    add (const char* begin, const char* end, bool numeric)
    {
      if (!empty ())
        append (1, '.');

      bool zo (false); // Digit zero-only component.
      if (numeric)
      {
        size_t n (end - begin);

        if (n > 16)
          throw invalid_argument ("16 digits maximum allowed in a component");

        append (16 - n, '0'); // Add padding zeros.
        append (begin, n);

        // See if all zero.
        //
        for (; begin != end && *begin == '0'; ++begin) ;
        zo = (begin == end);
      }
      else
        append (lcase (begin, end - begin));

      if (!zo)
        len_ = size ();
    }

  private:
    size_t len_ = 0; // Length without the trailing digit-only zero components.
  };

  // Return zero for versions having the '0[+<revision>]' form (stubs) and one
  // otherwise. Used for both version and version::data_type types.
  //
  template <typename T>
  inline static uint16_t
  default_epoch (const T& v)
  {
    return v.canonical_upstream.empty () && !v.release ? 0 : 1;
  }

  version::data_type::
  data_type (const char* v, parse pr, bool fold_zero_rev)
  {
    if (fold_zero_rev)
      assert (pr == parse::full);

    // Otherwise compiler gets confused with string() member.
    //
    using std::string;

    if (pr == parse::release && v == nullptr)
    {
      // Special case: final version release part.
      //
      canonical_release = "~";
      return;
    }

    assert (v != nullptr);

    optional<uint16_t> ep;

    auto bad_arg = [](const string& d) {throw invalid_argument (d);};

    auto uint16 = [&bad_arg](const string& s, const char* what) -> uint16_t
    {
      try
      {
        uint64_t v (stoull (s));

        if (v <= UINT16_MAX) // From <cstdint>.
          return static_cast<uint16_t> (v);
      }
      catch (const std::exception&)
      {
        // Fall through.
      }

      bad_arg (string (what) + " should be 2-byte unsigned integer");

      assert (false); // Can't be here.
      return 0;
    };

    enum class mode {epoch, upstream, release, revision};
    mode m (pr == parse::full
            ? (v[0] == '+'
               ? mode::epoch
               : mode::upstream)
            : (pr == parse::upstream
               ? mode::upstream
               : mode::release));

    canonical_part canon_upstream;
    canonical_part canon_release;

    canonical_part* canon_part (
      pr == parse::release ? &canon_release : &canon_upstream);

    const char* cb (m != mode::epoch ? v : v + 1); // Begin of a component.
    const char* ub (cb);                           // Begin of upstream part.
    const char* ue (cb);                           // End of upstream part.
    const char* rb (cb);                           // Begin of release part.
    const char* re (cb);                           // End of release part.
    const char* lnn (cb - 1);                      // Last non numeric char.

    const char* p (cb);
    for (char c; (c = *p) != '\0'; ++p)
    {
      switch (c)
      {
      case '+':
      case '-':
      case '.':
        {
          // Process the epoch part or the upstream/release part component.
          //

          // Characters '+', '-' are only valid for the full version parsing.
          //
          if (c != '.' && pr != parse::full)
            bad_arg (string ("unexpected '") + c + "' character");

          // Check if the component ending is valid for the current parsing
          // state.
          //
          if (m == mode::revision || (c == '-' && m == mode::release) ||
              (c != '-' && m == mode::epoch) || p == cb)
            bad_arg (string ("unexpected '") + c + "' character position");

          // Depending on the mode, parse epoch or append the component to the
          // current canonical part.
          //
          if (m == mode::epoch)
          {
            if (lnn >= cb) // Contains non-digits.
              bad_arg ("epoch should be 2-byte unsigned integer");

            ep = uint16 (string (cb, p), "epoch");
          }
          else
            canon_part->add (cb, p, lnn < cb);

          // Update the parsing state.
          //
          // Advance begin of a component.
          //
          cb = p + 1;

          // Advance end of the upstream/release parts.
          //
          if (m == mode::upstream)
            ue = p;
          else if (m == mode::release)
            re = p;
          else
            assert (m == mode::epoch);

          // Switch the mode if the component is terminated with '+' or '-'.
          //
          if (c == '+')
            m = mode::revision;
          else if (c == '-')
          {
            if (m == mode::epoch)
            {
              m = mode::upstream;
              ub = cb;
              ue = cb;
            }
            else
            {
              m = mode::release;
              rb = cb;
              re = cb;

              canon_part = &canon_release;
            }
          }

          break;
        }
      default:
        {
          if (!alnum (c))
            bad_arg ("alpha-numeric characters expected in a component");
        }
      }

      if (!digit (c))
        lnn = p;
    }

    assert (p >= cb); // 'p' denotes the end of the last component.

    // The epoch must always be followed by the upstream.
    //
    // An empty component is valid for the release part, and for the
    // upstream part when constructing empty or max limit version.
    //
    if (m == mode::epoch ||
        (p == cb && m != mode::release && pr != parse::upstream))
      bad_arg ("unexpected end");

    // Parse the last component.
    //
    if (m == mode::revision)
    {
      if (lnn >= cb) // Contains non-digits.
        bad_arg ("revision should be 2-byte unsigned integer");

      std::uint16_t rev (uint16 (cb, "revision"));

      if (rev != 0 || !fold_zero_rev)
        revision = rev;
    }
    else if (cb != p)
    {
      canon_part->add (cb, p, lnn < cb);

      if (m == mode::upstream)
        ue = p;
      else if (m == mode::release)
        re = p;
    }

    // Upstream and release pointer ranges are valid at the end of the day.
    //
    assert (ub <= ue && rb <= re);

    if (pr != parse::release)
    {
      // Fill upstream original and canonical parts.
      //
      if (!canon_upstream.empty ())
      {
        assert (ub != ue); // Can't happen if through all previous checks.
        canonical_upstream = canon_upstream.final ();

        if (pr == parse::full)
          upstream.assign (ub, ue);
      }
    }

    if (pr != parse::upstream)
    {
      // Fill release original and canonical parts.
      //
      if (!canon_release.empty ())
      {
        assert (rb != re); // Can't happen if through all previous checks.
        canonical_release = canon_release.final ();

        if (pr == parse::full)
          release = string (rb, re);
      }
      else
      {
        if (m == mode::release)
        {
          // Empty release part signifies the earliest possible version
          // release. Make original, and keep canonical representations empty.
          //
          if (pr == parse::full)
            release = "";
        }
        else
        {
          // Absent release part signifies the final (max) version release.
          // Assign the special value to the canonical representation, keep
          // the original one nullopt.
          //
          canonical_release = "~";
        }
      }
    }

    if (pr == parse::full)
    {
      epoch = ep ? *ep : default_epoch (*this);

      if (epoch == 0                  &&
          canonical_upstream.empty () &&
          canonical_release.empty ())
      {
        assert (!revision); // Can't happen if through all previous checks.
        bad_arg ("empty version");
      }
    }
  }

  version& version::
  operator= (const version& v)
  {
    if (this != &v)
      *this = version (v); // Reduce to move-assignment.
    return *this;
  }

  version& version::
  operator= (version&& v)
  {
    if (this != &v)
    {
      this->~version ();
      new (this) version (move (v)); // Assume noexcept move-construction.
    }
    return *this;
  }

  string version::
  string (bool ignore_revision, bool ignore_iteration) const
  {
    using std::to_string; // Hidden by to_string (repository_type).

    if (empty ())
      throw logic_error ("empty version");

    std::string v (epoch != default_epoch (*this)
                   ? '+' + to_string (epoch) + '-' + upstream
                   : upstream);

    if (release)
    {
      v += '-';
      v += *release;
    }

    if (!ignore_revision)
    {
      if (revision)
      {
        v += '+';
        v += to_string (*revision);
      }

      if (!ignore_iteration && iteration != 0)
      {
        v += '#';
        v += to_string (iteration);
      }
    }

    return v;
  }

  // text_file
  //
  text_file::
  ~text_file ()
  {
    if (file)
      path.~path_type ();
    else
      text.~string ();
  }

  text_file::
  text_file (text_file&& f): file (f.file), comment (move (f.comment))
  {
    if (file)
      new (&path) path_type (move (f.path));
    else
      new (&text) string (move (f.text));
  }

  text_file::
  text_file (const text_file& f): file (f.file), comment (f.comment)
  {
    if (file)
      new (&path) path_type (f.path);
    else
      new (&text) string (f.text);
  }

  text_file& text_file::
  operator= (text_file&& f)
  {
    if (this != &f)
    {
      this->~text_file ();
      new (this) text_file (move (f)); // Assume noexcept move-construction.
    }
    return *this;
  }

  text_file& text_file::
  operator= (const text_file& f)
  {
    if (this != &f)
      *this = text_file (f); // Reduce to move-assignment.
    return *this;
  }

  // manifest_url
  //
  manifest_url::
  manifest_url (const std::string& u, std::string c)
      : url (u),
        comment (move (c))
  {
    if (rootless)
      throw invalid_argument ("rootless URL");

    if (icasecmp (scheme, "file") == 0)
      throw invalid_argument ("local URL");

    if (!authority || authority->empty ())
      throw invalid_argument ("no authority");
  }

  // version_constraint
  //
  version_constraint::
  version_constraint (const std::string& s)
  {
    using std::string;

    auto bail = [] (const string& d) {throw invalid_argument (d);};

    char c (s[0]);
    if (c == '(' || c == '[') // The version range.
    {
      bool min_open (c == '(');

      size_t p (s.find_first_not_of (spaces, 1));
      if (p == string::npos)
        bail ("no min version specified");

      size_t e (s.find_first_of (spaces, p));

      const char* no_max_version ("no max version specified");

      if (e == string::npos)
        bail (no_max_version);

      version min_version;
      string mnv (s, p, e - p);

      // Leave the min version empty if it refers to the dependent package
      // version.
      //
      if (mnv != "$")
      try
      {
        min_version = version (mnv, false /* fold_zero_revision */);
      }
      catch (const invalid_argument& e)
      {
        bail (string ("invalid min version: ") + e.what ());
      }

      p = s.find_first_not_of (spaces, e);
      if (p == string::npos)
        bail (no_max_version);

      e = s.find_first_of (" \t])", p);

      const char* invalid_range ("invalid version range");

      if (e == string::npos)
        bail (invalid_range);

      version max_version;
      string mxv (s, p, e - p);

      // Leave the max version empty if it refers to the dependent package
      // version.
      //
      if (mxv != "$")
      try
      {
        max_version = version (mxv, false /* fold_zero_revision */);
      }
      catch (const invalid_argument& e)
      {
        bail (string ("invalid max version: ") + e.what ());
      }

      e = s.find_first_of ("])", e); // Might be a space.
      if (e == string::npos)
        bail (invalid_range);

      if (e + 1 != s.size ())
        bail ("unexpected text after version range");

      // Can throw invalid_argument that we don't need to intercept.
      //
      *this = version_constraint (move (min_version), min_open,
                                  move (max_version), s[e] == ')');
    }
    else if (c == '~' || c == '^') // The shortcut operator.
    {
      // If the shortcut operator refers to the dependent package version (the
      // '$' character), then create an incomplete constraint. Otherwise,
      // assume the version is standard and parse the operator representation
      // as the standard version constraint.
      //
      size_t p (s.find_first_not_of (spaces, 1));

      if (p != string::npos && s[p] == '$' && p + 1 == s.size ())
      {
        *this = version_constraint (version (), c == '~',
                                    version (), c == '^');
      }
      else
      {
        // To be used in the shortcut operator the package version must be
        // standard.
        //
        // Can throw invalid_argument that we don't need to intercept.
        //
        standard_version_constraint vc (s);

        try
        {
          assert (vc.min_version && vc.max_version);

          // Note that standard_version::string() folds the zero revision.
          // However, that's ok since the shortcut operator ~X.Y.Z+0
          // translates into [X.Y.Z+0 X.Y+1.0-) which covers the same versions
          // set as [X.Y.Z X.Y+1.0-).
          //
          *this = version_constraint (version (vc.min_version->string ()),
                                      vc.min_open,
                                      version (vc.max_version->string ()),
                                      vc.max_open);
        }
        catch (const invalid_argument&)
        {
          // Any standard version is a valid package version, so the
          // conversion should never fail.
          //
          assert (false);
        }
      }
    }
    else // The version comparison notation.
    {
      enum comparison {eq, lt, gt, le, ge};
      comparison operation (eq); // Uninitialized warning.
      size_t p (2);

      if (s.compare (0, 2, "==") == 0)
        operation = eq;
      else if (s.compare (0, 2, ">=") == 0)
        operation = ge;
      else if (s.compare (0, 2, "<=") == 0)
        operation = le;
      else if (c == '>')
      {
        operation = gt;
        p = 1;
      }
      else if (c == '<')
      {
        operation = lt;
        p = 1;
      }
      else
        bail ("invalid version comparison");

      p = s.find_first_not_of (spaces, p);

      if (p == string::npos)
        bail ("no version specified");

      try
      {
        version v;
        string vs (s, p);

        // Leave the version empty if it refers to the dependent package
        // version.
        //
        if (vs != "$")
          v = version (vs, false /* fold_zero_revision */);

        switch (operation)
        {
        case comparison::eq:
          *this = version_constraint (v);
          break;
        case comparison::lt:
          *this = version_constraint (nullopt, true, move (v), true);
          break;
        case comparison::le:
          *this = version_constraint (nullopt, true, move (v), false);
          break;
        case comparison::gt:
          *this = version_constraint (move (v), true, nullopt, true);
          break;
        case comparison::ge:
          *this = version_constraint (move (v), false, nullopt, true);
          break;
        }
      }
      catch (const invalid_argument& e)
      {
        bail (string ("invalid version: ") + e.what ());
      }
    }
  }

  version_constraint::
  version_constraint (optional<version> mnv, bool mno,
                      optional<version> mxv, bool mxo)
      : min_version (move (mnv)),
        max_version (move (mxv)),
        min_open (mno),
        max_open (mxo)
  {
    assert (
      // Min and max versions can't both be absent.
      //
      (min_version || max_version) &&

      // Absent version endpoint (infinity) should be open.
      //
      (min_version || min_open) && (max_version || max_open));

    if (min_version && max_version)
    {
      bool mxe (max_version->empty ());

      // If endpoint versions do not refer to the dependent package version
      // then the min version must (naturally) be lower than or equal to the
      // max version.
      //
      if (*min_version > *max_version && !mxe)
      {
        // Handle the (X+Y X] and [X+Y X] corner cases (any revision of
        // version X greater (or equal) than X+Y). Note that technically
        // X+Y > X (see version::compare() for details).
        //
        // Also note that we reasonably fail for (X+Y X) and [X+Y X).
        //
        if (!(!max_open              &&
              !max_version->revision &&
              max_version->compare (*min_version,
                                    true /* ignore_revision */) == 0))
          throw invalid_argument ("min version is greater than max version");
      }

      if (*min_version == *max_version)
      {
        // For non-empty versions, both endpoints must be closed, representing
        // the `== <version>` constraint. For empty versions no greater than
        // one endpoint can be open, representing the `== $`, `~$`, or `^$`
        // constraints.
        //
        if ((!mxe && (min_open || max_open)) || (mxe && min_open && max_open))
          throw invalid_argument ("equal version endpoints not closed");

        // If endpoint versions do not refer to the dependent package version
        // then they can't be earliest. Note: an empty version is earliest.
        //
        if (!mxe && max_version->release && max_version->release->empty ())
          throw invalid_argument ("equal version endpoints are earliest");
      }
    }
  }

  version_constraint version_constraint::
  effective (version v) const
  {
    using std::string;

    // The dependent package version can't be empty or earliest.
    //
    if (v.empty ())
      throw invalid_argument ("dependent version is empty");

    if (v.release && v.release->empty ())
      throw invalid_argument ("dependent version is earliest");

    // For the more detailed description of the following semantics refer to
    // the depends value documentation.

    // Strip the revision and iteration.
    //
    v = version (v.epoch,
                 move (v.upstream),
                 move (v.release),
                 nullopt /* revision */,
                 0 /* iteration */);

    // Calculate effective constraint for a shortcut operator.
    //
    if (min_version                &&
        min_version->empty ()      &&
        max_version == min_version &&
        (min_open || max_open))
    {
      assert (!min_open || !max_open); // Endpoints cannot be both open.

      string vs (v.string ());

      // Note that a stub dependent is not allowed for the shortcut operator.
      // However, we allow it here to fail later (in
      // standard_version_constraint()) with a more precise description.
      //
      optional<standard_version> sv (
        parse_standard_version (vs, standard_version::allow_stub));

      if (!sv)
        throw invalid_argument ("dependent version is not standard");

      standard_version_constraint vc (min_open ? "~$" : "^$", *sv);

      try
      {
        assert (vc.min_version && vc.max_version);

        return version_constraint (version (vc.min_version->string ()),
                                   vc.min_open,
                                   version (vc.max_version->string ()),
                                   vc.max_open);
      }
      catch (const invalid_argument&)
      {
        // There shouldn't be a reason for version_constraint() to throw.
        //
        assert (false);
      }
    }

    // Calculate effective constraint for a range.
    //
    return version_constraint (
      min_version && min_version->empty () ? v : min_version, min_open,
      max_version && max_version->empty () ? v : max_version, max_open);
  }

  std::string version_constraint::
  string () const
  {
    assert (!empty ());

    auto ver = [] (const version& v) {return v.empty () ? "$" : v.string ();};

    if (!min_version)
      return (max_open ? "< " : "<= ") + ver (*max_version);

    if (!max_version)
      return (min_open ? "> " : ">= ") + ver (*min_version);

    if (*min_version == *max_version)
    {
      const version& v (*min_version);

      if (!min_open && !max_open)
        return "== " + ver (v);

      assert (v.empty () && (!min_open || !max_open));
      return min_open ? "~$" : "^$";
    }

    // If the range can potentially be represented as a range shortcut
    // operator (^ or ~), having the [<standard-version> <standard-version>)
    // form, then produce the resulting string using the standard version
    // constraint code.
    //
    if (!min_open              &&
        max_open               &&
        !min_version->empty () &&
        !max_version->empty ())
    {
      if (optional<standard_version> mnv =
          parse_standard_version (min_version->string (),
                                  standard_version::allow_earliest))
      {
        if (optional<standard_version> mxv =
            parse_standard_version (max_version->string (),
                                    standard_version::allow_earliest))
        try
        {
          return standard_version_constraint (
            move (*mnv), min_open, move (*mxv), max_open).string ();
        }
        catch (const invalid_argument&)
        {
          // Invariants for both types of constraints are the same, so the
          // conversion should never fail.
          //
          assert (false);
        }
      }
    }

    // Represent as a range.
    //
    std::string r (min_open ? "(" : "[");
    r += ver (*min_version);
    r += ' ';
    r += ver (*max_version);
    r += max_open ? ')' : ']';
    return r;
  }

  // dependency
  //
  dependency::
  dependency (std::string d)
  {
    using std::string;
    using iterator = string::const_iterator;

    iterator b (d.begin ());
    iterator i (b);
    iterator ne (b); // End of name.
    iterator e (d.end ());

    // Find end of name (ne).
    //
    // Grep for '=<>([~^' in the bpkg source code and update, if changed.
    //
    const string cb ("=<>([~^");
    for (char c; i != e && cb.find (c = *i) == string::npos; ++i)
    {
      if (!space (c))
        ne = i + 1;
    }

    try
    {
      name = package_name (i == e ? move (d) : string (b, ne));
    }
    catch (const invalid_argument& e)
    {
      throw invalid_argument (string ("invalid package name: ") + e.what ());
    }

    if (i != e)
    try
    {
      constraint = version_constraint (string (i, e));
    }
    catch (const invalid_argument& e)
    {
      throw invalid_argument (string ("invalid package constraint: ") +
                              e.what ());
    }
  }

  std::string dependency::
  string () const
  {
    std::string r (name.string ());

    if (constraint)
    {
      r += ' ';
      r += constraint->string ();
    }

    return r;
  }

  // dependency_alternatives
  //
  ostream&
  operator<< (ostream& o, const dependency_alternatives& as)
  {
    if (as.conditional)
      o << '?';

    if (as.buildtime)
      o << '*';

    if (as.conditional || as.buildtime)
      o << ' ';

    bool f (true);
    for (const dependency& a: as)
      o << (f ? (f = false, "") : " | ") << a;

    if (!as.comment.empty ())
      o << "; " << as.comment;

    return o;
  }

  // requirement_alternatives
  //
  requirement_alternatives::
  requirement_alternatives (const std::string& v)
  {
    using std::string;

    // Allow specifying ?* in any order.
    //
    size_t n (v.size ());
    size_t cond ((n > 0 && v[0] == '?') || (n > 1 && v[1] == '?') ? 1 : 0);
    size_t btim ((n > 0 && v[0] == '*') || (n > 1 && v[1] == '*') ? 1 : 0);

    auto vc (parser::split_comment (v));

    conditional = (cond != 0);
    buildtime   = (btim != 0);
    comment     = move (vc.second);

    const string& vl (vc.first);

    string::const_iterator b (vl.begin ());
    string::const_iterator e (vl.end ());

    if (conditional || buildtime)
    {
      string::size_type p (vl.find_first_not_of (spaces, cond + btim));
      b = p == string::npos ? e : b + p;
    }

    list_parser lp (b, e, '|');
    for (string lv (lp.next ()); !lv.empty (); lv = lp.next ())
      push_back (lv);

    if (empty () && comment.empty ())
      throw invalid_argument ("empty package requirement specification");
  }

  std::string requirement_alternatives::
  string () const
  {
    return (conditional
            ? (buildtime ? "?* " : "? ")
            : (buildtime ? "* " : "")) +
           serializer::merge_comment (concatenate (*this, " | "), comment);
  }

  // build_class_term
  //
  build_class_term::
  ~build_class_term ()
  {
    if (simple)
      name.~string ();
    else
      expr.~vector<build_class_term> ();
  }

  build_class_term::
  build_class_term (build_class_term&& t)
      : operation (t.operation),
        inverted (t.inverted),
        simple (t.simple)
  {
    if (simple)
      new (&name) string (move (t.name));
    else
      new (&expr) vector<build_class_term> (move (t.expr));
  }

  build_class_term::
  build_class_term (const build_class_term& t)
      : operation (t.operation),
        inverted (t.inverted),
        simple (t.simple)
  {
    if (simple)
      new (&name) string (t.name);
    else
      new (&expr) vector<build_class_term> (t.expr);
  }

  build_class_term& build_class_term::
  operator= (build_class_term&& t)
  {
    if (this != &t)
    {
      this->~build_class_term ();

      // Assume noexcept move-construction.
      //
      new (this) build_class_term (move (t));
    }
    return *this;
  }

  build_class_term& build_class_term::
  operator= (const build_class_term& t)
  {
    if (this != &t)
      *this = build_class_term (t); // Reduce to move-assignment.
    return *this;
  }

  bool build_class_term::
  validate_name (const string& s)
  {
    if (s.empty ())
      throw invalid_argument ("empty class name");

    size_t i (0);
    char c (s[i++]);

    if (!(alnum (c) || c == '_'))
      throw invalid_argument (
        "class name '" + s + "' starts with '" + c + "'");

    for (; i != s.size (); ++i)
    {
      if (!(alnum (c = s[i]) || c == '+' || c == '-' || c == '_' || c == '.'))
        throw invalid_argument (
          "class name '" + s + "' contains '" + c + "'");
    }

    return s[0] == '_';
  }

  // build_class_expr
  //
  // Parse the string representation of a space-separated, potentially empty
  // build class expression.
  //
  // Calls itself recursively when a nested expression is encountered. In this
  // case the second parameter points to the position at which the nested
  // expression starts (right after the opening parenthesis). Updates the
  // position to refer the nested expression end (right after the closing
  // parenthesis).
  //
  static vector<build_class_term>
  parse_build_class_expr (const string& s, size_t* p = nullptr)
  {
    vector<build_class_term> r;

    bool root (p == nullptr);
    size_t e (0);

    if (root)
      p = &e;

    size_t n;
    for (size_t b (0); (n = next_word (s, b, *p)); )
    {
      string t (s, b, n);

      // Check for the nested expression end.
      //
      if (t == ")")
      {
        if (root)
          throw invalid_argument ("class term expected instead of ')'");

        break;
      }

      // Parse the term.
      //
      char op (t[0]); // Can be '\0'.

      if (op != '+')
      {
        if (op != '-' && op != '&')
          throw invalid_argument (
            "class term '" + t + "' must start with '+', '-', or '&'");

        // Only the root expression may start with a term having the '-' or
        // '&' operation.
        //
        if (r.empty () && !root)
          throw invalid_argument (
            "class term '" + t + "' must start with '+'");
      }

      bool inv (t[1] == '!');     // Can be '\0'.
      string nm (t, inv ? 2 : 1);

      // Append the compound term.
      //
      if (nm == "(")
        r.emplace_back (parse_build_class_expr (s, p), op, inv);

      // Append the simple term.
      //
      else
      {
        build_class_term::validate_name (nm);
        r.emplace_back (move (nm), op, inv);
      }
    }

    // Verify that the nested expression is terminated with the closing
    // parenthesis and is not empty.
    //
    if (!root)
    {
      // The zero-length of the last term means that we escaped the loop due
      // to the eos.
      //
      if (n == 0)
        throw invalid_argument (
          "nested class expression must be closed with ')'");

      if (r.empty ())
        throw invalid_argument ("empty nested class expression");
    }

    return r;
  }

  build_class_expr::
  build_class_expr (const std::string& s, std::string c)
      : comment (move (c))
  {
    using std::string;

    size_t eb (0); // Start of expression.

    // Parse the underlying classes until the expression term, ':', or eos is
    // encountered.
    //
    for (size_t b (0); next_word (s, b, eb); )
    {
      string nm (s, b, eb - b);

      if (nm[0] == '+' || nm[0] == '-' || nm[0] == '&')
      {
        // Expression must always be separated with ':' from the underlying
        // classes.
        //
        if (!underlying_classes.empty ())
          throw invalid_argument ("class expression separator ':' expected");

        eb = b; // Reposition to the term beginning.
        break;
      }
      else if (nm == ":")
      {
        // The ':' separator must follow the underlying class set.
        //
        if (underlying_classes.empty ())
          throw invalid_argument ("underlying class set expected");

        break;
      }

      build_class_term::validate_name (nm);
      underlying_classes.emplace_back (move (nm));
    }

    expr = parse_build_class_expr (eb == 0 ? s : string (s, eb));

    // At least one of the expression or underlying class set should be
    // present in the representation.
    //
    if (expr.empty () && underlying_classes.empty ())
      throw invalid_argument ("empty class expression");
  }

  build_class_expr::
  build_class_expr (const strings& cs, char op, std::string c)
      : comment (move (c))
  {
    vector<build_class_term> r;

    for (const std::string& c: cs)
      r.emplace_back (c, op == '-' ? '-' : '+', false /* inverse */);

    if (op == '&' && !r.empty ())
    {
      build_class_term t (move (r), '&', false /* inverse */);
      r = vector<build_class_term> ({move (t)});
    }

    expr = move (r);
  }

  // Return string representation of the build class expression.
  //
  static string
  to_string (const vector<build_class_term>& expr)
  {
    string r;
    for (const build_class_term& t: expr)
    {
      if (!r.empty ())
        r += ' ';

      r += t.operation;

      if (t.inverted)
        r += '!';

      r += t.simple ? t.name : "( " + to_string (t.expr) + " )";
    }

    return r;
  }

  string build_class_expr::
  string () const
  {
    using std::string;

    string r;
    for (const string& c: underlying_classes)
    {
      if (!r.empty ())
        r += ' ';

      r += c;
    }

    if (!expr.empty ())
    {
      if (!r.empty ())
        r += " : " + to_string (expr);
      else
        r = to_string (expr);
    }

    return r;
  }

  // Match build configuration classes against an expression, updating the
  // result.
  //
  static void
  match_classes (const strings& cs,
                 const build_class_inheritance_map& im,
                 const vector<build_class_term>& expr,
                 bool& r)
  {
    for (const build_class_term& t: expr)
    {
      // Note that the '+' operation may only invert false and the '-' and '&'
      // operations may only invert true (see below). So, let's optimize it a
      // bit.
      //
      if ((t.operation == '+') == r)
        continue;

      bool m (false);

      // We don't expect the class list to be long, so the linear search should
      // be fine.
      //
      if (t.simple)
      {
        // Check if any of the classes or their bases match the term name.
        //
        for (const string& c: cs)
        {
          m = (c == t.name);

          if (!m)
          {
            // Go through base classes.
            //
            for (auto i (im.find (c)); i != im.end (); )
            {
              const string& base (i->second);

              // Bail out if the base class matches.
              //
              m = (base == t.name);

              if (m)
                break;

              i = im.find (base);
            }
          }

          if (m)
            break;
        }
      }
      else
        match_classes (cs, im, t.expr, m);

      if (t.inverted)
        m = !m;

      switch (t.operation)
      {
      case '+': if (m) r = true;  break;
      case '-': if (m) r = false; break;
      case '&': r &= m;           break;
      default:  assert (false);
      }
    }
  }

  void build_class_expr::
  match (const strings& cs,
         const build_class_inheritance_map& im,
         bool& r) const
  {
    match_classes (cs, im, expr, r);
  }

  // text_type
  //
  string
  to_string (text_type t)
  {
    switch (t)
    {
    case text_type::plain:       return "text/plain";
    case text_type::github_mark: return "text/markdown;variant=GFM";
    case text_type::common_mark: return "text/markdown;variant=CommonMark";
    }

    assert (false); // Can't be here.
    return string ();
  }

  optional<text_type>
  to_text_type (const string& t)
  {
    auto bad_type = [] (const string& d) {throw invalid_argument (d);};

    // Parse the media type representation (see RFC2045 for details) into the
    // type/subtype value and the parameter list. Note: we don't support
    // parameter quoting and comments for simplicity.
    //
    size_t p (t.find (';'));
    const string& tp (p != string::npos ? trim (string (t, 0, p)) : t);

    small_vector<pair<string, string>, 1> ps;

    while (p != string::npos)
    {
      // Extract parameter name.
      //
      size_t b (p + 1);
      p = t.find ('=', b);

      if (p == string::npos)
        bad_type ("missing '='");

      string n (trim (string (t, b, p - b)));

      // Extract parameter value.
      //
      b = p + 1;
      p = t.find (';', b);

      string v (trim (string (t,
                              b,
                              p != string::npos ? p - b : string::npos)));

      ps.emplace_back (move (n), move (v));
    }

    // Calculate the resulting text type, failing on unrecognized media type,
    // unexpected parameter name or value.
    //
    // Note that type, subtype, and parameter names are matched
    // case-insensitively.
    //
    optional<text_type> r;

    // Currently only the plain and markdown text types are allowed. Later we
    // can potentially introduce some other text types.
    //
    if (icasecmp (tp, "text/plain") == 0)
    {
      // Currently, we don't expect parameters for plain text. Later we can
      // potentially introduce some plain text variants.
      //
      if (ps.empty ())
        r = text_type::plain;
    }
    else if (icasecmp (tp, "text/markdown") == 0)
    {
      // Currently, a single optional variant parameter with the two possible
      // values is allowed for markdown. Later we can potentially introduce
      // some other markdown variants.
      //
      if (ps.empty () ||
          (ps.size () == 1 && icasecmp (ps[0].first, "variant") == 0))
      {
        // Note that markdown variants are matched case-insensitively (see
        // RFC7763 for details).
        //
        string v;
        if (ps.empty () || icasecmp (v = move (ps[0].second), "GFM") == 0)
          r = text_type::github_mark;
        else if (icasecmp (v, "CommonMark") == 0)
          r = text_type::common_mark;
      }
    }
    else if (icasecmp (tp, "text/", 5) != 0)
      bad_type ("text type expected");

    return r;
  }

  // test_dependency_type
  //
  string
  to_string (test_dependency_type t)
  {
    switch (t)
    {
    case test_dependency_type::tests:      return "tests";
    case test_dependency_type::examples:   return "examples";
    case test_dependency_type::benchmarks: return "benchmarks";
    }

    assert (false); // Can't be here.
    return string ();
  }

  test_dependency_type
  to_test_dependency_type (const string& t)
  {
         if (t == "tests")      return test_dependency_type::tests;
    else if (t == "examples")   return test_dependency_type::examples;
    else if (t == "benchmarks") return test_dependency_type::benchmarks;
    else throw invalid_argument ("invalid test dependency type '" + t + "'");
  }


  // test_dependency
  //
  test_dependency::
  test_dependency (std::string v, test_dependency_type t)
      : type (t)
  {
    using std::string;

    buildtime = (v[0] == '*');
    size_t p (v.find_first_not_of (spaces, buildtime ? 1 : 0));

    if (p == string::npos)
      throw invalid_argument ("no package name specified");

    static_cast<dependency&> (*this) =
      dependency (p == 0 ? move (v) : string (v, p));
  }

  // pkg_package_manifest
  //
  static build_class_expr
  parse_build_class_expr (const name_value& nv,
                          bool first,
                          const string& source_name)
  {
    pair<string, string> vc (parser::split_comment (nv.value));
    string& v (vc.first);
    string& c (vc.second);

    auto bad_value = [&v, &nv, &source_name] (const string& d,
                                              const invalid_argument& e)
    {
      throw !source_name.empty ()
            ? parsing (source_name,
                       nv.value_line, nv.value_column,
                       d + ": " + e.what ())
            : parsing (d + " in '" + v + "': " + e.what ());
    };

    build_class_expr r;

    try
    {
      r = build_class_expr (v, move (c));

      // Underlying build configuration class set may appear only in the
      // first builds value.
      //
      if (!r.underlying_classes.empty () && !first)
        throw invalid_argument ("unexpected underlying class set");
    }
    catch (const invalid_argument& e)
    {
      bad_value ("invalid package builds", e);
    }

    return r;
  }

  static build_constraint
  parse_build_constraint (const name_value& nv,
                          bool exclusion,
                          const string& source_name)
  {
    pair<string, string> vc (parser::split_comment (nv.value));
    string& v (vc.first);
    string& c (vc.second);

    auto bad_value = [&v, &nv, &source_name] (const string& d)
    {
      throw !source_name.empty ()
            ? parsing (source_name, nv.value_line, nv.value_column, d)
            : parsing (d + " in '" + v + "'");
    };

    size_t p (v.find ('/'));
    string nm (p != string::npos ? v.substr (0, p) : move (v));

    optional<string> tg (p != string::npos
                         ? optional<string> (string (v, p + 1))
                         : nullopt);

    if (nm.empty ())
      bad_value ("empty build configuration name pattern");

    if (tg && tg->empty ())
      bad_value ("empty build target pattern");

    return build_constraint (exclusion, move (nm), move (tg), move (c));
  }

  static email
  parse_email (const name_value& nv,
               const char* what,
               const string& source_name,
               bool empty = false)
  {
    auto bad_value = [&nv, &source_name] (const string& d)
    {
      throw !source_name.empty ()
            ? parsing (source_name, nv.value_line, nv.value_column, d)
            : parsing (d);
    };

    pair<string, string> vc (parser::split_comment (nv.value));
    string& v (vc.first);
    string& c (vc.second);

    if (v.empty () && !empty)
      bad_value (string ("empty ") + what + " email");

    return email (move (v), move (c));
  }

  const version stub_version (0, "0", nullopt, nullopt, 0);

  static void
  parse_package_manifest (
    parser& p,
    name_value nv,
    const function<package_manifest::translate_function>& tf,
    bool iu,
    bool cd,
    package_manifest_flags fl,
    package_manifest& m)
  {
    auto bad_name ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.name_line, nv.name_column, d);});

    auto bad_value ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.value_line, nv.value_column, d);});

    // Make sure this is the start and we support the version.
    //
    if (!nv.name.empty ())
      bad_name ("start of package manifest expected");

    if (nv.value != "1")
      bad_value ("unsupported format version");

    auto parse_email = [&bad_name] (const name_value& nv,
                                    optional<email>& r,
                                    const char* what,
                                    const string& source_name,
                                    bool empty = false)
    {
      if (r)
        bad_name (what + string (" email redefinition"));

      r = bpkg::parse_email (nv, what, source_name, empty);
    };

    auto parse_url = [&bad_value] (const string& v,
                                   const char* what) -> manifest_url
    {
      auto p (parser::split_comment (v));

      if (v.empty ())
        bad_value (string ("empty ") + what + " url");

      manifest_url r;

      try
      {
        r = manifest_url (p.first, move (p.second));
      }
      catch (const invalid_argument& e)
      {
        bad_value (string ("invalid ") + what + " url: " + e.what ());
      }

      return r;
    };

    // Parse a string list (topics, keywords, etc). If the list length exceeds
    // five entries, then truncate it if the truncate flag is set and throw
    // manifest_parsing otherwise.
    //
    auto parse_list = [&bad_name, &bad_value] (const string& v,
                                               small_vector<string, 5>& r,
                                               char delim,
                                               bool single_word,
                                               bool truncate,
                                               const char* what)
    {
      if (!r.empty ())
        bad_name (string ("package ") + what + " redefinition");

      // Note that we parse the whole list to validate the entries.
      //
      list_parser lp (v.begin (), v.end (), delim);
      for (string lv (lp.next ()); !lv.empty (); lv = lp.next ())
      {
        if (single_word && lv.find_first_of (spaces) != string::npos)
          bad_value (string ("only single-word ") + what + " allowed");

        r.push_back (move (lv));
      }

      if (r.empty ())
        bad_value (string ("empty package ") + what + " specification");

      // If the list length limit is exceeded then truncate it or throw.
      //
      if (r.size () > 5)
      {
        if (truncate)
          r.resize (5);
        else
          bad_value (string ("up to five ") + what + " allowed");
      }
    };

    auto flag = [fl] (package_manifest_flags f)
    {
      return (fl & f) != package_manifest_flags::none;
    };

    // Cache the upstream version manifest value and validate whether it's
    // allowed later, after the version value is parsed.
    //
    optional<name_value> upstream_version;

    // We will cache the depends and the test dependency manifest values to
    // parse and, if requested, complete the version constraints later, after
    // the version value is parsed.
    //
    vector<name_value> dependencies;
    small_vector<name_value, 1> tests;

    // We will cache the description and its type values to validate them
    // later, after both are parsed.
    //
    optional<name_value> description;
    optional<name_value> description_type;

    for (nv = p.next (); !nv.empty (); nv = p.next ())
    {
      string& n (nv.name);
      string& v (nv.value);

      if (n == "name")
      {
        if (!m.name.empty ())
          bad_name ("package name redefinition");

        try
        {
          m.name = package_name (move (v));
        }
        catch (const invalid_argument& e)
        {
          bad_value (string ("invalid package name: ") + e.what ());
        }
      }
      else if (n == "version")
      {
        if (!m.version.empty ())
          bad_name ("package version redefinition");

        try
        {
          m.version = version (v);
        }
        catch (const invalid_argument& e)
        {
          bad_value (string ("invalid package version: ") + e.what ());
        }

        // Versions like 1.2.3- are forbidden in manifest as intended to be
        // used for version constrains rather than actual releases.
        //
        if (m.version.release && m.version.release->empty ())
          bad_value ("invalid package version release");

        if (tf)
        {
          tf (m.version);

          // Re-validate the version after the translation.
          //
          // The following description will be confusing for the end user.
          // However, they shouldn't ever see it unless the translation
          // function is broken.
          //
          if (m.version.empty ())
            bad_value ("empty translated package version");

          if (m.version.release && m.version.release->empty ())
            bad_value ("invalid translated package version " +
                       m.version.string () + ": earliest release");
        }
      }
      else if (n == "upstream-version")
      {
        if (upstream_version)
          bad_name ("upstream package version redefinition");

        if (v.empty ())
          bad_value ("empty upstream package version");

        upstream_version = move (nv);
      }
      else if (n == "project")
      {
        if (m.project)
          bad_name ("package project redefinition");

        try
        {
          m.project = package_name (move (v));
        }
        catch (const invalid_argument& e)
        {
          bad_value (string ("invalid project name: ") + e.what ());
        }
      }
      else if (n == "summary")
      {
        if (!m.summary.empty ())
          bad_name ("package summary redefinition");

        if (v.empty ())
          bad_value ("empty package summary");

        m.summary = move (v);
      }
      else if (n == "topics")
      {
        parse_list (v,
                    m.topics,
                    ','   /* delim */,
                    false /* single_word */,
                    false /* truncate */,
                    "topics");
      }
      else if (n == "keywords")
      {
        parse_list (v,
                    m.keywords,
                    ' '   /* delim */,
                    true  /* single_word */,
                    false /* truncate */,
                    "keywords");
      }
      else if (n == "tags")
      {
        parse_list (v,
                    m.keywords,
                    ','  /* delim */,
                    true /* single_word */,
                    true /* truncate */,
                    "tags");
      }
      else if (n == "description")
      {
        if (description)
        {
          if (description->name == "description-file")
            bad_name ("package description and description-file are "
                      "mutually exclusive");
          else
            bad_name ("package description redefinition");
        }

        if (v.empty ())
          bad_value ("empty package description");

        description = move (nv);
      }
      else if (n == "description-file")
      {
        if (flag (package_manifest_flags::forbid_file))
          bad_name ("package description-file not allowed");

        if (description)
        {
          if (description->name == "description-file")
            bad_name ("package description-file redefinition");
          else
            bad_name ("package description-file and description are "
                      "mutually exclusive");
        }

        description = move (nv);
      }
      else if (n == "description-type")
      {
        if (description_type)
          bad_name ("package description-type redefinition");

        description_type = move (nv);
      }
      else if (n == "changes")
      {
        if (v.empty ())
          bad_value ("empty package changes specification");

        m.changes.emplace_back (move (v));
      }
      else if (n == "changes-file")
      {
        if (flag (package_manifest_flags::forbid_file))
          bad_name ("package changes-file not allowed");

        auto vc (parser::split_comment (v));
        path p (move (vc.first));

        if (p.empty ())
          bad_value ("no path in package changes-file");

        if (p.absolute ())
          bad_value ("package changes-file path is absolute");

        m.changes.emplace_back (move (p), move (vc.second));
      }
      else if (n == "url")
      {
        if (m.url)
          bad_name ("project url redefinition");

        m.url = parse_url (v, "project");
      }
      else if (n == "email")
      {
        parse_email (nv, m.email, "project", p.name ());
      }
      else if (n == "doc-url")
      {
        if (m.doc_url)
          bad_name ("doc url redefinition");

        m.doc_url = parse_url (v, "doc");
      }
      else if (n == "src-url")
      {
        if (m.src_url)
          bad_name ("src url redefinition");

        m.src_url = parse_url (v, "src");
      }
      else if (n == "package-url")
      {
        if (m.package_url)
          bad_name ("package url redefinition");

        m.package_url = parse_url (v, "package");
      }
      else if (n == "package-email")
      {
        parse_email (nv, m.package_email, "package", p.name ());
      }
      else if (n == "build-email")
      {
        parse_email (nv, m.build_email, "build", p.name (), true /* empty */);
      }
      else if (n == "build-warning-email")
      {
        parse_email (nv, m.build_warning_email, "build warning", p.name ());
      }
      else if (n == "build-error-email")
      {
        parse_email (nv, m.build_error_email, "build error", p.name ());
      }
      else if (n == "priority")
      {
        if (m.priority)
          bad_name ("package priority redefinition");

        auto vc (parser::split_comment (v));
        strings::const_iterator b (priority_names.begin ());
        strings::const_iterator e (priority_names.end ());
        strings::const_iterator i (find (b, e, vc.first));

        if (i == e)
          bad_value ("invalid package priority");

        m.priority =
          priority (static_cast<priority::value_type> (i - b),
                    move (vc.second));
      }
      else if (n == "license")
      {
        auto vc (parser::split_comment (v));
        licenses l (move (vc.second));

        list_parser lp (vc.first.begin (), vc.first.end ());
        for (string lv (lp.next ()); !lv.empty (); lv = lp.next ())
        {
          // Reserve the license schemes for the future use and only recognize
          // the 'other' scheme for now, if specified. By default, the 'spdx'
          // scheme is implied.
          //
          // Note that if the substring that precedes ':' contains the
          // 'DocumentRef-' substring, then this is not a license scheme but
          // the license is a SPDX License Expression (see SPDX user defined
          // license reference for details).
          //
          size_t p (lv.find (':'));

          if (p != string::npos            &&
              lv.find ("DocumentRef-") > p &&
              lv.compare (0, p, "other") != 0)
            bad_value ("invalid package license scheme");

          l.push_back (move (lv));
        }

        if (l.empty ())
          bad_value ("empty package license specification");

        m.license_alternatives.push_back (move (l));
      }
      else if (n == "requires")
      {
        try
        {
          m.requirements.push_back (requirement_alternatives (v));
        }
        catch (const invalid_argument& e)
        {
          bad_value (e.what ());
        }
      }
      else if (n == "builds")
      {
        m.builds.push_back (
          parse_build_class_expr (nv, m.builds.empty (), p.name ()));
      }
      else if (n == "build-include")
      {
        m.build_constraints.push_back (
          parse_build_constraint (nv, false /* exclusion */, p.name ()));
      }
      else if (n == "build-exclude")
      {
        m.build_constraints.push_back (
          parse_build_constraint (nv, true /* exclusion */, p.name ()));
      }
      else if (n == "depends")
      {
        dependencies.push_back (move (nv));
      }
      // @@ TMP time to drop *-0.14.0?
      //
      else if (n == "tests"      || n == "tests-0.14.0"    ||
               n == "examples"   || n == "examples-0.14.0" ||
               n == "benchmarks" || n == "benchmarks-0.14.0")
      {
        // Strip the '-0.14.0' suffix from the value name, if present.
        //
        size_t p (n.find ('-'));
        if (p != string::npos)
          n.resize (p);

        tests.push_back (move (nv));
      }
      else if (n == "location")
      {
        if (flag (package_manifest_flags::forbid_location))
          bad_name ("package location not allowed");

        if (m.location)
          bad_name ("package location redefinition");

        try
        {
          path l (v);

          if (l.empty ())
            bad_value ("empty package location");

          if (l.absolute ())
            bad_value ("absolute package location");

          m.location = move (l);
        }
        catch (const invalid_path&)
        {
          bad_value ("invalid package location");
        }
      }
      else if (n == "sha256sum")
      {
        if (flag (package_manifest_flags::forbid_sha256sum))
          bad_name ("package sha256sum not allowed");

        if (m.sha256sum)
          bad_name ("package sha256sum redefinition");

        if (!valid_sha256 (v))
          bad_value ("invalid package sha256sum");

        m.sha256sum = move (v);
      }
      else if (n == "fragment")
      {
        if (flag (package_manifest_flags::forbid_fragment))
          bad_name ("package repository fragment not allowed");

        if (m.fragment)
          bad_name ("package repository fragment redefinition");

        if (v.empty ())
          bad_value ("empty package repository fragment");

        m.fragment = move (v);
      }
      else if (!iu)
        bad_name ("unknown name '" + n + "' in package manifest");
    }

    // Verify all non-optional values were specified.
    //
    if (m.name.empty ())
      bad_value ("no package name specified");
    else if (m.version.empty ())
      bad_value ("no package version specified");
    else if (m.summary.empty ())
      bad_value ("no package summary specified");
    else if (m.license_alternatives.empty ())
      bad_value ("no project license specified");

    // Verify that the upstream version is not specified for a stub.
    //
    if (upstream_version)
    {
      // Restore as bad_name() uses its line/column.
      //
      nv = move (*upstream_version);

      if (m.version.compare (stub_version, true /* ignore_revision */) == 0)
        bad_name ("upstream package version specified for a stub");

      m.upstream_version = move (nv.value);
    }

    // Verify that description is specified if the description type is
    // specified.
    //
    if (description_type && !description)
      bad_value ("no package description for specified description type");

    // Validate (and set) description and its type.
    //
    if (description)
    {
      // Restore as bad_value() uses its line/column.
      //
      nv = move (*description);

      string& v (nv.value);

      if (nv.name == "description-file")
      {
        auto vc (parser::split_comment (v));

        path p;
        try
        {
          p = path (move (vc.first));
        }
        catch (const invalid_path& e)
        {
          bad_value (string ("invalid package description file: ") +
                     e.what ());
        }

        if (p.empty ())
          bad_value ("no path in package description-file");

        if (p.absolute ())
          bad_value ("package description-file path is absolute");

        m.description = text_file (move (p), move (vc.second));
      }
      else
        m.description = text_file (move (v));

      if (description_type)
        m.description_type = move (description_type->value);

      // Verify the description type.
      //
      try
      {
        m.effective_description_type (iu);
      }
      catch (const invalid_argument& e)
      {
        if (description_type)
        {
          // Restore as bad_value() uses its line/column.
          //
          nv = move (*description_type);

          bad_value (string ("invalid package description type: ") +
                     e.what ());
        }
        else
          bad_value (string ("invalid package description file: ") +
                     e.what ());
      }
    }

    // Now, when the version manifest value is parsed, we can parse the
    // dependencies and complete their constraints, if requested.
    //
    auto complete_constraint = [&m, cd, &flag] (auto&& dep)
    {
      if (dep.constraint)
      try
      {
        version_constraint& vc (*dep.constraint);

        if (!vc.complete () &&
            flag (package_manifest_flags::forbid_incomplete_dependencies))
          throw invalid_argument ("$ not allowed");

        // Complete the constraint.
        //
        if (cd)
          vc = vc.effective (m.version);
      }
      catch (const invalid_argument& e)
      {
        throw invalid_argument (string ("invalid package constraint: ") +
                                e.what ());
      }

      return move (dep);
    };

    // Parse the regular dependencies.
    //
    for (name_value& d: dependencies)
    {
      nv = move (d); // Restore as bad_value() uses its line/column.

      const string& v (nv.value);

      // Allow specifying ?* in any order.
      //
      size_t n (v.size ());
      size_t cond ((n > 0 && v[0] == '?') || (n > 1 && v[1] == '?') ? 1 : 0);
      size_t btim ((n > 0 && v[0] == '*') || (n > 1 && v[1] == '*') ? 1 : 0);

      auto vc (parser::split_comment (v));

      const string& vl (vc.first);
      dependency_alternatives da (cond != 0, btim != 0, move (vc.second));

      string::const_iterator b (vl.begin ());
      string::const_iterator e (vl.end ());

      if (da.conditional || da.buildtime)
      {
        string::size_type p (vl.find_first_not_of (spaces, cond + btim));
        b = p == string::npos ? e : b + p;
      }

      try
      {
        list_parser lp (b, e, '|');
        for (string lv (lp.next ()); !lv.empty (); lv = lp.next ())
          da.push_back (complete_constraint (dependency (move (lv))));
      }
      catch (const invalid_argument& e)
      {
        bad_value (e.what ());
      }

      if (da.empty ())
        bad_value ("empty package dependency specification");

      m.dependencies.push_back (da);
    }

    // Parse the test dependencies.
    //
    for (name_value& t: tests)
    {
      nv = move (t); // Restore as bad_value() uses its line/column.

      try
      {
        m.tests.push_back (
          complete_constraint (
            test_dependency (move (nv.value),
                             to_test_dependency_type (nv.name))));
      }
      catch (const invalid_argument& e)
      {
        bad_value (e.what ());
      }
    }

    if (m.description       &&
        !m.description_type &&
        flag (package_manifest_flags::require_description_type))
      bad_name ("no package description type specified");

    if (!m.location && flag (package_manifest_flags::require_location))
      bad_name ("no package location specified");

    if (!m.sha256sum && flag (package_manifest_flags::require_sha256sum))
      bad_name ("no package sha256sum specified");
  }

  package_manifest
  pkg_package_manifest (parser& p, name_value nv, bool iu)
  {
    return package_manifest (
      p,
      move (nv),
      iu,
      false /* complete_depends */,
      package_manifest_flags::forbid_file              |
      package_manifest_flags::require_description_type |
      package_manifest_flags::require_location         |
      package_manifest_flags::forbid_fragment          |
      package_manifest_flags::forbid_incomplete_dependencies);
  }

  // package_manifest
  //
  package_manifest::
  package_manifest (manifest_parser& p,
                    const function<translate_function>& tf,
                    bool iu,
                    bool cd,
                    package_manifest_flags fl)
  {
    parse_package_manifest (p, p.next (), tf, iu, cd, fl, *this);

    // Make sure this is the end.
    //
    name_value nv (p.next ());
    if (!nv.empty ())
      throw parsing (p.name (), nv.name_line, nv.name_column,
                     "single package manifest expected");
  }

  package_manifest::
  package_manifest (manifest_parser& p,
                    bool iu,
                    bool cd,
                    package_manifest_flags fl)
      : package_manifest (p, function<translate_function> (), iu, cd, fl)
  {
  }

  package_manifest::
  package_manifest (manifest_parser& p,
                    name_value nv,
                    bool iu,
                    bool cd,
                    package_manifest_flags fl)
  {
    parse_package_manifest (
      p, move (nv), function<translate_function> (), iu, cd, fl, *this);
  }

  optional<text_type> package_manifest::
  effective_description_type (bool iu) const
  {
    if (!description)
      throw logic_error ("absent description");

    optional<text_type> r;

    if (description_type)
      r = to_text_type (*description_type);
    else if (description->file)
    {
      string ext (description->path.extension ());
      if (ext.empty () || icasecmp (ext, "txt") == 0)
        r = text_type::plain;
      else if (icasecmp (ext, "md") == 0 || icasecmp (ext, "markdown") == 0)
        r = text_type::github_mark;
    }
    else
      r = text_type::plain;

    if (!r && !iu)
      throw invalid_argument ("unknown text type");

    return r;
  }

  void package_manifest::
  override (const vector<manifest_name_value>& nvs, const string& name)
  {
    // Reset the build constraints value sub-group on the first call.
    //
    bool rbc (true);
    auto reset_build_constraints = [&rbc, this] ()
    {
      if (rbc)
      {
        build_constraints.clear ();
        rbc = false;
      }
    };

    // Reset the builds value group on the first call.
    //
    bool rb (true);
    auto reset_builds = [&rb, &reset_build_constraints, this] ()
    {
      if (rb)
      {
        builds.clear ();
        reset_build_constraints ();
        rb = false;
      }
    };

    // Reset the build emails value group on the first call.
    //
    bool rbe (true);
    auto reset_build_emails = [&rbe, this] ()
    {
      if (rbe)
      {
        build_email = nullopt;
        build_warning_email = nullopt;
        build_error_email = nullopt;
        rbe = false;
      }
    };

    for (const manifest_name_value& nv: nvs)
    {
      const string& n (nv.name);

      if (n == "builds")
      {
        reset_builds ();
        builds.push_back (parse_build_class_expr (nv, builds.empty (), name));
      }
      else if (n == "build-include")
      {
        reset_build_constraints ();

        build_constraints.push_back (
          parse_build_constraint (nv, false /* exclusion */, name));
      }
      else if (n == "build-exclude")
      {
        reset_build_constraints ();

        build_constraints.push_back (
          parse_build_constraint (nv, true /* exclusion */, name));
      }
      else if (n == "build-email")
      {
        reset_build_emails ();
        build_email = parse_email (nv, "build", name, true /* empty */);
      }
      else if (n == "build-warning-email")
      {
        reset_build_emails ();
        build_warning_email = parse_email (nv, "build warning", name);
      }
      else if (n == "build-error-email")
      {
        reset_build_emails ();
        build_error_email = parse_email (nv, "build error", name);
      }
      else
      {
        string d ("cannot override '" + n + "' value");

        throw !name.empty ()
              ? parsing (name, nv.name_line, nv.name_column, d)
              : parsing (d);
      }
    }
  }

  void package_manifest::
  validate_overrides (const vector<manifest_name_value>& nvs,
                      const string& name)
  {
    package_manifest p;
    p.override (nvs, name);
  }

  static const string description_file ("description-file");
  static const string changes_file     ("changes-file");

  void package_manifest::
  load_files (const function<load_function>& loader, bool iu)
  {
    auto load = [&loader] (const string& n, const path& p)
    {
      string r (loader (n, p));

      if (r.empty ())
        throw parsing ("package " + n + " references empty file");

      return r;
    };

    // Load the description-file manifest value.
    //
    if (description)
    {
      // Make the description type explicit.
      //
      optional<text_type> t (effective_description_type (iu)); // Can throw.

      assert (t || iu); // Can only be absent if we ignore unknown.

      if (!description_type && t)
        description_type = to_string (*t);

      // At this point the description type can only be absent if the
      // description comes from a file. Otherwise, we would end up with the
      // plain text.
      //
      assert (description_type || description->file);

      if (description->file)
      {
        if (!description_type)
          description_type = "text/unknown; extension=" +
                             description->path.extension ();

        description = text_file (load (description_file, description->path));
      }
    }

    // Load the changes-file manifest values.
    //
    for (text_file& c: changes)
    {
      if (c.file)
        c = text_file (load (changes_file, c.path));
    }
  }

  static void
  serialize_package_manifest (
    manifest_serializer& s,
    const package_manifest& m,
    bool header_only,
    const optional<standard_version>& min_ver = nullopt)
  {
    // @@ Should we check that all non-optional values are specified ?
    // @@ Should we check that values are valid: version release is not empty,
    //    sha256sum is a proper string, ...?
    // @@ Currently we don't know if we are serializing the individual package
    //    manifest or the package list manifest, so can't ensure all values
    //    allowed in the current context (*-file values).
    //

    s.next ("", "1"); // Start of manifest.

    auto bad_value ([&s](const string& d) {
        throw serialization (s.name (), d);});

    if (m.name.empty ())
      bad_value ("empty package name");

    s.next ("name", m.name.string ());
    s.next ("version", m.version.string ());

    if (m.upstream_version)
      s.next ("upstream-version", *m.upstream_version);

    if (m.project)
      s.next ("project", m.project->string ());

    if (m.priority)
    {
      size_t v (*m.priority);
      assert (v < priority_names.size ());

      s.next ("priority",
              serializer::merge_comment (priority_names[v],
                                         m.priority->comment));
    }

    s.next ("summary", m.summary);

    for (const auto& la: m.license_alternatives)
      s.next ("license",
              serializer::merge_comment (concatenate (la), la.comment));

    if (!header_only)
    {
      if (!m.topics.empty ())
        s.next ("topics", concatenate (m.topics));

      if (!m.keywords.empty ())
        s.next ("keywords", concatenate (m.keywords, " "));

      if (m.description)
      {
        if (m.description->file)
          s.next ("description-file",
                  serializer::merge_comment (m.description->path.string (),
                                             m.description->comment));
        else
          s.next ("description", m.description->text);

        if (m.description_type)
          s.next ("description-type", *m.description_type);
      }

      for (const auto& c: m.changes)
      {
        if (c.file)
          s.next ("changes-file",
                  serializer::merge_comment (c.path.string (), c.comment));
        else
          s.next ("changes", c.text);
      }

      if (m.url)
        s.next ("url",
                serializer::merge_comment (m.url->string (), m.url->comment));

      if (m.doc_url)
        s.next ("doc-url",
                serializer::merge_comment (m.doc_url->string (),
                                           m.doc_url->comment));

      if (m.src_url)
        s.next ("src-url",
                serializer::merge_comment (m.src_url->string (),
                                           m.src_url->comment));

      if (m.package_url)
        s.next ("package-url",
                serializer::merge_comment (m.package_url->string (),
                                           m.package_url->comment));

      if (m.email)
        s.next ("email",
                serializer::merge_comment (*m.email, m.email->comment));

      if (m.package_email)
        s.next ("package-email",
                serializer::merge_comment (*m.package_email,
                                           m.package_email->comment));

      if (m.build_email)
        s.next ("build-email",
                serializer::merge_comment (*m.build_email,
                                           m.build_email->comment));

      if (m.build_warning_email)
        s.next ("build-warning-email",
                serializer::merge_comment (*m.build_warning_email,
                                           m.build_warning_email->comment));

      if (m.build_error_email)
        s.next ("build-error-email",
                serializer::merge_comment (*m.build_error_email,
                                           m.build_error_email->comment));

      for (const dependency_alternatives& d: m.dependencies)
        s.next ("depends",
                (d.conditional
                 ? (d.buildtime ? "?* " : "? ")
                 : (d.buildtime ? "* " : "")) +
                serializer::merge_comment (concatenate (d, " | "), d.comment));

      for (const requirement_alternatives& r: m.requirements)
        s.next ("requires", r.string ());

      for (const test_dependency& t: m.tests)
      {
        string n (to_string (t.type));

        // If we generate the manifest for parsing by clients of libbpkg
        // versions less than 0.14.0-, then replace the introduced in 0.14.0
        // build-time tests, examples, and benchmarks values with
        // tests-0.14.0, examples-0.14.0, and benchmarks-0.14.0,
        // respectively. This way such clients will still be able to parse it,
        // ignoring unknown values.
        //
        // @@ TMP time to drop?
        //                                               0.14.0-
        if (t.buildtime && min_ver && min_ver->version < 13999990001ULL)
          n += "-0.14.0";

        s.next (n, t.string ());
      }

      for (const build_class_expr& e: m.builds)
        s.next ("builds", serializer::merge_comment (e.string (), e.comment));

      for (const build_constraint& c: m.build_constraints)
        s.next (c.exclusion ? "build-exclude" : "build-include",
                serializer::merge_comment (!c.target
                                           ? c.config
                                           : c.config + "/" + *c.target,
                                           c.comment));

      if (m.location)
        s.next ("location", m.location->posix_string ());

      if (m.sha256sum)
        s.next ("sha256sum", *m.sha256sum);

      if (m.fragment)
        s.next ("fragment", *m.fragment);
    }

    s.next ("", ""); // End of manifest.
  }

  void package_manifest::
  serialize (serializer& s, const optional<standard_version>& min_ver) const
  {
    serialize_package_manifest (s, *this, false, min_ver);
  }

  void package_manifest::
  serialize_header (serializer& s) const
  {
    serialize_package_manifest (s, *this, true);
  }

  // Parse the directory manifest that may contain the only (and required)
  // location name that refers to the package directory.
  //
  static package_manifest
  parse_directory_manifest (parser& p, name_value nv, bool iu)
  {
    auto bad_name ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.name_line, nv.name_column, d);});

    auto bad_value ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.value_line, nv.value_column, d);});

    // Make sure this is the start and we support the version.
    //
    if (!nv.name.empty ())
      bad_name ("start of package manifest expected");

    if (nv.value != "1")
      bad_value ("unsupported format version");

    package_manifest r;

    for (nv = p.next (); !nv.empty (); nv = p.next ())
    {
      string& n (nv.name);
      string& v (nv.value);

      if (n == "location")
      {
        if (r.location)
          bad_name ("package location redefinition");

        try
        {
          path l (v);

          if (l.empty ())
            bad_value ("empty package location");

          if (l.absolute ())
            bad_value ("absolute package location");

          // Make sure that the path is a directory (contains the trailing
          // slash).
          //
          if (!l.to_directory ())
            l = path_cast<dir_path> (move (l));

          r.location = move (l);
        }
        catch (const invalid_path&)
        {
          bad_value ("invalid package location");
        }
      }
      else if (n == "fragment")
      {
        if (r.fragment)
          bad_name ("package repository fragment redefinition");

        if (v.empty ())
          bad_value ("empty package repository fragment");

        r.fragment = move (v);
      }
      else if (!iu)
        bad_name ("unknown name '" + n + "' in package manifest");
    }

    if (!r.location)
      bad_name ("no package location specified");

    return r;
  }

  static package_manifest
  parse_directory_manifest (parser& p, bool iu)
  {
    package_manifest r (parse_directory_manifest (p, p.next (), iu));

    // Make sure this is the end.
    //
    name_value nv (p.next ());
    if (!nv.empty ())
      throw parsing (p.name (), nv.name_line, nv.name_column,
                     "single package manifest expected");

    return r;
  }

  // Serialize the directory manifest (see above).
  //
  static void
  serialize_directory_manifest (serializer& s, const package_manifest& m)
  {
    s.next ("", "1"); // Start of manifest.

    auto bad_value ([&s](const string& d) {
        throw serialization (s.name (), d);});

    if (!m.location)
      bad_value ("no valid location");

    s.next ("location", m.location->posix_representation ());

    if (m.fragment)
      s.next ("fragment", *m.fragment);

    s.next ("", ""); // End of manifest.
  }

  // dir_package_manifest
  //
  package_manifest
  dir_package_manifest (parser& p, name_value nv, bool iu)
  {
    return parse_directory_manifest (p, nv, iu);
  }

  package_manifest
  dir_package_manifest (parser& p, bool iu)
  {
    return parse_directory_manifest (p, iu);
  }

  void
  dir_package_manifest (serializer& s, const package_manifest& m)
  {
    serialize_directory_manifest (s, m);
  }

  // git_package_manifest
  //
  package_manifest
  git_package_manifest (parser& p, name_value nv, bool iu)
  {
    return parse_directory_manifest (p, nv, iu);
  }

  package_manifest
  git_package_manifest (parser& p, bool iu)
  {
    return parse_directory_manifest (p, iu);
  }

  void
  git_package_manifest (serializer& s, const package_manifest& m)
  {
    serialize_directory_manifest (s, m);
  }

  // pkg_package_manifests
  //
  pkg_package_manifests::
  pkg_package_manifests (parser& p, bool iu)
  {
    name_value nv (p.next ());

    auto bad_name ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.name_line, nv.name_column, d);});

    auto bad_value ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.value_line, nv.value_column, d);});

    // Make sure this is the start and we support the version.
    //
    if (!nv.name.empty ())
      bad_name ("start of package list manifest expected");

    if (nv.value != "1")
      bad_value ("unsupported format version");

    // Parse the package list manifest.
    //
    for (nv = p.next (); !nv.empty (); nv = p.next ())
    {
      string& n (nv.name);
      string& v (nv.value);

      if (n == "sha256sum")
      {
        if (!sha256sum.empty ())
          bad_name ("sha256sum redefinition");

        if (!valid_sha256 (v))
          bad_value ("invalid sha256sum");

        sha256sum = move (v);
      }
      else if (!iu)
        bad_name ("unknown name '" + n + "' in package list manifest");
    }

    // Verify all non-optional values were specified.
    //
    if (sha256sum.empty ())
      bad_value ("no sha256sum specified");

    // Parse package manifests.
    //
    for (nv = p.next (); !nv.empty (); nv = p.next ())
      push_back (pkg_package_manifest (p, move (nv), iu));
  }

  void pkg_package_manifests::
  serialize (serializer& s, const optional<standard_version>& min_ver) const
  {
    // Serialize the package list manifest.
    //
    // @@ Should we check that values are valid ?
    //
    s.next ("", "1"); // Start of manifest.
    s.next ("sha256sum", sha256sum);
    s.next ("", "");  // End of manifest.

    // Serialize package manifests.
    //
    for (const package_manifest& p: *this)
    {
      auto bad_value = [&p, &s](const string& d)
      {
        throw serialization (
          s.name (),
          d + " for " + p.name.string () + "-" + p.version.string ());
      };

      if (p.description)
      {
        if (p.description->file)
          bad_value ("forbidden description-file");

        if (!p.description_type)
          bad_value ("no valid description-type");
      }

      for (const auto& c: p.changes)
        if (c.file)
          bad_value ("forbidden changes-file");

      if (!p.location)
        bad_value ("no valid location");

      if (!p.sha256sum)
        bad_value ("no valid sha256sum");

      pkg_package_manifest (s, p, min_ver);
    }

    s.next ("", ""); // End of stream.
  }

  // Parse package directory manifests.
  //
  static void
  parse_directory_manifests (parser& p, bool iu, vector<package_manifest>& ms)
  {
    // Normally, such manifests are created manually, so let's check for
    // duplicates.
    //
    for (name_value nv (p.next ()); !nv.empty (); )
    {
      package_manifest pm (dir_package_manifest (p, move (nv), iu));
      nv = p.next ();

      for (const auto& m: ms)
      {
        if (m.location == pm.location)
          throw parsing (p.name (),
                         nv.name_line, nv.name_column,
                         "duplicate package manifest");
      }

      ms.push_back (move (pm));
    }
  }

  // Serialize package directory manifests.
  //
  static void
  serialize_directory_manifests (serializer& s,
                                 const vector<package_manifest>& ms)
  {
    for (const package_manifest& m: ms)
      serialize_directory_manifest (s, m);

    s.next ("", ""); // End of stream.
  }

  // dir_package_manifests
  //
  dir_package_manifests::
  dir_package_manifests (parser& p, bool iu)
  {
    parse_directory_manifests (p, iu, *this);
  }

  void dir_package_manifests::
  serialize (serializer& s) const
  {
    serialize_directory_manifests (s, *this);
  }

  // git_package_manifests
  //
  git_package_manifests::
  git_package_manifests (parser& p, bool iu)
  {
    parse_directory_manifests (p, iu, *this);
  }

  void git_package_manifests::
  serialize (serializer& s) const
  {
    serialize_directory_manifests (s, *this);
  }

  // repository_url_traits
  //
  optional<repository_url_traits::scheme_type> repository_url_traits::
  translate_scheme (const string_type&         url,
                    string_type&&              scheme,
                    optional<authority_type>&  authority,
                    optional<path_type>&       path,
                    optional<string_type>&     query,
                    optional<string_type>&     fragment,
                    bool&                      rootless)
  {
    auto bad_url = [] (const char* d = "invalid URL")
    {
      throw invalid_argument (d);
    };

    // Consider non-empty URL as a path if the URL parsing failed. If the URL
    // is empty then leave the basic_url ctor to throw.
    //
    if (scheme.empty ())
    {
      if (!url.empty ())
      try
      {
        size_t p (url.find ('#'));

        if (p != string::npos)
        {
          path = path_type (url.substr (0, p)).normalize ();
          fragment = url.substr (p + 1);
        }
        else
          path = path_type (url).normalize ();

        rootless = false;
        return scheme_type::file;
      }
      catch (const invalid_path&)
      {
        // If this is not a valid path either, then let's consider the
        // argument a broken URL, and leave the basic_url ctor to throw.
        //
      }

      return nullopt;
    }

    if (!authority && !path && !query)
      bad_url ("empty URL");

    if (rootless)
      bad_url ("rootless path");

    auto translate_remote = [&authority, &path, &bad_url] ()
    {
      if (!authority || authority->host.empty ())
        bad_url ("invalid host");

      // Normalize the host name/address.
      //
      authority->host.normalize ();

      // We don't distinguish between the absent and empty paths for the
      // remote repository URLs.
      //
      if (!path)
        path = path_type ();

      if (path->absolute ())
        bad_url ("absolute path");

      try
      {
        path->normalize (false /* actual */, true /* cur_empty */);
      }
      catch (const invalid_path&)
      {
        assert (false); // Can't be here as the path is relative.
      }

      // URL shouldn't go past the root directory of a server.
      //
      if (!path->empty () && *path->begin () == "..")
        bad_url ("invalid path");
    };

    if (icasecmp (scheme, "http") == 0)
    {
      translate_remote ();
      return scheme_type::http;
    }
    else if (icasecmp (scheme, "https") == 0)
    {
      translate_remote ();
      return scheme_type::https;
    }
    else if (icasecmp (scheme, "git") == 0)
    {
      translate_remote ();
      return scheme_type::git;
    }
    else if (icasecmp (scheme, "ssh") == 0)
    {
      translate_remote ();

      // Should we also support the scp-like syntax (see git-clone(1) man page
      // for details)? On the one hand, it would complicate things quite a bit
      // and also clashes with Windows path representation (maybe we could
      // forbid one character long hostnames for this syntax). On the other,
      // it seems to be widespread (used by GitHub). Let's postpone it until
      // requested by users.
      //
      return scheme_type::ssh;
    }
    else if (icasecmp (scheme, "file") == 0)
    {
      if (authority)
      {
        if (!authority->empty () &&
            (icasecmp (authority->host, "localhost") != 0 ||
             authority->port != 0                         ||
             !authority->user.empty ()))
          throw invalid_argument ("invalid authority");

        // We don't distinguish between the absent, empty and localhost
        // authorities for the local repository locations.
        //
        authority = nullopt;
      }

      if (!path)
        bad_url ("absent path");

      // On POSIX make the relative (to the authority "root") path absolute. On
      // Windows it must already be an absolute path.
      //
#ifndef _WIN32
      if (path->absolute ())
        bad_url ("absolute path");

      path = path_type ("/") / *path;
#else
      if (path->relative ())
        bad_url ("relative path");
#endif

      assert (path->absolute ());

      try
      {
        path->normalize ();
      }
      catch (const invalid_path&)
      {
        bad_url ("invalid path"); // Goes past the root directory.
      }

      if (query)
        bad_url ();

      return scheme_type::file;
    }
    else
      throw invalid_argument ("unknown scheme");
  }

  repository_url_traits::string_type repository_url_traits::
  translate_scheme (string_type&                     url,
                    const scheme_type&               scheme,
                    const optional<authority_type>&  authority,
                    const optional<path_type>&       path,
                    const optional<string_type>&     /*query*/,
                    const optional<string_type>&     fragment,
                    bool                             /*rootless*/)
  {
    switch (scheme)
    {
    case scheme_type::http:  return "http";
    case scheme_type::https: return "https";
    case scheme_type::git:   return "git";
    case scheme_type::ssh:   return "ssh";
    case scheme_type::file:
      {
        assert (path);

        if (path->absolute () && (fragment || authority))
          return "file";

        url = path->relative () ? path->posix_string () : path->string ();

        if (fragment)
        {
          assert (path->relative ());

          url += '#';
          url += *fragment;
        }

        return string_type ();
      }
    }

    assert (false); // Can't be here.
    return "";
  }

  repository_url_traits::path_type repository_url_traits::
  translate_path (string_type&& path)
  {
    try
    {
      return path_type (url::decode (path));
    }
    catch (const invalid_path&)
    {
      throw invalid_argument ("invalid url");
    }
  }

   repository_url_traits::string_type repository_url_traits::
   translate_path (const path_type& path)
   {
     // If the path is absolute then this is a local URL object and the file://
     // URL notation is being produced. Thus, on POSIX we need to make the path
     // relative (to the authority "root"). On Windows the path should stay
     // absolute but the directory separators must be converted to the POSIX
     // ones.
     //
     string r;
     if (path.absolute ())
     {
#ifndef _WIN32
       r = path.leaf (dir_path ("/")).string ();
#else
       r = path.string ();
       replace (r.begin (), r.end (), '\\', '/');
#endif
     }
     else
       r = path.posix_string ();

     return url::encode (r, [] (char& c) {return !url::path_char (c);});
   }

  // repository_type
  //
  string
  to_string (repository_type t)
  {
    switch (t)
    {
    case repository_type::pkg: return "pkg";
    case repository_type::dir: return "dir";
    case repository_type::git: return "git";
    }

    assert (false); // Can't be here.
    return string ();
  }

  inline static optional<repository_type>
  parse_repository_type (const string& t)
  {
         if (t == "pkg") return repository_type::pkg;
    else if (t == "dir") return repository_type::dir;
    else if (t == "git") return repository_type::git;
    else                 return nullopt;
  }

  repository_type
  to_repository_type (const string& t)
  {
    if (optional<repository_type> r = parse_repository_type (t))
      return *r;

    throw invalid_argument ("invalid repository type '" + t + "'");
  }

  repository_type
  guess_type (const repository_url& url, bool local)
  {
    assert (!url.empty ());

    switch (url.scheme)
    {
    case repository_protocol::git:
      {
        return repository_type::git;
      }
    case repository_protocol::http:
    case repository_protocol::https:
    case repository_protocol::ssh:
    case repository_protocol::file:
      {
        if (url.path->extension () == "git")
          return repository_type::git;

        if (url.scheme != repository_protocol::file) // HTTP(S) or SSH?
          return repository_type::pkg;

        return local &&
          dir_exists (path_cast<dir_path> (*url.path) / dir_path (".git"))
          ? repository_type::git
          : repository_type::pkg;
      }
    }

    assert (false); // Can't be here.
    return repository_type::pkg;
  }

  // typed_repository_url
  //
  typed_repository_url::
  typed_repository_url (const string& s)
  {
    using traits = url::traits_type;

    if (traits::find (s) == 0) // Looks like a non-rootless URL?
    {
      size_t p (s.find_first_of ("+:"));

      assert (p != string::npos); // At least the colon is present.

      if (s[p] == '+')
      {
        string r (s, p + 1);
        optional<repository_type> t;

        if (traits::find (r) == 0 &&                        // URL notation?
            (t = parse_repository_type (string (s, 0, p)))) // Valid type?
        {
          repository_url u (r);

          // Only consider the URL to be typed if it is not a relative
          // path. And yes, we may end up with a relative path for the URL
          // string (e.g. ftp://example.com).
          //
          if (!(u.scheme == repository_protocol::file && u.path->relative ()))
          {
            type = move (t);
            url  = move (u);
          }
        }
      }
    }

    // Parse the whole string as a repository URL if we failed to extract the
    // type.
    //
    if (url.empty ())
      url = repository_url (s); // Throws if empty.
  }

  // repository_location
  //
  static string
  strip_domain (const string& host, repository_type type)
  {
    assert (!host.empty ()); // Should be repository location host.

    optional<string> h;

    switch (type)
    {
    case repository_type::pkg:
      {
        bool bpkg (false);
        if (host.compare (0, 4, "www.") == 0 ||
            host.compare (0, 4, "pkg.") == 0 ||
            (bpkg = host.compare (0, 5, "bpkg.") == 0))
          h = string (host, bpkg ? 5 : 4);

        break;
      }
    case repository_type::git:
      {
        if (host.compare (0, 4, "www.") == 0 ||
            host.compare (0, 4, "git.") == 0 ||
            host.compare (0, 4, "scm.") == 0)
          h = string (host, 4);

        break;
      }
    case repository_type::dir:
      {
        // Can't be here as repository location for the dir type can only be
        // local.
        //
        assert (false);
        break;
      }
    }

    if (h && h->empty ())
      throw invalid_argument ("invalid host");

    return h ? *h : host;
  }

  // The 'pkg' path component and '.git' extension stripping mode.
  //
  enum class strip_mode {version, component, path, extension};

  static path
  strip_path (const path& p, strip_mode mode)
  {
    if (mode == strip_mode::extension)
    {
      const char* e (p.extension_cstring ());
      return e != nullptr && strcmp (e, "git") == 0 ? p.base () : p;
    }

    // Should be pkg repository location path.
    //
    assert (!p.empty () && *p.begin () != "..");

    auto rb (p.rbegin ()), i (rb), re (p.rend ());

    // Find the version component.
    //
    for (; i != re; ++i)
    {
      const string& c (*i);

      if (!c.empty () && c.find_first_not_of ("1234567890") == string::npos)
        break;
    }

    if (i == re)
      throw invalid_argument ("missing repository version");

    // Validate the version. At the moment the only valid value is 1.
    //
    try
    {
      if (stoul (*i) != 1)
        throw invalid_argument ("unsupported repository version");
    }
    catch (const std::exception&)
    {
      throw invalid_argument ("invalid repository version");
    }

    path res (rb, i);

    // Canonical name prefix part ends with the special "pkg" component.
    //
    bool pc (++i != re && (*i == "pkg" || *i == "bpkg"));

    if (pc && mode == strip_mode::component)
      ++i; // Strip the "pkg" component.

    if (!pc || mode != strip_mode::path)
      res = path (i, re) / res; // Concatenate prefix and path parts.

    return res;
  }

  repository_location::
  repository_location (repository_url u, repository_type t)
      : repository_location (move (u), t, repository_location ()) // Delegate.
  {
    if (!empty () && relative ())
      throw invalid_argument ("relative filesystem path");
  }

  repository_location::
  repository_location (const std::string& s,
                       const optional<repository_type>& t,
                       bool local)
  {
    typed_repository_url tu (s);

    if (t && tu.type && t != tu.type)
      throw invalid_argument (
        "mismatching repository types: " + to_string (*t) + " specified, " +
        to_string (*tu.type) + " in URL scheme");

    repository_type et (tu.type ? *tu.type :
                        t       ? *t       :
                        guess_type (tu.url, local));

    *this = repository_location (move (tu.url), et);
  }

  repository_location::
  repository_location (repository_url u,
                       repository_type t,
                       const repository_location& b)
      : url_ (move (u)),
        type_ (t)
  {
    using std::string;    // Hidden by string().
    using std::to_string; // Hidden by to_string(repository_type).
    using butl::path;     // Hidden by path().

    if (url_.empty ())
    {
      if (!b.empty ())
        throw invalid_argument ("empty location");

      return;
    }

    // Make sure that the URL object is properly constructed (see notes for the
    // repository_url class in the header).
    //
    assert (url_.path &&
            remote () == (url_.authority && !url_.authority->empty ()));

    // Verify that the URL object matches the repository type.
    //
    switch (t)
    {
    case repository_type::pkg:
      {
        if (url_.scheme == repository_protocol::git ||
            url_.scheme == repository_protocol::ssh)
          throw invalid_argument ("unsupported scheme for pkg repository");

        if (url_.fragment)
          throw invalid_argument ("unexpected fragment for pkg repository");

        break;
      }
    case repository_type::dir:
      {
        if (url_.scheme != repository_protocol::file)
          throw invalid_argument (
            "unsupported scheme for dir repository");

        if (url_.fragment)
          throw invalid_argument ("unexpected fragment for dir repository");

        break;
      }
    case repository_type::git:
      {
        // Verify the URL fragment.
        //
        if (url_.fragment)
          parse_git_ref_filters (*url_.fragment);

        break;
      }
    }

    // Base repository location can not be a relative path.
    //
    if (!b.empty () && b.relative ())
      throw invalid_argument ("base location is relative filesystem path");

    path& up (*url_.path);

    // For the repositories that are "directories", make sure that the URL
    // object's path is a directory (contains the trailing slash).
    //
    switch (t)
    {
    case repository_type::pkg:
    case repository_type::dir:
    case repository_type::git:
      {
        if (!up.to_directory ())
          up = path_cast<dir_path> (move (up));
        break;
      }
    }

    if (remote ())
    {
      canonical_name_ = to_string (type_);
      canonical_name_ += ':';
      canonical_name_ += strip_domain (url_.authority->host, type_);

      // For canonical name and for the HTTP protocol, treat a.com and
      // a.com:80 as the same name. The same rule applies to the HTTPS (port
      // 443), GIT (port 9418), and SSH (port 22) protocols.
      //
      uint16_t port (url_.authority->port);
      if (port != 0)
      {
        uint16_t def_port (0);

        switch (url_.scheme)
        {
        case repository_protocol::http:  def_port =   80; break;
        case repository_protocol::https: def_port =  443; break;
        case repository_protocol::git:   def_port = 9418; break;
        case repository_protocol::ssh:   def_port =   22; break;
        case repository_protocol::file:  assert (false); // Can't be here.
        }

        if (port != def_port)
          canonical_name_ += ':' + to_string (port);
      }
    }
    else
    {
      // Complete if we are relative and have base.
      //
      if (!b.empty () && up.relative ())
      {
        // Convert the relative path location to an absolute or remote one.
        //
        repository_url u (b.url ());
        *u.path /= up;

        // Override the base repository fragment.
        //
        u.fragment = move (url_.fragment);

        url_ = move (u);

        // Set canonical name to the base location canonical name 'pkg:<host>'
        // part. The '<path>[#<fragment>]' part of the canonical name is
        // calculated below.
        //
        if (b.remote ())
          canonical_name_ =
            b.canonical_name_.substr (0,
                                      b.canonical_name_.find_first_of ("/#"));
      }
    }

    // Normalize path to avoid different representations of the same location
    // and canonical name. So a/b/../c/1/x/../y and a/c/1/y to be considered
    // as same location.
    //
    // Note that we need to collapse 'example.com/a/..' to 'example.com/',
    // rather than to 'example.com/.'.
    //
    try
    {
      up.normalize (false /* actual */, remote () /* cur_empty */);
    }
    catch (const invalid_path&)
    {
      throw invalid_argument ("invalid path");
    }

    // For pkg repository we need to check path for emptiness before
    // proceeding further as a valid non empty location can not have an empty
    // URL object path member (which can be the case for the remote location,
    // but not for the relative or absolute).
    //
    if (type_ == repository_type::pkg && up.empty ())
      throw invalid_argument ("empty path");

    // Need to check that URL path do not go past the root directory of a WEB
    // server. We can not rely on the above normalize() function call doing
    // this check as soon as URL object path member contains a relative
    // directory for the remote location.
    //
    if (remote () && !up.empty () && *up.begin () == "..")
      throw invalid_argument ("invalid path");

    // Finish calculating the canonical name, unless we are relative.
    //
    if (relative ())
    {
      assert (canonical_name_.empty ());
      return;
    }

    // Canonical name part that is produced from the repository location path
    // part. The algorithm depends on the repository type.
    //
    path sp;

    // Convert the local repository location path to lower case on Windows.
    //
    // Note that we need to do that prior to stripping the special path
    // components to match them case-insensitively, so, for example, the
    // c:\pkg\1\stable and c:\Pkg\1\stable (or c:\repo.git and c:\repo.Git)
    // repository locations end up with the same canonical name.
    //
    #ifdef _WIN32
    const path& p (local () ? path (lcase (up.string ())) : up);
    #else
    const path& p (up);
    #endif

    switch (type_)
    {
    case repository_type::pkg:
      {
        // Produce the pkg repository canonical name <prefix>/<path> part (see
        // the Repository Chaining documentation for more details).
        //
        sp = strip_path (p,
                         remote ()
                         ? strip_mode::component
                         : strip_mode::path);

        // If for an absolute path location the stripping result is empty
        // (which also means <path> part is empty as well) then fallback to
        // stripping just the version component.
        //
        if (absolute () && sp.empty ())
          sp = strip_path (p, strip_mode::version);

        break;
      }
    case repository_type::dir:
      {
        // For dir repository we use the absolute (normalized) path.
        //
        sp = p;
        break;
      }
    case repository_type::git:
      {
        // For git repository we use the absolute (normalized) path, stripping
        // the .git extension if present.
        //
        sp = strip_path (p, strip_mode::extension);
        break;
      }
    }

    string cp (sp.relative () ? sp.posix_string () : sp.string ());

    // Don't allow canonical names without both host and path parts.
    //
    if (canonical_name_.empty () && cp.empty ())
      throw invalid_argument ("empty repository name");

    // Note: allow empty paths (e.g., http://stable.cppget.org/1/).
    //
    if (!cp.empty ())
    {
      if (!canonical_name_.empty ()) // If we have host and dir.
        canonical_name_ += '/';
      else                           // If we have just dir.
      {
        canonical_name_ = to_string (type_);
        canonical_name_ += ':';
      }
    }

    canonical_name_ += cp;

    if (url_.fragment)
    {
      canonical_name_ += '#';
      canonical_name_ += *url_.fragment;
    }
  }

  string repository_location::
  string () const
  {
    if (empty ()    ||
        relative () ||
        guess_type (url_, false /* local */) == type_)
      return url_.string ();

    std::string r (to_string (type_) + '+');

    // Enforce the 'file://' notation for local URLs, adding the empty
    // authority (see manifest.hxx for details).
    //
    if (url_.scheme == repository_protocol::file &&
        !url_.authority                          &&
        !url_.fragment)
    {
      repository_url u (url_.scheme,
                        repository_url::authority_type (),
                        url_.path);

      r += u.string ();
    }
    else
      r += url_.string ();

    return r;
  }

  // git_ref_filter
  //
  git_ref_filter::
  git_ref_filter (const string& rf)
  {
    exclusion = rf[0] == '-';

    // Strip the leading +/-.
    //
    const string& s (exclusion || rf[0] == '+' ? string (rf, 1) : rf);

    size_t p (s.find ('@'));

    if (p != string::npos)
    {
      if (p != 0)
        name = string (s, 0, p);

      if (p + 1 != s.size ())
        commit = string (s, p + 1);
    }
    else if (!s.empty ())
    {
      // A 40-characters fragment that consists of only hexadecimal digits is
      // assumed to be a commit id.
      //
      if (s.size () == 40 &&
          find_if_not (s.begin (), s.end (),

                       // Resolve the required overload.
                       //
                       static_cast<bool (*)(char)> (xdigit)) == s.end ())
        commit = s;
      else
        name = s;
    }

    if (!name && !commit)
      throw invalid_argument (
        "missing refname or commit id for git repository");

    if (commit && commit->size () != 40)
      throw invalid_argument (
        "git repository commit id must be 40 characters long");
  }

  git_ref_filters
  parse_git_ref_filters (const optional<string>& fs)
  {
    if (!fs)
      return git_ref_filters ({git_ref_filter ()});

    const string& s (*fs);

    git_ref_filters r;
    bool def (s[0] == '#');

    if (def)
      r.push_back (git_ref_filter ());

    for (size_t p (def ? 1 : 0); p != string::npos; )
    {
      size_t e (s.find (',', p));
      r.emplace_back (string (s, p, e != string::npos ? e - p : e));
      p = e != string::npos ? e + 1 : e;
    }
    return r;
  }

  // repository_manifest
  //
  optional<string> repository_manifest::
  effective_url (const repository_location& l) const
  {
    static const char* invalid_location ("invalid repository location");

    if (l.local ())
      throw invalid_argument (invalid_location);

    if (l.type () != repository_type::pkg || !url || (*url)[0] != '.')
      return url;

    const path rp (*url);
    auto i (rp.begin ());

    static const char* invalid_url ("invalid relative url");

    auto strip = [&i, &rp]() -> bool
    {
      if (i != rp.end ())
      {
        const auto& c (*i++);
        if (c == "..")
          return true;

        if (c == ".")
          return false;
      }

      throw invalid_argument (invalid_url);
    };

    bool strip_d (strip ()); // Strip domain.
    bool strip_p (strip ()); // Strip path.

    // The web interface relative path with the special first two components
    // stripped.
    //
    const path rpath (i, rp.end ());
    assert (rpath.relative ());

    repository_url u (l.url ());

    if (strip_d)
      u.authority->host.value = strip_domain (u.authority->host,
                                              repository_type::pkg);

    // Web interface URL path part.
    //
    // It is important to call strip_path() before appending the relative
    // path. Otherwise the effective URL for the path ./../../.. and the
    // repository location http://a.com/foo/pkg/1/math will wrongly be
    // http://a.com/foo/pkg instead of http://a.com.
    //
    path ipath (strip_path (*u.path,
                            strip_p
                            ? strip_mode::component
                            : strip_mode::version) /
                rpath);

    try
    {
      ipath.normalize (false /* actual */, true /* cur_empty */);
    }
    catch (const invalid_path&)
    {
      throw invalid_argument (invalid_location);
    }

    assert (ipath.relative ());

    if (!ipath.empty () && *ipath.begin () == "..")
      throw invalid_argument (invalid_location);

    // Strip the trailing slash for an empty path.
    //
    u.path = !ipath.empty () ? move (ipath) : optional<path> ();
    return u.string ();
  }

  static repository_manifest
  parse_repository_manifest (parser& p,
                             name_value nv,
                             repository_type base_type,
                             bool iu,
                             bool verify_version = true)
  {
    auto bad_name ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.name_line, nv.name_column, d);});

    auto bad_value ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.value_line, nv.value_column, d);});

    // Make sure this is the start and we support the version.
    //
    if (verify_version)
    {
      if (!nv.name.empty ())
        bad_name ("start of repository manifest expected");

      if (nv.value != "1")
        bad_value ("unsupported format version");

      nv = p.next ();
    }

    repository_manifest r;

    // The repository type value can go after the location value. So we need to
    // postpone the location value parsing until we went though all other
    // values.
    //
    optional<repository_type> type;
    optional<name_value> location;

    for (; !nv.empty (); nv = p.next ())
    {
      string& n (nv.name);
      string& v (nv.value);

      if (n == "location")
      {
        if (location)
          bad_name ("location redefinition");

        if (v.empty ())
          bad_value ("empty location");

        location = move (nv);
      }
      else if (n == "type")
      {
        if (type)
          bad_name ("type redefinition");

        try
        {
          type = to_repository_type (v);
        }
        catch (const invalid_argument& e)
        {
          bad_value (e.what ());
        }
      }
      else if (n == "role")
      {
        if (r.role)
          bad_name ("role redefinition");

        auto b (repository_role_names.cbegin ());
        auto e (repository_role_names.cend ());
        auto i (find (b, e, v));

        if (i == e)
          bad_value ("unrecognized role");

        r.role = static_cast<repository_role> (i - b);
      }
      else if (n == "url")
      {
        if (r.url)
          bad_name ("url redefinition");

        if (v.empty ())
          bad_value ("empty url");

        r.url = move (v);
      }
      else if (n == "email")
      {
        if (r.email)
          bad_name ("email redefinition");

        auto vc (parser::split_comment (v));

        if (vc.first.empty ())
          bad_value ("empty email");

        r.email = email (move (vc.first), move (vc.second));
      }
      else if (n == "summary")
      {
        if (r.summary)
          bad_name ("summary redefinition");

        if (v.empty ())
          bad_value ("empty summary");

        r.summary = move (v);
      }
      else if (n == "description")
      {
        if (r.description)
          bad_name ("description redefinition");

        if (v.empty ())
          bad_value ("empty description");

        r.description = move (v);
      }
      else if (n == "certificate")
      {
        if (base_type != repository_type::pkg)
          bad_name ("certificate not allowed");

        if (r.certificate)
          bad_name ("certificate redefinition");

        if (v.empty ())
          bad_value ("empty certificate");

        r.certificate = move (v);
      }
      else if (n == "trust")
      {
        if (r.trust)
          bad_name ("trust redefinition");

        if (!valid_fingerprint (v))
          bad_value ("invalid fingerprint");

        r.trust = move (v);
      }
      else if (n == "fragment")
      {
        if (r.fragment)
          bad_name ("fragment redefinition");

        if (v.empty ())
          bad_value ("empty fragment");

        r.fragment = move (v);
      }
      else if (!iu)
        bad_name ("unknown name '" + n + "' in repository manifest");
    }

    // Parse location.
    //
    if (location)
    try
    {
      repository_url u (move (location->value));

      if (!type)
        type = guess_type (u, false); // Can't throw.

      // Call prerequisite repository location constructor, do not amend
      // relative path.
      //
      r.location = repository_location (u, *type, repository_location ());
    }
    catch (const invalid_argument& e)
    {
      nv = move (*location); // Restore as bad_value() uses its line/column.
      bad_value (e.what ());
    }

    // Verify that all non-optional values were specified and the optional ones
    // are allowed.
    //
    // - location can be omitted
    // - role can be omitted
    // - trust, url, email, summary, description and certificate are allowed
    //
    bool base (r.effective_role () == repository_role::base);

    if (r.location.empty () != base)
      bad_value (r.location.empty ()
                 ? "no location specified"
                 : "location not allowed");

    if (r.trust && (base || r.location.type () != repository_type::pkg))
      bad_value ("trust not allowed");

    if (!base)
    {
      if (r.url)
        bad_value ("url not allowed");

      if (r.email)
        bad_value ("email not allowed");

      if (r.summary)
        bad_value ("summary not allowed");

      if (r.description)
        bad_value ("description not allowed");

      if (r.certificate)
        bad_value ("certificate not allowed");
    }

    return r;
  }

  static repository_manifest
  parse_repository_manifest (parser& p, repository_type base_type, bool iu)
  {
    repository_manifest r (
      parse_repository_manifest (p, p.next (), base_type, iu));

    // Make sure this is the end.
    //
    name_value nv (p.next ());
    if (!nv.empty ())
      throw parsing (p.name (), nv.name_line, nv.name_column,
                     "single repository manifest expected");

    return r;
  }

  void repository_manifest::
  serialize (serializer& s) const
  {
    auto bad_value ([&s](const string& d) {
        throw serialization (s.name (), d);});

    bool b (effective_role () == repository_role::base);

    if (location.empty () != b)
      bad_value (
        location.empty () ? "no location specified" : "location not allowed");

    s.next ("", "1"); // Start of manifest.

    // Note that the location can be relative, so we also serialize the
    // repository type.
    //
    if (!location.empty ())
    {
      s.next ("location", location.string ());
      s.next ("type", to_string (location.type ()));
    }

    if (role)
    {
      auto r (static_cast<size_t> (*role));
      assert (r < repository_role_names.size ());
      s.next ("role", repository_role_names[r]);
    }

    if (url)
    {
      if (!b)
        bad_value ("url not allowed");

      s.next ("url", *url);
    }

    if (email)
    {
      if (!b)
        bad_value ("email not allowed");

      s.next ("email", serializer::merge_comment (*email, email->comment));
    }

    if (summary)
    {
      if (!b)
        bad_value ("summary not allowed");

      s.next ("summary", *summary);
    }

    if (description)
    {
      if (!b)
        bad_value ("description not allowed");

      s.next ("description", *description);
    }

    if (certificate)
    {
      if (!b)
        bad_value ("certificate not allowed");

      s.next ("certificate", *certificate);
    }

    if (trust)
    {
      assert (b || !location.empty ());

      if (b || location.type () != repository_type::pkg)
        bad_value ("trust not allowed");

      s.next ("trust", *trust);
    }

    if (fragment)
      s.next ("fragment", *fragment);

    s.next ("", ""); // End of manifest.
  }

  static repository_manifest empty_base;

  const repository_manifest&
  find_base_repository (const vector<repository_manifest>& ms) noexcept
  {
    for (const repository_manifest& m: ms)
    {
      if (m.effective_role () == repository_role::base)
        return m;
    }

    return empty_base;
  }

  // pkg_repository_manifest
  //
  repository_manifest
  pkg_repository_manifest (parser& p, bool iu)
  {
    return parse_repository_manifest (p, repository_type::pkg, iu);
  }

  repository_manifest
  pkg_repository_manifest (parser& p, name_value nv, bool iu)
  {
    return parse_repository_manifest (p, nv, repository_type::pkg, iu);
  }

  // dir_repository_manifest
  //
  repository_manifest
  dir_repository_manifest (parser& p, bool iu)
  {
    return parse_repository_manifest (p, repository_type::dir, iu);
  }

  repository_manifest
  dir_repository_manifest (parser& p, name_value nv, bool iu)
  {
    return parse_repository_manifest (p, nv, repository_type::dir, iu);
  }

  // git_repository_manifest
  //
  repository_manifest
  git_repository_manifest (parser& p, bool iu)
  {
    return parse_repository_manifest (p, repository_type::git, iu);
  }

  repository_manifest
  git_repository_manifest (parser& p, name_value nv, bool iu)
  {
    return parse_repository_manifest (p, nv, repository_type::git, iu);
  }

  // Parse the repository manifest list.
  //
  static void
  parse_repository_manifests (parser& p,
                              repository_type base_type,
                              bool iu,
                              optional<repositories_manifest_header>& header,
                              vector<repository_manifest>& ms)
  {
    // Return nullopt on eos. Otherwise, parse and verify the
    // manifest-starting format version value and return the subsequent
    // manifest value, that can potentially be empty (for an empty manifest).
    //
    // Also save the manifest-starting position (start_nv) for the
    // diagnostics.
    //
    name_value start_nv;
    auto next_manifest = [&p, &start_nv] () -> optional<name_value>
    {
      start_nv = p.next ();

      if (start_nv.empty ())
        return nullopt;

      // Make sure this is the start and we support the version.
      //
      if (!start_nv.name.empty ())
        throw parsing (p.name (), start_nv.name_line, start_nv.name_column,
                       "start of repository manifest expected");

      if (start_nv.value != "1")
        throw parsing (p.name (), start_nv.value_line, start_nv.value_column,
                       "unsupported format version");

      return p.next ();
    };

    optional<name_value> nv (next_manifest ());

    if (!nv)
      throw parsing (p.name (), start_nv.name_line, start_nv.name_column,
                     "start of repository manifest expected");

    auto bad_name ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv->name_line, nv->name_column, d);});

    auto bad_value ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv->value_line, nv->value_column, d);});

    // First check if this a header manifest, if any manifest is present.
    //
    // Note that if this is none of the known header values, then we assume
    // this is a repository manifest (rather than a header that starts with an
    // unknown value; so use one of the original names to make sure it's
    // recognized as such, for example `compression:none`).
    //
    if (nv->name == "min-bpkg-version" ||
        nv->name == "compression")
    {
      header = repositories_manifest_header ();

      // First verify the version, if any.
      //
      if (nv->name == "min-bpkg-version")
      try
      {
        const string& v (nv->value);
        standard_version mbv (v, standard_version::allow_earliest);

        if (mbv > standard_version (LIBBPKG_VERSION_STR))
          bad_value (
            "incompatible repositories manifest: minimum bpkg version is " + v);

        header->min_bpkg_version = move (mbv);

        nv = p.next ();
      }
      catch (const invalid_argument& e)
      {
        bad_value (string ("invalid minimum bpkg version: ") + e.what ());
      }

      // Parse the remaining header values, failing if min-bpkg-version is
      // encountered (should be first).
      //
      for (; !nv->empty (); nv = p.next ())
      {
        const string& n (nv->name);
        string& v (nv->value);

        if (n == "min-bpkg-version")
        {
          bad_name ("minimum bpkg version must be first in repositories "
                    "manifest header");
        }
        else if (n == "compression")
        {
          header->compression = move (v);
        }
        else if (!iu)
          bad_name ("unknown name '" + n + "' in repositories manifest header");
      }

      nv = next_manifest ();
    }

    // Parse the manifest list.
    //
    // Note that if nv is present, then it contains the manifest's first
    // value, which can potentially be empty (for an empty manifest, which is
    // recognized as a base manifest).
    //
    // Also note that if the header is present but is not followed by
    // repository manifests (there is no ':' line after the header values),
    // then the empty manifest list is returned (no base manifest is
    // automatically added).
    //
    bool base (false);

    while (nv)
    {
      ms.push_back (parse_repository_manifest (p,
                                               *nv,
                                               base_type,
                                               iu,
                                               false /* verify_version */));

      // Make sure that there is a single base repository manifest in the
      // list.
      //
      if (ms.back ().effective_role () == repository_role::base)
      {
        if (base)
          throw parsing (p.name (), start_nv.name_line, start_nv.name_column,
                         "base repository manifest redefinition");
        base = true;
      }

      nv = next_manifest ();
    }
  }

  // Serialize the repository manifest list.
  //
  static void
  serialize_repository_manifests (
    serializer& s,
    const optional<repositories_manifest_header>& header,
    const vector<repository_manifest>& ms)
  {
    if (header)
    {
      s.next ("", "1"); // Start of manifest.

      const repositories_manifest_header& h (*header);

      if (h.min_bpkg_version)
        s.next ("min-bpkg-version", h.min_bpkg_version->string ());

      if (h.compression)
        s.next ("compression", *h.compression);

      s.next ("", ""); // End of manifest.
    }

    for (const repository_manifest& r: ms)
      r.serialize (s);

    s.next ("", ""); // End of stream.
  }

  // pkg_repository_manifests
  //
  pkg_repository_manifests::
  pkg_repository_manifests (parser& p, bool iu)
  {
    parse_repository_manifests (p, repository_type::pkg, iu, header, *this);
  }

  void pkg_repository_manifests::
  serialize (serializer& s) const
  {
    serialize_repository_manifests (s, header, *this);
  }

  // dir_repository_manifests
  //
  dir_repository_manifests::
  dir_repository_manifests (parser& p, bool iu)
  {
    parse_repository_manifests (p, repository_type::dir, iu, header, *this);
  }

  void dir_repository_manifests::
  serialize (serializer& s) const
  {
    serialize_repository_manifests (s, header, *this);
  }

  // git_repository_manifests
  //
  git_repository_manifests::
  git_repository_manifests (parser& p, bool iu)
  {
    parse_repository_manifests (p, repository_type::git, iu, header, *this);
  }

  void git_repository_manifests::
  serialize (serializer& s) const
  {
    serialize_repository_manifests (s, header, *this);
  }

  // signature_manifest
  //
  signature_manifest::
  signature_manifest (parser& p, bool iu)
      : signature_manifest (p, p.next (), iu) // Delegate
  {
    // Make sure this is the end.
    //
    name_value nv (p.next ());
    if (!nv.empty ())
      throw parsing (p.name (), nv.name_line, nv.name_column,
                     "single signature manifest expected");
  }

  signature_manifest::
  signature_manifest (parser& p, name_value nv, bool iu)
  {
    auto bad_name ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.name_line, nv.name_column, d);});

    auto bad_value ([&p, &nv](const string& d) {
        throw parsing (p.name (), nv.value_line, nv.value_column, d);});

    // Make sure this is the start and we support the version.
    //
    if (!nv.name.empty ())
      bad_name ("start of signature manifest expected");

    if (nv.value != "1")
      bad_value ("unsupported format version");

    for (nv = p.next (); !nv.empty (); nv = p.next ())
    {
      string& n (nv.name);
      string& v (nv.value);

      if (n == "sha256sum")
      {
        if (!sha256sum.empty ())
          bad_name ("sha256sum redefinition");

        if (v.empty ())
          bad_value ("empty sha256sum");

        if (!valid_sha256 (v))
          bad_value ("invalid sha256sum");

        sha256sum = move (v);
      }
      else if (n == "signature")
      {
        if (!signature.empty ())
          bad_name ("signature redefinition");

        if (v.empty ())
          bad_value ("empty signature");

        // Try to base64-decode as a sanity check.
        //
        try
        {
          signature = base64_decode (v);
        }
        catch (const invalid_argument&)
        {
          bad_value ("invalid signature");
        }
      }
      else if (!iu)
        bad_name ("unknown name '" + n + "' in signature manifest");
    }

    // Verify all non-optional values were specified.
    //
    if (sha256sum.empty ())
      bad_value ("no sha256sum specified");
    else if (signature.empty ())
      bad_value ("no signature specified");

    // Make sure this is the end.
    //
    nv = p.next ();
    if (!nv.empty ())
      throw parsing (p.name (), nv.name_line, nv.name_column,
                     "single signature manifest expected");
  }

  void signature_manifest::
  serialize (serializer& s) const
  {
    // @@ Should we check that values are valid ?
    //
    s.next ("", "1"); // Start of manifest.

    s.next ("sha256sum", sha256sum);
    s.next ("signature", base64_encode (signature));

    s.next ("", ""); // End of manifest.
  }

  // extract_package_*()
  //
  package_name
  extract_package_name (const char* s, bool allow_version)
  {
    if (!allow_version)
      return package_name (s);

    // Calculate the package name length as a length of the prefix that
    // doesn't contain spaces, slashes and the version constraint starting
    // characters. Note that none of them are valid package name characters.
    //
    size_t n (strcspn (s, " /=<>([~^"));
    return package_name (string (s, n));
  }

  version
  extract_package_version (const char* s, bool fold_zero_revision)
  {
    using traits = string::traits_type;

    if (const char* p = traits::find (s, traits::length (s), '/'))
    {
      version r (p + 1, fold_zero_revision);

      if (r.release && r.release->empty ())
        throw invalid_argument ("earliest version");

      if (r.compare (stub_version, true /* ignore_revision */) == 0)
        throw invalid_argument ("stub version");

      return r;
    }

    return version ();
  }
}