Python Formatted C Converter (PfCC)

Will Ware wware at world.std.com
Fri Oct 27 18:20:30 EDT 2000


Gareth McCaughan (Gareth.McCaughan at pobox.com) wrote:
> Find some
> simple subset of Python... Write a
> *translator* that turns this subset into C. That way, what
> you're writing is more or less real Python; if you do this
> right, you'll even be able to run the code in Python for
> prototyping purposes...

I got really intrigued with this idea and have started to tinker with
it. Below appears an example of what it is currently able to do. To
keep life simple, I am initially assuming everything is an int. I
posted the translator to alt.sources. When deja.com notices it, I'll
post their URL for it.

Here's an example function to be translated:

    def silly(x, y):
        if y > 20:
            x = x + 1
        return (6 * x + y * 3) / 7

and here is the resulting C output:

#include "Python.h"
#define None 0
PyObject * c_silly(PyObject *self, PyObject *args) {
int stack[3]; int *sp = &stack[0];
int x; int y;
if (!PyArg_ParseTuple(args, "ii", &x, &y)) return NULL;
/*SET_LINENO     */ Label_000:  /* Python line number 175 */
/*SET_LINENO     */ Label_003:  /* Python line number 176 */
/*LOAD_FAST      */ Label_006:  *sp++ = y;
/*LOAD_CONST     */ Label_009:  *sp++ = 20;
/*COMPARE_OP     */ Label_012:  sp--; sp[-1] = (sp[-1] > sp[0]);
/*JUMP_IF_FALSE  */ Label_015:  if (!sp[-1]) goto Label_035;
/*POP_TOP        */ Label_018:  sp--;
/*SET_LINENO     */ Label_019:  /* Python line number 177 */
/*LOAD_FAST      */ Label_022:  *sp++ = x;
/*LOAD_CONST     */ Label_025:  *sp++ = 1;
/*BINARY_ADD     */ Label_028:  sp--; sp[-1] = sp[-1] + sp[0];
/*STORE_FAST     */ Label_029:  x = *--sp;
/*JUMP_FORWARD   */ Label_032:  goto Label_036;
/*POP_TOP        */ Label_035:  sp--;
/*SET_LINENO     */ Label_036:  /* Python line number 178 */
/*LOAD_CONST     */ Label_039:  *sp++ = 6;
/*LOAD_FAST      */ Label_042:  *sp++ = x;
/*BINARY_MULTIPLY*/ Label_045:  sp--; sp[-1] = sp[-1] * sp[0];
/*LOAD_FAST      */ Label_046:  *sp++ = y;
/*LOAD_CONST     */ Label_049:  *sp++ = 3;
/*BINARY_MULTIPLY*/ Label_052:  sp--; sp[-1] = sp[-1] * sp[0];
/*BINARY_ADD     */ Label_053:  sp--; sp[-1] = sp[-1] + sp[0];
/*LOAD_CONST     */ Label_054:  *sp++ = 7;
/*BINARY_DIVIDE  */ Label_057:  sp--; sp[-1] = sp[-1] / sp[0];
/*RETURN_VALUE   */ Label_058:  return Py_BuildValue("i", sp[-1]);
/*LOAD_CONST     */ Label_059:  *sp++ = None;
/*RETURN_VALUE   */ Label_062:  return Py_BuildValue("i", sp[-1]);
}
static PyMethodDef foo_methods[] = {
{"silly", c_silly, 1},
{NULL, NULL}};
            DL_EXPORT(void)
            initfoo() {
            Py_InitModule("foo", foo_methods);
            }

-- 
# - - - - - - - - - - - - - - - - - - - - - - - -
# Resistance is futile. Capacitance is efficacious.
# Will Ware	email:    wware @ world.std.com



More information about the Python-list mailing list