export isl_ast_expr_set_op_arg
[isl.git] / interface / python.cc
blob3b54a03cd7b3bb6e2cc27a11574bc0319d39f3c9
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 <clang/AST/Attr.h>
38 #include "extract_interface.h"
39 #include "python.h"
41 /* Is the given type declaration marked as being a subtype of some other
42 * type? If so, return that other type in "super".
44 static bool is_subclass(RecordDecl *decl, string &super)
46 if (!decl->hasAttrs())
47 return false;
49 string sub = "isl_subclass";
50 size_t len = sub.length();
51 AttrVec attrs = decl->getAttrs();
52 for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
53 const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
54 if (!ann)
55 continue;
56 string s = ann->getAnnotation().str();
57 if (s.substr(0, len) == sub) {
58 super = s.substr(len + 1, s.length() - len - 2);
59 return true;
63 return false;
66 /* Is decl marked as a constructor?
68 static bool is_constructor(Decl *decl)
70 return has_annotation(decl, "isl_constructor");
73 /* Is decl marked as consuming a reference?
75 static bool takes(Decl *decl)
77 return has_annotation(decl, "isl_take");
80 /* isl_class collects all constructors and methods for an isl "class".
81 * "name" is the name of the class.
82 * "type" is the declaration that introduces the type.
84 struct isl_class {
85 string name;
86 RecordDecl *type;
87 set<FunctionDecl *> constructors;
88 set<FunctionDecl *> methods;
90 void print(map<string, isl_class> &classes, set<string> &done);
91 void print_constructor(FunctionDecl *method);
92 void print_method(FunctionDecl *method, bool subclass, string super);
95 /* Return the class that has a name that matches the initial part
96 * of the namd of function "fd".
98 static isl_class &method2class(map<string, isl_class> &classes,
99 FunctionDecl *fd)
101 string best;
102 map<string, isl_class>::iterator ci;
103 string name = fd->getNameAsString();
105 for (ci = classes.begin(); ci != classes.end(); ++ci) {
106 if (name.substr(0, ci->first.length()) == ci->first)
107 best = ci->first;
110 return classes[best];
113 /* Is "type" the type "isl_ctx *"?
115 static bool is_isl_ctx(QualType type)
117 if (!type->isPointerType())
118 return 0;
119 type = type->getPointeeType();
120 if (type.getAsString() != "isl_ctx")
121 return false;
123 return true;
126 /* Is the first argument of "fd" of type "isl_ctx *"?
128 static bool first_arg_is_isl_ctx(FunctionDecl *fd)
130 ParmVarDecl *param;
132 if (fd->getNumParams() < 1)
133 return false;
135 param = fd->getParamDecl(0);
136 return is_isl_ctx(param->getOriginalType());
139 /* Is "type" that of a pointer to an isl_* structure?
141 static bool is_isl_type(QualType type)
143 if (type->isPointerType()) {
144 string s = type->getPointeeType().getAsString();
145 return s.substr(0, 4) == "isl_";
148 return false;
151 /* Is "type" that of a pointer to a function?
153 static bool is_callback(QualType type)
155 if (!type->isPointerType())
156 return false;
157 type = type->getPointeeType();
158 return type->isFunctionType();
161 /* Is "type" that of "char *" of "const char *"?
163 static bool is_string(QualType type)
165 if (type->isPointerType()) {
166 string s = type->getPointeeType().getAsString();
167 return s == "const char" || s == "char";
170 return false;
173 /* Return the name of the type that "type" points to.
174 * The input "type" is assumed to be a pointer type.
176 static string extract_type(QualType type)
178 if (type->isPointerType())
179 return type->getPointeeType().getAsString();
180 assert(0);
183 /* Drop the "isl_" initial part of the type name "name".
185 static string type2python(string name)
187 return name.substr(4);
190 /* Construct a wrapper for a callback argument (at position "arg").
191 * Assign the wrapper to "cb". We assume here that a function call
192 * has at most one callback argument.
194 * The wrapper converts the arguments of the callback to python types.
195 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
196 * and returns -1. Otherwise the wrapper returns 0.
198 static void print_callback(QualType type, int arg)
200 const FunctionProtoType *fn = type->getAs<FunctionProtoType>();
201 unsigned n_arg = fn->getNumArgs();
203 printf(" exc_info = [None]\n");
204 printf(" fn = CFUNCTYPE(c_int");
205 for (int i = 0; i < n_arg - 1; ++i) {
206 QualType arg_type = fn->getArgType(i);
207 assert(is_isl_type(arg_type));
208 printf(", c_void_p");
210 printf(", c_void_p)\n");
211 printf(" def cb_func(");
212 for (int i = 0; i < n_arg; ++i) {
213 if (i)
214 printf(", ");
215 printf("cb_arg%d", i);
217 printf("):\n");
218 for (int i = 0; i < n_arg - 1; ++i) {
219 string arg_type;
220 arg_type = type2python(extract_type(fn->getArgType(i)));
221 printf(" cb_arg%d = %s(ctx=self.ctx, ptr=cb_arg%d)\n",
222 i, arg_type.c_str(), i);
224 printf(" try:\n");
225 printf(" arg%d(", arg);
226 for (int i = 0; i < n_arg - 1; ++i) {
227 if (i)
228 printf(", ");
229 printf("cb_arg%d", i);
231 printf(")\n");
232 printf(" except:\n");
233 printf(" import sys\n");
234 printf(" exc_info[0] = sys.exc_info()\n");
235 printf(" return -1\n");
236 printf(" return 0\n");
237 printf(" cb = fn(cb_func)\n");
240 /* Print a python method corresponding to the C function "method".
241 * "subclass" is set if the method belongs to a class that is a subclass
242 * of some other class ("super").
244 * If the function has a callback argument, then it also has a "user"
245 * argument. Since Python has closures, there is no need for such
246 * a user argument in the Python interface, so we simply drop it.
247 * We also create a wrapper ("cb") for the callback.
249 * If the function has additional arguments that refer to isl structures,
250 * then we check if the actual arguments are of the right type.
251 * If not, we try to convert it to the right type.
252 * It that doesn't work and if subclass is set, we try to convert self
253 * to the type of the superclass and call the corresponding method.
255 * If the function consumes a reference, then we pass it a copy of
256 * the actual argument.
258 void isl_class::print_method(FunctionDecl *method, bool subclass, string super)
260 string fullname = method->getName();
261 string cname = fullname.substr(name.length() + 1);
262 int num_params = method->getNumParams();
263 int drop_user = 0;
265 for (int i = 1; i < num_params; ++i) {
266 ParmVarDecl *param = method->getParamDecl(i);
267 QualType type = param->getOriginalType();
268 if (is_callback(type))
269 drop_user = 1;
272 printf(" def %s(self", cname.c_str());
273 for (int i = 1; i < num_params - drop_user; ++i)
274 printf(", arg%d", i);
275 printf("):\n");
277 for (int i = 1; i < num_params; ++i) {
278 ParmVarDecl *param = method->getParamDecl(i);
279 string type;
280 if (!is_isl_type(param->getOriginalType()))
281 continue;
282 type = type2python(extract_type(param->getOriginalType()));
283 printf(" try:\n");
284 printf(" if not arg%d.__class__ is %s:\n",
285 i, type.c_str());
286 printf(" arg%d = %s(arg%d)\n",
287 i, type.c_str(), i);
288 printf(" except:\n");
289 if (subclass) {
290 printf(" return %s(self).%s(",
291 type2python(super).c_str(), cname.c_str());
292 for (int i = 1; i < num_params - drop_user; ++i) {
293 if (i != 1)
294 printf(", ");
295 printf("arg%d", i);
297 printf(")\n");
298 } else
299 printf(" raise\n");
301 for (int i = 1; i < num_params; ++i) {
302 ParmVarDecl *param = method->getParamDecl(i);
303 QualType type = param->getOriginalType();
304 if (!is_callback(type))
305 continue;
306 print_callback(type->getPointeeType(), i);
308 printf(" res = isl.%s(", fullname.c_str());
309 if (takes(method->getParamDecl(0)))
310 printf("isl.%s_copy(self.ptr)", name.c_str());
311 else
312 printf("self.ptr");
313 for (int i = 1; i < num_params - drop_user; ++i) {
314 ParmVarDecl *param = method->getParamDecl(i);
315 QualType type = param->getOriginalType();
316 if (is_callback(type))
317 printf(", cb");
318 else if (takes(param)) {
319 string type_s = extract_type(type);
320 printf(", isl.%s_copy(arg%d.ptr)", type_s.c_str(), i);
321 } else
322 printf(", arg%d.ptr", i);
324 if (drop_user)
325 printf(", None");
326 printf(")\n");
328 if (is_isl_type(method->getResultType())) {
329 string type;
330 type = type2python(extract_type(method->getResultType()));
331 printf(" return %s(ctx=self.ctx, ptr=res)\n",
332 type.c_str());
333 } else {
334 if (drop_user) {
335 printf(" if exc_info[0] != None:\n");
336 printf(" raise exc_info[0][0], "
337 "exc_info[0][1], exc_info[0][2]\n");
339 printf(" return res\n");
343 /* Print part of the constructor for this isl_class.
345 * In particular, check if the actual arguments correspond to the
346 * formal arguments of "cons" and if so call "cons" and put the
347 * result in self.ptr and a reference to the default context in self.ctx.
349 * If the function consumes a reference, then we pass it a copy of
350 * the actual argument.
352 void isl_class::print_constructor(FunctionDecl *cons)
354 string fullname = cons->getName();
355 string cname = fullname.substr(name.length() + 1);
356 int num_params = cons->getNumParams();
357 int drop_ctx = first_arg_is_isl_ctx(cons);
359 printf(" if len(args) == %d", num_params - drop_ctx);
360 for (int i = drop_ctx; i < num_params; ++i) {
361 ParmVarDecl *param = cons->getParamDecl(i);
362 if (is_isl_type(param->getOriginalType())) {
363 string type;
364 type = extract_type(param->getOriginalType());
365 type = type2python(type);
366 printf(" and args[%d].__class__ is %s",
367 i - drop_ctx, type.c_str());
368 } else
369 printf(" and type(args[%d]) == str", i - drop_ctx);
371 printf(":\n");
372 printf(" self.ctx = Context.getDefaultInstance()\n");
373 printf(" self.ptr = isl.%s(", fullname.c_str());
374 if (drop_ctx)
375 printf("self.ctx");
376 for (int i = drop_ctx; i < num_params; ++i) {
377 ParmVarDecl *param = cons->getParamDecl(i);
378 if (i)
379 printf(", ");
380 if (is_isl_type(param->getOriginalType())) {
381 if (takes(param)) {
382 string type;
383 type = extract_type(param->getOriginalType());
384 printf("isl.%s_copy(args[%d].ptr)",
385 type.c_str(), i - drop_ctx);
386 } else
387 printf("args[%d].ptr", i - drop_ctx);
388 } else
389 printf("args[%d]", i - drop_ctx);
391 printf(")\n");
392 printf(" return\n");
395 /* Print out the definition of this isl_class.
397 * We first check if this isl_class is a subclass of some other class.
398 * If it is, we make sure the superclass is printed out first.
400 * Then we print a constructor with several cases, one for constructing
401 * a Python object from a return value and one for each function that
402 * was marked as a constructor.
404 * Next, we print out some common methods and the methods corresponding
405 * to functions that are not marked as constructors.
407 * Finally, we tell ctypes about the types of the arguments of the
408 * constructor functions and the return types of those function returning
409 * an isl object.
411 void isl_class::print(map<string, isl_class> &classes, set<string> &done)
413 string super;
414 string p_name = type2python(name);
415 set<FunctionDecl *>::iterator in;
416 bool subclass = is_subclass(type, super);
418 if (subclass && done.find(super) == done.end())
419 classes[super].print(classes, done);
420 done.insert(name);
422 printf("\n");
423 printf("class %s", p_name.c_str());
424 if (subclass)
425 printf("(%s)", type2python(super).c_str());
426 printf(":\n");
427 printf(" def __init__(self, *args, **keywords):\n");
429 printf(" if \"ptr\" in keywords:\n");
430 printf(" self.ctx = keywords[\"ctx\"]\n");
431 printf(" self.ptr = keywords[\"ptr\"]\n");
432 printf(" return\n");
434 for (in = constructors.begin(); in != constructors.end(); ++in)
435 print_constructor(*in);
436 printf(" raise Error\n");
437 printf(" def __del__(self):\n");
438 printf(" if hasattr(self, 'ptr'):\n");
439 printf(" isl.%s_free(self.ptr)\n", name.c_str());
440 printf(" def __str__(self):\n");
441 printf(" ptr = isl.%s_to_str(self.ptr)\n", name.c_str());
442 printf(" res = str(cast(ptr, c_char_p).value)\n");
443 printf(" libc.free(ptr)\n");
444 printf(" return res\n");
445 printf(" def __repr__(self):\n");
446 printf(" return 'isl.%s(\"%%s\")' %% str(self)\n", p_name.c_str());
448 for (in = methods.begin(); in != methods.end(); ++in)
449 print_method(*in, subclass, super);
451 printf("\n");
452 for (in = constructors.begin(); in != constructors.end(); ++in) {
453 string fullname = (*in)->getName();
454 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
455 printf("isl.%s.argtypes = [", fullname.c_str());
456 for (int i = 0; i < (*in)->getNumParams(); ++i) {
457 ParmVarDecl *param = (*in)->getParamDecl(i);
458 QualType type = param->getOriginalType();
459 if (i)
460 printf(", ");
461 if (is_isl_ctx(type))
462 printf("Context");
463 else if (is_isl_type(type))
464 printf("c_void_p");
465 else if (is_string(type))
466 printf("c_char_p");
467 else
468 printf("c_int");
470 printf("]\n");
472 for (in = methods.begin(); in != methods.end(); ++in) {
473 string fullname = (*in)->getName();
474 if (is_isl_type((*in)->getResultType()))
475 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
477 printf("isl.%s_free.argtypes = [c_void_p]\n", name.c_str());
478 printf("isl.%s_to_str.argtypes = [c_void_p]\n", name.c_str());
479 printf("isl.%s_to_str.restype = POINTER(c_char)\n", name.c_str());
482 /* Generate a python interface based on the extracted types and functions.
483 * We first collect all functions that belong to a certain type,
484 * separating constructors from regular methods.
486 * Then we print out each class in turn. If one of these is a subclass
487 * of some other class, it will make sure the superclass is printed out first.
489 void generate_python(set<RecordDecl *> &types, set<FunctionDecl *> functions)
491 map<string, isl_class> classes;
492 map<string, isl_class>::iterator ci;
493 set<string> done;
495 set<RecordDecl *>::iterator it;
496 for (it = types.begin(); it != types.end(); ++it) {
497 RecordDecl *decl = *it;
498 string name = decl->getName();
499 classes[name].name = name;
500 classes[name].type = decl;
503 set<FunctionDecl *>::iterator in;
504 for (in = functions.begin(); in != functions.end(); ++in) {
505 isl_class &c = method2class(classes, *in);
506 if (is_constructor(*in))
507 c.constructors.insert(*in);
508 else
509 c.methods.insert(*in);
512 for (ci = classes.begin(); ci != classes.end(); ++ci) {
513 if (done.find(ci->first) == done.end())
514 ci->second.print(classes, done);