This file is indexed.

/usr/lib/python3/dist-packages/hy/compiler.py is in python3-hy 0.12.1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2013, 2014 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Julien Danjou <julien@danjou.info>
# Copyright (c) 2013 Nicolas Dandrimont <nicolas.dandrimont@crans.org>
# Copyright (c) 2013 James King <james@agentultra.com>
# Copyright (c) 2013, 2014 Bob Tolbert <bob@tolbert.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from hy.models.expression import HyExpression
from hy.models.keyword import HyKeyword
from hy.models.integer import HyInteger
from hy.models.complex import HyComplex
from hy.models.string import HyString
from hy.models.symbol import HySymbol
from hy.models.float import HyFloat
from hy.models.list import HyList
from hy.models.set import HySet
from hy.models.dict import HyDict
from hy.models.cons import HyCons

from hy.errors import HyCompileError, HyTypeError

from hy.lex.parser import hy_symbol_mangle

import hy.macros
from hy._compat import (
    str_type, long_type, PY27, PY33, PY3, PY34, PY35, raise_empty)
from hy.macros import require, macroexpand, reader_macroexpand
import hy.importer

import traceback
import importlib
import codecs
import ast
import sys
import keyword

from collections import defaultdict


_compile_time_ns = {}


def compile_time_ns(module_name):
    ns = _compile_time_ns.get(module_name)
    if ns is None:
        ns = {'hy': hy, '__name__': module_name}
        _compile_time_ns[module_name] = ns
    return ns


_stdlib = {}


def load_stdlib():
    import hy.core
    for module in hy.core.STDLIB:
        mod = importlib.import_module(module)
        for e in mod.EXPORTS:
            _stdlib[e] = module


# True, False and None included here since they
# are assignable in Python 2.* but become
# keywords in Python 3.*
def _is_hy_builtin(name, module_name):
    extras = ['True', 'False', 'None']
    if name in extras or keyword.iskeyword(name):
        return True
    # for non-Hy modules, check for pre-existing name in
    # _compile_table
    if not module_name.startswith("hy."):
        return name in _compile_table
    return False


_compile_table = {}


def ast_str(foobar):
    if PY3:
        return str(foobar)

    try:
        return str(foobar)
    except UnicodeEncodeError:
        pass

    enc = codecs.getencoder('punycode')
    foobar, _ = enc(foobar)
    return "hy_%s" % (str(foobar).replace("-", "_"))


def builds(_type):

    unpythonic_chars = ["-"]
    really_ok = ["-"]
    if any(x in unpythonic_chars for x in str_type(_type)):
        if _type not in really_ok:
            raise TypeError("Dear Hypster: `build' needs to be *post* "
                            "translated strings... `%s' sucks." % (_type))

    def _dec(fn):
        _compile_table[_type] = fn
        return fn
    return _dec


def builds_if(_type, condition):
    if condition:
        return builds(_type)
    else:
        return lambda fn: fn


class Result(object):
    """
    Smart representation of the result of a hy->AST compilation

    This object tries to reconcile the hy world, where everything can be used
    as an expression, with the Python world, where statements and expressions
    need to coexist.

    To do so, we represent a compiler result as a list of statements `stmts`,
    terminated by an expression context `expr`. The expression context is used
    when the compiler needs to use the result as an expression.

    Results are chained by addition: adding two results together returns a
    Result representing the succession of the two Results' statements, with
    the second Result's expression context.

    We make sure that a non-empty expression context does not get clobbered by
    adding more results, by checking accesses to the expression context. We
    assume that the context has been used, or deliberately ignored, if it has
    been accessed.

    The Result object is interoperable with python AST objects: when an AST
    object gets added to a Result object, it gets converted on-the-fly.
    """
    __slots__ = ("imports", "stmts", "temp_variables",
                 "_expr", "__used_expr", "contains_yield")

    def __init__(self, *args, **kwargs):
        if args:
            # emulate kw-only args for future bits.
            raise TypeError("Yo: Hacker: don't pass me real args, dingus")

        self.imports = defaultdict(set)
        self.stmts = []
        self.temp_variables = []
        self._expr = None
        self.contains_yield = False

        self.__used_expr = False

        # XXX: Make sure we only have AST where we should.
        for kwarg in kwargs:
            if kwarg not in ["imports", "contains_yield", "stmts", "expr",
                             "temp_variables"]:
                raise TypeError(
                    "%s() got an unexpected keyword argument '%s'" % (
                        self.__class__.__name__, kwarg))
            setattr(self, kwarg, kwargs[kwarg])

    @property
    def expr(self):
        self.__used_expr = True
        return self._expr

    @expr.setter
    def expr(self, value):
        self.__used_expr = False
        self._expr = value

    def add_imports(self, mod, imports):
        """Autoimport `imports` from `mod`"""
        self.imports[mod].update(imports)

    def is_expr(self):
        """Check whether I am a pure expression"""
        return self._expr and not (self.imports or self.stmts)

    @property
    def force_expr(self):
        """Force the expression context of the Result.

        If there is no expression context, we return a "None" expression.
        """
        if self.expr:
            return self.expr

        # Spoof the position of the last statement for our generated None
        lineno = 0
        col_offset = 0
        if self.stmts:
            lineno = self.stmts[-1].lineno
            col_offset = self.stmts[-1].col_offset

        return ast.Name(id=ast_str("None"),
                        arg=ast_str("None"),
                        ctx=ast.Load(),
                        lineno=lineno,
                        col_offset=col_offset)
        # XXX: Likely raise Exception here - this will assertionfail
        #      pypy since the ast will be out of numerical order.

    def expr_as_stmt(self):
        """Convert the Result's expression context to a statement

        This is useful when we want to use the stored expression in a
        statement context (for instance in a code branch).

        We drop ast.Names if they are appended to statements, as they
        can't have any side effect. "Bare" names still get converted to
        statements.

        If there is no expression context, return an empty result.
        """
        if self.expr and not (isinstance(self.expr, ast.Name) and self.stmts):
            return Result() + ast.Expr(lineno=self.expr.lineno,
                                       col_offset=self.expr.col_offset,
                                       value=self.expr)
        return Result()

    def rename(self, new_name):
        """Rename the Result's temporary variables to a `new_name`.

        We know how to handle ast.Names and ast.FunctionDefs.
        """
        new_name = ast_str(new_name)
        for var in self.temp_variables:
            if isinstance(var, ast.Name):
                var.id = new_name
                var.arg = new_name
            elif isinstance(var, ast.FunctionDef):
                var.name = new_name
            else:
                raise TypeError("Don't know how to rename a %s!" % (
                    var.__class__.__name__))
        self.temp_variables = []

    def __add__(self, other):
        # If we add an ast statement, convert it first
        if isinstance(other, ast.stmt):
            return self + Result(stmts=[other])

        # If we add an ast expression, clobber the expression context
        if isinstance(other, ast.expr):
            return self + Result(expr=other)

        if isinstance(other, ast.excepthandler):
            return self + Result(stmts=[other])

        if not isinstance(other, Result):
            raise TypeError("Can't add %r with non-compiler result %r" % (
                self, other))

        # Check for expression context clobbering
        if self.expr and not self.__used_expr:
            traceback.print_stack()
            print("Bad boy clobbered expr %s with %s" % (
                ast.dump(self.expr),
                ast.dump(other.expr)))

        # Fairly obvious addition
        result = Result()
        result.imports = other.imports
        result.stmts = self.stmts + other.stmts
        result.expr = other.expr
        result.temp_variables = other.temp_variables
        result.contains_yield = False
        if self.contains_yield or other.contains_yield:
            result.contains_yield = True

        return result

    def __str__(self):
        return (
            "Result(imports=[%s], stmts=[%s], "
            "expr=%s, contains_yield=%s)"
        ) % (
            ", ".join(ast.dump(x) for x in self.imports),
            ", ".join(ast.dump(x) for x in self.stmts),
            ast.dump(self.expr) if self.expr else None,
            self.contains_yield
        )


def _branch(results):
    """Make a branch out of a list of Result objects

    This generates a Result from the given sequence of Results, forcing each
    expression context as a statement before the next result is used.

    We keep the expression context of the last argument for the returned Result
    """
    results = list(results)
    ret = Result()
    for result in results[:-1]:
        ret += result
        ret += result.expr_as_stmt()

    for result in results[-1:]:
        ret += result

    return ret


def _raise_wrong_args_number(expression, error):
    raise HyTypeError(expression,
                      error % (expression.pop(0),
                               len(expression)))


def checkargs(exact=None, min=None, max=None, even=None, multiple=None):
    def _dec(fn):
        def checker(self, expression):
            if exact is not None and (len(expression) - 1) != exact:
                _raise_wrong_args_number(
                    expression, "`%%s' needs %d arguments, got %%d" % exact)
            if min is not None and (len(expression) - 1) < min:
                _raise_wrong_args_number(
                    expression,
                    "`%%s' needs at least %d arguments, got %%d." % (min))

            if max is not None and (len(expression) - 1) > max:
                _raise_wrong_args_number(
                    expression,
                    "`%%s' needs at most %d arguments, got %%d" % (max))

            is_even = not((len(expression) - 1) % 2)
            if even is not None and is_even != even:
                even_str = "even" if even else "odd"
                _raise_wrong_args_number(
                    expression,
                    "`%%s' needs an %s number of arguments, got %%d"
                    % (even_str))

            if multiple is not None:
                if not (len(expression) - 1) in multiple:
                    choices = ", ".join([str(val) for val in multiple[:-1]])
                    choices += " or %s" % multiple[-1]
                    _raise_wrong_args_number(
                        expression,
                        "`%%s' needs %s arguments, got %%d" % choices)

            return fn(self, expression)

        return checker
    return _dec


class HyASTCompiler(object):

    def __init__(self, module_name):
        self.allow_builtins = False
        self.anon_fn_count = 0
        self.anon_var_count = 0
        self.imports = defaultdict(set)
        self.module_name = module_name
        self.temp_if = None
        if not module_name.startswith("hy.core"):
            # everything in core needs to be explicit.
            load_stdlib()

    def get_anon_var(self):
        self.anon_var_count += 1
        return "_hy_anon_var_%s" % self.anon_var_count

    def get_anon_fn(self):
        self.anon_fn_count += 1
        return "_hy_anon_fn_%d" % self.anon_fn_count

    def update_imports(self, result):
        """Retrieve the imports from the result object"""
        for mod in result.imports:
            self.imports[mod].update(result.imports[mod])

    def imports_as_stmts(self, expr):
        """Convert the Result's imports to statements"""
        ret = Result()
        for module, names in self.imports.items():
            if None in names:
                ret += self.compile([
                    HyExpression([
                        HySymbol("import"),
                        HySymbol(module),
                    ]).replace(expr)
                ])
            names = sorted(name for name in names if name)
            if names:
                ret += self.compile([
                    HyExpression([
                        HySymbol("import"),
                        HyList([
                            HySymbol(module),
                            HyList([HySymbol(name) for name in names])
                        ])
                    ]).replace(expr)
                ])
        self.imports = defaultdict(set)
        return ret.stmts

    def compile_atom(self, atom_type, atom):
        if atom_type in _compile_table:
            ret = _compile_table[atom_type](self, atom)
            if not isinstance(ret, Result):
                ret = Result() + ret
            return ret

    def compile(self, tree):
        try:
            _type = type(tree)
            ret = self.compile_atom(_type, tree)
            if ret:
                self.update_imports(ret)
                return ret
        except HyCompileError:
            # compile calls compile, so we're going to have multiple raise
            # nested; so let's re-raise this exception, let's not wrap it in
            # another HyCompileError!
            raise
        except HyTypeError as e:
            raise
        except Exception as e:
            raise_empty(HyCompileError, e, sys.exc_info()[2])

        raise HyCompileError(Exception("Unknown type: `%s'" % _type))

    def _compile_collect(self, exprs, with_kwargs=False):
        """Collect the expression contexts from a list of compiled expression.

        This returns a list of the expression contexts, and the sum of the
        Result objects passed as arguments.

        """
        compiled_exprs = []
        ret = Result()
        keywords = []

        exprs_iter = iter(exprs)
        for expr in exprs_iter:
            if with_kwargs and isinstance(expr, HyKeyword):
                try:
                    value = next(exprs_iter)
                except StopIteration:
                    raise HyTypeError(expr,
                                      "Keyword argument {kw} needs "
                                      "a value.".format(kw=str(expr[1:])))

                compiled_value = self.compile(value)
                ret += compiled_value

                # no unicode for py2 in ast names
                keyword = str(expr[2:])
                if "-" in keyword and keyword != "-":
                    keyword = keyword.replace("-", "_")

                keywords.append(ast.keyword(arg=keyword,
                                            value=compiled_value.force_expr,
                                            lineno=expr.start_line,
                                            col_offset=expr.start_column))
            else:
                ret += self.compile(expr)
                compiled_exprs.append(ret.force_expr)

        return compiled_exprs, ret, keywords

    def _compile_branch(self, exprs):
        return _branch(self.compile(expr) for expr in exprs)

    def _parse_lambda_list(self, exprs):
        """ Return FunctionDef parameter values from lambda list."""
        ll_keywords = ("&rest", "&optional", "&key", "&kwonly", "&kwargs")
        ret = Result()
        args = []
        defaults = []
        varargs = None
        kwonlyargs = []
        kwonlydefaults = []
        kwargs = None
        lambda_keyword = None

        for expr in exprs:

            if expr in ll_keywords:
                if expr == "&optional":
                    if len(defaults) > 0:
                        raise HyTypeError(expr,
                                          "There can only be &optional "
                                          "arguments or one &key argument")
                    lambda_keyword = expr
                elif expr in ("&rest", "&key", "&kwonly", "&kwargs"):
                    lambda_keyword = expr
                else:
                    raise HyTypeError(expr,
                                      "{0} is in an invalid "
                                      "position.".format(repr(expr)))
                # we don't actually care about this token, so we set
                # our state and continue to the next token...
                continue

            if lambda_keyword is None:
                args.append(expr)
            elif lambda_keyword == "&rest":
                if varargs:
                    raise HyTypeError(expr,
                                      "There can only be one "
                                      "&rest argument")
                varargs = expr
            elif lambda_keyword == "&key":
                if type(expr) != HyDict:
                    raise HyTypeError(expr,
                                      "There can only be one &key "
                                      "argument")
                else:
                    if len(defaults) > 0:
                        raise HyTypeError(expr,
                                          "There can only be &optional "
                                          "arguments or one &key argument")
                    # As you can see, Python has a funny way of
                    # defining keyword arguments.
                    it = iter(expr)
                    for k, v in zip(it, it):
                        if not isinstance(k, HyString):
                            raise HyTypeError(expr,
                                              "Only strings can be used "
                                              "as parameter names")
                        args.append(k)
                        ret += self.compile(v)
                        defaults.append(ret.force_expr)
            elif lambda_keyword == "&optional":
                if isinstance(expr, HyList):
                    if not len(expr) == 2:
                        raise HyTypeError(expr,
                                          "optional args should be bare names "
                                          "or 2-item lists")
                    k, v = expr
                else:
                    k = expr
                    v = HySymbol("None").replace(k)
                if not isinstance(k, HyString):
                    raise HyTypeError(expr,
                                      "Only strings can be used as "
                                      "parameter names")
                args.append(k)
                ret += self.compile(v)
                defaults.append(ret.force_expr)
            elif lambda_keyword == "&kwonly":
                if not PY3:
                    raise HyTypeError(expr,
                                      "keyword-only arguments are only "
                                      "available under Python 3")
                if isinstance(expr, HyList):
                    if len(expr) != 2:
                        raise HyTypeError(expr,
                                          "keyword-only args should be bare "
                                          "names or 2-item lists")
                    k, v = expr
                    kwonlyargs.append(k)
                    ret += self.compile(v)
                    kwonlydefaults.append(ret.force_expr)
                else:
                    k = expr
                    kwonlyargs.append(k)
                    kwonlydefaults.append(None)
            elif lambda_keyword == "&kwargs":
                if kwargs:
                    raise HyTypeError(expr,
                                      "There can only be one "
                                      "&kwargs argument")
                kwargs = expr

        return ret, args, defaults, varargs, kwonlyargs, kwonlydefaults, kwargs

    def _storeize(self, expr, name, func=None):
        """Return a new `name` object with an ast.Store() context"""
        if not func:
            func = ast.Store

        if isinstance(name, Result):
            if not name.is_expr():
                raise HyTypeError(expr,
                                  "Can't assign or delete a non-expression")
            name = name.expr

        if isinstance(name, (ast.Tuple, ast.List)):
            typ = type(name)
            new_elts = []
            for x in name.elts:
                new_elts.append(self._storeize(expr, x, func))
            new_name = typ(elts=new_elts)
        elif isinstance(name, ast.Name):
            new_name = ast.Name(id=name.id, arg=name.arg)
        elif isinstance(name, ast.Subscript):
            new_name = ast.Subscript(value=name.value, slice=name.slice)
        elif isinstance(name, ast.Attribute):
            new_name = ast.Attribute(value=name.value, attr=name.attr)
        else:
            raise HyTypeError(expr,
                              "Can't assign or delete a %s" %
                              type(expr).__name__)

        new_name.ctx = func()
        ast.copy_location(new_name, name)
        return new_name

    @builds(list)
    def compile_raw_list(self, entries):
        ret = self._compile_branch(entries)
        ret += ret.expr_as_stmt()
        return ret

    def _render_quoted_form(self, form, level):
        """
        Render a quoted form as a new HyExpression.

        `level` is the level of quasiquoting of the current form. We can
        unquote if level is 0.

        Returns a three-tuple (`imports`, `expression`, `splice`).

        The `splice` return value is used to mark `unquote-splice`d forms.
        We need to distinguish them as want to concatenate them instead of
        just nesting them.
        """
        if level == 0:
            if isinstance(form, HyExpression):
                if form and form[0] in ("unquote", "unquote_splice"):
                    if len(form) != 2:
                        raise HyTypeError(form,
                                          ("`%s' needs 1 argument, got %s" %
                                           form[0], len(form) - 1))
                    return set(), form[1], (form[0] == "unquote_splice")

        if isinstance(form, HyExpression):
            if form and form[0] == "quasiquote":
                level += 1
            if form and form[0] in ("unquote", "unquote_splice"):
                level -= 1

        name = form.__class__.__name__
        imports = set([name])

        if isinstance(form, (HyList, HyDict, HySet)):
            if not form:
                contents = HyList()
            else:
                # If there are arguments, they can be spliced
                # so we build a sum...
                contents = HyExpression([HySymbol("+"), HyList()])

            for x in form:
                f_imports, f_contents, splice = self._render_quoted_form(x,
                                                                         level)
                imports.update(f_imports)
                if splice:
                    to_add = HyExpression([HySymbol("list"), f_contents])
                else:
                    to_add = HyList([f_contents])

                contents.append(to_add)

            return imports, HyExpression([HySymbol(name),
                                          contents]).replace(form), False

        elif isinstance(form, HyCons):
            ret = HyExpression([HySymbol(name)])
            nimport, contents, splice = self._render_quoted_form(form.car,
                                                                 level)
            if splice:
                raise HyTypeError(form, "Can't splice dotted lists yet")
            imports.update(nimport)
            ret.append(contents)

            nimport, contents, splice = self._render_quoted_form(form.cdr,
                                                                 level)
            if splice:
                raise HyTypeError(form, "Can't splice the cdr of a cons")
            imports.update(nimport)
            ret.append(contents)

            return imports, ret.replace(form), False

        elif isinstance(form, HySymbol):
            return imports, HyExpression([HySymbol(name),
                                          HyString(form)]).replace(form), False

        return imports, HyExpression([HySymbol(name),
                                      form]).replace(form), False

    @builds("quote")
    @builds("quasiquote")
    @checkargs(exact=1)
    def compile_quote(self, entries):
        if entries[0] == "quote":
            # Never allow unquoting
            level = float("inf")
        else:
            level = 0
        imports, stmts, splice = self._render_quoted_form(entries[1], level)
        ret = self.compile(stmts)
        ret.add_imports("hy", imports)
        return ret

    @builds("unquote")
    @builds("unquote_splicing")
    def compile_unquote(self, expr):
        raise HyTypeError(expr,
                          "`%s' can't be used at the top-level" % expr[0])

    @builds("eval")
    @checkargs(min=1, max=3)
    def compile_eval(self, expr):
        expr.pop(0)

        if not isinstance(expr[0], (HyExpression, HySymbol)):
            raise HyTypeError(expr, "expression expected as first argument")

        elist = [HySymbol("hy_eval")] + [expr[0]]
        if len(expr) >= 2:
            elist.append(expr[1])
        else:
            elist.append(HyExpression([HySymbol("locals")]))

        if len(expr) == 3:
            elist.append(expr[2])
        else:
            elist.append(HyString(self.module_name))

        ret = self.compile(HyExpression(elist).replace(expr))

        ret.add_imports("hy.importer", ["hy_eval"])

        return ret

    @builds("do")
    def compile_do(self, expression):
        expression.pop(0)
        return self._compile_branch(expression)

    @builds("raise")
    @checkargs(multiple=[0, 1, 3])
    def compile_raise_expression(self, expr):
        expr.pop(0)
        ret = Result()
        if expr:
            ret += self.compile(expr.pop(0))

        cause = None
        if len(expr) == 2 and expr[0] == HyKeyword(":from"):
            if not PY3:
                raise HyCompileError(
                    "raise from only supported in python 3")
            expr.pop(0)
            cause = self.compile(expr.pop(0))
            cause = cause.expr

        # Use ret.expr to get a literal `None`
        ret += ast.Raise(
            lineno=expr.start_line,
            col_offset=expr.start_column,
            type=ret.expr,
            exc=ret.expr,
            inst=None,
            tback=None,
            cause=cause)

        return ret

    @builds("try")
    def compile_try_expression(self, expr):
        expr.pop(0)  # try

        try:
            body = expr.pop(0)
        except IndexError:
            body = []

        # (try something…)
        body = self.compile(body)

        var = self.get_anon_var()
        name = ast.Name(id=ast_str(var), arg=ast_str(var),
                        ctx=ast.Store(),
                        lineno=expr.start_line,
                        col_offset=expr.start_column)

        expr_name = ast.Name(id=ast_str(var), arg=ast_str(var),
                             ctx=ast.Load(),
                             lineno=expr.start_line,
                             col_offset=expr.start_column)

        returnable = Result(expr=expr_name, temp_variables=[expr_name, name],
                            contains_yield=body.contains_yield)

        body += ast.Assign(targets=[name],
                           value=body.force_expr,
                           lineno=expr.start_line,
                           col_offset=expr.start_column)

        body = body.stmts
        if not body:
            body = [ast.Pass(lineno=expr.start_line,
                             col_offset=expr.start_column)]

        orelse = []
        finalbody = []
        handlers = []
        handler_results = Result()

        for e in expr:
            if not len(e):
                raise HyTypeError(e, "Empty list not allowed in `try'")

            if e[0] == HySymbol("except"):
                handler_results += self._compile_catch_expression(e, name)
                handlers.append(handler_results.stmts.pop())
            elif e[0] == HySymbol("else"):
                orelse = self.try_except_helper(e, HySymbol("else"), orelse)
            elif e[0] == HySymbol("finally"):
                finalbody = self.try_except_helper(e, HySymbol("finally"),
                                                   finalbody)
            else:
                raise HyTypeError(e, "Unknown expression in `try'")

        # Using (else) without (except) is verboten!
        if orelse and not handlers:
            raise HyTypeError(
                e,
                "`try' cannot have `else' without `except'")

        # (try) or (try BODY)
        # Generate a default handler for Python >= 3.3 and pypy
        if not handlers and not finalbody and not orelse:
            handlers = [ast.ExceptHandler(
                lineno=expr.start_line,
                col_offset=expr.start_column,
                type=None,
                name=None,
                body=[ast.Raise(lineno=expr.start_line,
                                col_offset=expr.start_column)])]

        ret = handler_results

        if PY33:
            # Python 3.3 features a merge of TryExcept+TryFinally into Try.
            return ret + ast.Try(
                lineno=expr.start_line,
                col_offset=expr.start_column,
                body=body,
                handlers=handlers,
                orelse=orelse,
                finalbody=finalbody) + returnable

        if finalbody:
            if handlers:
                return ret + ast.TryFinally(
                    lineno=expr.start_line,
                    col_offset=expr.start_column,
                    body=[ast.TryExcept(
                        lineno=expr.start_line,
                        col_offset=expr.start_column,
                        handlers=handlers,
                        body=body,
                        orelse=orelse)],
                    finalbody=finalbody) + returnable

            return ret + ast.TryFinally(
                lineno=expr.start_line,
                col_offset=expr.start_column,
                body=body,
                finalbody=finalbody) + returnable

        return ret + ast.TryExcept(
            lineno=expr.start_line,
            col_offset=expr.start_column,
            handlers=handlers,
            body=body,
            orelse=orelse) + returnable

    def try_except_helper(self, hy_obj, symbol, accumulated):
        if accumulated:
            raise HyTypeError(
                hy_obj,
                "`try' cannot have more than one `%s'" % symbol)
        else:
            accumulated = self._compile_branch(hy_obj[1:])
            accumulated += accumulated.expr_as_stmt()
            accumulated = accumulated.stmts
        return accumulated

    @builds("except")
    def magic_internal_form(self, expr):
        raise HyTypeError(expr,
                          "Error: `%s' can't be used like that." % (expr[0]))

    def _compile_catch_expression(self, expr, var):
        catch = expr.pop(0)  # catch

        try:
            exceptions = expr.pop(0)
        except IndexError:
            exceptions = HyList()

        # exceptions catch should be either:
        # [[list of exceptions]]
        # or
        # [variable [list of exceptions]]
        # or
        # [variable exception]
        # or
        # [exception]
        # or
        # []

        if not isinstance(exceptions, HyList):
            raise HyTypeError(exceptions,
                              "`%s' exceptions list is not a list" % catch)
        if len(exceptions) > 2:
            raise HyTypeError(exceptions,
                              "`%s' exceptions list is too long" % catch)

        # [variable [list of exceptions]]
        # let's pop variable and use it as name
        if len(exceptions) == 2:
            name = exceptions.pop(0)
            if not isinstance(name, HySymbol):
                raise HyTypeError(
                    exceptions,
                    "Exception storage target name must be a symbol.")

            if PY3:
                # Python3 features a change where the Exception handler
                # moved the name from a Name() to a pure Python String type.
                #
                # We'll just make sure it's a pure "string", and let it work
                # it's magic.
                name = ast_str(name)
            else:
                # Python2 requires an ast.Name, set to ctx Store.
                name = self._storeize(name, self.compile(name))
        else:
            name = None

        try:
            exceptions_list = exceptions.pop(0)
        except IndexError:
            exceptions_list = []

        if isinstance(exceptions_list, list):
            if len(exceptions_list):
                # [FooBar BarFoo] → catch Foobar and BarFoo exceptions
                elts, _type, _ = self._compile_collect(exceptions_list)
                _type += ast.Tuple(elts=elts,
                                   lineno=expr.start_line,
                                   col_offset=expr.start_column,
                                   ctx=ast.Load())
            else:
                # [] → all exceptions caught
                _type = Result()
        elif isinstance(exceptions_list, HySymbol):
            _type = self.compile(exceptions_list)
        else:
            raise HyTypeError(exceptions,
                              "`%s' needs a valid exception list" % catch)

        body = self._compile_branch(expr)
        body += ast.Assign(targets=[var],
                           value=body.force_expr,
                           lineno=expr.start_line,
                           col_offset=expr.start_column)
        body += body.expr_as_stmt()

        body = body.stmts
        if not body:
            body = [ast.Pass(lineno=expr.start_line,
                             col_offset=expr.start_column)]

        # use _type.expr to get a literal `None`
        return _type + ast.ExceptHandler(
            lineno=expr.start_line,
            col_offset=expr.start_column,
            type=_type.expr,
            name=name,
            body=body)

    @builds("if*")
    @checkargs(min=2, max=3)
    def compile_if(self, expression):
        expression.pop(0)
        cond = self.compile(expression.pop(0))
        body = self.compile(expression.pop(0))

        orel = Result()
        nested = root = False
        if expression:
            orel_expr = expression.pop(0)
            if isinstance(orel_expr, HyExpression) and isinstance(orel_expr[0],
               HySymbol) and orel_expr[0] == 'if*':
                # Nested ifs: don't waste temporaries
                root = self.temp_if is None
                nested = True
                self.temp_if = self.temp_if or self.get_anon_var()
            orel = self.compile(orel_expr)

        if not cond.stmts and isinstance(cond.force_expr, ast.Name):
            name = cond.force_expr.id
            branch = None
            if name == 'True':
                branch = body
            elif name in ('False', 'None'):
                branch = orel
            if branch is not None:
                if self.temp_if and branch.stmts:
                    name = ast.Name(id=ast_str(self.temp_if),
                                    arg=ast_str(self.temp_if),
                                    ctx=ast.Store(),
                                    lineno=expression.start_line,
                                    col_offset=expression.start_column)

                    branch += ast.Assign(targets=[name],
                                         value=body.force_expr,
                                         lineno=expression.start_line,
                                         col_offset=expression.start_column)

                return branch

        # We want to hoist the statements from the condition
        ret = cond

        if body.stmts or orel.stmts:
            # We have statements in our bodies
            # Get a temporary variable for the result storage
            var = self.temp_if or self.get_anon_var()
            name = ast.Name(id=ast_str(var), arg=ast_str(var),
                            ctx=ast.Store(),
                            lineno=expression.start_line,
                            col_offset=expression.start_column)

            # Store the result of the body
            body += ast.Assign(targets=[name],
                               value=body.force_expr,
                               lineno=expression.start_line,
                               col_offset=expression.start_column)

            # and of the else clause
            if not nested or not orel.stmts or (not root and
               var != self.temp_if):
                orel += ast.Assign(targets=[name],
                                   value=orel.force_expr,
                                   lineno=expression.start_line,
                                   col_offset=expression.start_column)

            # Then build the if
            ret += ast.If(test=ret.force_expr,
                          body=body.stmts,
                          orelse=orel.stmts,
                          lineno=expression.start_line,
                          col_offset=expression.start_column)

            # And make our expression context our temp variable
            expr_name = ast.Name(id=ast_str(var), arg=ast_str(var),
                                 ctx=ast.Load(),
                                 lineno=expression.start_line,
                                 col_offset=expression.start_column)

            ret += Result(expr=expr_name, temp_variables=[expr_name, name])
        else:
            # Just make that an if expression
            ret += ast.IfExp(test=ret.force_expr,
                             body=body.force_expr,
                             orelse=orel.force_expr,
                             lineno=expression.start_line,
                             col_offset=expression.start_column)

        if root:
            self.temp_if = None

        return ret

    @builds("break")
    def compile_break_expression(self, expr):
        ret = ast.Break(lineno=expr.start_line,
                        col_offset=expr.start_column)

        return ret

    @builds("continue")
    def compile_continue_expression(self, expr):
        ret = ast.Continue(lineno=expr.start_line,
                           col_offset=expr.start_column)

        return ret

    @builds("assert")
    @checkargs(min=1, max=2)
    def compile_assert_expression(self, expr):
        expr.pop(0)  # assert
        e = expr.pop(0)
        if len(expr) == 1:
            msg = self.compile(expr.pop(0)).force_expr
        else:
            msg = None
        ret = self.compile(e)
        ret += ast.Assert(test=ret.force_expr,
                          msg=msg,
                          lineno=e.start_line,
                          col_offset=e.start_column)

        return ret

    @builds("global")
    @checkargs(min=1)
    def compile_global_expression(self, expr):
        expr.pop(0)  # global
        names = []
        while len(expr) > 0:
            identifier = expr.pop(0)
            name = ast_str(identifier)
            names.append(name)
            if not isinstance(identifier, HySymbol):
                raise HyTypeError(identifier, "(global) arguments must "
                                  " be Symbols")

        return ast.Global(names=names,
                          lineno=expr.start_line,
                          col_offset=expr.start_column)

    @builds("nonlocal")
    @checkargs(min=1)
    def compile_nonlocal_expression(self, expr):
        if not PY3:
            raise HyCompileError(
                "nonlocal only supported in python 3!")

        expr.pop(0)  # nonlocal
        names = []
        while len(expr) > 0:
            identifier = expr.pop(0)
            name = ast_str(identifier)
            names.append(name)
            if not isinstance(identifier, HySymbol):
                raise HyTypeError(identifier, "(nonlocal) arguments must "
                                  "be Symbols.")

        return ast.Nonlocal(names=names,
                            lineno=expr.start_line,
                            col_offset=expr.start_column)

    @builds("yield")
    @checkargs(max=1)
    def compile_yield_expression(self, expr):
        expr.pop(0)
        if PY33:
            ret = Result(contains_yield=False)
        else:
            ret = Result(contains_yield=True)

        value = None
        if expr != []:
            ret += self.compile(expr.pop(0))
            value = ret.force_expr

        ret += ast.Yield(
            value=value,
            lineno=expr.start_line,
            col_offset=expr.start_column)

        return ret

    @builds("yield_from")
    @checkargs(max=1)
    def compile_yield_from_expression(self, expr):
        if not PY33:
            raise HyCompileError(
                "yield-from only supported in python 3.3+!")

        expr.pop(0)
        ret = Result(contains_yield=True)

        value = None
        if expr != []:
            ret += self.compile(expr.pop(0))
            value = ret.force_expr

        ret += ast.YieldFrom(
            value=value,
            lineno=expr.start_line,
            col_offset=expr.start_column)

        return ret

    @builds("import")
    def compile_import_expression(self, expr):
        def _compile_import(expr, module, names=None, importer=ast.Import):
            if not names:
                names = [ast.alias(name=ast_str(module), asname=None)]
            ret = importer(lineno=expr.start_line,
                           col_offset=expr.start_column,
                           module=ast_str(module),
                           names=names,
                           level=0)
            return Result() + ret

        expr.pop(0)  # index
        rimports = Result()
        while len(expr) > 0:
            iexpr = expr.pop(0)

            if not isinstance(iexpr, (HySymbol, HyList)):
                raise HyTypeError(iexpr, "(import) requires a Symbol "
                                  "or a List.")

            if isinstance(iexpr, HySymbol):
                rimports += _compile_import(expr, iexpr)
                continue

            if isinstance(iexpr, HyList) and len(iexpr) == 1:
                rimports += _compile_import(expr, iexpr.pop(0))
                continue

            if isinstance(iexpr, HyList) and iexpr:
                module = iexpr.pop(0)
                entry = iexpr[0]
                if isinstance(entry, HyKeyword) and entry == HyKeyword(":as"):
                    if not len(iexpr) == 2:
                        raise HyTypeError(iexpr,
                                          "garbage after aliased import")
                    iexpr.pop(0)  # :as
                    alias = iexpr.pop(0)
                    names = [ast.alias(name=ast_str(module),
                                       asname=ast_str(alias))]
                    rimports += _compile_import(expr, ast_str(module), names)
                    continue

                if isinstance(entry, HyList):
                    names = []
                    while entry:
                        sym = entry.pop(0)
                        if entry and isinstance(entry[0], HyKeyword):
                            entry.pop(0)
                            alias = ast_str(entry.pop(0))
                        else:
                            alias = None
                        names.append(ast.alias(name=ast_str(sym),
                                               asname=alias))

                    rimports += _compile_import(expr, module,
                                                names, ast.ImportFrom)
                    continue

                raise HyTypeError(
                    entry,
                    "Unknown entry (`%s`) in the HyList" % (entry)
                )

        return rimports

    @builds("get")
    @checkargs(min=2)
    def compile_index_expression(self, expr):
        expr.pop(0)  # index

        val = self.compile(expr.pop(0))
        slices, ret, _ = self._compile_collect(expr)

        if val.stmts:
            ret += val

        for sli in slices:
            val = Result() + ast.Subscript(
                lineno=expr.start_line,
                col_offset=expr.start_column,
                value=val.force_expr,
                slice=ast.Index(value=sli),
                ctx=ast.Load())

        return ret + val

    @builds(".")
    @checkargs(min=1)
    def compile_attribute_access(self, expr):
        expr.pop(0)  # dot

        ret = self.compile(expr.pop(0))

        for attr in expr:
            if isinstance(attr, HySymbol):
                ret += ast.Attribute(lineno=attr.start_line,
                                     col_offset=attr.start_column,
                                     value=ret.force_expr,
                                     attr=ast_str(attr),
                                     ctx=ast.Load())
            elif type(attr) == HyList:
                if len(attr) != 1:
                    raise HyTypeError(
                        attr,
                        "The attribute access DSL only accepts HySymbols "
                        "and one-item lists, got {0}-item list instead".format(
                            len(attr),
                        ),
                    )
                compiled_attr = self.compile(attr.pop(0))
                ret = compiled_attr + ret + ast.Subscript(
                    lineno=attr.start_line,
                    col_offset=attr.start_column,
                    value=ret.force_expr,
                    slice=ast.Index(value=compiled_attr.force_expr),
                    ctx=ast.Load())
            else:
                raise HyTypeError(
                    attr,
                    "The attribute access DSL only accepts HySymbols "
                    "and one-item lists, got {0} instead".format(
                        type(attr).__name__,
                    ),
                )

        return ret

    @builds("del")
    def compile_del_expression(self, expr):
        root = expr.pop(0)
        if not expr:
            result = Result()
            result += ast.Name(id='None', ctx=ast.Load(),
                               lineno=root.start_line,
                               col_offset=root.start_column)
            return result

        del_targets = []
        ret = Result()
        for target in expr:
            compiled_target = self.compile(target)
            ret += compiled_target
            del_targets.append(self._storeize(target, compiled_target,
                                              ast.Del))

        return ret + ast.Delete(
            lineno=expr.start_line,
            col_offset=expr.start_column,
            targets=del_targets)

    @builds("cut")
    @checkargs(min=1, max=4)
    def compile_cut_expression(self, expr):
        expr.pop(0)  # index
        val = self.compile(expr.pop(0))  # target

        low = Result()
        if expr != []:
            low = self.compile(expr.pop(0))

        high = Result()
        if expr != []:
            high = self.compile(expr.pop(0))

        step = Result()
        if expr != []:
            step = self.compile(expr.pop(0))

        # use low.expr, high.expr and step.expr to use a literal `None`.
        return val + low + high + step + ast.Subscript(
            lineno=expr.start_line,
            col_offset=expr.start_column,
            value=val.force_expr,
            slice=ast.Slice(lower=low.expr,
                            upper=high.expr,
                            step=step.expr),
            ctx=ast.Load())

    @builds("assoc")
    @checkargs(min=3, even=False)
    def compile_assoc_expression(self, expr):
        expr.pop(0)  # assoc
        # (assoc foo bar baz)  => foo[bar] = baz
        target = self.compile(expr.pop(0))
        ret = target
        i = iter(expr)
        for (key, val) in ((self.compile(x), self.compile(y))
                           for (x, y) in zip(i, i)):

            ret += key + val + ast.Assign(
                lineno=expr.start_line,
                col_offset=expr.start_column,
                targets=[
                    ast.Subscript(
                        lineno=expr.start_line,
                        col_offset=expr.start_column,
                        value=target.force_expr,
                        slice=ast.Index(value=key.force_expr),
                        ctx=ast.Store())],
                value=val.force_expr)
        return ret

    @builds("with_decorator")
    @checkargs(min=1)
    def compile_decorate_expression(self, expr):
        expr.pop(0)  # with-decorator
        fn = self.compile(expr.pop(-1))
        if not fn.stmts or not (isinstance(fn.stmts[-1], ast.FunctionDef) or
                                isinstance(fn.stmts[-1], ast.ClassDef)):
            raise HyTypeError(expr, "Decorated a non-function")
        decorators, ret, _ = self._compile_collect(expr)
        fn.stmts[-1].decorator_list = decorators + fn.stmts[-1].decorator_list
        return ret + fn

    @builds("with*")
    @checkargs(min=2)
    def compile_with_expression(self, expr):
        expr.pop(0)  # with*

        args = expr.pop(0)
        if not isinstance(args, HyList):
            raise HyTypeError(expr,
                              "with expects a list, received `{0}'".format(
                                  type(args).__name__))
        if len(args) < 1:
            raise HyTypeError(expr, "with needs [[arg (expr)]] or [[(expr)]]]")

        args.reverse()
        ctx = self.compile(args.pop(0))

        thing = None
        if args != []:
            thing = self._storeize(args[0], self.compile(args.pop(0)))

        body = self._compile_branch(expr)

        var = self.get_anon_var()
        name = ast.Name(id=ast_str(var), arg=ast_str(var),
                        ctx=ast.Store(),
                        lineno=expr.start_line,
                        col_offset=expr.start_column)

        # Store the result of the body in a tempvar
        body += ast.Assign(targets=[name],
                           value=body.force_expr,
                           lineno=expr.start_line,
                           col_offset=expr.start_column)

        the_with = ast.With(context_expr=ctx.force_expr,
                            lineno=expr.start_line,
                            col_offset=expr.start_column,
                            optional_vars=thing,
                            body=body.stmts)

        if PY33:
            the_with.items = [ast.withitem(context_expr=ctx.force_expr,
                                           optional_vars=thing)]

        ret = ctx + the_with
        # And make our expression context our temp variable
        expr_name = ast.Name(id=ast_str(var), arg=ast_str(var),
                             ctx=ast.Load(),
                             lineno=expr.start_line,
                             col_offset=expr.start_column)

        ret += Result(expr=expr_name, temp_variables=[expr_name, name])

        return ret

    @builds(",")
    def compile_tuple(self, expr):
        expr.pop(0)
        elts, ret, _ = self._compile_collect(expr)
        ret += ast.Tuple(elts=elts,
                         lineno=expr.start_line,
                         col_offset=expr.start_column,
                         ctx=ast.Load())
        return ret

    def _compile_generator_iterables(self, trailers):
        """Helper to compile the "trailing" parts of comprehensions:
        generators and conditions"""

        generators = trailers.pop(0)

        cond = self.compile(trailers.pop(0)) if trailers != [] else Result()

        gen_it = iter(generators)
        paired_gens = zip(gen_it, gen_it)

        gen_res = Result()
        gen = []
        for target, iterable in paired_gens:
            comp_target = self.compile(target)
            target = self._storeize(target, comp_target)
            gen_res += self.compile(iterable)
            gen.append(ast.comprehension(
                target=target,
                iter=gen_res.force_expr,
                ifs=[],
                is_async=False))

        if cond.expr:
            gen[-1].ifs.append(cond.expr)

        return gen_res + cond, gen

    @builds("list_comp")
    @checkargs(min=2, max=3)
    def compile_list_comprehension(self, expr):
        # (list-comp expr (target iter) cond?)
        expr.pop(0)
        expression = expr.pop(0)
        gen_gen = expr[0]

        if not isinstance(gen_gen, HyList):
            raise HyTypeError(gen_gen, "Generator expression must be a list.")

        gen_res, gen = self._compile_generator_iterables(expr)

        if len(gen) == 0:
            raise HyTypeError(gen_gen, "Generator expression cannot be empty.")

        compiled_expression = self.compile(expression)
        ret = compiled_expression + gen_res
        ret += ast.ListComp(
            lineno=expr.start_line,
            col_offset=expr.start_column,
            elt=compiled_expression.force_expr,
            generators=gen)

        return ret

    @builds("set_comp")
    @checkargs(min=2, max=3)
    def compile_set_comprehension(self, expr):
        if PY27:
            ret = self.compile_list_comprehension(expr)
            expr = ret.expr
            ret.expr = ast.SetComp(
                lineno=expr.lineno,
                col_offset=expr.col_offset,
                elt=expr.elt,
                generators=expr.generators)

            return ret

        expr[0] = HySymbol("list_comp").replace(expr[0])
        expr = HyExpression([HySymbol("set"), expr]).replace(expr)
        return self.compile(expr)

    @builds("dict_comp")
    @checkargs(min=3, max=4)
    def compile_dict_comprehension(self, expr):
        if PY27:
            expr.pop(0)  # dict-comp
            key = expr.pop(0)
            value = expr.pop(0)

            gen_res, gen = self._compile_generator_iterables(expr)

            compiled_key = self.compile(key)
            compiled_value = self.compile(value)
            ret = compiled_key + compiled_value + gen_res
            ret += ast.DictComp(
                lineno=expr.start_line,
                col_offset=expr.start_column,
                key=compiled_key.force_expr,
                value=compiled_value.force_expr,
                generators=gen)

            return ret

        # In Python 2.6, turn (dict-comp key value [foo]) into
        # (dict (list-comp (, key value) [foo]))

        expr[0] = HySymbol("list_comp").replace(expr[0])
        expr[1:3] = [HyExpression(
            [HySymbol(",")] +
            expr[1:3]
        ).replace(expr[1])]
        expr = HyExpression([HySymbol("dict"), expr]).replace(expr)
        return self.compile(expr)

    @builds("genexpr")
    def compile_genexpr(self, expr):
        ret = self.compile_list_comprehension(expr)
        expr = ret.expr
        ret.expr = ast.GeneratorExp(
            lineno=expr.lineno,
            col_offset=expr.col_offset,
            elt=expr.elt,
            generators=expr.generators)
        return ret

    @builds("apply")
    @checkargs(min=1, max=3)
    def compile_apply_expression(self, expr):
        expr.pop(0)  # apply

        ret = Result()

        fun = expr.pop(0)

        # We actually defer the compilation of the function call to
        # @builds(HyExpression), allowing us to work on method calls
        call = HyExpression([fun]).replace(fun)

        if isinstance(fun, HySymbol) and fun.startswith("."):
            # (apply .foo lst) needs to work as lst[0].foo(*lst[1:])
            if not expr:
                raise HyTypeError(
                    expr, "apply of a method needs to have an argument"
                )

            # We need to grab the arguments, and split them.

            # Assign them to a variable if they're not one already
            if type(expr[0]) == HyList:
                if len(expr[0]) == 0:
                    raise HyTypeError(
                        expr, "apply of a method needs to have an argument"
                    )
                call.append(expr[0].pop(0))
            else:
                if isinstance(expr[0], HySymbol):
                    tempvar = expr[0]
                else:
                    tempvar = HySymbol(self.get_anon_var()).replace(expr[0])
                    assignment = HyExpression(
                        [HySymbol("setv"), tempvar, expr[0]]
                    ).replace(expr[0])

                    # and add the assignment to our result
                    ret += self.compile(assignment)

                # The first argument is the object on which to call the method
                # So we translate (apply .foo args) to (.foo (get args 0))
                call.append(HyExpression(
                    [HySymbol("get"), tempvar, HyInteger(0)]
                ).replace(tempvar))

                # We then pass the other arguments to the function
                expr[0] = HyExpression(
                    [HySymbol("cut"), tempvar, HyInteger(1)]
                ).replace(expr[0])

        ret += self.compile(call)

        if not isinstance(ret.expr, ast.Call):
            raise HyTypeError(
                fun, "compiling the application of `{}' didn't return a "
                "function call, but `{}'".format(fun, type(ret.expr).__name__)
            )
        if ret.expr.starargs or ret.expr.kwargs:
            raise HyTypeError(
                expr, "compiling the function application returned a function "
                "call with arguments"
            )

        if expr:
            stargs = expr.pop(0)
            if stargs is not None:
                stargs = self.compile(stargs)
                if PY35:
                    stargs_expr = stargs.force_expr
                    ret.expr.args.append(
                        ast.Starred(stargs_expr, ast.Load(),
                                    lineno=stargs_expr.lineno,
                                    col_offset=stargs_expr.col_offset)
                    )
                else:
                    ret.expr.starargs = stargs.force_expr
                ret = stargs + ret

        if expr:
            kwargs = expr.pop(0)
            if isinstance(kwargs, HyDict):
                new_kwargs = []
                for k, v in kwargs.items():
                    if isinstance(k, HySymbol):
                        pass
                    elif isinstance(k, HyString):
                        k = HyString(hy_symbol_mangle(str_type(k))).replace(k)
                    elif isinstance(k, HyKeyword):
                        sym = hy_symbol_mangle(str_type(k)[2:])
                        k = HyString(sym).replace(k)
                    new_kwargs += [k, v]
                kwargs = HyDict(new_kwargs).replace(kwargs)

            kwargs = self.compile(kwargs)
            if PY35:
                kwargs_expr = kwargs.force_expr
                ret.expr.keywords.append(
                    ast.keyword(None, kwargs_expr,
                                lineno=kwargs_expr.lineno,
                                col_offset=kwargs_expr.col_offset)
                )
            else:
                ret.expr.kwargs = kwargs.force_expr
            ret = kwargs + ret

        return ret

    @builds("not")
    @builds("~")
    @checkargs(1)
    def compile_unary_operator(self, expression):
        ops = {"not": ast.Not,
               "~": ast.Invert}
        operator = expression.pop(0)
        operand = self.compile(expression.pop(0))

        operand += ast.UnaryOp(op=ops[operator](),
                               operand=operand.expr,
                               lineno=operator.start_line,
                               col_offset=operator.start_column)
        return operand

    @builds("require")
    def compile_require(self, expression):
        """
        TODO: keep track of what we've imported in this run and then
        "unimport" it after we've completed `thing' so that we don't pollute
        other envs.
        """
        for entry in expression[1:]:
            if isinstance(entry, HySymbol):
                # e.g., (require foo)
                __import__(entry)
                require(entry, self.module_name, all_macros=True,
                        prefix=entry)
            elif isinstance(entry, HyList) and len(entry) == 2:
                # e.g., (require [foo [bar baz :as MyBaz bing]])
                # or (require [foo [*]])
                module, names = entry
                if not isinstance(names, HyList):
                    raise HyTypeError(names,
                                      "(require) name lists should be HyLists")
                __import__(module)
                if '*' in names:
                    if len(names) != 1:
                        raise HyTypeError(names, "* in a (require) name list "
                                                 "must be on its own")
                    require(module, self.module_name, all_macros=True)
                else:
                    assignments = {}
                    while names:
                        if len(names) > 1 and names[1] == HyKeyword(":as"):
                            k, _, v = names[:3]
                            del names[:3]
                            assignments[k] = v
                        else:
                            symbol = names.pop(0)
                            assignments[symbol] = symbol
                    require(module, self.module_name, assignments=assignments)
            elif (isinstance(entry, HyList) and len(entry) == 3
                    and entry[1] == HyKeyword(":as")):
                # e.g., (require [foo :as bar])
                module, _, prefix = entry
                __import__(module)
                require(module, self.module_name, all_macros=True,
                        prefix=prefix)
            else:
                raise HyTypeError(entry, "unrecognized (require) syntax")
        return Result()

    @builds("and")
    @builds("or")
    def compile_logical_or_and_and_operator(self, expression):
        ops = {"and": (ast.And, "True"),
               "or": (ast.Or, "None")}
        operator = expression.pop(0)
        opnode, default = ops[operator]
        root_line, root_column = operator.start_line, operator.start_column
        if len(expression) == 0:
            return ast.Name(id=default,
                            ctx=ast.Load(),
                            lineno=root_line,
                            col_offset=root_column)
        elif len(expression) == 1:
            return self.compile(expression[0])
        ret = Result()
        values = list(map(self.compile, expression))
        has_stmt = any(value.stmts for value in values)
        if has_stmt:
            # Compile it to an if...else sequence
            var = self.get_anon_var()
            name = ast.Name(id=var,
                            ctx=ast.Store(),
                            lineno=root_line,
                            col_offset=root_column)
            expr_name = ast.Name(id=var,
                                 ctx=ast.Load(),
                                 lineno=root_line,
                                 col_offset=root_column)
            temp_variables = [name, expr_name]

            def make_assign(value, node=None):
                if node is None:
                    line, column = root_line, root_column
                else:
                    line, column = node.lineno, node.col_offset
                positioned_name = ast.Name(id=var, ctx=ast.Store(),
                                           lineno=line, col_offset=column)
                temp_variables.append(positioned_name)
                return ast.Assign(targets=[positioned_name],
                                  value=value,
                                  lineno=line,
                                  col_offset=column)
            root = []
            current = root
            for i, value in enumerate(values):
                if value.stmts:
                    node = value.stmts[0]
                    current.extend(value.stmts)
                else:
                    node = value.expr
                current.append(make_assign(value.force_expr, value.force_expr))
                if i == len(values)-1:
                    # Skip a redundant 'if'.
                    break
                if operator == "and":
                    cond = expr_name
                elif operator == "or":
                    cond = ast.UnaryOp(op=ast.Not(),
                                       operand=expr_name,
                                       lineno=node.lineno,
                                       col_offset=node.col_offset)
                current.append(ast.If(test=cond,
                                      body=[],
                                      lineno=node.lineno,
                                      col_offset=node.col_offset,
                                      orelse=[]))
                current = current[-1].body
            ret = sum(root, ret)
            ret += Result(expr=expr_name, temp_variables=temp_variables)
        else:
            ret += ast.BoolOp(op=opnode(),
                              lineno=root_line,
                              col_offset=root_column,
                              values=[value.force_expr for value in values])
        return ret

    def _compile_compare_op_expression(self, expression):
        ops = {"=": ast.Eq, "!=": ast.NotEq,
               "<": ast.Lt, "<=": ast.LtE,
               ">": ast.Gt, ">=": ast.GtE,
               "is": ast.Is, "is_not": ast.IsNot,
               "in": ast.In, "not_in": ast.NotIn}

        inv = expression.pop(0)
        op = ops[inv]
        ops = [op() for x in range(1, len(expression))]

        e = expression[0]
        exprs, ret, _ = self._compile_collect(expression)

        return ret + ast.Compare(left=exprs[0],
                                 ops=ops,
                                 comparators=exprs[1:],
                                 lineno=e.start_line,
                                 col_offset=e.start_column)

    @builds("=")
    @builds("!=")
    @builds("<")
    @builds("<=")
    @builds(">")
    @builds(">=")
    @checkargs(min=1)
    def compile_compare_op_expression(self, expression):
        if len(expression) == 2:
            rval = "True"
            if expression[0] == "!=":
                rval = "False"
            return ast.Name(id=rval,
                            ctx=ast.Load(),
                            lineno=expression.start_line,
                            col_offset=expression.start_column)
        return self._compile_compare_op_expression(expression)

    @builds("is")
    @builds("in")
    @builds("is_not")
    @builds("not_in")
    @checkargs(min=2)
    def compile_compare_op_expression_coll(self, expression):
        return self._compile_compare_op_expression(expression)

    @builds("%")
    @builds("**")
    @builds("<<")
    @builds(">>")
    @builds("|")
    @builds("^")
    @builds("&")
    @builds_if("@", PY35)
    @checkargs(min=2)
    def compile_maths_expression(self, expression):
        ops = {"+": ast.Add,
               "/": ast.Div,
               "//": ast.FloorDiv,
               "*": ast.Mult,
               "-": ast.Sub,
               "%": ast.Mod,
               "**": ast.Pow,
               "<<": ast.LShift,
               ">>": ast.RShift,
               "|": ast.BitOr,
               "^": ast.BitXor,
               "&": ast.BitAnd}
        if PY35:
            ops.update({"@": ast.MatMult})

        inv = expression.pop(0)
        op = ops[inv]

        ret = self.compile(expression.pop(0))
        for child in expression:
            left_expr = ret.force_expr
            ret += self.compile(child)
            right_expr = ret.force_expr
            ret += ast.BinOp(left=left_expr,
                             op=op(),
                             right=right_expr,
                             lineno=child.start_line,
                             col_offset=child.start_column)
        return ret

    @builds("*")
    @builds("/")
    @builds("//")
    def compile_maths_expression_mul(self, expression):
        if len(expression) > 2:
            return self.compile_maths_expression(expression)
        else:
            id_op = {"*": HyInteger(1), "/": HyInteger(1), "//": HyInteger(1)}

            op = expression.pop(0)
            arg = expression.pop(0) if expression else id_op[op]
            expr = HyExpression([
                HySymbol(op),
                id_op[op],
                arg
            ]).replace(expression)
            return self.compile_maths_expression(expr)

    def compile_maths_expression_additive(self, expression):
        if len(expression) > 2:
            return self.compile_maths_expression(expression)
        else:
            op = {"+": ast.UAdd, "-": ast.USub}[expression.pop(0)]()
            arg = expression.pop(0)
            ret = self.compile(arg)
            ret += ast.UnaryOp(op=op,
                               operand=ret.force_expr,
                               lineno=arg.start_line,
                               col_offset=arg.start_column)
            return ret

    @builds("+")
    def compile_maths_expression_add(self, expression):
        if len(expression) == 1:
            # Nullary +
            return ast.Num(n=long_type(0),
                           lineno=expression.start_line,
                           col_offset=expression.start_column)
        else:
            return self.compile_maths_expression_additive(expression)

    @builds("-")
    @checkargs(min=1)
    def compile_maths_expression_sub(self, expression):
        return self.compile_maths_expression_additive(expression)

    @builds("+=")
    @builds("/=")
    @builds("//=")
    @builds("*=")
    @builds("_=")
    @builds("%=")
    @builds("**=")
    @builds("<<=")
    @builds(">>=")
    @builds("|=")
    @builds("^=")
    @builds("&=")
    @builds_if("@=", PY35)
    @checkargs(2)
    def compile_augassign_expression(self, expression):
        ops = {"+=": ast.Add,
               "/=": ast.Div,
               "//=": ast.FloorDiv,
               "*=": ast.Mult,
               "_=": ast.Sub,
               "%=": ast.Mod,
               "**=": ast.Pow,
               "<<=": ast.LShift,
               ">>=": ast.RShift,
               "|=": ast.BitOr,
               "^=": ast.BitXor,
               "&=": ast.BitAnd}
        if PY35:
            ops.update({"@=": ast.MatMult})

        op = ops[expression[0]]

        target = self._storeize(expression[1], self.compile(expression[1]))
        ret = self.compile(expression[2])

        ret += ast.AugAssign(
            target=target,
            value=ret.force_expr,
            op=op(),
            lineno=expression.start_line,
            col_offset=expression.start_column)

        return ret

    @checkargs(1)
    def _compile_keyword_call(self, expression):
        expression.append(expression.pop(0))
        expression.insert(0, HySymbol("get"))
        return self.compile(expression)

    @builds(HyExpression)
    def compile_expression(self, expression):
        # Perform macro expansions
        expression = macroexpand(expression, self)
        if not isinstance(expression, HyExpression):
            # Go through compile again if the type changed.
            return self.compile(expression)

        if expression == []:
            return self.compile_list(expression)

        fn = expression[0]
        func = None
        if isinstance(fn, HyKeyword):
            return self._compile_keyword_call(expression)

        if isinstance(fn, HyString):
            ret = self.compile_atom(fn, expression)
            if ret:
                return ret

            if fn.startswith("."):
                # (.split "test test") -> "test test".split()
                # (.a.b.c x) -> (.c (. x a b)) ->  x.a.b.c()

                # Get the method name (the last named attribute
                # in the chain of attributes)
                attrs = [HySymbol(a).replace(fn) for a in fn.split(".")[1:]]
                fn = attrs.pop()

                # Get the object we're calling the method on
                # (extracted with the attribute access DSL)
                i = 1
                if len(expression) != 2:
                    # If the expression has only one object,
                    # always use that as the callee.
                    # Otherwise, hunt for the first thing that
                    # isn't a keyword argument or its value.
                    while i < len(expression):
                        if isinstance(expression[i], HyKeyword):
                            # Skip the keyword argument and its value.
                            i += 1
                        else:
                            # Use expression[i].
                            break
                        i += 1
                    else:
                        raise HyTypeError(expression,
                                          "attribute access requires object")
                func = self.compile(HyExpression(
                    [HySymbol(".").replace(fn), expression.pop(i)] +
                    attrs))

                # And get the method
                func += ast.Attribute(lineno=fn.start_line,
                                      col_offset=fn.start_column,
                                      value=func.force_expr,
                                      attr=ast_str(fn),
                                      ctx=ast.Load())

        if not func:
            func = self.compile(fn)

        # An exception for pulling together keyword args is if we're doing
        # a typecheck, eg (type :foo)
        if fn in ("type", "HyKeyword", "keyword", "name", "is_keyword"):
            with_kwargs = False
        else:
            with_kwargs = True

        args, ret, kwargs = self._compile_collect(expression[1:],
                                                  with_kwargs)

        ret += ast.Call(func=func.expr,
                        args=args,
                        keywords=kwargs,
                        starargs=None,
                        kwargs=None,
                        lineno=expression.start_line,
                        col_offset=expression.start_column)

        return func + ret

    @builds("def")
    @builds("setv")
    def compile_def_expression(self, expression):
        root = expression.pop(0)
        if not expression:
            result = Result()
            result += ast.Name(id='None', ctx=ast.Load(),
                               lineno=root.start_line,
                               col_offset=root.start_column)
            return result
        elif len(expression) == 2:
            return self._compile_assign(expression[0], expression[1],
                                        expression.start_line,
                                        expression.start_column)
        elif len(expression) % 2 != 0:
            raise HyTypeError(expression,
                              "`{}' needs an even number of arguments".format(
                                  root))
        else:
            result = Result()
            exprs = []
            for tgt, target in zip(expression[::2], expression[1::2]):
                item = self._compile_assign(tgt, target,
                                            tgt.start_line, tgt.start_column)
                result += item
                exprs.append(item.force_expr)

            result += ast.Tuple(elts=exprs, lineno=expression.start_line,
                                col_offset=expression.start_column,
                                ctx=ast.Load())
            return result

    def _compile_assign(self, name, result,
                        start_line, start_column):

        str_name = "%s" % name
        if _is_hy_builtin(str_name, self.module_name) and \
           not self.allow_builtins:
            raise HyTypeError(name,
                              "Can't assign to a builtin: `%s'" % str_name)

        result = self.compile(result)
        ld_name = self.compile(name)

        if isinstance(ld_name.expr, ast.Call):
            raise HyTypeError(name,
                              "Can't assign to a callable: `%s'" % str_name)

        if result.temp_variables \
           and isinstance(name, HyString) \
           and '.' not in name:
            result.rename(name)
        else:
            st_name = self._storeize(name, ld_name)
            result += ast.Assign(
                lineno=start_line,
                col_offset=start_column,
                targets=[st_name],
                value=result.force_expr)

        result += ld_name
        return result

    @builds("for*")
    @checkargs(min=1)
    def compile_for_expression(self, expression):
        expression.pop(0)  # for

        args = expression.pop(0)

        if not isinstance(args, HyList):
            raise HyTypeError(expression,
                              "for expects a list, received `{0}'".format(
                                  type(args).__name__))

        try:
            target_name, iterable = args
        except ValueError:
            raise HyTypeError(expression,
                              "for requires two forms in the list")

        target = self._storeize(target_name, self.compile(target_name))

        ret = Result()

        orel = Result()
        # (for* [] body (else …))
        if expression and expression[-1][0] == HySymbol("else"):
            else_expr = expression.pop()
            if len(else_expr) > 2:
                raise HyTypeError(
                    else_expr,
                    "`else' statement in `for' is too long")
            elif len(else_expr) == 2:
                orel += self.compile(else_expr[1])
                orel += orel.expr_as_stmt()

        ret += self.compile(iterable)

        body = self._compile_branch(expression)
        body += body.expr_as_stmt()

        ret += ast.For(lineno=expression.start_line,
                       col_offset=expression.start_column,
                       target=target,
                       iter=ret.force_expr,
                       body=body.stmts,
                       orelse=orel.stmts)

        ret.contains_yield = body.contains_yield

        return ret

    @builds("while")
    @checkargs(min=2)
    def compile_while_expression(self, expr):
        expr.pop(0)  # "while"
        ret = self.compile(expr.pop(0))

        body = self._compile_branch(expr)
        body += body.expr_as_stmt()

        ret += ast.While(test=ret.force_expr,
                         body=body.stmts,
                         orelse=[],
                         lineno=expr.start_line,
                         col_offset=expr.start_column)

        ret.contains_yield = body.contains_yield

        return ret

    @builds(HyList)
    def compile_list(self, expression):
        elts, ret, _ = self._compile_collect(expression)
        ret += ast.List(elts=elts,
                        ctx=ast.Load(),
                        lineno=expression.start_line,
                        col_offset=expression.start_column)
        return ret

    @builds(HySet)
    def compile_set(self, expression):
        elts, ret, _ = self._compile_collect(expression)
        if PY27:
            ret += ast.Set(elts=elts,
                           ctx=ast.Load(),
                           lineno=expression.start_line,
                           col_offset=expression.start_column)
        else:
            ret += ast.Call(func=ast.Name(id='set',
                                          ctx=ast.Load(),
                                          lineno=expression.start_line,
                                          col_offset=expression.start_column),
                            args=[
                                ast.List(elts=elts,
                                         ctx=ast.Load(),
                                         lineno=expression.start_line,
                                         col_offset=expression.start_column)],
                            keywords=[],
                            starargs=None,
                            kwargs=None,
                            lineno=expression.start_line,
                            col_offset=expression.start_column)
        return ret

    @builds("lambda")
    @builds("fn")
    @checkargs(min=1)
    def compile_function_def(self, expression):
        called_as = expression.pop(0)

        arglist = expression.pop(0)
        if not isinstance(arglist, HyList):
            raise HyTypeError(expression,
                              "First argument to `{}' must be a list".format(
                                  called_as))

        (ret, args, defaults, stararg,
         kwonlyargs, kwonlydefaults, kwargs) = self._parse_lambda_list(arglist)
        for i, arg in enumerate(args):
            if isinstance(arg, HyList):
                # Destructuring argument
                if not arg:
                    raise HyTypeError(arglist,
                                      "Cannot destruct empty list")
                args[i] = var = HySymbol(self.get_anon_var())
                expression = HyExpression([
                    HyExpression([
                        HyString("setv"), arg, var
                    ])]
                ) + expression
                expression = expression.replace(arg[0])

        if PY34:
            # Python 3.4+ requires that args are an ast.arg object, rather
            # than an ast.Name or bare string.
            args = [ast.arg(arg=ast_str(x),
                            annotation=None,  # Fix me!
                            lineno=x.start_line,
                            col_offset=x.start_column) for x in args]

            kwonlyargs = [ast.arg(arg=ast_str(x), annotation=None,
                                  lineno=x.start_line,
                                  col_offset=x.start_column)
                          for x in kwonlyargs]

            # XXX: Beware. Beware. This wasn't put into the parse lambda
            # list because it's really just an internal parsing thing.

            if kwargs:
                kwargs = ast.arg(arg=ast_str(kwargs), annotation=None,
                                 lineno=kwargs.start_line,
                                 col_offset=kwargs.start_column)

            if stararg:
                stararg = ast.arg(arg=ast_str(stararg), annotation=None,
                                  lineno=stararg.start_line,
                                  col_offset=stararg.start_column)

            # Let's find a better home for these guys.
        else:
            args = [ast.Name(arg=ast_str(x), id=ast_str(x),
                             ctx=ast.Param(),
                             lineno=x.start_line,
                             col_offset=x.start_column) for x in args]

            if PY3:
                kwonlyargs = [ast.Name(arg=ast_str(x), id=ast_str(x),
                                       ctx=ast.Param(), lineno=x.start_line,
                                       col_offset=x.start_column)
                              for x in kwonlyargs]

            if kwargs:
                kwargs = ast_str(kwargs)

            if stararg:
                stararg = ast_str(stararg)

        args = ast.arguments(
            args=args,
            vararg=stararg,
            kwarg=kwargs,
            kwonlyargs=kwonlyargs,
            kw_defaults=kwonlydefaults,
            defaults=defaults)

        body = self._compile_branch(expression)
        if not body.stmts and called_as == "lambda":
            ret += ast.Lambda(
                lineno=expression.start_line,
                col_offset=expression.start_column,
                args=args,
                body=body.force_expr)

            return ret

        if body.expr:
            if body.contains_yield and not PY33:
                # Prior to PEP 380 (introduced in Python 3.3)
                # generators may not have a value in a return
                # statement.
                body += body.expr_as_stmt()
            else:
                body += ast.Return(value=body.expr,
                                   lineno=body.expr.lineno,
                                   col_offset=body.expr.col_offset)

        if not body.stmts:
            body += ast.Pass(lineno=expression.start_line,
                             col_offset=expression.start_column)

        name = self.get_anon_fn()

        ret += ast.FunctionDef(name=name,
                               lineno=expression.start_line,
                               col_offset=expression.start_column,
                               args=args,
                               body=body.stmts,
                               decorator_list=[])

        ast_name = ast.Name(id=name,
                            arg=name,
                            ctx=ast.Load(),
                            lineno=expression.start_line,
                            col_offset=expression.start_column)

        ret += Result(expr=ast_name, temp_variables=[ast_name, ret.stmts[-1]])

        return ret

    @builds("defclass")
    @checkargs(min=1)
    def compile_class_expression(self, expressions):
        def rewire_init(expr):
            new_args = []
            if expr[0] == HySymbol("setv"):
                pairs = expr[1:]
                while len(pairs) > 0:
                    k, v = (pairs.pop(0), pairs.pop(0))
                    if k == HySymbol("__init__"):
                        v.append(HySymbol("None"))
                    new_args.append(k)
                    new_args.append(v)
                expr = HyExpression([
                    HySymbol("setv")
                ] + new_args).replace(expr)

            return expr

        expressions.pop(0)  # class

        class_name = expressions.pop(0)

        if expressions:
            base_list = expressions.pop(0)
            if not isinstance(base_list, HyList):
                raise HyTypeError(expressions,
                                  "Bases class must be a list")
            bases_expr, bases, _ = self._compile_collect(base_list)
        else:
            bases_expr = []
            bases = Result()

        body = Result()

        # grab the doc string, if there is one
        if expressions and isinstance(expressions[0], HyString):
            docstring = expressions.pop(0)
            symb = HySymbol("__doc__")
            symb.start_line = docstring.start_line
            symb.start_column = docstring.start_column
            body += self._compile_assign(symb, docstring,
                                         docstring.start_line,
                                         docstring.start_column)
            body += body.expr_as_stmt()

        allow_builtins = self.allow_builtins
        self.allow_builtins = True
        if expressions and isinstance(expressions[0], HyList) \
           and not isinstance(expressions[0], HyExpression):
            expr = expressions.pop(0)
            expr = HyExpression([
                HySymbol("setv")
            ] + expr).replace(expr)
            body += self.compile(rewire_init(expr))

        for expression in expressions:
            expr = rewire_init(macroexpand(expression, self))
            body += self.compile(expr)

        self.allow_builtins = allow_builtins

        if not body.stmts:
            body += ast.Pass(lineno=expressions.start_line,
                             col_offset=expressions.start_column)

        return bases + ast.ClassDef(
            lineno=expressions.start_line,
            col_offset=expressions.start_column,
            decorator_list=[],
            name=ast_str(class_name),
            keywords=[],
            starargs=None,
            kwargs=None,
            bases=bases_expr,
            body=body.stmts)

    def _compile_time_hack(self, expression):
        """Compile-time hack: we want to get our new macro now
        We must provide __name__ in the namespace to make the Python
        compiler set the __module__ attribute of the macro function."""
        hy.importer.hy_eval(expression,
                            compile_time_ns(self.module_name),
                            self.module_name)

        # We really want to have a `hy` import to get hy.macro in
        ret = self.compile(expression)
        ret.add_imports('hy', [None])
        return ret

    @builds("defmacro")
    @checkargs(min=1)
    def compile_macro(self, expression):
        expression.pop(0)
        name = expression.pop(0)
        if not isinstance(name, HySymbol):
            raise HyTypeError(name, ("received a `%s' instead of a symbol "
                                     "for macro name" % type(name).__name__))
        name = HyString(name).replace(name)
        for kw in ("&kwonly", "&kwargs", "&key"):
            if kw in expression[0]:
                raise HyTypeError(name, "macros cannot use %s" % kw)
        new_expression = HyExpression([
            HySymbol("with_decorator"),
            HyExpression([HySymbol("hy.macros.macro"), name]),
            HyExpression([HySymbol("fn")] + expression),
        ]).replace(expression)

        ret = self._compile_time_hack(new_expression)

        return ret

    @builds("defreader")
    @checkargs(min=2)
    def compile_reader(self, expression):
        expression.pop(0)
        name = expression.pop(0)
        NOT_READERS = [":", "&"]
        if name in NOT_READERS or len(name) > 1:
            raise NameError("%s can't be used as a macro reader symbol" % name)
        if not isinstance(name, HySymbol) and not isinstance(name, HyString):
            raise HyTypeError(name,
                              ("received a `%s' instead of a symbol "
                               "for reader macro name" % type(name).__name__))
        name = HyString(name).replace(name)
        new_expression = HyExpression([
            HySymbol("with_decorator"),
            HyExpression([HySymbol("hy.macros.reader"), name]),
            HyExpression([HySymbol("fn")] + expression),
        ]).replace(expression)

        ret = self._compile_time_hack(new_expression)

        return ret

    @builds("dispatch_reader_macro")
    @checkargs(exact=2)
    def compile_dispatch_reader_macro(self, expression):
        expression.pop(0)  # dispatch-reader-macro
        str_char = expression.pop(0)
        if not type(str_char) == HyString:
            raise HyTypeError(
                str_char,
                "Trying to expand a reader macro using `{0}' instead "
                "of string".format(type(str_char).__name__),
            )
        expr = reader_macroexpand(str_char, expression.pop(0), self)
        return self.compile(expr)

    @builds("eval_and_compile")
    def compile_eval_and_compile(self, expression):
        expression[0] = HySymbol("do")
        hy.importer.hy_eval(expression,
                            compile_time_ns(self.module_name),
                            self.module_name)
        expression.pop(0)
        return self._compile_branch(expression)

    @builds("eval_when_compile")
    def compile_eval_when_compile(self, expression):
        expression[0] = HySymbol("do")
        hy.importer.hy_eval(expression,
                            compile_time_ns(self.module_name),
                            self.module_name)
        return Result()

    @builds(HyCons)
    def compile_cons(self, cons):
        raise HyTypeError(cons, "Can't compile a top-level cons cell")

    @builds(HyInteger)
    def compile_integer(self, number):
        return ast.Num(n=long_type(number),
                       lineno=number.start_line,
                       col_offset=number.start_column)

    @builds(HyFloat)
    def compile_float(self, number):
        return ast.Num(n=float(number),
                       lineno=number.start_line,
                       col_offset=number.start_column)

    @builds(HyComplex)
    def compile_complex(self, number):
        return ast.Num(n=complex(number),
                       lineno=number.start_line,
                       col_offset=number.start_column)

    @builds(HySymbol)
    def compile_symbol(self, symbol):
        if "." in symbol:
            glob, local = symbol.rsplit(".", 1)

            if not glob:
                raise HyTypeError(symbol, 'cannot access attribute on '
                                          'anything other than a name '
                                          '(in order to get attributes of'
                                          'expressions, use '
                                          '`(. <expression> {attr})` or '
                                          '`(.{attr} <expression>)`)'.format(
                                              attr=local))

            if not local:
                raise HyTypeError(symbol, 'cannot access empty attribute')

            glob = HySymbol(glob).replace(symbol)
            ret = self.compile_symbol(glob)

            ret = ast.Attribute(
                lineno=symbol.start_line,
                col_offset=symbol.start_column,
                value=ret,
                attr=ast_str(local),
                ctx=ast.Load()
            )
            return ret

        if symbol in _stdlib:
            self.imports[_stdlib[symbol]].add(symbol)

        return ast.Name(id=ast_str(symbol),
                        arg=ast_str(symbol),
                        ctx=ast.Load(),
                        lineno=symbol.start_line,
                        col_offset=symbol.start_column)

    @builds(HyString)
    def compile_string(self, string):
        return ast.Str(s=str_type(string),
                       lineno=string.start_line,
                       col_offset=string.start_column)

    @builds(HyKeyword)
    def compile_keyword(self, keyword):
        return ast.Str(s=str_type(keyword),
                       lineno=keyword.start_line,
                       col_offset=keyword.start_column)

    @builds(HyDict)
    def compile_dict(self, m):
        keyvalues, ret, _ = self._compile_collect(m)

        ret += ast.Dict(lineno=m.start_line,
                        col_offset=m.start_column,
                        keys=keyvalues[::2],
                        values=keyvalues[1::2])
        return ret


def hy_compile(tree, module_name, root=ast.Module, get_expr=False):
    """
    Compile a HyObject tree into a Python AST Module.

    If `get_expr` is True, return a tuple (module, last_expression), where
    `last_expression` is the.
    """

    body = []
    expr = None

    if tree:
        compiler = HyASTCompiler(module_name)
        result = compiler.compile(tree)
        expr = result.force_expr

        if not get_expr:
            result += result.expr_as_stmt()

        if isinstance(tree, list):
            spoof_tree = tree[0]
        else:
            spoof_tree = tree
        body = compiler.imports_as_stmts(spoof_tree) + result.stmts

    ret = root(body=body)

    if get_expr:
        expr = ast.Expression(body=expr)
        ret = (ret, expr)

    return ret