summaryrefslogtreecommitdiff
path: root/cheetah/c/_namemapper.c
blob: d07769e2e4d855533eb4059ee92aaf577ef0f066 (plain)
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
/* ***************************************************************************
This is the C language version of NameMapper.py.  See the comments and
DocStrings in NameMapper for details on the purpose and interface of this
module.

===============================================================================
$Id: _namemapper.c,v 1.34 2007/12/10 18:25:20 tavis_rudd Exp $
Authors: Tavis Rudd <tavis@damnsimple.com>
Version: $Revision: 1.34 $
Start Date: 2001/08/07
Last Revision Date: $Date: 2007/12/10 18:25:20 $
*/

/* *************************************************************************** */
#include "Python.h"             /* Python header files */
#include <string.h>
#include <stdlib.h>

#ifdef __cplusplus
extern "C" {
#endif


static PyObject *NotFound;   /* locally-raised exception */
static PyObject *TooManyPeriods;   /* locally-raised exception */
static PyObject* pprintMod_pformat; /* used for exception formatting */
#define MAXCHUNKS 15		/* max num of nameChunks for the arrays */
#define TRUE 1
#define FALSE 0

#define ALLOW_WRAPPING_OF_NOTFOUND_EXCEPTIONS 1
#define INCLUDE_NAMESPACE_REPR_IN_NOTFOUND_EXCEPTIONS 0

# define createNameCopyAndChunks() {\
  nameCopy = malloc(strlen(name) + 1);\
  tmpPntr1 = name; \
  tmpPntr2 = nameCopy;\
  while ((*tmpPntr2++ = *tmpPntr1++)); \
  numChunks = getNameChunks(nameChunks, name, nameCopy); \
  if (PyErr_Occurred()) { 	/* there might have been TooManyPeriods */\
    free(nameCopy);\
    return NULL;\
  }\
}

#define OLD_checkForNameInNameSpaceAndReturnIfFound() { \
    if ( PyNamemapper_hasKey(nameSpace, nameChunks[0]) ) {\
      theValue = PyNamemapper_valueForName(nameSpace, nameChunks, numChunks, executeCallables);\
      free(nameCopy);\
      if (wrapInternalNotFoundException(name, nameSpace)) {\
	theValue = NULL;\
      }\
      return theValue;\
    }\
}

#define checkForNameInNameSpaceAndReturnIfFound(namespace_decref) { \
    if ( PyNamemapper_hasKey(nameSpace, nameChunks[0]) ) {\
      theValue = PyNamemapper_valueForName(nameSpace, nameChunks, numChunks, executeCallables);\
      if (namespace_decref) {\
        Py_DECREF(nameSpace);\
      }\
      if (wrapInternalNotFoundException(name, nameSpace)) {\
	theValue = NULL;\
      }\
      goto done;\
    }\
}

/* *************************************************************************** */
/* First the c versions of the functions */
/* *************************************************************************** */

static void
setNotFoundException(char *key, PyObject *namespace)
{


  PyObject *exceptionStr = NULL;
  exceptionStr = Py_BuildValue("s","cannot find '");
  PyString_ConcatAndDel(&exceptionStr, Py_BuildValue("s", key));
  PyString_ConcatAndDel(&exceptionStr, Py_BuildValue("s", "'"));
  if (INCLUDE_NAMESPACE_REPR_IN_NOTFOUND_EXCEPTIONS) {
    PyString_ConcatAndDel(&exceptionStr, Py_BuildValue("s", " in the namespace "));
    PyString_ConcatAndDel(&exceptionStr, 
			  PyObject_CallFunctionObjArgs(pprintMod_pformat, namespace, NULL));
  }
  PyErr_SetObject(NotFound, exceptionStr);
  Py_DECREF(exceptionStr);
}

static int
wrapInternalNotFoundException(char *fullName, PyObject *namespace)
{
  PyObject *excType, *excValue, *excTraceback, *isAlreadyWrapped = NULL;
  if (!ALLOW_WRAPPING_OF_NOTFOUND_EXCEPTIONS) {
    return 0;
  } 
  if (PyErr_Occurred() && PyErr_GivenExceptionMatches(PyErr_Occurred(), NotFound)) {
    PyErr_Fetch(&excType, &excValue, &excTraceback);
    isAlreadyWrapped = PyObject_CallMethod(excValue, "find", "s", "while searching");

    if (isAlreadyWrapped != NULL) {
	if (PyInt_AsLong(isAlreadyWrapped)==-1) { /* only wrap once */
	    PyString_ConcatAndDel(&excValue, Py_BuildValue("s", " while searching for '"));
	    PyString_ConcatAndDel(&excValue, Py_BuildValue("s", fullName));
	    PyString_ConcatAndDel(&excValue, Py_BuildValue("s", "'"));
	    if (INCLUDE_NAMESPACE_REPR_IN_NOTFOUND_EXCEPTIONS) {
		PyString_ConcatAndDel(&excValue, Py_BuildValue("s", " in "));
		PyString_ConcatAndDel(&excValue, Py_BuildValue("s", "the top-level namespace "));
		PyString_ConcatAndDel(&excValue, 
				      PyObject_CallFunctionObjArgs(pprintMod_pformat, namespace, NULL));
	    }
	}
	Py_DECREF(isAlreadyWrapped);
    }
    PyErr_Restore(excType, excValue, excTraceback);
    return -1;
  } else {
    return 0;
  }
}


static int 
isInstanceOrClass(PyObject *nextVal) {
    /* old style classes or instances */
    if((PyInstance_Check(nextVal)) || (PyClass_Check(nextVal))) {
        return 1;
    }

    if(PyObject_HasAttrString(nextVal, "__class__")) {
	/* new style classes or instances */
        if(PyType_Check(nextVal) || PyObject_HasAttrString(nextVal, "mro")) {
            return 1;
        }
        if(PyObject_HasAttrString(nextVal, "im_func") 
	   || PyObject_HasAttrString(nextVal, "func_code")
	   || PyObject_HasAttrString(nextVal, "__self__")) {
	    /* method, func, or builtin func */
            return 0;
	}
        if ((!PyObject_HasAttrString(nextVal, "mro")) && PyObject_HasAttrString(nextVal, "__init__")) {
	    /* instance */
            return 1;
        }
    }
    return 0;
}


static int getNameChunks(char *nameChunks[], char *name, char *nameCopy) 
{
  char c;
  char *currChunk;
  int currChunkNum = 0;
  
  currChunk = nameCopy;
  while ('\0' != (c = *nameCopy)){
    if ('.' == c) {
      if (currChunkNum >= (MAXCHUNKS-2)) { /* avoid overflowing nameChunks[] */
	PyErr_SetString(TooManyPeriods, name); 
	return 0;
      }

      *nameCopy ='\0';
      nameChunks[currChunkNum++] = currChunk;
      nameCopy++;
      currChunk = nameCopy;
    } else 
      nameCopy++;
  }
  if (nameCopy > currChunk) {
    nameChunks[currChunkNum++] = currChunk;
  }
  return currChunkNum;
}


static int 
PyNamemapper_hasKey(PyObject *obj, char *key)
{
  if (PyMapping_Check(obj) && PyMapping_HasKeyString(obj, key)) {
    return TRUE;
  } else if (PyObject_HasAttrString(obj, key)) {
    return TRUE;
  } else {
    return FALSE;
  }
}


static PyObject *
PyNamemapper_valueForKey(PyObject *obj, char *key)
{
  PyObject *theValue = NULL;

  if (PyMapping_Check(obj) && PyMapping_HasKeyString(obj, key)) {
    theValue = PyMapping_GetItemString(obj, key);
  } else if (PyObject_HasAttrString(obj, key)) {
    theValue = PyObject_GetAttrString(obj, key);

  } else {
    setNotFoundException(key, obj);
  }

  return theValue;
}

static PyObject *
PyNamemapper_valueForName(PyObject *obj, char *nameChunks[], 
			  int numChunks, 
			  int executeCallables)
{
    int i;
    char *currentKey;
    PyObject *currentVal = NULL;
    PyObject *nextVal = NULL;

    currentVal = obj;
    for (i=0; i < numChunks;i++) {
        currentKey = nameChunks[i];
        if (PyErr_CheckSignals()) {	/* not sure if I really need to do this here, but what the hell */
            if (i>0) {
                Py_DECREF(currentVal);
            }
            return NULL;
        }
        
        if (PyMapping_Check(currentVal) && PyMapping_HasKeyString(currentVal, currentKey)) {
            nextVal = PyMapping_GetItemString(currentVal, currentKey);
        } 
        else {
          PyObject *exc;
          nextVal = PyObject_GetAttrString(currentVal, currentKey);
          exc = PyErr_Occurred();
          if (exc != NULL) {
            // if exception == AttributeError
            if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
                setNotFoundException(currentKey, currentVal);
                if (i > 0) {
                    Py_DECREF(currentVal);
                }
                return NULL;
            }
          }
        }
        if (i > 0) {
            Py_DECREF(currentVal);
        }

        if (executeCallables && PyCallable_Check(nextVal) && (!isInstanceOrClass(nextVal)) ) {
            //if (executeCallables && PyCallable_Check(nextVal) && (!PyInstance_Check(nextVal)) 
            //&& (!PyClass_Check(nextVal)) && (!PyType_Check(nextVal)) ) {
            if (!(currentVal = PyObject_CallObject(nextVal, NULL))) {
                Py_DECREF(nextVal);
                return NULL;
            }

            Py_DECREF(nextVal);
        } else {
            currentVal = nextVal;
        }
    }

    return currentVal;
}


/* *************************************************************************** */
/* Now the wrapper functions to export into the Python module */
/* *************************************************************************** */


static PyObject *
namemapper_valueForKey(PyObject *self, PyObject *args)
{
  PyObject *obj;
  char *key;

  if (!PyArg_ParseTuple(args, "Os", &obj, &key)) {
    return NULL;
  }

  return PyNamemapper_valueForKey(obj, key);

}

static PyObject *
namemapper_valueForName(PyObject *self, PyObject *args, PyObject *keywds)
{


  PyObject *obj;
  char *name;
  int executeCallables = 0;

  char *nameCopy = NULL;
  char *tmpPntr1 = NULL;
  char *tmpPntr2 = NULL;
  char *nameChunks[MAXCHUNKS];
  int numChunks;

  PyObject *theValue;

  static char *kwlist[] = {"obj", "name", "executeCallables", NULL};

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "Os|i", kwlist,  &obj, &name, &executeCallables)) {
    return NULL;
  }

  createNameCopyAndChunks();  

  theValue = PyNamemapper_valueForName(obj, nameChunks, numChunks, executeCallables);
  free(nameCopy);
  if (wrapInternalNotFoundException(name, obj)) {
    theValue = NULL;
  }
  return theValue;

}

static PyObject *
namemapper_valueFromSearchList(PyObject *self, PyObject *args, PyObject *keywds)
{

  PyObject *searchList;
  char *name;
  int executeCallables = 0;

  char *nameCopy = NULL;
  char *tmpPntr1 = NULL;
  char *tmpPntr2 = NULL;
  char *nameChunks[MAXCHUNKS];
  int numChunks;

  PyObject *nameSpace = NULL;
  PyObject *theValue = NULL;
  PyObject *iterator = NULL;

  static char *kwlist[] = {"searchList", "name", "executeCallables", NULL};

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "Os|i", kwlist,  &searchList, &name, 
				   &executeCallables)) {
    return NULL;
  }

  createNameCopyAndChunks();

  iterator = PyObject_GetIter(searchList);
  if (iterator == NULL) {
    PyErr_SetString(PyExc_TypeError,"This searchList is not iterable!");
    goto done;
  }

  while ( (nameSpace = PyIter_Next(iterator)) ) {
    checkForNameInNameSpaceAndReturnIfFound(TRUE);
    Py_DECREF(nameSpace);
    if(PyErr_CheckSignals()) {
      theValue = NULL;
      goto done;
    }
  }
  if (PyErr_Occurred()) {
    theValue = NULL;
    goto done;
  }

  setNotFoundException(nameChunks[0], searchList);
 done:
  Py_XDECREF(iterator);
  free(nameCopy);
  return theValue;
}

static PyObject *
namemapper_valueFromFrameOrSearchList(PyObject *self, PyObject *args, PyObject *keywds)
{

  /* python function args */
  char *name;
  int executeCallables = 0;
  PyObject *searchList = NULL;

  /* locals */
  char *nameCopy = NULL;
  char *tmpPntr1 = NULL;
  char *tmpPntr2 = NULL;
  char *nameChunks[MAXCHUNKS];
  int numChunks;

  PyObject *nameSpace = NULL;
  PyObject *theValue = NULL;
  PyObject *excString = NULL;
  PyObject *iterator = NULL;

  static char *kwlist[] = {"searchList", "name", "executeCallables", NULL};

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "Os|i", kwlist,  &searchList, &name, 
				   &executeCallables)) {
    return NULL;
  }

  createNameCopyAndChunks();
  
  nameSpace = PyEval_GetLocals();
  checkForNameInNameSpaceAndReturnIfFound(FALSE);  

  iterator = PyObject_GetIter(searchList);
  if (iterator == NULL) {
    PyErr_SetString(PyExc_TypeError,"This searchList is not iterable!");
    goto done;
  }
  while ( (nameSpace = PyIter_Next(iterator)) ) {
    checkForNameInNameSpaceAndReturnIfFound(TRUE);
    Py_DECREF(nameSpace);
    if(PyErr_CheckSignals()) {
      theValue = NULL;
      goto done;
    }
  }
  if (PyErr_Occurred()) {
    theValue = NULL;
    goto done;
  }

  nameSpace = PyEval_GetGlobals();
  checkForNameInNameSpaceAndReturnIfFound(FALSE);

  nameSpace = PyEval_GetBuiltins();
  checkForNameInNameSpaceAndReturnIfFound(FALSE);

  excString = Py_BuildValue("s", "[locals()]+searchList+[globals(), __builtins__]");
  setNotFoundException(nameChunks[0], excString);
  Py_DECREF(excString);

 done:
  Py_XDECREF(iterator);
  free(nameCopy);
  return theValue;
}

static PyObject *
namemapper_valueFromFrame(PyObject *self, PyObject *args, PyObject *keywds)
{

  /* python function args */
  char *name;
  int executeCallables = 0;

  /* locals */
  char *tmpPntr1 = NULL;
  char *tmpPntr2 = NULL;

  char *nameCopy = NULL;
  char *nameChunks[MAXCHUNKS];
  int numChunks;

  PyObject *nameSpace = NULL;
  PyObject *theValue = NULL;
  PyObject *excString = NULL;

  static char *kwlist[] = {"name", "executeCallables", NULL};

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|i", kwlist, &name, &executeCallables)) {
    return NULL;
  }

  createNameCopyAndChunks();
  
  nameSpace = PyEval_GetLocals();
  checkForNameInNameSpaceAndReturnIfFound(FALSE);
  
  nameSpace = PyEval_GetGlobals();
  checkForNameInNameSpaceAndReturnIfFound(FALSE);

  nameSpace = PyEval_GetBuiltins();
  checkForNameInNameSpaceAndReturnIfFound(FALSE);

  excString = Py_BuildValue("s", "[locals(), globals(), __builtins__]");
  setNotFoundException(nameChunks[0], excString);
  Py_DECREF(excString);
 done:
  free(nameCopy);
  return theValue;
}

/* *************************************************************************** */
/* Method registration table: name-string -> function-pointer */

static struct PyMethodDef namemapper_methods[] = {
  {"valueForKey", namemapper_valueForKey,  1},
  {"valueForName", (PyCFunction)namemapper_valueForName,  METH_VARARGS|METH_KEYWORDS},
  {"valueFromSearchList", (PyCFunction)namemapper_valueFromSearchList,  METH_VARARGS|METH_KEYWORDS},
  {"valueFromFrame", (PyCFunction)namemapper_valueFromFrame,  METH_VARARGS|METH_KEYWORDS},
  {"valueFromFrameOrSearchList", (PyCFunction)namemapper_valueFromFrameOrSearchList,  METH_VARARGS|METH_KEYWORDS},
  {NULL,         NULL}
};


/* *************************************************************************** */
/* Initialization function (import-time) */

DL_EXPORT(void)
init_namemapper(void)
{
  PyObject *m, *d, *pprintMod;

  /* create the module and add the functions */
  m = Py_InitModule("_namemapper", namemapper_methods);        /* registration hook */
  
  /* add symbolic constants to the module */
  d = PyModule_GetDict(m);
  NotFound = PyErr_NewException("NameMapper.NotFound",PyExc_LookupError,NULL);
  TooManyPeriods = PyErr_NewException("NameMapper.TooManyPeriodsInName",NULL,NULL);
  PyDict_SetItemString(d, "NotFound", NotFound);
  PyDict_SetItemString(d, "TooManyPeriodsInName", TooManyPeriods);
  pprintMod = PyImport_ImportModule("pprint");
  if (!pprintMod)
        return;
  pprintMod_pformat = PyObject_GetAttrString(pprintMod, "pformat");
  Py_DECREF(pprintMod);
  /* check for errors */
  if (PyErr_Occurred())
    Py_FatalError("Can't initialize module _namemapper");
}

#ifdef __cplusplus
}
#endif