summaryrefslogtreecommitdiffstats
path: root/sandbox/sebastien/cpp/apr-2/modules/python/eval.hpp
blob: 2dd4b8ba33e37c7899551dacd0fedd522b49ad57 (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
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/* $Rev$ $Date$ */

#ifndef tuscany_python_eval_hpp
#define tuscany_python_eval_hpp

/**
 * Python script evaluation logic.
 */
#include <python2.6/Python.h>

#include "list.hpp"
#include "value.hpp"

namespace tuscany {
namespace python {

/**
 * Represent a Python runtime.
 */
class PythonRuntime {
public:
    PythonRuntime() {
        if (Py_IsInitialized())
            return;
        Py_InitializeEx(0);
        const char* arg0 = "";
        PySys_SetArgv(0, const_cast<char**>(&arg0));
    }
};

/**
 * Return the last python error.
 */
const string lastError() {
    if(PyErr_Occurred()) {
        PyObject* type;
        PyObject* val;
        PyObject* trace;
        PyErr_Fetch(&type, &val, &trace);
        if (type != NULL && val != NULL) {
            PyObject* stype = PyObject_Str(type);    
            PyObject* sval = PyObject_Str(val);    
            string msg = string() + PyString_AsString(stype) + " : " + PyString_AsString(sval);
            Py_DECREF(stype);
            Py_DECREF(sval);                                    
            Py_DECREF(type);
            Py_DECREF(val);
            Py_XDECREF(trace);
            PyErr_Print();
            return msg;
        }
        PyErr_Print();
        Py_XDECREF(type);
        Py_XDECREF(val);
        Py_XDECREF(trace);
        PyErr_Print();
        return "Unknown Python error";
    }
    return "";
}

/**
 * Declare conversion functions.
 */
PyObject* valueToPyObject(const value& v);
const value pyObjectToValue(PyObject *o);
PyObject* valuesToPyTuple(const list<value>& v);
const list<value> pyTupleToValues(PyObject* o);

/**
 * Callable python type used to represent a lambda expression.
 */
typedef struct {
  PyObject_HEAD
  lambda<value(const list<value>&)> func;
} pyLambda;

PyObject *mkPyLambda(const lambda<value(const list<value>&)>& l);

void pyLambda_dealloc(PyObject* self) {
    PyMem_DEL(self);
}

const string pyRepr(PyObject * o) {
    return PyString_AsString(PyObject_Repr(o));
}

PyObject* pyLambda_call(PyObject* self, PyObject* args, unused PyObject* kwds) {
    debug("python::call");
    const pyLambda* pyl = (pyLambda*)self;
    const value result = pyl->func(pyTupleToValues(args));
    debug(result, "python::call::result");
    Py_DECREF(args);
    PyObject *pyr = valueToPyObject(result);
    Py_INCREF(pyr);
    return pyr;
}

struct pyProxy {
    const value name;
    const lambda<value(const list<value>&)> func;

    pyProxy(const value& name, const lambda<value(const list<value>&)>& func) : name(name), func(func) {
    }

    const value operator()(const list<value>& args) const {
        debug(name, "python::proxy::name");
        const value result = func(cons<value>(name, args));
        debug(result, "python::proxy::result");
        return result;
    }
};

PyObject* pyLambda_getattr(PyObject *self, PyObject *attrname) {
    const string name = PyString_AsString(attrname);
    if (substr(name, 0, 1) == "_")
        return PyObject_GenericGetAttr(self, attrname);

    if (name == "eval") {
        Py_INCREF(self);
        return self;
    }

    const pyLambda* pyl = (pyLambda*)self;
    debug(name, "python::getattr::name");
    PyObject* pyr = mkPyLambda(pyProxy(name, pyl->func));
    Py_INCREF(pyr);
    return pyr;
}

PyTypeObject pyLambda_type = {
    PyObject_HEAD_INIT(0)
    0,
    "lambda",
    sizeof(pyLambda),
    0,
    (destructor)pyLambda_dealloc,
    0, 0, 0, 0, 0, 0, 0, 0, 0,
    (ternaryfunc)pyLambda_call,
    0, 
    (binaryfunc)pyLambda_getattr,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0
};

/**
 * Create a new python object representing a lambda expression.
 */
PyObject *mkPyLambda(const lambda<value(const list<value>&)>& l) {
    pyLambda* pyl = NULL;
    pyl = PyObject_NEW(pyLambda, &pyLambda_type);
    if (pyl != NULL)
      pyl->func = l;
    return (PyObject *)pyl;
}

/**
 * Convert a list of values to a python list.
 */
PyObject* valuesToPyListHelper(PyObject* l, const list<value>& v) {
    if (isNil(v))
        return l;
    PyList_Append(l, valueToPyObject(car(v)));
    return valuesToPyListHelper(l, cdr(v));
}

PyObject* valuesToPyTuple(const list<value>& v) {
    return PyList_AsTuple(valuesToPyListHelper(PyList_New(0), v));
}

/**
 * Convert a value to a python object.
 */
PyObject* valueToPyObject(const value& v) {
    switch (type(v)) {
    case value::List:
        return valuesToPyTuple(v);
    case value::Lambda:
        return mkPyLambda(v);
    case value::Symbol:
        return PyString_FromString(c_str(string("'") + v));
    case value::String:
        return PyString_FromString(c_str(v));
    case value::Number:
        return PyFloat_FromDouble((double)v);
    case value::Bool:
        return (bool)v? Py_True : Py_False;
    default:
        return Py_None;
    }
}

/**
 * Convert a python tuple to a list of values.
 */

const list<value> pyTupleToValuesHelper(PyObject* o, const size_t i, const size_t size) {
    if (i == size)
        return list<value>();
    return cons(pyObjectToValue(PyTuple_GetItem(o, i)), pyTupleToValuesHelper(o, i + 1, size));
}

const list<value> pyTupleToValues(PyObject* o) {
    return pyTupleToValuesHelper(o, 0, PyTuple_Size(o));
}

/**
 * Lambda function used to represent a python callable object.
 */
struct pyCallable {
    PyObject* func;

    pyCallable(PyObject* func) : func(func) {
        Py_INCREF(func);
    }

    ~pyCallable() {
        Py_DECREF(func);
    }

    const value operator()(const list<value>& args) const {
        PyObject* pyargs = valuesToPyTuple(args);
        PyObject* result = PyObject_CallObject(func, pyargs);
        Py_DECREF(pyargs);
        const value v = pyObjectToValue(result);
        Py_DECREF(result);
        return v;
    }
};

/**
 * Convert a python object to a value.
 */
const value pyObjectToValue(PyObject *o) {
    if (PyString_Check(o)) {
        const char* s = PyString_AsString(o);
        if (*s == '\'')
            return value(s + 1);
        return value(string(s));
    }
    if (PyBool_Check(o))
        return value(o == Py_True);
    if (PyInt_Check(o))
        return value((double)PyInt_AsLong(o));
    if (PyLong_Check(o))
        return value((double)PyLong_AsLong(o));
    if (PyFloat_Check(o))
        return value((double)PyFloat_AsDouble(o));
    if (PyTuple_Check(o))
        return pyTupleToValues(o);
    if (PyCallable_Check(o))
        return lambda<value(const list<value>&)>(pyCallable(o));
    return value();
}

/**
 * Convert a python script path to a module name.
 */
const string moduleName(const string& path) {
    return join(".", tokenize("/", substr(path, 0, length(path) -3)));
}

/**
 * Evaluate an expression against a script provided as a python object.
 */
const failable<value> evalScript(const value& expr, PyObject* script) {

    // Get the requested function
    PyObject* func = PyObject_GetAttrString(script, c_str(car<value>(expr)));
    if (func == NULL) {

        // The start, stop, and restart functions are optional
        const value fn = car<value>(expr);
        if (fn == "start" || fn == "stop") {
            PyErr_Clear();
            return value(lambda<value(const list<value>&)>());
        }

        return mkfailure<value>(string("Couldn't find function: ") + car<value>(expr) + " : " + lastError());
    }
    if (!PyCallable_Check(func)) {
        Py_DECREF(func);
        return mkfailure<value>(string("Couldn't find callable function: ") + car<value>(expr));
    }

    // Convert args to python objects
    PyObject* args = valuesToPyTuple(cdr<value>(expr));

    // Call the function
    PyObject* result = PyObject_CallObject(func, args);
    Py_DECREF(args);
    Py_DECREF(func);
    if (result == NULL)
        return mkfailure<value>(string("Function call failed: ") + car<value>(expr) + " : " + lastError());

    // Convert python result to a value
    const value v = pyObjectToValue(result);
    Py_DECREF(result);
    return v;
}

/**
 * Read a python script from an input stream.
 */
const failable<PyObject*> readScript(const string& name, const string& path, istream& is) {
    const list<string> ls = streamList(is);
    ostringstream os;
    write(ls, os);
    PyObject* code = Py_CompileStringFlags(c_str(str(os)), c_str(path), Py_file_input, NULL);
    if (code == NULL)
        return mkfailure<PyObject*>(string("Couldn't compile script: ") + path + " : " + lastError());
    PyObject* mod = PyImport_ExecCodeModuleEx(const_cast<char*>(c_str(name)), code, const_cast<char*>(c_str(path)));
    if (mod == NULL)
        return mkfailure<PyObject*>(string("Couldn't import module: ") + path + " : " + lastError());
    return mod;
}

/**
 * Evaluate an expression against a script provided as an input stream.
 */
const failable<value> evalScript(const value& expr, istream& is) {
    failable<PyObject*> script = readScript("script", "script.py", is);
    if (!hasContent(script))
        return mkfailure<value>(reason(script));
    return evalScript(expr, content(script));
}

}
}
#endif /* tuscany_python_eval_hpp */