configure.ac: remove spurious ","
[isl.git] / interface / python.cc
blob784b4be389aea7072735cbf0c5c29b6bed608f60
1 /*
2 * Copyright 2011 Sven Verdoolaege. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY SVEN VERDOOLAEGE ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SVEN VERDOOLAEGE OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
31 * Sven Verdoolaege.
32 */
34 #include <stdio.h>
35 #include <iostream>
36 #include <map>
37 #include "extract_interface.h"
38 #include "python.h"
40 /* Is the given type declaration marked as being a subtype of some other
41 * type? If so, return that other type in "super".
43 static bool is_subclass(RecordDecl *decl, string &super)
45 if (!decl->hasAttrs())
46 return false;
48 string sub = "isl_subclass";
49 size_t len = sub.length();
50 AttrVec attrs = decl->getAttrs();
51 for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
52 const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
53 if (!ann)
54 continue;
55 string s = ann->getAnnotation().str();
56 if (s.substr(0, len) == sub) {
57 super = s.substr(len + 1, s.length() - len - 2);
58 return true;
62 return false;
65 /* Is decl marked as a constructor?
67 static bool is_constructor(Decl *decl)
69 return has_annotation(decl, "isl_constructor");
72 /* Is decl marked as consuming a reference?
74 static bool takes(Decl *decl)
76 return has_annotation(decl, "isl_take");
79 /* isl_class collects all constructors and methods for an isl "class".
80 * "name" is the name of the class.
81 * "type" is the declaration that introduces the type.
83 struct isl_class {
84 string name;
85 RecordDecl *type;
86 set<FunctionDecl *> constructors;
87 set<FunctionDecl *> methods;
89 void print(map<string, isl_class> &classes, set<string> &done);
90 void print_constructor(FunctionDecl *method);
91 void print_method(FunctionDecl *method, bool subclass, string super);
94 /* Return the class that has a name that matches the initial part
95 * of the namd of function "fd".
97 static isl_class &method2class(map<string, isl_class> &classes,
98 FunctionDecl *fd)
100 string best;
101 map<string, isl_class>::iterator ci;
102 string name = fd->getNameAsString();
104 for (ci = classes.begin(); ci != classes.end(); ++ci) {
105 if (name.substr(0, ci->first.length()) == ci->first)
106 best = ci->first;
109 return classes[best];
112 /* Is "type" the type "isl_ctx *"?
114 static bool is_isl_ctx(QualType type)
116 if (!type->isPointerType())
117 return 0;
118 type = type->getPointeeType();
119 if (type.getAsString() != "isl_ctx")
120 return false;
122 return true;
125 /* Is the first argument of "fd" of type "isl_ctx *"?
127 static bool first_arg_is_isl_ctx(FunctionDecl *fd)
129 ParmVarDecl *param;
131 if (fd->getNumParams() < 1)
132 return false;
134 param = fd->getParamDecl(0);
135 return is_isl_ctx(param->getOriginalType());
138 /* Is "type" that of a pointer to an isl_* structure?
140 static bool is_isl_type(QualType type)
142 if (type->isPointerType()) {
143 string s = type->getPointeeType().getAsString();
144 return s.substr(0, 4) == "isl_";
147 return false;
150 /* Is "type" that of a pointer to a function?
152 static bool is_callback(QualType type)
154 if (!type->isPointerType())
155 return false;
156 type = type->getPointeeType();
157 return type->isFunctionType();
160 /* Is "type" that of "char *" of "const char *"?
162 static bool is_string(QualType type)
164 if (type->isPointerType()) {
165 string s = type->getPointeeType().getAsString();
166 return s == "const char" || s == "char";
169 return false;
172 /* Return the name of the type that "type" points to.
173 * The input "type" is assumed to be a pointer type.
175 static string extract_type(QualType type)
177 if (type->isPointerType())
178 return type->getPointeeType().getAsString();
179 assert(0);
182 /* Drop the "isl_" initial part of the type name "name".
184 static string type2python(string name)
186 return name.substr(4);
189 /* Construct a wrapper for a callback argument (at position "arg").
190 * Assign the wrapper to "cb". We assume here that a function call
191 * has at most one callback argument.
193 * The wrapper converts the arguments of the callback to python types.
194 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
195 * and returns -1. Otherwise the wrapper returns 0.
197 static void print_callback(QualType type, int arg)
199 const FunctionProtoType *fn = type->getAs<FunctionProtoType>();
200 unsigned n_arg = fn->getNumArgs();
202 printf(" exc_info = [None]\n");
203 printf(" fn = CFUNCTYPE(c_int");
204 for (int i = 0; i < n_arg - 1; ++i) {
205 QualType arg_type = fn->getArgType(i);
206 assert(is_isl_type(arg_type));
207 printf(", c_void_p");
209 printf(", c_void_p)\n");
210 printf(" def cb_func(");
211 for (int i = 0; i < n_arg; ++i) {
212 if (i)
213 printf(", ");
214 printf("cb_arg%d", i);
216 printf("):\n");
217 for (int i = 0; i < n_arg - 1; ++i) {
218 string arg_type;
219 arg_type = type2python(extract_type(fn->getArgType(i)));
220 printf(" cb_arg%d = %s(ctx=self.ctx, ptr=cb_arg%d)\n",
221 i, arg_type.c_str(), i);
223 printf(" try:\n");
224 printf(" arg%d(", arg);
225 for (int i = 0; i < n_arg - 1; ++i) {
226 if (i)
227 printf(", ");
228 printf("cb_arg%d", i);
230 printf(")\n");
231 printf(" except:\n");
232 printf(" import sys\n");
233 printf(" exc_info[0] = sys.exc_info()\n");
234 printf(" return -1\n");
235 printf(" return 0\n");
236 printf(" cb = fn(cb_func)\n");
239 /* Print a python method corresponding to the C function "method".
240 * "subclass" is set if the method belongs to a class that is a subclass
241 * of some other class ("super").
243 * If the function has a callback argument, then it also has a "user"
244 * argument. Since Python has closures, there is no need for such
245 * a user argument in the Python interface, so we simply drop it.
246 * We also create a wrapper ("cb") for the callback.
248 * If the function has additional arguments that refer to isl structures,
249 * then we check if the actual arguments are of the right type.
250 * If not, we try to convert it to the right type.
251 * It that doesn't work and if subclass is set, we try to convert self
252 * to the type of the superclass and call the corresponding method.
254 * If the function consumes a reference, then we pass it a copy of
255 * the actual argument.
257 void isl_class::print_method(FunctionDecl *method, bool subclass, string super)
259 string fullname = method->getName();
260 string cname = fullname.substr(name.length() + 1);
261 int num_params = method->getNumParams();
262 int drop_user = 0;
264 for (int i = 1; i < num_params; ++i) {
265 ParmVarDecl *param = method->getParamDecl(i);
266 QualType type = param->getOriginalType();
267 if (is_callback(type))
268 drop_user = 1;
271 printf(" def %s(self", cname.c_str());
272 for (int i = 1; i < num_params - drop_user; ++i)
273 printf(", arg%d", i);
274 printf("):\n");
276 for (int i = 1; i < num_params; ++i) {
277 ParmVarDecl *param = method->getParamDecl(i);
278 string type;
279 if (!is_isl_type(param->getOriginalType()))
280 continue;
281 type = type2python(extract_type(param->getOriginalType()));
282 printf(" try:\n");
283 printf(" if not arg%d.__class__ is %s:\n",
284 i, type.c_str());
285 printf(" arg%d = %s(arg%d)\n",
286 i, type.c_str(), i);
287 printf(" except:\n");
288 if (subclass) {
289 printf(" return %s(self).%s(",
290 type2python(super).c_str(), cname.c_str());
291 for (int i = 1; i < num_params - drop_user; ++i) {
292 if (i != 1)
293 printf(", ");
294 printf("arg%d", i);
296 printf(")\n");
297 } else
298 printf(" raise\n");
300 for (int i = 1; i < num_params; ++i) {
301 ParmVarDecl *param = method->getParamDecl(i);
302 QualType type = param->getOriginalType();
303 if (!is_callback(type))
304 continue;
305 print_callback(type->getPointeeType(), i);
307 printf(" res = isl.%s(", fullname.c_str());
308 if (takes(method->getParamDecl(0)))
309 printf("isl.%s_copy(self.ptr)", name.c_str());
310 else
311 printf("self.ptr");
312 for (int i = 1; i < num_params - drop_user; ++i) {
313 ParmVarDecl *param = method->getParamDecl(i);
314 QualType type = param->getOriginalType();
315 if (is_callback(type))
316 printf(", cb");
317 else if (takes(param)) {
318 string type_s = extract_type(type);
319 printf(", isl.%s_copy(arg%d.ptr)", type_s.c_str(), i);
320 } else
321 printf(", arg%d.ptr", i);
323 if (drop_user)
324 printf(", None");
325 printf(")\n");
327 if (is_isl_type(method->getResultType())) {
328 string type;
329 type = type2python(extract_type(method->getResultType()));
330 printf(" return %s(ctx=self.ctx, ptr=res)\n",
331 type.c_str());
332 } else {
333 if (drop_user) {
334 printf(" if exc_info[0] != None:\n");
335 printf(" raise exc_info[0][0], "
336 "exc_info[0][1], exc_info[0][2]\n");
338 printf(" return res\n");
342 /* Print part of the constructor for this isl_class.
344 * In particular, check if the actual arguments correspond to the
345 * formal arguments of "cons" and if so call "cons" and put the
346 * result in self.ptr and a reference to the default context in self.ctx.
348 * If the function consumes a reference, then we pass it a copy of
349 * the actual argument.
351 void isl_class::print_constructor(FunctionDecl *cons)
353 string fullname = cons->getName();
354 string cname = fullname.substr(name.length() + 1);
355 int num_params = cons->getNumParams();
356 int drop_ctx = first_arg_is_isl_ctx(cons);
358 printf(" if len(args) == %d", num_params - drop_ctx);
359 for (int i = drop_ctx; i < num_params; ++i) {
360 ParmVarDecl *param = cons->getParamDecl(i);
361 if (is_isl_type(param->getOriginalType())) {
362 string type;
363 type = extract_type(param->getOriginalType());
364 type = type2python(type);
365 printf(" and args[%d].__class__ is %s",
366 i - drop_ctx, type.c_str());
367 } else
368 printf(" and type(args[%d]) == str", i - drop_ctx);
370 printf(":\n");
371 printf(" self.ctx = Context.getDefaultInstance()\n");
372 printf(" self.ptr = isl.%s(", fullname.c_str());
373 if (drop_ctx)
374 printf("self.ctx");
375 for (int i = drop_ctx; i < num_params; ++i) {
376 ParmVarDecl *param = cons->getParamDecl(i);
377 if (i)
378 printf(", ");
379 if (is_isl_type(param->getOriginalType())) {
380 if (takes(param)) {
381 string type;
382 type = extract_type(param->getOriginalType());
383 printf("isl.%s_copy(args[%d].ptr)",
384 type.c_str(), i - drop_ctx);
385 } else
386 printf("args[%d].ptr", i - drop_ctx);
387 } else
388 printf("args[%d]", i - drop_ctx);
390 printf(")\n");
391 printf(" return\n");
394 /* Print out the definition of this isl_class.
396 * We first check if this isl_class is a subclass of some other class.
397 * If it is, we make sure the superclass is printed out first.
399 * Then we print a constructor with several cases, one for constructing
400 * a Python object from a return value and one for each function that
401 * was marked as a constructor.
403 * Next, we print out some common methods and the methods corresponding
404 * to functions that are not marked as constructors.
406 * Finally, we tell ctypes about the types of the arguments of the
407 * constructor functions and the return types of those function returning
408 * an isl object.
410 void isl_class::print(map<string, isl_class> &classes, set<string> &done)
412 string super;
413 string p_name = type2python(name);
414 set<FunctionDecl *>::iterator in;
415 bool subclass = is_subclass(type, super);
417 if (subclass && done.find(super) == done.end())
418 classes[super].print(classes, done);
419 done.insert(name);
421 printf("\n");
422 printf("class %s", p_name.c_str());
423 if (subclass)
424 printf("(%s)", type2python(super).c_str());
425 printf(":\n");
426 printf(" def __init__(self, *args, **keywords):\n");
428 printf(" if \"ptr\" in keywords:\n");
429 printf(" self.ctx = keywords[\"ctx\"]\n");
430 printf(" self.ptr = keywords[\"ptr\"]\n");
431 printf(" return\n");
433 for (in = constructors.begin(); in != constructors.end(); ++in)
434 print_constructor(*in);
435 printf(" raise Error\n");
436 printf(" def __del__(self):\n");
437 printf(" if hasattr(self, 'ptr'):\n");
438 printf(" isl.%s_free(self.ptr)\n", name.c_str());
439 printf(" def __str__(self):\n");
440 printf(" ptr = isl.%s_to_str(self.ptr)\n", name.c_str());
441 printf(" res = str(cast(ptr, c_char_p).value)\n");
442 printf(" libc.free(ptr)\n");
443 printf(" return res\n");
444 printf(" def __repr__(self):\n");
445 printf(" return 'isl.%s(\"%%s\")' %% str(self)\n", p_name.c_str());
447 for (in = methods.begin(); in != methods.end(); ++in)
448 print_method(*in, subclass, super);
450 printf("\n");
451 for (in = constructors.begin(); in != constructors.end(); ++in) {
452 string fullname = (*in)->getName();
453 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
454 printf("isl.%s.argtypes = [", fullname.c_str());
455 for (int i = 0; i < (*in)->getNumParams(); ++i) {
456 ParmVarDecl *param = (*in)->getParamDecl(i);
457 QualType type = param->getOriginalType();
458 if (i)
459 printf(", ");
460 if (is_isl_ctx(type))
461 printf("Context");
462 else if (is_isl_type(type))
463 printf("c_void_p");
464 else if (is_string(type))
465 printf("c_char_p");
466 else
467 printf("c_int");
469 printf("]\n");
471 for (in = methods.begin(); in != methods.end(); ++in) {
472 string fullname = (*in)->getName();
473 if (is_isl_type((*in)->getResultType()))
474 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
476 printf("isl.%s_free.argtypes = [c_void_p]\n", name.c_str());
477 printf("isl.%s_to_str.argtypes = [c_void_p]\n", name.c_str());
478 printf("isl.%s_to_str.restype = POINTER(c_char)\n", name.c_str());
481 /* Generate a python interface based on the extracted types and functions.
482 * We first collect all functions that belong to a certain type,
483 * separating constructors from regular methods.
485 * Then we print out each class in turn. If one of these is a subclass
486 * of some other class, it will make sure the superclass is printed out first.
488 void generate_python(set<RecordDecl *> &types, set<FunctionDecl *> functions)
490 map<string, isl_class> classes;
491 map<string, isl_class>::iterator ci;
492 set<string> done;
494 set<RecordDecl *>::iterator it;
495 for (it = types.begin(); it != types.end(); ++it) {
496 RecordDecl *decl = *it;
497 string name = decl->getName();
498 classes[name].name = name;
499 classes[name].type = decl;
502 set<FunctionDecl *>::iterator in;
503 for (in = functions.begin(); in != functions.end(); ++in) {
504 isl_class &c = method2class(classes, *in);
505 if (is_constructor(*in))
506 c.constructors.insert(*in);
507 else
508 c.methods.insert(*in);
511 for (ci = classes.begin(); ci != classes.end(); ++ci) {
512 if (done.find(ci->first) == done.end())
513 ci->second.print(classes, done);