isl_basic_map_contains: return false in case of dimension mismatch
[isl.git] / interface / python.cc
blobc32ca3fbaf368a3df3269ad72d94b7f1d18ad6d7
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.
56 * The order of the types is the opposite of the order in which they
57 * appear in the source. In particular, the first annotation
58 * is the one that is closest to the annotated type and the corresponding
59 * type is then also the first that will appear in the sequence of types.
61 static vector<string> find_superclasses(RecordDecl *decl)
63 vector<string> super;
65 if (!decl->hasAttrs())
66 return super;
68 string sub = "isl_subclass";
69 size_t len = sub.length();
70 AttrVec attrs = decl->getAttrs();
71 for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
72 const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
73 if (!ann)
74 continue;
75 string s = ann->getAnnotation().str();
76 if (s.substr(0, len) == sub) {
77 s = s.substr(len + 1, s.length() - len - 2);
78 super.push_back(s);
82 return super;
85 /* Is decl marked as being part of an overloaded method?
87 static bool is_overload(Decl *decl)
89 return has_annotation(decl, "isl_overload");
92 /* Is decl marked as a constructor?
94 static bool is_constructor(Decl *decl)
96 return has_annotation(decl, "isl_constructor");
99 /* Is decl marked as consuming a reference?
101 static bool takes(Decl *decl)
103 return has_annotation(decl, "isl_take");
106 /* Is decl marked as returning a reference that is required to be freed.
108 static bool gives(Decl *decl)
110 return has_annotation(decl, "isl_give");
113 /* isl_class collects all constructors and methods for an isl "class".
114 * "name" is the name of the class.
115 * "type" is the declaration that introduces the type.
116 * "methods" contains the set of methods, grouped by method name.
117 * "fn_to_str" is a reference to the *_to_str method of this class, if any.
118 * "fn_free" is a reference to the *_free method of this class, if any.
120 struct isl_class {
121 string name;
122 RecordDecl *type;
123 set<FunctionDecl *> constructors;
124 map<string, set<FunctionDecl *> > methods;
125 FunctionDecl *fn_to_str;
126 FunctionDecl *fn_free;
128 bool is_static(FunctionDecl *method);
130 void print(map<string, isl_class> &classes, set<string> &done);
131 void print_constructor(FunctionDecl *method);
132 void print_representation(const string &python_name);
133 void print_method_type(FunctionDecl *fd);
134 void print_method_types();
135 void print_method(FunctionDecl *method, vector<string> super);
136 void print_method_overload(FunctionDecl *method);
137 void print_method(const string &fullname,
138 const set<FunctionDecl *> &methods, vector<string> super);
141 /* Return the class that has a name that matches the initial part
142 * of the name of function "fd" or NULL if no such class could be found.
144 static isl_class *method2class(map<string, isl_class> &classes,
145 FunctionDecl *fd)
147 string best;
148 map<string, isl_class>::iterator ci;
149 string name = fd->getNameAsString();
151 for (ci = classes.begin(); ci != classes.end(); ++ci) {
152 if (name.substr(0, ci->first.length()) == ci->first)
153 best = ci->first;
156 if (classes.find(best) == classes.end()) {
157 cerr << "Unable to find class of " << name << endl;
158 return NULL;
161 return &classes[best];
164 /* Is "type" the type "isl_ctx *"?
166 static bool is_isl_ctx(QualType type)
168 if (!type->isPointerType())
169 return 0;
170 type = type->getPointeeType();
171 if (type.getAsString() != "isl_ctx")
172 return false;
174 return true;
177 /* Is the first argument of "fd" of type "isl_ctx *"?
179 static bool first_arg_is_isl_ctx(FunctionDecl *fd)
181 ParmVarDecl *param;
183 if (fd->getNumParams() < 1)
184 return false;
186 param = fd->getParamDecl(0);
187 return is_isl_ctx(param->getOriginalType());
190 /* Is "type" that of a pointer to an isl_* structure?
192 static bool is_isl_type(QualType type)
194 if (type->isPointerType()) {
195 string s;
197 type = type->getPointeeType();
198 if (type->isFunctionType())
199 return false;
200 s = type.getAsString();
201 return s.substr(0, 4) == "isl_";
204 return false;
207 /* Is "type" the type isl_bool?
209 static bool is_isl_bool(QualType type)
211 string s;
213 if (type->isPointerType())
214 return false;
216 s = type.getAsString();
217 return s == "isl_bool";
220 /* Is "type" that of a pointer to char.
222 static bool is_string_type(QualType type)
224 if (type->isPointerType()) {
225 string s;
227 type = type->getPointeeType();
228 if (type->isFunctionType())
229 return false;
230 s = type.getAsString();
231 return s == "const char" || "char";
234 return false;
237 /* Is "type" that of a pointer to a function?
239 static bool is_callback(QualType type)
241 if (!type->isPointerType())
242 return false;
243 type = type->getPointeeType();
244 return type->isFunctionType();
247 /* Is "type" that of "char *" of "const char *"?
249 static bool is_string(QualType type)
251 if (type->isPointerType()) {
252 string s = type->getPointeeType().getAsString();
253 return s == "const char" || s == "char";
256 return false;
259 /* Return the name of the type that "type" points to.
260 * The input "type" is assumed to be a pointer type.
262 static string extract_type(QualType type)
264 if (type->isPointerType())
265 return type->getPointeeType().getAsString();
266 die("Cannot extract type from non-pointer type");
269 /* Drop the "isl_" initial part of the type name "name".
271 static string type2python(string name)
273 return name.substr(4);
276 /* If "method" is overloaded, then drop the suffix of "name"
277 * corresponding to the type of the final argument and
278 * return the modified name (or the original name if
279 * no modifications were made).
281 static string drop_type_suffix(string name, FunctionDecl *method)
283 int num_params;
284 ParmVarDecl *param;
285 string type;
286 size_t name_len, type_len;
288 if (!is_overload(method))
289 return name;
291 num_params = method->getNumParams();
292 param = method->getParamDecl(num_params - 1);
293 type = extract_type(param->getOriginalType());
294 type = type.substr(4);
295 name_len = name.length();
296 type_len = type.length();
298 if (name_len > type_len && name.substr(name_len - type_len) == type)
299 name = name.substr(0, name_len - type_len - 1);
301 return name;
304 /* Should "method" be considered to be a static method?
305 * That is, is the first argument something other than
306 * an instance of the class?
308 bool isl_class::is_static(FunctionDecl *method)
310 ParmVarDecl *param = method->getParamDecl(0);
311 QualType type = param->getOriginalType();
313 if (!is_isl_type(type))
314 return true;
315 return extract_type(type) != name;
318 /* Print the header of the method "name" with "n_arg" arguments.
319 * If "is_static" is set, then mark the python method as static.
321 * If the method is called "from", then rename it to "convert_from"
322 * because "from" is a python keyword.
324 static void print_method_header(bool is_static, const string &name, int n_arg)
326 const char *s;
328 if (is_static)
329 printf(" @staticmethod\n");
331 s = name.c_str();
332 if (name == "from")
333 s = "convert_from";
335 printf(" def %s(", s);
336 for (int i = 0; i < n_arg; ++i) {
337 if (i)
338 printf(", ");
339 printf("arg%d", i);
341 printf("):\n");
344 /* Print a check that the argument in position "pos" is of type "type".
345 * If this fails and if "upcast" is set, then convert the first
346 * argument to "super" and call the method "name" on it, passing
347 * the remaining of the "n" arguments.
348 * If the check fails and "upcast" is not set, then simply raise
349 * an exception.
350 * If "upcast" is not set, then the "super", "name" and "n" arguments
351 * to this function are ignored.
353 static void print_type_check(const string &type, int pos, bool upcast,
354 const string &super, const string &name, int n)
356 printf(" try:\n");
357 printf(" if not arg%d.__class__ is %s:\n",
358 pos, type.c_str());
359 printf(" arg%d = %s(arg%d)\n",
360 pos, type.c_str(), pos);
361 printf(" except:\n");
362 if (upcast) {
363 printf(" return %s(arg0).%s(",
364 type2python(super).c_str(), name.c_str());
365 for (int i = 1; i < n; ++i) {
366 if (i != 1)
367 printf(", ");
368 printf("arg%d", i);
370 printf(")\n");
371 } else
372 printf(" raise\n");
375 /* Construct a wrapper for a callback argument (at position "arg").
376 * Assign the wrapper to "cb". We assume here that a function call
377 * has at most one callback argument.
379 * The wrapper converts the arguments of the callback to python types.
380 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
381 * and returns -1. Otherwise the wrapper returns 0.
383 static void print_callback(QualType type, int arg)
385 const FunctionProtoType *fn = type->getAs<FunctionProtoType>();
386 unsigned n_arg = fn->getNumArgs();
388 printf(" exc_info = [None]\n");
389 printf(" fn = CFUNCTYPE(c_int");
390 for (unsigned i = 0; i < n_arg - 1; ++i) {
391 if (!is_isl_type(fn->getArgType(i)))
392 die("Argument has non-isl type");
393 printf(", c_void_p");
395 printf(", c_void_p)\n");
396 printf(" def cb_func(");
397 for (unsigned i = 0; i < n_arg; ++i) {
398 if (i)
399 printf(", ");
400 printf("cb_arg%d", i);
402 printf("):\n");
403 for (unsigned i = 0; i < n_arg - 1; ++i) {
404 string arg_type;
405 arg_type = type2python(extract_type(fn->getArgType(i)));
406 printf(" cb_arg%d = %s(ctx=arg0.ctx, "
407 "ptr=cb_arg%d)\n", i, arg_type.c_str(), i);
409 printf(" try:\n");
410 printf(" arg%d(", arg);
411 for (unsigned i = 0; i < n_arg - 1; ++i) {
412 if (i)
413 printf(", ");
414 printf("cb_arg%d", i);
416 printf(")\n");
417 printf(" except:\n");
418 printf(" import sys\n");
419 printf(" exc_info[0] = sys.exc_info()\n");
420 printf(" return -1\n");
421 printf(" return 0\n");
422 printf(" cb = fn(cb_func)\n");
425 /* Print the argument at position "arg" in call to "fd".
426 * "skip" is the number of initial arguments of "fd" that are
427 * skipped in the Python method.
429 * If the argument is a callback, then print a reference to
430 * the callback wrapper "cb".
431 * Otherwise, if the argument is marked as consuming a reference,
432 * then pass a copy of the the pointer stored in the corresponding
433 * argument passed to the Python method.
434 * Otherwise, if the argument is a pointer, then pass this pointer itself.
435 * Otherwise, pass the argument directly.
437 static void print_arg_in_call(FunctionDecl *fd, int arg, int skip)
439 ParmVarDecl *param = fd->getParamDecl(arg);
440 QualType type = param->getOriginalType();
441 if (is_callback(type)) {
442 printf("cb");
443 } else if (takes(param)) {
444 string type_s = extract_type(type);
445 printf("isl.%s_copy(arg%d.ptr)", type_s.c_str(), arg - skip);
446 } else if (type->isPointerType()) {
447 printf("arg%d.ptr", arg - skip);
448 } else {
449 printf("arg%d", arg - skip);
453 /* Print the return statement of the python method corresponding
454 * to the C function "method".
456 * If the return type is a (const) char *, then convert the result
457 * to a Python string, raising an error on NULL and freeing
458 * the C string if needed.
460 * If the return type is isl_bool, then convert the result to
461 * a Python boolean, raising an error on isl_bool_error.
463 static void print_method_return(FunctionDecl *method)
465 QualType return_type = method->getReturnType();
467 if (is_isl_type(return_type)) {
468 string type;
470 type = type2python(extract_type(return_type));
471 printf(" return %s(ctx=ctx, ptr=res)\n", type.c_str());
472 } else if (is_string_type(return_type)) {
473 printf(" if res == 0:\n");
474 printf(" raise\n");
475 printf(" string = str(cast(res, c_char_p).value)\n");
477 if (gives(method))
478 printf(" libc.free(res)\n");
480 printf(" return string\n");
481 } else if (is_isl_bool(return_type)) {
482 printf(" if res < 0:\n");
483 printf(" raise\n");
484 printf(" return bool(res)\n");
485 } else {
486 printf(" return res\n");
490 /* Print a python method corresponding to the C function "method".
491 * "super" contains the superclasses of the class to which the method belongs,
492 * with the first element corresponding to the annotation that appears
493 * closest to the annotated type. This superclass is the least
494 * general extension of the annotated type in the linearization
495 * of the class hierarchy.
497 * If the first argument of "method" is something other than an instance
498 * of the class, then mark the python method as static.
499 * If, moreover, this first argument is an isl_ctx, then remove
500 * it from the arguments of the Python method.
502 * If the function has a callback argument, then it also has a "user"
503 * argument. Since Python has closures, there is no need for such
504 * a user argument in the Python interface, so we simply drop it.
505 * We also create a wrapper ("cb") for the callback.
507 * For each argument of the function that refers to an isl structure,
508 * including the object on which the method is called,
509 * we check if the corresponding actual argument is of the right type.
510 * If not, we try to convert it to the right type.
511 * If that doesn't work and if "super" contains at least one element, we try
512 * to convert self to the type of the first superclass in "super" and
513 * call the corresponding method.
515 * If the function consumes a reference, then we pass it a copy of
516 * the actual argument.
518 void isl_class::print_method(FunctionDecl *method, vector<string> super)
520 string fullname = method->getName();
521 string cname = fullname.substr(name.length() + 1);
522 int num_params = method->getNumParams();
523 int drop_user = 0;
524 int drop_ctx = first_arg_is_isl_ctx(method);
526 for (int i = 1; i < num_params; ++i) {
527 ParmVarDecl *param = method->getParamDecl(i);
528 QualType type = param->getOriginalType();
529 if (is_callback(type))
530 drop_user = 1;
533 print_method_header(is_static(method), cname,
534 num_params - drop_ctx - drop_user);
536 for (int i = drop_ctx; i < num_params; ++i) {
537 ParmVarDecl *param = method->getParamDecl(i);
538 string type;
539 if (!is_isl_type(param->getOriginalType()))
540 continue;
541 type = type2python(extract_type(param->getOriginalType()));
542 if (!drop_ctx && i > 0 && super.size() > 0)
543 print_type_check(type, i - drop_ctx, true, super[0],
544 cname, num_params - drop_user);
545 else
546 print_type_check(type, i - drop_ctx, false, "",
547 cname, -1);
549 for (int i = 1; i < num_params; ++i) {
550 ParmVarDecl *param = method->getParamDecl(i);
551 QualType type = param->getOriginalType();
552 if (!is_callback(type))
553 continue;
554 print_callback(type->getPointeeType(), i - drop_ctx);
556 if (drop_ctx)
557 printf(" ctx = Context.getDefaultInstance()\n");
558 else
559 printf(" ctx = arg0.ctx\n");
560 printf(" res = isl.%s(", fullname.c_str());
561 if (drop_ctx)
562 printf("ctx");
563 else
564 print_arg_in_call(method, 0, 0);
565 for (int i = 1; i < num_params - drop_user; ++i) {
566 printf(", ");
567 print_arg_in_call(method, i, drop_ctx);
569 if (drop_user)
570 printf(", None");
571 printf(")\n");
573 if (drop_user) {
574 printf(" if exc_info[0] != None:\n");
575 printf(" raise (exc_info[0][0], "
576 "exc_info[0][1], exc_info[0][2])\n");
579 print_method_return(method);
582 /* Print part of an overloaded python method corresponding to the C function
583 * "method".
585 * In particular, print code to test whether the arguments passed to
586 * the python method correspond to the arguments expected by "method"
587 * and to call "method" if they do.
589 void isl_class::print_method_overload(FunctionDecl *method)
591 string fullname = method->getName();
592 int num_params = method->getNumParams();
593 int first;
594 string type;
596 first = is_static(method) ? 0 : 1;
598 printf(" if ");
599 for (int i = first; i < num_params; ++i) {
600 if (i > first)
601 printf(" and ");
602 ParmVarDecl *param = method->getParamDecl(i);
603 if (is_isl_type(param->getOriginalType())) {
604 string type;
605 type = extract_type(param->getOriginalType());
606 type = type2python(type);
607 printf("arg%d.__class__ is %s", i, type.c_str());
608 } else
609 printf("type(arg%d) == str", i);
611 printf(":\n");
612 printf(" res = isl.%s(", fullname.c_str());
613 print_arg_in_call(method, 0, 0);
614 for (int i = 1; i < num_params; ++i) {
615 printf(", ");
616 print_arg_in_call(method, i, 0);
618 printf(")\n");
619 type = type2python(extract_type(method->getReturnType()));
620 printf(" return %s(ctx=arg0.ctx, ptr=res)\n", type.c_str());
623 /* Print a python method with a name derived from "fullname"
624 * corresponding to the C functions "methods".
625 * "super" contains the superclasses of the class to which the method belongs.
627 * If "methods" consists of a single element that is not marked overloaded,
628 * the use print_method to print the method.
629 * Otherwise, print an overloaded method with pieces corresponding
630 * to each function in "methods".
632 void isl_class::print_method(const string &fullname,
633 const set<FunctionDecl *> &methods, vector<string> super)
635 string cname;
636 set<FunctionDecl *>::const_iterator it;
637 int num_params;
638 FunctionDecl *any_method;
640 any_method = *methods.begin();
641 if (methods.size() == 1 && !is_overload(any_method)) {
642 print_method(any_method, super);
643 return;
646 cname = fullname.substr(name.length() + 1);
647 num_params = any_method->getNumParams();
649 print_method_header(is_static(any_method), cname, num_params);
651 for (it = methods.begin(); it != methods.end(); ++it)
652 print_method_overload(*it);
655 /* Print part of the constructor for this isl_class.
657 * In particular, check if the actual arguments correspond to the
658 * formal arguments of "cons" and if so call "cons" and put the
659 * result in self.ptr and a reference to the default context in self.ctx.
661 * If the function consumes a reference, then we pass it a copy of
662 * the actual argument.
664 void isl_class::print_constructor(FunctionDecl *cons)
666 string fullname = cons->getName();
667 string cname = fullname.substr(name.length() + 1);
668 int num_params = cons->getNumParams();
669 int drop_ctx = first_arg_is_isl_ctx(cons);
671 printf(" if len(args) == %d", num_params - drop_ctx);
672 for (int i = drop_ctx; i < num_params; ++i) {
673 ParmVarDecl *param = cons->getParamDecl(i);
674 QualType type = param->getOriginalType();
675 if (is_isl_type(type)) {
676 string s;
677 s = type2python(extract_type(type));
678 printf(" and args[%d].__class__ is %s",
679 i - drop_ctx, s.c_str());
680 } else if (type->isPointerType()) {
681 printf(" and type(args[%d]) == str", i - drop_ctx);
682 } else {
683 printf(" and type(args[%d]) == int", i - drop_ctx);
686 printf(":\n");
687 printf(" self.ctx = Context.getDefaultInstance()\n");
688 printf(" self.ptr = isl.%s(", fullname.c_str());
689 if (drop_ctx)
690 printf("self.ctx");
691 for (int i = drop_ctx; i < num_params; ++i) {
692 ParmVarDecl *param = cons->getParamDecl(i);
693 if (i)
694 printf(", ");
695 if (is_isl_type(param->getOriginalType())) {
696 if (takes(param)) {
697 string type;
698 type = extract_type(param->getOriginalType());
699 printf("isl.%s_copy(args[%d].ptr)",
700 type.c_str(), i - drop_ctx);
701 } else
702 printf("args[%d].ptr", i - drop_ctx);
703 } else
704 printf("args[%d]", i - drop_ctx);
706 printf(")\n");
707 printf(" return\n");
710 /* Print the header of the class "name" with superclasses "super".
711 * The order of the superclasses is the opposite of the order
712 * in which the corresponding annotations appear in the source code.
714 static void print_class_header(const string &name, const vector<string> &super)
716 printf("class %s", name.c_str());
717 if (super.size() > 0) {
718 printf("(");
719 for (unsigned i = 0; i < super.size(); ++i) {
720 if (i > 0)
721 printf(", ");
722 printf("%s", type2python(super[i]).c_str());
724 printf(")");
725 } else {
726 printf("(object)");
728 printf(":\n");
731 /* Tell ctypes about the return type of "fd".
732 * In particular, if "fd" returns a pointer to an isl object,
733 * then tell ctypes it returns a "c_void_p".
734 * Similarly, if "fd" returns an isl_bool,
735 * then tell ctypes it returns a "c_bool".
736 * If "fd" returns a char *, then simply tell ctypes.
738 static void print_restype(FunctionDecl *fd)
740 string fullname = fd->getName();
741 QualType type = fd->getReturnType();
742 if (is_isl_type(type))
743 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
744 else if (is_isl_bool(type))
745 printf("isl.%s.restype = c_bool\n", fullname.c_str());
746 else if (is_string_type(type))
747 printf("isl.%s.restype = POINTER(c_char)\n", fullname.c_str());
750 /* Tell ctypes about the types of the arguments of the function "fd".
752 static void print_argtypes(FunctionDecl *fd)
754 string fullname = fd->getName();
755 int n = fd->getNumParams();
756 int drop_user = 0;
758 printf("isl.%s.argtypes = [", fullname.c_str());
759 for (int i = 0; i < n - drop_user; ++i) {
760 ParmVarDecl *param = fd->getParamDecl(i);
761 QualType type = param->getOriginalType();
762 if (is_callback(type))
763 drop_user = 1;
764 if (i)
765 printf(", ");
766 if (is_isl_ctx(type))
767 printf("Context");
768 else if (is_isl_type(type) || is_callback(type))
769 printf("c_void_p");
770 else if (is_string(type))
771 printf("c_char_p");
772 else
773 printf("c_int");
775 if (drop_user)
776 printf(", c_void_p");
777 printf("]\n");
780 /* Print type definitions for the method 'fd'.
782 void isl_class::print_method_type(FunctionDecl *fd)
784 print_restype(fd);
785 print_argtypes(fd);
788 /* Print declarations for methods printing the class representation,
789 * provided there is a corresponding *_to_str function.
791 * In particular, provide an implementation of __str__ and __repr__ methods to
792 * override the default representation used by python. Python uses __str__ to
793 * pretty print the class (e.g., when calling print(obj)) and uses __repr__
794 * when printing a precise representation of an object (e.g., when dumping it
795 * in the REPL console).
797 * Check the type of the argument before calling the *_to_str function
798 * on it in case the method was called on an object from a subclass.
800 void isl_class::print_representation(const string &python_name)
802 if (!fn_to_str)
803 return;
805 printf(" def __str__(arg0):\n");
806 print_type_check(python_name, 0, false, "", "", -1);
807 printf(" ptr = isl.%s(arg0.ptr)\n",
808 string(fn_to_str->getName()).c_str());
809 printf(" res = str(cast(ptr, c_char_p).value)\n");
810 printf(" libc.free(ptr)\n");
811 printf(" return res\n");
812 printf(" def __repr__(self):\n");
813 printf(" s = str(self)\n");
814 printf(" if '\"' in s:\n");
815 printf(" return 'isl.%s(\"\"\"%%s\"\"\")' %% s\n",
816 python_name.c_str());
817 printf(" else:\n");
818 printf(" return 'isl.%s(\"%%s\")' %% s\n",
819 python_name.c_str());
822 /* Print code to set method type signatures.
824 * To be able to call C functions it is necessary to explicitly set their
825 * argument and result types. Do this for all exported constructors and
826 * methods, as well as for the *_to_str method, if it exists.
827 * Assuming each exported class has a *_free method,
828 * also unconditionally set the type of such methods.
830 void isl_class::print_method_types()
832 set<FunctionDecl *>::iterator in;
833 map<string, set<FunctionDecl *> >::iterator it;
835 for (in = constructors.begin(); in != constructors.end(); ++in)
836 print_method_type(*in);
838 for (it = methods.begin(); it != methods.end(); ++it)
839 for (in = it->second.begin(); in != it->second.end(); ++in)
840 print_method_type(*in);
842 print_method_type(fn_free);
843 if (fn_to_str)
844 print_method_type(fn_to_str);
847 /* Print out the definition of this isl_class.
849 * We first check if this isl_class is a subclass of one or more other classes.
850 * If it is, we make sure those superclasses are printed out first.
852 * Then we print a constructor with several cases, one for constructing
853 * a Python object from a return value and one for each function that
854 * was marked as a constructor.
856 * Next, we print out some common methods and the methods corresponding
857 * to functions that are not marked as constructors.
859 * Finally, we tell ctypes about the types of the arguments of the
860 * constructor functions and the return types of those function returning
861 * an isl object.
863 void isl_class::print(map<string, isl_class> &classes, set<string> &done)
865 string p_name = type2python(name);
866 set<FunctionDecl *>::iterator in;
867 map<string, set<FunctionDecl *> >::iterator it;
868 vector<string> super = find_superclasses(type);
870 for (unsigned i = 0; i < super.size(); ++i)
871 if (done.find(super[i]) == done.end())
872 classes[super[i]].print(classes, done);
873 done.insert(name);
875 printf("\n");
876 print_class_header(p_name, super);
877 printf(" def __init__(self, *args, **keywords):\n");
879 printf(" if \"ptr\" in keywords:\n");
880 printf(" self.ctx = keywords[\"ctx\"]\n");
881 printf(" self.ptr = keywords[\"ptr\"]\n");
882 printf(" return\n");
884 for (in = constructors.begin(); in != constructors.end(); ++in)
885 print_constructor(*in);
886 printf(" raise Error\n");
887 printf(" def __del__(self):\n");
888 printf(" if hasattr(self, 'ptr'):\n");
889 printf(" isl.%s_free(self.ptr)\n", name.c_str());
891 print_representation(p_name);
893 for (it = methods.begin(); it != methods.end(); ++it)
894 print_method(it->first, it->second, super);
896 printf("\n");
898 print_method_types();
901 /* Generate a python interface based on the extracted types and functions.
902 * We first collect all functions that belong to a certain type,
903 * separating constructors from regular methods and keeping track
904 * of the _to_str and _free functions, if any, separately. If there are any
905 * overloaded functions, then they are grouped based on their name
906 * after removing the argument type suffix.
908 * Then we print out each class in turn. If one of these is a subclass
909 * of some other class, it will make sure the superclass is printed out first.
911 void generate_python(set<RecordDecl *> &exported_types,
912 set<FunctionDecl *> exported_functions, set<FunctionDecl *> functions)
914 map<string, isl_class> classes;
915 map<string, isl_class>::iterator ci;
916 set<string> done;
917 map<string, FunctionDecl *> functions_by_name;
919 set<FunctionDecl *>::iterator in;
920 for (in = functions.begin(); in != functions.end(); ++in) {
921 FunctionDecl *decl = *in;
922 functions_by_name[decl->getName()] = decl;
925 set<RecordDecl *>::iterator it;
926 for (it = exported_types.begin(); it != exported_types.end(); ++it) {
927 RecordDecl *decl = *it;
928 map<string, FunctionDecl *>::iterator i;
930 string name = decl->getName();
931 classes[name].name = name;
932 classes[name].type = decl;
933 classes[name].fn_to_str = NULL;
934 classes[name].fn_free = NULL;
936 i = functions_by_name.find(name + "_to_str");
937 if (i != functions_by_name.end())
938 classes[name].fn_to_str = i->second;
940 i = functions_by_name.find (name + "_free");
941 if (i == functions_by_name.end())
942 die("No _free function found");
943 classes[name].fn_free = i->second;
946 for (in = exported_functions.begin(); in != exported_functions.end();
947 ++in) {
948 isl_class *c = method2class(classes, *in);
949 if (!c)
950 continue;
951 if (is_constructor(*in)) {
952 c->constructors.insert(*in);
953 } else {
954 FunctionDecl *method = *in;
955 string fullname = method->getName();
956 fullname = drop_type_suffix(fullname, method);
957 c->methods[fullname].insert(method);
961 for (ci = classes.begin(); ci != classes.end(); ++ci) {
962 if (done.find(ci->first) == done.end())
963 ci->second.print(classes, done);