pyobjc / Modules / objc / formal-protocol.m

  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
/*
 * Implementation of support type for formal protocols.
 *
 * See the module DOCSTR for more information.
 */
#include "pyobjc.h"

struct Protocol_struct {
	@defs(Protocol);
};

PyDoc_STRVAR(proto_cls_doc,
"objc.formal_protocol(name, supers, selector_list)\n"
"\n"
"This class is used to proxy Objective-C formal protocols, and can also be \n"
"used to define new formal protocols.\n"
"");

typedef struct {
	PyObject_HEAD

	Protocol* objc;
} PyObjCFormalProtocol;


static void
proto_dealloc(PyObject* object)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	PyObjC_UnregisterPythonProxy(self->objc, object);
	object->ob_type->tp_free(object);
}


static PyObject*
proto_repr(PyObject* object)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	const char* name;

	name = [self->objc name];
	if (name == NULL) {
		name = "<nil>";
	}

	return PyString_FromFormat("<%s %s at %p>", self->ob_type->tp_name, name, (void*)self);
}

static PyObject*
proto_get__class__(PyObject* object __attribute__((__unused__)), void* closure __attribute__((__unused__)))
{
	return PyObjCClass_New([Protocol class]);
}

static PyObject*
proto_get__name__(PyObject* object, void* closure __attribute__((__unused__)))
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	const char* name = [self->objc name];

	if (name == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}

	return PyString_FromString(name);
}


static PyObject*
proto_new(PyTypeObject* type __attribute__((__unused__)), 
	PyObject* args, PyObject* kwds)
{
static	char*	keywords[] = { "name", "supers", "selectors", NULL };
	PyObjCFormalProtocol* result = NULL;
	char* name;
	PyObject* supers;
	PyObject* selectors;
	int i, len;
	int numInstance = 0;
	int numClass = 0;
	struct Protocol_struct* theProtocol = NULL;
	struct objc_method_description* c;

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "sOO:formal_protocol",
			keywords, &name, &supers, &selectors)) { 
		return NULL;
	}

	if (supers != Py_None) {
		supers = PySequence_Fast(supers, "supers need to be a sequence of objc.formal_protocols");
		if (supers == NULL) return NULL;
		len = PySequence_Fast_GET_SIZE(supers);
		for (i = 0; i < len; i++) {
			PyObject* v = PySequence_Fast_GET_ITEM(supers, i);
			if (!PyObjCFormalProtocol_Check(v)) {
				PyErr_SetString(PyExc_TypeError, "supers need to be a sequence of objc.formal_protocols");
				Py_DECREF(supers);
				return NULL;
			}
		}

	} else {
		Py_INCREF(supers);
	}

	selectors = PySequence_Fast(selectors, "selectors need to be a sequence of selectors");
	if (selectors == NULL) {
		Py_DECREF(supers);
		return NULL;
	}

	len = PySequence_Fast_GET_SIZE(selectors);
	for (i = 0; i < len; i++) {
		PyObject* sel = PySequence_Fast_GET_ITEM(selectors, i);
		if (sel == NULL || !PyObjCSelector_Check(sel)) {
			PyErr_SetString(PyExc_TypeError,
				"selectors need to be a sequence of selectors");
			Py_DECREF(supers);
			Py_DECREF(selectors);
			return NULL;
		}
		if (PyObjCSelector_GetFlags(sel)&PyObjCSelector_kCLASS_METHOD) {
			numClass++;
		} else {
			numInstance++;
		}
	}

	/* Allocate the protocol with alloc+init, don't shortcut through
	 * malloc, that doesn't work.
	 */
	theProtocol = (struct Protocol_struct*)[[Protocol alloc] init];
	if (theProtocol == NULL) {
		PyErr_NoMemory();
		goto error;
	}

	theProtocol->protocol_name = strdup(name);
	if (theProtocol->protocol_name == NULL) {
		PyErr_NoMemory();
		goto error;
	}

	if (supers == Py_None) {
		theProtocol->protocol_list = NULL;
	} else {
		len = PySequence_Fast_GET_SIZE(supers);
		theProtocol->protocol_list = malloc(
			sizeof(struct objc_protocol_list) +
			(1+len) * sizeof(Protocol*));
		theProtocol->protocol_list->next = NULL;
		theProtocol->protocol_list->count = len;
		for (i = 0; i < len; i++) {
			PyObject* v = PySequence_Fast_GET_ITEM(supers, i);
			theProtocol->protocol_list->list[i] =
				PyObjCFormalProtocol_GetProtocol(v);
			if (theProtocol->protocol_list->list[i] == NULL) {
				goto error;
			}
		}
		theProtocol->protocol_list->list[i] = NULL;
	}

	if (numInstance != NULL) {
		theProtocol->instance_methods = malloc(
			sizeof(struct objc_method_description_list) +
			(1+numInstance)  * sizeof(struct objc_method_description));
		if (theProtocol->instance_methods == NULL) {
			PyErr_NoMemory();
			goto error;
		}
		theProtocol->instance_methods->count = 0;
	}
	if (numClass != NULL) {
		theProtocol->class_methods = malloc(
			sizeof(struct objc_method_description_list) + 
			(1+numClass)  * sizeof(struct objc_method_description));
		if (theProtocol->class_methods == NULL) {
			PyErr_NoMemory();
			goto error;
		}
		theProtocol->class_methods->count = 0;
	}

	len = PySequence_Fast_GET_SIZE(selectors);
	for (i = 0; i < len; i++) {
		PyObject* sel = PySequence_Fast_GET_ITEM(selectors, i);
		SEL theSel = PyObjCSelector_GetSelector(sel);
		char* theSignature = PyObjCSelector_Signature(sel);

		if (PyObjCSelector_GetFlags(sel)&PyObjCSelector_kCLASS_METHOD) {
			c = &(theProtocol->class_methods->list[
				theProtocol->class_methods->count++]);
			c->name = theSel;
			c->types = strdup(theSignature);
			if (c->types == NULL) goto error;
		} else {
			c = &(theProtocol->instance_methods->list[
				theProtocol->instance_methods->count++]);
			c->name = theSel;
			c->types = strdup(theSignature);
			if (c->types == NULL) goto error;
		}
	}

	if (theProtocol->instance_methods) {
		c = &(theProtocol->instance_methods->list[
			theProtocol->instance_methods->count]);
		c->name = NULL;
		c->types = NULL;
	}

	if (theProtocol->class_methods) {
		c = &(theProtocol->class_methods->list[
			theProtocol->class_methods->count]);
		c->name = NULL;
		c->types = NULL;
	}


	result = (PyObjCFormalProtocol*)PyObject_New(
			PyObjCFormalProtocol, &PyObjCFormalProtocol_Type);
	if (result == NULL) goto error;

	Py_DECREF(selectors);
	Py_DECREF(supers);

	result->objc = (Protocol*)theProtocol;
	PyObjC_RegisterPythonProxy(result->objc, (PyObject*)result);
	return (PyObject*)result;

error:
	Py_DECREF(selectors);
	Py_DECREF(supers);

	if (theProtocol == NULL) return NULL;

	if (theProtocol->protocol_name != NULL) {
		free(theProtocol->protocol_name);
	}

	if (theProtocol->protocol_list != NULL) {
		free(theProtocol->protocol_list);
	}

	if (theProtocol->instance_methods != NULL) {
		for (i = 0; i < theProtocol->instance_methods->count; i++) {
			c = theProtocol->instance_methods->list + i;
			if (c->name) {
				free(c->name);
			}
		}
		free(theProtocol->instance_methods);
	}

	if (theProtocol->class_methods != NULL) {
		for (i = 0; i < theProtocol->class_methods->count; i++) {
			c = theProtocol->class_methods->list + i;
			if (c->name) {
				free(c->name);
			}
		}
		free(theProtocol->class_methods);
	}
	return NULL;
}

static PyObject*
proto_name(PyObject* object)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	const char* name = [self->objc name];

	if (name == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}

	return PyString_FromString(name);
}

static PyObject*
proto_conformsTo_(PyObject* object, PyObject* args)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	PyObject* protocol;
	Protocol* objc_protocol;

	if (!PyArg_ParseTuple(args, "O", &protocol)) {
		return NULL;
	}

	if (!PyObjCFormalProtocol_Check(protocol)) {
		PyErr_SetString(PyExc_TypeError, "Expecting a formal protocol");
		return NULL;
	}
	objc_protocol = PyObjCFormalProtocol_GetProtocol(protocol);

	if ([self->objc conformsTo:objc_protocol]) {
		return PyBool_FromLong(1);
	} else {
		return PyBool_FromLong(0);
	}
}

static PyObject*
descriptionForInstanceMethod_(PyObject* object, PyObject* sel)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	SEL aSelector;
	struct objc_method_description* descr;

	if (PyObjCSelector_Check(sel)) {
		aSelector = PyObjCSelector_GetSelector(sel);
	} else if (PyString_Check(sel)) {
		char* s = PyString_AsString(sel);
		if (*s == '\0') {
			PyErr_SetString(PyExc_ValueError, 
					"empty selector name");
			return NULL;
		}

		aSelector = PyObjCRT_SELUID(s);
	}

	descr = [self->objc descriptionForInstanceMethod:aSelector];
	if (descr == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	} else {
		return Py_BuildValue("(ss)",
			PyObjCRT_SELName(descr->name),
			descr->types);
	}
}

static PyObject*
descriptionForClassMethod_(PyObject* object, PyObject* sel)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	SEL aSelector;
	struct objc_method_description* descr;

	if (PyObjCSelector_Check(sel)) {
		aSelector = PyObjCSelector_GetSelector(sel);
	} else if (PyString_Check(sel)) {
		char* s = PyString_AsString(sel);
		if (*s == '\0') {
			PyErr_SetString(PyExc_ValueError, 
					"empty selector name");
			return NULL;
		}

		aSelector = PyObjCRT_SELUID(s);
	}

	descr = [self->objc descriptionForClassMethod:aSelector];
	if (descr == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	} else {
		return Py_BuildValue("(ss)",
			PyObjCRT_SELName(descr->name),
			descr->types);
	}
}

static PyMethodDef proto_methods[] = {
	{
		"name",
		(PyCFunction)proto_name,
		METH_NOARGS,
		"Return the  protocol name",
	},
	{
		"conformsTo_",
		(PyCFunction)proto_conformsTo_,
		METH_VARARGS,
		"Does this protocol conform to another protocol"
	},
	{
		"descriptionForInstanceMethod_",
		(PyCFunction)descriptionForInstanceMethod_,
		METH_O,
		"Description for an instance method in the protocol"
	},
	{
		"descriptionForClassMethod_",
		(PyCFunction)descriptionForClassMethod_,
		METH_O,
		"Description for a class method in the protocol"
	},
	{ 0, 0, 0, 0 }
};

static PyGetSetDef proto_getset[] = {
	{
		"X__class__",
		(getter)proto_get__class__,
		NULL,
		NULL,
		0
	},
	{
		"__name__",
		(getter)proto_get__name__,
		NULL,
		NULL,
		0
	},
	{ NULL, NULL, NULL, NULL, 0 }
};

PyTypeObject PyObjCFormalProtocol_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,					/* ob_size */
	"objc.formal_protocol",			/* tp_name */
	sizeof(PyObjCFormalProtocol),		/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	proto_dealloc,	 			/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	proto_repr,				/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,		       			/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,			/* tp_flags */
 	proto_cls_doc,				/* tp_doc */
 	0,					/* tp_traverse */
 	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	proto_methods,				/* tp_methods */
	0,					/* tp_members */
	proto_getset,				/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
	0,					/* tp_init */
	0,					/* tp_alloc */
	proto_new,				/* tp_new */
	0,		        		/* tp_free */
	0,					/* tp_is_gc */
        0,                                      /* tp_bases */
        0,                                      /* tp_mro */
        0,                                      /* tp_cache */
        0,                                      /* tp_subclasses */
        0,                                      /* tp_weaklist */
        0                                       /* tp_del */
};


/*
 * Find information about a selector in the protocol.
 *
 * Return NULL if no information can be found, but does not set an
 * exception.
 */
const char* 
PyObjCFormalProtocol_FindSelectorSignature(PyObject* object, SEL selector, int isClassMethod)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	
	struct objc_method_description* descr;

	if (isClassMethod) {
		descr = [self->objc descriptionForClassMethod: selector];
	} else {
		descr = [self->objc descriptionForInstanceMethod: selector];
	}
	if (descr) {
		return descr->types;
	}
	return NULL;
}

static int 
signaturesEqual(char* sig1, char* sig2)
{
	char buf1[1024];
	char buf2[1024];
	int r;

	/* Return 0 if the two signatures are not equal */
	if (strcmp(sig1, sig2) == 0) return 1;

	/* For some reason compiler-generated signatures contain numbers that
	 * are not used by the runtime. These are irrelevant for our comparison
	 */
	r = PyObjCRT_SimplifySignature(sig1, buf1, sizeof(buf1));
	if (r == -1) { 
		return 0; 
	}

	r = PyObjCRT_SimplifySignature(sig2, buf2, sizeof(buf2));
	if (r == -1) { 
		return 0; 
	}


	return strcmp(buf1, buf2) == 0;
}


extern PyObject* findSelInDict(PyObject* clsdict, SEL selector);
extern int signaturesEqual(char* sig1, char* sig2);


static int
do_verify(
	const char* protocol_name, 
	struct objc_method_description* descr, 
	int is_class __attribute__((__unused__)), 
	char* name,
	PyObject* super_class, 
	PyObject* clsdict)
{
	PyObject* meth;

	/* TODO: take classmethodness into account */

	meth = findSelInDict(clsdict, descr->name);
	if (meth == NULL || !PyObjCSelector_Check(meth)) {

		meth = PyObjCClass_FindSelector(super_class, descr->name);
		if (meth == NULL || !PyObjCSelector_Check(meth)) {
			PyErr_Format(PyExc_TypeError,
				"class %s does not full implement protocol "
				"%s: no implementation for %s",
				name,
				protocol_name,
				PyObjCRT_SELName(descr->name));
			return 0;
		}
	}

	if (signaturesEqual(descr->types, 
				PyObjCSelector_Signature(meth))) {
		return 1;
	} 

	PyErr_Format(PyExc_TypeError,
		"class %s does not correctly implement "
		"protocol %s: the signature for method %s "
		"is %s instead of %s",
		name,
		protocol_name,
		PyObjCRT_SELName(descr->name),
		PyObjCSelector_Signature(meth),
		descr->types);
	return 0;
}

static int
do_check(
    const char* protocol_name,
    Protocol* protocol, 
    char* name, 
    PyObject* super_class, 
    PyObject* clsdict)
{
	struct Protocol_struct* cur; 
	int i, r;

	cur = (struct Protocol_struct*)protocol;

	if (cur->protocol_list) {
		for (i = 0; i < cur->protocol_list->count; i++) {
			r = do_check(protocol_name, cur->protocol_list->list[i], name, super_class, clsdict);
			if (r == 0) return r;
		}
	}

	if (cur->instance_methods) {
		for (i = 0; i < cur->instance_methods->count; i++) {
			if (!do_verify(protocol_name, cur->instance_methods->list + i, 0, name, super_class, clsdict)) {
				return 0;
			}
		}
	} 
	if (cur->class_methods) {
		for (i = 0; i < cur->class_methods->count; i++) {
			if (!do_verify(protocol_name, cur->class_methods->list + i, 1, name, super_class, clsdict)) {
				return 0;
			}
		}
	} 
	return 1;
}

int	
PyObjCFormalProtocol_CheckClass(
	PyObject* obj, char* name, PyObject* super_class, PyObject* clsdict)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)obj;	

	if (!PyObjCFormalProtocol_Check(obj)) {
		PyErr_Format(PyExc_TypeError,
			"First argument is not an 'objc.formal_protocol' but "
			"'%s'", obj->ob_type->tp_name);
		return 0;
	}
	if (!PyObjCClass_Check(super_class)) {
		PyErr_Format(PyExc_TypeError,
			"Third argument is not an 'objc.objc_class' but "
			"'%s'", super_class->ob_type->tp_name);
		return 0;
	}
	if (!PyDict_Check(clsdict)) {
		PyErr_Format(PyExc_TypeError,
			"Fourth argument is not a 'dict' but '%s'",
			clsdict->ob_type->tp_name);
		return 0;
	}

	return do_check([self->objc name], self->objc, name, super_class, clsdict);
}

PyObject* PyObjCFormalProtocol_ForProtocol(Protocol* protocol)
{
	PyObjCFormalProtocol* result;

	result = (PyObjCFormalProtocol*)PyObject_New(
			PyObjCFormalProtocol, &PyObjCFormalProtocol_Type);
	if (result == NULL) {
		return NULL;
	}

	result->objc = protocol;
	PyObjC_RegisterPythonProxy(result->objc, (PyObject*)result);
	return (PyObject*)result;
}

Protocol* PyObjCFormalProtocol_GetProtocol(PyObject* object)
{
	PyObjCFormalProtocol* self = (PyObjCFormalProtocol*)object;	

	if (!PyObjCFormalProtocol_Check(self)) {
		PyErr_Format(PyExc_TypeError, 
			"Expecting objc.formal_protocol, got %s",
			self->ob_type->tp_name);
		return NULL;
	}

	return self->objc;
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.