isl_output.c: print_disjunct: use names from space argument
[isl.git] / interface / python.cc
blob6bef4f322cbe6a8fc1df9e66e3de1c977f7592c3
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 "isl_config.h"
36 #include <stdio.h>
37 #include <iostream>
38 #include <map>
39 #include <clang/AST/Attr.h>
40 #include "extract_interface.h"
41 #include "python.h"
43 /* Is the given type declaration marked as being a subtype of some other
44 * type? If so, return that other type in "super".
46 static bool is_subclass(RecordDecl *decl, string &super)
48 if (!decl->hasAttrs())
49 return false;
51 string sub = "isl_subclass";
52 size_t len = sub.length();
53 AttrVec attrs = decl->getAttrs();
54 for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
55 const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
56 if (!ann)
57 continue;
58 string s = ann->getAnnotation().str();
59 if (s.substr(0, len) == sub) {
60 super = s.substr(len + 1, s.length() - len - 2);
61 return true;
65 return false;
68 /* Is decl marked as a constructor?
70 static bool is_constructor(Decl *decl)
72 return has_annotation(decl, "isl_constructor");
75 /* Is decl marked as consuming a reference?
77 static bool takes(Decl *decl)
79 return has_annotation(decl, "isl_take");
82 /* isl_class collects all constructors and methods for an isl "class".
83 * "name" is the name of the class.
84 * "type" is the declaration that introduces the type.
86 struct isl_class {
87 string name;
88 RecordDecl *type;
89 set<FunctionDecl *> constructors;
90 set<FunctionDecl *> methods;
92 void print(map<string, isl_class> &classes, set<string> &done);
93 void print_constructor(FunctionDecl *method);
94 void print_method(FunctionDecl *method, bool subclass, string super);
97 /* Return the class that has a name that matches the initial part
98 * of the namd of function "fd".
100 static isl_class &method2class(map<string, isl_class> &classes,
101 FunctionDecl *fd)
103 string best;
104 map<string, isl_class>::iterator ci;
105 string name = fd->getNameAsString();
107 for (ci = classes.begin(); ci != classes.end(); ++ci) {
108 if (name.substr(0, ci->first.length()) == ci->first)
109 best = ci->first;
112 return classes[best];
115 /* Is "type" the type "isl_ctx *"?
117 static bool is_isl_ctx(QualType type)
119 if (!type->isPointerType())
120 return 0;
121 type = type->getPointeeType();
122 if (type.getAsString() != "isl_ctx")
123 return false;
125 return true;
128 /* Is the first argument of "fd" of type "isl_ctx *"?
130 static bool first_arg_is_isl_ctx(FunctionDecl *fd)
132 ParmVarDecl *param;
134 if (fd->getNumParams() < 1)
135 return false;
137 param = fd->getParamDecl(0);
138 return is_isl_ctx(param->getOriginalType());
141 /* Is "type" that of a pointer to an isl_* structure?
143 static bool is_isl_type(QualType type)
145 if (type->isPointerType()) {
146 string s;
148 type = type->getPointeeType();
149 if (type->isFunctionType())
150 return false;
151 s = type.getAsString();
152 return s.substr(0, 4) == "isl_";
155 return false;
158 /* Is "type" that of a pointer to a function?
160 static bool is_callback(QualType type)
162 if (!type->isPointerType())
163 return false;
164 type = type->getPointeeType();
165 return type->isFunctionType();
168 /* Is "type" that of "char *" of "const char *"?
170 static bool is_string(QualType type)
172 if (type->isPointerType()) {
173 string s = type->getPointeeType().getAsString();
174 return s == "const char" || s == "char";
177 return false;
180 /* Return the name of the type that "type" points to.
181 * The input "type" is assumed to be a pointer type.
183 static string extract_type(QualType type)
185 if (type->isPointerType())
186 return type->getPointeeType().getAsString();
187 assert(0);
190 /* Drop the "isl_" initial part of the type name "name".
192 static string type2python(string name)
194 return name.substr(4);
197 /* Construct a wrapper for a callback argument (at position "arg").
198 * Assign the wrapper to "cb". We assume here that a function call
199 * has at most one callback argument.
201 * The wrapper converts the arguments of the callback to python types.
202 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
203 * and returns -1. Otherwise the wrapper returns 0.
205 static void print_callback(QualType type, int arg)
207 const FunctionProtoType *fn = type->getAs<FunctionProtoType>();
208 unsigned n_arg = fn->getNumArgs();
210 printf(" exc_info = [None]\n");
211 printf(" fn = CFUNCTYPE(c_int");
212 for (int i = 0; i < n_arg - 1; ++i) {
213 QualType arg_type = fn->getArgType(i);
214 assert(is_isl_type(arg_type));
215 printf(", c_void_p");
217 printf(", c_void_p)\n");
218 printf(" def cb_func(");
219 for (int i = 0; i < n_arg; ++i) {
220 if (i)
221 printf(", ");
222 printf("cb_arg%d", i);
224 printf("):\n");
225 for (int i = 0; i < n_arg - 1; ++i) {
226 string arg_type;
227 arg_type = type2python(extract_type(fn->getArgType(i)));
228 printf(" cb_arg%d = %s(ctx=arg0.ctx, "
229 "ptr=cb_arg%d)\n", i, arg_type.c_str(), i);
231 printf(" try:\n");
232 printf(" arg%d(", arg);
233 for (int i = 0; i < n_arg - 1; ++i) {
234 if (i)
235 printf(", ");
236 printf("cb_arg%d", i);
238 printf(")\n");
239 printf(" except:\n");
240 printf(" import sys\n");
241 printf(" exc_info[0] = sys.exc_info()\n");
242 printf(" return -1\n");
243 printf(" return 0\n");
244 printf(" cb = fn(cb_func)\n");
247 /* Print a python method corresponding to the C function "method".
248 * "subclass" is set if the method belongs to a class that is a subclass
249 * of some other class ("super").
251 * If the function has a callback argument, then it also has a "user"
252 * argument. Since Python has closures, there is no need for such
253 * a user argument in the Python interface, so we simply drop it.
254 * We also create a wrapper ("cb") for the callback.
256 * For each argument of the function that refers to an isl structure,
257 * including the object on which the method is called,
258 * we check if the corresponding actual argument is of the right type.
259 * If not, we try to convert it to the right type.
260 * It that doesn't work and if subclass is set, we try to convert self
261 * to the type of the superclass and call the corresponding method.
263 * If the function consumes a reference, then we pass it a copy of
264 * the actual argument.
266 void isl_class::print_method(FunctionDecl *method, bool subclass, string super)
268 string fullname = method->getName();
269 string cname = fullname.substr(name.length() + 1);
270 int num_params = method->getNumParams();
271 int drop_user = 0;
273 for (int i = 1; i < num_params; ++i) {
274 ParmVarDecl *param = method->getParamDecl(i);
275 QualType type = param->getOriginalType();
276 if (is_callback(type))
277 drop_user = 1;
280 printf(" def %s(arg0", cname.c_str());
281 for (int i = 1; i < num_params - drop_user; ++i)
282 printf(", arg%d", i);
283 printf("):\n");
285 for (int i = 0; i < num_params; ++i) {
286 ParmVarDecl *param = method->getParamDecl(i);
287 string type;
288 if (!is_isl_type(param->getOriginalType()))
289 continue;
290 type = type2python(extract_type(param->getOriginalType()));
291 printf(" try:\n");
292 printf(" if not arg%d.__class__ is %s:\n",
293 i, type.c_str());
294 printf(" arg%d = %s(arg%d)\n",
295 i, type.c_str(), i);
296 printf(" except:\n");
297 if (i > 0 && subclass) {
298 printf(" return %s(arg0).%s(",
299 type2python(super).c_str(), cname.c_str());
300 for (int i = 1; i < num_params - drop_user; ++i) {
301 if (i != 1)
302 printf(", ");
303 printf("arg%d", i);
305 printf(")\n");
306 } else
307 printf(" raise\n");
309 for (int i = 1; i < num_params; ++i) {
310 ParmVarDecl *param = method->getParamDecl(i);
311 QualType type = param->getOriginalType();
312 if (!is_callback(type))
313 continue;
314 print_callback(type->getPointeeType(), i);
316 printf(" res = isl.%s(", fullname.c_str());
317 if (takes(method->getParamDecl(0)))
318 printf("isl.%s_copy(arg0.ptr)", name.c_str());
319 else
320 printf("arg0.ptr");
321 for (int i = 1; i < num_params - drop_user; ++i) {
322 ParmVarDecl *param = method->getParamDecl(i);
323 QualType type = param->getOriginalType();
324 if (is_callback(type))
325 printf(", cb");
326 else if (takes(param)) {
327 string type_s = extract_type(type);
328 printf(", isl.%s_copy(arg%d.ptr)", type_s.c_str(), i);
329 } else
330 printf(", arg%d.ptr", i);
332 if (drop_user)
333 printf(", None");
334 printf(")\n");
336 if (is_isl_type(method->getReturnType())) {
337 string type;
338 type = type2python(extract_type(method->getReturnType()));
339 printf(" return %s(ctx=arg0.ctx, ptr=res)\n",
340 type.c_str());
341 } else {
342 if (drop_user) {
343 printf(" if exc_info[0] != None:\n");
344 printf(" raise exc_info[0][0], "
345 "exc_info[0][1], exc_info[0][2]\n");
347 printf(" return res\n");
351 /* Print part of the constructor for this isl_class.
353 * In particular, check if the actual arguments correspond to the
354 * formal arguments of "cons" and if so call "cons" and put the
355 * result in self.ptr and a reference to the default context in self.ctx.
357 * If the function consumes a reference, then we pass it a copy of
358 * the actual argument.
360 void isl_class::print_constructor(FunctionDecl *cons)
362 string fullname = cons->getName();
363 string cname = fullname.substr(name.length() + 1);
364 int num_params = cons->getNumParams();
365 int drop_ctx = first_arg_is_isl_ctx(cons);
367 printf(" if len(args) == %d", num_params - drop_ctx);
368 for (int i = drop_ctx; i < num_params; ++i) {
369 ParmVarDecl *param = cons->getParamDecl(i);
370 if (is_isl_type(param->getOriginalType())) {
371 string type;
372 type = extract_type(param->getOriginalType());
373 type = type2python(type);
374 printf(" and args[%d].__class__ is %s",
375 i - drop_ctx, type.c_str());
376 } else
377 printf(" and type(args[%d]) == str", i - drop_ctx);
379 printf(":\n");
380 printf(" self.ctx = Context.getDefaultInstance()\n");
381 printf(" self.ptr = isl.%s(", fullname.c_str());
382 if (drop_ctx)
383 printf("self.ctx");
384 for (int i = drop_ctx; i < num_params; ++i) {
385 ParmVarDecl *param = cons->getParamDecl(i);
386 if (i)
387 printf(", ");
388 if (is_isl_type(param->getOriginalType())) {
389 if (takes(param)) {
390 string type;
391 type = extract_type(param->getOriginalType());
392 printf("isl.%s_copy(args[%d].ptr)",
393 type.c_str(), i - drop_ctx);
394 } else
395 printf("args[%d].ptr", i - drop_ctx);
396 } else
397 printf("args[%d]", i - drop_ctx);
399 printf(")\n");
400 printf(" return\n");
403 /* Print out the definition of this isl_class.
405 * We first check if this isl_class is a subclass of some other class.
406 * If it is, we make sure the superclass is printed out first.
408 * Then we print a constructor with several cases, one for constructing
409 * a Python object from a return value and one for each function that
410 * was marked as a constructor.
412 * Next, we print out some common methods and the methods corresponding
413 * to functions that are not marked as constructors.
415 * Finally, we tell ctypes about the types of the arguments of the
416 * constructor functions and the return types of those function returning
417 * an isl object.
419 void isl_class::print(map<string, isl_class> &classes, set<string> &done)
421 string super;
422 string p_name = type2python(name);
423 set<FunctionDecl *>::iterator in;
424 bool subclass = is_subclass(type, super);
426 if (subclass && done.find(super) == done.end())
427 classes[super].print(classes, done);
428 done.insert(name);
430 printf("\n");
431 printf("class %s", p_name.c_str());
432 if (subclass)
433 printf("(%s)", type2python(super).c_str());
434 printf(":\n");
435 printf(" def __init__(self, *args, **keywords):\n");
437 printf(" if \"ptr\" in keywords:\n");
438 printf(" self.ctx = keywords[\"ctx\"]\n");
439 printf(" self.ptr = keywords[\"ptr\"]\n");
440 printf(" return\n");
442 for (in = constructors.begin(); in != constructors.end(); ++in)
443 print_constructor(*in);
444 printf(" raise Error\n");
445 printf(" def __del__(self):\n");
446 printf(" if hasattr(self, 'ptr'):\n");
447 printf(" isl.%s_free(self.ptr)\n", name.c_str());
448 printf(" def __str__(self):\n");
449 printf(" ptr = isl.%s_to_str(self.ptr)\n", name.c_str());
450 printf(" res = str(cast(ptr, c_char_p).value)\n");
451 printf(" libc.free(ptr)\n");
452 printf(" return res\n");
453 printf(" def __repr__(self):\n");
454 printf(" return 'isl.%s(\"%%s\")' %% str(self)\n",
455 p_name.c_str());
457 for (in = methods.begin(); in != methods.end(); ++in)
458 print_method(*in, subclass, super);
460 printf("\n");
461 for (in = constructors.begin(); in != constructors.end(); ++in) {
462 string fullname = (*in)->getName();
463 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
464 printf("isl.%s.argtypes = [", fullname.c_str());
465 for (int i = 0; i < (*in)->getNumParams(); ++i) {
466 ParmVarDecl *param = (*in)->getParamDecl(i);
467 QualType type = param->getOriginalType();
468 if (i)
469 printf(", ");
470 if (is_isl_ctx(type))
471 printf("Context");
472 else if (is_isl_type(type))
473 printf("c_void_p");
474 else if (is_string(type))
475 printf("c_char_p");
476 else
477 printf("c_int");
479 printf("]\n");
481 for (in = methods.begin(); in != methods.end(); ++in) {
482 string fullname = (*in)->getName();
483 if (is_isl_type((*in)->getReturnType()))
484 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
486 printf("isl.%s_free.argtypes = [c_void_p]\n", name.c_str());
487 printf("isl.%s_to_str.argtypes = [c_void_p]\n", name.c_str());
488 printf("isl.%s_to_str.restype = POINTER(c_char)\n", name.c_str());
491 /* Generate a python interface based on the extracted types and functions.
492 * We first collect all functions that belong to a certain type,
493 * separating constructors from regular methods.
495 * Then we print out each class in turn. If one of these is a subclass
496 * of some other class, it will make sure the superclass is printed out first.
498 void generate_python(set<RecordDecl *> &types, set<FunctionDecl *> functions)
500 map<string, isl_class> classes;
501 map<string, isl_class>::iterator ci;
502 set<string> done;
504 set<RecordDecl *>::iterator it;
505 for (it = types.begin(); it != types.end(); ++it) {
506 RecordDecl *decl = *it;
507 string name = decl->getName();
508 classes[name].name = name;
509 classes[name].type = decl;
512 set<FunctionDecl *>::iterator in;
513 for (in = functions.begin(); in != functions.end(); ++in) {
514 isl_class &c = method2class(classes, *in);
515 if (is_constructor(*in))
516 c.constructors.insert(*in);
517 else
518 c.methods.insert(*in);
521 for (ci = classes.begin(); ci != classes.end(); ++ci) {
522 if (done.find(ci->first) == done.end())
523 ci->second.print(classes, done);