interface/python.cc: document order of superclasses
[isl.git] / interface / python.cc
blobd8a992d41f5b44e6367186964a689dbc041f4312
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.
495 * If the first argument of "method" is something other than an instance
496 * of the class, then mark the python method as static.
497 * If, moreover, this first argument is an isl_ctx, then remove
498 * it from the arguments of the Python method.
500 * If the function has a callback argument, then it also has a "user"
501 * argument. Since Python has closures, there is no need for such
502 * a user argument in the Python interface, so we simply drop it.
503 * We also create a wrapper ("cb") for the callback.
505 * For each argument of the function that refers to an isl structure,
506 * including the object on which the method is called,
507 * we check if the corresponding actual argument is of the right type.
508 * If not, we try to convert it to the right type.
509 * If that doesn't work and if "super" contains at least one element, we try
510 * to convert self to the type of the first superclass in "super" and
511 * call the corresponding method.
513 * If the function consumes a reference, then we pass it a copy of
514 * the actual argument.
516 void isl_class::print_method(FunctionDecl *method, vector<string> super)
518 string fullname = method->getName();
519 string cname = fullname.substr(name.length() + 1);
520 int num_params = method->getNumParams();
521 int drop_user = 0;
522 int drop_ctx = first_arg_is_isl_ctx(method);
524 for (int i = 1; i < num_params; ++i) {
525 ParmVarDecl *param = method->getParamDecl(i);
526 QualType type = param->getOriginalType();
527 if (is_callback(type))
528 drop_user = 1;
531 print_method_header(is_static(method), cname,
532 num_params - drop_ctx - drop_user);
534 for (int i = drop_ctx; i < num_params; ++i) {
535 ParmVarDecl *param = method->getParamDecl(i);
536 string type;
537 if (!is_isl_type(param->getOriginalType()))
538 continue;
539 type = type2python(extract_type(param->getOriginalType()));
540 if (!drop_ctx && i > 0 && super.size() > 0)
541 print_type_check(type, i - drop_ctx, true, super[0],
542 cname, num_params - drop_user);
543 else
544 print_type_check(type, i - drop_ctx, false, "",
545 cname, -1);
547 for (int i = 1; i < num_params; ++i) {
548 ParmVarDecl *param = method->getParamDecl(i);
549 QualType type = param->getOriginalType();
550 if (!is_callback(type))
551 continue;
552 print_callback(type->getPointeeType(), i - drop_ctx);
554 if (drop_ctx)
555 printf(" ctx = Context.getDefaultInstance()\n");
556 else
557 printf(" ctx = arg0.ctx\n");
558 printf(" res = isl.%s(", fullname.c_str());
559 if (drop_ctx)
560 printf("ctx");
561 else
562 print_arg_in_call(method, 0, 0);
563 for (int i = 1; i < num_params - drop_user; ++i) {
564 printf(", ");
565 print_arg_in_call(method, i, drop_ctx);
567 if (drop_user)
568 printf(", None");
569 printf(")\n");
571 if (drop_user) {
572 printf(" if exc_info[0] != None:\n");
573 printf(" raise exc_info[0][0], "
574 "exc_info[0][1], exc_info[0][2]\n");
577 print_method_return(method);
580 /* Print part of an overloaded python method corresponding to the C function
581 * "method".
583 * In particular, print code to test whether the arguments passed to
584 * the python method correspond to the arguments expected by "method"
585 * and to call "method" if they do.
587 void isl_class::print_method_overload(FunctionDecl *method)
589 string fullname = method->getName();
590 int num_params = method->getNumParams();
591 int first;
592 string type;
594 first = is_static(method) ? 0 : 1;
596 printf(" if ");
597 for (int i = first; i < num_params; ++i) {
598 if (i > first)
599 printf(" and ");
600 ParmVarDecl *param = method->getParamDecl(i);
601 if (is_isl_type(param->getOriginalType())) {
602 string type;
603 type = extract_type(param->getOriginalType());
604 type = type2python(type);
605 printf("arg%d.__class__ is %s", i, type.c_str());
606 } else
607 printf("type(arg%d) == str", i);
609 printf(":\n");
610 printf(" res = isl.%s(", fullname.c_str());
611 print_arg_in_call(method, 0, 0);
612 for (int i = 1; i < num_params; ++i) {
613 printf(", ");
614 print_arg_in_call(method, i, 0);
616 printf(")\n");
617 type = type2python(extract_type(method->getReturnType()));
618 printf(" return %s(ctx=arg0.ctx, ptr=res)\n", type.c_str());
621 /* Print a python method with a name derived from "fullname"
622 * corresponding to the C functions "methods".
623 * "super" contains the superclasses of the class to which the method belongs.
625 * If "methods" consists of a single element that is not marked overloaded,
626 * the use print_method to print the method.
627 * Otherwise, print an overloaded method with pieces corresponding
628 * to each function in "methods".
630 void isl_class::print_method(const string &fullname,
631 const set<FunctionDecl *> &methods, vector<string> super)
633 string cname;
634 set<FunctionDecl *>::const_iterator it;
635 int num_params;
636 FunctionDecl *any_method;
638 any_method = *methods.begin();
639 if (methods.size() == 1 && !is_overload(any_method)) {
640 print_method(any_method, super);
641 return;
644 cname = fullname.substr(name.length() + 1);
645 num_params = any_method->getNumParams();
647 print_method_header(is_static(any_method), cname, num_params);
649 for (it = methods.begin(); it != methods.end(); ++it)
650 print_method_overload(*it);
653 /* Print part of the constructor for this isl_class.
655 * In particular, check if the actual arguments correspond to the
656 * formal arguments of "cons" and if so call "cons" and put the
657 * result in self.ptr and a reference to the default context in self.ctx.
659 * If the function consumes a reference, then we pass it a copy of
660 * the actual argument.
662 void isl_class::print_constructor(FunctionDecl *cons)
664 string fullname = cons->getName();
665 string cname = fullname.substr(name.length() + 1);
666 int num_params = cons->getNumParams();
667 int drop_ctx = first_arg_is_isl_ctx(cons);
669 printf(" if len(args) == %d", num_params - drop_ctx);
670 for (int i = drop_ctx; i < num_params; ++i) {
671 ParmVarDecl *param = cons->getParamDecl(i);
672 QualType type = param->getOriginalType();
673 if (is_isl_type(type)) {
674 string s;
675 s = type2python(extract_type(type));
676 printf(" and args[%d].__class__ is %s",
677 i - drop_ctx, s.c_str());
678 } else if (type->isPointerType()) {
679 printf(" and type(args[%d]) == str", i - drop_ctx);
680 } else {
681 printf(" and type(args[%d]) == int", i - drop_ctx);
684 printf(":\n");
685 printf(" self.ctx = Context.getDefaultInstance()\n");
686 printf(" self.ptr = isl.%s(", fullname.c_str());
687 if (drop_ctx)
688 printf("self.ctx");
689 for (int i = drop_ctx; i < num_params; ++i) {
690 ParmVarDecl *param = cons->getParamDecl(i);
691 if (i)
692 printf(", ");
693 if (is_isl_type(param->getOriginalType())) {
694 if (takes(param)) {
695 string type;
696 type = extract_type(param->getOriginalType());
697 printf("isl.%s_copy(args[%d].ptr)",
698 type.c_str(), i - drop_ctx);
699 } else
700 printf("args[%d].ptr", i - drop_ctx);
701 } else
702 printf("args[%d]", i - drop_ctx);
704 printf(")\n");
705 printf(" return\n");
708 /* Print the header of the class "name" with superclasses "super".
709 * The order of the superclasses is the opposite of the order
710 * in which the corresponding annotations appear in the source code.
712 static void print_class_header(const string &name, const vector<string> &super)
714 printf("class %s", name.c_str());
715 if (super.size() > 0) {
716 printf("(");
717 for (unsigned i = 0; i < super.size(); ++i) {
718 if (i > 0)
719 printf(", ");
720 printf("%s", type2python(super[i]).c_str());
722 printf(")");
724 printf(":\n");
727 /* Tell ctypes about the return type of "fd".
728 * In particular, if "fd" returns a pointer to an isl object,
729 * then tell ctypes it returns a "c_void_p".
730 * Similarly, if "fd" returns an isl_bool,
731 * then tell ctypes it returns a "c_bool".
732 * If "fd" returns a char *, then simply tell ctypes.
734 static void print_restype(FunctionDecl *fd)
736 string fullname = fd->getName();
737 QualType type = fd->getReturnType();
738 if (is_isl_type(type))
739 printf("isl.%s.restype = c_void_p\n", fullname.c_str());
740 else if (is_isl_bool(type))
741 printf("isl.%s.restype = c_bool\n", fullname.c_str());
742 else if (is_string_type(type))
743 printf("isl.%s.restype = POINTER(c_char)\n", fullname.c_str());
746 /* Tell ctypes about the types of the arguments of the function "fd".
748 static void print_argtypes(FunctionDecl *fd)
750 string fullname = fd->getName();
751 int n = fd->getNumParams();
752 int drop_user = 0;
754 printf("isl.%s.argtypes = [", fullname.c_str());
755 for (int i = 0; i < n - drop_user; ++i) {
756 ParmVarDecl *param = fd->getParamDecl(i);
757 QualType type = param->getOriginalType();
758 if (is_callback(type))
759 drop_user = 1;
760 if (i)
761 printf(", ");
762 if (is_isl_ctx(type))
763 printf("Context");
764 else if (is_isl_type(type) || is_callback(type))
765 printf("c_void_p");
766 else if (is_string(type))
767 printf("c_char_p");
768 else
769 printf("c_int");
771 if (drop_user)
772 printf(", c_void_p");
773 printf("]\n");
776 /* Print type definitions for the method 'fd'.
778 void isl_class::print_method_type(FunctionDecl *fd)
780 print_restype(fd);
781 print_argtypes(fd);
784 /* Print declarations for methods printing the class representation,
785 * provided there is a corresponding *_to_str function.
787 * In particular, provide an implementation of __str__ and __repr__ methods to
788 * override the default representation used by python. Python uses __str__ to
789 * pretty print the class (e.g., when calling print(obj)) and uses __repr__
790 * when printing a precise representation of an object (e.g., when dumping it
791 * in the REPL console).
793 * Check the type of the argument before calling the *_to_str function
794 * on it in case the method was called on an object from a subclass.
796 void isl_class::print_representation(const string &python_name)
798 if (!fn_to_str)
799 return;
801 printf(" def __str__(arg0):\n");
802 print_type_check(python_name, 0, false, "", "", -1);
803 printf(" ptr = isl.%s(arg0.ptr)\n",
804 string(fn_to_str->getName()).c_str());
805 printf(" res = str(cast(ptr, c_char_p).value)\n");
806 printf(" libc.free(ptr)\n");
807 printf(" return res\n");
808 printf(" def __repr__(self):\n");
809 printf(" s = str(self)\n");
810 printf(" if '\"' in s:\n");
811 printf(" return 'isl.%s(\"\"\"%%s\"\"\")' %% s\n",
812 python_name.c_str());
813 printf(" else:\n");
814 printf(" return 'isl.%s(\"%%s\")' %% s\n",
815 python_name.c_str());
818 /* Print code to set method type signatures.
820 * To be able to call C functions it is necessary to explicitly set their
821 * argument and result types. Do this for all exported constructors and
822 * methods, as well as for the *_to_str method, if it exists.
823 * Assuming each exported class has a *_free method,
824 * also unconditionally set the type of such methods.
826 void isl_class::print_method_types()
828 set<FunctionDecl *>::iterator in;
829 map<string, set<FunctionDecl *> >::iterator it;
831 for (in = constructors.begin(); in != constructors.end(); ++in)
832 print_method_type(*in);
834 for (it = methods.begin(); it != methods.end(); ++it)
835 for (in = it->second.begin(); in != it->second.end(); ++in)
836 print_method_type(*in);
838 print_method_type(fn_free);
839 if (fn_to_str)
840 print_method_type(fn_to_str);
843 /* Print out the definition of this isl_class.
845 * We first check if this isl_class is a subclass of one or more other classes.
846 * If it is, we make sure those superclasses are printed out first.
848 * Then we print a constructor with several cases, one for constructing
849 * a Python object from a return value and one for each function that
850 * was marked as a constructor.
852 * Next, we print out some common methods and the methods corresponding
853 * to functions that are not marked as constructors.
855 * Finally, we tell ctypes about the types of the arguments of the
856 * constructor functions and the return types of those function returning
857 * an isl object.
859 void isl_class::print(map<string, isl_class> &classes, set<string> &done)
861 string p_name = type2python(name);
862 set<FunctionDecl *>::iterator in;
863 map<string, set<FunctionDecl *> >::iterator it;
864 vector<string> super = find_superclasses(type);
866 for (unsigned i = 0; i < super.size(); ++i)
867 if (done.find(super[i]) == done.end())
868 classes[super[i]].print(classes, done);
869 done.insert(name);
871 printf("\n");
872 print_class_header(p_name, super);
873 printf(" def __init__(self, *args, **keywords):\n");
875 printf(" if \"ptr\" in keywords:\n");
876 printf(" self.ctx = keywords[\"ctx\"]\n");
877 printf(" self.ptr = keywords[\"ptr\"]\n");
878 printf(" return\n");
880 for (in = constructors.begin(); in != constructors.end(); ++in)
881 print_constructor(*in);
882 printf(" raise Error\n");
883 printf(" def __del__(self):\n");
884 printf(" if hasattr(self, 'ptr'):\n");
885 printf(" isl.%s_free(self.ptr)\n", name.c_str());
887 print_representation(p_name);
889 for (it = methods.begin(); it != methods.end(); ++it)
890 print_method(it->first, it->second, super);
892 printf("\n");
894 print_method_types();
897 /* Generate a python interface based on the extracted types and functions.
898 * We first collect all functions that belong to a certain type,
899 * separating constructors from regular methods and keeping track
900 * of the _to_str and _free functions, if any, separately. If there are any
901 * overloaded functions, then they are grouped based on their name
902 * after removing the argument type suffix.
904 * Then we print out each class in turn. If one of these is a subclass
905 * of some other class, it will make sure the superclass is printed out first.
907 void generate_python(set<RecordDecl *> &exported_types,
908 set<FunctionDecl *> exported_functions, set<FunctionDecl *> functions)
910 map<string, isl_class> classes;
911 map<string, isl_class>::iterator ci;
912 set<string> done;
913 map<string, FunctionDecl *> functions_by_name;
915 set<FunctionDecl *>::iterator in;
916 for (in = functions.begin(); in != functions.end(); ++in) {
917 FunctionDecl *decl = *in;
918 functions_by_name[decl->getName()] = decl;
921 set<RecordDecl *>::iterator it;
922 for (it = exported_types.begin(); it != exported_types.end(); ++it) {
923 RecordDecl *decl = *it;
924 map<string, FunctionDecl *>::iterator i;
926 string name = decl->getName();
927 classes[name].name = name;
928 classes[name].type = decl;
929 classes[name].fn_to_str = NULL;
930 classes[name].fn_free = NULL;
932 i = functions_by_name.find(name + "_to_str");
933 if (i != functions_by_name.end())
934 classes[name].fn_to_str = i->second;
936 i = functions_by_name.find (name + "_free");
937 if (i == functions_by_name.end())
938 die("No _free function found");
939 classes[name].fn_free = i->second;
942 for (in = exported_functions.begin(); in != exported_functions.end();
943 ++in) {
944 isl_class *c = method2class(classes, *in);
945 if (!c)
946 continue;
947 if (is_constructor(*in)) {
948 c->constructors.insert(*in);
949 } else {
950 FunctionDecl *method = *in;
951 string fullname = method->getName();
952 fullname = drop_type_suffix(fullname, method);
953 c->methods[fullname].insert(method);
957 for (ci = classes.begin(); ci != classes.end(); ++ci) {
958 if (done.find(ci->first) == done.end())
959 ci->second.print(classes, done);