python interface: only export __str__ and __repr__ if *_to_str is declared
[isl.git] / interface / python.cc
blob223bf78c3e89d9eabc3cf6dacc3ede0d52b0f310
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.
115 struct isl_class {
116 string name;
117 RecordDecl *type;
118 set<FunctionDecl *> constructors;
119 map<string, set<FunctionDecl *> > methods;
120 FunctionDecl *fn_to_str;
122 bool is_static(FunctionDecl *method);
124 void print(map<string, isl_class> &classes, set<string> &done);
125 void print_constructor(FunctionDecl *method);
126 void print_representation(const string &python_name);
127 void print_method_type(FunctionDecl *fd);
128 void print_method_types();
129 void print_method(FunctionDecl *method, vector<string> super);
130 void print_method_overload(FunctionDecl *method, vector<string> super);
131 void print_method(const string &fullname,
132 const set<FunctionDecl *> &methods, vector<string> super);
135 /* Return the class that has a name that matches the initial part
136 * of the name of function "fd" or NULL if no such class could be found.
138 static isl_class *method2class(map<string, isl_class> &classes,
139 FunctionDecl *fd)
141 string best;
142 map<string, isl_class>::iterator ci;
143 string name = fd->getNameAsString();
145 for (ci = classes.begin(); ci != classes.end(); ++ci) {
146 if (name.substr(0, ci->first.length()) == ci->first)
147 best = ci->first;
150 if (classes.find(best) == classes.end()) {
151 cerr << "Unable to find class of " << name << endl;
152 return NULL;
155 return &classes[best];
158 /* Is "type" the type "isl_ctx *"?
160 static bool is_isl_ctx(QualType type)
162 if (!type->isPointerType())
163 return 0;
164 type = type->getPointeeType();
165 if (type.getAsString() != "isl_ctx")
166 return false;
168 return true;
171 /* Is the first argument of "fd" of type "isl_ctx *"?
173 static bool first_arg_is_isl_ctx(FunctionDecl *fd)
175 ParmVarDecl *param;
177 if (fd->getNumParams() < 1)
178 return false;
180 param = fd->getParamDecl(0);
181 return is_isl_ctx(param->getOriginalType());
184 /* Is "type" that of a pointer to an isl_* structure?
186 static bool is_isl_type(QualType type)
188 if (type->isPointerType()) {
189 string s;
191 type = type->getPointeeType();
192 if (type->isFunctionType())
193 return false;
194 s = type.getAsString();
195 return s.substr(0, 4) == "isl_";
198 return false;
201 /* Is "type" the type isl_bool?
203 static bool is_isl_bool(QualType type)
205 string s;
207 if (type->isPointerType())
208 return false;
210 s = type.getAsString();
211 return s == "isl_bool";
214 /* Is "type" that of a pointer to char.
216 static bool is_string_type(QualType type)
218 if (type->isPointerType()) {
219 string s;
221 type = type->getPointeeType();
222 if (type->isFunctionType())
223 return false;
224 s = type.getAsString();
225 return s == "const char" || "char";
228 return false;
231 /* Is "type" that of a pointer to a function?
233 static bool is_callback(QualType type)
235 if (!type->isPointerType())
236 return false;
237 type = type->getPointeeType();
238 return type->isFunctionType();
241 /* Is "type" that of "char *" of "const char *"?
243 static bool is_string(QualType type)
245 if (type->isPointerType()) {
246 string s = type->getPointeeType().getAsString();
247 return s == "const char" || s == "char";
250 return false;
253 /* Return the name of the type that "type" points to.
254 * The input "type" is assumed to be a pointer type.
256 static string extract_type(QualType type)
258 if (type->isPointerType())
259 return type->getPointeeType().getAsString();
260 die("Cannot extract type from non-pointer type");
263 /* Drop the "isl_" initial part of the type name "name".
265 static string type2python(string name)
267 return name.substr(4);
270 /* If "method" is overloaded, then drop the suffix of "name"
271 * corresponding to the type of the final argument and
272 * return the modified name (or the original name if
273 * no modifications were made).
275 static string drop_type_suffix(string name, FunctionDecl *method)
277 int num_params;
278 ParmVarDecl *param;
279 string type;
280 size_t name_len, type_len;
282 if (!is_overload(method))
283 return name;
285 num_params = method->getNumParams();
286 param = method->getParamDecl(num_params - 1);
287 type = extract_type(param->getOriginalType());
288 type = type.substr(4);
289 name_len = name.length();
290 type_len = type.length();
292 if (name_len > type_len && name.substr(name_len - type_len) == type)
293 name = name.substr(0, name_len - type_len - 1);
295 return name;
298 /* Should "method" be considered to be a static method?
299 * That is, is the first argument something other than
300 * an instance of the class?
302 bool isl_class::is_static(FunctionDecl *method)
304 ParmVarDecl *param = method->getParamDecl(0);
305 QualType type = param->getOriginalType();
307 if (!is_isl_type(type))
308 return true;
309 return extract_type(type) != name;
312 /* Print the header of the method "name" with "n_arg" arguments.
313 * If "is_static" is set, then mark the python method as static.
315 * If the method is called "from", then rename it to "convert_from"
316 * because "from" is a python keyword.
318 static void print_method_header(bool is_static, const string &name, int n_arg)
320 const char *s;
322 if (is_static)
323 printf(" @staticmethod\n");
325 s = name.c_str();
326 if (name == "from")
327 s = "convert_from";
329 printf(" def %s(", s);
330 for (int i = 0; i < n_arg; ++i) {
331 if (i)
332 printf(", ");
333 printf("arg%d", i);
335 printf("):\n");
338 /* Print a check that the argument in position "pos" is of type "type".
339 * If this fails and if "upcast" is set, then convert the first
340 * argument to "super" and call the method "name" on it, passing
341 * the remaining of the "n" arguments.
342 * If the check fails and "upcast" is not set, then simply raise
343 * an exception.
344 * If "upcast" is not set, then the "super", "name" and "n" arguments
345 * to this function are ignored.
347 static void print_type_check(const string &type, int pos, bool upcast,
348 const string &super, const string &name, int n)
350 printf(" try:\n");
351 printf(" if not arg%d.__class__ is %s:\n",
352 pos, type.c_str());
353 printf(" arg%d = %s(arg%d)\n",
354 pos, type.c_str(), pos);
355 printf(" except:\n");
356 if (upcast) {
357 printf(" return %s(arg0).%s(",
358 type2python(super).c_str(), name.c_str());
359 for (int i = 1; i < n; ++i) {
360 if (i != 1)
361 printf(", ");
362 printf("arg%d", i);
364 printf(")\n");
365 } else
366 printf(" raise\n");
369 /* Construct a wrapper for a callback argument (at position "arg").
370 * Assign the wrapper to "cb". We assume here that a function call
371 * has at most one callback argument.
373 * The wrapper converts the arguments of the callback to python types.
374 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
375 * and returns -1. Otherwise the wrapper returns 0.
377 static void print_callback(QualType type, int arg)
379 const FunctionProtoType *fn = type->getAs<FunctionProtoType>();
380 unsigned n_arg = fn->getNumArgs();
382 printf(" exc_info = [None]\n");
383 printf(" fn = CFUNCTYPE(c_int");
384 for (unsigned i = 0; i < n_arg - 1; ++i) {
385 if (!is_isl_type(fn->getArgType(i)))
386 die("Argument has non-isl type");
387 printf(", c_void_p");
389 printf(", c_void_p)\n");
390 printf(" def cb_func(");
391 for (unsigned i = 0; i < n_arg; ++i) {
392 if (i)
393 printf(", ");
394 printf("cb_arg%d", i);
396 printf("):\n");
397 for (unsigned i = 0; i < n_arg - 1; ++i) {
398 string arg_type;
399 arg_type = type2python(extract_type(fn->getArgType(i)));
400 printf(" cb_arg%d = %s(ctx=arg0.ctx, "
401 "ptr=cb_arg%d)\n", i, arg_type.c_str(), i);
403 printf(" try:\n");
404 printf(" arg%d(", arg);
405 for (unsigned i = 0; i < n_arg - 1; ++i) {
406 if (i)
407 printf(", ");
408 printf("cb_arg%d", i);
410 printf(")\n");
411 printf(" except:\n");
412 printf(" import sys\n");
413 printf(" exc_info[0] = sys.exc_info()\n");
414 printf(" return -1\n");
415 printf(" return 0\n");
416 printf(" cb = fn(cb_func)\n");
419 /* Print the argument at position "arg" in call to "fd".
420 * "skip" is the number of initial arguments of "fd" that are
421 * skipped in the Python method.
423 * If the argument is a callback, then print a reference to
424 * the callback wrapper "cb".
425 * Otherwise, if the argument is marked as consuming a reference,
426 * then pass a copy of the the pointer stored in the corresponding
427 * argument passed to the Python method.
428 * Otherwise, if the argument is a pointer, then pass this pointer itself.
429 * Otherwise, pass the argument directly.
431 static void print_arg_in_call(FunctionDecl *fd, int arg, int skip)
433 ParmVarDecl *param = fd->getParamDecl(arg);
434 QualType type = param->getOriginalType();
435 if (is_callback(type)) {
436 printf("cb");
437 } else if (takes(param)) {
438 string type_s = extract_type(type);
439 printf("isl.%s_copy(arg%d.ptr)", type_s.c_str(), arg - skip);
440 } else if (type->isPointerType()) {
441 printf("arg%d.ptr", arg - skip);
442 } else {
443 printf("arg%d", arg - skip);
447 /* Print the return statement of the python method corresponding
448 * to the C function "method".
450 * If the return type is a (const) char *, then convert the result
451 * to a Python string, raising an error on NULL and freeing
452 * the C string if needed.
454 * If the return type is isl_bool, then convert the result to
455 * a Python boolean, raising an error on isl_bool_error.
457 static void print_method_return(FunctionDecl *method)
459 QualType return_type = method->getReturnType();
461 if (is_isl_type(return_type)) {
462 string type;
464 type = type2python(extract_type(return_type));
465 printf(" return %s(ctx=ctx, ptr=res)\n", type.c_str());
466 } else if (is_string_type(return_type)) {
467 printf(" if res == 0:\n");
468 printf(" raise\n");
469 printf(" string = str(cast(res, c_char_p).value)\n");
471 if (gives(method))
472 printf(" libc.free(res)\n");
474 printf(" return string\n");
475 } else if (is_isl_bool(return_type)) {
476 printf(" if res < 0:\n");
477 printf(" raise\n");
478 printf(" return bool(res)\n");
479 } else {
480 printf(" return res\n");
484 /* Print a python method corresponding to the C function "method".
485 * "super" contains the superclasses of the class to which the method belongs.
487 * If the first argument of "method" is something other than an instance
488 * of the class, then mark the python method as static.
489 * If, moreover, this first argument is an isl_ctx, then remove
490 * it from the arguments of the Python method.
492 * If the function has a callback argument, then it also has a "user"
493 * argument. Since Python has closures, there is no need for such
494 * a user argument in the Python interface, so we simply drop it.
495 * We also create a wrapper ("cb") for the callback.
497 * For each argument of the function that refers to an isl structure,
498 * including the object on which the method is called,
499 * we check if the corresponding actual argument is of the right type.
500 * If not, we try to convert it to the right type.
501 * If that doesn't work and if "super" contains at least one element, we try
502 * to convert self to the type of the first superclass in "super" and
503 * call the corresponding method.
505 * If the function consumes a reference, then we pass it a copy of
506 * the actual argument.
508 void isl_class::print_method(FunctionDecl *method, vector<string> super)
510 string fullname = method->getName();
511 string cname = fullname.substr(name.length() + 1);
512 int num_params = method->getNumParams();
513 int drop_user = 0;
514 int drop_ctx = first_arg_is_isl_ctx(method);
516 for (int i = 1; i < num_params; ++i) {
517 ParmVarDecl *param = method->getParamDecl(i);
518 QualType type = param->getOriginalType();
519 if (is_callback(type))
520 drop_user = 1;
523 print_method_header(is_static(method), cname,
524 num_params - drop_ctx - drop_user);
526 for (int i = drop_ctx; i < num_params; ++i) {
527 ParmVarDecl *param = method->getParamDecl(i);
528 string type;
529 if (!is_isl_type(param->getOriginalType()))
530 continue;
531 type = type2python(extract_type(param->getOriginalType()));
532 if (!drop_ctx && i > 0 && super.size() > 0)
533 print_type_check(type, i - drop_ctx, true, super[0],
534 cname, num_params - drop_user);
535 else
536 print_type_check(type, i - drop_ctx, false, "",
537 cname, -1);
539 for (int i = 1; i < num_params; ++i) {
540 ParmVarDecl *param = method->getParamDecl(i);
541 QualType type = param->getOriginalType();
542 if (!is_callback(type))
543 continue;
544 print_callback(type->getPointeeType(), i - drop_ctx);
546 if (drop_ctx)
547 printf(" ctx = Context.getDefaultInstance()\n");
548 else
549 printf(" ctx = arg0.ctx\n");
550 printf(" res = isl.%s(", fullname.c_str());
551 if (drop_ctx)
552 printf("ctx");
553 else
554 print_arg_in_call(method, 0, 0);
555 for (int i = 1; i < num_params - drop_user; ++i) {
556 printf(", ");
557 print_arg_in_call(method, i, drop_ctx);
559 if (drop_user)
560 printf(", None");
561 printf(")\n");
563 if (drop_user) {
564 printf(" if exc_info[0] != None:\n");
565 printf(" raise exc_info[0][0], "
566 "exc_info[0][1], exc_info[0][2]\n");
569 print_method_return(method);
572 /* Print part of an overloaded python method corresponding to the C function
573 * "method".
574 * "super" contains the superclasses of the class to which the method belongs.
576 * In particular, print code to test whether the arguments passed to
577 * the python method correspond to the arguments expected by "method"
578 * and to call "method" if they do.
580 void isl_class::print_method_overload(FunctionDecl *method,
581 vector<string> super)
583 string fullname = method->getName();
584 int num_params = method->getNumParams();
585 int first;
586 string type;
588 first = is_static(method) ? 0 : 1;
590 printf(" if ");
591 for (int i = first; i < num_params; ++i) {
592 if (i > first)
593 printf(" and ");
594 ParmVarDecl *param = method->getParamDecl(i);
595 if (is_isl_type(param->getOriginalType())) {
596 string type;
597 type = extract_type(param->getOriginalType());
598 type = type2python(type);
599 printf("arg%d.__class__ is %s", i, type.c_str());
600 } else
601 printf("type(arg%d) == str", i);
603 printf(":\n");
604 printf(" res = isl.%s(", fullname.c_str());
605 print_arg_in_call(method, 0, 0);
606 for (int i = 1; i < num_params; ++i) {
607 printf(", ");
608 print_arg_in_call(method, i, 0);
610 printf(")\n");
611 type = type2python(extract_type(method->getReturnType()));
612 printf(" return %s(ctx=arg0.ctx, ptr=res)\n", type.c_str());
615 /* Print a python method with a name derived from "fullname"
616 * corresponding to the C functions "methods".
617 * "super" contains the superclasses of the class to which the method belongs.
619 * If "methods" consists of a single element that is not marked overloaded,
620 * the use print_method to print the method.
621 * Otherwise, print an overloaded method with pieces corresponding
622 * to each function in "methods".
624 void isl_class::print_method(const string &fullname,
625 const set<FunctionDecl *> &methods, vector<string> super)
627 string cname;
628 set<FunctionDecl *>::const_iterator it;
629 int num_params;
630 FunctionDecl *any_method;
632 any_method = *methods.begin();
633 if (methods.size() == 1 && !is_overload(any_method)) {
634 print_method(any_method, super);
635 return;
638 cname = fullname.substr(name.length() + 1);
639 num_params = any_method->getNumParams();
641 print_method_header(is_static(any_method), cname, num_params);
643 for (it = methods.begin(); it != methods.end(); ++it)
644 print_method_overload(*it, super);
647 /* Print part of the constructor for this isl_class.
649 * In particular, check if the actual arguments correspond to the
650 * formal arguments of "cons" and if so call "cons" and put the
651 * result in self.ptr and a reference to the default context in self.ctx.
653 * If the function consumes a reference, then we pass it a copy of
654 * the actual argument.
656 void isl_class::print_constructor(FunctionDecl *cons)
658 string fullname = cons->getName();
659 string cname = fullname.substr(name.length() + 1);
660 int num_params = cons->getNumParams();
661 int drop_ctx = first_arg_is_isl_ctx(cons);
663 printf(" if len(args) == %d", num_params - drop_ctx);
664 for (int i = drop_ctx; i < num_params; ++i) {
665 ParmVarDecl *param = cons->getParamDecl(i);
666 QualType type = param->getOriginalType();
667 if (is_isl_type(type)) {
668 string s;
669 s = type2python(extract_type(type));
670 printf(" and args[%d].__class__ is %s",
671 i - drop_ctx, s.c_str());
672 } else if (type->isPointerType()) {
673 printf(" and type(args[%d]) == str", i - drop_ctx);
674 } else {
675 printf(" and type(args[%d]) == int", i - drop_ctx);
678 printf(":\n");
679 printf(" self.ctx = Context.getDefaultInstance()\n");
680 printf(" self.ptr = isl.%s(", fullname.c_str());
681 if (drop_ctx)
682 printf("self.ctx");
683 for (int i = drop_ctx; i < num_params; ++i) {
684 ParmVarDecl *param = cons->getParamDecl(i);
685 if (i)
686 printf(", ");
687 if (is_isl_type(param->getOriginalType())) {
688 if (takes(param)) {
689 string type;
690 type = extract_type(param->getOriginalType());
691 printf("isl.%s_copy(args[%d].ptr)",
692 type.c_str(), i - drop_ctx);
693 } else
694 printf("args[%d].ptr", i - drop_ctx);
695 } else
696 printf("args[%d]", i - drop_ctx);
698 printf(")\n");
699 printf(" return\n");
702 /* Print the header of the class "name" with superclasses "super".
704 static void print_class_header(const string &name, const vector<string> &super)
706 printf("class %s", name.c_str());
707 if (super.size() > 0) {
708 printf("(");
709 for (unsigned i = 0; i < super.size(); ++i) {
710 if (i > 0)
711 printf(", ");
712 printf("%s", type2python(super[i]).c_str());
714 printf(")");
716 printf(":\n");
719 /* Tell ctypes about the return type of "fd".
720 * In particular, if "fd" returns a pointer to an isl object,
721 * then tell ctypes it returns a "c_void_p".
722 * Similarly, if "fd" returns an isl_bool,
723 * then tell ctypes it returns a "c_bool".
724 * If "fd" returns a char *, then simply tell ctypes.
726 static void print_restype(FunctionDecl *fd)
728 string fullname = fd->getName();
729 QualType type = fd->getReturnType();
730 if (is_isl_type(type))
731 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
732 else if (is_isl_bool(type))
733 printf("isl.%s.restype = c_bool\n", fullname.c_str());
734 else if (is_string_type(type))
735 printf("isl.%s.restype = POINTER(c_char)\n", fullname.c_str());
738 /* Tell ctypes about the types of the arguments of the function "fd".
740 static void print_argtypes(FunctionDecl *fd)
742 string fullname = fd->getName();
743 int n = fd->getNumParams();
744 int drop_user = 0;
746 printf("isl.%s.argtypes = [", fullname.c_str());
747 for (int i = 0; i < n - drop_user; ++i) {
748 ParmVarDecl *param = fd->getParamDecl(i);
749 QualType type = param->getOriginalType();
750 if (is_callback(type))
751 drop_user = 1;
752 if (i)
753 printf(", ");
754 if (is_isl_ctx(type))
755 printf("Context");
756 else if (is_isl_type(type) || is_callback(type))
757 printf("c_void_p");
758 else if (is_string(type))
759 printf("c_char_p");
760 else
761 printf("c_int");
763 if (drop_user)
764 printf(", c_void_p");
765 printf("]\n");
768 /* Print type definitions for the method 'fd'.
770 void isl_class::print_method_type(FunctionDecl *fd)
772 print_restype(fd);
773 print_argtypes(fd);
776 /* Print declarations for methods printing the class representation,
777 * provided there is a corresponding *_to_str function.
779 * In particular, provide an implementation of __str__ and __repr__ methods to
780 * override the default representation used by python. Python uses __str__ to
781 * pretty print the class (e.g., when calling print(obj)) and uses __repr__
782 * when printing a precise representation of an object (e.g., when dumping it
783 * in the REPL console).
785 * Check the type of the argument before calling the *_to_str function
786 * on it in case the method was called on an object from a subclass.
788 void isl_class::print_representation(const string &python_name)
790 if (!fn_to_str)
791 return;
793 printf(" def __str__(arg0):\n");
794 print_type_check(python_name, 0, false, "", "", -1);
795 printf(" ptr = isl.%s(arg0.ptr)\n",
796 string(fn_to_str->getName()).c_str());
797 printf(" res = str(cast(ptr, c_char_p).value)\n");
798 printf(" libc.free(ptr)\n");
799 printf(" return res\n");
800 printf(" def __repr__(self):\n");
801 printf(" s = str(self)\n");
802 printf(" if '\"' in s:\n");
803 printf(" return 'isl.%s(\"\"\"%%s\"\"\")' %% s\n",
804 python_name.c_str());
805 printf(" else:\n");
806 printf(" return 'isl.%s(\"%%s\")' %% s\n",
807 python_name.c_str());
810 /* Print code to set method type signatures.
812 * To be able to call C functions it is necessary to explicitly set their
813 * argument and result types. Do this for all exported constructors and
814 * methods, as well as for the *_to_str method, if it exists.
815 * Assuming each exported class has a *_free method,
816 * also unconditionally set the type of such methods.
818 void isl_class::print_method_types()
820 set<FunctionDecl *>::iterator in;
821 map<string, set<FunctionDecl *> >::iterator it;
823 for (in = constructors.begin(); in != constructors.end(); ++in)
824 print_method_type(*in);
826 for (it = methods.begin(); it != methods.end(); ++it)
827 for (in = it->second.begin(); in != it->second.end(); ++in)
828 print_method_type(*in);
830 printf("isl.%s_free.argtypes = [c_void_p]\n", name.c_str());
831 if (fn_to_str)
832 print_method_type(fn_to_str);
835 /* Print out the definition of this isl_class.
837 * We first check if this isl_class is a subclass of one or more other classes.
838 * If it is, we make sure those superclasses are printed out first.
840 * Then we print a constructor with several cases, one for constructing
841 * a Python object from a return value and one for each function that
842 * was marked as a constructor.
844 * Next, we print out some common methods and the methods corresponding
845 * to functions that are not marked as constructors.
847 * Finally, we tell ctypes about the types of the arguments of the
848 * constructor functions and the return types of those function returning
849 * an isl object.
851 void isl_class::print(map<string, isl_class> &classes, set<string> &done)
853 string p_name = type2python(name);
854 set<FunctionDecl *>::iterator in;
855 map<string, set<FunctionDecl *> >::iterator it;
856 vector<string> super = find_superclasses(type);
858 for (unsigned i = 0; i < super.size(); ++i)
859 if (done.find(super[i]) == done.end())
860 classes[super[i]].print(classes, done);
861 done.insert(name);
863 printf("\n");
864 print_class_header(p_name, super);
865 printf(" def __init__(self, *args, **keywords):\n");
867 printf(" if \"ptr\" in keywords:\n");
868 printf(" self.ctx = keywords[\"ctx\"]\n");
869 printf(" self.ptr = keywords[\"ptr\"]\n");
870 printf(" return\n");
872 for (in = constructors.begin(); in != constructors.end(); ++in)
873 print_constructor(*in);
874 printf(" raise Error\n");
875 printf(" def __del__(self):\n");
876 printf(" if hasattr(self, 'ptr'):\n");
877 printf(" isl.%s_free(self.ptr)\n", name.c_str());
879 print_representation(p_name);
881 for (it = methods.begin(); it != methods.end(); ++it)
882 print_method(it->first, it->second, super);
884 printf("\n");
886 print_method_types();
889 /* Generate a python interface based on the extracted types and functions.
890 * We first collect all functions that belong to a certain type,
891 * separating constructors from regular methods and keeping track
892 * of the _to_str function, if any, separately. If there are any
893 * overloaded functions, then they are grouped based on their name
894 * after removing the argument type suffix.
896 * Then we print out each class in turn. If one of these is a subclass
897 * of some other class, it will make sure the superclass is printed out first.
899 void generate_python(set<RecordDecl *> &exported_types,
900 set<FunctionDecl *> exported_functions, set<FunctionDecl *> functions)
902 map<string, isl_class> classes;
903 map<string, isl_class>::iterator ci;
904 set<string> done;
905 map<string, FunctionDecl *> functions_by_name;
907 set<FunctionDecl *>::iterator in;
908 for (in = functions.begin(); in != functions.end(); ++in) {
909 FunctionDecl *decl = *in;
910 functions_by_name[decl->getName()] = decl;
913 set<RecordDecl *>::iterator it;
914 for (it = exported_types.begin(); it != exported_types.end(); ++it) {
915 RecordDecl *decl = *it;
916 map<string, FunctionDecl *>::iterator i;
918 string name = decl->getName();
919 classes[name].name = name;
920 classes[name].type = decl;
921 classes[name].fn_to_str = NULL;
923 i = functions_by_name.find(name + "_to_str");
924 if (i != functions_by_name.end())
925 classes[name].fn_to_str = i->second;
928 for (in = exported_functions.begin(); in != exported_functions.end();
929 ++in) {
930 isl_class *c = method2class(classes, *in);
931 if (!c)
932 continue;
933 if (is_constructor(*in)) {
934 c->constructors.insert(*in);
935 } else {
936 FunctionDecl *method = *in;
937 string fullname = method->getName();
938 fullname = drop_type_suffix(fullname, method);
939 c->methods[fullname].insert(method);
943 for (ci = classes.begin(); ci != classes.end(); ++ci) {
944 if (done.find(ci->first) == done.end())
945 ci->second.print(classes, done);