Source

pyd / infrastructure / pyd / class_wrap.d

Full commit
   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
/*
Copyright 2006, 2007 Kirk McDonald

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.
*/

/**
  Contains utilities for wrapping D classes.
*/
module pyd.class_wrap;

import deimos.python.Python;

import std.algorithm: countUntil;
import std.traits;
import std.conv;
import std.exception: enforce;
import std.functional;
import std.metastrings;
import std.typetuple;
import std.string: format;
import std.typecons: Tuple;
import util.typelist;
import util.multi_index;
import util.replace: Replace;
import pyd.ctor_wrap;
import pyd.def;
import pyd.exception;
import pyd.func_wrap;
import pyd.make_object;
import pyd.make_wrapper;
import pyd.op_wrap;
import pyd.struct_wrap;

version(Pyd_with_StackThreads) static assert(0, "sorry - stackthreads are gone");

PyTypeObject*[ClassInfo] wrapped_classes;
template shim_class(T) {
    PyTypeObject* shim_class;
}

// This is split out in case I ever want to make a subtype of a wrapped class.
template PydWrapObject_HEAD(T) {
    mixin PyObject_HEAD;
    T d_obj;
}

// The class object, a subtype of PyObject
template wrapped_class_object(T) {
    extern(C)
    struct wrapped_class_object {
        mixin PydWrapObject_HEAD!(T);
    }
}

void init_PyTypeObject(T)(ref PyTypeObject tipo) {
    Py_SET_REFCNT(&tipo, 1);
    tipo.tp_dealloc = &wrapped_methods!(T).wrapped_dealloc;
    tipo.tp_new = &wrapped_methods!(T).wrapped_new;
}
//
template wrapped_class_type(T) {
// The type object, an instance of PyType_Type
    static PyTypeObject wrapped_class_type;
}

// A mapping of all class references that are being held by Python.
alias Tuple!(void*,"d",PyObject*,"py") D2Py;
alias MultiIndexContainer!(D2Py, IndexedBy!(HashedUnique!("a.d")), 
        MallocAllocator, MutableView) WrappedObjectMap;

WrappedObjectMap _wrapped_gc_objects = null;

// would initialize in static this, but static this apparently isn't run
// in shared libs
@property wrapped_gc_objects() {
    if(!_wrapped_gc_objects) _wrapped_gc_objects = new WrappedObjectMap();
    return _wrapped_gc_objects;
}

template Dt2Py(dg_t) {
    alias Tuple!(dg_t,"d",PyObject*,"py") Dt2Py;
}

// A mapping of all GC references that are being held by Python.
template wrapped_gc_references(dg_t) {
    alias MultiIndexContainer!(Dt2Py!dg_t, IndexedBy!(HashedUnique!("a.d")), 
            MallocAllocator, MutableView) WrappedReferenceMap;
    WrappedReferenceMap _wrapped_gc_references;

    @property wrapped_gc_references() {
        if(!_wrapped_gc_references) 
            _wrapped_gc_references = new WrappedReferenceMap();
        return _wrapped_gc_references;
    }
}

/**
 * A useful check for whether a given class has been wrapped. Mainly used by
 * the conversion functions (see make_object.d), but possibly useful elsewhere.
 */
template is_wrapped(T) {
    bool is_wrapped = false;
}

// The list of wrapped methods for this class.
template wrapped_method_list(T) {
    PyMethodDef[] wrapped_method_list = [
        { null, null, 0, null }
    ];
}

// The list of wrapped properties for this class.
template wrapped_prop_list(T) {
    static PyGetSetDef[] wrapped_prop_list = [
        { null, null, null, null, null }
    ];
}

//-///////////////////
// STANDARD METHODS //
//-///////////////////

// Various wrapped methods
template wrapped_methods(T) {
    alias wrapped_class_object!(T) wrap_object;
    /// The generic "__new__" method
    extern(C)
    PyObject* wrapped_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
        return exception_catcher(delegate PyObject*() {
            wrap_object* self;

            self = cast(wrap_object*)type.tp_alloc(type, 0);
            if (self !is null) {
                self.d_obj = null;
            }

            return cast(PyObject*)self;
        });
    }

    // The generic dealloc method.
    extern(C)
    void wrapped_dealloc(PyObject* self) {
        // EMN: the *&%^^%! generic dealloc method is triggering a call to
        //  *&^%*%(! malloc for that delegate during a @(*$76*&! 
        //  garbage collection
        //  Solution: don't use a *&%%^^! delegate in a destructor!
        static struct StackDelegate{
            PyObject* x;
            void dg() {
                WrapPyObject_SetObj!(T)(x, cast(T)null);
                x.ob_type.tp_free(x);
            }
        }
        StackDelegate x;
        x.x = self;
        exception_catcher(&x.dg);
    }
}

template wrapped_repr(T, alias fn) {
    alias wrapped_class_object!(T) wrap_object;
    alias dg_wrapper!(T, typeof(&fn)) get_dg;
    /// The default repr method calls the class's toString.
    extern(C)
    PyObject* repr(PyObject* self) {
        return exception_catcher(delegate PyObject*() {
            auto dg = get_dg((cast(wrap_object*)self).d_obj, &fn);
            return d_to_python(dg());
        });
    }
}

private template ID(A){ alias A ID; }
private struct CW(A...){ alias A C; }

template IsProperty(alias T) {
    enum bool IsProperty = 
        (functionAttributes!(T) & FunctionAttribute.property) != 0;
}

template IsGetter(alias T) {
    enum bool IsGetter = ParameterTypeTuple!T .length == 0 && 
        !is(ReturnType!T == void);
}

template IsSetter(RT) {
    template IsSetter(alias T) {
        enum bool IsSetter = ParameterTypeTuple!T .length == 1 && 
                is(ParameterTypeTuple!(T)[0] == RT);
    }
}
template IsAnySetter(alias T) {
    enum bool IsAnySetter = ParameterTypeTuple!T .length == 1;
}

// This template gets an alias to a property and derives the types of the
// getter form and the setter form. It requires that the getter form return the
// same type that the setter form accepts.
struct property_parts(alias p, string _mode) {
    alias ID!(__traits(parent, p)) Parent;
    enum nom = __traits(identifier, p);
    alias TypeTuple!(__traits(getOverloads, Parent, nom)) Overloads;
    static if(_mode == "" || countUntil(_mode, "r") != 1) {
        alias Filter!(IsGetter,Overloads) Getters;
        static if(_mode == "" && Getters.length == 0) {
            enum isgproperty = false;
            enum rmode = "";
        }else{
            static assert(Getters.length != 0, 
                    Format!("can't find property %s.%s getter", 
                        Parent.stringof, nom));
            static assert(Getters.length == 1, 
                    Format!("can't handle property overloads of %s.%s getter (types %s)", 
                        Parent.stringof, nom, staticMap!(ReturnType,Getters).stringof));
            alias Getters[0] GetterFn;
            alias typeof(&GetterFn) getter_type;
            enum isgproperty = IsProperty!GetterFn;
            enum rmode = "r";
        }
    }else {
        enum isgproperty = false;
        enum rmode = "";
    }
    //enum bool pred1 = _mode == "" || countUntil(_mode, "w") != -1;
    static if(_mode == "" || countUntil(_mode, "w") != -1) {
        static if(rmode == "r") {
            alias Filter!(IsSetter!(ReturnType!getter_type), Overloads) Setters;
        }else {
            alias Filter!(IsAnySetter, Overloads) Setters;
        }

        //enum bool pred2 = _mode == "" && Setters.length == 0;
        static if(_mode == "" && Setters.length == 0) {
            enum bool issproperty = false;
            enum string wmode = "";
        }else{
            static assert(Setters.length != 0, Format!("can't find property %s.%s setter", Parent.stringof, nom));
            static assert(Setters.length == 1, 
                Format!("can't handle property overloads of %s.%s setter %s", 
                    Parent.stringof, nom, Setters.stringof));
            alias Setters[0] SetterFn;
            alias typeof(&SetterFn) setter_type;
            static if(rmode == "r") {
                static assert(!(IsProperty!GetterFn ^ IsProperty!(Setters[0])), 
                        Format!("%s.%s: getter and setter must both be @property or not @property", 
                            Parent.stringof, nom));
            }
            enum issproperty = IsProperty!SetterFn;
            enum wmode = "w";
        }
    }else{
        enum issproperty = false;
        enum wmode = "";
    }

    enum mode = rmode ~ wmode;
    enum bool isproperty = isgproperty || issproperty;
}

//
template wrapped_get(T, Parts) {
    // A generic wrapper around a "getter" property.
    extern(C)
    PyObject* func(PyObject* self, void* closure) {
        // method_wrap already catches exceptions
        return method_wrap!(T, Parts.GetterFn).func(self, null, null);
    }
}

//
template wrapped_set(T, Parts) {
    // A generic wrapper around a "setter" property.
    extern(C)
    int func(PyObject* self, PyObject* value, void* closure) {
        PyObject* temp_tuple = PyTuple_New(1);
        if (temp_tuple is null) return -1;
        scope(exit) Py_DECREF(temp_tuple);
        Py_INCREF(value);
        PyTuple_SetItem(temp_tuple, 0, value);
        PyObject* res = method_wrap!(T, Parts.SetterFn).func(self, temp_tuple, null);
        // If we get something back, we need to DECREF it.
        if (res) Py_DECREF(res);
        // If we don't, propagate the exception
        else return -1;
        // Otherwise, all is well.
        return 0;
    }
}

//-///////////////////////////
// CLASS WRAPPING INTERFACE //
//-///////////////////////////

//enum ParamType { Def, StaticDef, Property, Init, Parent, Hide, Iter, AltIter }
struct DoNothing {
    static void call(T) () {}
}

/**
Wraps a member function of the class.

Supports default arguments, typesafe variadic arguments, and python's 
keyword arguments.

Params:
fn = The member function to wrap.
Options = Optional parameters. Takes Docstring!(docstring), PyName!(pyname), 
and fn_t.
fn_t = The type of the function. It is only useful to specify this
       if more than one function has the same name as this one.
pyname = The name of the function as it will appear in Python. Defaults to 
fn's name in D
docstring = The function's docstring. Defaults to "".
*/
struct Def(alias fn, Options...) {
    alias Args!("","", __traits(identifier,fn), "",Options) args;
    static if(args.rem.length) {
        alias args.rem[0] fn_t;
    }else {
        alias typeof(&fn) fn_t;
    }
    mixin _Def!(fn, args.pyname, fn_t, args.docstring);
}

template _Def(alias _fn, string name, fn_t, string docstring) {
    alias def_selector!(_fn,fn_t).FN func;
    static assert(!__traits(isStaticFunction, func)); // TODO
    alias fn_t func_t;
    enum realname = __traits(identifier,func);
    enum funcname = name;
    enum min_args = minArgs!(func);
    enum bool needs_shim = false;

    static void call(T) () {
        pragma(msg, "class.def: " ~ name);
        static PyMethodDef empty = { null, null, 0, null };
        alias wrapped_method_list!(T) list;
        list[$-1].ml_name = (name ~ "\0").ptr;
        list[$-1].ml_meth = cast(PyCFunction) &method_wrap!(T, func).func;
        list[$-1].ml_flags = METH_VARARGS | METH_KEYWORDS;
        list[$-1].ml_doc = (docstring~"\0").ptr;
        list ~= empty;
        // It's possible that appending the empty item invalidated the
        // pointer in the type struct, so we renew it here.
        wrapped_class_type!(T).tp_methods = list.ptr;
    }
    template shim(size_t i, T) {
        enum shim = Replace!(q{    
            alias Params[$i] __pyd_p$i;
            ReturnType!(__pyd_p$i.func_t) $realname(ParameterTypeTuple!(__pyd_p$i.func_t) t) {
                return __pyd_get_overload!("$realname", __pyd_p$i.func_t).func("$name", t);
            }
            alias T.$realname $realname;
        }, "$i",i,"$realname",realname, "$name", name);
    }
}

/**
Wraps a static member function of the class. Similar to pyd.def.def

Supports default arguments, typesafe variadic arguments, and python's 
keyword arguments.

Params:
fn = The member function to wrap.
Options = Optional parameters. Takes Docstring!(docstring), PyName!(pyname), 
and fn_t
fn_t = The type of the function. It is only useful to specify this
       if more than one function has the same name as this one.
pyname = The name of the function as it will appear in Python. Defaults to fn's 
name in D.
docstring = The function's docstring. Defaults to "".
*/
struct StaticDef(alias fn, Options...) {
    alias Args!("","", __traits(identifier,fn), "",Options) args;
    static if(args.rem.length) {
        alias args.rem[0] fn_t;
    }else {
        alias typeof(&fn) fn_t;
    }
    mixin _StaticDef!(fn, args.pyname, fn_t, args.docstring);
}

mixin template _StaticDef(alias fn, string name, fn_t, string docstring) {
    alias def_selector!(fn,fn_t).FN func;
    static assert(__traits(isStaticFunction, func)); // TODO
    alias fn_t func_t;
    enum funcname = name;
    enum bool needs_shim = false;
    static void call(T) () {
        pragma(msg, "class.static_def: " ~ name);
        static PyMethodDef empty = { null, null, 0, null };
        alias wrapped_method_list!(T) list;
        list[$-1].ml_name = (name ~ "\0").ptr;
        list[$-1].ml_meth = cast(PyCFunction) &function_wrap!func.func;
        list[$-1].ml_flags = METH_VARARGS | METH_STATIC | METH_KEYWORDS;
        list[$-1].ml_doc = (docstring~"\0").ptr;
        list ~= empty;
        wrapped_class_type!(T).tp_methods = list.ptr;
    }
    template shim(size_t i,T) {
        enum shim = "";
    }
}

/**
Wraps a property of the class. 

Params:
fn = The property to wrap. 
Options = Optional parameters. Takes Docstring!(docstring), PyName!(pyname), 
and Mode!(mode)
pyname = The name of the property as it will appear in Python. Defaults to 
fn's name in D.
mode = specifies whether this property is readable, writable. possible values 
are "r", "w", "rw", and "" (in the latter case, automatically determine which 
mode to use based on availability of getter and setter forms of fn). Defaults
to "".
docstring = The function's docstring. Defaults to "".
*/
struct Property(alias fn, Options...) {
    alias Args!("","", __traits(identifier,fn), "",Options) args;
    static assert(args.rem.length == 0, "Propery takes no other parameter");
    mixin _Property!(fn, args.pyname, args.mode, args.docstring);
}

template _Property(alias fn, string pyname, string _mode, string docstring) {
    alias property_parts!(fn, _mode) parts;
    pragma(msg, "property: ", parts.nom);
    static if(parts.isproperty) {
        mixin _Member!(parts.nom, pyname, parts.mode, docstring);

        template shim(size_t i, T) {
            enum shim = "";
        }
    }else {
        static if(countUntil(parts.mode,"r") != -1) {
            alias parts.getter_type get_t;
        }
        static if(countUntil(parts.mode,"w") != -1) {
            alias parts.setter_type set_t;
        }
        enum realname = __traits(identifier, fn);
        enum funcname = pyname;
        enum bool needs_shim = false;
        static void call(T) () {
            pragma(msg, "class.prop: " ~ pyname);
            static PyGetSetDef empty = { null, null, null, null, null };
            wrapped_prop_list!(T)[$-1].name = (pyname ~ "\0").dup.ptr;
            static if (countUntil(parts.mode, "r") != -1) {
                wrapped_prop_list!(T)[$-1].get =
                    &wrapped_get!(T, parts).func;
            }
            static if (countUntil(parts.mode, "w") != -1) {
                wrapped_prop_list!(T)[$-1].set =
                    &wrapped_set!(T, parts).func;
            }
            wrapped_prop_list!(T)[$-1].doc = (docstring~"\0").dup.ptr;
            wrapped_prop_list!(T)[$-1].closure = null;
            wrapped_prop_list!(T) ~= empty;
            // It's possible that appending the empty item invalidated the
            // pointer in the type struct, so we renew it here.
            wrapped_class_type!(T).tp_getset =
                wrapped_prop_list!(T).ptr;
        }
        template shim(size_t i, T) {
            static if(countUntil(parts.mode, "r") != -1) {
                enum getter = Replace!(q{
                ReturnType!(__pyd_p$i.get_t) $realname() {
                    return __pyd_get_overload!("$realname", __pyd_p$i.get_t).func("$name");
                }
                } , "$i",i,"$realname",realname, "$name", pyname);
            }else{
                enum getter = "";
            }
            static if(countUntil(parts.mode, "w") != -1) {
                enum setter = Replace!(q{
                ReturnType!(__pyd_p$i.set_t) $realname(ParameterTypeTuple!(__pyd_p$i.set_t) t) {
                    return __pyd_get_overload!("$realname", __pyd_p$i.set_t).func("$name", t);
                }
                }, "$i", i, "$realname",realname, "$name", pyname);
            }else {
                enum setter = "";
            }
            enum shim = Replace!(q{
                alias Params[$i] __pyd_p$i;
                $getter
                $setter;
            }, "$i",i, "$getter", getter, "$setter",setter);
        }
    }
}

/**
Wraps a method as the class's ___repr__ in Python.

Params:
fn = The property to wrap. Must have the signature string function().
*/
struct Repr(alias _fn) {
    alias def_selector!(_fn, string function()).FN fn;
    enum bool needs_shim = false;
    static void call(T)() {
        alias wrapped_class_type!(T) type;
        type.tp_repr = &wrapped_repr!(T, fn).repr;
    }
    template shim(size_t i,T) {
        enum shim = "";
    }
}

/**
Wraps the constructors of the class.

This template takes a single specialization of the ctor template
(see ctor_wrap.d), which describes a constructor that the class 
supports. The default constructor need not be
specified, and will always be available if the class supports it.

Supports default arguments, typesafe variadic arguments, and python's 
keyword arguments.

Params:
    cps = Parameter list of the constructor to be wrapped.

Bugs:
This currently does not support having multiple constructors with
the same number of arguments.
*/
struct Init(cps ...) {
    alias cps CtorParams;
    enum bool needs_shim = false;
    template Inner(T) {
        static if(isPointer!T && is(PointerTarget!T == struct)) 
            alias PointerTarget!T BaseT;
        else alias T BaseT;
        alias TypeTuple!(__traits(getOverloads, BaseT, "__ctor")) Overloads;
        template IsDesired(alias ctor) {
            alias ParameterTypeTuple!ctor ps;
            enum bool IsDesired = is(ps == CtorParams);
        }
        alias Filter!(IsDesired, Overloads) VOverloads;
        static assert(VOverloads.length != 0, 
                Format!("%s: Cannot find constructor with params %s", 
                    T.stringof, CtorParams.stringof));
        alias VOverloads[0] FN;
    }
    static void call(T)() {
    }
    template shim(size_t i, T) {
        enum params = getparams!(Inner!T.FN);
        alias ParameterIdentifierTuple!(Inner!T.FN) paramids;
        enum shim = Replace!(q{
            alias Params[$i] __pyd_p$i;
            this($params) {
                super($ids);
            }
        }, "$i", i, "$params", params, "$ids", Join!(",", paramids));
    }
}

template IsInit(T) {
    enum bool IsInit = __traits(hasMember, T, "CtorParams");
}

enum binaryslots = [
    "+": "type.tp_as_number.nb_add", 
    "+=": "type.tp_as_number.nb_inplace_add", 
    "-": "type.tp_as_number.nb_subtract", 
    "-=": "type.tp_as_number.nb_inplace_subtract", 
    "*": "type.tp_as_number.nb_multiply",
    "*=": "type.tp_as_number.nb_inplace_multiply",
    "/": "type.tp_as_number.nb_divide",
    "/=": "type.tp_as_number.nb_inplace_divide",
    "%": "type.tp_as_number.nb_remainder",
    "%=": "type.tp_as_number.nb_inplace_remainder",
    "^^": "type.tp_as_number.nb_power",
    "^^=": "type.tp_as_number.nb_inplace_power",
    "<<": "type.tp_as_number.nb_lshift",
    "<<=": "type.tp_as_number.nb_inplace_lshift",
    ">>": "type.tp_as_number.nb_rshift",
    ">>=": "type.tp_as_number.nb_inplace_rshift",
    "&": "type.tp_as_number.nb_and",
    "&=": "type.tp_as_number.nb_inplace_and",
    "^": "type.tp_as_number.nb_xor",
    "^=": "type.tp_as_number.nb_inplace_xor",
    "|": "type.tp_as_number.nb_or",
    "|=": "type.tp_as_number.nb_inplace_or",
    "~": "type.tp_as_sequence.sq_concat",
    "~=": "type.tp_as_sequence.sq_inplace_concat",
    "in": "type.tp_as_sequence.sq_contains",
];

bool IsPyBinary(string op) {
    foreach(_op, slot; binaryslots) {
        if (op[$-1] != '=' && op == _op) return true;
    }
    return false;
}
bool IsPyAsg(string op0) {
    auto op = op0~"=";
    foreach(_op, slot; binaryslots) {
        if (op == _op) return true;
    }
    return false;
}

enum unaryslots = [
    "+": "type.tp_as_number.nb_positive",
    "-": "type.tp_as_number.nb_negative",
    "~": "type.tp_as_number.nb_invert",
];

bool IsPyUnary(string op) {
    foreach(_op, slot; unaryslots) {
        if(op == _op) return true;
    }
    return false;
}

// string mixin to initialize tp_as_number or tp_as_sequence or tp_as_mapping
// if necessary. Scope mixed in must have these variables:
//  slot: a value from binaryslots or unaryslots
//  type: a PyObjectType.
string autoInitializeMethods() {
    return q{
        static if(countUntil(slot, "tp_as_number") != -1) {
            if(type.tp_as_number is null) 
                type.tp_as_number = new PyNumberMethods;
        }else static if(countUntil(slot, "tp_as_sequence") != -1) {
            if(type.tp_as_sequence is null) 
                type.tp_as_sequence = new PySequenceMethods;
        }else static if(countUntil(slot, "tp_as_mapping") != -1) {
            if(type.tp_as_mapping is null) 
                type.tp_as_mapping = new PyMappingMethods;
        }
    };
}

private struct Guess{}

struct BinaryOperatorX(string _op, bool isR, rhs_t) {
    enum op = _op;
    enum isRight = isR;

    static if(isR) enum nom = "opBinaryRight";
    else enum nom = "opBinary";

    enum bool needs_shim = false;

    template Inner(C) {
        enum fn_str1 = "Alias!(C."~nom~"!(op))";
        enum fn_str2 = "C."~nom~"!(op,rhs_t)";
        enum string OP = op;
        static if(!__traits(hasMember, C, nom)) {
            static assert(0, C.stringof ~ " has no "~(isR ?"reflected ":"")~
                    "binary operator overloads");
        }
        template Alias(alias fn) {
            alias fn Alias;
        }
        static if(is(typeof(mixin(fn_str1)) == function)) {
            alias ParameterTypeTuple!(typeof(mixin(fn_str1)))[0] RHS_T;
            alias ReturnType!(typeof(mixin(fn_str1))) RET_T;
            mixin("alias " ~ fn_str1 ~ " FN;");
            static if(!is(rhs_t == Guess))
                static assert(is(RHS_T == rhs_t), 
                        Format!("expected typeof(rhs) = %s, found %s", 
                            rhs.stringof, RHS_T.stringof));
        }else static if(is(rhs_t == Guess)) {
            static assert(false, 
                    Format!("Operator %s: Cannot determine type of rhs", op));
        } else static if(is(typeof(mixin(fn_str2)) == function)) {
            alias rhs_t RHS_T;
            alias ReturnType!(typeof(mixin(fn_str2))) RET_T;
            mixin("alias "~fn_str2~" FN;");
        } else static assert(false, "Cannot get operator overload");
    }

    static void call(T)() {
        // can't handle __op__ __rop__ pairs here
    }

    template shim(size_t i, T) {
        // bah
        enum shim = "";
    }
}

/**
Wrap a binary operator overload. 

Example:
---
class Foo{
    int _j;
    int opBinary(string op)(int i) if(op == "+"){
        return i+_j;
    }
    int opBinaryRight(string op)(int i) if(op == "+"){
        return i+_j;
    }
}

class_wrap!(Foo,
    OpBinary!("+"),
    OpBinaryRight!("+"));
---

Params:
    op = Operator to wrap
    rhs_t = (optional) Type of opBinary's parameter for disambiguation if 
    there are multiple overloads. 
Bugs:
    Issue 8602 prevents disambiguation for case X opBinary(string op, T)(T t);
  */
template OpBinary(string op, rhs_t = Guess) if(IsPyBinary(op) && op != "in"){
    alias BinaryOperatorX!(op, false, rhs_t) OpBinary;
}

/// ditto
template OpBinaryRight(string op, lhs_t = Guess) if(IsPyBinary(op)) {
    alias BinaryOperatorX!(op, true, lhs_t) OpBinaryRight;
}

/**
  Wrap a unary operator overload.
*/
struct OpUnary(string _op) if(IsPyUnary(_op)) {
    enum op = _op;
    enum bool needs_shim = false;

    template Inner(C) {
        enum string OP = op;
        static if(!__traits(hasMember, C, "opUnary")) {
            static assert(0, C.stringof ~ " has no unary operator overloads");
        }
        static if(is(typeof(C.init.opUnary!(op)) == function)) {
            alias ReturnType!(C.opUnary!(op)) RET_T;
            alias C.opUnary!(op) FN;
        } else static assert(false, "Cannot get operator overload");
    }
    static void call(T)() {
        alias wrapped_class_type!T type;
        enum slot = unaryslots[op];
        mixin(autoInitializeMethods());
        mixin(slot ~ " = &opfunc_unary_wrap!(T, Inner!T .FN).func;");
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

/**
  Wrap an operator assignment overload.

Example:
---
class Foo{
    int _j;
    void opOpAssign(string op)(int i) if(op == "+"){
        _j = i;
    }
}

class_wrap!(Foo,
    OpAssign!("+"));
---
Params:
    op = Base operator to wrap
    rhs_t = (optional) Type of opOpAssign's parameter for disambiguation if 
    there are multiple overloads. 
*/
struct OpAssign(string _op, rhs_t = Guess) if(IsPyAsg(_op)) {
    enum op = _op~"=";

    enum bool needs_shim = false;

    template Inner(C) {
        enum string OP = op;
        static if(!__traits(hasMember, C, "opOpAssign")) {
            static assert(0, C.stringof ~ " has no operator assignment overloads");
        }
        static if(is(typeof(C.init.opOpAssign!(_op)) == function)) {
            alias ParameterTypeTuple!(typeof(C.opOpAssign!(_op)))[0] RHS_T;
            alias ReturnType!(typeof(C.opOpAssign!(_op))) RET_T;
            alias C.opOpAssign!(_op) FN;
            static if(!is(rhs_t == Guess))
                static assert(is(RHS_T == rhs_t), 
                        Format!("expected typeof(rhs) = %s, found %s", 
                            rhs.stringof, RHS_T.stringof));
        }else static if(is(rhs_t == Guess)) {
            static assert(false, "Cannot determine type of rhs");
        } else static if(is(typeof(C.opOpAssign!(_op,rhs_t)) == function)) {
            alias rhs_t RHS_T;
            alias ReturnType!(typeof(C.opOpAssign!(_op,rhs_t))) RET_T;
            alias C.opOpAssign!(_op,rhs_t) FN;
        } else static assert(false, "Cannot get operator assignment overload");
    }
    static void call(T)() {
        alias wrapped_class_type!T type;
        enum slot = binaryslots[op];
        mixin(autoInitializeMethods());
        alias CW!(TypeTuple!(OpAssign)) OpAsg;
        alias CW!(TypeTuple!()) Nop;
        static if(op == "^^=")
            mixin(slot ~ " = &powopasg_wrap!(T, Inner!T.FN).func;");
        else
            mixin(slot ~ " = &binopasg_wrap!(T, Inner!T.FN).func;");
    }

    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

// struct types could probably take any parameter type
// class types must take Object
/**
  Wrap opCmp.

Params:
    rhs_t = (optional) Type of opCmp's parameter for disambiguation if there
    are multiple overloads (for classes it will always be Object).
  */
struct OpCompare(_rhs_t = Guess) {
    enum bool needs_shim = false;


    template Inner(C) {
        static if(is(_rhs_t == Guess) && is(C == class)) {
            alias Object rhs_t;
        }else {
            alias _rhs_t rhs_t;
        }
        static if(!__traits(hasMember, C, "opCmp")) {
            static assert(0, C.stringof ~ " has no comparison operator overloads");
        }
        static if(!is(typeof(C.init.opCmp) == function)) {
            static assert(0, Format!("why is %s.opCmp not a function?",C));
        }
        alias TypeTuple!(__traits(getOverloads, C, "opCmp")) Overloads;
        static if(is(rhs_t == Guess) && Overloads.length > 1) {
            static assert(0, Format!("Cannot choose between %s", Overloads));
        }else static if(Overloads.length == 1) {
            static if(!is(rhs_t == Guess) &&
                !is(ParameterTypeTuple!(Overloads[0])[0] == rhs_t)) {
                static assert(0, Format!("%s.opCmp: expected param %s, got %s",
                            C, rhs_t, ParameterTypeTuple!(Overloads[0])));
            }else{
                alias Overloads[0] FN;
            }
        }else{
            template IsDesiredOverload(alias fn) {
                enum bool IsDesiredOverload = is(ParameterTypeTuple!(fn)[0] == rhs_t);
            }
            alias Filter!(IsDesiredOverload, Overloads) Overloads1;
            static assert(Overloads1.length == 1, 
                    Format!("Cannot choose between %s", Overloads1));
            alias Overloads1[0] FN;
        }
    }
    static void call(T)() {
        alias wrapped_class_type!T type;
        type.tp_richcompare = &rich_opcmp_wrap!(T, Inner!T.FN).func;
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

/**
  Wrap opIndex, opIndexAssign.

Params:
    index_t = (optional) Types of opIndex's parameters for disambiguation if
    there are multiple overloads.
*/
struct OpIndex(index_t...) {
    enum bool needs_shim = false;
    template Inner(C) {
        static if(!__traits(hasMember, C, "opIndex")) {
            static assert(0, C.stringof ~ " has no index operator overloads");
        }
        static if(is(typeof(C.init.opIndex) == function)) {
            alias TypeTuple!(__traits(getOverloads, C, "opIndex")) Overloads;
            static if(index_t.length == 0 && Overloads.length > 1) {
                static assert(0, 
                        Format!("%s.opIndex: Cannot choose between %s",
                            C.stringof,Overloads.stringof));
            }else static if(index_t.length == 0) {
                alias Overloads[0] FN;
            }else{
                template IsDesiredOverload(alias fn) {
                    enum bool IsDesiredOverload = is(ParameterTypeTuple!fn == index_t);
                }
                alias Filter!(IsDesiredOverload, Overloads) Overloads1;
                static assert(Overloads1.length == 1, 
                        Format!("%s.opIndex: Cannot choose between %s",
                            C.stringof,Overloads1.stringof));
                alias Overloads1[0] FN;
            }
        }else static if(is(typeof(C.init.opIndex!(index_t)) == function)) {
            alias C.opIndex!(index_t) FN;
        }else{
            static assert(0, 
                    Format!("cannot get a handle on %s.opIndex", C.stringof));
        }
    }
    static void call(T)() {
        /*
        alias wrapped_class_type!T type;
        enum slot = "type.tp_as_mapping.mp_subscript";
        mixin(autoInitializeMethods());
        mixin(slot ~ " = &opindex_wrap!(T, Inner!T.FN).func;");
        */
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

/// ditto
struct OpIndexAssign(index_t...) {
    static assert(index_t.length != 1, 
            "opIndexAssign must have at least 2 parameters");
    enum bool needs_shim = false;
    template Inner(C) {
        static if(!__traits(hasMember, C, "opIndexAssign")) {
            static assert(0, C.stringof ~ " has no index operator overloads");
        }
        static if(is(typeof(C.init.opIndex) == function)) {
            alias TypeTuple!(__traits(getOverloads, C, "opIndexAssign")) Overloads;
            template IsValidOverload(alias fn) {
                enum bool IsValidOverload = ParameterTypeTuple!fn.length >= 2;
            }
            alias Filter!(IsValidOverload, Overloads) VOverloads;
            static if(VOverloads.length == 0 && Overloads.length != 0)
                static assert(0,
                        "opIndexAssign must have at least 2 parameters");
            static if(index_t.length == 0 && VOverloads.length > 1) {
                static assert(0, 
                        Format!("%s.opIndexAssign: Cannot choose between %s",
                            C.stringof,VOverloads.stringof));
            }else static if(index_t.length == 0) {
                alias VOverloads[0] FN;
            }else{
                template IsDesiredOverload(alias fn) {
                    enum bool IsDesiredOverload = is(ParameterTypeTuple!fn == index_t);
                }
                alias Filter!(IsDesiredOverload, VOverloads) Overloads1;
                static assert(Overloads1.length == 1, 
                        Format!("%s.opIndex: Cannot choose between %s",
                            C.stringof,Overloads1.stringof));
                alias Overloads1[0] FN;
            }
        }else static if(is(typeof(C.init.opIndexAssign!(index_t)) == function)) {
            alias C.opIndexAssign!(index_t) FN;
        }else{
            static assert(0, 
                    Format!("cannot get a handle on %s.opIndexAssign", C.stringof));
        }
    }
    static void call(T)() {
        /*
        alias wrapped_class_type!T type;
        enum slot = "type.tp_as_mapping.mp_ass_subscript";
        mixin(autoInitializeMethods());
        mixin(slot ~ " = &opindexassign_wrap!(T, Inner!T.FN).func;");
        */
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

/**
  Wrap opSlice.

  Requires signature 
---
Foo.opSlice(Py_ssize_t, Py_ssize_t);
---
 This is a limitation of the C/Python API.
  */
struct OpSlice() {
    enum bool needs_shim = false;
    template Inner(C) {
        static if(!__traits(hasMember, C, "opSlice")) {
            static assert(0, C.stringof ~ " has no slice operator overloads");
        }
        static if(is(typeof(C.init.opSlice) == function)) {
            alias TypeTuple!(__traits(getOverloads, C, "opSlice")) Overloads;
            template IsDesiredOverload(alias fn) {
                enum bool IsDesiredOverload = is(ParameterTypeTuple!fn == 
                        TypeTuple!(Py_ssize_t,Py_ssize_t));
            }
            alias Filter!(IsDesiredOverload, Overloads) Overloads1;
            static assert(Overloads1.length != 0, 
                    Format!("%s.opSlice: must have overload %s",
                        C.stringof,TypeTuple!(Py_ssize_t,Py_ssize_t).stringof));
            static assert(Overloads1.length == 1, 
                    Format!("%s.opSlice: cannot choose between %s",
                        C.stringof,Overloads1.stringof));
            alias Overloads1[0] FN;
        }else{
            static assert(0, Format!("cannot get a handle on %s.opSlice",
                        C.stringof));
        }
    }
    static void call(T)() {
        /*
        alias wrapped_class_type!T type;
        enum slot = "type.tp_as_sequence.sq_slice";
        mixin(autoInitializeMethods());
        mixin(slot ~ " = &opslice_wrap!(T, Inner!T.FN).func;");
        */
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

/**
  Wrap opSliceAssign.

  Requires signature 
---
Foo.opSliceAssign(Value,Py_ssize_t, Py_ssize_t);
---
 This is a limitation of the C/Python API.
  */
struct OpSliceAssign(rhs_t = Guess) {
    enum bool needs_shim = false;
    template Inner(C) {
        static if(!__traits(hasMember, C, "opSliceAssign")) {
            static assert(0, C.stringof ~ " has no slice assignment operator overloads");
        }
        static if(is(typeof(C.init.opSliceAssign) == function)) {
            alias TypeTuple!(__traits(getOverloads, C, "opSliceAssign")) Overloads;
            template IsDesiredOverload(alias fn) {
                alias ParameterTypeTuple!fn ps;
                enum bool IsDesiredOverload = 
                    is(ps[1..3] == TypeTuple!(Py_ssize_t,Py_ssize_t));
            }
            alias Filter!(IsDesiredOverload, Overloads) Overloads1;
            static assert(Overloads1.length != 0, 
                    Format!("%s.opSliceAssign: must have overload %s",
                        C.stringof,TypeTuple!(Guess,Py_ssize_t,Py_ssize_t).stringof));
            static if(is(rhs_t == Guess)) {
                static assert(Overloads1.length == 1, 
                        Format!("%s.opSliceAssign: cannot choose between %s",
                            C.stringof,Overloads1.stringof));
                alias Overloads1[0] FN;
            }else{
                template IsDesiredOverload2(alias fn) {
                    alias ParameterTypeTuple!fn ps;
                    enum bool IsDesiredOverload2 = is(ps[0] == rhs_t);
                }
                alias Filter!(IsDesiredOverload2, Overloads1) Overloads2;
                static assert(Overloads2.length == 1, 
                        Format!("%s.opSliceAssign: cannot choose between %s",
                            C.stringof,Overloads2.stringof));
                alias Overloads2[0] FN;
            }
        }else{
            static assert(0, Format!("cannot get a handle on %s.opSlice",
                        C.stringof));
        }
    }
    static void call(T)() {
        /*
        alias wrapped_class_type!T type;
        enum slot = "type.tp_as_sequence.sq_ass_slice";
        mixin(autoInitializeMethods());
        mixin(slot ~ " = &opsliceassign_wrap!(T, Inner!T.FN).func;");
        */
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

/**
  wrap opCall. The parameter types of opCall must be specified.
*/
struct OpCall(Args_t...) {
    enum bool needs_shim = false;

    template Inner(T) {
        alias TypeTuple!(__traits(getOverloads, T, "opCall")) Overloads;
        template IsDesiredOverload(alias fn) {
            alias ParameterTypeTuple!fn ps;
            enum bool IsDesiredOverload = is(ps == Args_t);
        }
        alias Filter!(IsDesiredOverload, Overloads) VOverloads;
        static if(VOverloads.length == 0) {
            static assert(0,
                    Format!("%s.opCall: cannot find signature %s", T.stringof, 
                        Args_t.stringof));
        }else static if(VOverloads.length == 1){
            alias VOverloads[0] FN;
        }else static assert(0,
                Format!("%s.%s: cannot choose between %s", T.stringof, nom,
                    VOverloads.stringof));
    }
    static void call(T)() {
        alias wrapped_class_type!T type;
        alias Inner!T.FN fn;
        type.tp_call = &opcall_wrap!(T, Inner!T.FN).func;
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}

/**
  Wraps Foo.length or another function as python's ___len__ function. 

  Requires signature 
---
Py_ssize_t length();
---
  This is a limitation of the C/Python API.
  */
template Len() {
    alias _Len!() Len;
}

/// ditto
template Len(alias fn) {
    alias _Len!(fn) Len;
}

struct _Len(fnt...) {
    enum bool needs_shim = false;
    template Inner(T) {
        static if(fnt.length == 0) {
            enum nom = "length";
        }else{
            enum nom = __traits(identifier, fnt[0]);
        }
        alias TypeTuple!(__traits(getOverloads, T, nom)) Overloads;
        template IsDesiredOverload(alias fn) {
            alias ParameterTypeTuple!fn ps;
            alias ReturnType!fn rt;
            enum bool IsDesiredOverload = isImplicitlyConvertible!(rt,Py_ssize_t) && ps.length == 0;
        }
        alias Filter!(IsDesiredOverload, Overloads) VOverloads;
        static if(VOverloads.length == 0 && Overloads.length != 0) {
            static assert(0,
                    Format!("%s.%s must have signature %s", T.stringof, nom,
                        (Py_ssize_t function()).stringof));
        }else static if(VOverloads.length == 1){
            alias VOverloads[0] FN;
        }else static assert(0,
                Format!("%s.%s: cannot choose between %s", T.stringof, nom,
                    VOverloads.stringof));
    }
    static void call(T)() {
        alias wrapped_class_type!T type;
        enum slot = "type.tp_as_sequence.sq_length";
        mixin(autoInitializeMethods());
        mixin(slot ~ " = &length_wrap!(T, Inner!T.FN).func;");
    }
    template shim(size_t i,T) {
        // bah
        enum shim = "";
    }
}


template param1(C) { 
    template param1(T) {alias ParameterTypeTuple!(T.Inner!C .FN)[0] param1; }
}

alias Pred!q{__traits(hasMember, A,"op")} IsOp;
alias Pred!q{A.stringof.startsWith("OpUnary!")} IsUn;
template IsBin(T...) {
    static if(T[0].stringof.startsWith("BinaryOperatorX!")) 
        enum bool IsBin = !T[0].isRight;
    else
        enum bool IsBin = false;
}
template IsBinR(T...) {
    static if(T[0].stringof.startsWith("BinaryOperatorX!")) 
        enum IsBinR = T[0].isRight;
    else
        enum IsBinR = false;
}

// handle all operator overloads. Ops must only contain operator overloads.
struct Operators(Ops...) {
    enum bool needs_shim = false;

    template BinOp(string op, T) {
        alias Pred!(Replace!(q{A.op == "OP"},"OP",op)) IsThisOp;
        alias Filter!(IsThisOp, Ops) Ops0;
        alias Filter!(IsBin, Ops0) OpsL;
        alias staticMap!(param1!T, OpsL) OpsLparams;
        static assert(OpsL.length <= 1, 
                Replace!("Cannot overload $T1 $OP x with types $T2", 
                    "$OP", op, "$T1", T.stringof, "$T2",  OpsLparams.stringof));
        alias Filter!(IsBinR, Ops0) OpsR;
        alias staticMap!(param1, OpsR) OpsRparams;
        static assert(OpsR.length <= 1, 
                Replace!("Cannot overload x $OP $T1 with types $T2", 
                    "$OP", op, "$T1", T.stringof, "$T2",  OpsRparams.stringof));
        static assert(op[$-1] != '=' || OpsR.length == 0, 
                "Cannot reflect assignment operator");

        static void call() {
            static if(OpsL.length + OpsR.length != 0) {
                alias wrapped_class_type!T type;
                enum slot = binaryslots[op];
                mixin(autoInitializeMethods());
                static if(op == "in") {
                    mixin(slot ~ " = &inop_wrap!(T, CW!OpsL, CW!OpsR).func;");
                }else static if(op == "^^" || op == "^^=") {
                    mixin(slot ~ " = &powop_wrap!(T, CW!OpsL, CW!OpsR).func;");
                }else {
                    mixin(slot ~ " = &binop_wrap!(T, CW!OpsL, CW!OpsR).func;");
                }
            }
        }

    }
    struct UnOp(string op, T) {
        alias Pred!(Replace!(q{A.op == "OP"},"OP",op)) IsThisOp;
        alias Filter!(IsUn, Filter!(IsThisOp, Ops)) Ops1;
        static assert(Ops1.length <= 1, 
                Replace!("Cannot have overloads of $OP$T1", 
                    "$OP", op, "$T1", T.stringof));
        static void call() {
            static if(Ops1.length != 0) {
                alias wrapped_class_type!T type;
                alias Ops1[0] Ops1_0;
                alias Ops1_0.Inner!T .FN fn;
                enum slot = unaryslots[op];
                mixin(autoInitializeMethods());
                mixin(slot ~ " = &opfunc_unary_wrap!(T, fn).func;");
            }
        }
    }

    static void call(T)() {
        alias NoDuplicates!(staticMap!(Pred!"A.op", Ops)) str_op_tuple;
        enum binops = binaryslots.keys();
        foreach(_op; str_op_tuple) {
            BinOp!(_op, T).call(); // noop if op is unary
            UnOp!(_op, T).call(); // noop if op is binary
        }
    }
}

struct Constructors(Ctors...) {
    enum bool needs_shim = true;

    static void call(T, Shim)() {
        alias wrapped_class_type!T type;
        static if(Ctors.length) {
            type.tp_init = &wrapped_ctors!(T, Shim, Ctors).func;
        }else {
            // If a ctor wasn't supplied, try the default.
            // If the default ctor isn't available, and no ctors were supplied,
            // then this class cannot be instantiated from Python.
            // (Structs always use the default ctor.)
            static if (is(typeof(new T))) {
                static if (is(T == class)) {
                    type.tp_init = &wrapped_init!(Shim).init;
                } else {
                    type.tp_init = &wrapped_struct_init!(T).init;
                }
            }
        }
    }
}

template IsDef(string pyname) {
    template IsDef(Params...) {
        static if(Params[0].stringof.startsWith("Def!") && 
                __traits(hasMember,Params[0], "funcname")) {
            enum bool IsDef = (Params[0].funcname == pyname);
        }else{
            enum bool IsDef = false;
        }
    }
}
struct Iterator(Params...) {
    alias Filter!(IsDef!"__iter__", Params) Iters;
    alias Filter!(IsDef!"next", Params) Nexts;
    enum bool needs_shim = false;
    static void call(T)() {
        alias wrapped_class_type!T type;
        static if(Iters.length == 1 && Nexts.length == 1) {
            version(Python_3_0_Or_Later) {
            }else{
                type.tp_flags |= Py_TPFLAGS_HAVE_ITER;
            }
            type.tp_iter = &opiter_wrap!(T, Iters[0].func).func;
            type.tp_iternext = &opiter_wrap!(T, Nexts[0].func).func;
        }
    }
}

template IsOpIndex(P...) {
    enum bool IsOpIndex = P[0].stringof.startsWith("OpIndex!");
}
template IsOpIndexAssign(P...) {
    enum bool IsOpIndexAssign = P[0].stringof.startsWith("OpIndexAssign!");
}
template IsOpSlice(P...) {
    enum bool IsOpSlice = P[0].stringof.startsWith("OpSlice!");
}
template IsOpSliceAssign(P...) {
    enum bool IsOpSliceAssign = P[0].stringof.startsWith("OpSliceAssign!");
}
template IsLen(P...) {
    enum bool IsLen = P[0].stringof.startsWith("Len!");
}
/*
   Extended slice syntax goes through mp_subscript, mp_ass_subscript,
   not sq_slice, sq_ass_slice.

TODO: Python's extended slicing is more powerful than D's. We should expose
this.
*/
struct IndexSliceMerge(Params...) {
    alias Filter!(IsOpIndex, Params) OpIndexs;
    alias Filter!(IsOpIndexAssign, Params) OpIndexAssigns;
    alias Filter!(IsOpSlice, Params) OpSlices;
    alias Filter!(IsOpSliceAssign, Params) OpSliceAssigns;
    alias Filter!(IsLen, Params) Lens;

    static assert(OpIndexs.length <= 1);
    static assert(OpIndexAssigns.length <= 1);
    static assert(OpSlices.length <= 1);
    static assert(OpSliceAssigns.length <= 1);

    static void call(T)() {
        alias wrapped_class_type!T type;
        static if(OpIndexs.length + OpSlices.length) {
            {
                enum slot = "type.tp_as_mapping.mp_subscript";
                mixin(autoInitializeMethods());
                mixin(slot ~ " = &op_func!(T);");
            }
        }
        static if(OpIndexAssigns.length + OpSliceAssigns.length) {
            {
                enum slot = "type.tp_as_mapping.mp_ass_subscript";
                mixin(autoInitializeMethods());
                mixin(slot ~ " = &ass_func!(T);");
            }
        }
    }


    static extern(C) PyObject* op_func(T)(PyObject* self, PyObject* key) {
        static if(OpIndexs.length) {
            version(Python_2_5_Or_Later) {
                if(!PyIndex_Check(key)) goto slice;
                Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
            }else{
                if(!PyInt_Check(key)) goto slice;
                C_long i = PyLong_AsLong(key);
            }
            if(i == -1 && PyErr_Occurred()) {
                return null;
            }
            alias OpIndexs[0] OpIndex0;
            return opindex_wrap!(T, OpIndex0.Inner!T.FN).func(self, key);
        }
slice:
        static if(OpSlices.length) {
            if(PySlice_Check(key)) {
                Py_ssize_t len = PyObject_Length(self);
                Py_ssize_t start, stop, step, slicelength;
                if(PySlice_GetIndicesEx(key, len,
                            &start, &stop, &step, &slicelength) < 0) {
                    return null;
                }
                if(step != 1) {
                    PyErr_SetString(PyExc_TypeError, 
                            "slice steps not supported in D");
                    return null;
                }
                alias OpSlices[0] OpSlice0;
                return opslice_wrap!(T, OpSlice0.Inner!T.FN).func(
                        self, start, stop);
            }
        }
        PyErr_SetString(PyExc_TypeError, format(
                    "index type '%s' not supported\0", to!string(key.ob_type.tp_name)).ptr);
        return null;
    }

    static extern(C) int ass_func(T)(PyObject* self, PyObject* key, 
            PyObject* val) {
        static if(OpIndexAssigns.length) {
            version(Python_2_5_Or_Later) {
                if(!PyIndex_Check(key)) goto slice;
                Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
            }else{
                if(!PyInt_Check(key)) goto slice;
                C_long i = PyLong_AsLong(key);
            }
            if(i == -1 && PyErr_Occurred()) {
                return -1;
            }
            alias OpIndexAssigns[0] OpIndexAssign0;
            return opindexassign_wrap!(T, OpIndexAssign0.Inner!T.FN).func(
                    self, key, val);
        }
slice:
        static if(OpSliceAssigns.length) {
            if(PySlice_Check(key)) {
                Py_ssize_t len = PyObject_Length(self);
                Py_ssize_t start, stop, step, slicelength;
                if(PySlice_GetIndicesEx(key, len,
                            &start, &stop, &step, &slicelength) < 0) {
                    return -1;
                }
                if(step != 1) {
                    PyErr_SetString(PyExc_TypeError, 
                            "slice steps not supported in D");
                    return -1;
                }
                alias OpSliceAssigns[0] OpSliceAssign0;
                return opsliceassign_wrap!(T, OpSliceAssign0.Inner!T.FN).func(
                        self, start, stop, val);
            }
        }
        PyErr_SetString(PyExc_TypeError, format(
                    "assign index type '%s' not supported\0", to!string(key.ob_type.tp_name)).ptr);
        return -1;
    }
}

/*
Params: each param is a Type which supports the interface

Param.needs_shim == false => Param.call!(T)
or 
Param.needs_shim == true => Param.call!(T, Shim)

    performs appropriate mutations to the PyTypeObject

Param.shim!(i,T) for i : Params[i] == Param

    generates a string to be mixed in to Shim type

where T is the type being wrapped, Shim is the wrapped type

*/

/**
  Wrap a class.

Params:
    T = The class being wrapped.
    Params = Mixture of definitions of members of T to be wrapped and 
    optional arguments. 
    Concerning optional arguments, accepts PyName!(pyname), ModuleName!(modulename), and Docstring!(docstring).
    pyname = The name of the class as it will appear in Python. Defaults to 
    T's name in D
    modulename = The name of the python module in which the wrapped class 
            resides. Defaults to "".
    docstring = The class's docstring. Defaults to "".
  */
void wrap_class(T, Params...)() {
    alias Args!("","", __traits(identifier,T), "",Params) args;
    _wrap_class!(T, args.pyname, args.docstring, args.modulename, args.rem).wrap_class();
}
template _wrap_class(_T, string name, string docstring, string modulename, Params...) {
    import std.conv;
    import util.typelist;
    static if (is(_T == class)) {
        pragma(msg, "wrap_class: " ~ name);
        alias pyd.make_wrapper.make_wrapper!(_T, Params).wrapper shim_class;
        //alias W.wrapper shim_class;
        alias _T T;
    } else {
        pragma(msg, "wrap_struct: '" ~ name ~ "'");
        alias void shim_class;
        alias _T* T;
    }
    void wrap_class() {
        if(!Pyd_Module_p(modulename)) {
            if(should_defer_class_wrap(modulename, name)) {
                defer_class_wrap(modulename, name,  toDelegate(&wrap_class));
                return;
            }
        }
        alias wrapped_class_type!(T) type;
        init_PyTypeObject!T(type);

        foreach (param; Params) {
            static if (param.needs_shim) {
                param.call!(T, shim_class)();
            } else {
                param.call!(T)();
            }
        }

        assert(Pyd_Module_p(modulename) !is null, "Must initialize module '" ~ modulename ~ "' before wrapping classes.");
        string module_name = to!string(PyModule_GetName(Pyd_Module_p(modulename)));

        //////////////////
        // Basic values //
        //////////////////
        Py_SET_TYPE(&type, &PyType_Type);
        type.tp_basicsize = (wrapped_class_object!(T)).sizeof;
        type.tp_doc       = (docstring ~ "\0").ptr;
        version(Python_3_0_Or_Later) {
            type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
        }else{
            type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES;
        }
        //type.tp_repr      = &wrapped_repr!(T).repr;
        type.tp_methods   = wrapped_method_list!(T).ptr;
        type.tp_name      = (module_name ~ "." ~ name ~ "\0").ptr;

        /////////////////
        // Inheritance //
        /////////////////
        // Inherit classes from their wrapped superclass.
        static if (is(T B == super)) {
            foreach (C; B) {
                static if (is(C == class) && !is(C == Object)) {
                    if (is_wrapped!(C)) {
                        type.tp_base = &wrapped_class_type!(C);
                    }
                }
            }
        }

        ////////////////////////
        // Operator overloads //
        ////////////////////////

        Operators!(Filter!(IsOp, Params)).call!T();
        // its just that simple.

        IndexSliceMerge!(Params).call!T();
        // indexing and slicing aren't exactly simple.

        //////////////////////////
        // Constructor wrapping //
        //////////////////////////
        Constructors!(Filter!(IsInit, Params)).call!(T, shim_class)();

        //////////////////////////
        // Iterator wrapping    //
        //////////////////////////
        Iterator!(Params).call!(T)();
    

        //////////////////
        // Finalization //
        //////////////////
        if (PyType_Ready(&type) < 0) {
            throw new Exception("Couldn't ready wrapped type!");
        }
        Py_INCREF(cast(PyObject*)&type);
        PyModule_AddObject(Pyd_Module_p(modulename), (name~"\0").ptr, cast(PyObject*)&type);

        is_wrapped!(T) = true;
        static if (is(T == class)) {
            is_wrapped!(shim_class) = true;
            wrapped_classes[T.classinfo] = &type;
            wrapped_classes[shim_class.classinfo] = &type;
        }
    }
}

//-////////////////////
// PYD API FUNCTIONS //
//-////////////////////

// If the passed D reference has an existing Python object, return a borrowed
// reference to it. Otherwise, return null.
PyObject_BorrowedRef* get_existing_reference(T) (T t) {
    static if (is(T == class)) {
        auto range = wrapped_gc_objects.equalRange(cast(void*) t);
        if(range.empty) return null;
        return borrowed(range.front.py);
    } else {
        auto range = wrapped_gc_references!(T).equalRange(t);
        if(range.empty) return null;
        return borrowed(range.front.py);
    }
}

// Drop the passed D reference from the pool of held references.
void drop_reference(T) (T t) {
    static if (is(T == class)) {
        wrapped_gc_objects.removeKey(cast(void*)t);
    } else {
        wrapped_gc_references!(T).removeKey(t);
    }
}

// Add the passed D reference to the pool of held references.
void add_reference(T) (T t, PyObject* o) {
    static if (is(T == class)) {
        wrapped_gc_objects.insert(D2Py(cast(void*)t, o));
    } else {
        wrapped_gc_references!(T).insert(Dt2Py!T(t, o));
    }
}

PyObject* WrapPyObject_FromObject(T) (T t) {
    return WrapPyObject_FromTypeAndObject(&wrapped_class_type!(T), t);
}

/*
 * Returns a new Python object of a wrapped type.
 */
PyObject* WrapPyObject_FromTypeAndObject(T) (PyTypeObject* type, T t) {
    //alias wrapped_class_object!(T) wrapped_object;
    //alias wrapped_class_type!(T) type;
    if (is_wrapped!(T)) {
        // If this object is already wrapped, get the existing object.
        PyObject_BorrowedRef* obj_p = get_existing_reference(t);
        if (obj_p) {
            return Py_INCREF(obj_p);
        }
        // Otherwise, allocate a new object
        PyObject* obj = type.tp_new(type, null, null);
        // Set the contained instance
        WrapPyObject_SetObj(obj, t);
        return obj;
    } else {
        PyErr_SetString(PyExc_RuntimeError, ("Type " ~ typeid(T).toString() ~ " is not wrapped by Pyd.").ptr);
        return null;
    }
}

/*
 * Returns the object contained in a Python wrapped type.
 */
T WrapPyObject_AsObject(T) (PyObject* _self) {
    alias wrapped_class_object!(T) wrapped_object;
    alias wrapped_class_type!(T) type;
    wrapped_object* self = cast(wrapped_object*)_self;
    if (!is_wrapped!(T)) {
        throw new Exception(format("Error extracting D object: Type %s is not wrapped.",typeid(T).toString()));
    }
    if (self is null) {
        throw new Exception("Error extracting D object: 'self' was null!");
    }
    static if (is(T == class)) {
        if (cast(Object)(self.d_obj) is null) {
            throw new Exception("Error extracting D object: Reference was not castable to Object!");
        }
        if (cast(T)cast(Object)(self.d_obj) is null) {
            throw new Exception(format("Error extracting D object: Object was not castable to type %s.",typeid(T).toString()));
        }
    }
    return self.d_obj;
}

/*
 * Sets the contained object in self to t.
 */
void WrapPyObject_SetObj(T) (PyObject* _self, T t) {
    alias wrapped_class_object!(T) obj;
    obj* self = cast(obj*)_self;
    if (t is self.d_obj) return;
    // Clean up the old object, if there is one
    if (self.d_obj !is null) {
        drop_reference(self.d_obj);
    }
    self.d_obj = t;
    // Handle the new one, if there is one
    if (t !is null) add_reference(self.d_obj, _self);
}