mark isl_space_compatible as deprecated
[isl.git] / interface / python.cc
blob80977e7728c1f4c727ebe10c90052e0c8be8fb98
1 /*
2 * Copyright 2011,2015 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 <vector>
40 #include <clang/AST/Attr.h>
41 #include "extract_interface.h"
42 #include "python.h"
44 static void die(const char *msg) __attribute__((noreturn));
46 /* Print error message "msg" and abort.
48 static void die(const char *msg)
50 fprintf(stderr, "%s", msg);
51 abort();
54 /* Return a sequence of the types of which the given type declaration is
55 * marked as being a subtype.
57 static vector<string> find_superclasses(RecordDecl *decl)
59 vector<string> super;
61 if (!decl->hasAttrs())
62 return super;
64 string sub = "isl_subclass";
65 size_t len = sub.length();
66 AttrVec attrs = decl->getAttrs();
67 for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
68 const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
69 if (!ann)
70 continue;
71 string s = ann->getAnnotation().str();
72 if (s.substr(0, len) == sub) {
73 s = s.substr(len + 1, s.length() - len - 2);
74 super.push_back(s);
78 return super;
81 /* Is decl marked as being part of an overloaded method?
83 static bool is_overload(Decl *decl)
85 return has_annotation(decl, "isl_overload");
88 /* Is decl marked as a constructor?
90 static bool is_constructor(Decl *decl)
92 return has_annotation(decl, "isl_constructor");
95 /* Is decl marked as consuming a reference?
97 static bool takes(Decl *decl)
99 return has_annotation(decl, "isl_take");
102 /* Is decl marked as returning a reference that is required to be freed.
104 static bool gives(Decl *decl)
106 return has_annotation(decl, "isl_give");
109 /* isl_class collects all constructors and methods for an isl "class".
110 * "name" is the name of the class.
111 * "type" is the declaration that introduces the type.
112 * "methods" contains the set of methods, grouped by method name.
113 * "fn_to_str" is a reference to the *_to_str method of this class, if any.
114 * "fn_free" is a reference to the *_free method of this class, if any.
116 struct isl_class {
117 string name;
118 RecordDecl *type;
119 set<FunctionDecl *> constructors;
120 map<string, set<FunctionDecl *> > methods;
121 FunctionDecl *fn_to_str;
122 FunctionDecl *fn_free;
124 bool is_static(FunctionDecl *method);
126 void print(map<string, isl_class> &classes, set<string> &done);
127 void print_constructor(FunctionDecl *method);
128 void print_representation(const string &python_name);
129 void print_method_type(FunctionDecl *fd);
130 void print_method_types();
131 void print_method(FunctionDecl *method, vector<string> super);
132 void print_method_overload(FunctionDecl *method, vector<string> super);
133 void print_method(const string &fullname,
134 const set<FunctionDecl *> &methods, vector<string> super);
137 /* Return the class that has a name that matches the initial part
138 * of the name of function "fd" or NULL if no such class could be found.
140 static isl_class *method2class(map<string, isl_class> &classes,
141 FunctionDecl *fd)
143 string best;
144 map<string, isl_class>::iterator ci;
145 string name = fd->getNameAsString();
147 for (ci = classes.begin(); ci != classes.end(); ++ci) {
148 if (name.substr(0, ci->first.length()) == ci->first)
149 best = ci->first;
152 if (classes.find(best) == classes.end()) {
153 cerr << "Unable to find class of " << name << endl;
154 return NULL;
157 return &classes[best];
160 /* Is "type" the type "isl_ctx *"?
162 static bool is_isl_ctx(QualType type)
164 if (!type->isPointerType())
165 return 0;
166 type = type->getPointeeType();
167 if (type.getAsString() != "isl_ctx")
168 return false;
170 return true;
173 /* Is the first argument of "fd" of type "isl_ctx *"?
175 static bool first_arg_is_isl_ctx(FunctionDecl *fd)
177 ParmVarDecl *param;
179 if (fd->getNumParams() < 1)
180 return false;
182 param = fd->getParamDecl(0);
183 return is_isl_ctx(param->getOriginalType());
186 /* Is "type" that of a pointer to an isl_* structure?
188 static bool is_isl_type(QualType type)
190 if (type->isPointerType()) {
191 string s;
193 type = type->getPointeeType();
194 if (type->isFunctionType())
195 return false;
196 s = type.getAsString();
197 return s.substr(0, 4) == "isl_";
200 return false;
203 /* Is "type" the type isl_bool?
205 static bool is_isl_bool(QualType type)
207 string s;
209 if (type->isPointerType())
210 return false;
212 s = type.getAsString();
213 return s == "isl_bool";
216 /* Is "type" that of a pointer to char.
218 static bool is_string_type(QualType type)
220 if (type->isPointerType()) {
221 string s;
223 type = type->getPointeeType();
224 if (type->isFunctionType())
225 return false;
226 s = type.getAsString();
227 return s == "const char" || "char";
230 return false;
233 /* Is "type" that of a pointer to a function?
235 static bool is_callback(QualType type)
237 if (!type->isPointerType())
238 return false;
239 type = type->getPointeeType();
240 return type->isFunctionType();
243 /* Is "type" that of "char *" of "const char *"?
245 static bool is_string(QualType type)
247 if (type->isPointerType()) {
248 string s = type->getPointeeType().getAsString();
249 return s == "const char" || s == "char";
252 return false;
255 /* Return the name of the type that "type" points to.
256 * The input "type" is assumed to be a pointer type.
258 static string extract_type(QualType type)
260 if (type->isPointerType())
261 return type->getPointeeType().getAsString();
262 die("Cannot extract type from non-pointer type");
265 /* Drop the "isl_" initial part of the type name "name".
267 static string type2python(string name)
269 return name.substr(4);
272 /* If "method" is overloaded, then drop the suffix of "name"
273 * corresponding to the type of the final argument and
274 * return the modified name (or the original name if
275 * no modifications were made).
277 static string drop_type_suffix(string name, FunctionDecl *method)
279 int num_params;
280 ParmVarDecl *param;
281 string type;
282 size_t name_len, type_len;
284 if (!is_overload(method))
285 return name;
287 num_params = method->getNumParams();
288 param = method->getParamDecl(num_params - 1);
289 type = extract_type(param->getOriginalType());
290 type = type.substr(4);
291 name_len = name.length();
292 type_len = type.length();
294 if (name_len > type_len && name.substr(name_len - type_len) == type)
295 name = name.substr(0, name_len - type_len - 1);
297 return name;
300 /* Should "method" be considered to be a static method?
301 * That is, is the first argument something other than
302 * an instance of the class?
304 bool isl_class::is_static(FunctionDecl *method)
306 ParmVarDecl *param = method->getParamDecl(0);
307 QualType type = param->getOriginalType();
309 if (!is_isl_type(type))
310 return true;
311 return extract_type(type) != name;
314 /* Print the header of the method "name" with "n_arg" arguments.
315 * If "is_static" is set, then mark the python method as static.
317 * If the method is called "from", then rename it to "convert_from"
318 * because "from" is a python keyword.
320 static void print_method_header(bool is_static, const string &name, int n_arg)
322 const char *s;
324 if (is_static)
325 printf(" @staticmethod\n");
327 s = name.c_str();
328 if (name == "from")
329 s = "convert_from";
331 printf(" def %s(", s);
332 for (int i = 0; i < n_arg; ++i) {
333 if (i)
334 printf(", ");
335 printf("arg%d", i);
337 printf("):\n");
340 /* Print a check that the argument in position "pos" is of type "type".
341 * If this fails and if "upcast" is set, then convert the first
342 * argument to "super" and call the method "name" on it, passing
343 * the remaining of the "n" arguments.
344 * If the check fails and "upcast" is not set, then simply raise
345 * an exception.
346 * If "upcast" is not set, then the "super", "name" and "n" arguments
347 * to this function are ignored.
349 static void print_type_check(const string &type, int pos, bool upcast,
350 const string &super, const string &name, int n)
352 printf(" try:\n");
353 printf(" if not arg%d.__class__ is %s:\n",
354 pos, type.c_str());
355 printf(" arg%d = %s(arg%d)\n",
356 pos, type.c_str(), pos);
357 printf(" except:\n");
358 if (upcast) {
359 printf(" return %s(arg0).%s(",
360 type2python(super).c_str(), name.c_str());
361 for (int i = 1; i < n; ++i) {
362 if (i != 1)
363 printf(", ");
364 printf("arg%d", i);
366 printf(")\n");
367 } else
368 printf(" raise\n");
371 /* Construct a wrapper for a callback argument (at position "arg").
372 * Assign the wrapper to "cb". We assume here that a function call
373 * has at most one callback argument.
375 * The wrapper converts the arguments of the callback to python types.
376 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
377 * and returns -1. Otherwise the wrapper returns 0.
379 static void print_callback(QualType type, int arg)
381 const FunctionProtoType *fn = type->getAs<FunctionProtoType>();
382 unsigned n_arg = fn->getNumArgs();
384 printf(" exc_info = [None]\n");
385 printf(" fn = CFUNCTYPE(c_int");
386 for (unsigned i = 0; i < n_arg - 1; ++i) {
387 if (!is_isl_type(fn->getArgType(i)))
388 die("Argument has non-isl type");
389 printf(", c_void_p");
391 printf(", c_void_p)\n");
392 printf(" def cb_func(");
393 for (unsigned i = 0; i < n_arg; ++i) {
394 if (i)
395 printf(", ");
396 printf("cb_arg%d", i);
398 printf("):\n");
399 for (unsigned i = 0; i < n_arg - 1; ++i) {
400 string arg_type;
401 arg_type = type2python(extract_type(fn->getArgType(i)));
402 printf(" cb_arg%d = %s(ctx=arg0.ctx, "
403 "ptr=cb_arg%d)\n", i, arg_type.c_str(), i);
405 printf(" try:\n");
406 printf(" arg%d(", arg);
407 for (unsigned i = 0; i < n_arg - 1; ++i) {
408 if (i)
409 printf(", ");
410 printf("cb_arg%d", i);
412 printf(")\n");
413 printf(" except:\n");
414 printf(" import sys\n");
415 printf(" exc_info[0] = sys.exc_info()\n");
416 printf(" return -1\n");
417 printf(" return 0\n");
418 printf(" cb = fn(cb_func)\n");
421 /* Print the argument at position "arg" in call to "fd".
422 * "skip" is the number of initial arguments of "fd" that are
423 * skipped in the Python method.
425 * If the argument is a callback, then print a reference to
426 * the callback wrapper "cb".
427 * Otherwise, if the argument is marked as consuming a reference,
428 * then pass a copy of the the pointer stored in the corresponding
429 * argument passed to the Python method.
430 * Otherwise, if the argument is a pointer, then pass this pointer itself.
431 * Otherwise, pass the argument directly.
433 static void print_arg_in_call(FunctionDecl *fd, int arg, int skip)
435 ParmVarDecl *param = fd->getParamDecl(arg);
436 QualType type = param->getOriginalType();
437 if (is_callback(type)) {
438 printf("cb");
439 } else if (takes(param)) {
440 string type_s = extract_type(type);
441 printf("isl.%s_copy(arg%d.ptr)", type_s.c_str(), arg - skip);
442 } else if (type->isPointerType()) {
443 printf("arg%d.ptr", arg - skip);
444 } else {
445 printf("arg%d", arg - skip);
449 /* Print the return statement of the python method corresponding
450 * to the C function "method".
452 * If the return type is a (const) char *, then convert the result
453 * to a Python string, raising an error on NULL and freeing
454 * the C string if needed.
456 * If the return type is isl_bool, then convert the result to
457 * a Python boolean, raising an error on isl_bool_error.
459 static void print_method_return(FunctionDecl *method)
461 QualType return_type = method->getReturnType();
463 if (is_isl_type(return_type)) {
464 string type;
466 type = type2python(extract_type(return_type));
467 printf(" return %s(ctx=ctx, ptr=res)\n", type.c_str());
468 } else if (is_string_type(return_type)) {
469 printf(" if res == 0:\n");
470 printf(" raise\n");
471 printf(" string = str(cast(res, c_char_p).value)\n");
473 if (gives(method))
474 printf(" libc.free(res)\n");
476 printf(" return string\n");
477 } else if (is_isl_bool(return_type)) {
478 printf(" if res < 0:\n");
479 printf(" raise\n");
480 printf(" return bool(res)\n");
481 } else {
482 printf(" return res\n");
486 /* Print a python method corresponding to the C function "method".
487 * "super" contains the superclasses of the class to which the method belongs.
489 * If the first argument of "method" is something other than an instance
490 * of the class, then mark the python method as static.
491 * If, moreover, this first argument is an isl_ctx, then remove
492 * it from the arguments of the Python method.
494 * If the function has a callback argument, then it also has a "user"
495 * argument. Since Python has closures, there is no need for such
496 * a user argument in the Python interface, so we simply drop it.
497 * We also create a wrapper ("cb") for the callback.
499 * For each argument of the function that refers to an isl structure,
500 * including the object on which the method is called,
501 * we check if the corresponding actual argument is of the right type.
502 * If not, we try to convert it to the right type.
503 * If that doesn't work and if "super" contains at least one element, we try
504 * to convert self to the type of the first superclass in "super" and
505 * call the corresponding method.
507 * If the function consumes a reference, then we pass it a copy of
508 * the actual argument.
510 void isl_class::print_method(FunctionDecl *method, vector<string> super)
512 string fullname = method->getName();
513 string cname = fullname.substr(name.length() + 1);
514 int num_params = method->getNumParams();
515 int drop_user = 0;
516 int drop_ctx = first_arg_is_isl_ctx(method);
518 for (int i = 1; i < num_params; ++i) {
519 ParmVarDecl *param = method->getParamDecl(i);
520 QualType type = param->getOriginalType();
521 if (is_callback(type))
522 drop_user = 1;
525 print_method_header(is_static(method), cname,
526 num_params - drop_ctx - drop_user);
528 for (int i = drop_ctx; i < num_params; ++i) {
529 ParmVarDecl *param = method->getParamDecl(i);
530 string type;
531 if (!is_isl_type(param->getOriginalType()))
532 continue;
533 type = type2python(extract_type(param->getOriginalType()));
534 if (!drop_ctx && i > 0 && super.size() > 0)
535 print_type_check(type, i - drop_ctx, true, super[0],
536 cname, num_params - drop_user);
537 else
538 print_type_check(type, i - drop_ctx, false, "",
539 cname, -1);
541 for (int i = 1; i < num_params; ++i) {
542 ParmVarDecl *param = method->getParamDecl(i);
543 QualType type = param->getOriginalType();
544 if (!is_callback(type))
545 continue;
546 print_callback(type->getPointeeType(), i - drop_ctx);
548 if (drop_ctx)
549 printf(" ctx = Context.getDefaultInstance()\n");
550 else
551 printf(" ctx = arg0.ctx\n");
552 printf(" res = isl.%s(", fullname.c_str());
553 if (drop_ctx)
554 printf("ctx");
555 else
556 print_arg_in_call(method, 0, 0);
557 for (int i = 1; i < num_params - drop_user; ++i) {
558 printf(", ");
559 print_arg_in_call(method, i, drop_ctx);
561 if (drop_user)
562 printf(", None");
563 printf(")\n");
565 if (drop_user) {
566 printf(" if exc_info[0] != None:\n");
567 printf(" raise exc_info[0][0], "
568 "exc_info[0][1], exc_info[0][2]\n");
571 print_method_return(method);
574 /* Print part of an overloaded python method corresponding to the C function
575 * "method".
576 * "super" contains the superclasses of the class to which the method belongs.
578 * In particular, print code to test whether the arguments passed to
579 * the python method correspond to the arguments expected by "method"
580 * and to call "method" if they do.
582 void isl_class::print_method_overload(FunctionDecl *method,
583 vector<string> super)
585 string fullname = method->getName();
586 int num_params = method->getNumParams();
587 int first;
588 string type;
590 first = is_static(method) ? 0 : 1;
592 printf(" if ");
593 for (int i = first; i < num_params; ++i) {
594 if (i > first)
595 printf(" and ");
596 ParmVarDecl *param = method->getParamDecl(i);
597 if (is_isl_type(param->getOriginalType())) {
598 string type;
599 type = extract_type(param->getOriginalType());
600 type = type2python(type);
601 printf("arg%d.__class__ is %s", i, type.c_str());
602 } else
603 printf("type(arg%d) == str", i);
605 printf(":\n");
606 printf(" res = isl.%s(", fullname.c_str());
607 print_arg_in_call(method, 0, 0);
608 for (int i = 1; i < num_params; ++i) {
609 printf(", ");
610 print_arg_in_call(method, i, 0);
612 printf(")\n");
613 type = type2python(extract_type(method->getReturnType()));
614 printf(" return %s(ctx=arg0.ctx, ptr=res)\n", type.c_str());
617 /* Print a python method with a name derived from "fullname"
618 * corresponding to the C functions "methods".
619 * "super" contains the superclasses of the class to which the method belongs.
621 * If "methods" consists of a single element that is not marked overloaded,
622 * the use print_method to print the method.
623 * Otherwise, print an overloaded method with pieces corresponding
624 * to each function in "methods".
626 void isl_class::print_method(const string &fullname,
627 const set<FunctionDecl *> &methods, vector<string> super)
629 string cname;
630 set<FunctionDecl *>::const_iterator it;
631 int num_params;
632 FunctionDecl *any_method;
634 any_method = *methods.begin();
635 if (methods.size() == 1 && !is_overload(any_method)) {
636 print_method(any_method, super);
637 return;
640 cname = fullname.substr(name.length() + 1);
641 num_params = any_method->getNumParams();
643 print_method_header(is_static(any_method), cname, num_params);
645 for (it = methods.begin(); it != methods.end(); ++it)
646 print_method_overload(*it, super);
649 /* Print part of the constructor for this isl_class.
651 * In particular, check if the actual arguments correspond to the
652 * formal arguments of "cons" and if so call "cons" and put the
653 * result in self.ptr and a reference to the default context in self.ctx.
655 * If the function consumes a reference, then we pass it a copy of
656 * the actual argument.
658 void isl_class::print_constructor(FunctionDecl *cons)
660 string fullname = cons->getName();
661 string cname = fullname.substr(name.length() + 1);
662 int num_params = cons->getNumParams();
663 int drop_ctx = first_arg_is_isl_ctx(cons);
665 printf(" if len(args) == %d", num_params - drop_ctx);
666 for (int i = drop_ctx; i < num_params; ++i) {
667 ParmVarDecl *param = cons->getParamDecl(i);
668 QualType type = param->getOriginalType();
669 if (is_isl_type(type)) {
670 string s;
671 s = type2python(extract_type(type));
672 printf(" and args[%d].__class__ is %s",
673 i - drop_ctx, s.c_str());
674 } else if (type->isPointerType()) {
675 printf(" and type(args[%d]) == str", i - drop_ctx);
676 } else {
677 printf(" and type(args[%d]) == int", i - drop_ctx);
680 printf(":\n");
681 printf(" self.ctx = Context.getDefaultInstance()\n");
682 printf(" self.ptr = isl.%s(", fullname.c_str());
683 if (drop_ctx)
684 printf("self.ctx");
685 for (int i = drop_ctx; i < num_params; ++i) {
686 ParmVarDecl *param = cons->getParamDecl(i);
687 if (i)
688 printf(", ");
689 if (is_isl_type(param->getOriginalType())) {
690 if (takes(param)) {
691 string type;
692 type = extract_type(param->getOriginalType());
693 printf("isl.%s_copy(args[%d].ptr)",
694 type.c_str(), i - drop_ctx);
695 } else
696 printf("args[%d].ptr", i - drop_ctx);
697 } else
698 printf("args[%d]", i - drop_ctx);
700 printf(")\n");
701 printf(" return\n");
704 /* Print the header of the class "name" with superclasses "super".
706 static void print_class_header(const string &name, const vector<string> &super)
708 printf("class %s", name.c_str());
709 if (super.size() > 0) {
710 printf("(");
711 for (unsigned i = 0; i < super.size(); ++i) {
712 if (i > 0)
713 printf(", ");
714 printf("%s", type2python(super[i]).c_str());
716 printf(")");
718 printf(":\n");
721 /* Tell ctypes about the return type of "fd".
722 * In particular, if "fd" returns a pointer to an isl object,
723 * then tell ctypes it returns a "c_void_p".
724 * Similarly, if "fd" returns an isl_bool,
725 * then tell ctypes it returns a "c_bool".
726 * If "fd" returns a char *, then simply tell ctypes.
728 static void print_restype(FunctionDecl *fd)
730 string fullname = fd->getName();
731 QualType type = fd->getReturnType();
732 if (is_isl_type(type))
733 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
734 else if (is_isl_bool(type))
735 printf("isl.%s.restype = c_bool\n", fullname.c_str());
736 else if (is_string_type(type))
737 printf("isl.%s.restype = POINTER(c_char)\n", fullname.c_str());
740 /* Tell ctypes about the types of the arguments of the function "fd".
742 static void print_argtypes(FunctionDecl *fd)
744 string fullname = fd->getName();
745 int n = fd->getNumParams();
746 int drop_user = 0;
748 printf("isl.%s.argtypes = [", fullname.c_str());
749 for (int i = 0; i < n - drop_user; ++i) {
750 ParmVarDecl *param = fd->getParamDecl(i);
751 QualType type = param->getOriginalType();
752 if (is_callback(type))
753 drop_user = 1;
754 if (i)
755 printf(", ");
756 if (is_isl_ctx(type))
757 printf("Context");
758 else if (is_isl_type(type) || is_callback(type))
759 printf("c_void_p");
760 else if (is_string(type))
761 printf("c_char_p");
762 else
763 printf("c_int");
765 if (drop_user)
766 printf(", c_void_p");
767 printf("]\n");
770 /* Print type definitions for the method 'fd'.
772 void isl_class::print_method_type(FunctionDecl *fd)
774 print_restype(fd);
775 print_argtypes(fd);
778 /* Print declarations for methods printing the class representation,
779 * provided there is a corresponding *_to_str function.
781 * In particular, provide an implementation of __str__ and __repr__ methods to
782 * override the default representation used by python. Python uses __str__ to
783 * pretty print the class (e.g., when calling print(obj)) and uses __repr__
784 * when printing a precise representation of an object (e.g., when dumping it
785 * in the REPL console).
787 * Check the type of the argument before calling the *_to_str function
788 * on it in case the method was called on an object from a subclass.
790 void isl_class::print_representation(const string &python_name)
792 if (!fn_to_str)
793 return;
795 printf(" def __str__(arg0):\n");
796 print_type_check(python_name, 0, false, "", "", -1);
797 printf(" ptr = isl.%s(arg0.ptr)\n",
798 string(fn_to_str->getName()).c_str());
799 printf(" res = str(cast(ptr, c_char_p).value)\n");
800 printf(" libc.free(ptr)\n");
801 printf(" return res\n");
802 printf(" def __repr__(self):\n");
803 printf(" s = str(self)\n");
804 printf(" if '\"' in s:\n");
805 printf(" return 'isl.%s(\"\"\"%%s\"\"\")' %% s\n",
806 python_name.c_str());
807 printf(" else:\n");
808 printf(" return 'isl.%s(\"%%s\")' %% s\n",
809 python_name.c_str());
812 /* Print code to set method type signatures.
814 * To be able to call C functions it is necessary to explicitly set their
815 * argument and result types. Do this for all exported constructors and
816 * methods, as well as for the *_to_str method, if it exists.
817 * Assuming each exported class has a *_free method,
818 * also unconditionally set the type of such methods.
820 void isl_class::print_method_types()
822 set<FunctionDecl *>::iterator in;
823 map<string, set<FunctionDecl *> >::iterator it;
825 for (in = constructors.begin(); in != constructors.end(); ++in)
826 print_method_type(*in);
828 for (it = methods.begin(); it != methods.end(); ++it)
829 for (in = it->second.begin(); in != it->second.end(); ++in)
830 print_method_type(*in);
832 print_method_type(fn_free);
833 if (fn_to_str)
834 print_method_type(fn_to_str);
837 /* Print out the definition of this isl_class.
839 * We first check if this isl_class is a subclass of one or more other classes.
840 * If it is, we make sure those superclasses are printed out first.
842 * Then we print a constructor with several cases, one for constructing
843 * a Python object from a return value and one for each function that
844 * was marked as a constructor.
846 * Next, we print out some common methods and the methods corresponding
847 * to functions that are not marked as constructors.
849 * Finally, we tell ctypes about the types of the arguments of the
850 * constructor functions and the return types of those function returning
851 * an isl object.
853 void isl_class::print(map<string, isl_class> &classes, set<string> &done)
855 string p_name = type2python(name);
856 set<FunctionDecl *>::iterator in;
857 map<string, set<FunctionDecl *> >::iterator it;
858 vector<string> super = find_superclasses(type);
860 for (unsigned i = 0; i < super.size(); ++i)
861 if (done.find(super[i]) == done.end())
862 classes[super[i]].print(classes, done);
863 done.insert(name);
865 printf("\n");
866 print_class_header(p_name, super);
867 printf(" def __init__(self, *args, **keywords):\n");
869 printf(" if \"ptr\" in keywords:\n");
870 printf(" self.ctx = keywords[\"ctx\"]\n");
871 printf(" self.ptr = keywords[\"ptr\"]\n");
872 printf(" return\n");
874 for (in = constructors.begin(); in != constructors.end(); ++in)
875 print_constructor(*in);
876 printf(" raise Error\n");
877 printf(" def __del__(self):\n");
878 printf(" if hasattr(self, 'ptr'):\n");
879 printf(" isl.%s_free(self.ptr)\n", name.c_str());
881 print_representation(p_name);
883 for (it = methods.begin(); it != methods.end(); ++it)
884 print_method(it->first, it->second, super);
886 printf("\n");
888 print_method_types();
891 /* Generate a python interface based on the extracted types and functions.
892 * We first collect all functions that belong to a certain type,
893 * separating constructors from regular methods and keeping track
894 * of the _to_str and _free functions, if any, separately. If there are any
895 * overloaded functions, then they are grouped based on their name
896 * after removing the argument type suffix.
898 * Then we print out each class in turn. If one of these is a subclass
899 * of some other class, it will make sure the superclass is printed out first.
901 void generate_python(set<RecordDecl *> &exported_types,
902 set<FunctionDecl *> exported_functions, set<FunctionDecl *> functions)
904 map<string, isl_class> classes;
905 map<string, isl_class>::iterator ci;
906 set<string> done;
907 map<string, FunctionDecl *> functions_by_name;
909 set<FunctionDecl *>::iterator in;
910 for (in = functions.begin(); in != functions.end(); ++in) {
911 FunctionDecl *decl = *in;
912 functions_by_name[decl->getName()] = decl;
915 set<RecordDecl *>::iterator it;
916 for (it = exported_types.begin(); it != exported_types.end(); ++it) {
917 RecordDecl *decl = *it;
918 map<string, FunctionDecl *>::iterator i;
920 string name = decl->getName();
921 classes[name].name = name;
922 classes[name].type = decl;
923 classes[name].fn_to_str = NULL;
924 classes[name].fn_free = NULL;
926 i = functions_by_name.find(name + "_to_str");
927 if (i != functions_by_name.end())
928 classes[name].fn_to_str = i->second;
930 i = functions_by_name.find (name + "_free");
931 if (i == functions_by_name.end())
932 die("No _free function found");
933 classes[name].fn_free = i->second;
936 for (in = exported_functions.begin(); in != exported_functions.end();
937 ++in) {
938 isl_class *c = method2class(classes, *in);
939 if (!c)
940 continue;
941 if (is_constructor(*in)) {
942 c->constructors.insert(*in);
943 } else {
944 FunctionDecl *method = *in;
945 string fullname = method->getName();
946 fullname = drop_type_suffix(fullname, method);
947 c->methods[fullname].insert(method);
951 for (ci = classes.begin(); ci != classes.end(); ++ci) {
952 if (done.find(ci->first) == done.end())
953 ci->second.print(classes, done);