Source

pyobjc / pyobjc / Modules / objc / class-builder.m

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
/*
 * This file contains the code that is used to create proxy-classes for Python
 * classes in the objective-C runtime.
 */
#include <Python.h>
#include "pyobjc.h"
#include "objc_support.h"
#include <Foundation/NSInvocation.h>


/* We add 1 instance variable to hybrid objective-C/Python classes, this 
 * contains the reference to the python half of the class. Name should be 
 * not be used by Objective-C classes that are not managed by PyObjC... 
 */
static char pyobj_ivar[] = "__pyobjc_obj__";

/* List of instance variables, methods and class-methods that should not
 * be overridden from python
 */
static char* dont_override_methods[] = {
        pyobj_ivar,
	"alloc",
	"dealloc",
	"retain",
	"release",
	"autorelease",
	"retainCount",
	NULL
};

/* Special methods for Python subclasses of Objective-C objects */
static id class_method_alloc(id self, SEL sel);
static id class_method_allocWithZone(id self, SEL sel, NSZone* zone);

static id object_method_retain(id self, SEL sel);
static void object_method_release(id self, SEL sel);
static unsigned object_method_retainCount(id self, SEL sel);
static BOOL object_method_respondsToSelector(id self, SEL selector, 
	SEL aSelector);
static NSMethodSignature*  object_method_methodSignatureForSelector(id self, 
	SEL selector, SEL aSelector);
static void object_method_forwardInvocation(id self, SEL selector, 
	NSInvocation* invocation);


/*
 * When we create a 'Class' we actually create the struct below. This allows
 * us to add some extra information to the class defintion.
 */
struct class_wrapper {
	struct objc_class  class;
	struct objc_class  meta_class;
	PyObject*          python_class;
};

#define IDENT_CHARS "ABCDEFGHIJKLMNOPQSRTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"

/*
 * This function finds the superclass of the class where 'selector' is
 * overridden using 'currentImp'.
 *
 * This is needed to call the correct superclass implementation in case 
 * of multiple layers of subclassing in Python. If we don't find the 'real'
 * superclass, a call to 
 *   'objc_msgSendSuper({ self->isa->super_class, self }, ...)' will just 
 * transfer back to 'currentImp' if the method was called from a subclass (e.g.
 * if 'currentImp' is the IMP for the superclass of 'self->isa' instead of the
 * one from 'self'.
 *
 * The 'right' way to do this is by building closures (if done correctly it
 * would at least be faster), but that requires an external library or low-level
 * (assembly) trickery.
 */
static Class find_real_superclass(Class startAt, SEL selector, 
		Method (*find_method)(Class, SEL), IMP currentImp)
{
	Method m;
	Class  cur;

	cur = startAt;
	m = find_method(cur, selector);

	/* Skip to class containing this function */
	while (m == NULL || m->method_imp != currentImp) {
		cur = cur->super_class;
		if (!cur) abort();
		m = find_method(cur, selector);
	}

	/* Skip all classes containing this function */
	while (m != NULL && m->method_imp == currentImp) {
		cur = cur->super_class;
		if (!cur) abort();
		m = find_method(cur, selector);
	}

	/* We found the 'real' superclass */
	return cur;
}


/*
 * Return wether the object is (partially) implemented in python
 */
int ObjC_HasPythonImplementation(id obj)
{
	if (obj == nil) return 0;
	
	return (class_getInstanceVariable(obj->isa, pyobj_ivar) != NULL);
}

/*
 * Get the python half of the implementation.
 *
 * Returns a borrowed reference.
 */
PyObject* ObjC_GetPythonImplementation(id obj)
{
	PyObject* pyobj = NULL;
	Ivar      var   = NULL;

	if (obj == nil) {
		ObjCErr_Set(objc_internal_error,
			"ObjC_GetPythonImplementation called for <nil>");
		return NULL;
	}

	var = object_getInstanceVariable(obj, pyobj_ivar, (void**)&pyobj);
	if (var == NULL) {
		ObjCErr_Set(objc_internal_error,
			"ObjC_GetPythonImplementation called for "
			"normal object of class %s", obj->isa->name);
		return NULL;
	}
	if (pyobj == NULL) {
		return Py_None;
	}

	return pyobj;
}

static int
ObjC_SetPythonImplementation(id obj, PyObject* newval)
{
	Ivar      var   = NULL;

	if (obj == nil) {
		ObjCErr_Set(objc_internal_error,
			"ObjC_GetPythonImplementation called for <nil>");
		return -1;
	}

	var = class_getInstanceVariable(obj->isa, pyobj_ivar);
	if (var == NULL) {
		ObjCErr_Set(objc_internal_error,
			"ObjC_SetPythonImplementation called for "
			"normal object of class %s", obj->isa->name);
		return -1;
	}
	*(PyObject**)(((char*)obj)+var->ivar_offset) = newval;
	return 0;
}

/*
 * Last step of the construction a python subclass of an objective-C class.
 *
 * Set reference to the python half in the objective-C half of the class.
 *
 * Return 0 on success, -1 on failure.
 */
int ObjCClass_SetClass(Class objc_class, PyObject* py_class)
{
	if (objc_class == nil) {
		ObjCErr_Set(objc_internal_error, 
			"Trying to set class of <nil>\n", objc_class->name);
		return -1;
	}
	if (class_getInstanceVariable(objc_class, pyobj_ivar) == NULL) {
		ObjCErr_Set(objc_internal_error, 
			"Trying to set class of non-python %s", 
			objc_class->name);
		return -1;
	}
	if (py_class == NULL || !ObjCClass_Check(py_class)) {
		ObjCErr_Set(objc_internal_error,
			"Trying to set class to of %s to invalid value "
			"(type %s instead of %s)",
			objc_class->name, py_class->ob_type->tp_name,
			ObjCClass_Type.tp_name);
		return -1;
	}
	if (((struct class_wrapper*)objc_class)->python_class != NULL) {
		ObjCErr_Set(objc_internal_error,
			"Trying to set update PythonClass of %s",
			objc_class->name);
		return -1;
	}


	((struct class_wrapper*)objc_class)->python_class = py_class;
	Py_INCREF(py_class);

	objc_addClass(objc_class);
	return 0;
}

/*
 * Call this when the python half of the class could not be created. 
 *
 * Due to technical restrictions it is not allowed to unbuild a class that
 * is already registered with the Objective-C runtime.
 */
void ObjCClass_UnbuildClass(Class objc_class)
{
	struct class_wrapper* wrapper = (struct class_wrapper*)objc_class;

	if (objc_class == nil) {
		ObjCErr_Set(objc_internal_error, 
		"Trying to unregister class <nil>");
		return;
	}
	if (class_getInstanceVariable(objc_class, pyobj_ivar) == NULL) {
		ObjCErr_Set(objc_internal_error, 
			"Trying to unregister class %s, but it is not "
			"python based", 
			objc_class->name);
		return;
	}
	if (wrapper->python_class != NULL) {
		ObjCErr_Set(objc_internal_error,
			"Trying to unregister objective-C class %s, but it "
			"is already registered with the runtime",
			objc_class->name);
		return;
	}


	if (wrapper->class.methodLists) {
		if (wrapper->class.methodLists[0]) {
			free(wrapper->class.methodLists[0]);
		}
		free(wrapper->class.methodLists);
	}
	if (wrapper->meta_class.methodLists) {
		if (wrapper->meta_class.methodLists[0]) {
			free(wrapper->meta_class.methodLists[0]);
		}
		free(wrapper->meta_class.methodLists);
	}
	free((char*)(wrapper->class.name));
	free(objc_class);
}

/*
 * Find the signature of 'selector' in the list of protocols.
 */
static char*
find_protocol_signature(PyObject* protocols, SEL selector)
{
	int len;
	int i;

	if (!PyList_Check(protocols)) {
		ObjCErr_Set(objc_internal_error,
			"Protocol-list is not a list");
		return NULL;
	}

	len = PyList_Size(protocols);
	for (i = 0; i < len; i++) {
		PyObject* p;
		PyObject* info;
	
		p = PyList_GetItem(protocols, i);
		if (p == NULL) {
			PyErr_Clear();
			continue;
		}
		if (!ObjCInformalProtocol_Check(p)) continue;

		info = ObjCIPFindInfo(p, selector);
		if (info != NULL) {
			return ObjCSelector_Signature(info);
		}
	}
	return NULL;
}

/*
 * First step of creating a python subclass of an objective-C class
 *
 * Returns NULL or the newly created objective-C klass. 'class_dict' may
 * be modified by this function.
 *
 * TODO:
 * - Set 'sel_class' of ObjCPythonSelector instances
 * - This function complete ignores other base-classes, even though they
 *   might override methods. Need to check the MRO documentation to check
 *   if this is a problem. 
 * - It is a problem when the user tries to use mixins to define common
 *   methods (like a NSTableViewDataSource mixin).
 */
Class ObjCClass_BuildClass(Class super_class,  PyObject* protocols,
				char* name, PyObject* class_dict)
{
	PyObject*                key_list = NULL;
	PyObject*                key = NULL;
	PyObject*                value = NULL;
	int                      i, key_count;
	int	                 ivar_count = 0;
	int                      ivar_size  = 0;
	int                      meta_method_count = 0;
	int                      method_count = 0;
	int                      first_python_gen = 0;
	struct objc_ivar_list*   ivar_list = NULL;
	struct objc_method_list* method_list = NULL;
	struct objc_method_list* meta_method_list = NULL;
	struct class_wrapper*    new_class = NULL;
	Class                    root_class;
	char**                   curname;
	PyObject*		 py_superclass;


	/* XXX: May as well directly pass this in... */
	py_superclass = ObjCClass_New(super_class);
	if (py_superclass == NULL) return NULL;


	if (!PyList_Check(protocols)) {
		ObjCErr_Set(objc_internal_error, "%s", 
			"protocol list not a PyList");
		goto error_cleanup;
	}
	if (!PyDict_Check(class_dict)) {
		ObjCErr_Set(objc_internal_error, "%s", 
			"class dict not a PyDict");
		goto error_cleanup;
	}
	if (super_class == NULL) {
		ObjCErr_Set(objc_internal_error, "%s", 
			"must have super_class");
		goto error_cleanup;
	}

	if (objc_lookUpClass(name) != NULL) {
		ObjCErr_Set(objc_error, "class '%s' exists", name);
		goto error_cleanup;
	}
	if (strspn(name, IDENT_CHARS) != strlen(name)) {
		ObjCErr_Set(objc_error, "'%s' not a valid name", name);
		goto error_cleanup;
	}


	/* 
	 * Check for methods/variables that must not be overridden in python.
	 */
	for (curname = dont_override_methods; *curname != NULL; curname++) {
		key = PyDict_GetItemString(class_dict, *curname);
		if (key != NULL) {
			ObjCErr_Set(objc_error,
				"Cannot override %s from python", *curname);
			goto error_cleanup;
		}
	}

	key_list = PyDict_Keys(class_dict);
	if (key_list == NULL) {
		goto error_cleanup;
	}

	key_count = PyList_Size(key_list);
	if (PyErr_Occurred()) {
		Py_DECREF(key_list);
		goto error_cleanup;
	}


	if (class_getInstanceVariable(super_class, pyobj_ivar) == 0) {
		first_python_gen = 1;

		/* 
		 * This class has a super_class that is pure objective-C
		 * We'll add some instance variables and methods that are
		 * needed for the correct functioning of the class. 
		 *
		 * See the code below the next loop.
		 */
		ivar_count        += 1;
		meta_method_count += 2; 
		method_count      += 7;
	}

	/* First round, count new instance-vars and check for overridden 
	 * methods.
	 */
	for (i = 0; i < key_count; i++) {
		key = PyList_GetItem(key_list, i);
		if (PyErr_Occurred()) {
			PyErr_Clear();
			ObjCErr_Set(objc_internal_error,
				"Cannot fetch key in keylist");
			goto error_cleanup;
		}

		value = PyDict_GetItem(class_dict, key);
		if (value == NULL) {
			PyErr_Clear();
			ObjCErr_Set(objc_internal_error,
				"Cannot fetch item in keylist");
			goto error_cleanup;
		}

		if (ObjCIvar_Check(value)) {
			if (class_getInstanceVariable(super_class, 
					((ObjCIvar*)value)->name) != NULL) {
				ObjCErr_Set(objc_error,
					"Cannot replace instance variable %s",
					((ObjCIvar*)value)->name);
				goto error_cleanup;
			}

			ivar_count ++;
			ivar_size += objc_sizeof_type(((ObjCIvar*)value)->type);

		} else if (ObjCSelector_Check(value)) {
			ObjCSelector* sel = (ObjCSelector*)value;
			Method        meth;

			if (sel->sel_flags & ObjCSelector_kCLASS_METHOD) {
				meth = class_getClassMethod(super_class,
					sel->sel_selector);
				if (meth) {
					meta_method_count ++;
				}


			} else {
				meth = class_getInstanceMethod(super_class,
					sel->sel_selector);
				method_count ++;
			}

		} else if (PyMethod_Check(value) || PyFunction_Check(value)) {
			PyObject* pyname;
			char*     name;
			SEL	  selector;
			Method    meth;
			int       is_class_method = 0;

			pyname = PyObject_GetAttrString(value, "__name__");
			if (pyname == NULL) continue;

			name = PyString_AS_STRING(pyname);
			if (name[0] == '_' && name[1] == '_') {
				/* Skip special methods */
				continue;
			}

			selector = ObjCSelector_DefaultSelector(name);

			meth = class_getInstanceMethod(super_class, selector);
			if (!meth) {
				meth = class_getClassMethod(
						super_class, selector);
				if (meth) {
					is_class_method = 1;
				}
			}

			if (meth) {
				/* The function overrides a method in the 
				 * objective-C class, replace by a selector 
				 * object.
				 *
				 * Get the signature through the python wrapper,
				 * the user may have specified a more exact
				 * signature!
				 */
				PyObject* super_sel = ObjCClass_FindSelector(
					py_superclass, selector);
				if (!super_sel) goto error_cleanup;

				value = ObjCSelector_New(
					value, 
					selector, 
					ObjCSelector_Signature(super_sel),
					is_class_method);
				Py_DECREF(super_sel);
			} else {
				char* signature;

				signature = find_protocol_signature(
					protocols, selector);
				value = ObjCSelector_New(
					value, 
					selector, 
					signature,
					0);
			}
			if (value == NULL) goto error_cleanup;
				
			if (PyDict_SetItem(class_dict, key, value) < 0) {
				goto error_cleanup;
			}
			Py_DECREF(value); value = NULL;
			method_count++;
		}			
	}

	/* Allocate space for the new instance variables and methods */

	if (ivar_count == 0)  {
		ivar_list = NULL;
	} else {
		ivar_list = malloc(sizeof(struct objc_ivar_list) +
			(ivar_count)*sizeof(struct objc_ivar));
		if (ivar_list == NULL) {
			PyErr_NoMemory();
			goto error_cleanup;
		}
		ivar_list->ivar_count = 0;
	}

	if (method_count == 0) {
		method_list = NULL;
	} else {
		method_list = malloc(sizeof(struct objc_method_list) +
			(method_count)*sizeof(struct objc_method));
		if (method_list == NULL) {
			PyErr_NoMemory();
			goto error_cleanup;
		}
		memset(method_list, 0, sizeof(struct objc_method_list) +
			(method_count)*sizeof(struct objc_method));
		method_list->method_count      = 0;
		method_list->obsolete = NULL; /* DEBUG */
	}

	if (meta_method_count == 0) {
		meta_method_list = NULL;
	} else {
		meta_method_list = malloc(sizeof(struct objc_method_list)+
			(meta_method_count)*sizeof(struct objc_method));
		if (meta_method_list == NULL) {
			PyErr_NoMemory();
			goto error_cleanup;
		}
		memset(meta_method_list, 0, sizeof(struct objc_method_list)+
			(meta_method_count)*sizeof(struct objc_method));
		meta_method_list->method_count = 0;
		meta_method_list->obsolete = NULL; /* DEBUG */
	}


	/* And fill the method_lists and ivar_list */

	/* Create new_class here, just in case we are the first python
	 * generation, in which case we need to use new_class (it must just
	 * be there, it doesn't have to be initialized)
	 */
	new_class = calloc(1, sizeof(struct class_wrapper));
	if (new_class == NULL) {
		goto error_cleanup;
	}

	ivar_size = super_class->instance_size;

	if (first_python_gen) {
		/* Our parent is a pure Objective-C class, add our magic
		 * methods and variables 
		 */
		 
		Ivar var = ivar_list->ivar_list;
		Method meth;
		PyObject* sel;
		ivar_list->ivar_count++;

		var->ivar_name = pyobj_ivar;
		var->ivar_type = "^v";
		var->ivar_offset = ivar_size;
		ivar_size += sizeof(void*);

		/* XXX: Make these global lists instead of macros */

#		define META_METH(pyname, selector, types, imp) 		\
			meth = meta_method_list->method_list + 		\
				meta_method_list->method_count++;	\
			meth->method_name = selector;			\
			meth->method_types = types;			\
			meth->method_imp = (IMP)imp;			\
			sel = ObjCSelector_NewNative(&new_class->class, \
				selector,  types, 1);			\
			if (sel == NULL) goto error_cleanup;		\
			PyDict_SetItemString(class_dict, pyname, sel);	\
			Py_DECREF(sel)

#		define METH(pyname, selector, types, imp) 		\
			meth = method_list->method_list + 		\
				method_list->method_count++;		\
			meth->method_name = selector;			\
			meth->method_types = types;			\
			meth->method_imp = (IMP)imp;			\
			sel = ObjCSelector_NewNative(&new_class->class, \
				selector,  types, 0);			\
			if (sel == NULL) goto error_cleanup;		\
			PyDict_SetItemString(class_dict, pyname, sel);	\
			Py_DECREF(sel)
					

		META_METH("alloc", @selector(alloc), "@@:", class_method_alloc);
		META_METH("allocWithZone_", @selector(allocWithZone:), "@@:^{_NSZone=}", class_method_allocWithZone);

		METH("retain", @selector(retain), "@@:", object_method_retain);
		METH("release", @selector(release), "v@:", object_method_release);
		METH("retainCount", @selector(retainCount), "I@:", object_method_retainCount);
		METH("respondsToSelector_", @selector(respondsToSelector:), "c@::", 
			object_method_respondsToSelector);
		METH("methodSignatureForSelector_", @selector(methodSignatureForSelector:), "@@::", 
			object_method_methodSignatureForSelector);
		METH("forwardInvocation_", @selector(forwardInvocation:), "v@:@", 
			object_method_forwardInvocation);

#undef		METH
#undef		META_METH
	}

	for (i = 0; i < key_count; i++) {
		key = PyList_GetItem(key_list, i);
		if (key == NULL) {
			ObjCErr_Set(objc_internal_error,
				"Cannot fetch key in keylist");
			goto error_cleanup;
		}

		value = PyDict_GetItem(class_dict, key);
		if (value == NULL)  {
			ObjCErr_Set(objc_internal_error,
				"Cannot fetch item in keylist");
			goto error_cleanup;
		}

		if (ObjCIvar_Check(value)) {
			Ivar var;

			var = ivar_list->ivar_list + ivar_list->ivar_count;
			ivar_list->ivar_count++;

			var->ivar_name = ((ObjCIvar*)value)->name;
			var->ivar_type = ((ObjCIvar*)value)->type;
			var->ivar_offset = ivar_size;

			ivar_size += objc_sizeof_type(var->ivar_type);

		} else if (ObjCSelector_Check(value)) {
			ObjCSelector* sel = (ObjCSelector*)value;
			Method        meth;
			int           is_override = 0;
			struct objc_method_list* lst;

			if (sel->sel_flags & ObjCSelector_kCLASS_METHOD) {
				meth = class_getClassMethod(super_class,
					sel->sel_selector);
				if (!meth) continue;
				is_override = 1;
				lst = meta_method_list;
			} else {
				meth = class_getInstanceMethod(super_class,
					sel->sel_selector);
				if (meth) is_override = 1;
				lst = method_list;
			}

			meth = lst->method_list + lst->method_count;
			meth->method_name = sel->sel_selector;
			meth->method_types = sel->sel_signature;
		
			if (is_override) {
				meth->method_imp = 
					ObjC_FindIMP(super_class, 
						sel->sel_selector);
			} else {
				meth->method_imp = 
					ObjC_FindIMPForSignature(sel->sel_signature);

			}

			if (sel->sel_class == NULL) {
				sel->sel_class = &new_class->class;
			}

			if (meth->method_imp == NULL) {
				goto error_cleanup;
			}
			lst->method_count++;
		}
	}
	Py_DECREF(key_list);
	key_list = NULL;

	/* And now initialize the actual class... */

	root_class = super_class;
	while (root_class->super_class != NULL) {
		root_class = root_class->super_class;
	}

	new_class->python_class = NULL;
	new_class->class.methodLists = NULL;
	new_class->meta_class.methodLists = NULL;
	new_class->class.isa = &new_class->meta_class;
	new_class->class.info = CLS_CLASS;
	new_class->meta_class.info = CLS_META;

	new_class->class.name = strdup(name);
	new_class->meta_class.name = new_class->class.name;

	new_class->class.methodLists = 
		calloc(1, sizeof(struct objc_method_list*));
	if (new_class->class.methodLists == NULL) abort();
	new_class->class.methodLists[0] = NULL;

	new_class->meta_class.methodLists = 
		calloc(1, sizeof(struct objc_method_list*));
	if (new_class->meta_class.methodLists == NULL) abort();
	new_class->meta_class.methodLists[0] = NULL;

	new_class->class.super_class = super_class;
	new_class->meta_class.super_class = super_class->isa;
	new_class->meta_class.isa = root_class->isa;

	new_class->class.instance_size = ivar_size;
	new_class->class.ivars = ivar_list;

	/* Be explicit about clearing data, should not be necessary with
	 * 'calloc'
	 */
	new_class->class.cache = NULL;
	new_class->meta_class.cache = NULL;

	new_class->class.protocols = NULL;
	new_class->meta_class.protocols = NULL;

	if (method_list) {
		class_addMethods(&(new_class->class), method_list);
	}
	if (meta_method_list) {
		class_addMethods(&(new_class->meta_class), meta_method_list);
	}

	Py_XDECREF(py_superclass);

	/* 
	 * NOTE: Class is not registered yet, we do that as lately as possible
	 * because it is impossible to remove the registration from the
	 * objective-C runtime (at least on MacOS X).
	 */
	return (Class)new_class;

error_cleanup:
	Py_XDECREF(py_superclass);

	if (key_list != NULL) {
		Py_DECREF(key_list);
		key_list = NULL;
	}

	if (ivar_list) {
		free(ivar_list);
	}
	if (method_list) {
		free(method_list);
	}
	if (meta_method_list) {
		free(meta_method_list);
	}

	if (new_class != NULL) {
		if (new_class->class.methodLists) {
			free(new_class->class.methodLists);
		}
		if (new_class->meta_class.methodLists) {
			free(new_class->meta_class.methodLists);
		}
		if (new_class->class.name) {
			free((char*)(new_class->class.name));
		}
		free(new_class);
	}

	return NULL;
}

/*
 * Below here are implementations of various methods needed to correctly
 * subclass Objective-C classes from Python. 
 *
 * These are added to the new Objective-C class by  ObjCClass_BuildClass (but
 * only if the super_class is a 'pure' objective-C klass)
 *
 * The protocol for objc-python object-clusters is:
 * - +alloc calls [super alloc], then creates a new Python 'wrapper' for it
 *   (ObjCObject_New) and sets a pointer to that wrapper object in the 
 *   correct instance variable of the new object
 * - +allocWithZone: is implemented in a simular manner.
 * - the references from the python-side to the objective-c side and back
 *   do _not_ count in the reference-count of the cluster
 * - the reference-count is stored in the python-side
 * - deallocactie doen we eerst in python en dan in objective-C
 *
 * NOTE:
 * - These functions will be used as methods, but as far as the compiler
 *   knows these are normal functions. You cannot use [super call]s here.
 */

/*
 * +alloc
 */
static id class_method_alloc(id self, SEL sel)
{  
   /* NSObject documentation defines +alloc as 'allocWithZone:nil' */
   return class_method_allocWithZone(self, sel, nil);
}


/* +allocWithZone: */
static id class_method_allocWithZone(id self, SEL sel, NSZone* zone)
{
   PyObject* pyclass;
   ObjCObject* pyobject;
   id          obj;
   struct objc_super super;

   pyclass = ((struct class_wrapper*)self)->python_class;

   super.class = find_real_superclass((Class)self, @selector(allocWithZone:),
   	class_getClassMethod, (IMP)class_method_allocWithZone)->isa;
   super.receiver = self;

   obj = objc_msgSendSuper(&super, @selector(allocWithZone:), zone); 
   if (obj == nil) {
	   return nil;	
   }

   pyobject = (ObjCObject*)ObjCObject_New(obj);
   if (pyobject == NULL) {
       ObjCErr_ToObjC();
       return nil;
   }

   pyobject->is_paired = 1;

   /* obj->__pyobjc_obj__ = pyobjct */ 
   if (ObjC_SetPythonImplementation(obj, (PyObject*)pyobject) == -1) {
       Py_DECREF(pyobject);
       ObjCErr_ToObjC();
       return nil;
   }
   return obj;
}

/* -retain */
static id object_method_retain(id self, SEL sel)
{
	PyObject* pyself;

	pyself = ObjC_GetPythonImplementation(self);

	if (pyself == Py_None) {
		struct objc_super super;
		
   		super.class = find_real_superclass(self->isa, 
			@selector(retain), class_getInstanceMethod, 
			(IMP)object_method_retain);
		super.receiver = self;

		self = objc_msgSendSuper(&super, @selector(retain)); 
	} else if (pyself) {
		OC_CheckRevive(pyself);
		Py_INCREF(pyself);
	} else {
		PyErr_Clear();
	}

	return self;
}

/* -release */
static void object_method_release(id self, SEL sel)
{
	struct objc_super super;
	PyObject* obj;

	
	obj = ObjC_GetPythonImplementation(self);

	if (obj == NULL) {
		PyErr_Clear();
		return;
	} else if (obj == Py_None) {
   		super.class = find_real_superclass(self->isa, 
			@selector(release), class_getInstanceMethod, 
			(IMP)object_method_release);
		super.receiver = self;

		self = objc_msgSendSuper(&super, @selector(release)); 
		return;
	}

	if (obj->ob_refcnt <= 0) {
		
		/* Remove reference to the Python object. We don't need it
		 * any more (because the ObjCObject code will remove it 
		 * when this function returns) and [super release] may 
		 * call back to us some time later on ([NSWindow release] in
		 * a seperator thread).
		 */
		if (ObjC_SetPythonImplementation(self, 0) == -1) {
		       ObjCErr_ToObjC();
		       return;
		}

		/* [super release] */
   		super.class = find_real_superclass(self->isa, 
			@selector(release), class_getInstanceMethod, 
			(IMP)object_method_release);
		super.receiver = self;

		self = objc_msgSendSuper(&super, @selector(release)); 
		return;

	} else {
		/* If the reference count is 1, Py_DECREF causes a call
		 * to object_dealloc, which in turn calls back to us
		 * with a reference-count of 0.
		 */
		Py_DECREF(obj);
		return;
	} 

	return;
}

/* -retainCount */
static unsigned object_method_retainCount(id self, SEL sel)
{
	PyObject* obj = ObjC_GetPythonImplementation(self);

	if (obj == Py_None) {
		struct objc_super super;
		
   		super.class = find_real_superclass(self->isa, 
			@selector(retainCount), class_getInstanceMethod, 
			(IMP)object_method_retainCount);
		super.receiver = self;

		return (int)objc_msgSendSuper(&super, @selector(retainCount)); 
	}
	return obj->ob_refcnt;
}

/* -respondsToSelector: */
static BOOL 
object_method_respondsToSelector(id self, SEL selector, SEL aSelector)
{
	struct objc_super super;
	BOOL              res;
        PyObject*         pyself;
	PyObject*         pymeth;


	/* First check if we respond */
	pyself = ObjC_GetPythonImplementation(self);
	if (pyself == NULL) {
		return NO;
	}
	pymeth = ObjCObject_FindSelector(pyself, aSelector);
	if (pymeth) {
		Py_DECREF(pymeth);
		return YES;
	}
	PyErr_Clear();


	/* Check superclass */
	super.class = find_real_superclass(self->isa, 
			selector, class_getInstanceMethod, 
			(IMP)object_method_respondsToSelector);
	super.receiver = self;

	res = (int)objc_msgSendSuper(&super, selector, aSelector);

	return res;
}

/* -methodSignatureForSelector */
static NSMethodSignature*  
object_method_methodSignatureForSelector(id self, SEL selector, SEL aSelector)
{
	NSMethodSignature* result = nil;
	struct objc_super  super;
        PyObject*          pyself;
	PyObject*          pymeth;


	super.class = find_real_superclass(self->isa, 
			selector, class_getInstanceMethod, 
			(IMP)object_method_methodSignatureForSelector);
	super.receiver = self;

	NS_DURING
		result = objc_msgSendSuper(&super, selector, aSelector);
	NS_HANDLER
		result = nil;
	NS_ENDHANDLER

	if (result != nil) {
		return result;
	}

	pyself = ObjC_GetPythonImplementation(self);
	if (pyself == NULL) {
		ObjCErr_ToObjC();
		return nil;
	}

	pymeth = ObjCObject_FindSelector(pyself, aSelector);
	if (!pymeth) {
		ObjCErr_ToObjC();
		return nil;
	}

	result =  [NSMethodSignature signatureWithObjCTypes:(
		  	(ObjCSelector*)pymeth)->sel_signature];
	[result autorelease];
	Py_DECREF(pymeth);
	return result;
}

/* -forwardInvocation: */
static void
object_method_forwardInvocation(id self, SEL selector, NSInvocation* invocation)
{
	PyObject*	args;
	PyObject* 	result;
	PyObject*       v;
	int             i;
	int 		len;
	NSMethodSignature* signature;
	char		   argbuf[1024];
	const char* 		type;
	void* arg = NULL;
	const char* err;
	int   arglen;

	signature = [invocation methodSignature];
	len = [signature numberOfArguments];

	args = PyTuple_New(len - 1);
	if (args == NULL) {
		ObjCErr_ToObjC();
	}

	i = PyTuple_SetItem(args, 0, pythonify_c_value(
					[signature getArgumentTypeAtIndex:0],
					(void*)&self));
	if (i < 0) {
		Py_DECREF(args);
		ObjCErr_ToObjC();
		return;
	}

	for (i = 2; i < len; i++) {
		type = [signature getArgumentTypeAtIndex:i];
		arglen = objc_sizeof_type(type);
		arg = alloca(arglen);
		
		[invocation getArgument:argbuf atIndex:i];
		v = pythonify_c_value(type, argbuf);
		if (v == NULL) {
			Py_DECREF(args);
			ObjCErr_ToObjC();
			return;
		}

		if (PyTuple_SetItem(args, i-1, v) < 0) {
			Py_DECREF(args);
			ObjCErr_ToObjC();
			return;
		}
	}

	result = ObjC_call_to_python(self, [invocation selector], args);
	Py_DECREF(args);
	if (result == NULL) {
		ObjCErr_ToObjC();
		return;
	}

	type = [signature methodReturnType];
	arglen = objc_sizeof_type(type);
	arg = alloca(arglen+1);

	err = depythonify_c_value(type, result, arg);
	if (err != NULL) {
		ObjCErr_Set(objc_error,
			"Cannot depythonify result: %s", err);
		ObjCErr_ToObjC();
		return;
	}
}

/*
 * XXX: Function ObjC_call_to_python should be moved
 */

PyObject*
ObjC_call_to_python(id self, SEL selector, PyObject* arglist)
{
	PyObject* pyself = NULL;
	PyObject* pymeth = NULL;
	PyObject* result;


	pyself = ObjC_GetPythonImplementation(self);
	if (pyself == NULL) {
		ObjCErr_ToObjC();
		return NULL;
	}
	pymeth = ObjCObject_FindSelector(pyself, selector);
	if (pymeth == NULL) {
		ObjCErr_ToObjC();
		return NULL;
	}

	result = PyObject_Call(pymeth, arglist, NULL);
	Py_DECREF(pymeth);

	if (result == NULL) {
		ObjCErr_ToObjC();
		return NULL;
	}

	return result;
}