File: roster.cc

package info (click to toggle)
monotone 0.31-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 20,680 kB
  • ctags: 14,801
  • sloc: cpp: 87,711; ansic: 64,862; sh: 5,691; lisp: 954; perl: 783; makefile: 509; python: 265; sql: 98; sed: 16
file content (4905 lines) | stat: -rw-r--r-- 154,571 bytes parent folder | download
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
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
// Copyright (C) 2005 Nathaniel Smith <njs@pobox.com>
//
// This program is made available under the GNU GPL version 2.0 or
// greater. See the accompanying file COPYING for details.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.

#include <algorithm>
#include <stack>
#include <set>
#include <string>
#include <vector>
#include <sstream>

#include "app_state.hh"
#include "basic_io.hh"
#include "cset.hh"
#include "platform-wrapped.hh"
#include "roster.hh"
#include "revision.hh"
#include "vocab.hh"
#include "transforms.hh"
#include "simplestring_xform.hh"
#include "localized_file_io.hh"
#include "parallel_iter.hh"
#include "restrictions.hh"
#include "safe_map.hh"
#include "ui.hh"

#include <boost/lexical_cast.hpp>

using std::inserter;
using std::make_pair;
using std::map;
using std::ostringstream;
using std::pair;
using std::reverse;
using std::set;
using std::set_union;
using std::stack;
using std::string;
using std::vector;

using boost::lexical_cast;

///////////////////////////////////////////////////////////////////

template <> void
dump(full_attr_map_t const & val, string & out)
{
  ostringstream oss;
  for (full_attr_map_t::const_iterator i = val.begin(); i != val.end(); ++i)
    oss << "attr key: '" << i->first << "'\n"
        << "  status: " << (i->second.first ? "live" : "dead") << "\n"
        << "   value: '" << i->second.second << "'\n";
  out = oss.str();
}

template <> void
dump(set<revision_id> const & revids, string & out)
{
  out.clear();
  bool first = true;
  for (set<revision_id>::const_iterator i = revids.begin();
       i != revids.end(); ++i)
    {
      if (!first)
        out += ", ";
      first = false;
      out += i->inner()();
    }
}

template <> void
dump(marking_t const & marking, string & out)
{
  ostringstream oss;
  string tmp;
  oss << "birth_revision: " << marking.birth_revision << "\n";
  dump(marking.parent_name, tmp);
  oss << "parent_name: " << tmp << "\n";
  dump(marking.file_content, tmp);
  oss << "file_content: " << tmp << "\n";
  oss << "attrs (number: " << marking.attrs.size() << "):\n";
  for (map<attr_key, set<revision_id> >::const_iterator
         i = marking.attrs.begin(); i != marking.attrs.end(); ++i)
    {
      dump(i->second, tmp);
      oss << "  " << i->first << ": " << tmp << "\n";
    }
  out = oss.str();
}

template <> void
dump(marking_map const & markings, string & out)
{
  ostringstream oss;
  for (marking_map::const_iterator i = markings.begin();
       i != markings.end();
       ++i)
    {
      oss << "Marking for " << i->first << ":\n";
      string marking_str, indented_marking_str;
      dump(i->second, marking_str);
      prefix_lines_with("    ", marking_str, indented_marking_str);
      oss << indented_marking_str << "\n";
    }
  out = oss.str();
}

namespace
{
  //
  // We have a few concepts of "nullness" here:
  //
  // - the_null_node is a node_id. It does not correspond to a real node;
  //   it's an id you use for the parent of the root, or of any node which
  //   is detached.
  //
  // - the_null_component is a path_component. It is the *name* of the root
  //   node. Its string representation is "", the empty string.
  //
  // - The split_path corresponding to the_null_node is [], the empty vector.
  //
  // - The split_path corresponding to the root node is [""], the 1-element
  //   vector containing the_null_component.
  //
  // - The split_path corresponding to foo/bar is ["", "foo", "bar"].
  //
  // - The only legal one-element split_path is [""], referring to the
  //   root node.
  //
  // We do this in order to support the notion of moving the root directory
  // around, or applying attributes to the root directory (though we will
  // not support moving the root at this time, since we haven't worked out
  // all the UI implications yet).
  //


  const node_id first_node = 1;
  const node_id first_temp_node = widen<node_id, int>(1) << (sizeof(node_id) * 8 - 1);
  inline bool temp_node(node_id n)
  {
    return n & first_temp_node;
  }
}


node::node(node_id i)
  : self(i),
    parent(the_null_node),
    name(the_null_component)
{
}


node::node()
  : self(the_null_node),
    parent(the_null_node),
    name(the_null_component)
{
}


dir_node::dir_node(node_id i)
  : node(i)
{
}


dir_node::dir_node()
  : node()
{
}


bool
dir_node::has_child(path_component const & pc) const
{
  return children.find(pc) != children.end();
}

node_t
dir_node::get_child(path_component const & pc) const
{
  return safe_get(children, pc);
}


void
dir_node::attach_child(path_component const & pc, node_t child)
{
  I(null_node(child->parent));
  I(null_name(child->name));
  safe_insert(children, make_pair(pc, child));
  child->parent = this->self;
  child->name = pc;
}


node_t
dir_node::detach_child(path_component const & pc)
{
  node_t n = get_child(pc);
  n->parent = the_null_node;
  n->name = the_null_component;
  safe_erase(children, pc);
  return n;
}


node_t
dir_node::clone()
{
  dir_t d = dir_t(new dir_node(self));
  d->parent = parent;
  d->name = name;
  d->attrs = attrs;
  d->children = children;
  return d;
}


file_node::file_node(node_id i, file_id const & f)
  : node(i),
    content(f)
{
}


file_node::file_node()
  : node()
{
}


node_t
file_node::clone()
{
  file_t f = file_t(new file_node(self, content));
  f->parent = parent;
  f->name = name;
  f->attrs = attrs;
  return f;
}

template <> void
dump(node_t const & n, string & out)
{
  ostringstream oss;
  string name;
  dump(n->name, name);
  oss << "address: " << n << " (uses: " << n.use_count() << ")\n"
      << "self: " << n->self << "\n"
      << "parent: " << n->parent << "\n"
      << "name: " << name << "\n";
  string attr_map_s;
  dump(n->attrs, attr_map_s);
  oss << "attrs:\n" << attr_map_s;
  oss << "type: ";
  if (is_file_t(n))
    oss << "file\n"
        << "content: " << downcast_to_file_t(n)->content << "\n";
  else
    {
      oss << "dir\n";
      dir_map const & c = downcast_to_dir_t(n)->children;
      oss << "children: " << c.size() << "\n";
      for (dir_map::const_iterator i = c.begin(); i != c.end(); ++i)
        {
          dump(i->first, name);
          oss << "  " << name << " -> " << i->second << "\n";
        }
    }
  out = oss.str();
}

// helper
void
roster_t::do_deep_copy_from(roster_t const & other)
{
  MM(*this);
  MM(other);
  I(!root_dir);
  I(nodes.empty());
  for (node_map::const_iterator i = other.nodes.begin(); i != other.nodes.end();
       ++i)
    safe_insert(nodes, make_pair(i->first, i->second->clone()));
  for (node_map::iterator i = nodes.begin(); i != nodes.end(); ++i)
    if (is_dir_t(i->second))
      {
        dir_map & children = downcast_to_dir_t(i->second)->children;
        for (dir_map::iterator j = children.begin(); j != children.end(); ++j)
          j->second = safe_get(nodes, j->second->self);
      }
  if (other.root_dir)
    root_dir = downcast_to_dir_t(safe_get(nodes, other.root_dir->self));
}

roster_t::roster_t(roster_t const & other)
{
  do_deep_copy_from(other);
}

roster_t &
roster_t::operator=(roster_t const & other)
{
  root_dir.reset();
  nodes.clear();
  do_deep_copy_from(other);
  return *this;
}


struct
dfs_iter
{

  dir_t root;
  bool return_root;
  stack< pair<dir_t, dir_map::const_iterator> > stk;


  dfs_iter(dir_t r)
    : root(r), return_root(root)
  {
    if (root && !root->children.empty())
      stk.push(make_pair(root, root->children.begin()));
  }


  bool finished() const
  {
    return (!return_root) && stk.empty();
  }


  node_t operator*() const
  {
    I(!finished());
    if (return_root)
      return root;
    else
      {
        I(!stk.empty());
        return stk.top().second->second;
      }
  }


  void operator++()
  {
    I(!finished());

    if (return_root)
      {
        return_root = false;
        return;
      }

    // we're not finished, so we need to set up so operator* will return the
    // right thing.
    node_t ntmp = stk.top().second->second;
    if (is_dir_t(ntmp))
      {
        dir_t dtmp = downcast_to_dir_t(ntmp);
        stk.push(make_pair(dtmp, dtmp->children.begin()));
      }
    else
      ++(stk.top().second);

    while (!stk.empty()
           && stk.top().second == stk.top().first->children.end())
      {
        stk.pop();
        if (!stk.empty())
          ++stk.top().second;
      }
  }
};


bool
roster_t::has_root() const
{
  return static_cast<bool>(root_dir);
}


inline bool
same_type(node_t a, node_t b)
{
  return is_file_t(a) == is_file_t(b);
}


inline bool
shallow_equal(node_t a, node_t b,
              bool shallow_compare_dir_children)
{
  if (a->self != b->self)
    return false;

  if (a->parent != b->parent)
    return false;

  if (a->name != b->name)
    return false;

  if (a->attrs != b->attrs)
    return false;

  if (! same_type(a,b))
    return false;

  if (is_file_t(a))
    {
      file_t fa = downcast_to_file_t(a);
      file_t fb = downcast_to_file_t(b);
      if (!(fa->content == fb->content))
        return false;
    }
  else
    {
      dir_t da = downcast_to_dir_t(a);
      dir_t db = downcast_to_dir_t(b);

      if (shallow_compare_dir_children)
        {
          if (da->children.size() != db->children.size())
            return false;

          dir_map::const_iterator
            i = da->children.begin(),
            j = db->children.begin();

          while (i != da->children.end() && j != db->children.end())
            {
              if (i->first != j->first)
                return false;
              if (i->second->self != j->second->self)
                return false;
              ++i;
              ++j;
            }
          I(i == da->children.end() && j == db->children.end());
        }
    }
  return true;
}


// FIXME_ROSTERS: why does this do two loops?  why does it pass 'true' to
// shallow_equal?
// -- njs
bool
roster_t::operator==(roster_t const & other) const
{
  node_map::const_iterator i = nodes.begin(), j = other.nodes.begin();
  while (i != nodes.end() && j != other.nodes.end())
    {
      if (i->first != j->first)
        return false;
      if (!shallow_equal(i->second, j->second, true))
        return false;
      ++i;
      ++j;
    }

  if (i != nodes.end() || j != other.nodes.end())
    return false;

  dfs_iter p(root_dir), q(other.root_dir);
  while (! (p.finished() || q.finished()))
    {
      if (!shallow_equal(*p, *q, true))
        return false;
      ++p;
      ++q;
    }

  if (!(p.finished() && q.finished()))
    return false;

  return true;
}


node_t
roster_t::get_node(split_path const & sp) const
{
  split_path dirname;
  path_component basename;
  dirname_basename(sp, dirname, basename);

  MM(sp);
  MM(*this);

  I(has_root());

  if (dirname.empty())
    {
      I(null_name(basename));
      return root_dir;
    }

  dir_t d = root_dir;
  for (split_path::const_iterator i = dirname.begin()+1; i != dirname.end(); ++i)
    d = downcast_to_dir_t(d->get_child(*i));
  return d->get_child(basename);
}

bool
roster_t::has_node(node_id n) const
{
  return nodes.find(n) != nodes.end();
}

bool
roster_t::is_root(node_id n) const
{
  return has_root() && root_dir->self == n;
}

bool
roster_t::has_node(split_path const & sp) const
{
  split_path dirname;
  path_component basename;
  dirname_basename(sp, dirname, basename);

  if (dirname.empty())
    {
      I(null_name(basename));
      return has_root();
    }

  // If we have no root, we *definitely* don't have a non-root path
  if (!has_root())
    return false;

  dir_t d = root_dir;
  for (split_path::const_iterator i = dirname.begin()+1; i != dirname.end(); ++i)
    {
      if (d->children.find(*i) == d->children.end())
        return false;
      node_t child = d->get_child(*i);
      if (!is_dir_t(child))
        return false;
      d = downcast_to_dir_t(child);
    }
  return d->children.find(basename) != d->children.end();
}



node_t
roster_t::get_node(node_id nid) const
{
  return safe_get(nodes, nid);
}


void
roster_t::get_name(node_id nid, split_path & sp) const
{
  I(!null_node(nid));
  sp.clear();
  while (!null_node(nid))
    {
      node_t n = get_node(nid);
      sp.push_back(n->name);
      nid = n->parent;
    }
  reverse(sp.begin(), sp.end());
}


void
roster_t::replace_node_id(node_id from, node_id to)
{
  I(!null_node(from));
  I(!null_node(to));
  node_t n = get_node(from);
  safe_erase(nodes, from);
  safe_insert(nodes, make_pair(to, n));
  n->self = to;

  if (is_dir_t(n))
    {
      dir_t d = downcast_to_dir_t(n);
      for (dir_map::iterator i = d->children.begin(); i != d->children.end(); ++i)
        {
          I(i->second->parent == from);
          i->second->parent = to;
        }
    }
}


// this records the old location into the old_locations member, to prevent the
// same node from being re-attached at the same place.
node_id
roster_t::detach_node(split_path const & pth)
{
  split_path dirname;
  path_component basename;
  dirname_basename(pth, dirname, basename);

  I(has_root());
  if (dirname.empty())
    {
      // detaching the root dir
      I(null_name(basename));
      node_id root_id = root_dir->self;
      safe_insert(old_locations,
                  make_pair(root_id, make_pair(root_dir->parent, root_dir->name)));
      // clear ("reset") the root_dir shared_pointer
      root_dir.reset();
      I(!has_root());
      return root_id;
    }

  dir_t parent = downcast_to_dir_t(get_node(dirname));
  node_id nid = parent->detach_child(basename)->self;
  safe_insert(old_locations,
              make_pair(nid, make_pair(parent->self, basename)));
  I(!null_node(nid));
  return nid;
}

void
roster_t::detach_node(node_id nid)
{
  node_t n = get_node(nid);
  if (null_node(n->parent))
    {
      // detaching the root dir
      I(null_name(n->name));
      safe_insert(old_locations,
                  make_pair(nid, make_pair(n->parent, n->name)));
      root_dir.reset();
      I(!has_root());
    }
  else
    {
      path_component name = n->name;
      dir_t parent = downcast_to_dir_t(get_node(n->parent));
      I(parent->detach_child(name) == n);
      safe_insert(old_locations,
                  make_pair(nid, make_pair(n->parent, name)));
    }
}

void
roster_t::drop_detached_node(node_id nid)
{
  // ensure the node is already detached
  node_t n = get_node(nid);
  I(null_node(n->parent));
  I(null_name(n->name));
  // if it's a dir, make sure it's empty
  if (is_dir_t(n))
    I(downcast_to_dir_t(n)->children.empty());
  // all right, kill it
  safe_erase(nodes, nid);
  // can use safe_erase here, because while not every detached node appears in
  // old_locations, all those that used to be in the tree do.  and you should
  // only ever be dropping nodes that were detached, not nodes that you just
  // created and that have never been attached.
  safe_erase(old_locations, nid);
}


// this creates a node in a detached state, but it does _not_ insert an entry
// for it into the old_locations member, because there is no old_location to
// forbid
node_id
roster_t::create_dir_node(node_id_source & nis)
{
  node_id nid = nis.next();
  create_dir_node(nid);
  return nid;
}
void
roster_t::create_dir_node(node_id nid)
{
  dir_t d = dir_t(new dir_node());
  d->self = nid;
  safe_insert(nodes, make_pair(nid, d));
}


// this creates a node in a detached state, but it does _not_ insert an entry
// for it into the old_locations member, because there is no old_location to
// forbid
node_id
roster_t::create_file_node(file_id const & content, node_id_source & nis)
{
  node_id nid = nis.next();
  create_file_node(content, nid);
  return nid;
}
void
roster_t::create_file_node(file_id const & content, node_id nid)
{
  file_t f = file_t(new file_node());
  f->self = nid;
  f->content = content;
  safe_insert(nodes, make_pair(nid, f));
}

void
roster_t::attach_node(node_id nid, split_path const & dst)
{
  split_path dirname;
  path_component basename;
  dirname_basename(dst, dirname, basename);

  MM(dst);

  if (dirname.empty())
    // attaching the root node
    attach_node(nid, the_null_node, basename);
  else
    attach_node(nid, get_node(dirname)->self, basename);
}

void
roster_t::attach_node(node_id nid, node_id parent, path_component name)
{
  node_t n = get_node(nid);

  I(!null_node(n->self));
  // ensure the node is already detached (as best one can)
  I(null_node(n->parent));
  I(null_name(n->name));

  // this iterator might point to old_locations.end(), because old_locations
  // only includes entries for renames, not new nodes
  map<node_id, pair<node_id, path_component> >::iterator
    i = old_locations.find(nid);

  if (null_node(parent) || null_name(name))
    {
      I(null_node(parent) && null_name(name));
      I(null_node(n->parent));
      I(null_name(n->name));
      I(!has_root());
      root_dir = downcast_to_dir_t(n);
      I(i == old_locations.end() || i->second != make_pair(root_dir->parent,
                                                           root_dir->name));
    }
  else
    {
      dir_t parent_n = downcast_to_dir_t(get_node(parent));
      parent_n->attach_child(name, n);
      I(i == old_locations.end() || i->second != make_pair(n->parent, n->name));
    }

  if (i != old_locations.end())
    old_locations.erase(i);
}

void
roster_t::apply_delta(split_path const & pth,
                      file_id const & old_id,
                      file_id const & new_id)
{
  file_t f = downcast_to_file_t(get_node(pth));
  I(f->content == old_id);
  I(!null_node(f->self));
  I(!(f->content == new_id));
  f->content = new_id;
}

void
roster_t::set_content(node_id nid, file_id const & new_id)
{
  file_t f = downcast_to_file_t(get_node(nid));
  I(!(f->content == new_id));
  f->content = new_id;
}


void
roster_t::clear_attr(split_path const & pth,
                     attr_key const & name)
{
  set_attr(pth, name, make_pair(false, attr_value()));
}

void
roster_t::erase_attr(node_id nid,
                     attr_key const & name)
{
  node_t n = get_node(nid);
  safe_erase(n->attrs, name);
}

void
roster_t::set_attr(split_path const & pth,
                   attr_key const & name,
                   attr_value const & val)
{
  set_attr(pth, name, make_pair(true, val));
}


void
roster_t::set_attr(split_path const & pth,
                   attr_key const & name,
                   pair<bool, attr_value> const & val)
{
  node_t n = get_node(pth);
  I(val.first || val.second().empty());
  I(!null_node(n->self));
  full_attr_map_t::iterator i = n->attrs.find(name);
  if (i == n->attrs.end())
    i = safe_insert(n->attrs, make_pair(name,
                                        make_pair(false, attr_value())));
  I(i->second != val);
  i->second = val;
}

// same as above, but allowing <unknown> -> <dead> transition
void
roster_t::set_attr_unknown_to_dead_ok(node_id nid,
                                      attr_key const & name,
                                      pair<bool, attr_value> const & val)
{
  node_t n = get_node(nid);
  I(val.first || val.second().empty());
  full_attr_map_t::iterator i = n->attrs.find(name);
  if (i != n->attrs.end())
    I(i->second != val);
  n->attrs[name] = val;
}

bool
roster_t::get_attr(split_path const & pth,
                   attr_key const & name,
                   attr_value & val) const
{
  I(has_node(pth));

  node_t n = get_node(pth);
  full_attr_map_t::const_iterator i = n->attrs.find(name);
  if (i != n->attrs.end() && i->second.first)
    {
      val = i->second.second;
      return true;
    }
  return false;
} 


template <> void
dump(roster_t const & val, string & out)
{
  ostringstream oss;
  if (val.root_dir)
    oss << "Root node: " << val.root_dir->self << "\n"
        << "   at " << val.root_dir << ", uses: " << val.root_dir.use_count() << "\n";
  else
    oss << "root dir is NULL\n";
  for (node_map::const_iterator i = val.nodes.begin(); i != val.nodes.end(); ++i)
    {
      oss << "\nNode " << i->first << "\n";
      string node_s;
      dump(i->second, node_s);
      oss << node_s;
    }
  out = oss.str();
}

void
roster_t::check_sane(bool temp_nodes_ok) const
{
  I(has_root());
  node_map::const_iterator ri;

  I(old_locations.empty());

  for (ri = nodes.begin();
       ri != nodes.end();
       ++ri)
    {
      node_id nid = ri->first;
      I(!null_node(nid));
      if (!temp_nodes_ok)
        I(!temp_node(nid));
      node_t n = ri->second;
      I(n->self == nid);
      if (is_dir_t(n))
        {
          if (null_name(n->name) || null_node(n->parent))
            I(null_name(n->name) && null_node(n->parent));
          else
            I(!null_name(n->name) && !null_node(n->parent));
        }
      else
        {
          I(!null_name(n->name) && !null_node(n->parent));
          I(!null_id(downcast_to_file_t(n)->content));
        }
      for (full_attr_map_t::const_iterator i = n->attrs.begin(); i != n->attrs.end(); ++i)
        I(i->second.first || i->second.second().empty());
      if (n != root_dir)
        {
          I(!null_node(n->parent));
          I(downcast_to_dir_t(get_node(n->parent))->get_child(n->name) == n);
        }

    }

  I(has_root());
  size_t maxdepth = nodes.size();
  for (dfs_iter i(root_dir); !i.finished(); ++i)
    {
      I(*i == get_node((*i)->self));
      I(maxdepth-- > 0);
    }
  I(maxdepth == 0);
}

void
roster_t::check_sane_against(marking_map const & markings, bool temp_nodes_ok) const
{

  check_sane(temp_nodes_ok);

  node_map::const_iterator ri;
  marking_map::const_iterator mi;

  for (ri = nodes.begin(), mi = markings.begin();
       ri != nodes.end() && mi != markings.end();
       ++ri, ++mi)
    {
      I(!null_id(mi->second.birth_revision));
      I(!mi->second.parent_name.empty());

      if (is_file_t(ri->second))
        I(!mi->second.file_content.empty());
      else
        I(mi->second.file_content.empty());

      full_attr_map_t::const_iterator rai;
      map<attr_key, set<revision_id> >::const_iterator mai;
      for (rai = ri->second->attrs.begin(), mai = mi->second.attrs.begin();
           rai != ri->second->attrs.end() && mai != mi->second.attrs.end();
           ++rai, ++mai)
        {
          I(rai->first == mai->first);
          I(!mai->second.empty());
        }
      I(rai == ri->second->attrs.end() && mai == mi->second.attrs.end());
      // TODO: attrs
    }

  I(ri == nodes.end() && mi == markings.end());
}


temp_node_id_source::temp_node_id_source()
  : curr(first_temp_node)
{}

node_id
temp_node_id_source::next()
{
    node_id n = curr++;
    I(temp_node(n));
    return n;
}

editable_roster_base::editable_roster_base(roster_t & r, node_id_source & nis)
  : r(r), nis(nis)
{}

node_id
editable_roster_base::detach_node(split_path const & src)
{
  // L(FL("detach_node('%s')") % file_path(src));
  return r.detach_node(src);
}

void
editable_roster_base::drop_detached_node(node_id nid)
{
  // L(FL("drop_detached_node(%d)") % nid);
  r.drop_detached_node(nid);
}

node_id
editable_roster_base::create_dir_node()
{
  // L(FL("create_dir_node()"));
  node_id n = r.create_dir_node(nis);
  // L(FL("create_dir_node() -> %d") % n);
  return n;
}

node_id
editable_roster_base::create_file_node(file_id const & content)
{
  // L(FL("create_file_node('%s')") % content);
  node_id n = r.create_file_node(content, nis);
  // L(FL("create_file_node('%s') -> %d") % content % n);
  return n;
}

void
editable_roster_base::attach_node(node_id nid, split_path const & dst)
{
  // L(FL("attach_node(%d, '%s')") % nid % file_path(dst));
  MM(dst);
  MM(this->r);
  r.attach_node(nid, dst);
}

void
editable_roster_base::apply_delta(split_path const & pth,
                                  file_id const & old_id,
                                  file_id const & new_id)
{
  // L(FL("clear_attr('%s', '%s', '%s')") % file_path(pth) % old_id % new_id);
  r.apply_delta(pth, old_id, new_id);
}

void
editable_roster_base::clear_attr(split_path const & pth,
                                 attr_key const & name)
{
  // L(FL("clear_attr('%s', '%s')") % file_path(pth) % name);
  r.clear_attr(pth, name);
}

void
editable_roster_base::set_attr(split_path const & pth,
                               attr_key const & name,
                               attr_value const & val)
{
  // L(FL("set_attr('%s', '%s', '%s')") % file_path(pth) % name % val);
  r.set_attr(pth, name, val);
}

void
editable_roster_base::commit()
{
}

namespace
{
  struct true_node_id_source
    : public node_id_source
  {
    true_node_id_source(app_state & app) : app(app) {}
    virtual node_id next()
    {
      node_id n = app.db.next_node_id();
      I(!temp_node(n));
      return n;
    }
    app_state & app;
  };


  class editable_roster_for_merge
    : public editable_roster_base
  {
  public:
    set<node_id> new_nodes;
    editable_roster_for_merge(roster_t & r, node_id_source & nis)
      : editable_roster_base(r, nis)
    {}
    virtual node_id create_dir_node()
    {
      node_id nid = this->editable_roster_base::create_dir_node();
      new_nodes.insert(nid);
      return nid;
    }
    virtual node_id create_file_node(file_id const & content)
    {
      node_id nid = this->editable_roster_base::create_file_node(content);
      new_nodes.insert(nid);
      return nid;
    }
  };


  // This handles all the stuff in a_new.
  void unify_roster_oneway(roster_t & a, set<node_id> & a_new,
                           roster_t & b, set<node_id> & b_new,
                           node_id_source & nis)
  {
    for (set<node_id>::const_iterator i = a_new.begin(); i != a_new.end(); ++i)
      {
        node_id const aid = *i;
        split_path sp;
        // SPEEDUP?: climb out only so far as is necessary to find a shared
        // id?  possibly faster (since usually will get a hit immediately),
        // but may not be worth the effort (since it doesn't take that long to
        // get out in any case)
        a.get_name(aid, sp);
        node_id bid = b.get_node(sp)->self;
        if (temp_node(bid))
          {
            node_id new_nid = nis.next();
            // the node_id_source provided to this function must only generate
            // true node ids, because this code was written with the
            // assumption that only true nids would come in or go out, and
            // temp ids are used as an intermediate stage to indicate nodes
            // that need true ids installed.
            // FIXME: make everything work correctly when this node_id_source
            // returns temp ids.  This is needed for workspace merge support.
            // FIXME: having done this, add a test in database_check.cc that
            // for each revision, generates that rev's roster from scratch,
            // and compares it to the one stored in the db.  (Do the
            // comparison using something like equal_up_to_renumbering, except
            // should say if (!temp_node(a) && !temp_node(b)) I(a == b).)
            I(!temp_node(new_nid));
            a.replace_node_id(aid, new_nid);
            b.replace_node_id(bid, new_nid);
            b_new.erase(bid);
          }
        else
          {
            a.replace_node_id(aid, bid);
          }
      }
  }


  void
  union_corpses(roster_t & left, roster_t & right)
  {
    // left and right should be equal, except that each may have some attr
    // corpses that the other does not
    map<node_id, node_t>::const_iterator left_i = left.all_nodes().begin();
    map<node_id, node_t>::const_iterator right_i = right.all_nodes().begin();
    while (left_i != left.all_nodes().end() || right_i != right.all_nodes().end())
      {
        I(left_i->second->self == right_i->second->self);
        parallel::iter<full_attr_map_t> j(left_i->second->attrs,
                                          right_i->second->attrs);
        // we batch up the modifications until the end, so as not to be
        // changing things around under the parallel::iter's feet
        set<attr_key> left_missing, right_missing;
        while (j.next())
          {
            MM(j);
            switch (j.state())
              {
              case parallel::invalid:
                I(false);

              case parallel::in_left:
                // this is a corpse
                I(!j.left_data().first);
                right_missing.insert(j.left_key());
                break;

              case parallel::in_right:
                // this is a corpse
                I(!j.right_data().first);
                left_missing.insert(j.right_key());
                break;

              case parallel::in_both:
                break;
              }
          }
        for (set<attr_key>::const_iterator j = left_missing.begin();
             j != left_missing.end(); ++j)
          safe_insert(left_i->second->attrs,
                      make_pair(*j, make_pair(false, attr_value())));
        for (set<attr_key>::const_iterator j = right_missing.begin();
             j != right_missing.end(); ++j)
          safe_insert(right_i->second->attrs,
                      make_pair(*j, make_pair(false, attr_value())));
        ++left_i;
        ++right_i;
      }
    I(left_i == left.all_nodes().end());
    I(right_i == right.all_nodes().end());
  }

  // After this, left should == right, and there should be no temporary ids.
  // Destroys sets, because that's handy (it has to scan over both, but it can
  // skip some double-scanning)
  void
  unify_rosters(roster_t & left, set<node_id> & left_new,
                roster_t & right, set<node_id> & right_new,
                node_id_source & nis)
  {
    // Our basic problem is this: when interpreting a revision with multiple
    // csets, those csets all give enough information for us to get the same
    // manifest, and even a bit more than that.  However, there is some
    // information that is not exposed at the manifest level, and csets alone
    // do not give us all we need.  This function is responsible taking the
    // two rosters that we get from pure cset application, and fixing them up
    // so that they are wholly identical.

    // The first thing that is missing is identification of files.  If one
    // cset says "add_file" and the other says nothing, then the add_file is
    // not really an add_file.  One of our rosters will have a temp id for
    // this file, and the other will not.  In this case, we replace the temp
    // id with the other side's permanent id.  However, if both csets say
    // "add_file", then this really is a new id; both rosters will have temp
    // ids, and we replace both of them with a newly allocated id.  After
    // this, the two rosters will have identical node_ids at every path.
    unify_roster_oneway(left, left_new, right, right_new, nis);
    unify_roster_oneway(right, right_new, left, left_new, nis);

    // The other thing we need to fix up is attr corpses.  Live attrs are made
    // identical by the csets; but if, say, on one side of a fork an attr is
    // added and then deleted, then one of our incoming merge rosters will
    // have a corpse for that attr, and the other will not.  We need to make
    // sure at both of them end up with the corpse.  This function fixes up
    // that.
    union_corpses(left, right);
  }

  template <typename T> void
  mark_unmerged_scalar(set<revision_id> const & parent_marks,
                       T const & parent_val,
                       revision_id const & new_rid,
                       T const & new_val,
                       set<revision_id> & new_marks)
  {
    I(new_marks.empty());
    if (parent_val == new_val)
      new_marks = parent_marks;
    else
      new_marks.insert(new_rid);
  }

  // This function implements the case.
  //   a   b1
  //    \ /
  //     b2
  void
  mark_won_merge(set<revision_id> const & a_marks,
                 set<revision_id> const & a_uncommon_ancestors,
                 set<revision_id> const & b1_marks,
                 revision_id const & new_rid,
                 set<revision_id> & new_marks)
  {
    for (set<revision_id>::const_iterator i = a_marks.begin();
         i != a_marks.end(); ++i)
      {
        if (a_uncommon_ancestors.find(*i) != a_uncommon_ancestors.end())
          {
            // at least one element of *(a) is not an ancestor of b1
            new_marks.clear();
            new_marks.insert(new_rid);
            return;
          }
      }
    // all elements of *(a) are ancestors of b1; this was a clean merge to b,
    // so copy forward the marks.
    new_marks = b1_marks;
  }

  template <typename T> void
  mark_merged_scalar(set<revision_id> const & left_marks,
                     set<revision_id> const & left_uncommon_ancestors,
                     T const & left_val,
                     set<revision_id> const & right_marks,
                     set<revision_id> const & right_uncommon_ancestors,
                     T const & right_val,
                     revision_id const & new_rid,
                     T const & new_val,
                     set<revision_id> & new_marks)
  {
    I(new_marks.empty());

    // let's not depend on T::operator!= being defined, only on T::operator==
    // being defined.
    bool diff_from_left = !(new_val == left_val);
    bool diff_from_right = !(new_val == right_val);

    // some quick sanity checks
    for (set<revision_id>::const_iterator i = left_marks.begin();
         i != left_marks.end(); ++i)
      I(right_uncommon_ancestors.find(*i) == right_uncommon_ancestors.end());
    for (set<revision_id>::const_iterator i = right_marks.begin();
         i != right_marks.end(); ++i)
      I(left_uncommon_ancestors.find(*i) == left_uncommon_ancestors.end());

    if (diff_from_left && diff_from_right)
      new_marks.insert(new_rid);

    else if (diff_from_left && !diff_from_right)
      mark_won_merge(left_marks, left_uncommon_ancestors, right_marks,
                     new_rid, new_marks);

    else if (!diff_from_left && diff_from_right)
      mark_won_merge(right_marks, right_uncommon_ancestors, left_marks,
                     new_rid, new_marks);

    else
      {
        // this is the case
        //   a   a
        //    \ /
        //     a
        // so we simply union the mark sets.  This is technically not
        // quite the canonical multi-*-merge thing to do; in the case
        //     a1*
        //    / \      (blah blah; avoid multi-line-comment warning)
        //   b   a2
        //   |   |
        //   a3* |
        //    \ /
        //     a4
        // we will set *(a4) = {a1, a3}, even though the minimal
        // common ancestor set is {a3}.  we could fix this by running
        // erase_ancestors.  However, there isn't really any point;
        // the only operation performed on *(a4) is to test *(a4) > R
        // for some revision R.  The truth-value of this test cannot
        // be affected by added new revisions to *(a4) that are
        // ancestors of revisions that are already in *(a4).
        set_union(left_marks.begin(), left_marks.end(),
                  right_marks.begin(), right_marks.end(),
                  inserter(new_marks, new_marks.begin()));
      }
  }

  void
  mark_new_node(revision_id const & new_rid, node_t n, marking_t & new_marking)
  {
    new_marking.birth_revision = new_rid;
    I(new_marking.parent_name.empty());
    new_marking.parent_name.insert(new_rid);
    I(new_marking.file_content.empty());
    if (is_file_t(n))
      new_marking.file_content.insert(new_rid);
    I(new_marking.attrs.empty());
    set<revision_id> singleton;
    singleton.insert(new_rid);
    for (full_attr_map_t::const_iterator i = n->attrs.begin();
         i != n->attrs.end(); ++i)
      new_marking.attrs.insert(make_pair(i->first, singleton));
  }

  void
  mark_unmerged_node(marking_t const & parent_marking, node_t parent_n,
                     revision_id const & new_rid, node_t n,
                     marking_t & new_marking)
  {
    // SPEEDUP?: the common case here is that the parent and child nodes are
    // exactly identical, in which case the markings are also exactly
    // identical.  There might be a win in first doing an overall
    // comparison/copy, in case it can be better optimized as a block
    // comparison and a block copy...

    I(same_type(parent_n, n) && parent_n->self == n->self);

    new_marking.birth_revision = parent_marking.birth_revision;

    mark_unmerged_scalar(parent_marking.parent_name,
                         make_pair(parent_n->parent, parent_n->name),
                         new_rid,
                         make_pair(n->parent, n->name),
                         new_marking.parent_name);

    if (is_file_t(n))
      mark_unmerged_scalar(parent_marking.file_content,
                           downcast_to_file_t(parent_n)->content,
                           new_rid,
                           downcast_to_file_t(n)->content,
                           new_marking.file_content);

    for (full_attr_map_t::const_iterator i = n->attrs.begin();
           i != n->attrs.end(); ++i)
      {
        set<revision_id> & new_marks = new_marking.attrs[i->first];
        I(new_marks.empty());
        full_attr_map_t::const_iterator j = parent_n->attrs.find(i->first);
        if (j == parent_n->attrs.end())
          new_marks.insert(new_rid);
        else
          mark_unmerged_scalar(safe_get(parent_marking.attrs, i->first),
                               j->second,
                               new_rid, i->second, new_marks);
      }
  }

  void
  mark_merged_node(marking_t const & left_marking,
                   set<revision_id> left_uncommon_ancestors,
                   node_t ln,
                   marking_t const & right_marking,
                   set<revision_id> right_uncommon_ancestors,
                   node_t rn,
                   revision_id const & new_rid,
                   node_t n,
                   marking_t & new_marking)
  {
    I(same_type(ln, n) && same_type(rn, n));
    I(left_marking.birth_revision == right_marking.birth_revision);
    new_marking.birth_revision = left_marking.birth_revision;

    // name
    mark_merged_scalar(left_marking.parent_name, left_uncommon_ancestors,
                       make_pair(ln->parent, ln->name),
                       right_marking.parent_name, right_uncommon_ancestors,
                       make_pair(rn->parent, rn->name),
                       new_rid,
                       make_pair(n->parent, n->name),
                       new_marking.parent_name);
    // content
    if (is_file_t(n))
      {
        file_t f = downcast_to_file_t(n);
        file_t lf = downcast_to_file_t(ln);
        file_t rf = downcast_to_file_t(rn);
        mark_merged_scalar(left_marking.file_content, left_uncommon_ancestors,
                           lf->content,
                           right_marking.file_content, right_uncommon_ancestors,
                           rf->content,
                           new_rid, f->content, new_marking.file_content);
      }
    // attrs
    for (full_attr_map_t::const_iterator i = n->attrs.begin();
         i != n->attrs.end(); ++i)
      {
        attr_key const & key = i->first;
        full_attr_map_t::const_iterator li = ln->attrs.find(key);
        full_attr_map_t::const_iterator ri = rn->attrs.find(key);
        I(new_marking.attrs.find(key) == new_marking.attrs.end());
        // [], when used to refer to a non-existent element, default
        // constructs that element and returns a reference to it.  We make use
        // of this here.
        set<revision_id> & new_marks = new_marking.attrs[key];

        if (li == ln->attrs.end() && ri == rn->attrs.end())
          // this is a brand new attribute, never before seen
          safe_insert(new_marks, new_rid);

        else if (li != ln->attrs.end() && ri == rn->attrs.end())
          // only the left side has seen this attr before
          mark_unmerged_scalar(safe_get(left_marking.attrs, key),
                               li->second,
                               new_rid, i->second, new_marks);

        else if (li == ln->attrs.end() && ri != rn->attrs.end())
          // only the right side has seen this attr before
          mark_unmerged_scalar(safe_get(right_marking.attrs, key),
                               ri->second,
                               new_rid, i->second, new_marks);

        else
          // both sides have seen this attr before
          mark_merged_scalar(safe_get(left_marking.attrs, key),
                             left_uncommon_ancestors,
                             li->second,
                             safe_get(right_marking.attrs, key),
                             right_uncommon_ancestors,
                             ri->second,
                             new_rid, i->second, new_marks);
      }

    // some extra sanity checking -- attributes are not allowed to be deleted,
    // so we double check that they haven't.
    // SPEEDUP?: this code could probably be made more efficient -- but very
    // rarely will any node have more than, say, one attribute, so it probably
    // doesn't matter.
    for (full_attr_map_t::const_iterator i = ln->attrs.begin();
         i != ln->attrs.end(); ++i)
      I(n->attrs.find(i->first) != n->attrs.end());
    for (full_attr_map_t::const_iterator i = rn->attrs.begin();
         i != rn->attrs.end(); ++i)
      I(n->attrs.find(i->first) != n->attrs.end());
  }


  // This function is also responsible for verifying ancestry invariants --
  // those invariants on a roster that involve the structure of the roster's
  // parents, rather than just the structure of the roster itself.
  void
  mark_merge_roster(roster_t const & left_roster,
                    marking_map const & left_markings,
                    set<revision_id> const & left_uncommon_ancestors,
                    roster_t const & right_roster,
                    marking_map const & right_markings,
                    set<revision_id> const & right_uncommon_ancestors,
                    revision_id const & new_rid,
                    roster_t const & merge,
                    marking_map & new_markings)
  {
    for (node_map::const_iterator i = merge.all_nodes().begin();
         i != merge.all_nodes().end(); ++i)
      {
        node_t const & n = i->second;
        // SPEEDUP?: instead of using find repeatedly, iterate everything in
        // parallel
        map<node_id, node_t>::const_iterator lni = left_roster.all_nodes().find(i->first);
        map<node_id, node_t>::const_iterator rni = right_roster.all_nodes().find(i->first);

        bool exists_in_left = (lni != left_roster.all_nodes().end());
        bool exists_in_right = (rni != right_roster.all_nodes().end());

        marking_t new_marking;

        if (!exists_in_left && !exists_in_right)
          mark_new_node(new_rid, n, new_marking);

        else if (!exists_in_left && exists_in_right)
          {
            node_t const & right_node = rni->second;
            marking_t const & right_marking = safe_get(right_markings, n->self);
            // must be unborn on the left (as opposed to dead)
            I(right_uncommon_ancestors.find(right_marking.birth_revision)
              != right_uncommon_ancestors.end());
            mark_unmerged_node(right_marking, right_node,
                               new_rid, n, new_marking);
          }
        else if (exists_in_left && !exists_in_right)
          {
            node_t const & left_node = lni->second;
            marking_t const & left_marking = safe_get(left_markings, n->self);
            // must be unborn on the right (as opposed to dead)
            I(left_uncommon_ancestors.find(left_marking.birth_revision)
              != left_uncommon_ancestors.end());
            mark_unmerged_node(left_marking, left_node,
                               new_rid, n, new_marking);
          }
        else
          {
            node_t const & left_node = lni->second;
            node_t const & right_node = rni->second;
            mark_merged_node(safe_get(left_markings, n->self),
                             left_uncommon_ancestors, left_node,
                             safe_get(right_markings, n->self),
                             right_uncommon_ancestors, right_node,
                             new_rid, n, new_marking);
          }

        safe_insert(new_markings, make_pair(i->first, new_marking));
      }
  }


  class editable_roster_for_nonmerge
    : public editable_roster_base
  {
  public:
    editable_roster_for_nonmerge(roster_t & r, node_id_source & nis,
                                 revision_id const & rid,
                                 marking_map & markings)
      : editable_roster_base(r, nis),
        rid(rid), markings(markings)
    {}

    virtual node_id detach_node(split_path const & src)
    {
      node_id nid = this->editable_roster_base::detach_node(src);
      marking_map::iterator marking = markings.find(nid);
      I(marking != markings.end());
      marking->second.parent_name.clear();
      marking->second.parent_name.insert(rid);
      return nid;
    }

    virtual void drop_detached_node(node_id nid)
    {
      this->editable_roster_base::drop_detached_node(nid);
      safe_erase(markings, nid);
    }

    virtual node_id create_dir_node()
    {
      return handle_new(this->editable_roster_base::create_dir_node());
    }

    virtual node_id create_file_node(file_id const & content)
    {
      return handle_new(this->editable_roster_base::create_file_node(content));
    }

    virtual void apply_delta(split_path const & pth,
                             file_id const & old_id, file_id const & new_id)
    {
      this->editable_roster_base::apply_delta(pth, old_id, new_id);
      node_id nid = r.get_node(pth)->self;
      marking_map::iterator marking = markings.find(nid);
      I(marking != markings.end());
      marking->second.file_content.clear();
      marking->second.file_content.insert(rid);
    }

    virtual void clear_attr(split_path const & pth, attr_key const & name)
    {
      this->editable_roster_base::clear_attr(pth, name);
      handle_attr(pth, name);
    }

    virtual void set_attr(split_path const & pth, attr_key const & name,
                          attr_value const & val)
    {
      this->editable_roster_base::set_attr(pth, name, val);
      handle_attr(pth, name);
    }

    node_id handle_new(node_id nid)
    {
      node_t n = r.get_node(nid);
      marking_t new_marking;
      mark_new_node(rid, n, new_marking);
      safe_insert(markings, make_pair(nid, new_marking));
      return nid;
    }

    void handle_attr(split_path const & pth, attr_key const & name)
    {
      node_id nid = r.get_node(pth)->self;
      marking_map::iterator marking = markings.find(nid);
      map<attr_key, set<revision_id> >::iterator am = marking->second.attrs.find(name);
      if (am == marking->second.attrs.end())
        {
          marking->second.attrs.insert(make_pair(name, set<revision_id>()));
          am = marking->second.attrs.find(name);
        }

      I(am != marking->second.attrs.end());
      am->second.clear();
      am->second.insert(rid);
    }

  private:
    revision_id const & rid;
    // markings starts out as the parent's markings
    marking_map & markings;
  };


  // yes, this function takes 14 arguments.  I'm very sorry.
  void
  make_roster_for_merge(revision_id const & left_rid,
                        roster_t const & left_roster,
                        marking_map const & left_markings,
                        cset const & left_cs,
                        set<revision_id> left_uncommon_ancestors,

                        revision_id const & right_rid,
                        roster_t const & right_roster,
                        marking_map const & right_markings,
                        cset const & right_cs,
                        set<revision_id> right_uncommon_ancestors,

                        revision_id const & new_rid,
                        roster_t & new_roster,
                        marking_map & new_markings,
                        node_id_source & nis)
  {
    I(!null_id(left_rid) && !null_id(right_rid));
    I(left_uncommon_ancestors.find(left_rid) != left_uncommon_ancestors.end());
    I(left_uncommon_ancestors.find(right_rid) == left_uncommon_ancestors.end());
    I(right_uncommon_ancestors.find(right_rid) != right_uncommon_ancestors.end());
    I(right_uncommon_ancestors.find(left_rid) == right_uncommon_ancestors.end());
    MM(left_rid);
    MM(left_roster);
    MM(left_markings);
    MM(left_cs);
    MM(left_uncommon_ancestors);
    MM(right_rid);
    MM(right_roster);
    MM(right_markings);
    MM(right_cs);
    MM(right_uncommon_ancestors);
    MM(new_rid);
    MM(new_roster);
    MM(new_markings);
    {
      temp_node_id_source temp_nis;
      new_roster = left_roster;
      roster_t from_right_r(right_roster);
      MM(from_right_r);

      editable_roster_for_merge from_left_er(new_roster, temp_nis);
      editable_roster_for_merge from_right_er(from_right_r, temp_nis);

      left_cs.apply_to(from_left_er);
      right_cs.apply_to(from_right_er);

      set<node_id> new_ids;
      unify_rosters(new_roster, from_left_er.new_nodes,
                    from_right_r, from_right_er.new_nodes,
                    nis);
      I(new_roster == from_right_r);
    }

    // SPEEDUP?: instead of constructing new marking from scratch, track which
    // nodes were modified, and scan only them
    // load one of the parent markings directly into the new marking map
    new_markings.clear();
    mark_merge_roster(left_roster, left_markings, left_uncommon_ancestors,
                      right_roster, right_markings, right_uncommon_ancestors,
                      new_rid, new_roster, new_markings);
  }


  // WARNING: this function is not tested directly (no unit tests).  Do not
  // put real logic in it.
  void
  make_roster_for_merge(revision_id const & left_rid, cset const & left_cs,
                        revision_id const & right_rid, cset const & right_cs,
                        revision_id const & new_rid,
                        roster_t & new_roster, marking_map & new_markings,
                        app_state & app)
  {
    I(!null_id(left_rid) && !null_id(right_rid));
    database::cached_roster left_cached, right_cached;
    app.db.get_roster(left_rid, left_cached);
    app.db.get_roster(right_rid, right_cached);
    true_node_id_source tnis = true_node_id_source(app);

    set<revision_id> left_uncommon_ancestors, right_uncommon_ancestors;
    app.db.get_uncommon_ancestors(left_rid, right_rid,
                                  left_uncommon_ancestors,
                                  right_uncommon_ancestors);
    make_roster_for_merge(left_rid, *left_cached.first, *left_cached.second, left_cs,
                          left_uncommon_ancestors,
                          right_rid, *right_cached.first, *right_cached.second, right_cs,
                          right_uncommon_ancestors,
                          new_rid,
                          new_roster, new_markings,
                          tnis);
  }

  // Warning: this function expects the parent's roster and markings in the
  // 'new_roster' and 'new_markings' parameters, and they are modified
  // destructively!
  // This function performs an almost identical task to
  // mark_roster_with_one_parent; however, for efficiency, it is implemented
  // in a different, destructive way.
  void
  make_roster_for_nonmerge(cset const & cs,
                           revision_id const & new_rid,
                           roster_t & new_roster, marking_map & new_markings,
                           node_id_source & nis)
  {
    editable_roster_for_nonmerge er(new_roster, nis, new_rid, new_markings);
    cs.apply_to(er);
  }

  // WARNING: this function is not tested directly (no unit tests).  Do not
  // put real logic in it.
  void
  make_roster_for_nonmerge(revision_id const & parent_rid,
                           cset const & parent_cs,
                           revision_id const & new_rid,
                           roster_t & new_roster, marking_map & new_markings,
                           app_state & app)
  {
    app.db.get_roster(parent_rid, new_roster, new_markings);
    true_node_id_source nis(app);
    make_roster_for_nonmerge(parent_cs, new_rid, new_roster, new_markings, nis);
  }
}

void
mark_roster_with_no_parents(revision_id const & rid,
                            roster_t const & roster,
                            marking_map & markings)
{
  roster_t mock_parent;
  marking_map mock_parent_markings;
  mark_roster_with_one_parent(mock_parent, mock_parent_markings,
                              rid, roster, markings);
}

void
mark_roster_with_one_parent(roster_t const & parent,
                            marking_map const & parent_markings,
                            revision_id const & child_rid,
                            roster_t const & child,
                            marking_map & child_markings)
{
  MM(parent);
  MM(parent_markings);
  MM(child_rid);
  MM(child);
  MM(child_markings);

  I(!null_id(child_rid));
  child_markings.clear();
  
  for (node_map::const_iterator i = child.all_nodes().begin();
       i != child.all_nodes().end(); ++i)
    {
      marking_t new_marking;
      if (parent.has_node(i->first))
        mark_unmerged_node(safe_get(parent_markings, i->first),
                           parent.get_node(i->first),
                           child_rid, i->second, new_marking);
      else
        mark_new_node(child_rid, i->second, new_marking);
      safe_insert(child_markings, make_pair(i->first, new_marking));
    }

  child.check_sane_against(child_markings, true);
}

// WARNING: this function is not tested directly (no unit tests).  Do not put
// real logic in it.
void
make_roster_for_revision(revision_t const & rev, revision_id const & new_rid,
                         roster_t & new_roster, marking_map & new_markings,
                         app_state & app)
{
  MM(rev);
  MM(new_rid);
  MM(new_roster);
  MM(new_markings);
  if (rev.edges.size() == 1)
    make_roster_for_nonmerge(edge_old_revision(rev.edges.begin()),
                             edge_changes(rev.edges.begin()),
                             new_rid, new_roster, new_markings, app);
  else if (rev.edges.size() == 2)
    {
      edge_map::const_iterator i = rev.edges.begin();
      revision_id const & left_rid = edge_old_revision(i);
      cset const & left_cs = edge_changes(i);
      ++i;
      revision_id const & right_rid = edge_old_revision(i);
      cset const & right_cs = edge_changes(i);
      make_roster_for_merge(left_rid, left_cs, right_rid, right_cs,
                            new_rid, new_roster, new_markings, app);
    }
  else
    I(false);

  new_roster.check_sane_against(new_markings);
}


////////////////////////////////////////////////////////////////////
//   Calculation of a cset
////////////////////////////////////////////////////////////////////


namespace
{

  void delta_only_in_from(roster_t const & from,
                          node_id nid, node_t n,
                          cset & cs)
  {
    split_path sp;
    from.get_name(nid, sp);
    safe_insert(cs.nodes_deleted, sp);
  }


  void delta_only_in_to(roster_t const & to, node_id nid, node_t n,
                        cset & cs)
  {
    split_path sp;
    to.get_name(nid, sp);
    if (is_file_t(n))
      {
        safe_insert(cs.files_added,
                    make_pair(sp, downcast_to_file_t(n)->content));
      }
    else
      {
        safe_insert(cs.dirs_added, sp);
      }
    for (full_attr_map_t::const_iterator i = n->attrs.begin();
         i != n->attrs.end(); ++i)
      if (i->second.first)
        safe_insert(cs.attrs_set,
                    make_pair(make_pair(sp, i->first), i->second.second));
  }

  void delta_in_both(node_id nid,
                     roster_t const & from, node_t from_n,
                     roster_t const & to, node_t to_n,
                     cset & cs)
  {
    I(same_type(from_n, to_n));
    I(from_n->self == to_n->self);

    if (shallow_equal(from_n, to_n, false))
      return;

    split_path from_sp, to_sp;
    from.get_name(nid, from_sp);
    to.get_name(nid, to_sp);

    // Compare name and path.
    if (from_n->name != to_n->name || from_n->parent != to_n->parent)
      safe_insert(cs.nodes_renamed, make_pair(from_sp, to_sp));

    // Compare file content.
    if (is_file_t(from_n))
      {
        file_t from_f = downcast_to_file_t(from_n);
        file_t to_f = downcast_to_file_t(to_n);
        if (!(from_f->content == to_f->content))
          {
            safe_insert(cs.deltas_applied,
                        make_pair(to_sp, make_pair(from_f->content,
                                                   to_f->content)));
          }
      }

    // Compare attrs.
    {
      parallel::iter<full_attr_map_t> i(from_n->attrs, to_n->attrs);
      while (i.next())
        {
          MM(i);
          if ((i.state() == parallel::in_left
               || (i.state() == parallel::in_both && !i.right_data().first))
              && i.left_data().first)
            {
              safe_insert(cs.attrs_cleared,
                          make_pair(to_sp, i.left_key()));
            }
          else if ((i.state() == parallel::in_right
                    || (i.state() == parallel::in_both && !i.left_data().first))
                   && i.right_data().first)
            {
              safe_insert(cs.attrs_set,
                          make_pair(make_pair(to_sp, i.right_key()),
                                    i.right_data().second));
            }
          else if (i.state() == parallel::in_both
                   && i.right_data().first
                   && i.left_data().first
                   && i.right_data().second != i.left_data().second)
            {
              safe_insert(cs.attrs_set,
                          make_pair(make_pair(to_sp, i.right_key()),
                                    i.right_data().second));
            }
        }
    }
  }
}

void
make_cset(roster_t const & from, roster_t const & to, cset & cs)
{
  cs.clear();
  parallel::iter<node_map> i(from.all_nodes(), to.all_nodes());
  while (i.next())
    {
      MM(i);
      switch (i.state())
        {
        case parallel::invalid:
          I(false);

        case parallel::in_left:
          // deleted
          delta_only_in_from(from, i.left_key(), i.left_data(), cs);
          break;

        case parallel::in_right:
          // added
          delta_only_in_to(to, i.right_key(), i.right_data(), cs);
          break;

        case parallel::in_both:
          // moved/renamed/patched/attribute changes
          delta_in_both(i.left_key(), from, i.left_data(), to, i.right_data(), cs);
          break;
        }
    }
}


// we assume our input is sane
bool
equal_up_to_renumbering(roster_t const & a, marking_map const & a_markings,
                        roster_t const & b, marking_map const & b_markings)
{
  if (a.all_nodes().size() != b.all_nodes().size())
    return false;

  for (node_map::const_iterator i = a.all_nodes().begin();
       i != a.all_nodes().end(); ++i)
    {
      split_path sp;
      a.get_name(i->first, sp);
      if (!b.has_node(sp))
        return false;
      node_t b_n = b.get_node(sp);
      // we already know names are the same
      if (!same_type(i->second, b_n))
        return false;
      if (i->second->attrs != b_n->attrs)
        return false;
      if (is_file_t(i->second))
        {
          if (!(downcast_to_file_t(i->second)->content
                == downcast_to_file_t(b_n)->content))
            return false;
        }
      // nodes match, check the markings too
      if (!(safe_get(a_markings, i->first) == safe_get(b_markings, b_n->self)))
        return false;
    }
  return true;
}


void make_restricted_csets(roster_t const & from, roster_t const & to,
                           cset & included, cset & excluded,
                           node_restriction const & mask)
{
  included.clear();
  excluded.clear();

  L(FL("building restricted csets"));
  parallel::iter<node_map> i(from.all_nodes(), to.all_nodes());
  while (i.next())
    {
      MM(i);
      switch (i.state())
        {
        case parallel::invalid:
          I(false);

        case parallel::in_left:
          // deleted
          if (mask.includes(from, i.left_key()))
            {
              delta_only_in_from(from, i.left_key(), i.left_data(), included);
              L(FL("included left %d") % i.left_key());
            }
          else
            {
              delta_only_in_from(from, i.left_key(), i.left_data(), excluded);
              L(FL("excluded left %d") % i.left_key());
            }
          break;

        case parallel::in_right:
          // added
          if (mask.includes(to, i.right_key()))
            {
              delta_only_in_to(to, i.right_key(), i.right_data(), included);
              L(FL("included right %d") % i.right_key());
            }
          else
            {
              delta_only_in_to(to, i.right_key(), i.right_data(), excluded);
              L(FL("excluded right %d") % i.right_key());
            }
          break;

        case parallel::in_both:
          // moved/renamed/patched/attribute changes
          if (mask.includes(from, i.left_key()) || mask.includes(to, i.right_key()))
            {
              delta_in_both(i.left_key(), from, i.left_data(), to, i.right_data(), included);
              L(FL("in both %d %d") % i.left_key() % i.right_key());
            }
          else
            {
              delta_in_both(i.left_key(), from, i.left_data(), to, i.right_data(), excluded);
              L(FL("in both %d %d") % i.left_key() % i.right_key());
            }
          break;
        }
    }

}

class editable_roster_for_check
  : public editable_roster_base
{
 public:
  editable_roster_for_check(roster_t & r);
  virtual node_id detach_node(split_path const & src);
  virtual void drop_detached_node(node_id nid);
  virtual void attach_node(node_id nid, split_path const & dst);
  int problems;

 private:
  temp_node_id_source nis;
  map<node_id, pair<split_path, vector<path_component> > > detached_dirs;
};

editable_roster_for_check::editable_roster_for_check(roster_t & r)
  : editable_roster_base(r, nis), problems(0)
{
  node_map nodes = r.all_nodes();
  node_map::const_iterator i = nodes.begin();
  node_id max = i->first;

  for (; i != nodes.end(); ++i)
    {
      if (i->first > max)
        max = i->first;
    }

  // ensure our node source starts beyond the max temp node in this roster
  while (nis.next() <= max)
    ;
}

node_id
editable_roster_for_check::detach_node(split_path const & src)
{
  node_t n = r.get_node(src);
  if (is_dir_t(n))
    {
      dir_t dir = downcast_to_dir_t(n);
      vector<path_component> children;
      for (dir_map::const_iterator 
             i = dir->children.begin(); i != dir->children.end(); ++i)
        {
          children.push_back(i->first);
        }
      detached_dirs.insert(make_pair(dir->self, 
                                     make_pair(src, children)));
    }

  return this->editable_roster_base::detach_node(src);
}

void
editable_roster_for_check::drop_detached_node(node_id nid)
{
  node_t n = r.get_node(nid);
  if (is_dir_t(n) && !downcast_to_dir_t(n)->children.empty())
    {
      map<node_id, pair<split_path, vector<path_component> > >::const_iterator 
        i = detached_dirs.find(nid);
      I(i != detached_dirs.end());

      split_path dir = i->second.first;
      for (vector<path_component>::const_iterator 
             p = i->second.second.begin(); p != i->second.second.end(); ++p)
        {
          split_path child(dir);
          child.push_back(*p);
          W(F("restriction includes deletion of '%s' but excludes deletion of '%s'")
            % dir % child);
          problems++;
        }
    }
  else
    {
      this->editable_roster_base::drop_detached_node(nid);
    }
}

void
editable_roster_for_check::attach_node(node_id nid, split_path const & dst)
{
  split_path dirname;
  path_component basename;
  dirname_basename(dst, dirname, basename);

  if (!dirname.empty() && !r.has_node(dirname))
    {
      W(F("restriction excludes addition of '%s' but includes addition of '%s'")
        % dirname % dst);
      problems++;
    }
  else
    {
      this->editable_roster_base::attach_node(nid, dst);
    }
}

void
check_restricted_cset(roster_t const & roster, cset const & cs)
{
  // This command checks that a cset generated by make_restricted_cset still
  // is sensical when applied to the given roster -- e.g., it does not
  // include a deletion of a directory that would be empty, except that some
  // of the deletions/renames that emptied it were not included in the
  // restriction, it does not include the addition of a file when the
  // addition of its parent directory was not included, etc.

  MM(roster);
  MM(cs);

  // make a copy of the roster to apply the cset to destructively
  roster_t tmp(roster);
  editable_roster_for_check e(tmp);
  cs.apply_to(e);

  N(e.problems == 0, F("invalid restriction"));
}


void
select_nodes_modified_by_cset(cset const & cs,
                              roster_t const & old_roster,
                              roster_t const & new_roster,
                              set<node_id> & nodes_modified)
{
  nodes_modified.clear();

  path_set modified_prestate_nodes;
  path_set modified_poststate_nodes;

  // Pre-state damage

  copy(cs.nodes_deleted.begin(), cs.nodes_deleted.end(),
       inserter(modified_prestate_nodes, modified_prestate_nodes.begin()));

  for (map<split_path, split_path>::const_iterator i = cs.nodes_renamed.begin();
       i != cs.nodes_renamed.end(); ++i)
    modified_prestate_nodes.insert(i->first);

  // Post-state damage

  copy(cs.dirs_added.begin(), cs.dirs_added.end(),
       inserter(modified_poststate_nodes, modified_poststate_nodes.begin()));

  for (map<split_path, file_id>::const_iterator i = cs.files_added.begin();
       i != cs.files_added.end(); ++i)
    modified_poststate_nodes.insert(i->first);

  for (map<split_path, split_path>::const_iterator i = cs.nodes_renamed.begin();
       i != cs.nodes_renamed.end(); ++i)
    modified_poststate_nodes.insert(i->second);

  for (map<split_path, pair<file_id, file_id> >::const_iterator i = cs.deltas_applied.begin();
       i != cs.deltas_applied.end(); ++i)
    modified_poststate_nodes.insert(i->first);

  for (set<pair<split_path, attr_key> >::const_iterator i = cs.attrs_cleared.begin();
       i != cs.attrs_cleared.end(); ++i)
    modified_poststate_nodes.insert(i->first);

  for (map<pair<split_path, attr_key>, attr_value>::const_iterator i = cs.attrs_set.begin();
       i != cs.attrs_set.end(); ++i)
    modified_poststate_nodes.insert(i->first.first);

  // Finale

  for (path_set::const_iterator i = modified_prestate_nodes.begin();
       i != modified_prestate_nodes.end(); ++i)
    {
      I(old_roster.has_node(*i));
      nodes_modified.insert(old_roster.get_node(*i)->self);
    }

  for (path_set::const_iterator i = modified_poststate_nodes.begin();
       i != modified_poststate_nodes.end(); ++i)
    {
      I(new_roster.has_node(*i));
      nodes_modified.insert(new_roster.get_node(*i)->self);
    }

}

void
roster_t::extract_path_set(path_set & paths) const
{
  paths.clear();
  if (has_root())
    {
      for (dfs_iter i(root_dir); !i.finished(); ++i)
        {
          node_t curr = *i;
          split_path pth;
          get_name(curr->self, pth);
          if (!workspace_root(pth))
            paths.insert(pth);
        }
    }
}


////////////////////////////////////////////////////////////////////
//   I/O routines
////////////////////////////////////////////////////////////////////

void
push_marking(basic_io::stanza & st,
             bool is_file,
             marking_t const & mark)
{

  I(!null_id(mark.birth_revision));
  st.push_hex_pair(basic_io::syms::birth, mark.birth_revision.inner());

  for (set<revision_id>::const_iterator i = mark.parent_name.begin();
       i != mark.parent_name.end(); ++i)
    st.push_hex_pair(basic_io::syms::path_mark, i->inner());

  if (is_file)
    {
      for (set<revision_id>::const_iterator i = mark.file_content.begin();
           i != mark.file_content.end(); ++i)
        st.push_hex_pair(basic_io::syms::content_mark, i->inner());
    }
  else
    I(mark.file_content.empty());

  for (map<attr_key, set<revision_id> >::const_iterator i = mark.attrs.begin();
       i != mark.attrs.end(); ++i)
    {
      for (set<revision_id>::const_iterator j = i->second.begin();
           j != i->second.end(); ++j)
        st.push_hex_triple(basic_io::syms::attr_mark, i->first(), j->inner());
    }
}


void
parse_marking(basic_io::parser & pa,
              marking_t & marking)
{
  while (pa.symp())
    {
      string rev;
      if (pa.symp(basic_io::syms::birth))
        {
          pa.sym();
          pa.hex(rev);
          marking.birth_revision = revision_id(rev);
        }
      else if (pa.symp(basic_io::syms::path_mark))
        {
          pa.sym();
          pa.hex(rev);
          safe_insert(marking.parent_name, revision_id(rev));
        }
      else if (pa.symp(basic_io::syms::content_mark))
        {
          pa.sym();
          pa.hex(rev);
          safe_insert(marking.file_content, revision_id(rev));
        }
      else if (pa.symp(basic_io::syms::attr_mark))
        {
          string k;
          pa.sym();
          pa.str(k);
          pa.hex(rev);
          attr_key key = attr_key(k);
          safe_insert(marking.attrs[key], revision_id(rev));
        }
      else break;
    }
}

// SPEEDUP?: hand-writing a parser for manifests was a measurable speed win,
// and the original parser was much simpler than basic_io.  After benchmarking
// consider replacing the roster disk format with something that can be
// processed more efficiently.

void
roster_t::print_to(basic_io::printer & pr,
                   marking_map const & mm,
                   bool print_local_parts) const
{
  I(has_root());
  {
    basic_io::stanza st;
    st.push_str_pair(basic_io::syms::format_version, "1");
    pr.print_stanza(st);
  }
  for (dfs_iter i(root_dir); !i.finished(); ++i)
    {
      node_t curr = *i;
      split_path pth;
      get_name(curr->self, pth);

      file_path fp = file_path(pth);

      basic_io::stanza st;
      if (is_dir_t(curr))
        {
          // L(FL("printing dir %s") % fp);
          st.push_file_pair(basic_io::syms::dir, fp);
        }
      else
        {
          file_t ftmp = downcast_to_file_t(curr);
          st.push_file_pair(basic_io::syms::file, fp);
          st.push_hex_pair(basic_io::syms::content, ftmp->content.inner());
          // L(FL("printing file %s") % fp);
        }

      if (print_local_parts)
        {
          I(curr->self != the_null_node);
          st.push_str_pair(basic_io::syms::ident, lexical_cast<string>(curr->self));
        }

      // Push the non-dormant part of the attr map
      for (full_attr_map_t::const_iterator j = curr->attrs.begin();
           j != curr->attrs.end(); ++j)
        {
          if (j->second.first)
            {
              // L(FL("printing attr %s : %s = %s") % fp % j->first % j->second);
              st.push_str_triple(basic_io::syms::attr, j->first(), j->second.second());
            }
        }

      if (print_local_parts)
        {
          // Push the dormant part of the attr map
          for (full_attr_map_t::const_iterator j = curr->attrs.begin();
               j != curr->attrs.end(); ++j)
            {
              if (!j->second.first)
                {
                  I(j->second.second().empty());
                  st.push_str_pair(basic_io::syms::dormant_attr, j->first());
                }
            }

          marking_map::const_iterator m = mm.find(curr->self);
          I(m != mm.end());
          push_marking(st, is_file_t(curr), m->second);
        }

      pr.print_stanza(st);
    }
}

inline size_t
read_num(string const & s)
{
  size_t n = 0;

  for (string::const_iterator i = s.begin(); i != s.end(); i++)
    {
      I(*i >= '0' && *i <= '9');
      n *= 10;
      n += static_cast<size_t>(*i - '0');
    }
  return n;
}

void
roster_t::parse_from(basic_io::parser & pa,
                     marking_map & mm)
{
  // Instantiate some lookaside caches to ensure this roster reuses
  // string storage across ATOMIC elements.
  id::symtab id_syms;
  path_component::symtab path_syms;
  attr_key::symtab attr_key_syms;
  attr_value::symtab attr_value_syms;


  // We *always* parse the local part of a roster, because we do not
  // actually send the non-local part over the network; the only times
  // we serialize a manifest (non-local roster) is when we're printing
  // it out for a user, or when we're hashing it for a manifest ID.
  nodes.clear();
  root_dir.reset();
  mm.clear();

  {
    pa.esym(basic_io::syms::format_version);
    string vers;
    pa.str(vers);
    I(vers == "1");
  }

  while(pa.symp())
    {
      string pth, ident, rev;
      node_t n;

      if (pa.symp(basic_io::syms::file))
        {
          string content;
          pa.sym();
          pa.str(pth);
          pa.esym(basic_io::syms::content);
          pa.hex(content);
          pa.esym(basic_io::syms::ident);
          pa.str(ident);
          n = file_t(new file_node(read_num(ident),
                                   file_id(content)));
        }
      else if (pa.symp(basic_io::syms::dir))
        {
          pa.sym();
          pa.str(pth);
          pa.esym(basic_io::syms::ident);
          pa.str(ident);
          n = dir_t(new dir_node(read_num(ident)));
        }
      else
        break;

      I(static_cast<bool>(n));

      safe_insert(nodes, make_pair(n->self, n));
      if (is_dir_t(n) && pth.empty())
        {
          I(! has_root());
          root_dir = downcast_to_dir_t(n);
        }
      else
        {
          I(!pth.empty());
          split_path sp;
          internal_string_to_split_path(pth, sp);
          attach_node(n->self, sp);
        }

      // Non-dormant attrs
      while(pa.symp(basic_io::syms::attr))
        {
          pa.sym();
          string k, v;
          pa.str(k);
          pa.str(v);
          safe_insert(n->attrs, make_pair(attr_key(k),
                                          make_pair(true, attr_value(v))));
        }

      // Dormant attrs
      while(pa.symp(basic_io::syms::dormant_attr))
        {
          pa.sym();
          string k;
          pa.str(k);
          safe_insert(n->attrs, make_pair(attr_key(k),
                                          make_pair(false, attr_value())));
        }

      {
        marking_t & m(safe_insert(mm, make_pair(n->self, marking_t()))->second);
        parse_marking(pa, m);
      }
    }
}


void
read_roster_and_marking(roster_data const & dat,
                        roster_t & ros,
                        marking_map & mm)
{
  basic_io::input_source src(dat.inner()(), "roster");
  basic_io::tokenizer tok(src);
  basic_io::parser pars(tok);
  ros.parse_from(pars, mm);
  I(src.lookahead == EOF);
  ros.check_sane_against(mm);
}


static void
write_roster_and_marking(roster_t const & ros,
                         marking_map const & mm,
                         data & dat,
                         bool print_local_parts)
{
  if (print_local_parts)
    ros.check_sane_against(mm);
  else
    ros.check_sane(true);
  basic_io::printer pr;
  ros.print_to(pr, mm, print_local_parts);
  dat = pr.buf;
}


void
write_roster_and_marking(roster_t const & ros,
                         marking_map const & mm,
                         roster_data & dat)
{
  data tmp;
  write_roster_and_marking(ros, mm, tmp, true);
  dat = tmp;
}


void
write_manifest_of_roster(roster_t const & ros,
                         manifest_data & dat)
{
  data tmp;
  marking_map mm;
  write_roster_and_marking(ros, mm, tmp, false);
  dat = tmp;
}

void calculate_ident(roster_t const & ros,
                     manifest_id & ident)
{
  manifest_data tmp;
  if (!ros.all_nodes().empty())
    {
      write_manifest_of_roster(ros, tmp);
      calculate_ident(tmp, ident);
    }
}

////////////////////////////////////////////////////////////////////
//   testing
////////////////////////////////////////////////////////////////////

#ifdef BUILD_UNIT_TESTS
#include "unit_tests.hh"
#include "sanity.hh"
#include "constants.hh"
#include "randomizer.hh"

#include "roster_delta.hh"

#include <string>
#include <cstdlib>
#include <boost/lexical_cast.hpp>

using std::logic_error;
using std::search;

using boost::shared_ptr;

static void
make_fake_marking_for(roster_t const & r, marking_map & mm)
{
  mm.clear();
  revision_id rid(string("0123456789abcdef0123456789abcdef01234567"));
  for (node_map::const_iterator i = r.all_nodes().begin(); i != r.all_nodes().end();
       ++i)
    {
      marking_t fake_marks;
      mark_new_node(rid, i->second, fake_marks);
      mm.insert(make_pair(i->first, fake_marks));
    }
}

static void
do_testing_on_one_roster(roster_t const & r)
{
  if (!r.has_root())
    {
      I(r.all_nodes().size() == 0);
      // not much testing to be done on an empty roster -- can't iterate over
      // it or read/write it.
      return;
    }

  MM(r);
  // test dfs_iter by making sure it returns the same number of items as there
  // are items in all_nodes()
  int n; MM(n);
  n = r.all_nodes().size();
  int dfs_counted = 0; MM(dfs_counted);
  split_path root_name;
  file_path().split(root_name);
  for (dfs_iter i(downcast_to_dir_t(r.get_node(root_name))); !i.finished(); ++i)
    ++dfs_counted;
  I(n == dfs_counted);

  // do a read/write spin
  roster_data r_dat; MM(r_dat);
  marking_map fm;
  make_fake_marking_for(r, fm);
  write_roster_and_marking(r, fm, r_dat);
  roster_t r2; MM(r2);
  marking_map fm2;
  read_roster_and_marking(r_dat, r2, fm2);
  I(r == r2);
  I(fm == fm2);
  roster_data r2_dat; MM(r2_dat);
  write_roster_and_marking(r2, fm2, r2_dat);
  I(r_dat == r2_dat);
}

static void
do_testing_on_two_equivalent_csets(cset const & a, cset const & b)
{
  // we do all this reading/writing/comparing of both strings and objects to
  // cross-check the reading, writing, and comparison logic against each
  // other.  (if, say, there is a field in cset that == forgets to check but
  // that write remembers to include, this should catch it).
  MM(a);
  MM(b);
  I(a == b);

  data a_dat, b_dat, a2_dat, b2_dat;
  MM(a_dat);
  MM(b_dat);
  MM(a2_dat);
  MM(b2_dat);

  write_cset(a, a_dat);
  write_cset(b, b_dat);
  I(a_dat == b_dat);
  cset a2, b2;
  MM(a2);
  MM(b2);
  read_cset(a_dat, a2);
  read_cset(b_dat, b2);
  I(a2 == a);
  I(b2 == b);
  I(b2 == a);
  I(a2 == b);
  I(a2 == b2);
  write_cset(a2, a2_dat);
  write_cset(b2, b2_dat);
  I(a_dat == a2_dat);
  I(b_dat == b2_dat);
}

static void
apply_cset_and_do_testing(roster_t & r, cset const & cs, node_id_source & nis)
{
  MM(r);
  MM(cs);
  roster_t original = r;
  MM(original);
  I(original == r);

  editable_roster_base e(r, nis);
  cs.apply_to(e);

  cset derived;
  MM(derived);
  make_cset(original, r, derived);

  do_testing_on_two_equivalent_csets(cs, derived);
  do_testing_on_one_roster(r);
}

static void
tests_on_two_rosters(roster_t const & a, roster_t const & b, node_id_source & nis)
{
  MM(a);
  MM(b);

  do_testing_on_one_roster(a);
  do_testing_on_one_roster(b);

  cset a_to_b; MM(a_to_b);
  cset b_to_a; MM(b_to_a);
  make_cset(a, b, a_to_b);
  make_cset(b, a, b_to_a);
  roster_t a2(b); MM(a2);
  roster_t b2(a); MM(b2);
  // we can't use a cset to entirely empty out a roster, so don't bother doing
  // the apply_to tests towards an empty roster
  // (NOTE: if you notice this special case in a time when root dirs can be
  // renamed or deleted, remove it, it will no longer be necessary.
  if (!a.all_nodes().empty())
    {
      editable_roster_base eb(a2, nis);
      b_to_a.apply_to(eb);
    }
  else
    a2 = a;
  if (!b.all_nodes().empty())
    {
      editable_roster_base ea(b2, nis);
      a_to_b.apply_to(ea);
    }
  else
    b2 = b;
  // We'd like to assert that a2 == a and b2 == b, but we can't, because they
  // will have new ids assigned.
  // But they _will_ have the same manifests, assuming things are working
  // correctly.
  manifest_data a_dat; MM(a_dat);
  manifest_data a2_dat; MM(a2_dat);
  manifest_data b_dat; MM(b_dat);
  manifest_data b2_dat; MM(b2_dat);
  if (a.has_root())
    write_manifest_of_roster(a, a_dat);
  if (a2.has_root())
    write_manifest_of_roster(a2, a2_dat);
  if (b.has_root())
    write_manifest_of_roster(b, b_dat);
  if (b2.has_root())
    write_manifest_of_roster(b2, b2_dat);
  I(a_dat == a2_dat);
  I(b_dat == b2_dat);

  cset a2_to_b2; MM(a2_to_b2);
  cset b2_to_a2; MM(b2_to_a2);
  make_cset(a2, b2, a2_to_b2);
  make_cset(b2, a2, b2_to_a2);
  do_testing_on_two_equivalent_csets(a_to_b, a2_to_b2);
  do_testing_on_two_equivalent_csets(b_to_a, b2_to_a2);
  
  {
    marking_map a_marking;
    make_fake_marking_for(a, a_marking);
    marking_map b_marking;
    make_fake_marking_for(b, b_marking);
    test_roster_delta_on(a, a_marking, b, b_marking);
  }
}

template<typename M>
typename M::const_iterator
random_element(M const & m, randomizer & rng)
{
  size_t i = rng.uniform(m.size());
  typename M::const_iterator j = m.begin();
  while (i > 0)
    {
      I(j != m.end());
      --i;
      ++j;
    }
  return j;
}

string new_word(randomizer & rng)
{
  static string wordchars = "abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  static unsigned tick = 0;
  string tmp;
  do
    {
      tmp += wordchars[rng.uniform(wordchars.size())];
    }
  while (tmp.size() < 10 && !rng.flip(10));
  return tmp + lexical_cast<string>(tick++);
}

file_id new_ident(randomizer & rng)
{
  static string tab = "0123456789abcdef";
  string tmp;
  tmp.reserve(constants::idlen);
  for (unsigned i = 0; i < constants::idlen; ++i)
    tmp += tab[rng.uniform(tab.size())];
  return file_id(tmp);
}

path_component new_component(randomizer & rng)
{
  split_path pieces;
  file_path_internal(new_word(rng)).split(pieces);
  return pieces.back();
}


attr_key pick_attr(full_attr_map_t const & attrs, randomizer & rng)
{
  return random_element(attrs, rng)->first;
}

attr_key pick_attr(attr_map_t const & attrs, randomizer & rng)
{
  return random_element(attrs, rng)->first;
}

bool parent_of(split_path const & p,
               split_path const & c)
{
  bool is_parent = false;

  if (p.size() <= c.size())
    {
      split_path::const_iterator c_anchor =
        search(c.begin(), c.end(),
               p.begin(), p.end());

      is_parent = (c_anchor == c.begin());
    }

  //     L(FL("path '%s' is%s parent of '%s'")
  //       % file_path(p)
  //       % (is_parent ? "" : " not")
  //       % file_path(c));

  return is_parent;
}

void perform_random_action(roster_t & r, node_id_source & nis, randomizer & rng)
{
  cset c;
  I(r.has_root());
  while (c.empty())
    {
      node_t n = random_element(r.all_nodes(), rng)->second;
      split_path pth;
      r.get_name(n->self, pth);
      // L(FL("considering acting on '%s'") % file_path(pth));

      switch (rng.uniform(7))
        {
        default:
        case 0:
        case 1:
        case 2:
          if (is_file_t(n) || (pth.size() > 1 && rng.flip()))
            // Add a sibling of an existing entry.
            pth[pth.size() - 1] = new_component(rng);

          else
            // Add a child of an existing entry.
            pth.push_back(new_component(rng));

          if (rng.flip())
            {
              // L(FL("adding dir '%s'") % file_path(pth));
              safe_insert(c.dirs_added, pth);
            }
          else
            {
              // L(FL("adding file '%s'") % file_path(pth));
              safe_insert(c.files_added, make_pair(pth, new_ident(rng)));
            }
          break;

        case 3:
          if (is_file_t(n))
            {
              // L(FL("altering content of file '%s'") % file_path(pth));
              safe_insert(c.deltas_applied,
                          make_pair
                          (pth, make_pair(downcast_to_file_t(n)->content,
                                          new_ident(rng))));
            }
          break;

        case 4:
          {
            node_t n2 = random_element(r.all_nodes(), rng)->second;
            split_path pth2;
            r.get_name(n2->self, pth2);

            if (n == n2)
              continue;

            if (is_file_t(n2) || (pth2.size() > 1 && rng.flip()))
              {
                // L(FL("renaming to a sibling of an existing entry '%s'")
                //   % file_path(pth2));
                // Move to a sibling of an existing entry.
                pth2[pth2.size() - 1] = new_component(rng);
              }

            else
              {
                // L(FL("renaming to a child of an existing entry '%s'")
                //   % file_path(pth2));
                // Move to a child of an existing entry.
                pth2.push_back(new_component(rng));
              }

            if (!parent_of(pth, pth2))
              {
                // L(FL("renaming '%s' -> '%s")
                //   % file_path(pth) % file_path(pth2));
                safe_insert(c.nodes_renamed, make_pair(pth, pth2));
              }
          }
          break;

        case 5:
          if (!null_node(n->parent)
              && (is_file_t(n) || downcast_to_dir_t(n)->children.empty())
              && r.all_nodes().size() > 1) // do not delete the root
            {
              // L(FL("deleting '%s'") % file_path(pth));
              safe_insert(c.nodes_deleted, pth);
            }
          break;

        case 6:
          if (!n->attrs.empty() && rng.flip())
            {
              attr_key k = pick_attr(n->attrs, rng);
              if (safe_get(n->attrs, k).first)
                {
                  if (rng.flip())
                    {
                      // L(FL("clearing attr on '%s'") % file_path(pth));
                      safe_insert(c.attrs_cleared, make_pair(pth, k));
                    }
                  else
                    {
                      // L(FL("changing attr on '%s'\n") % file_path(pth));
                      safe_insert(c.attrs_set,
                                  make_pair(make_pair(pth, k), new_word(rng)));
                    }
                }
              else
                {
                  // L(FL("setting previously set attr on '%s'")
                  //   % file_path(pth));
                  safe_insert(c.attrs_set,
                              make_pair(make_pair(pth, k), new_word(rng)));
                }
            }
          else
            {
              // L(FL("setting attr on '%s'") % file_path(pth));
              safe_insert(c.attrs_set,
                          make_pair(make_pair(pth, new_word(rng)), new_word(rng)));
            }
          break;
        }
    }
  // now do it
  apply_cset_and_do_testing(r, c, nis);
}

testing_node_id_source::testing_node_id_source()
  : curr(first_node)
{}

node_id
testing_node_id_source::next()
{
  // L(FL("creating node %x") % curr);
  node_id n = curr++;
  I(!temp_node(n));
  return n;
}

template <> void
dump(int const & i, string & out)
{
  out = lexical_cast<string>(i) + "\n";
}

UNIT_TEST(roster, random_actions)
{
  randomizer rng;
  roster_t r;
  testing_node_id_source nis;

  roster_t empty, prev, recent, ancient;

  {
    // give all the rosters a root
    split_path root;
    cset c;
    root.push_back(the_null_component);
    c.dirs_added.insert(root);
    apply_cset_and_do_testing(r, c, nis);
  }

  empty = ancient = recent = prev = r;
  for (int i = 0; i < 2000; )
    {
      int manychanges = 100 + rng.uniform(300);
      P(F("random roster actions: outer step at %d, making %d changes")
        % i % manychanges);

      for (int outer_limit = i + manychanges; i < outer_limit; )
        {
          int fewchanges = 5 + rng.uniform(10);
          // P(F("random roster actions: inner step at %d, making %d changes")
          //   % i % fewchanges);

          for (int inner_limit = i + fewchanges; i < inner_limit; i++)
            {
              // P(F("random roster actions: change %d") % i);
              perform_random_action(r, nis, rng);
              I(!(prev == r));
              prev = r;
            }
          tests_on_two_rosters(recent, r, nis);
          tests_on_two_rosters(empty, r, nis);
          recent = r;
        }
      tests_on_two_rosters(ancient, r, nis);
      ancient = r;
    }
}

// some of our raising operations leave our state corrupted.  so rather than
// trying to do all the illegal things in one pass, we re-run this function a
// bunch of times, and each time we do only one of these potentially
// corrupting tests.  Test numbers are in the range [0, total).

#define MAYBE(code) if (total == to_run) { L(FL(#code)); code; return; } ++total

static void
check_sane_roster_do_tests(int to_run, int& total)
{
  total = 0;
  testing_node_id_source nis;
  roster_t r;
  MM(r);

  // roster must have a root dir
  MAYBE(BOOST_CHECK_THROW(r.check_sane(false), logic_error));
  MAYBE(BOOST_CHECK_THROW(r.check_sane(true), logic_error));

  split_path sp_, sp_foo, sp_foo_bar, sp_foo_baz;
  file_path().split(sp_);
  file_path_internal("foo").split(sp_foo);
  file_path_internal("foo/bar").split(sp_foo_bar);
  file_path_internal("foo/baz").split(sp_foo_baz);
  node_id nid_f = r.create_file_node(file_id(string("0000000000000000000000000000000000000000")),
                                     nis);
  // root must be a directory, not a file
  MAYBE(BOOST_CHECK_THROW(r.attach_node(nid_f, sp_), logic_error));

  node_id root_dir = r.create_dir_node(nis);
  r.attach_node(root_dir, sp_);
  // has a root dir, but a detached file
  MAYBE(BOOST_CHECK_THROW(r.check_sane(false), logic_error));
  MAYBE(BOOST_CHECK_THROW(r.check_sane(true), logic_error));

  r.attach_node(nid_f, sp_foo);
  // now should be sane
  BOOST_CHECK_NOT_THROW(r.check_sane(false), logic_error);
  BOOST_CHECK_NOT_THROW(r.check_sane(true), logic_error);

  node_id nid_d = r.create_dir_node(nis);
  // if "foo" exists, can't attach another node at "foo"
  MAYBE(BOOST_CHECK_THROW(r.attach_node(nid_d, sp_foo), logic_error));
  // if "foo" is a file, can't attach a node at "foo/bar"
  MAYBE(BOOST_CHECK_THROW(r.attach_node(nid_d, sp_foo_bar), logic_error));

  BOOST_CHECK(r.detach_node(sp_foo) == nid_f);
  r.attach_node(nid_d, sp_foo);
  r.attach_node(nid_f, sp_foo_bar);
  BOOST_CHECK_NOT_THROW(r.check_sane(false), logic_error);
  BOOST_CHECK_NOT_THROW(r.check_sane(true), logic_error);

  temp_node_id_source nis_tmp;
  node_id nid_tmp = r.create_dir_node(nis_tmp);
  // has a detached node
  MAYBE(BOOST_CHECK_THROW(r.check_sane(false), logic_error));
  MAYBE(BOOST_CHECK_THROW(r.check_sane(true), logic_error));
  r.attach_node(nid_tmp, sp_foo_baz);
  // now has no detached nodes, but one temp node
  MAYBE(BOOST_CHECK_THROW(r.check_sane(false), logic_error));
  BOOST_CHECK_NOT_THROW(r.check_sane(true), logic_error);
}

#undef MAYBE

UNIT_TEST(roster, check_sane_roster)
{
  int total;
  check_sane_roster_do_tests(-1, total);
  for (int to_run = 0; to_run < total; ++to_run)
    {
      L(FL("check_sane_roster_test: loop = %i (of %i)") % to_run % (total - 1));
      int tmp;
      check_sane_roster_do_tests(to_run, tmp);
    }
}

UNIT_TEST(roster, check_sane_roster_loop)
{
  testing_node_id_source nis;
  roster_t r; MM(r);
  split_path root, foo_bar;
  file_path().split(root);
  file_path_internal("foo/bar").split(foo_bar);
  r.attach_node(r.create_dir_node(nis), root);
  node_id nid_foo = r.create_dir_node(nis);
  node_id nid_bar = r.create_dir_node(nis);
  r.attach_node(nid_foo, nid_bar, foo_bar[1]);
  r.attach_node(nid_bar, nid_foo, foo_bar[2]);
  BOOST_CHECK_THROW(r.check_sane(true), logic_error);
}

UNIT_TEST(roster, check_sane_roster_screwy_dir_map)
{
  testing_node_id_source nis;
  roster_t r; MM(r);
  split_path root, foo;
  file_path().split(root);
  file_path_internal("foo").split(foo);
  r.attach_node(r.create_dir_node(nis), root);
  roster_t other; MM(other);
  node_id other_nid = other.create_dir_node(nis);
  dir_t root_n = downcast_to_dir_t(r.get_node(root));
  root_n->children.insert(make_pair(*(foo.end()-1), other.get_node(other_nid)));
  BOOST_CHECK_THROW(r.check_sane(), logic_error);
  // well, but that one was easy, actually, because a dir traversal will hit
  // more nodes than actually exist... so let's make it harder, by making sure
  // that a dir traversal will hit exactly as many nodes as actually exist.
  node_id distractor_nid = r.create_dir_node(nis);
  BOOST_CHECK_THROW(r.check_sane(), logic_error);
  // and even harder, by making that node superficially valid too
  dir_t distractor_n = downcast_to_dir_t(r.get_node(distractor_nid));
  distractor_n->parent = distractor_nid;
  distractor_n->name = *(foo.end()-1);
  distractor_n->children.insert(make_pair(distractor_n->name, distractor_n));
  BOOST_CHECK_THROW(r.check_sane(), logic_error);
}

UNIT_TEST(roster, bad_attr)
{
  testing_node_id_source nis;
  roster_t r; MM(r);
  split_path root;
  file_path().split(root);
  r.attach_node(r.create_dir_node(nis), root);
  BOOST_CHECK_THROW(r.set_attr(root, attr_key("test_key1"),
                               make_pair(false, attr_value("invalid"))),
                    logic_error);
  BOOST_CHECK_NOT_THROW(r.check_sane(true), logic_error);
  safe_insert(r.get_node(root)->attrs,
              make_pair(attr_key("test_key2"),
                        make_pair(false, attr_value("invalid"))));
  BOOST_CHECK_THROW(r.check_sane(true), logic_error);
}

////////////////////////////////////////////////////////////////////////
// exhaustive marking tests
////////////////////////////////////////////////////////////////////////

// The marking/roster generation code is extremely critical.  It is the very
// core of monotone's versioning technology, very complex, and bugs can result
// in corrupt and nonsensical histories (not to mention erroneous merges and
// the like).  Furthermore, the code that implements it is littered with
// case-by-case analysis, where copy-paste errors could easily occur.  So the
// purpose of this section is to systematically and exhaustively test every
// possible case.
//
// Our underlying merger, *-merge, works on scalars, case-by-case.  The cases are:
//   0 parent:
//       a*
//   1 parent:
//       a     a
//       |     |
//       a     b*
//   2 parents:
//       a   a  a   a  a   b  a   b
//        \ /    \ /    \ /    \ /
//         a      b*     c*     a?
//
// Each node has a number of scalars associated with it:
//   * basename+parent
//   * file content (iff a file)
//   * attributes
//
// So for each scalar, we want to test each way it can appear in each of the
// above shapes.  This is made more complex by lifecycles.  We can achieve a 0
// parent node as:
//   * a node in a 0-parent roster (root revision)
//   * a newly added node in a 1-parent roster
//   * a newly added node in a 2-parent roster
// a 1 parent node as:
//   * a pre-existing node in a 1-parent roster
//   * a node in a 2-parent roster that only existed in one of the parents
// a 2 parent node as:
//   * a pre-existing node in a 2-parent roster
//
// Because the basename+parent and file_content scalars have lifetimes that
// exactly match the lifetime of the node they are on, those are all the cases
// for these scalars.  However, attrs make things a bit more complicated,
// because they can be added.  An attr can have 0 parents:
//   * in any of the above cases, with an attribute newly added on the node
// And one parent:
//   * in any of the cases above with one node parent and the attr pre-existing
//   * in a 2-parent node where the attr exists in only one of the parents
//
// Plus, just to be sure, in the merge cases we check both the given example
// and the mirror-reversed one, since the code implementing this could
// conceivably mark merge(A, B) right but get merge(B, A) wrong.  And for the
// scalars that can appear on either files or dirs, we check both.

// The following somewhat elaborate code implements all these checks.  The
// most important background assumption to know, is that it always assumes
// (and this assumption is hard-coded in various places) that it is looking at
// one of the following topologies:
//
//     old
//
//     old
//      |
//     new
//
//     old
//     / \.
// left   right
//     \ /
//     new
//
// There is various tricksiness in making sure that the root directory always
// has the right birth_revision, that nodes are created with good birth
// revisions and sane markings on the scalars we are not interested in, etc.
// This code is ugly and messy and could use refactoring, but it seems to
// work.

////////////////
// These are some basic utility pieces handy for the exhaustive mark tests

namespace
{
  template <typename T> set<T>
  singleton(T const & t)
  {
    set<T> s;
    s.insert(t);
    return s;
  }

  template <typename T> set<T>
  doubleton(T const & t1, T const & t2)
  {
    set<T> s;
    s.insert(t1);
    s.insert(t2);
    return s;
  }

  revision_id old_rid(string("0000000000000000000000000000000000000000"));
  revision_id left_rid(string("1111111111111111111111111111111111111111"));
  revision_id right_rid(string("2222222222222222222222222222222222222222"));
  revision_id new_rid(string("4444444444444444444444444444444444444444"));

  split_path
  split(string const & s)
  {
    split_path sp;
    file_path_internal(s).split(sp);
    return sp;
  }

////////////////
// These classes encapsulate information about all the different scalars
// that *-merge applies to.

  typedef enum { scalar_a, scalar_b, scalar_c,
                 scalar_none, scalar_none_2 } scalar_val;

  void
  dump(scalar_val const & val, string & out)
  {
    switch (val)
      {
      case scalar_a: out = "scalar_a"; break;
      case scalar_b: out = "scalar_b"; break;
      case scalar_c: out = "scalar_c"; break;
      case scalar_none: out = "scalar_none"; break;
      case scalar_none_2: out = "scalar_none_2"; break;
      }
    out += "\n";
  }

  struct a_scalar
  {
    virtual void set(revision_id const & scalar_origin_rid,
                     scalar_val val, set<revision_id> const & this_scalar_mark,
                     roster_t & roster, marking_map & markings)
      = 0;
    virtual ~a_scalar() {};

    node_id_source & nis;
    node_id const root_nid;
    node_id const obj_under_test_nid;
    a_scalar(node_id_source & nis)
      : nis(nis), root_nid(nis.next()), obj_under_test_nid(nis.next())
    {}

    void setup(roster_t & roster, marking_map & markings)
    {
      roster.create_dir_node(root_nid);
      roster.attach_node(root_nid, split(""));
      marking_t marking;
      marking.birth_revision = old_rid;
      marking.parent_name.insert(old_rid);
      safe_insert(markings, make_pair(root_nid, marking));
    }

    virtual string my_type() const = 0;

    virtual void dump(string & out) const
    {
      ostringstream oss;
      oss << "type: " << my_type() << "\n"
          << "root_nid: " << root_nid << "\n"
          << "obj_under_test_nid: " << obj_under_test_nid << "\n";
      out = oss.str();
    }
  };

  void
  dump(a_scalar const & s, string & out)
  {
    s.dump(out);
  }

  struct file_maker
  {
    static void make_obj(revision_id const & scalar_origin_rid, node_id nid,
                         roster_t & roster, marking_map & markings)
    {
      make_file(scalar_origin_rid, nid,
                file_id(string("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")),
                roster, markings);
    }
    static void make_file(revision_id const & scalar_origin_rid, node_id nid,
                          file_id const & fid,
                          roster_t & roster, marking_map & markings)
    {
      roster.create_file_node(fid, nid);
      marking_t marking;
      marking.birth_revision = scalar_origin_rid;
      marking.parent_name = marking.file_content = singleton(scalar_origin_rid);
      safe_insert(markings, make_pair(nid, marking));
    }
  };

  struct dir_maker
  {
    static void make_obj(revision_id const & scalar_origin_rid, node_id nid,
                         roster_t & roster, marking_map & markings)
    {
      roster.create_dir_node(nid);
      marking_t marking;
      marking.birth_revision = scalar_origin_rid;
      marking.parent_name = singleton(scalar_origin_rid);
      safe_insert(markings, make_pair(nid, marking));
    }
  };

  struct file_content_scalar : public a_scalar
  {
    virtual string my_type() const { return "file_content_scalar"; }

    map<scalar_val, file_id> values;
    file_content_scalar(node_id_source & nis)
      : a_scalar(nis)
    {
      safe_insert(values,
                  make_pair(scalar_a,
                            file_id(string("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))));
      safe_insert(values,
                  make_pair(scalar_b,
                            file_id(string("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"))));
      safe_insert(values,
                  make_pair(scalar_c,
                            file_id(string("cccccccccccccccccccccccccccccccccccccccc"))));
    }
    virtual void
    set(revision_id const & scalar_origin_rid, scalar_val val,
        std::set<revision_id> const & this_scalar_mark,
        roster_t & roster, marking_map & markings)
    {
      setup(roster, markings);
      if (val != scalar_none)
        {
          file_maker::make_file(scalar_origin_rid, obj_under_test_nid,
                                safe_get(values, val),
                                roster, markings);
          roster.attach_node(obj_under_test_nid, split("foo"));
          markings[obj_under_test_nid].file_content = this_scalar_mark;
        }
      roster.check_sane_against(markings);
    }
  };

  template <typename T>
  struct X_basename_scalar : public a_scalar
  {
    virtual string my_type() const { return "X_basename_scalar"; }

    map<scalar_val, split_path> values;
    X_basename_scalar(node_id_source & nis)
      : a_scalar(nis)
    {
      safe_insert(values, make_pair(scalar_a, split("a")));
      safe_insert(values, make_pair(scalar_b, split("b")));
      safe_insert(values, make_pair(scalar_c, split("c")));
    }
    virtual void
    set(revision_id const & scalar_origin_rid, scalar_val val,
        std::set<revision_id> const & this_scalar_mark,
        roster_t & roster, marking_map & markings)
    {
      setup(roster, markings);
      if (val != scalar_none)
        {
          T::make_obj(scalar_origin_rid, obj_under_test_nid, roster, markings);
          roster.attach_node(obj_under_test_nid, safe_get(values, val));
          markings[obj_under_test_nid].parent_name = this_scalar_mark;
        }
      roster.check_sane_against(markings);
    }
  };

  template <typename T>
  struct X_parent_scalar : public a_scalar
  {
    virtual string my_type() const { return "X_parent_scalar"; }

    map<scalar_val, split_path> values;
    node_id const a_nid, b_nid, c_nid;
    X_parent_scalar(node_id_source & nis)
      : a_scalar(nis), a_nid(nis.next()), b_nid(nis.next()), c_nid(nis.next())
    {
      safe_insert(values, make_pair(scalar_a, split("dir_a/foo")));
      safe_insert(values, make_pair(scalar_b, split("dir_b/foo")));
      safe_insert(values, make_pair(scalar_c, split("dir_c/foo")));
    }
    void
    setup_dirs(roster_t & roster, marking_map & markings)
    {
      roster.create_dir_node(a_nid);
      roster.attach_node(a_nid, split("dir_a"));
      roster.create_dir_node(b_nid);
      roster.attach_node(b_nid, split("dir_b"));
      roster.create_dir_node(c_nid);
      roster.attach_node(c_nid, split("dir_c"));
      marking_t marking;
      marking.birth_revision = old_rid;
      marking.parent_name.insert(old_rid);
      safe_insert(markings, make_pair(a_nid, marking));
      safe_insert(markings, make_pair(b_nid, marking));
      safe_insert(markings, make_pair(c_nid, marking));
    }
    virtual void
    set(revision_id const & scalar_origin_rid, scalar_val val,
        std::set<revision_id> const & this_scalar_mark,
        roster_t & roster, marking_map & markings)
    {
      setup(roster, markings);
      setup_dirs(roster, markings);
      if (val != scalar_none)
        {
          T::make_obj(scalar_origin_rid, obj_under_test_nid, roster, markings);
          roster.attach_node(obj_under_test_nid, safe_get(values, val));
          markings[obj_under_test_nid].parent_name = this_scalar_mark;
        }
      roster.check_sane_against(markings);
    }
  };

  // this scalar represents an attr whose node already exists, and we put an
  // attr on it.
  template <typename T>
  struct X_attr_existing_node_scalar : public a_scalar
  {
    virtual string my_type() const { return "X_attr_scalar"; }

    map<scalar_val, pair<bool, attr_value> > values;
    X_attr_existing_node_scalar(node_id_source & nis)
      : a_scalar(nis)
    {
      safe_insert(values, make_pair(scalar_a, make_pair(true, attr_value("a"))));
      safe_insert(values, make_pair(scalar_b, make_pair(true, attr_value("b"))));
      safe_insert(values, make_pair(scalar_c, make_pair(true, attr_value("c"))));
    }
    virtual void
    set(revision_id const & scalar_origin_rid, scalar_val val,
        std::set<revision_id> const & this_scalar_mark,
        roster_t & roster, marking_map & markings)
    {
      setup(roster, markings);
      // _not_ scalar_origin_rid, because our object exists everywhere, regardless of
      // when the attr shows up
      T::make_obj(old_rid, obj_under_test_nid, roster, markings);
      roster.attach_node(obj_under_test_nid, split("foo"));
      if (val != scalar_none)
        {
          safe_insert(roster.get_node(obj_under_test_nid)->attrs,
                      make_pair(attr_key("test_key"), safe_get(values, val)));
          markings[obj_under_test_nid].attrs[attr_key("test_key")] = this_scalar_mark;
        }
      roster.check_sane_against(markings);
    }
  };

  // this scalar represents an attr whose node does not exist; we create the
  // node when we create the attr.
  template <typename T>
  struct X_attr_new_node_scalar : public a_scalar
  {
    virtual string my_type() const { return "X_attr_scalar"; }

    map<scalar_val, pair<bool, attr_value> > values;
    X_attr_new_node_scalar(node_id_source & nis)
      : a_scalar(nis)
    {
      safe_insert(values, make_pair(scalar_a, make_pair(true, attr_value("a"))));
      safe_insert(values, make_pair(scalar_b, make_pair(true, attr_value("b"))));
      safe_insert(values, make_pair(scalar_c, make_pair(true, attr_value("c"))));
    }
    virtual void
    set(revision_id const & scalar_origin_rid, scalar_val val,
        std::set<revision_id> const & this_scalar_mark,
        roster_t & roster, marking_map & markings)
    {
      setup(roster, markings);
      if (val != scalar_none)
        {
          T::make_obj(scalar_origin_rid, obj_under_test_nid, roster, markings);
          roster.attach_node(obj_under_test_nid, split("foo"));
          safe_insert(roster.get_node(obj_under_test_nid)->attrs,
                      make_pair(attr_key("test_key"), safe_get(values, val)));
          markings[obj_under_test_nid].attrs[attr_key("test_key")] = this_scalar_mark;
        }
      roster.check_sane_against(markings);
    }
  };

  typedef vector<shared_ptr<a_scalar> > scalars;
  scalars
  all_scalars(node_id_source & nis)
  {
    scalars ss;
    ss.push_back(shared_ptr<a_scalar>(new file_content_scalar(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_basename_scalar<file_maker>(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_basename_scalar<dir_maker>(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_parent_scalar<file_maker>(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_parent_scalar<dir_maker>(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_attr_existing_node_scalar<file_maker>(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_attr_existing_node_scalar<dir_maker>(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_attr_new_node_scalar<file_maker>(nis)));
    ss.push_back(shared_ptr<a_scalar>(new X_attr_new_node_scalar<dir_maker>(nis)));
    return ss;
  }
}

////////////////
// These functions encapsulate the logic for running a particular mark
// scenario with a particular scalar with 0, 1, or 2 roster parents.

static void
run_with_0_roster_parents(a_scalar & s, revision_id scalar_origin_rid,
                          scalar_val new_val,
                          set<revision_id> const & new_mark_set,
                          node_id_source & nis)
{
  MM(s);
  MM(scalar_origin_rid);
  MM(new_val);
  MM(new_mark_set);
  roster_t expected_roster; MM(expected_roster);
  marking_map expected_markings; MM(expected_markings);

  s.set(scalar_origin_rid, new_val, new_mark_set, expected_roster, expected_markings);

  roster_t empty_roster;
  cset cs; MM(cs);
  make_cset(empty_roster, expected_roster, cs);

  roster_t new_roster; MM(new_roster);
  marking_map new_markings; MM(new_markings);
  // this function takes the old parent roster/marking and modifies them; in
  // our case, the parent roster/marking are empty, and so are our
  // roster/marking, so we don't need to do anything special.
  make_roster_for_nonmerge(cs, old_rid, new_roster, new_markings, nis);

  I(equal_up_to_renumbering(expected_roster, expected_markings,
                            new_roster, new_markings));

  marking_map new_markings2; MM(new_markings2);
  mark_roster_with_no_parents(old_rid, new_roster, new_markings2);
  I(new_markings == new_markings2);

  marking_map new_markings3; MM(new_markings3);
  roster_t parent3;
  marking_map old_markings3;
  mark_roster_with_one_parent(parent3, old_markings3, old_rid, new_roster,
                              new_markings3);
  I(new_markings == new_markings3);
}

static void
run_with_1_roster_parent(a_scalar & s,
                         revision_id scalar_origin_rid,
                         scalar_val parent_val,
                         set<revision_id> const & parent_mark_set,
                         scalar_val new_val,
                         set<revision_id> const & new_mark_set,
                         node_id_source & nis)
{
  MM(s);
  MM(scalar_origin_rid);
  MM(parent_val);
  MM(parent_mark_set);
  MM(new_val);
  MM(new_mark_set);
  roster_t parent_roster; MM(parent_roster);
  marking_map parent_markings; MM(parent_markings);
  roster_t expected_roster; MM(expected_roster);
  marking_map expected_markings; MM(expected_markings);

  s.set(scalar_origin_rid, parent_val, parent_mark_set, parent_roster, parent_markings);
  s.set(scalar_origin_rid, new_val, new_mark_set, expected_roster, expected_markings);

  cset cs; MM(cs);
  make_cset(parent_roster, expected_roster, cs);

  roster_t new_roster; MM(new_roster);
  marking_map new_markings; MM(new_markings);
  new_roster = parent_roster;
  new_markings = parent_markings;
  make_roster_for_nonmerge(cs, new_rid, new_roster, new_markings, nis);

  I(equal_up_to_renumbering(expected_roster, expected_markings,
                            new_roster, new_markings));

  marking_map new_markings2; MM(new_markings2);
  mark_roster_with_one_parent(parent_roster, parent_markings,
                              new_rid, new_roster, new_markings2);
  I(new_markings == new_markings2);
}

static void
run_with_2_roster_parents(a_scalar & s,
                          revision_id scalar_origin_rid,
                          scalar_val left_val,
                          set<revision_id> const & left_mark_set,
                          scalar_val right_val,
                          set<revision_id> const & right_mark_set,
                          scalar_val new_val,
                          set<revision_id> const & new_mark_set,
                          node_id_source & nis)
{
  MM(s);
  MM(scalar_origin_rid);
  MM(left_val);
  MM(left_mark_set);
  MM(right_val);
  MM(right_mark_set);
  MM(new_val);
  MM(new_mark_set);
  roster_t left_roster; MM(left_roster);
  roster_t right_roster; MM(right_roster);
  roster_t expected_roster; MM(expected_roster);
  marking_map left_markings; MM(left_markings);
  marking_map right_markings; MM(right_markings);
  marking_map expected_markings; MM(expected_markings);

  s.set(scalar_origin_rid, left_val, left_mark_set, left_roster, left_markings);
  s.set(scalar_origin_rid, right_val, right_mark_set, right_roster, right_markings);
  s.set(scalar_origin_rid, new_val, new_mark_set, expected_roster, expected_markings);

  cset left_cs; MM(left_cs);
  cset right_cs; MM(right_cs);
  make_cset(left_roster, expected_roster, left_cs);
  make_cset(right_roster, expected_roster, right_cs);

  set<revision_id> left_uncommon_ancestors; MM(left_uncommon_ancestors);
  left_uncommon_ancestors.insert(left_rid);
  set<revision_id> right_uncommon_ancestors; MM(right_uncommon_ancestors);
  right_uncommon_ancestors.insert(right_rid);

  roster_t new_roster; MM(new_roster);
  marking_map new_markings; MM(new_markings);
  make_roster_for_merge(left_rid, left_roster, left_markings, left_cs,
                        left_uncommon_ancestors,
                        right_rid, right_roster, right_markings, right_cs,
                        right_uncommon_ancestors,
                        new_rid, new_roster, new_markings,
                        nis);

  I(equal_up_to_renumbering(expected_roster, expected_markings,
                            new_roster, new_markings));
}

////////////////
// These functions encapsulate all the different ways to get a 0 parent node,
// a 1 parent node, and a 2 parent node.

////////////////
// These functions encapsulate all the different ways to get a 0 parent
// scalar, a 1 parent scalar, and a 2 parent scalar.

// FIXME: have clients just use s.nis instead of passing it separately...?

static void
run_a_2_scalar_parent_mark_scenario_exact(revision_id const & scalar_origin_rid,
                                          scalar_val left_val,
                                          set<revision_id> const & left_mark_set,
                                          scalar_val right_val,
                                          set<revision_id> const & right_mark_set,
                                          scalar_val new_val,
                                          set<revision_id> const & new_mark_set)
{
  testing_node_id_source nis;
  scalars ss = all_scalars(nis);
  for (scalars::const_iterator i = ss.begin(); i != ss.end(); ++i)
    {
      run_with_2_roster_parents(**i, scalar_origin_rid,
                                left_val, left_mark_set,
                                right_val, right_mark_set,
                                new_val, new_mark_set,
                                nis);
    }
}

static revision_id
flip_revision_id(revision_id const & rid)
{
  if (rid == old_rid || rid == new_rid)
    return rid;
  else if (rid == left_rid)
    return right_rid;
  else if (rid == right_rid)
    return left_rid;
  else
    I(false);
}

static set<revision_id>
flip_revision(set<revision_id> const & rids)
{
  set<revision_id> flipped_rids;
  for (set<revision_id>::const_iterator i = rids.begin(); i != rids.end(); ++i)
    flipped_rids.insert(flip_revision_id(*i));
  return flipped_rids;
}

static void
run_a_2_scalar_parent_mark_scenario(revision_id const & scalar_origin_rid,
                                    scalar_val left_val,
                                    set<revision_id> const & left_mark_set,
                                    scalar_val right_val,
                                    set<revision_id> const & right_mark_set,
                                    scalar_val new_val,
                                    set<revision_id> const & new_mark_set)
{
  // run both what we're given...
  run_a_2_scalar_parent_mark_scenario_exact(scalar_origin_rid,
                                            left_val, left_mark_set,
                                            right_val, right_mark_set,
                                            new_val, new_mark_set);
  // ...and its symmetric reflection.  but we have to flip the mark set,
  // because the exact stuff has hard-coded the names of the various
  // revisions and their uncommon ancestor sets.
  {
    set<revision_id> flipped_left_mark_set = flip_revision(left_mark_set);
    set<revision_id> flipped_right_mark_set = flip_revision(right_mark_set);
    set<revision_id> flipped_new_mark_set = flip_revision(new_mark_set);

    run_a_2_scalar_parent_mark_scenario_exact(flip_revision_id(scalar_origin_rid),
                                              right_val, flipped_right_mark_set,
                                              left_val, flipped_left_mark_set,
                                              new_val, flipped_new_mark_set);
  }
}

static void
run_a_2_scalar_parent_mark_scenario(scalar_val left_val,
                                    set<revision_id> const & left_mark_set,
                                    scalar_val right_val,
                                    set<revision_id> const & right_mark_set,
                                    scalar_val new_val,
                                    set<revision_id> const & new_mark_set)
{
  run_a_2_scalar_parent_mark_scenario(old_rid,
                                      left_val, left_mark_set,
                                      right_val, right_mark_set,
                                      new_val, new_mark_set);
}

static void
run_a_1_scalar_parent_mark_scenario(scalar_val parent_val,
                                    set<revision_id> const & parent_mark_set,
                                    scalar_val new_val,
                                    set<revision_id> const & new_mark_set)
{
  {
    testing_node_id_source nis;
    scalars ss = all_scalars(nis);
    for (scalars::const_iterator i = ss.begin(); i != ss.end(); ++i)
      run_with_1_roster_parent(**i, old_rid,
                               parent_val, parent_mark_set,
                               new_val, new_mark_set,
                               nis);
  }
  // this is an asymmetric, test, so run it via the code that will test it
  // both ways
  run_a_2_scalar_parent_mark_scenario(left_rid,
                                      parent_val, parent_mark_set,
                                      scalar_none, set<revision_id>(),
                                      new_val, new_mark_set);
}

static void
run_a_0_scalar_parent_mark_scenario()
{
  {
    testing_node_id_source nis;
    scalars ss = all_scalars(nis);
    for (scalars::const_iterator i = ss.begin(); i != ss.end(); ++i)
      {
        run_with_0_roster_parents(**i, old_rid, scalar_a, singleton(old_rid), nis);
        run_with_1_roster_parent(**i, new_rid,
                                 scalar_none, set<revision_id>(),
                                 scalar_a, singleton(new_rid),
                                 nis);
        run_with_2_roster_parents(**i, new_rid,
                                  scalar_none, set<revision_id>(),
                                  scalar_none, set<revision_id>(),
                                  scalar_a, singleton(new_rid),
                                  nis);
      }
  }
}

////////////////
// These functions contain the actual list of *-merge cases that we would like
// to test.

UNIT_TEST(roster, all_0_scalar_parent_mark_scenarios)
{
  L(FL("TEST: begin checking 0-parent marking"));
  // a*
  run_a_0_scalar_parent_mark_scenario();
  L(FL("TEST: end checking 0-parent marking"));
}

UNIT_TEST(roster, all_1_scalar_parent_mark_scenarios)
{
  L(FL("TEST: begin checking 1-parent marking"));
  //  a
  //  |
  //  a
  run_a_1_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_a, singleton(old_rid));
  //  a*
  //  |
  //  a
  run_a_1_scalar_parent_mark_scenario(scalar_a, singleton(left_rid),
                                      scalar_a, singleton(left_rid));
  // a*  a*
  //  \ /
  //   a
  //   |
  //   a
  run_a_1_scalar_parent_mark_scenario(scalar_a, doubleton(left_rid, right_rid),
                                      scalar_a, doubleton(left_rid, right_rid));
  //  a
  //  |
  //  b*
  run_a_1_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_b, singleton(new_rid));
  //  a*
  //  |
  //  b*
  run_a_1_scalar_parent_mark_scenario(scalar_a, singleton(left_rid),
                                      scalar_b, singleton(new_rid));
  // a*  a*
  //  \ /
  //   a
  //   |
  //   b*
  run_a_1_scalar_parent_mark_scenario(scalar_a, doubleton(left_rid, right_rid),
                                      scalar_b, singleton(new_rid));
  L(FL("TEST: end checking 1-parent marking"));
}

UNIT_TEST(roster, all_2_scalar_parent_mark_scenarios)
{
  L(FL("TEST: begin checking 2-parent marking"));
  ///////////////////////////////////////////////////////////////////
  // a   a
  //  \ /
  //   a
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_a, singleton(old_rid),
                                      scalar_a, singleton(old_rid));
  // a   a*
  //  \ /
  //   a
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_a, singleton(right_rid),
                                      scalar_a, doubleton(old_rid, right_rid));
  // a*  a*
  //  \ /
  //   a
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(left_rid),
                                      scalar_a, singleton(right_rid),
                                      scalar_a, doubleton(left_rid, right_rid));

  ///////////////////////////////////////////////////////////////////
  // a   a
  //  \ /
  //   b*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_a, singleton(old_rid),
                                      scalar_b, singleton(new_rid));
  // a   a*
  //  \ /
  //   b*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_a, singleton(right_rid),
                                      scalar_b, singleton(new_rid));
  // a*  a*
  //  \ /
  //   b*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(left_rid),
                                      scalar_a, singleton(right_rid),
                                      scalar_b, singleton(new_rid));

  ///////////////////////////////////////////////////////////////////
  //  a*  b*
  //   \ /
  //    c*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(left_rid),
                                      scalar_b, singleton(right_rid),
                                      scalar_c, singleton(new_rid));
  //  a   b*
  //   \ /
  //    c*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_b, singleton(right_rid),
                                      scalar_c, singleton(new_rid));
  // this case cannot actually arise, because if *(a) = *(b) then val(a) =
  // val(b).  but hey.
  //  a   b
  //   \ /
  //    c*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_b, singleton(old_rid),
                                      scalar_c, singleton(new_rid));

  ///////////////////////////////////////////////////////////////////
  //  a*  b*
  //   \ /
  //    a*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(left_rid),
                                      scalar_b, singleton(right_rid),
                                      scalar_a, singleton(new_rid));
  //  a   b*
  //   \ /
  //    a*
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(old_rid),
                                      scalar_b, singleton(right_rid),
                                      scalar_a, singleton(new_rid));
  //  a*  b
  //   \ /
  //    a
  run_a_2_scalar_parent_mark_scenario(scalar_a, singleton(left_rid),
                                      scalar_b, singleton(old_rid),
                                      scalar_a, singleton(left_rid));

  // FIXME: be nice to test:
  //  a*  a*  b
  //   \ /   /
  //    a   /
  //     \ /
  //      a
  L(FL("TEST: end checking 2-parent marking"));
}

// there is _one_ remaining case that the above tests miss, because they
// couple scalar lifetimes and node lifetimes.  Maybe they shouldn't do that,
// but anyway... until someone decides to refactor, we need this.  The basic
// issue is that for content and name scalars, the scalar lifetime and the
// node lifetime are identical.  For attrs, this isn't necessarily true.  This
// is why we have two different attr scalars.  Let's say that "." means a node
// that doesn't exist, and "+" means a node that exists but has no roster.
// The first scalar checks cases like
//     +
//     |
//     a
//
//   +   +
//    \ /
//     a*
//
//   a*  +
//    \ /
//     a
// and the second one checks cases like
//     .
//     |
//     a
//
//   .   .
//    \ /
//     a*
//
//   a*  .
//    \ /
//     a
// Between them, they cover _almost_ all possibilities.  The one that they
// miss is:
//   .   +
//    \ /
//     a*
// (and its reflection).
// That is what this test checks.
// Sorry it's so code-duplication-iferous.  Refactors would be good...

namespace
{
  // this scalar represents an attr whose node may or may not already exist
  template <typename T>
  struct X_attr_mixed_scalar : public a_scalar
  {
    virtual string my_type() const { return "X_attr_scalar"; }

    map<scalar_val, pair<bool, attr_value> > values;
    X_attr_mixed_scalar(node_id_source & nis)
      : a_scalar(nis)
    {
      safe_insert(values, make_pair(scalar_a, make_pair(true, attr_value("a"))));
      safe_insert(values, make_pair(scalar_b, make_pair(true, attr_value("b"))));
      safe_insert(values, make_pair(scalar_c, make_pair(true, attr_value("c"))));
    }
    virtual void
    set(revision_id const & scalar_origin_rid, scalar_val val,
        std::set<revision_id> const & this_scalar_mark,
        roster_t & roster, marking_map & markings)
    {
      setup(roster, markings);
      // scalar_none is . in the above notation
      // and scalar_none_2 is +
      if (val != scalar_none)
        {
          T::make_obj(scalar_origin_rid, obj_under_test_nid, roster, markings);
          roster.attach_node(obj_under_test_nid, split("foo"));
        }
      if (val != scalar_none && val != scalar_none_2)
        {
          safe_insert(roster.get_node(obj_under_test_nid)->attrs,
                      make_pair(attr_key("test_key"), safe_get(values, val)));
          markings[obj_under_test_nid].attrs[attr_key("test_key")] = this_scalar_mark;
        }
      roster.check_sane_against(markings);
    }
  };
}

UNIT_TEST(roster, residual_attr_mark_scenario)
{
  L(FL("TEST: begin checking residual attr marking case"));
  {
    testing_node_id_source nis;
    X_attr_mixed_scalar<file_maker> s(nis);
    run_with_2_roster_parents(s, left_rid,
                              scalar_none_2, set<revision_id>(),
                              scalar_none, set<revision_id>(),
                              scalar_a, singleton(new_rid),
                              nis);
  }
  {
    testing_node_id_source nis;
    X_attr_mixed_scalar<dir_maker> s(nis);
    run_with_2_roster_parents(s, left_rid,
                              scalar_none_2, set<revision_id>(),
                              scalar_none, set<revision_id>(),
                              scalar_a, singleton(new_rid),
                              nis);
  }
  {
    testing_node_id_source nis;
    X_attr_mixed_scalar<file_maker> s(nis);
    run_with_2_roster_parents(s, right_rid,
                              scalar_none, set<revision_id>(),
                              scalar_none_2, set<revision_id>(),
                              scalar_a, singleton(new_rid),
                              nis);
  }
  {
    testing_node_id_source nis;
    X_attr_mixed_scalar<dir_maker> s(nis);
    run_with_2_roster_parents(s, right_rid,
                              scalar_none, set<revision_id>(),
                              scalar_none_2, set<revision_id>(),
                              scalar_a, singleton(new_rid),
                              nis);
  }
  L(FL("TEST: end checking residual attr marking case"));
}

////////////////////////////////////////////////////////////////////////
// end of exhaustive tests
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
// lifecyle tests
////////////////////////////////////////////////////////////////////////

// nodes can't survive dying on one side of a merge
UNIT_TEST(roster, die_die_die_merge)
{
  roster_t left_roster; MM(left_roster);
  marking_map left_markings; MM(left_markings);
  roster_t right_roster; MM(right_roster);
  marking_map right_markings; MM(right_markings);
  testing_node_id_source nis;

  // left roster is empty except for the root
  left_roster.attach_node(left_roster.create_dir_node(nis), split(""));
  marking_t an_old_marking;
  an_old_marking.birth_revision = old_rid;
  an_old_marking.parent_name = singleton(old_rid);
  safe_insert(left_markings, make_pair(left_roster.get_node(split(""))->self,
                                       an_old_marking));
  // right roster is identical, except for a dir created in the old rev
  right_roster = left_roster;
  right_markings = left_markings;
  right_roster.attach_node(right_roster.create_dir_node(nis), split("foo"));
  safe_insert(right_markings, make_pair(right_roster.get_node(split("foo"))->self,
                                        an_old_marking));

  left_roster.check_sane_against(left_markings);
  right_roster.check_sane_against(right_markings);

  cset left_cs; MM(left_cs);
  // we add the node
  left_cs.dirs_added.insert(split("foo"));
  // we do nothing
  cset right_cs; MM(right_cs);

  roster_t new_roster; MM(new_roster);
  marking_map new_markings; MM(new_markings);

  // because the dir was created in the old rev, the left side has logically
  // seen it and killed it, so it needs to be dead in the result.
  BOOST_CHECK_THROW(
     make_roster_for_merge(left_rid, left_roster, left_markings, left_cs,
                           singleton(left_rid),
                           right_rid, right_roster, right_markings, right_cs,
                           singleton(right_rid),
                           new_rid, new_roster, new_markings,
                           nis),
     logic_error);
  BOOST_CHECK_THROW(
     make_roster_for_merge(right_rid, right_roster, right_markings, right_cs,
                           singleton(right_rid),
                           left_rid, left_roster, left_markings, left_cs,
                           singleton(left_rid),
                           new_rid, new_roster, new_markings,
                           nis),
     logic_error);
}
// nodes can't change type file->dir or dir->file
//    make_cset fails
//    merging a file and a dir with the same nid and no mention of what should
//      happen to them fails

UNIT_TEST(roster, same_nid_diff_type)
{
  randomizer rng;
  testing_node_id_source nis;

  roster_t dir_roster; MM(dir_roster);
  marking_map dir_markings; MM(dir_markings);
  dir_roster.attach_node(dir_roster.create_dir_node(nis), split(""));
  marking_t marking;
  marking.birth_revision = old_rid;
  marking.parent_name = singleton(old_rid);
  safe_insert(dir_markings, make_pair(dir_roster.get_node(split(""))->self,
                                      marking));

  roster_t file_roster; MM(file_roster);
  marking_map file_markings; MM(file_markings);
  file_roster = dir_roster;
  file_markings = dir_markings;

  // okay, they both have the root dir
  node_id nid = nis.next();
  dir_roster.create_dir_node(nid);
  dir_roster.attach_node(nid, split("foo"));
  safe_insert(dir_markings, make_pair(nid, marking));

  file_roster.create_file_node(new_ident(rng), nid);
  file_roster.attach_node(nid, split("foo"));
  marking.file_content = singleton(old_rid);
  safe_insert(file_markings, make_pair(nid, marking));

  dir_roster.check_sane_against(dir_markings);
  file_roster.check_sane_against(file_markings);

  cset cs; MM(cs);
  BOOST_CHECK_THROW(make_cset(dir_roster, file_roster, cs), logic_error);
  BOOST_CHECK_THROW(make_cset(file_roster, dir_roster, cs), logic_error);

  cset left_cs; MM(left_cs);
  cset right_cs; MM(right_cs);
  roster_t new_roster; MM(new_roster);
  marking_map new_markings; MM(new_markings);
  BOOST_CHECK_THROW(
     make_roster_for_merge(left_rid, dir_roster, dir_markings, left_cs,
                           singleton(left_rid),
                           right_rid, file_roster, file_markings, right_cs,
                           singleton(right_rid),
                           new_rid, new_roster, new_markings,
                           nis),
     logic_error);
  BOOST_CHECK_THROW(
     make_roster_for_merge(left_rid, file_roster, file_markings, left_cs,
                           singleton(left_rid),
                           right_rid, dir_roster, dir_markings, right_cs,
                           singleton(right_rid),
                           new_rid, new_roster, new_markings,
                           nis),
     logic_error);

}

UNIT_TEST(roster, write_roster)
{
  L(FL("TEST: write_roster_test"));
  roster_t r; MM(r);
  marking_map mm; MM(mm);

  testing_node_id_source nis;
  split_path root, foo, xx, fo, foo_bar, foo_ang, foo_zoo;
  file_path().split(root);
  file_path_internal("foo").split(foo);
  file_path_internal("foo/ang").split(foo_ang);
  file_path_internal("foo/bar").split(foo_bar);
  file_path_internal("foo/zoo").split(foo_zoo);
  file_path_internal("fo").split(fo);
  file_path_internal("xx").split(xx);

  file_id f1(string("1111111111111111111111111111111111111111"));
  revision_id rid(string("1234123412341234123412341234123412341234"));
  node_id nid;

  // if adding new nodes, add them at the end to keep the node_id order

  nid = nis.next();
  r.create_dir_node(nid);
  r.attach_node(nid, root);
  mark_new_node(rid, r.get_node(nid), mm[nid]);

  nid = nis.next();
  r.create_dir_node(nid);
  r.attach_node(nid, foo);
  mark_new_node(rid, r.get_node(nid), mm[nid]);

  nid = nis.next();
  r.create_dir_node(nid);
  r.attach_node(nid, xx);
  r.set_attr(xx, attr_key("say"), attr_value("hello"));
  mark_new_node(rid, r.get_node(nid), mm[nid]);

  nid = nis.next();
  r.create_dir_node(nid);
  r.attach_node(nid, fo);
  mark_new_node(rid, r.get_node(nid), mm[nid]);

  // check that files aren't ordered separately to dirs & vice versa
  nid = nis.next();
  r.create_file_node(f1, nid);
  r.attach_node(nid, foo_bar);
  r.set_attr(foo_bar, attr_key("fascist"), attr_value("tidiness"));
  mark_new_node(rid, r.get_node(nid), mm[nid]);

  nid = nis.next();
  r.create_dir_node(nid);
  r.attach_node(nid, foo_ang);
  mark_new_node(rid, r.get_node(nid), mm[nid]);

  nid = nis.next();
  r.create_dir_node(nid);
  r.attach_node(nid, foo_zoo);
  r.set_attr(foo_zoo, attr_key("regime"), attr_value("new"));
  r.clear_attr(foo_zoo, attr_key("regime"));
  mark_new_node(rid, r.get_node(nid), mm[nid]);

  {
    // manifest first
    manifest_data mdat; MM(mdat);
    write_manifest_of_roster(r, mdat);

    manifest_data
      expected(string("format_version \"1\"\n"
                      "\n"
                      "dir \"\"\n"
                      "\n"
                      "dir \"fo\"\n"
                      "\n"
                      "dir \"foo\"\n"
                      "\n"
                      "dir \"foo/ang\"\n"
                      "\n"
                      "   file \"foo/bar\"\n"
                      "content [1111111111111111111111111111111111111111]\n"
                      "   attr \"fascist\" \"tidiness\"\n"
                      "\n"
                      "dir \"foo/zoo\"\n"
                      "\n"
                      " dir \"xx\"\n"
                      "attr \"say\" \"hello\"\n"
                      ));
    MM(expected);

    BOOST_CHECK_NOT_THROW( I(expected == mdat), logic_error);
  }

  {
    // full roster with local parts
    roster_data rdat; MM(rdat);
    write_roster_and_marking(r, mm, rdat);

    // node_id order is a hassle.
    // root 1, foo 2, xx 3, fo 4, foo_bar 5, foo_ang 6, foo_zoo 7
    roster_data
      expected(string("format_version \"1\"\n"
                      "\n"
                      "      dir \"\"\n"
                      "    ident \"1\"\n"
                      "    birth [1234123412341234123412341234123412341234]\n"
                      "path_mark [1234123412341234123412341234123412341234]\n"
                      "\n"
                      "      dir \"fo\"\n"
                      "    ident \"4\"\n"
                      "    birth [1234123412341234123412341234123412341234]\n"
                      "path_mark [1234123412341234123412341234123412341234]\n"
                      "\n"
                      "      dir \"foo\"\n"
                      "    ident \"2\"\n"
                      "    birth [1234123412341234123412341234123412341234]\n"
                      "path_mark [1234123412341234123412341234123412341234]\n"
                      "\n"
                      "      dir \"foo/ang\"\n"
                      "    ident \"6\"\n"
                      "    birth [1234123412341234123412341234123412341234]\n"
                      "path_mark [1234123412341234123412341234123412341234]\n"
                      "\n"
                      "        file \"foo/bar\"\n"
                      "     content [1111111111111111111111111111111111111111]\n"
                      "       ident \"5\"\n"
                      "        attr \"fascist\" \"tidiness\"\n"
                      "       birth [1234123412341234123412341234123412341234]\n"
                      "   path_mark [1234123412341234123412341234123412341234]\n"
                      "content_mark [1234123412341234123412341234123412341234]\n"
                      "   attr_mark \"fascist\" [1234123412341234123412341234123412341234]\n"
                      "\n"
                      "         dir \"foo/zoo\"\n"
                      "       ident \"7\"\n"
                      "dormant_attr \"regime\"\n"
                      "       birth [1234123412341234123412341234123412341234]\n"
                      "   path_mark [1234123412341234123412341234123412341234]\n"
                      "   attr_mark \"regime\" [1234123412341234123412341234123412341234]\n"
                      "\n"
                      "      dir \"xx\"\n"
                      "    ident \"3\"\n"
                      "     attr \"say\" \"hello\"\n"
                      "    birth [1234123412341234123412341234123412341234]\n"
                      "path_mark [1234123412341234123412341234123412341234]\n"
                      "attr_mark \"say\" [1234123412341234123412341234123412341234]\n"
                      ));
    MM(expected);

    BOOST_CHECK_NOT_THROW( I(expected == rdat), logic_error);
  }
}

UNIT_TEST(roster, check_sane_against)
{
  testing_node_id_source nis;
  split_path root, foo, bar;
  file_path().split(root);
  file_path_internal("foo").split(foo);
  file_path_internal("bar").split(bar);

  file_id f1(string("1111111111111111111111111111111111111111"));
  revision_id rid(string("1234123412341234123412341234123412341234"));
  node_id nid;

  {
    L(FL("TEST: check_sane_against_test, no extra nodes in rosters"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, foo);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, bar);
    // missing the marking

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, no extra nodes in markings"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, foo);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, bar);
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    r.detach_node(bar);

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, missing birth rev"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, foo);
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    mm[nid].birth_revision = revision_id();

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, missing path mark"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, foo);
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    mm[nid].parent_name.clear();

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, missing content mark"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_file_node(f1, nid);
    r.attach_node(nid, foo);
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    mm[nid].file_content.clear();

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, extra content mark"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    mark_new_node(rid, r.get_node(nid), mm[nid]);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, foo);
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    mm[nid].file_content.insert(rid);

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, missing attr mark"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    // NB: mark and _then_ add attr
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    r.set_attr(root, attr_key("my_key"), attr_value("my_value"));

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, empty attr mark"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    r.set_attr(root, attr_key("my_key"), attr_value("my_value"));
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    mm[nid].attrs[attr_key("my_key")].clear();

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }

  {
    L(FL("TEST: check_sane_against_test, extra attr mark"));
    roster_t r; MM(r);
    marking_map mm; MM(mm);

    nid = nis.next();
    r.create_dir_node(nid);
    r.attach_node(nid, root);
    r.set_attr(root, attr_key("my_key"), attr_value("my_value"));
    mark_new_node(rid, r.get_node(nid), mm[nid]);
    mm[nid].attrs[attr_key("my_second_key")].insert(rid);

    BOOST_CHECK_THROW(r.check_sane_against(mm), logic_error);
  }
}

static void
check_post_roster_unification_ok(roster_t const & left,
                                 roster_t const & right)
{
  MM(left);
  MM(right);
  I(left == right);
  left.check_sane();
  right.check_sane();
}

static void
create_some_new_temp_nodes(temp_node_id_source & nis,
                           roster_t & left_ros,
                           set<node_id> & left_new_nodes,
                           roster_t & right_ros,
                           set<node_id> & right_new_nodes,
                           randomizer & rng)
{
  size_t n_nodes = 10 + (rng.uniform(30));
  editable_roster_base left_er(left_ros, nis);
  editable_roster_base right_er(right_ros, nis);

  // Stick in a root if there isn't one.
  if (!left_ros.has_root())
    {
      I(!right_ros.has_root());
      split_path root;
      root.push_back(the_null_component);

      node_id left_nid = left_er.create_dir_node();
      left_new_nodes.insert(left_nid);
      left_er.attach_node(left_nid, root);

      node_id right_nid = right_er.create_dir_node();
      right_new_nodes.insert(right_nid);
      right_er.attach_node(right_nid, root);
    }

  // Now throw in a bunch of others
  for (size_t i = 0; i < n_nodes; ++i)
    {
      node_t left_n = random_element(left_ros.all_nodes(), rng)->second;

      node_id left_nid, right_nid;
      if (rng.flip())
        {
          left_nid = left_er.create_dir_node();
          right_nid = right_er.create_dir_node();
        }
      else
        {
          file_id fid = new_ident(rng);
          left_nid = left_er.create_file_node(fid);
          right_nid = right_er.create_file_node(fid);
        }

      left_new_nodes.insert(left_nid);
      right_new_nodes.insert(right_nid);

      split_path pth;
      left_ros.get_name(left_n->self, pth);

      I(right_ros.has_node(pth));

      if (is_file_t(left_n) || (pth.size() > 1 && rng.flip()))
        // Add a sibling of an existing entry.
        pth[pth.size() - 1] = new_component(rng);
      else
        // Add a child of an existing entry.
        pth.push_back(new_component(rng));

      left_er.attach_node(left_nid, pth);
      right_er.attach_node(right_nid, pth);
    }
}

UNIT_TEST(roster, unify_rosters_randomized)
{
  L(FL("TEST: begin checking unification of rosters (randomly)"));
  temp_node_id_source tmp_nis;
  testing_node_id_source test_nis;
  roster_t left, right;
  randomizer rng;
  for (size_t i = 0; i < 30; ++i)
    {
      set<node_id> left_new, right_new;
      create_some_new_temp_nodes(tmp_nis, left, left_new, right, right_new, rng);
      create_some_new_temp_nodes(tmp_nis, right, right_new, left, left_new, rng);
      unify_rosters(left, left_new, right, right_new, test_nis);
      check_post_roster_unification_ok(left, right);
    }
  L(FL("TEST: end checking unification of rosters (randomly)"));
}

UNIT_TEST(roster, unify_rosters_end_to_end_ids)
{
  L(FL("TEST: begin checking unification of rosters (end to end, ids)"));
  revision_id has_rid = left_rid;
  revision_id has_not_rid = right_rid;
  file_id my_fid(string("9012901290129012901290129012901290129012"));

  testing_node_id_source nis;

  roster_t has_not_roster; MM(has_not_roster);
  marking_map has_not_markings; MM(has_not_markings);
  {
    has_not_roster.attach_node(has_not_roster.create_dir_node(nis), split(""));
    marking_t root_marking;
    root_marking.birth_revision = old_rid;
    root_marking.parent_name = singleton(old_rid);
    safe_insert(has_not_markings, make_pair(has_not_roster.root()->self,
                                            root_marking));
  }

  roster_t has_roster = has_not_roster; MM(has_roster);
  marking_map has_markings = has_not_markings; MM(has_markings);
  node_id new_id;
  {
    new_id = has_roster.create_file_node(my_fid, nis);
    has_roster.attach_node(new_id, split("foo"));
    marking_t file_marking;
    file_marking.birth_revision = has_rid;
    file_marking.parent_name = file_marking.file_content = singleton(has_rid);
    safe_insert(has_markings, make_pair(new_id, file_marking));
  }

  cset add_cs; MM(add_cs);
  safe_insert(add_cs.files_added, make_pair(split("foo"), my_fid));
  cset no_add_cs; MM(no_add_cs);

  // added in left, then merged
  {
    roster_t new_roster; MM(new_roster);
    marking_map new_markings; MM(new_markings);
    make_roster_for_merge(has_rid, has_roster, has_markings, no_add_cs,
                          singleton(has_rid),
                          has_not_rid, has_not_roster, has_not_markings, add_cs,
                          singleton(has_not_rid),
                          new_rid, new_roster, new_markings,
                          nis);
    I(new_roster.get_node(split("foo"))->self == new_id);
  }
  // added in right, then merged
  {
    roster_t new_roster; MM(new_roster);
    marking_map new_markings; MM(new_markings);
    make_roster_for_merge(has_not_rid, has_not_roster, has_not_markings, add_cs,
                          singleton(has_not_rid),
                          has_rid, has_roster, has_markings, no_add_cs,
                          singleton(has_rid),
                          new_rid, new_roster, new_markings,
                          nis);
    I(new_roster.get_node(split("foo"))->self == new_id);
  }
  // added in merge
  // this is a little "clever", it uses the same has_not_roster twice, but the
  // second time it passes the has_rid, to make it a possible graph.
  {
    roster_t new_roster; MM(new_roster);
    marking_map new_markings; MM(new_markings);
    make_roster_for_merge(has_not_rid, has_not_roster, has_not_markings, add_cs,
                          singleton(has_not_rid),
                          has_rid, has_not_roster, has_not_markings, add_cs,
                          singleton(has_rid),
                          new_rid, new_roster, new_markings,
                          nis);
    I(new_roster.get_node(split("foo"))->self
      != has_roster.get_node(split("foo"))->self);
  }
  L(FL("TEST: end checking unification of rosters (end to end, ids)"));
}

UNIT_TEST(roster, unify_rosters_end_to_end_attr_corpses)
{
  L(FL("TEST: begin checking unification of rosters (end to end, attr corpses)"));
  revision_id first_rid = left_rid;
  revision_id second_rid = right_rid;
  file_id my_fid(string("9012901290129012901290129012901290129012"));

  testing_node_id_source nis;

  // Both rosters have the file "foo"; in one roster, it has the attr corpse
  // "testfoo1", and in the other, it has the attr corpse "testfoo2".  Only
  // the second roster has the file "bar"; it has the attr corpse "testbar".

  roster_t first_roster; MM(first_roster);
  marking_map first_markings; MM(first_markings);
  node_id foo_id;
  {
    first_roster.attach_node(first_roster.create_dir_node(nis), split(""));
    marking_t marking;
    marking.birth_revision = old_rid;
    marking.parent_name = singleton(old_rid);
    safe_insert(first_markings, make_pair(first_roster.root()->self, marking));

    foo_id = first_roster.create_file_node(my_fid, nis);
    first_roster.attach_node(foo_id, split("foo"));
    marking.file_content = singleton(old_rid);
    safe_insert(first_markings,
                make_pair(first_roster.get_node(split("foo"))->self, marking));
  }

  roster_t second_roster = first_roster; MM(second_roster);
  marking_map second_markings = first_markings; MM(second_markings);
  {
    second_roster.attach_node(second_roster.create_file_node(my_fid, nis),
                              split("bar"));
    safe_insert(second_roster.get_node(split("bar"))->attrs,
                make_pair(attr_key("testbar"), make_pair(false, attr_value())));
    marking_t marking;
    marking.birth_revision = second_rid;
    marking.parent_name = marking.file_content = singleton(second_rid);
    safe_insert(marking.attrs,
                make_pair(attr_key("testbar"), singleton(second_rid)));
    safe_insert(second_markings,
                make_pair(second_roster.get_node(split("bar"))->self, marking));
  }

  // put in the attrs on foo
  {
    safe_insert(first_roster.get_node(foo_id)->attrs,
                make_pair(attr_key("testfoo1"), make_pair(false, attr_value())));
    safe_insert(first_markings.find(foo_id)->second.attrs,
                make_pair(attr_key("testfoo1"), singleton(first_rid)));
    safe_insert(second_roster.get_node(foo_id)->attrs,
                make_pair(attr_key("testfoo2"), make_pair(false, attr_value())));
    safe_insert(second_markings.find(foo_id)->second.attrs,
                make_pair(attr_key("testfoo2"), singleton(second_rid)));
  }

  cset add_cs; MM(add_cs);
  safe_insert(add_cs.files_added, make_pair(split("bar"), my_fid));
  cset no_add_cs; MM(no_add_cs);

  {
    roster_t new_roster; MM(new_roster);
    marking_map new_markings; MM(new_markings);
    make_roster_for_merge(first_rid, first_roster, first_markings, add_cs,
                          singleton(first_rid),
                          second_rid, second_roster, second_markings, no_add_cs,
                          singleton(second_rid),
                          new_rid, new_roster, new_markings,
                          nis);
    I(new_roster.get_node(split("foo"))->attrs.size() == 2);
    I(new_roster.get_node(split("bar"))->attrs
      == second_roster.get_node(split("bar"))->attrs);
    I(new_roster.get_node(split("bar"))->attrs.size() == 1);
  }
  {
    roster_t new_roster; MM(new_roster);
    marking_map new_markings; MM(new_markings);
    make_roster_for_merge(second_rid, second_roster, second_markings, no_add_cs,
                          singleton(second_rid),
                          first_rid, first_roster, first_markings, add_cs,
                          singleton(first_rid),
                          new_rid, new_roster, new_markings,
                          nis);
    I(new_roster.get_node(split("foo"))->attrs.size() == 2);
    I(new_roster.get_node(split("bar"))->attrs
      == second_roster.get_node(split("bar"))->attrs);
    I(new_roster.get_node(split("bar"))->attrs.size() == 1);
  }

  L(FL("TEST: end checking unification of rosters (end to end, attr corpses)"));
}

#endif // BUILD_UNIT_TESTS

// Local Variables:
// mode: C++
// fill-column: 76
// c-file-style: "gnu"
// indent-tabs-mode: nil
// End:
// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s: