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
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

pub use self::AnnNode::*;

use abi;
use ast::{self, TokenTree};
use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
use ast::Attribute;
use attr::ThinAttributesExt;
use ast_util;
use util::parser::AssocOp;
use attr;
use owned_slice::OwnedSlice;
use attr::{AttrMetaMethods, AttributeMethods};
use codemap::{self, CodeMap, BytePos};
use diagnostic;
use parse::token::{self, BinOpToken, Token, InternedString};
use parse::lexer::comments;
use parse;
use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
use print::pp::{Breaks, eof};
use print::pp::Breaks::{Consistent, Inconsistent};
use ptr::P;
use std_inject;
use str::slice_shift_char;

use std::ascii;
use std::io::{self, Write, Read};
use std::iter;

pub enum AnnNode<'a> {
    NodeIdent(&'a ast::Ident),
    NodeName(&'a ast::Name),
    NodeBlock(&'a ast::Block),
    NodeItem(&'a ast::Item),
    NodeSubItem(ast::NodeId),
    NodeExpr(&'a ast::Expr),
    NodePat(&'a ast::Pat),
}

pub trait PpAnn {
    fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
    fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
}

#[derive(Copy, Clone)]
pub struct NoAnn;

impl PpAnn for NoAnn {}

#[derive(Copy, Clone)]
pub struct CurrentCommentAndLiteral {
    pub cur_cmnt: usize,
    pub cur_lit: usize,
}

pub struct State<'a> {
    pub s: pp::Printer<'a>,
    cm: Option<&'a CodeMap>,
    comments: Option<Vec<comments::Comment> >,
    literals: Option<Vec<comments::Literal> >,
    cur_cmnt_and_lit: CurrentCommentAndLiteral,
    boxes: Vec<pp::Breaks>,
    ann: &'a (PpAnn+'a),
}

pub fn rust_printer<'a>(writer: Box<Write+'a>) -> State<'a> {
    static NO_ANN: NoAnn = NoAnn;
    rust_printer_annotated(writer, &NO_ANN)
}

pub fn rust_printer_annotated<'a>(writer: Box<Write+'a>,
                                  ann: &'a PpAnn) -> State<'a> {
    State {
        s: pp::mk_printer(writer, DEFAULT_COLUMNS),
        cm: None,
        comments: None,
        literals: None,
        cur_cmnt_and_lit: CurrentCommentAndLiteral {
            cur_cmnt: 0,
            cur_lit: 0
        },
        boxes: Vec::new(),
        ann: ann,
    }
}

pub const INDENT_UNIT: usize = 4;

pub const DEFAULT_COLUMNS: usize = 78;

/// Requires you to pass an input filename and reader so that
/// it can scan the input text for comments and literals to
/// copy forward.
pub fn print_crate<'a>(cm: &'a CodeMap,
                       span_diagnostic: &diagnostic::SpanHandler,
                       krate: &ast::Crate,
                       filename: String,
                       input: &mut Read,
                       out: Box<Write+'a>,
                       ann: &'a PpAnn,
                       is_expanded: bool) -> io::Result<()> {
    let mut s = State::new_from_input(cm,
                                      span_diagnostic,
                                      filename,
                                      input,
                                      out,
                                      ann,
                                      is_expanded);
    if is_expanded && !std_inject::no_std(krate) {
        // We need to print `#![no_std]` (and its feature gate) so that
        // compiling pretty-printed source won't inject libstd again.
        // However we don't want these attributes in the AST because
        // of the feature gate, so we fake them up here.

        // #![feature(prelude_import)]
        let prelude_import_meta = attr::mk_word_item(InternedString::new("prelude_import"));
        let list = attr::mk_list_item(InternedString::new("feature"),
                                      vec![prelude_import_meta]);
        let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), list);
        try!(s.print_attribute(&fake_attr));

        // #![no_std]
        let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
        let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
        try!(s.print_attribute(&fake_attr));
    }

    try!(s.print_mod(&krate.module, &krate.attrs));
    try!(s.print_remaining_comments());
    eof(&mut s.s)
}

impl<'a> State<'a> {
    pub fn new_from_input(cm: &'a CodeMap,
                          span_diagnostic: &diagnostic::SpanHandler,
                          filename: String,
                          input: &mut Read,
                          out: Box<Write+'a>,
                          ann: &'a PpAnn,
                          is_expanded: bool) -> State<'a> {
        let (cmnts, lits) = comments::gather_comments_and_literals(
            span_diagnostic,
            filename,
            input);

        State::new(
            cm,
            out,
            ann,
            Some(cmnts),
            // If the code is post expansion, don't use the table of
            // literals, since it doesn't correspond with the literals
            // in the AST anymore.
            if is_expanded { None } else { Some(lits) })
    }

    pub fn new(cm: &'a CodeMap,
               out: Box<Write+'a>,
               ann: &'a PpAnn,
               comments: Option<Vec<comments::Comment>>,
               literals: Option<Vec<comments::Literal>>) -> State<'a> {
        State {
            s: pp::mk_printer(out, DEFAULT_COLUMNS),
            cm: Some(cm),
            comments: comments,
            literals: literals,
            cur_cmnt_and_lit: CurrentCommentAndLiteral {
                cur_cmnt: 0,
                cur_lit: 0
            },
            boxes: Vec::new(),
            ann: ann,
        }
    }
}

pub fn to_string<F>(f: F) -> String where
    F: FnOnce(&mut State) -> io::Result<()>,
{
    let mut wr = Vec::new();
    {
        let mut printer = rust_printer(Box::new(&mut wr));
        f(&mut printer).unwrap();
        eof(&mut printer.s).unwrap();
    }
    String::from_utf8(wr).unwrap()
}

pub fn binop_to_string(op: BinOpToken) -> &'static str {
    match op {
        token::Plus     => "+",
        token::Minus    => "-",
        token::Star     => "*",
        token::Slash    => "/",
        token::Percent  => "%",
        token::Caret    => "^",
        token::And      => "&",
        token::Or       => "|",
        token::Shl      => "<<",
        token::Shr      => ">>",
    }
}

pub fn token_to_string(tok: &Token) -> String {
    match *tok {
        token::Eq                   => "=".to_string(),
        token::Lt                   => "<".to_string(),
        token::Le                   => "<=".to_string(),
        token::EqEq                 => "==".to_string(),
        token::Ne                   => "!=".to_string(),
        token::Ge                   => ">=".to_string(),
        token::Gt                   => ">".to_string(),
        token::Not                  => "!".to_string(),
        token::Tilde                => "~".to_string(),
        token::OrOr                 => "||".to_string(),
        token::AndAnd               => "&&".to_string(),
        token::BinOp(op)            => binop_to_string(op).to_string(),
        token::BinOpEq(op)          => format!("{}=", binop_to_string(op)),

        /* Structural symbols */
        token::At                   => "@".to_string(),
        token::Dot                  => ".".to_string(),
        token::DotDot               => "..".to_string(),
        token::DotDotDot            => "...".to_string(),
        token::Comma                => ",".to_string(),
        token::Semi                 => ";".to_string(),
        token::Colon                => ":".to_string(),
        token::ModSep               => "::".to_string(),
        token::RArrow               => "->".to_string(),
        token::LArrow               => "<-".to_string(),
        token::FatArrow             => "=>".to_string(),
        token::OpenDelim(token::Paren) => "(".to_string(),
        token::CloseDelim(token::Paren) => ")".to_string(),
        token::OpenDelim(token::Bracket) => "[".to_string(),
        token::CloseDelim(token::Bracket) => "]".to_string(),
        token::OpenDelim(token::Brace) => "{".to_string(),
        token::CloseDelim(token::Brace) => "}".to_string(),
        token::Pound                => "#".to_string(),
        token::Dollar               => "$".to_string(),
        token::Question             => "?".to_string(),

        /* Literals */
        token::Literal(lit, suf) => {
            let mut out = match lit {
                token::Byte(b)           => format!("b'{}'", b),
                token::Char(c)           => format!("'{}'", c),
                token::Float(c)          => c.to_string(),
                token::Integer(c)        => c.to_string(),
                token::Str_(s)           => format!("\"{}\"", s),
                token::StrRaw(s, n)      => format!("r{delim}\"{string}\"{delim}",
                                                    delim=repeat("#", n),
                                                    string=s),
                token::ByteStr(v)         => format!("b\"{}\"", v),
                token::ByteStrRaw(s, n)   => format!("br{delim}\"{string}\"{delim}",
                                                    delim=repeat("#", n),
                                                    string=s),
            };

            if let Some(s) = suf {
                out.push_str(&s.as_str())
            }

            out
        }

        /* Name components */
        token::Ident(s, _)          => s.to_string(),
        token::Lifetime(s)          => s.to_string(),
        token::Underscore           => "_".to_string(),

        /* Other */
        token::DocComment(s)        => s.to_string(),
        token::SubstNt(s, _)        => format!("${}", s),
        token::MatchNt(s, t, _, _)  => format!("${}:{}", s, t),
        token::Eof                  => "<eof>".to_string(),
        token::Whitespace           => " ".to_string(),
        token::Comment              => "/* */".to_string(),
        token::Shebang(s)           => format!("/* shebang: {}*/", s),

        token::SpecialVarNt(var)    => format!("${}", var.as_str()),

        token::Interpolated(ref nt) => match *nt {
            token::NtExpr(ref e)        => expr_to_string(&**e),
            token::NtMeta(ref e)        => meta_item_to_string(&**e),
            token::NtTy(ref e)          => ty_to_string(&**e),
            token::NtPath(ref e)        => path_to_string(&**e),
            token::NtItem(ref e)        => item_to_string(&**e),
            token::NtBlock(ref e)       => block_to_string(&**e),
            token::NtStmt(ref e)        => stmt_to_string(&**e),
            token::NtPat(ref e)         => pat_to_string(&**e),
            token::NtIdent(ref e, _)    => ident_to_string(**e),
            token::NtTT(ref e)          => tt_to_string(&**e),
            token::NtArm(ref e)         => arm_to_string(&*e),
            token::NtImplItem(ref e)    => impl_item_to_string(&**e),
            token::NtTraitItem(ref e)   => trait_item_to_string(&**e),
            token::NtGenerics(ref e)    => generics_to_string(&*e),
            token::NtWhereClause(ref e) => where_clause_to_string(&*e),
            token::NtArg(ref e)         => arg_to_string(&*e),
        }
    }
}

pub fn ty_to_string(ty: &ast::Ty) -> String {
    to_string(|s| s.print_type(ty))
}

pub fn ty_param_to_string(param: &ast::TyParam) -> String {
    to_string(|s| s.print_ty_param(param))
}

pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
    to_string(|s| s.print_bounds("", bounds))
}

pub fn pat_to_string(pat: &ast::Pat) -> String {
    to_string(|s| s.print_pat(pat))
}

pub fn arm_to_string(arm: &ast::Arm) -> String {
    to_string(|s| s.print_arm(arm))
}

pub fn expr_to_string(e: &ast::Expr) -> String {
    to_string(|s| s.print_expr(e))
}

pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
    to_string(|s| s.print_lifetime(e))
}

pub fn tt_to_string(tt: &ast::TokenTree) -> String {
    to_string(|s| s.print_tt(tt))
}

pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
    to_string(|s| s.print_tts(tts))
}

pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
    to_string(|s| s.print_stmt(stmt))
}

pub fn attr_to_string(attr: &ast::Attribute) -> String {
    to_string(|s| s.print_attribute(attr))
}

pub fn item_to_string(i: &ast::Item) -> String {
    to_string(|s| s.print_item(i))
}

pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
    to_string(|s| s.print_impl_item(i))
}

pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
    to_string(|s| s.print_trait_item(i))
}

pub fn generics_to_string(generics: &ast::Generics) -> String {
    to_string(|s| s.print_generics(generics))
}

pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
    to_string(|s| s.print_where_clause(i))
}

pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
    to_string(|s| s.print_fn_block_args(p))
}

pub fn path_to_string(p: &ast::Path) -> String {
    to_string(|s| s.print_path(p, false, 0))
}

pub fn ident_to_string(id: ast::Ident) -> String {
    to_string(|s| s.print_ident(id))
}

pub fn fun_to_string(decl: &ast::FnDecl,
                     unsafety: ast::Unsafety,
                     constness: ast::Constness,
                     name: ast::Ident,
                     opt_explicit_self: Option<&ast::ExplicitSelf_>,
                     generics: &ast::Generics)
                     -> String {
    to_string(|s| {
        try!(s.head(""));
        try!(s.print_fn(decl, unsafety, constness, abi::Rust, Some(name),
                        generics, opt_explicit_self, ast::Inherited));
        try!(s.end()); // Close the head box
        s.end() // Close the outer box
    })
}

pub fn block_to_string(blk: &ast::Block) -> String {
    to_string(|s| {
        // containing cbox, will be closed by print-block at }
        try!(s.cbox(INDENT_UNIT));
        // head-ibox, will be closed by print-block after {
        try!(s.ibox(0));
        s.print_block(blk)
    })
}

pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
    to_string(|s| s.print_meta_item(mi))
}

pub fn attribute_to_string(attr: &ast::Attribute) -> String {
    to_string(|s| s.print_attribute(attr))
}

pub fn lit_to_string(l: &ast::Lit) -> String {
    to_string(|s| s.print_literal(l))
}

pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
    to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
}

pub fn variant_to_string(var: &ast::Variant) -> String {
    to_string(|s| s.print_variant(var))
}

pub fn arg_to_string(arg: &ast::Arg) -> String {
    to_string(|s| s.print_arg(arg))
}

pub fn mac_to_string(arg: &ast::Mac) -> String {
    to_string(|s| s.print_mac(arg, ::parse::token::Paren))
}

pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
    match vis {
        ast::Public => format!("pub {}", s),
        ast::Inherited => s.to_string()
    }
}

fn needs_parentheses(expr: &ast::Expr) -> bool {
    match expr.node {
        ast::ExprAssign(..) | ast::ExprBinary(..) |
        ast::ExprClosure(..) |
        ast::ExprAssignOp(..) | ast::ExprCast(..) |
        ast::ExprInPlace(..) => true,
        _ => false,
    }
}

pub trait PrintState<'a> {
    fn writer(&mut self) -> &mut pp::Printer<'a>;
    fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
    fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
    fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral;
    fn literals(&self) -> &Option<Vec<comments::Literal>>;

    fn word_space(&mut self, w: &str) -> io::Result<()> {
        try!(word(self.writer(), w));
        space(self.writer())
    }

    fn popen(&mut self) -> io::Result<()> { word(self.writer(), "(") }

    fn pclose(&mut self) -> io::Result<()> { word(self.writer(), ")") }

    fn is_begin(&mut self) -> bool {
        match self.writer().last_token() {
            pp::Token::Begin(_) => true,
            _ => false,
        }
    }

    fn is_end(&mut self) -> bool {
        match self.writer().last_token() {
            pp::Token::End => true,
            _ => false,
        }
    }

    // is this the beginning of a line?
    fn is_bol(&mut self) -> bool {
        self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
    }

    fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
        if !self.is_bol() {
            try!(hardbreak(self.writer()))
        }
        Ok(())
    }

    // "raw box"
    fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
        self.boxes().push(b);
        pp::rbox(self.writer(), u, b)
    }

    fn ibox(&mut self, u: usize) -> io::Result<()> {
        self.boxes().push(pp::Breaks::Inconsistent);
        pp::ibox(self.writer(), u)
    }

    fn end(&mut self) -> io::Result<()> {
        self.boxes().pop().unwrap();
        pp::end(self.writer())
    }

    fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
        where F: FnMut(&mut Self, &T) -> io::Result<()>,
    {
        try!(self.rbox(0, b));
        let mut first = true;
        for elt in elts {
            if first { first = false; } else { try!(self.word_space(",")); }
            try!(op(self, elt));
        }
        self.end()
    }

    fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
        let mut cur_lit = self.cur_cmnt_and_lit().cur_lit;

        let mut result = None;

        if let &Some(ref lits) = self.literals()
        {
            while cur_lit < lits.len() {
                let ltrl = (*lits)[cur_lit].clone();
                if ltrl.pos > pos { break; }
                cur_lit += 1;
                if ltrl.pos == pos {
                    result = Some(ltrl);
                    break;
                }
            }
        }

        self.cur_cmnt_and_lit().cur_lit = cur_lit;
        result
    }

    fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
        loop {
            match self.next_comment() {
                Some(ref cmnt) => {
                    if (*cmnt).pos < pos {
                        try!(self.print_comment(cmnt));
                        self.cur_cmnt_and_lit().cur_cmnt += 1;
                    } else { break; }
                }
                _ => break
            }
        }
        Ok(())
    }

    fn print_comment(&mut self,
                     cmnt: &comments::Comment) -> io::Result<()> {
        match cmnt.style {
            comments::Mixed => {
                assert_eq!(cmnt.lines.len(), 1);
                try!(zerobreak(self.writer()));
                try!(word(self.writer(), &cmnt.lines[0]));
                zerobreak(self.writer())
            }
            comments::Isolated => {
                try!(self.hardbreak_if_not_bol());
                for line in &cmnt.lines {
                    // Don't print empty lines because they will end up as trailing
                    // whitespace
                    if !line.is_empty() {
                        try!(word(self.writer(), &line[..]));
                    }
                    try!(hardbreak(self.writer()));
                }
                Ok(())
            }
            comments::Trailing => {
                try!(word(self.writer(), " "));
                if cmnt.lines.len() == 1 {
                    try!(word(self.writer(), &cmnt.lines[0]));
                    hardbreak(self.writer())
                } else {
                    try!(self.ibox(0));
                    for line in &cmnt.lines {
                        if !line.is_empty() {
                            try!(word(self.writer(), &line[..]));
                        }
                        try!(hardbreak(self.writer()));
                    }
                    self.end()
                }
            }
            comments::BlankLine => {
                // We need to do at least one, possibly two hardbreaks.
                let is_semi = match self.writer().last_token() {
                    pp::Token::String(s, _) => ";" == s,
                    _ => false
                };
                if is_semi || self.is_begin() || self.is_end() {
                    try!(hardbreak(self.writer()));
                }
                hardbreak(self.writer())
            }
        }
    }

    fn next_comment(&mut self) -> Option<comments::Comment> {
        let cur_cmnt = self.cur_cmnt_and_lit().cur_cmnt;
        match *self.comments() {
            Some(ref cmnts) => {
                if cur_cmnt < cmnts.len() {
                    Some(cmnts[cur_cmnt].clone())
                } else {
                    None
                }
            }
            _ => None
        }
    }

    fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
        try!(self.maybe_print_comment(lit.span.lo));
        match self.next_lit(lit.span.lo) {
            Some(ref ltrl) => {
                return word(self.writer(), &(*ltrl).lit);
            }
            _ => ()
        }
        match lit.node {
            ast::LitStr(ref st, style) => self.print_string(&st, style),
            ast::LitByte(byte) => {
                let mut res = String::from("b'");
                res.extend(ascii::escape_default(byte).map(|c| c as char));
                res.push('\'');
                word(self.writer(), &res[..])
            }
            ast::LitChar(ch) => {
                let mut res = String::from("'");
                res.extend(ch.escape_default());
                res.push('\'');
                word(self.writer(), &res[..])
            }
            ast::LitInt(i, t) => {
                match t {
                    ast::SignedIntLit(st, ast::Plus) => {
                        word(self.writer(),
                             &ast_util::int_val_to_string(st, i as i64))
                    }
                    ast::SignedIntLit(st, ast::Minus) => {
                        let istr = ast_util::int_val_to_string(st, -(i as i64));
                        word(self.writer(),
                             &format!("-{}", istr))
                    }
                    ast::UnsignedIntLit(ut) => {
                        word(self.writer(), &ast_util::uint_val_to_string(ut, i))
                    }
                    ast::UnsuffixedIntLit(ast::Plus) => {
                        word(self.writer(), &format!("{}", i))
                    }
                    ast::UnsuffixedIntLit(ast::Minus) => {
                        word(self.writer(), &format!("-{}", i))
                    }
                }
            }
            ast::LitFloat(ref f, t) => {
                word(self.writer(),
                     &format!(
                         "{}{}",
                         &f,
                         &ast_util::float_ty_to_string(t)))
            }
            ast::LitFloatUnsuffixed(ref f) => word(self.writer(), &f[..]),
            ast::LitBool(val) => {
                if val { word(self.writer(), "true") } else { word(self.writer(), "false") }
            }
            ast::LitByteStr(ref v) => {
                let mut escaped: String = String::new();
                for &ch in v.iter() {
                    escaped.extend(ascii::escape_default(ch)
                                         .map(|c| c as char));
                }
                word(self.writer(), &format!("b\"{}\"", escaped))
            }
        }
    }

    fn print_string(&mut self, st: &str,
                    style: ast::StrStyle) -> io::Result<()> {
        let st = match style {
            ast::CookedStr => {
                (format!("\"{}\"", st.chars().flat_map(char::escape_default).collect::<String>()))
            }
            ast::RawStr(n) => {
                (format!("r{delim}\"{string}\"{delim}",
                         delim=repeat("#", n),
                         string=st))
            }
        };
        word(self.writer(), &st[..])
    }

    fn print_inner_attributes(&mut self,
                              attrs: &[ast::Attribute]) -> io::Result<()> {
        self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
    }

    fn print_inner_attributes_no_trailing_hardbreak(&mut self,
                                                   attrs: &[ast::Attribute])
                                                   -> io::Result<()> {
        self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
    }

    fn print_outer_attributes(&mut self,
                              attrs: &[ast::Attribute]) -> io::Result<()> {
        self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
    }

    fn print_inner_attributes_inline(&mut self,
                                     attrs: &[ast::Attribute]) -> io::Result<()> {
        self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
    }

    fn print_outer_attributes_inline(&mut self,
                                     attrs: &[ast::Attribute]) -> io::Result<()> {
        self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
    }

    fn print_either_attributes(&mut self,
                              attrs: &[ast::Attribute],
                              kind: ast::AttrStyle,
                              is_inline: bool,
                              trailing_hardbreak: bool) -> io::Result<()> {
        let mut count = 0;
        for attr in attrs {
            if attr.node.style == kind {
                    try!(self.print_attribute_inline(attr, is_inline));
                    if is_inline {
                        try!(self.nbsp());
                    }
                    count += 1;
            }
        }
        if count > 0 && trailing_hardbreak && !is_inline {
            try!(self.hardbreak_if_not_bol());
        }
        Ok(())
    }

    fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
        self.print_attribute_inline(attr, false)
    }

    fn print_attribute_inline(&mut self, attr: &ast::Attribute,
                              is_inline: bool) -> io::Result<()> {
        if !is_inline {
            try!(self.hardbreak_if_not_bol());
        }
        try!(self.maybe_print_comment(attr.span.lo));
        if attr.node.is_sugared_doc {
            word(self.writer(), &attr.value_str().unwrap())
        } else {
            match attr.node.style {
                ast::AttrStyle::Inner => try!(word(self.writer(), "#![")),
                ast::AttrStyle::Outer => try!(word(self.writer(), "#[")),
            }
            try!(self.print_meta_item(&*attr.meta()));
            word(self.writer(), "]")
        }
    }

    fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
        try!(self.ibox(INDENT_UNIT));
        match item.node {
            ast::MetaWord(ref name) => {
                try!(word(self.writer(), &name));
            }
            ast::MetaNameValue(ref name, ref value) => {
                try!(self.word_space(&name[..]));
                try!(self.word_space("="));
                try!(self.print_literal(value));
            }
            ast::MetaList(ref name, ref items) => {
                try!(word(self.writer(), &name));
                try!(self.popen());
                try!(self.commasep(Consistent,
                                   &items[..],
                                   |s, i| s.print_meta_item(&**i)));
                try!(self.pclose());
            }
        }
        self.end()
    }

    fn space_if_not_bol(&mut self) -> io::Result<()> {
        if !self.is_bol() { try!(space(self.writer())); }
        Ok(())
    }

    fn nbsp(&mut self) -> io::Result<()> { word(self.writer(), " ") }
}

impl<'a> PrintState<'a> for State<'a> {
    fn writer(&mut self) -> &mut pp::Printer<'a> {
        &mut self.s
    }

    fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
        &mut self.boxes
    }

    fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
        &mut self.comments
    }

    fn cur_cmnt_and_lit(&mut self) -> &mut CurrentCommentAndLiteral {
        &mut self.cur_cmnt_and_lit
    }

    fn literals(&self) -> &Option<Vec<comments::Literal>> {
        &self.literals
    }
}

impl<'a> State<'a> {
    pub fn cbox(&mut self, u: usize) -> io::Result<()> {
        self.boxes.push(pp::Breaks::Consistent);
        pp::cbox(&mut self.s, u)
    }

    pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
        try!(word(&mut self.s, w));
        self.nbsp()
    }

    pub fn head(&mut self, w: &str) -> io::Result<()> {
        // outer-box is consistent
        try!(self.cbox(INDENT_UNIT));
        // head-box is inconsistent
        try!(self.ibox(w.len() + 1));
        // keyword that starts the head
        if !w.is_empty() {
            try!(self.word_nbsp(w));
        }
        Ok(())
    }

    pub fn bopen(&mut self) -> io::Result<()> {
        try!(word(&mut self.s, "{"));
        self.end() // close the head-box
    }

    pub fn bclose_(&mut self, span: codemap::Span,
                   indented: usize) -> io::Result<()> {
        self.bclose_maybe_open(span, indented, true)
    }
    pub fn bclose_maybe_open(&mut self, span: codemap::Span,
                             indented: usize, close_box: bool) -> io::Result<()> {
        try!(self.maybe_print_comment(span.hi));
        try!(self.break_offset_if_not_bol(1, -(indented as isize)));
        try!(word(&mut self.s, "}"));
        if close_box {
            try!(self.end()); // close the outer-box
        }
        Ok(())
    }
    pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
        self.bclose_(span, INDENT_UNIT)
    }

    pub fn in_cbox(&self) -> bool {
        match self.boxes.last() {
            Some(&last_box) => last_box == pp::Breaks::Consistent,
            None => false
        }
    }

    pub fn break_offset_if_not_bol(&mut self, n: usize,
                                   off: isize) -> io::Result<()> {
        if !self.is_bol() {
            break_offset(&mut self.s, n, off)
        } else {
            if off != 0 && self.s.last_token().is_hardbreak_tok() {
                // We do something pretty sketchy here: tuck the nonzero
                // offset-adjustment we were going to deposit along with the
                // break into the previous hardbreak.
                self.s.replace_last_token(pp::hardbreak_tok_offset(off));
            }
            Ok(())
        }
    }

    // Synthesizes a comment that was not textually present in the original source
    // file.
    pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
        try!(word(&mut self.s, "/*"));
        try!(space(&mut self.s));
        try!(word(&mut self.s, &text[..]));
        try!(space(&mut self.s));
        word(&mut self.s, "*/")
    }



    pub fn commasep_cmnt<T, F, G>(&mut self,
                                  b: Breaks,
                                  elts: &[T],
                                  mut op: F,
                                  mut get_span: G) -> io::Result<()> where
        F: FnMut(&mut State, &T) -> io::Result<()>,
        G: FnMut(&T) -> codemap::Span,
    {
        try!(self.rbox(0, b));
        let len = elts.len();
        let mut i = 0;
        for elt in elts {
            try!(self.maybe_print_comment(get_span(elt).hi));
            try!(op(self, elt));
            i += 1;
            if i < len {
                try!(word(&mut self.s, ","));
                try!(self.maybe_print_trailing_comment(get_span(elt),
                                                    Some(get_span(&elts[i]).hi)));
                try!(self.space_if_not_bol());
            }
        }
        self.end()
    }

    pub fn commasep_exprs(&mut self, b: Breaks,
                          exprs: &[P<ast::Expr>]) -> io::Result<()> {
        self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
    }

    pub fn print_mod(&mut self, _mod: &ast::Mod,
                     attrs: &[ast::Attribute]) -> io::Result<()> {
        try!(self.print_inner_attributes(attrs));
        for item in &_mod.items {
            try!(self.print_item(&**item));
        }
        Ok(())
    }

    pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
                             attrs: &[ast::Attribute]) -> io::Result<()> {
        try!(self.print_inner_attributes(attrs));
        for item in &nmod.items {
            try!(self.print_foreign_item(&**item));
        }
        Ok(())
    }

    pub fn print_opt_lifetime(&mut self,
                              lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
        if let Some(l) = *lifetime {
            try!(self.print_lifetime(&l));
            try!(self.nbsp());
        }
        Ok(())
    }

    pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
        try!(self.maybe_print_comment(ty.span.lo));
        try!(self.ibox(0));
        match ty.node {
            ast::TyVec(ref ty) => {
                try!(word(&mut self.s, "["));
                try!(self.print_type(&**ty));
                try!(word(&mut self.s, "]"));
            }
            ast::TyPtr(ref mt) => {
                try!(word(&mut self.s, "*"));
                match mt.mutbl {
                    ast::MutMutable => try!(self.word_nbsp("mut")),
                    ast::MutImmutable => try!(self.word_nbsp("const")),
                }
                try!(self.print_type(&*mt.ty));
            }
            ast::TyRptr(ref lifetime, ref mt) => {
                try!(word(&mut self.s, "&"));
                try!(self.print_opt_lifetime(lifetime));
                try!(self.print_mt(mt));
            }
            ast::TyTup(ref elts) => {
                try!(self.popen());
                try!(self.commasep(Inconsistent, &elts[..],
                                   |s, ty| s.print_type(&**ty)));
                if elts.len() == 1 {
                    try!(word(&mut self.s, ","));
                }
                try!(self.pclose());
            }
            ast::TyParen(ref typ) => {
                try!(self.popen());
                try!(self.print_type(&**typ));
                try!(self.pclose());
            }
            ast::TyBareFn(ref f) => {
                let generics = ast::Generics {
                    lifetimes: f.lifetimes.clone(),
                    ty_params: OwnedSlice::empty(),
                    where_clause: ast::WhereClause {
                        id: ast::DUMMY_NODE_ID,
                        predicates: Vec::new(),
                    },
                };
                try!(self.print_ty_fn(f.abi,
                                      f.unsafety,
                                      &*f.decl,
                                      None,
                                      &generics,
                                      None));
            }
            ast::TyPath(None, ref path) => {
                try!(self.print_path(path, false, 0));
            }
            ast::TyPath(Some(ref qself), ref path) => {
                try!(self.print_qpath(path, qself, false))
            }
            ast::TyObjectSum(ref ty, ref bounds) => {
                try!(self.print_type(&**ty));
                try!(self.print_bounds("+", &bounds[..]));
            }
            ast::TyPolyTraitRef(ref bounds) => {
                try!(self.print_bounds("", &bounds[..]));
            }
            ast::TyFixedLengthVec(ref ty, ref v) => {
                try!(word(&mut self.s, "["));
                try!(self.print_type(&**ty));
                try!(word(&mut self.s, "; "));
                try!(self.print_expr(&**v));
                try!(word(&mut self.s, "]"));
            }
            ast::TyTypeof(ref e) => {
                try!(word(&mut self.s, "typeof("));
                try!(self.print_expr(&**e));
                try!(word(&mut self.s, ")"));
            }
            ast::TyInfer => {
                try!(word(&mut self.s, "_"));
            }
            ast::TyMac(ref m) => {
                try!(self.print_mac(m, token::Paren));
            }
        }
        self.end()
    }

    pub fn print_foreign_item(&mut self,
                              item: &ast::ForeignItem) -> io::Result<()> {
        try!(self.hardbreak_if_not_bol());
        try!(self.maybe_print_comment(item.span.lo));
        try!(self.print_outer_attributes(&item.attrs));
        match item.node {
            ast::ForeignItemFn(ref decl, ref generics) => {
                try!(self.head(""));
                try!(self.print_fn(decl, ast::Unsafety::Normal,
                                   ast::Constness::NotConst,
                                   abi::Rust, Some(item.ident),
                                   generics, None, item.vis));
                try!(self.end()); // end head-ibox
                try!(word(&mut self.s, ";"));
                self.end() // end the outer fn box
            }
            ast::ForeignItemStatic(ref t, m) => {
                try!(self.head(&visibility_qualified(item.vis,
                                                    "static")));
                if m {
                    try!(self.word_space("mut"));
                }
                try!(self.print_ident(item.ident));
                try!(self.word_space(":"));
                try!(self.print_type(&**t));
                try!(word(&mut self.s, ";"));
                try!(self.end()); // end the head-ibox
                self.end() // end the outer cbox
            }
        }
    }

    fn print_associated_const(&mut self,
                              ident: ast::Ident,
                              ty: &ast::Ty,
                              default: Option<&ast::Expr>,
                              vis: ast::Visibility)
                              -> io::Result<()>
    {
        try!(word(&mut self.s, &visibility_qualified(vis, "")));
        try!(self.word_space("const"));
        try!(self.print_ident(ident));
        try!(self.word_space(":"));
        try!(self.print_type(ty));
        if let Some(expr) = default {
            try!(space(&mut self.s));
            try!(self.word_space("="));
            try!(self.print_expr(expr));
        }
        word(&mut self.s, ";")
    }

    fn print_associated_type(&mut self,
                             ident: ast::Ident,
                             bounds: Option<&ast::TyParamBounds>,
                             ty: Option<&ast::Ty>)
                             -> io::Result<()> {
        try!(self.word_space("type"));
        try!(self.print_ident(ident));
        if let Some(bounds) = bounds {
            try!(self.print_bounds(":", bounds));
        }
        if let Some(ty) = ty {
            try!(space(&mut self.s));
            try!(self.word_space("="));
            try!(self.print_type(ty));
        }
        word(&mut self.s, ";")
    }

    /// Pretty-print an item
    pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
        try!(self.hardbreak_if_not_bol());
        try!(self.maybe_print_comment(item.span.lo));
        try!(self.print_outer_attributes(&item.attrs));
        try!(self.ann.pre(self, NodeItem(item)));
        match item.node {
            ast::ItemExternCrate(ref optional_path) => {
                try!(self.head(&visibility_qualified(item.vis,
                                                     "extern crate")));
                if let Some(p) = *optional_path {
                    let val = p.as_str();
                    if val.contains("-") {
                        try!(self.print_string(&val, ast::CookedStr));
                    } else {
                        try!(self.print_name(p));
                    }
                    try!(space(&mut self.s));
                    try!(word(&mut self.s, "as"));
                    try!(space(&mut self.s));
                }
                try!(self.print_ident(item.ident));
                try!(word(&mut self.s, ";"));
                try!(self.end()); // end inner head-block
                try!(self.end()); // end outer head-block
            }
            ast::ItemUse(ref vp) => {
                try!(self.head(&visibility_qualified(item.vis,
                                                     "use")));
                try!(self.print_view_path(&**vp));
                try!(word(&mut self.s, ";"));
                try!(self.end()); // end inner head-block
                try!(self.end()); // end outer head-block
            }
            ast::ItemStatic(ref ty, m, ref expr) => {
                try!(self.head(&visibility_qualified(item.vis,
                                                    "static")));
                if m == ast::MutMutable {
                    try!(self.word_space("mut"));
                }
                try!(self.print_ident(item.ident));
                try!(self.word_space(":"));
                try!(self.print_type(&**ty));
                try!(space(&mut self.s));
                try!(self.end()); // end the head-ibox

                try!(self.word_space("="));
                try!(self.print_expr(&**expr));
                try!(word(&mut self.s, ";"));
                try!(self.end()); // end the outer cbox
            }
            ast::ItemConst(ref ty, ref expr) => {
                try!(self.head(&visibility_qualified(item.vis,
                                                    "const")));
                try!(self.print_ident(item.ident));
                try!(self.word_space(":"));
                try!(self.print_type(&**ty));
                try!(space(&mut self.s));
                try!(self.end()); // end the head-ibox

                try!(self.word_space("="));
                try!(self.print_expr(&**expr));
                try!(word(&mut self.s, ";"));
                try!(self.end()); // end the outer cbox
            }
            ast::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
                try!(self.head(""));
                try!(self.print_fn(
                    decl,
                    unsafety,
                    constness,
                    abi,
                    Some(item.ident),
                    typarams,
                    None,
                    item.vis
                ));
                try!(word(&mut self.s, " "));
                try!(self.print_block_with_attrs(&**body, &item.attrs));
            }
            ast::ItemMod(ref _mod) => {
                try!(self.head(&visibility_qualified(item.vis,
                                                    "mod")));
                try!(self.print_ident(item.ident));
                if _mod.items.is_empty() {
                    try!(word(&mut self.s, ";"));
                    try!(self.end()); // end inner head-block
                    try!(self.end()); // end outer head-block
                } else {
                    try!(self.nbsp());
                    try!(self.bopen());
                    try!(self.print_mod(_mod, &item.attrs));
                    try!(self.bclose(item.span));
                }
            }
            ast::ItemForeignMod(ref nmod) => {
                try!(self.head("extern"));
                try!(self.word_nbsp(&nmod.abi.to_string()));
                try!(self.bopen());
                try!(self.print_foreign_mod(nmod, &item.attrs));
                try!(self.bclose(item.span));
            }
            ast::ItemTy(ref ty, ref params) => {
                try!(self.ibox(INDENT_UNIT));
                try!(self.ibox(0));
                try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
                try!(self.print_ident(item.ident));
                try!(self.print_generics(params));
                try!(self.end()); // end the inner ibox

                try!(self.print_where_clause(&params.where_clause));
                try!(space(&mut self.s));
                try!(self.word_space("="));
                try!(self.print_type(&**ty));
                try!(word(&mut self.s, ";"));
                try!(self.end()); // end the outer ibox
            }
            ast::ItemEnum(ref enum_definition, ref params) => {
                try!(self.print_enum_def(
                    enum_definition,
                    params,
                    item.ident,
                    item.span,
                    item.vis
                ));
            }
            ast::ItemStruct(ref struct_def, ref generics) => {
                try!(self.head(&visibility_qualified(item.vis,"struct")));
                try!(self.print_struct(&struct_def, generics, item.ident, item.span, true));
            }

            ast::ItemDefaultImpl(unsafety, ref trait_ref) => {
                try!(self.head(""));
                try!(self.print_visibility(item.vis));
                try!(self.print_unsafety(unsafety));
                try!(self.word_nbsp("impl"));
                try!(self.print_trait_ref(trait_ref));
                try!(space(&mut self.s));
                try!(self.word_space("for"));
                try!(self.word_space(".."));
                try!(self.bopen());
                try!(self.bclose(item.span));
            }
            ast::ItemImpl(unsafety,
                          polarity,
                          ref generics,
                          ref opt_trait,
                          ref ty,
                          ref impl_items) => {
                try!(self.head(""));
                try!(self.print_visibility(item.vis));
                try!(self.print_unsafety(unsafety));
                try!(self.word_nbsp("impl"));

                if generics.is_parameterized() {
                    try!(self.print_generics(generics));
                    try!(space(&mut self.s));
                }

                match polarity {
                    ast::ImplPolarity::Negative => {
                        try!(word(&mut self.s, "!"));
                    },
                    _ => {}
                }

                match *opt_trait {
                    Some(ref t) => {
                        try!(self.print_trait_ref(t));
                        try!(space(&mut self.s));
                        try!(self.word_space("for"));
                    }
                    None => {}
                }

                try!(self.print_type(&**ty));
                try!(self.print_where_clause(&generics.where_clause));

                try!(space(&mut self.s));
                try!(self.bopen());
                try!(self.print_inner_attributes(&item.attrs));
                for impl_item in impl_items {
                    try!(self.print_impl_item(impl_item));
                }
                try!(self.bclose(item.span));
            }
            ast::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
                try!(self.head(""));
                try!(self.print_visibility(item.vis));
                try!(self.print_unsafety(unsafety));
                try!(self.word_nbsp("trait"));
                try!(self.print_ident(item.ident));
                try!(self.print_generics(generics));
                let mut real_bounds = Vec::with_capacity(bounds.len());
                for b in bounds.iter() {
                    if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
                        try!(space(&mut self.s));
                        try!(self.word_space("for ?"));
                        try!(self.print_trait_ref(&ptr.trait_ref));
                    } else {
                        real_bounds.push(b.clone());
                    }
                }
                try!(self.print_bounds(":", &real_bounds[..]));
                try!(self.print_where_clause(&generics.where_clause));
                try!(word(&mut self.s, " "));
                try!(self.bopen());
                for trait_item in trait_items {
                    try!(self.print_trait_item(trait_item));
                }
                try!(self.bclose(item.span));
            }
            ast::ItemMac(codemap::Spanned { ref node, .. }) => {
                try!(self.print_visibility(item.vis));
                try!(self.print_path(&node.path, false, 0));
                try!(word(&mut self.s, "! "));
                try!(self.print_ident(item.ident));
                try!(self.cbox(INDENT_UNIT));
                try!(self.popen());
                try!(self.print_tts(&node.tts[..]));
                try!(self.pclose());
                try!(word(&mut self.s, ";"));
                try!(self.end());
            }
        }
        self.ann.post(self, NodeItem(item))
    }

    fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
        self.print_path(&t.path, false, 0)
    }

    fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
        if !lifetimes.is_empty() {
            try!(word(&mut self.s, "for<"));
            let mut comma = false;
            for lifetime_def in lifetimes {
                if comma {
                    try!(self.word_space(","))
                }
                try!(self.print_lifetime_def(lifetime_def));
                comma = true;
            }
            try!(word(&mut self.s, ">"));
        }
        Ok(())
    }

    fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
        try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
        self.print_trait_ref(&t.trait_ref)
    }

    pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
                          generics: &ast::Generics, ident: ast::Ident,
                          span: codemap::Span,
                          visibility: ast::Visibility) -> io::Result<()> {
        try!(self.head(&visibility_qualified(visibility, "enum")));
        try!(self.print_ident(ident));
        try!(self.print_generics(generics));
        try!(self.print_where_clause(&generics.where_clause));
        try!(space(&mut self.s));
        self.print_variants(&enum_definition.variants, span)
    }

    pub fn print_variants(&mut self,
                          variants: &[P<ast::Variant>],
                          span: codemap::Span) -> io::Result<()> {
        try!(self.bopen());
        for v in variants {
            try!(self.space_if_not_bol());
            try!(self.maybe_print_comment(v.span.lo));
            try!(self.print_outer_attributes(&v.node.attrs));
            try!(self.ibox(INDENT_UNIT));
            try!(self.print_variant(&**v));
            try!(word(&mut self.s, ","));
            try!(self.end());
            try!(self.maybe_print_trailing_comment(v.span, None));
        }
        self.bclose(span)
    }

    pub fn print_visibility(&mut self, vis: ast::Visibility) -> io::Result<()> {
        match vis {
            ast::Public => self.word_nbsp("pub"),
            ast::Inherited => Ok(())
        }
    }

    pub fn print_struct(&mut self,
                        struct_def: &ast::VariantData,
                        generics: &ast::Generics,
                        ident: ast::Ident,
                        span: codemap::Span,
                        print_finalizer: bool) -> io::Result<()> {
        try!(self.print_ident(ident));
        try!(self.print_generics(generics));
        if !struct_def.is_struct() {
            if struct_def.is_tuple() {
                try!(self.popen());
                try!(self.commasep(
                    Inconsistent, struct_def.fields(),
                    |s, field| {
                        match field.node.kind {
                            ast::NamedField(..) => panic!("unexpected named field"),
                            ast::UnnamedField(vis) => {
                                try!(s.print_visibility(vis));
                                try!(s.maybe_print_comment(field.span.lo));
                                s.print_type(&*field.node.ty)
                            }
                        }
                    }
                ));
                try!(self.pclose());
            }
            try!(self.print_where_clause(&generics.where_clause));
            if print_finalizer {
                try!(word(&mut self.s, ";"));
            }
            try!(self.end());
            self.end() // close the outer-box
        } else {
            try!(self.print_where_clause(&generics.where_clause));
            try!(self.nbsp());
            try!(self.bopen());
            try!(self.hardbreak_if_not_bol());

            for field in struct_def.fields() {
                match field.node.kind {
                    ast::UnnamedField(..) => panic!("unexpected unnamed field"),
                    ast::NamedField(ident, visibility) => {
                        try!(self.hardbreak_if_not_bol());
                        try!(self.maybe_print_comment(field.span.lo));
                        try!(self.print_outer_attributes(&field.node.attrs));
                        try!(self.print_visibility(visibility));
                        try!(self.print_ident(ident));
                        try!(self.word_nbsp(":"));
                        try!(self.print_type(&*field.node.ty));
                        try!(word(&mut self.s, ","));
                    }
                }
            }

            self.bclose(span)
        }
    }

    /// This doesn't deserve to be called "pretty" printing, but it should be
    /// meaning-preserving. A quick hack that might help would be to look at the
    /// spans embedded in the TTs to decide where to put spaces and newlines.
    /// But it'd be better to parse these according to the grammar of the
    /// appropriate macro, transcribe back into the grammar we just parsed from,
    /// and then pretty-print the resulting AST nodes (so, e.g., we print
    /// expression arguments as expressions). It can be done! I think.
    pub fn print_tt(&mut self, tt: &ast::TokenTree) -> io::Result<()> {
        match *tt {
            TokenTree::Token(_, ref tk) => {
                try!(word(&mut self.s, &token_to_string(tk)));
                match *tk {
                    parse::token::DocComment(..) => {
                        hardbreak(&mut self.s)
                    }
                    _ => Ok(())
                }
            }
            TokenTree::Delimited(_, ref delimed) => {
                try!(word(&mut self.s, &token_to_string(&delimed.open_token())));
                try!(space(&mut self.s));
                try!(self.print_tts(&delimed.tts));
                try!(space(&mut self.s));
                word(&mut self.s, &token_to_string(&delimed.close_token()))
            },
            TokenTree::Sequence(_, ref seq) => {
                try!(word(&mut self.s, "$("));
                for tt_elt in &seq.tts {
                    try!(self.print_tt(tt_elt));
                }
                try!(word(&mut self.s, ")"));
                match seq.separator {
                    Some(ref tk) => {
                        try!(word(&mut self.s, &token_to_string(tk)));
                    }
                    None => {},
                }
                match seq.op {
                    ast::ZeroOrMore => word(&mut self.s, "*"),
                    ast::OneOrMore => word(&mut self.s, "+"),
                }
            }
        }
    }

    pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> io::Result<()> {
        try!(self.ibox(0));
        let mut suppress_space = false;
        for (i, tt) in tts.iter().enumerate() {
            if i != 0 && !suppress_space {
                try!(space(&mut self.s));
            }
            try!(self.print_tt(tt));
            // There should be no space between the module name and the following `::` in paths,
            // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701)
            suppress_space = match *tt {
                TokenTree::Token(_, token::Ident(_, token::ModName)) |
                TokenTree::Token(_, token::MatchNt(_, _, _, token::ModName)) |
                TokenTree::Token(_, token::SubstNt(_, token::ModName)) => true,
                _ => false
            }
        }
        self.end()
    }

    pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
        try!(self.head(""));
        let generics = ast_util::empty_generics();
        try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
        match v.node.disr_expr {
            Some(ref d) => {
                try!(space(&mut self.s));
                try!(self.word_space("="));
                self.print_expr(&**d)
            }
            _ => Ok(())
        }
    }

    pub fn print_method_sig(&mut self,
                            ident: ast::Ident,
                            m: &ast::MethodSig,
                            vis: ast::Visibility)
                            -> io::Result<()> {
        self.print_fn(&m.decl,
                      m.unsafety,
                      m.constness,
                      m.abi,
                      Some(ident),
                      &m.generics,
                      Some(&m.explicit_self.node),
                      vis)
    }

    pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
                            -> io::Result<()> {
        try!(self.ann.pre(self, NodeSubItem(ti.id)));
        try!(self.hardbreak_if_not_bol());
        try!(self.maybe_print_comment(ti.span.lo));
        try!(self.print_outer_attributes(&ti.attrs));
        match ti.node {
            ast::ConstTraitItem(ref ty, ref default) => {
                try!(self.print_associated_const(ti.ident, &ty,
                                                 default.as_ref().map(|expr| &**expr),
                                                 ast::Inherited));
            }
            ast::MethodTraitItem(ref sig, ref body) => {
                if body.is_some() {
                    try!(self.head(""));
                }
                try!(self.print_method_sig(ti.ident, sig, ast::Inherited));
                if let Some(ref body) = *body {
                    try!(self.nbsp());
                    try!(self.print_block_with_attrs(body, &ti.attrs));
                } else {
                    try!(word(&mut self.s, ";"));
                }
            }
            ast::TypeTraitItem(ref bounds, ref default) => {
                try!(self.print_associated_type(ti.ident, Some(bounds),
                                                default.as_ref().map(|ty| &**ty)));
            }
        }
        self.ann.post(self, NodeSubItem(ti.id))
    }

    pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
        try!(self.ann.pre(self, NodeSubItem(ii.id)));
        try!(self.hardbreak_if_not_bol());
        try!(self.maybe_print_comment(ii.span.lo));
        try!(self.print_outer_attributes(&ii.attrs));
        match ii.node {
            ast::ImplItemKind::Const(ref ty, ref expr) => {
                try!(self.print_associated_const(ii.ident, &ty, Some(&expr), ii.vis));
            }
            ast::ImplItemKind::Method(ref sig, ref body) => {
                try!(self.head(""));
                try!(self.print_method_sig(ii.ident, sig, ii.vis));
                try!(self.nbsp());
                try!(self.print_block_with_attrs(body, &ii.attrs));
            }
            ast::ImplItemKind::Type(ref ty) => {
                try!(self.print_associated_type(ii.ident, None, Some(ty)));
            }
            ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
                // code copied from ItemMac:
                try!(self.print_path(&node.path, false, 0));
                try!(word(&mut self.s, "! "));
                try!(self.cbox(INDENT_UNIT));
                try!(self.popen());
                try!(self.print_tts(&node.tts[..]));
                try!(self.pclose());
                try!(word(&mut self.s, ";"));
                try!(self.end())
            }
        }
        self.ann.post(self, NodeSubItem(ii.id))
    }

    pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
        try!(self.maybe_print_comment(st.span.lo));
        match st.node {
            ast::StmtDecl(ref decl, _) => {
                try!(self.print_decl(&**decl));
            }
            ast::StmtExpr(ref expr, _) => {
                try!(self.space_if_not_bol());
                try!(self.print_expr_outer_attr_style(&**expr, false));
            }
            ast::StmtSemi(ref expr, _) => {
                try!(self.space_if_not_bol());
                try!(self.print_expr_outer_attr_style(&**expr, false));
                try!(word(&mut self.s, ";"));
            }
            ast::StmtMac(ref mac, style, ref attrs) => {
                try!(self.space_if_not_bol());
                try!(self.print_outer_attributes(attrs.as_attr_slice()));
                let delim = match style {
                    ast::MacStmtWithBraces => token::Brace,
                    _ => token::Paren
                };
                try!(self.print_mac(&**mac, delim));
                match style {
                    ast::MacStmtWithBraces => {}
                    _ => try!(word(&mut self.s, ";")),
                }
            }
        }
        if parse::classify::stmt_ends_with_semi(&st.node) {
            try!(word(&mut self.s, ";"));
        }
        self.maybe_print_trailing_comment(st.span, None)
    }

    pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
        self.print_block_with_attrs(blk, &[])
    }

    pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
        self.print_block_unclosed_indent(blk, INDENT_UNIT)
    }

    pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
                                            attrs: &[ast::Attribute])
                                           -> io::Result<()> {
        self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
    }

    pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
                                       indented: usize) -> io::Result<()> {
        self.print_block_maybe_unclosed(blk, indented, &[], false)
    }

    pub fn print_block_with_attrs(&mut self,
                                  blk: &ast::Block,
                                  attrs: &[ast::Attribute]) -> io::Result<()> {
        self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
    }

    pub fn print_block_maybe_unclosed(&mut self,
                                      blk: &ast::Block,
                                      indented: usize,
                                      attrs: &[ast::Attribute],
                                      close_box: bool) -> io::Result<()> {
        match blk.rules {
            ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
            ast::DefaultBlock => ()
        }
        try!(self.maybe_print_comment(blk.span.lo));
        try!(self.ann.pre(self, NodeBlock(blk)));
        try!(self.bopen());

        try!(self.print_inner_attributes(attrs));

        for st in &blk.stmts {
            try!(self.print_stmt(&**st));
        }
        match blk.expr {
            Some(ref expr) => {
                try!(self.space_if_not_bol());
                try!(self.print_expr_outer_attr_style(&**expr, false));
                try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
            }
            _ => ()
        }
        try!(self.bclose_maybe_open(blk.span, indented, close_box));
        self.ann.post(self, NodeBlock(blk))
    }

    fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
        match els {
            Some(_else) => {
                match _else.node {
                    // "another else-if"
                    ast::ExprIf(ref i, ref then, ref e) => {
                        try!(self.cbox(INDENT_UNIT - 1));
                        try!(self.ibox(0));
                        try!(word(&mut self.s, " else if "));
                        try!(self.print_expr(&**i));
                        try!(space(&mut self.s));
                        try!(self.print_block(&**then));
                        self.print_else(e.as_ref().map(|e| &**e))
                    }
                    // "another else-if-let"
                    ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
                        try!(self.cbox(INDENT_UNIT - 1));
                        try!(self.ibox(0));
                        try!(word(&mut self.s, " else if let "));
                        try!(self.print_pat(&**pat));
                        try!(space(&mut self.s));
                        try!(self.word_space("="));
                        try!(self.print_expr(&**expr));
                        try!(space(&mut self.s));
                        try!(self.print_block(&**then));
                        self.print_else(e.as_ref().map(|e| &**e))
                    }
                    // "final else"
                    ast::ExprBlock(ref b) => {
                        try!(self.cbox(INDENT_UNIT - 1));
                        try!(self.ibox(0));
                        try!(word(&mut self.s, " else "));
                        self.print_block(&**b)
                    }
                    // BLEAH, constraints would be great here
                    _ => {
                        panic!("print_if saw if with weird alternative");
                    }
                }
            }
            _ => Ok(())
        }
    }

    pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
                    elseopt: Option<&ast::Expr>) -> io::Result<()> {
        try!(self.head("if"));
        try!(self.print_expr(test));
        try!(space(&mut self.s));
        try!(self.print_block(blk));
        self.print_else(elseopt)
    }

    pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
                        elseopt: Option<&ast::Expr>) -> io::Result<()> {
        try!(self.head("if let"));
        try!(self.print_pat(pat));
        try!(space(&mut self.s));
        try!(self.word_space("="));
        try!(self.print_expr(expr));
        try!(space(&mut self.s));
        try!(self.print_block(blk));
        self.print_else(elseopt)
    }

    pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
                     -> io::Result<()> {
        try!(self.print_path(&m.node.path, false, 0));
        try!(word(&mut self.s, "!"));
        match delim {
            token::Paren => try!(self.popen()),
            token::Bracket => try!(word(&mut self.s, "[")),
            token::Brace => {
                // head-ibox, will be closed by bopen()
                try!(self.ibox(0));
                // Don't ask me why the regular bopen() does
                // more then just opening a brace...
                try!(self.bopen())
            }
        }
        try!(self.print_tts(&m.node.tts));
        match delim {
            token::Paren => self.pclose(),
            token::Bracket => word(&mut self.s, "]"),
            token::Brace => self.bclose(m.span),
        }
    }


    fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
        try!(self.popen());
        try!(self.commasep_exprs(Inconsistent, args));
        self.pclose()
    }

    pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
                                      binop: ast::BinOp) -> bool {
        match sub_expr.node {
            ast::ExprBinary(ref sub_op, _, _) => {
                if AssocOp::from_ast_binop(sub_op.node).precedence() <
                    AssocOp::from_ast_binop(binop.node).precedence() {
                    true
                } else {
                    false
                }
            }
            _ => true
        }
    }

    pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
        let needs_par = needs_parentheses(expr);
        if needs_par {
            try!(self.popen());
        }
        try!(self.print_expr(expr));
        if needs_par {
            try!(self.pclose());
        }
        Ok(())
    }

    fn print_expr_in_place(&mut self,
                           place: &ast::Expr,
                           expr: &ast::Expr) -> io::Result<()> {
        try!(self.print_expr_maybe_paren(place));
        try!(space(&mut self.s));
        try!(self.word_space("<-"));
        self.print_expr_maybe_paren(expr)
    }

    fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
                      attrs: &[Attribute]) -> io::Result<()> {
        try!(self.ibox(INDENT_UNIT));
        try!(word(&mut self.s, "["));
        try!(self.print_inner_attributes_inline(attrs));
        try!(self.commasep_exprs(Inconsistent, &exprs[..]));
        try!(word(&mut self.s, "]"));
        self.end()
    }

    fn print_expr_repeat(&mut self,
                         element: &ast::Expr,
                         count: &ast::Expr,
                         attrs: &[Attribute]) -> io::Result<()> {
        try!(self.ibox(INDENT_UNIT));
        try!(word(&mut self.s, "["));
        try!(self.print_inner_attributes_inline(attrs));
        try!(self.print_expr(element));
        try!(self.word_space(";"));
        try!(self.print_expr(count));
        try!(word(&mut self.s, "]"));
        self.end()
    }

    fn print_expr_struct(&mut self,
                         path: &ast::Path,
                         fields: &[ast::Field],
                         wth: &Option<P<ast::Expr>>,
                         attrs: &[Attribute]) -> io::Result<()> {
        try!(self.print_path(path, true, 0));
        try!(word(&mut self.s, "{"));
        try!(self.print_inner_attributes_inline(attrs));
        try!(self.commasep_cmnt(
            Consistent,
            &fields[..],
            |s, field| {
                try!(s.ibox(INDENT_UNIT));
                try!(s.print_ident(field.ident.node));
                try!(s.word_space(":"));
                try!(s.print_expr(&*field.expr));
                s.end()
            },
            |f| f.span));
        match *wth {
            Some(ref expr) => {
                try!(self.ibox(INDENT_UNIT));
                if !fields.is_empty() {
                    try!(word(&mut self.s, ","));
                    try!(space(&mut self.s));
                }
                try!(word(&mut self.s, ".."));
                try!(self.print_expr(&**expr));
                try!(self.end());
            }
            _ => if !fields.is_empty() {
                try!(word(&mut self.s, ","))
            }
        }
        try!(word(&mut self.s, "}"));
        Ok(())
    }

    fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
                      attrs: &[Attribute]) -> io::Result<()> {
        try!(self.popen());
        try!(self.print_inner_attributes_inline(attrs));
        try!(self.commasep_exprs(Inconsistent, &exprs[..]));
        if exprs.len() == 1 {
            try!(word(&mut self.s, ","));
        }
        self.pclose()
    }

    fn print_expr_call(&mut self,
                       func: &ast::Expr,
                       args: &[P<ast::Expr>]) -> io::Result<()> {
        try!(self.print_expr_maybe_paren(func));
        self.print_call_post(args)
    }

    fn print_expr_method_call(&mut self,
                              ident: ast::SpannedIdent,
                              tys: &[P<ast::Ty>],
                              args: &[P<ast::Expr>]) -> io::Result<()> {
        let base_args = &args[1..];
        try!(self.print_expr(&*args[0]));
        try!(word(&mut self.s, "."));
        try!(self.print_ident(ident.node));
        if !tys.is_empty() {
            try!(word(&mut self.s, "::<"));
            try!(self.commasep(Inconsistent, tys,
                               |s, ty| s.print_type(&**ty)));
            try!(word(&mut self.s, ">"));
        }
        self.print_call_post(base_args)
    }

    fn print_expr_binary(&mut self,
                         op: ast::BinOp,
                         lhs: &ast::Expr,
                         rhs: &ast::Expr) -> io::Result<()> {
        if self.check_expr_bin_needs_paren(lhs, op) {
            try!(self.print_expr_maybe_paren(lhs));
        } else {
            try!(self.print_expr(lhs));
        }
        try!(space(&mut self.s));
        try!(self.word_space(ast_util::binop_to_string(op.node)));
        if self.check_expr_bin_needs_paren(rhs, op) {
            self.print_expr_maybe_paren(rhs)
        } else {
            self.print_expr(rhs)
        }
    }

    fn print_expr_unary(&mut self,
                        op: ast::UnOp,
                        expr: &ast::Expr) -> io::Result<()> {
        try!(word(&mut self.s, ast_util::unop_to_string(op)));
        self.print_expr_maybe_paren(expr)
    }

    fn print_expr_addr_of(&mut self,
                          mutability: ast::Mutability,
                          expr: &ast::Expr) -> io::Result<()> {
        try!(word(&mut self.s, "&"));
        try!(self.print_mutability(mutability));
        self.print_expr_maybe_paren(expr)
    }

    pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
        self.print_expr_outer_attr_style(expr, true)
    }

    fn print_expr_outer_attr_style(&mut self,
                                  expr: &ast::Expr,
                                  is_inline: bool) -> io::Result<()> {
        try!(self.maybe_print_comment(expr.span.lo));

        let attrs = expr.attrs.as_attr_slice();
        if is_inline {
            try!(self.print_outer_attributes_inline(attrs));
        } else {
            try!(self.print_outer_attributes(attrs));
        }

        try!(self.ibox(INDENT_UNIT));
        try!(self.ann.pre(self, NodeExpr(expr)));
        match expr.node {
            ast::ExprBox(ref expr) => {
                try!(self.word_space("box"));
                try!(self.print_expr(expr));
            }
            ast::ExprInPlace(ref place, ref expr) => {
                try!(self.print_expr_in_place(place, expr));
            }
            ast::ExprVec(ref exprs) => {
                try!(self.print_expr_vec(&exprs[..], attrs));
            }
            ast::ExprRepeat(ref element, ref count) => {
                try!(self.print_expr_repeat(&**element, &**count, attrs));
            }
            ast::ExprStruct(ref path, ref fields, ref wth) => {
                try!(self.print_expr_struct(path, &fields[..], wth, attrs));
            }
            ast::ExprTup(ref exprs) => {
                try!(self.print_expr_tup(&exprs[..], attrs));
            }
            ast::ExprCall(ref func, ref args) => {
                try!(self.print_expr_call(&**func, &args[..]));
            }
            ast::ExprMethodCall(ident, ref tys, ref args) => {
                try!(self.print_expr_method_call(ident, &tys[..], &args[..]));
            }
            ast::ExprBinary(op, ref lhs, ref rhs) => {
                try!(self.print_expr_binary(op, &**lhs, &**rhs));
            }
            ast::ExprUnary(op, ref expr) => {
                try!(self.print_expr_unary(op, &**expr));
            }
            ast::ExprAddrOf(m, ref expr) => {
                try!(self.print_expr_addr_of(m, &**expr));
            }
            ast::ExprLit(ref lit) => {
                try!(self.print_literal(&**lit));
            }
            ast::ExprCast(ref expr, ref ty) => {
                if let ast::ExprCast(..) = expr.node {
                    try!(self.print_expr(&**expr));
                } else {
                    try!(self.print_expr_maybe_paren(&**expr));
                }
                try!(space(&mut self.s));
                try!(self.word_space("as"));
                try!(self.print_type(&**ty));
            }
            ast::ExprIf(ref test, ref blk, ref elseopt) => {
                try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
            }
            ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
                try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
            }
            ast::ExprWhile(ref test, ref blk, opt_ident) => {
                if let Some(ident) = opt_ident {
                    try!(self.print_ident(ident));
                    try!(self.word_space(":"));
                }
                try!(self.head("while"));
                try!(self.print_expr(&**test));
                try!(space(&mut self.s));
                try!(self.print_block_with_attrs(&**blk, attrs));
            }
            ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
                if let Some(ident) = opt_ident {
                    try!(self.print_ident(ident));
                    try!(self.word_space(":"));
                }
                try!(self.head("while let"));
                try!(self.print_pat(&**pat));
                try!(space(&mut self.s));
                try!(self.word_space("="));
                try!(self.print_expr(&**expr));
                try!(space(&mut self.s));
                try!(self.print_block_with_attrs(&**blk, attrs));
            }
            ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
                if let Some(ident) = opt_ident {
                    try!(self.print_ident(ident));
                    try!(self.word_space(":"));
                }
                try!(self.head("for"));
                try!(self.print_pat(&**pat));
                try!(space(&mut self.s));
                try!(self.word_space("in"));
                try!(self.print_expr(&**iter));
                try!(space(&mut self.s));
                try!(self.print_block_with_attrs(&**blk, attrs));
            }
            ast::ExprLoop(ref blk, opt_ident) => {
                if let Some(ident) = opt_ident {
                    try!(self.print_ident(ident));
                    try!(self.word_space(":"));
                }
                try!(self.head("loop"));
                try!(space(&mut self.s));
                try!(self.print_block_with_attrs(&**blk, attrs));
            }
            ast::ExprMatch(ref expr, ref arms) => {
                try!(self.cbox(INDENT_UNIT));
                try!(self.ibox(4));
                try!(self.word_nbsp("match"));
                try!(self.print_expr(&**expr));
                try!(space(&mut self.s));
                try!(self.bopen());
                try!(self.print_inner_attributes_no_trailing_hardbreak(attrs));
                for arm in arms {
                    try!(self.print_arm(arm));
                }
                try!(self.bclose_(expr.span, INDENT_UNIT));
            }
            ast::ExprClosure(capture_clause, ref decl, ref body) => {
                try!(self.print_capture_clause(capture_clause));

                try!(self.print_fn_block_args(&**decl));
                try!(space(&mut self.s));

                let default_return = match decl.output {
                    ast::DefaultReturn(..) => true,
                    _ => false
                };

                if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
                    try!(self.print_block_unclosed(&**body));
                } else {
                    // we extract the block, so as not to create another set of boxes
                    let i_expr = body.expr.as_ref().unwrap();
                    match i_expr.node {
                        ast::ExprBlock(ref blk) => {
                            try!(self.print_block_unclosed_with_attrs(
                                &**blk,
                                i_expr.attrs.as_attr_slice()));
                        }
                        _ => {
                            // this is a bare expression
                            try!(self.print_expr(&**i_expr));
                            try!(self.end()); // need to close a box
                        }
                    }
                }
                // a box will be closed by print_expr, but we didn't want an overall
                // wrapper so we closed the corresponding opening. so create an
                // empty box to satisfy the close.
                try!(self.ibox(0));
            }
            ast::ExprBlock(ref blk) => {
                // containing cbox, will be closed by print-block at }
                try!(self.cbox(INDENT_UNIT));
                // head-box, will be closed by print-block after {
                try!(self.ibox(0));
                try!(self.print_block_with_attrs(&**blk, attrs));
            }
            ast::ExprAssign(ref lhs, ref rhs) => {
                try!(self.print_expr(&**lhs));
                try!(space(&mut self.s));
                try!(self.word_space("="));
                try!(self.print_expr(&**rhs));
            }
            ast::ExprAssignOp(op, ref lhs, ref rhs) => {
                try!(self.print_expr(&**lhs));
                try!(space(&mut self.s));
                try!(word(&mut self.s, ast_util::binop_to_string(op.node)));
                try!(self.word_space("="));
                try!(self.print_expr(&**rhs));
            }
            ast::ExprField(ref expr, id) => {
                try!(self.print_expr(&**expr));
                try!(word(&mut self.s, "."));
                try!(self.print_ident(id.node));
            }
            ast::ExprTupField(ref expr, id) => {
                try!(self.print_expr(&**expr));
                try!(word(&mut self.s, "."));
                try!(self.print_usize(id.node));
            }
            ast::ExprIndex(ref expr, ref index) => {
                try!(self.print_expr(&**expr));
                try!(word(&mut self.s, "["));
                try!(self.print_expr(&**index));
                try!(word(&mut self.s, "]"));
            }
            ast::ExprRange(ref start, ref end) => {
                if let &Some(ref e) = start {
                    try!(self.print_expr(&**e));
                }
                try!(word(&mut self.s, ".."));
                if let &Some(ref e) = end {
                    try!(self.print_expr(&**e));
                }
            }
            ast::ExprPath(None, ref path) => {
                try!(self.print_path(path, true, 0))
            }
            ast::ExprPath(Some(ref qself), ref path) => {
                try!(self.print_qpath(path, qself, true))
            }
            ast::ExprBreak(opt_ident) => {
                try!(word(&mut self.s, "break"));
                try!(space(&mut self.s));
                if let Some(ident) = opt_ident {
                    try!(self.print_ident(ident.node));
                    try!(space(&mut self.s));
                }
            }
            ast::ExprAgain(opt_ident) => {
                try!(word(&mut self.s, "continue"));
                try!(space(&mut self.s));
                if let Some(ident) = opt_ident {
                    try!(self.print_ident(ident.node));
                    try!(space(&mut self.s))
                }
            }
            ast::ExprRet(ref result) => {
                try!(word(&mut self.s, "return"));
                match *result {
                    Some(ref expr) => {
                        try!(word(&mut self.s, " "));
                        try!(self.print_expr(&**expr));
                    }
                    _ => ()
                }
            }
            ast::ExprInlineAsm(ref a) => {
                try!(word(&mut self.s, "asm!"));
                try!(self.popen());
                try!(self.print_string(&a.asm, a.asm_str_style));
                try!(self.word_space(":"));

                try!(self.commasep(Inconsistent, &a.outputs,
                                   |s, &(ref co, ref o, is_rw)| {
                    match slice_shift_char(co) {
                        Some(('=', operand)) if is_rw => {
                            try!(s.print_string(&format!("+{}", operand),
                                                ast::CookedStr))
                        }
                        _ => try!(s.print_string(&co, ast::CookedStr))
                    }
                    try!(s.popen());
                    try!(s.print_expr(&**o));
                    try!(s.pclose());
                    Ok(())
                }));
                try!(space(&mut self.s));
                try!(self.word_space(":"));

                try!(self.commasep(Inconsistent, &a.inputs,
                                   |s, &(ref co, ref o)| {
                    try!(s.print_string(&co, ast::CookedStr));
                    try!(s.popen());
                    try!(s.print_expr(&**o));
                    try!(s.pclose());
                    Ok(())
                }));
                try!(space(&mut self.s));
                try!(self.word_space(":"));

                try!(self.commasep(Inconsistent, &a.clobbers,
                                   |s, co| {
                    try!(s.print_string(&co, ast::CookedStr));
                    Ok(())
                }));

                let mut options = vec!();
                if a.volatile {
                    options.push("volatile");
                }
                if a.alignstack {
                    options.push("alignstack");
                }
                if a.dialect == ast::AsmDialect::Intel {
                    options.push("intel");
                }

                if !options.is_empty() {
                    try!(space(&mut self.s));
                    try!(self.word_space(":"));
                    try!(self.commasep(Inconsistent, &*options,
                                       |s, &co| {
                        try!(s.print_string(co, ast::CookedStr));
                        Ok(())
                    }));
                }

                try!(self.pclose());
            }
            ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
            ast::ExprParen(ref e) => {
                try!(self.popen());
                try!(self.print_inner_attributes_inline(attrs));
                try!(self.print_expr(&**e));
                try!(self.pclose());
            }
        }
        try!(self.ann.post(self, NodeExpr(expr)));
        self.end()
    }

    pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
        try!(self.print_pat(&*loc.pat));
        if let Some(ref ty) = loc.ty {
            try!(self.word_space(":"));
            try!(self.print_type(&**ty));
        }
        Ok(())
    }

    pub fn print_decl(&mut self, decl: &ast::Decl) -> io::Result<()> {
        try!(self.maybe_print_comment(decl.span.lo));
        match decl.node {
            ast::DeclLocal(ref loc) => {
                try!(self.print_outer_attributes(loc.attrs.as_attr_slice()));
                try!(self.space_if_not_bol());
                try!(self.ibox(INDENT_UNIT));
                try!(self.word_nbsp("let"));

                try!(self.ibox(INDENT_UNIT));
                try!(self.print_local_decl(&**loc));
                try!(self.end());
                if let Some(ref init) = loc.init {
                    try!(self.nbsp());
                    try!(self.word_space("="));
                    try!(self.print_expr(&**init));
                }
                self.end()
            }
            ast::DeclItem(ref item) => self.print_item(&**item)
        }
    }

    pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
        try!(word(&mut self.s, &ident.name.as_str()));
        self.ann.post(self, NodeIdent(&ident))
    }

    pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
        word(&mut self.s, &i.to_string())
    }

    pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
        try!(word(&mut self.s, &name.as_str()));
        self.ann.post(self, NodeName(&name))
    }

    pub fn print_for_decl(&mut self, loc: &ast::Local,
                          coll: &ast::Expr) -> io::Result<()> {
        try!(self.print_local_decl(loc));
        try!(space(&mut self.s));
        try!(self.word_space("in"));
        self.print_expr(coll)
    }

    fn print_path(&mut self,
                  path: &ast::Path,
                  colons_before_params: bool,
                  depth: usize)
                  -> io::Result<()>
    {
        try!(self.maybe_print_comment(path.span.lo));

        let mut first = !path.global;
        for segment in &path.segments[..path.segments.len()-depth] {
            if first {
                first = false
            } else {
                try!(word(&mut self.s, "::"))
            }

            try!(self.print_ident(segment.identifier));

            try!(self.print_path_parameters(&segment.parameters, colons_before_params));
        }

        Ok(())
    }

    fn print_qpath(&mut self,
                   path: &ast::Path,
                   qself: &ast::QSelf,
                   colons_before_params: bool)
                   -> io::Result<()>
    {
        try!(word(&mut self.s, "<"));
        try!(self.print_type(&qself.ty));
        if qself.position > 0 {
            try!(space(&mut self.s));
            try!(self.word_space("as"));
            let depth = path.segments.len() - qself.position;
            try!(self.print_path(&path, false, depth));
        }
        try!(word(&mut self.s, ">"));
        try!(word(&mut self.s, "::"));
        let item_segment = path.segments.last().unwrap();
        try!(self.print_ident(item_segment.identifier));
        self.print_path_parameters(&item_segment.parameters, colons_before_params)
    }

    fn print_path_parameters(&mut self,
                             parameters: &ast::PathParameters,
                             colons_before_params: bool)
                             -> io::Result<()>
    {
        if parameters.is_empty() {
            return Ok(());
        }

        if colons_before_params {
            try!(word(&mut self.s, "::"))
        }

        match *parameters {
            ast::AngleBracketedParameters(ref data) => {
                try!(word(&mut self.s, "<"));

                let mut comma = false;
                for lifetime in &data.lifetimes {
                    if comma {
                        try!(self.word_space(","))
                    }
                    try!(self.print_lifetime(lifetime));
                    comma = true;
                }

                if !data.types.is_empty() {
                    if comma {
                        try!(self.word_space(","))
                    }
                    try!(self.commasep(
                        Inconsistent,
                        &data.types,
                        |s, ty| s.print_type(&**ty)));
                        comma = true;
                }

                for binding in data.bindings.iter() {
                    if comma {
                        try!(self.word_space(","))
                    }
                    try!(self.print_ident(binding.ident));
                    try!(space(&mut self.s));
                    try!(self.word_space("="));
                    try!(self.print_type(&*binding.ty));
                    comma = true;
                }

                try!(word(&mut self.s, ">"))
            }

            ast::ParenthesizedParameters(ref data) => {
                try!(word(&mut self.s, "("));
                try!(self.commasep(
                    Inconsistent,
                    &data.inputs,
                    |s, ty| s.print_type(&**ty)));
                try!(word(&mut self.s, ")"));

                match data.output {
                    None => { }
                    Some(ref ty) => {
                        try!(self.space_if_not_bol());
                        try!(self.word_space("->"));
                        try!(self.print_type(&**ty));
                    }
                }
            }
        }

        Ok(())
    }

    pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
        try!(self.maybe_print_comment(pat.span.lo));
        try!(self.ann.pre(self, NodePat(pat)));
        /* Pat isn't normalized, but the beauty of it
         is that it doesn't matter */
        match pat.node {
            ast::PatWild => try!(word(&mut self.s, "_")),
            ast::PatIdent(binding_mode, ref path1, ref sub) => {
                match binding_mode {
                    ast::BindByRef(mutbl) => {
                        try!(self.word_nbsp("ref"));
                        try!(self.print_mutability(mutbl));
                    }
                    ast::BindByValue(ast::MutImmutable) => {}
                    ast::BindByValue(ast::MutMutable) => {
                        try!(self.word_nbsp("mut"));
                    }
                }
                try!(self.print_ident(path1.node));
                match *sub {
                    Some(ref p) => {
                        try!(word(&mut self.s, "@"));
                        try!(self.print_pat(&**p));
                    }
                    None => ()
                }
            }
            ast::PatEnum(ref path, ref args_) => {
                try!(self.print_path(path, true, 0));
                match *args_ {
                    None => try!(word(&mut self.s, "(..)")),
                    Some(ref args) => {
                        if !args.is_empty() {
                            try!(self.popen());
                            try!(self.commasep(Inconsistent, &args[..],
                                              |s, p| s.print_pat(&**p)));
                            try!(self.pclose());
                        }
                    }
                }
            }
            ast::PatQPath(ref qself, ref path) => {
                try!(self.print_qpath(path, qself, false));
            }
            ast::PatStruct(ref path, ref fields, etc) => {
                try!(self.print_path(path, true, 0));
                try!(self.nbsp());
                try!(self.word_space("{"));
                try!(self.commasep_cmnt(
                    Consistent, &fields[..],
                    |s, f| {
                        try!(s.cbox(INDENT_UNIT));
                        if !f.node.is_shorthand {
                            try!(s.print_ident(f.node.ident));
                            try!(s.word_nbsp(":"));
                        }
                        try!(s.print_pat(&*f.node.pat));
                        s.end()
                    },
                    |f| f.node.pat.span));
                if etc {
                    if !fields.is_empty() { try!(self.word_space(",")); }
                    try!(word(&mut self.s, ".."));
                }
                try!(space(&mut self.s));
                try!(word(&mut self.s, "}"));
            }
            ast::PatTup(ref elts) => {
                try!(self.popen());
                try!(self.commasep(Inconsistent,
                                   &elts[..],
                                   |s, p| s.print_pat(&**p)));
                if elts.len() == 1 {
                    try!(word(&mut self.s, ","));
                }
                try!(self.pclose());
            }
            ast::PatBox(ref inner) => {
                try!(word(&mut self.s, "box "));
                try!(self.print_pat(&**inner));
            }
            ast::PatRegion(ref inner, mutbl) => {
                try!(word(&mut self.s, "&"));
                if mutbl == ast::MutMutable {
                    try!(word(&mut self.s, "mut "));
                }
                try!(self.print_pat(&**inner));
            }
            ast::PatLit(ref e) => try!(self.print_expr(&**e)),
            ast::PatRange(ref begin, ref end) => {
                try!(self.print_expr(&**begin));
                try!(space(&mut self.s));
                try!(word(&mut self.s, "..."));
                try!(self.print_expr(&**end));
            }
            ast::PatVec(ref before, ref slice, ref after) => {
                try!(word(&mut self.s, "["));
                try!(self.commasep(Inconsistent,
                                   &before[..],
                                   |s, p| s.print_pat(&**p)));
                if let Some(ref p) = *slice {
                    if !before.is_empty() { try!(self.word_space(",")); }
                    if p.node != ast::PatWild {
                        try!(self.print_pat(&**p));
                    }
                    try!(word(&mut self.s, ".."));
                    if !after.is_empty() { try!(self.word_space(",")); }
                }
                try!(self.commasep(Inconsistent,
                                   &after[..],
                                   |s, p| s.print_pat(&**p)));
                try!(word(&mut self.s, "]"));
            }
            ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
        }
        self.ann.post(self, NodePat(pat))
    }

    fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
        // I have no idea why this check is necessary, but here it
        // is :(
        if arm.attrs.is_empty() {
            try!(space(&mut self.s));
        }
        try!(self.cbox(INDENT_UNIT));
        try!(self.ibox(0));
        try!(self.print_outer_attributes(&arm.attrs));
        let mut first = true;
        for p in &arm.pats {
            if first {
                first = false;
            } else {
                try!(space(&mut self.s));
                try!(self.word_space("|"));
            }
            try!(self.print_pat(&**p));
        }
        try!(space(&mut self.s));
        if let Some(ref e) = arm.guard {
            try!(self.word_space("if"));
            try!(self.print_expr(&**e));
            try!(space(&mut self.s));
        }
        try!(self.word_space("=>"));

        match arm.body.node {
            ast::ExprBlock(ref blk) => {
                // the block will close the pattern's ibox
                try!(self.print_block_unclosed_indent(&**blk, INDENT_UNIT));

                // If it is a user-provided unsafe block, print a comma after it
                if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
                    try!(word(&mut self.s, ","));
                }
            }
            _ => {
                try!(self.end()); // close the ibox for the pattern
                try!(self.print_expr(&*arm.body));
                try!(word(&mut self.s, ","));
            }
        }
        self.end() // close enclosing cbox
    }

    // Returns whether it printed anything
    fn print_explicit_self(&mut self,
                           explicit_self: &ast::ExplicitSelf_,
                           mutbl: ast::Mutability) -> io::Result<bool> {
        try!(self.print_mutability(mutbl));
        match *explicit_self {
            ast::SelfStatic => { return Ok(false); }
            ast::SelfValue(_) => {
                try!(word(&mut self.s, "self"));
            }
            ast::SelfRegion(ref lt, m, _) => {
                try!(word(&mut self.s, "&"));
                try!(self.print_opt_lifetime(lt));
                try!(self.print_mutability(m));
                try!(word(&mut self.s, "self"));
            }
            ast::SelfExplicit(ref typ, _) => {
                try!(word(&mut self.s, "self"));
                try!(self.word_space(":"));
                try!(self.print_type(&**typ));
            }
        }
        return Ok(true);
    }

    pub fn print_fn(&mut self,
                    decl: &ast::FnDecl,
                    unsafety: ast::Unsafety,
                    constness: ast::Constness,
                    abi: abi::Abi,
                    name: Option<ast::Ident>,
                    generics: &ast::Generics,
                    opt_explicit_self: Option<&ast::ExplicitSelf_>,
                    vis: ast::Visibility) -> io::Result<()> {
        try!(self.print_fn_header_info(unsafety, constness, abi, vis));

        if let Some(name) = name {
            try!(self.nbsp());
            try!(self.print_ident(name));
        }
        try!(self.print_generics(generics));
        try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
        self.print_where_clause(&generics.where_clause)
    }

    pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
                         opt_explicit_self: Option<&ast::ExplicitSelf_>)
        -> io::Result<()> {
        // It is unfortunate to duplicate the commasep logic, but we want the
        // self type and the args all in the same box.
        try!(self.rbox(0, Inconsistent));
        let mut first = true;
        if let Some(explicit_self) = opt_explicit_self {
            let m = match *explicit_self {
                ast::SelfStatic => ast::MutImmutable,
                _ => match decl.inputs[0].pat.node {
                    ast::PatIdent(ast::BindByValue(m), _, _) => m,
                    _ => ast::MutImmutable
                }
            };
            first = !try!(self.print_explicit_self(explicit_self, m));
        }

        // HACK(eddyb) ignore the separately printed self argument.
        let args = if first {
            &decl.inputs[..]
        } else {
            &decl.inputs[1..]
        };

        for arg in args {
            if first { first = false; } else { try!(self.word_space(",")); }
            try!(self.print_arg(arg));
        }

        self.end()
    }

    pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
                                 opt_explicit_self: Option<&ast::ExplicitSelf_>)
        -> io::Result<()> {
        try!(self.popen());
        try!(self.print_fn_args(decl, opt_explicit_self));
        if decl.variadic {
            try!(word(&mut self.s, ", ..."));
        }
        try!(self.pclose());

        self.print_fn_output(decl)
    }

    pub fn print_fn_block_args(
            &mut self,
            decl: &ast::FnDecl)
            -> io::Result<()> {
        try!(word(&mut self.s, "|"));
        try!(self.print_fn_args(decl, None));
        try!(word(&mut self.s, "|"));

        if let ast::DefaultReturn(..) = decl.output {
            return Ok(());
        }

        try!(self.space_if_not_bol());
        try!(self.word_space("->"));
        match decl.output {
            ast::Return(ref ty) => {
                try!(self.print_type(&**ty));
                self.maybe_print_comment(ty.span.lo)
            }
            ast::DefaultReturn(..) => unreachable!(),
            ast::NoReturn(span) => {
                try!(self.word_nbsp("!"));
                self.maybe_print_comment(span.lo)
            }
        }
    }

    pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
                                -> io::Result<()> {
        match capture_clause {
            ast::CaptureByValue => self.word_space("move"),
            ast::CaptureByRef => Ok(()),
        }
    }

    pub fn print_bounds(&mut self,
                        prefix: &str,
                        bounds: &[ast::TyParamBound])
                        -> io::Result<()> {
        if !bounds.is_empty() {
            try!(word(&mut self.s, prefix));
            let mut first = true;
            for bound in bounds {
                try!(self.nbsp());
                if first {
                    first = false;
                } else {
                    try!(self.word_space("+"));
                }

                try!(match *bound {
                    TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
                        self.print_poly_trait_ref(tref)
                    }
                    TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
                        try!(word(&mut self.s, "?"));
                        self.print_poly_trait_ref(tref)
                    }
                    RegionTyParamBound(ref lt) => {
                        self.print_lifetime(lt)
                    }
                })
            }
            Ok(())
        } else {
            Ok(())
        }
    }

    pub fn print_lifetime(&mut self,
                          lifetime: &ast::Lifetime)
                          -> io::Result<()>
    {
        self.print_name(lifetime.name)
    }

    pub fn print_lifetime_def(&mut self,
                              lifetime: &ast::LifetimeDef)
                              -> io::Result<()>
    {
        try!(self.print_lifetime(&lifetime.lifetime));
        let mut sep = ":";
        for v in &lifetime.bounds {
            try!(word(&mut self.s, sep));
            try!(self.print_lifetime(v));
            sep = "+";
        }
        Ok(())
    }

    pub fn print_generics(&mut self,
                          generics: &ast::Generics)
                          -> io::Result<()>
    {
        let total = generics.lifetimes.len() + generics.ty_params.len();
        if total == 0 {
            return Ok(());
        }

        try!(word(&mut self.s, "<"));

        let mut ints = Vec::new();
        for i in 0..total {
            ints.push(i);
        }

        try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
            if idx < generics.lifetimes.len() {
                let lifetime = &generics.lifetimes[idx];
                s.print_lifetime_def(lifetime)
            } else {
                let idx = idx - generics.lifetimes.len();
                let param = &generics.ty_params[idx];
                s.print_ty_param(param)
            }
        }));

        try!(word(&mut self.s, ">"));
        Ok(())
    }

    pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
        try!(self.print_ident(param.ident));
        try!(self.print_bounds(":", &param.bounds));
        match param.default {
            Some(ref default) => {
                try!(space(&mut self.s));
                try!(self.word_space("="));
                self.print_type(&**default)
            }
            _ => Ok(())
        }
    }

    pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
                              -> io::Result<()> {
        if where_clause.predicates.is_empty() {
            return Ok(())
        }

        try!(space(&mut self.s));
        try!(self.word_space("where"));

        for (i, predicate) in where_clause.predicates.iter().enumerate() {
            if i != 0 {
                try!(self.word_space(","));
            }

            match *predicate {
                ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
                                                                             ref bounded_ty,
                                                                             ref bounds,
                                                                             ..}) => {
                    try!(self.print_formal_lifetime_list(bound_lifetimes));
                    try!(self.print_type(&**bounded_ty));
                    try!(self.print_bounds(":", bounds));
                }
                ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
                                                                               ref bounds,
                                                                               ..}) => {
                    try!(self.print_lifetime(lifetime));
                    try!(word(&mut self.s, ":"));

                    for (i, bound) in bounds.iter().enumerate() {
                        try!(self.print_lifetime(bound));

                        if i != 0 {
                            try!(word(&mut self.s, ":"));
                        }
                    }
                }
                ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
                    try!(self.print_path(path, false, 0));
                    try!(space(&mut self.s));
                    try!(self.word_space("="));
                    try!(self.print_type(&**ty));
                }
            }
        }

        Ok(())
    }

    pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
        match vp.node {
            ast::ViewPathSimple(ident, ref path) => {
                try!(self.print_path(path, false, 0));

                if path.segments.last().unwrap().identifier.name !=
                        ident.name {
                    try!(space(&mut self.s));
                    try!(self.word_space("as"));
                    try!(self.print_ident(ident));
                }

                Ok(())
            }

            ast::ViewPathGlob(ref path) => {
                try!(self.print_path(path, false, 0));
                word(&mut self.s, "::*")
            }

            ast::ViewPathList(ref path, ref idents) => {
                if path.segments.is_empty() {
                    try!(word(&mut self.s, "{"));
                } else {
                    try!(self.print_path(path, false, 0));
                    try!(word(&mut self.s, "::{"));
                }
                try!(self.commasep(Inconsistent, &idents[..], |s, w| {
                    match w.node {
                        ast::PathListIdent { name, rename, .. } => {
                            try!(s.print_ident(name));
                            if let Some(ident) = rename {
                                try!(space(&mut s.s));
                                try!(s.word_space("as"));
                                try!(s.print_ident(ident));
                            }
                            Ok(())
                        },
                        ast::PathListMod { rename, .. } => {
                            try!(word(&mut s.s, "self"));
                            if let Some(ident) = rename {
                                try!(space(&mut s.s));
                                try!(s.word_space("as"));
                                try!(s.print_ident(ident));
                            }
                            Ok(())
                        }
                    }
                }));
                word(&mut self.s, "}")
            }
        }
    }

    pub fn print_mutability(&mut self,
                            mutbl: ast::Mutability) -> io::Result<()> {
        match mutbl {
            ast::MutMutable => self.word_nbsp("mut"),
            ast::MutImmutable => Ok(()),
        }
    }

    pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
        try!(self.print_mutability(mt.mutbl));
        self.print_type(&*mt.ty)
    }

    pub fn print_arg(&mut self, input: &ast::Arg) -> io::Result<()> {
        try!(self.ibox(INDENT_UNIT));
        match input.ty.node {
            ast::TyInfer => try!(self.print_pat(&*input.pat)),
            _ => {
                match input.pat.node {
                    ast::PatIdent(_, ref path1, _) if
                        path1.node.name ==
                            parse::token::special_idents::invalid.name => {
                        // Do nothing.
                    }
                    _ => {
                        try!(self.print_pat(&*input.pat));
                        try!(word(&mut self.s, ":"));
                        try!(space(&mut self.s));
                    }
                }
                try!(self.print_type(&*input.ty));
            }
        }
        self.end()
    }

    pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
        if let ast::DefaultReturn(..) = decl.output {
            return Ok(());
        }

        try!(self.space_if_not_bol());
        try!(self.ibox(INDENT_UNIT));
        try!(self.word_space("->"));
        match decl.output {
            ast::NoReturn(_) =>
                try!(self.word_nbsp("!")),
            ast::DefaultReturn(..) => unreachable!(),
            ast::Return(ref ty) =>
                try!(self.print_type(&**ty))
        }
        try!(self.end());

        match decl.output {
            ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
            _ => Ok(())
        }
    }

    pub fn print_ty_fn(&mut self,
                       abi: abi::Abi,
                       unsafety: ast::Unsafety,
                       decl: &ast::FnDecl,
                       name: Option<ast::Ident>,
                       generics: &ast::Generics,
                       opt_explicit_self: Option<&ast::ExplicitSelf_>)
                       -> io::Result<()> {
        try!(self.ibox(INDENT_UNIT));
        if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
            try!(word(&mut self.s, "for"));
            try!(self.print_generics(generics));
        }
        let generics = ast::Generics {
            lifetimes: Vec::new(),
            ty_params: OwnedSlice::empty(),
            where_clause: ast::WhereClause {
                id: ast::DUMMY_NODE_ID,
                predicates: Vec::new(),
            },
        };
        try!(self.print_fn(decl,
                           unsafety,
                           ast::Constness::NotConst,
                           abi,
                           name,
                           &generics,
                           opt_explicit_self,
                           ast::Inherited));
        self.end()
    }

    pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
                                        next_pos: Option<BytePos>)
        -> io::Result<()> {
        let cm = match self.cm {
            Some(cm) => cm,
            _ => return Ok(())
        };
        match self.next_comment() {
            Some(ref cmnt) => {
                if (*cmnt).style != comments::Trailing { return Ok(()) }
                let span_line = cm.lookup_char_pos(span.hi);
                let comment_line = cm.lookup_char_pos((*cmnt).pos);
                let mut next = (*cmnt).pos + BytePos(1);
                match next_pos { None => (), Some(p) => next = p }
                if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
                    span_line.line == comment_line.line {
                        try!(self.print_comment(cmnt));
                        self.cur_cmnt_and_lit.cur_cmnt += 1;
                    }
            }
            _ => ()
        }
        Ok(())
    }

    pub fn print_remaining_comments(&mut self) -> io::Result<()> {
        // If there aren't any remaining comments, then we need to manually
        // make sure there is a line break at the end.
        if self.next_comment().is_none() {
            try!(hardbreak(&mut self.s));
        }
        loop {
            match self.next_comment() {
                Some(ref cmnt) => {
                    try!(self.print_comment(cmnt));
                    self.cur_cmnt_and_lit.cur_cmnt += 1;
                }
                _ => break
            }
        }
        Ok(())
    }

    pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
                                                  opt_abi: Option<abi::Abi>)
        -> io::Result<()> {
        match opt_abi {
            Some(abi::Rust) => Ok(()),
            Some(abi) => {
                try!(self.word_nbsp("extern"));
                self.word_nbsp(&abi.to_string())
            }
            None => Ok(())
        }
    }

    pub fn print_extern_opt_abi(&mut self,
                                opt_abi: Option<abi::Abi>) -> io::Result<()> {
        match opt_abi {
            Some(abi) => {
                try!(self.word_nbsp("extern"));
                self.word_nbsp(&abi.to_string())
            }
            None => Ok(())
        }
    }

    pub fn print_fn_header_info(&mut self,
                                unsafety: ast::Unsafety,
                                constness: ast::Constness,
                                abi: abi::Abi,
                                vis: ast::Visibility) -> io::Result<()> {
        try!(word(&mut self.s, &visibility_qualified(vis, "")));

        match constness {
            ast::Constness::NotConst => {}
            ast::Constness::Const => try!(self.word_nbsp("const"))
        }

        try!(self.print_unsafety(unsafety));

        if abi != abi::Rust {
            try!(self.word_nbsp("extern"));
            try!(self.word_nbsp(&abi.to_string()));
        }

        word(&mut self.s, "fn")
    }

    pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
        match s {
            ast::Unsafety::Normal => Ok(()),
            ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
        }
    }
}

fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }

#[cfg(test)]
mod tests {
    use super::*;

    use ast;
    use ast_util;
    use codemap;
    use parse::token;

    #[test]
    fn test_fun_to_string() {
        let abba_ident = token::str_to_ident("abba");

        let decl = ast::FnDecl {
            inputs: Vec::new(),
            output: ast::DefaultReturn(codemap::DUMMY_SP),
            variadic: false
        };
        let generics = ast_util::empty_generics();
        assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
                                 ast::Constness::NotConst,
                                 abba_ident,
                                 None, &generics),
                   "fn abba()");
    }

    #[test]
    fn test_variant_to_string() {
        let ident = token::str_to_ident("principal_skinner");

        let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
            name: ident,
            attrs: Vec::new(),
            // making this up as I go.... ?
            data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
            disr_expr: None,
        });

        let varstr = variant_to_string(&var);
        assert_eq!(varstr, "principal_skinner");
    }

    #[test]
    fn test_signed_int_to_string() {
        let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
        let neg_int = ast::LitInt((!42 + 1) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
        assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
                   lit_to_string(&codemap::dummy_spanned(neg_int)));
    }
}