2 * Copyright 2011,2015 Sven Verdoolaege. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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
34 #include "isl_config.h"
45 #include "generator.h"
47 /* Argument format for Python methods with a fixed number of arguments.
49 static const char *fixed_arg_fmt
= "arg%d";
50 /* Argument format for Python methods with a variable number of arguments.
52 static const char *var_arg_fmt
= "args[%d]";
54 /* Drop the "isl_" initial part of the type name "name".
56 static string
type2python(string name
)
58 return name
.substr(4);
61 /* Print the arguments of a method with "n_arg" arguments, starting at "first".
63 void python_generator::print_method_arguments(int first
, int n_arg
)
65 for (int i
= first
; i
< n_arg
; ++i
) {
72 /* Print the start of a definition for method "name"
73 * (without specifying the arguments).
74 * If "is_static" is set, then mark the python method as static.
76 * If the method is called "from", then rename it to "convert_from"
77 * because "from" is a python keyword.
79 static void print_method_def(bool is_static
, const string
&name
)
84 printf(" @staticmethod\n");
93 /* Print the header of the method "name" with "n_arg" arguments.
94 * If "is_static" is set, then mark the python method as static.
96 void python_generator::print_method_header(bool is_static
, const string
&name
,
99 print_method_def(is_static
, name
);
101 print_method_arguments(0, n_arg
);
105 /* Print formatted output with the given indentation.
107 static void print_indent(int indent
, const char *format
, ...)
111 printf("%*s", indent
, " ");
112 va_start(args
, format
);
113 vprintf(format
, args
);
117 /* Print a check that the argument in position "pos" is of type "type"
118 * with the given indentation.
119 * If this fails and if "upcast" is set, then convert the first
120 * argument to "super" and call the method "name" on it, passing
121 * the remaining of the "n" arguments.
122 * If the check fails and "upcast" is not set, then simply raise
124 * If "upcast" is not set, then the "super", "name" and "n" arguments
125 * to this function are ignored.
126 * "fmt" is the format for printing Python method arguments.
128 void python_generator::print_type_check(int indent
, const string
&type
,
129 const char *fmt
, int pos
, bool upcast
, const string
&super
,
130 const string
&name
, int n
)
132 print_indent(indent
, "try:\n");
133 print_indent(indent
, " if not ");
135 printf(".__class__ is %s:\n", type
.c_str());
136 print_indent(indent
, " ");
138 printf(" = %s(", type
.c_str());
141 print_indent(indent
, "except:\n");
143 print_indent(indent
, " return %s(",
144 type2python(super
).c_str());
146 printf(").%s(", name
.c_str());
147 for (int i
= 1; i
< n
; ++i
) {
154 print_indent(indent
, " raise\n");
157 /* For each of the "n" initial arguments of the function "method"
158 * that refer to an isl structure,
159 * including the object on which the method is called,
160 * check if the corresponding actual argument is of the right type.
161 * If not, try and convert it to the right type.
162 * If that doesn't work and if "super" contains at least one element,
163 * try and convert self to the type of the first superclass in "super" and
164 * call the corresponding method.
165 * If "first_is_ctx" is set, then the first argument is skipped.
167 void python_generator::print_type_checks(const string
&cname
,
168 FunctionDecl
*method
, bool first_is_ctx
, int n
,
169 const vector
<string
> &super
)
171 for (int i
= first_is_ctx
; i
< n
; ++i
) {
172 ParmVarDecl
*param
= method
->getParamDecl(i
);
175 if (!is_isl_type(param
->getOriginalType()))
177 type
= type2python(extract_type(param
->getOriginalType()));
178 if (!first_is_ctx
&& i
> 0 && super
.size() > 0)
179 print_type_check(8, type
, fixed_arg_fmt
,
180 i
- first_is_ctx
, true,
183 print_type_check(8, type
, fixed_arg_fmt
,
184 i
- first_is_ctx
, false, "", cname
, -1);
188 /* Print a call to the *_copy function corresponding to "type".
190 void python_generator::print_copy(QualType type
)
192 string type_s
= extract_type(type
);
194 printf("isl.%s_copy", type_s
.c_str());
197 /* Construct a wrapper for callback argument "param" (at position "arg").
198 * Assign the wrapper to "cb{arg}".
200 * The wrapper converts the arguments of the callback to python types,
201 * taking a copy if the C callback does not take its arguments.
202 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
203 * and returns a value indicating an error. Otherwise the wrapper
204 * returns a value indicating success.
205 * In case the C callback is expected to return an isl_stat,
206 * the error value is -1 and the success value is 0.
207 * In case the C callback is expected to return an isl_bool,
208 * the error value is -1 and the success value is 1 or 0 depending
209 * on the result of the Python callback.
210 * Otherwise, None is returned to indicate an error and
211 * a copy of the object in case of success.
213 void python_generator::print_callback(ParmVarDecl
*param
, int arg
)
215 QualType type
= param
->getOriginalType();
216 const FunctionProtoType
*fn
= extract_prototype(type
);
217 QualType return_type
= fn
->getReturnType();
218 unsigned n_arg
= fn
->getNumArgs();
220 printf(" exc_info = [None]\n");
221 printf(" fn = CFUNCTYPE(");
222 if (is_isl_stat(return_type
) || is_isl_bool(return_type
))
226 for (unsigned i
= 0; i
< n_arg
- 1; ++i
) {
227 if (!is_isl_type(fn
->getArgType(i
)))
228 die("Argument has non-isl type");
229 printf(", c_void_p");
231 printf(", c_void_p)\n");
232 printf(" def cb_func(");
233 for (unsigned i
= 0; i
< n_arg
; ++i
) {
236 printf("cb_arg%d", i
);
239 for (unsigned i
= 0; i
< n_arg
- 1; ++i
) {
241 arg_type
= type2python(extract_type(fn
->getArgType(i
)));
242 printf(" cb_arg%d = %s(ctx=arg0.ctx, ptr=",
243 i
, arg_type
.c_str());
244 if (!callback_takes_argument(param
, i
))
245 print_copy(fn
->getArgType(i
));
246 printf("(cb_arg%d))\n", i
);
249 if (is_isl_stat(return_type
))
250 printf(" arg%d(", arg
);
252 printf(" res = arg%d(", arg
);
253 for (unsigned i
= 0; i
< n_arg
- 1; ++i
) {
256 printf("cb_arg%d", i
);
259 printf(" except BaseException as e:\n");
260 printf(" exc_info[0] = e\n");
261 if (is_isl_stat(return_type
) || is_isl_bool(return_type
))
262 printf(" return -1\n");
264 printf(" return None\n");
265 if (is_isl_stat(return_type
)) {
266 printf(" return 0\n");
267 } else if (is_isl_bool(return_type
)) {
268 printf(" return 1 if res else 0\n");
271 print_copy(return_type
);
272 printf("(res.ptr)\n");
274 printf(" cb%d = fn(cb_func)\n", arg
);
277 /* Print the argument at position "arg" in call to "fd".
278 * "fmt" is the format for printing Python method arguments.
279 * "skip" is the number of initial arguments of "fd" that are
280 * skipped in the Python method.
282 * If the (first) argument is an isl_ctx, then print "ctx",
283 * assuming that the caller has made the context available
284 * in a "ctx" variable.
285 * Otherwise, if the argument is a callback, then print a reference to
286 * the corresponding callback wrapper.
287 * Otherwise, if the argument is marked as consuming a reference,
288 * then pass a copy of the pointer stored in the corresponding
289 * argument passed to the Python method.
290 * Otherwise, if the argument is a string, then the python string is first
291 * encoded as a byte sequence, using 'ascii' as encoding. This assumes
292 * that all strings passed to isl can be converted to 'ascii'.
293 * Otherwise, if the argument is a pointer, then pass this pointer itself.
294 * Otherwise, pass the argument directly.
296 void python_generator::print_arg_in_call(FunctionDecl
*fd
, const char *fmt
,
299 ParmVarDecl
*param
= fd
->getParamDecl(arg
);
300 QualType type
= param
->getOriginalType();
301 if (is_isl_ctx(type
)) {
303 } else if (is_callback(type
)) {
304 printf("cb%d", arg
- skip
);
305 } else if (takes(param
)) {
308 printf(fmt
, arg
- skip
);
310 } else if (is_string(type
)) {
311 printf(fmt
, arg
- skip
);
312 printf(".encode('ascii')");
313 } else if (type
->isPointerType()) {
314 printf(fmt
, arg
- skip
);
317 printf(fmt
, arg
- skip
);
321 /* Generate code that raises the exception captured in "exc_info", if any,
322 * with the given indentation.
324 static void print_rethrow(int indent
, const char *exc_info
)
326 print_indent(indent
, "if %s is not None:\n", exc_info
);
327 print_indent(indent
, " raise %s\n", exc_info
);
330 /* Print code with the given indentation that checks
331 * whether any of the persistent callbacks of "clazz"
332 * is set and if it failed with an exception. If so, the 'exc_info'
333 * field contains the exception and is raised again.
334 * The field is cleared because the callback and its data may get reused.
335 * "fmt" is the format for printing Python method arguments.
337 static void print_persistent_callback_failure_check(int indent
,
338 const isl_class
&clazz
, const char *fmt
)
340 const set
<FunctionDecl
*> &callbacks
= clazz
.persistent_callbacks
;
341 set
<FunctionDecl
*>::const_iterator in
;
343 for (in
= callbacks
.begin(); in
!= callbacks
.end(); ++in
) {
344 string callback_name
= clazz
.persistent_callback_name(*in
);
346 print_indent(indent
, "if hasattr(");
348 printf(", '%s') and ", callback_name
.c_str());
350 printf(".%s['exc_info'] != None:\n", callback_name
.c_str());
351 print_indent(indent
, " exc_info = ");
353 printf(".%s['exc_info'][0]\n", callback_name
.c_str());
354 print_indent(indent
, " ");
356 printf(".%s['exc_info'][0] = None\n", callback_name
.c_str());
357 print_rethrow(indent
+ 4, "exc_info");
361 /* Print the return statement of the python method corresponding
362 * to the C function "method" with the given indentation.
363 * If the object on which the method was called
364 * may have a persistent callback, then first check if any of those failed.
365 * "fmt" is the format for printing Python method arguments.
367 * If the method returns a new instance of the same object type and
368 * if the class has any persistent callbacks, then the data
369 * for these callbacks are copied from the original to the new object.
370 * If the method it itself setting a persistent callback,
371 * then keep track of the constructed C callback (such that it doesn't
372 * get destroyed) and the data structure that holds the captured exception
373 * (such that it can be raised again).
374 * The callback appears in position 1 and the C callback is therefore
377 * If the return type is a (const) char *, then convert the result
378 * to a Python string, raising an error on NULL and freeing
379 * the C string if needed. For python 3 compatibility, the string returned
380 * by isl is explicitly decoded as an 'ascii' string. This is correct
381 * as all strings returned by isl are expected to be 'ascii'.
383 * If the return type is isl_stat, isl_bool or isl_size, then
384 * raise an error on isl_stat_error, isl_bool_error or isl_size_error.
385 * In case of isl_bool, the result is converted to
387 * In case of isl_size, the result is converted to a Python int.
389 void python_generator::print_method_return(int indent
, const isl_class
&clazz
,
390 FunctionDecl
*method
, const char *fmt
)
392 QualType return_type
= method
->getReturnType();
394 if (!is_static(clazz
, method
))
395 print_persistent_callback_failure_check(indent
, clazz
, fmt
);
397 if (is_isl_type(return_type
)) {
400 type
= type2python(extract_type(return_type
));
402 "obj = %s(ctx=ctx, ptr=res)\n", type
.c_str());
403 if (is_mutator(clazz
, method
) &&
404 clazz
.has_persistent_callbacks())
405 print_indent(indent
, "obj.copy_callbacks(arg0)\n");
406 if (clazz
.persistent_callbacks
.count(method
)) {
407 string callback_name
;
409 callback_name
= clazz
.persistent_callback_name(method
);
410 print_indent(indent
, "obj.%s = { 'func': cb1, "
411 "'exc_info': exc_info }\n",
412 callback_name
.c_str());
414 print_indent(indent
, "return obj\n");
415 } else if (is_string(return_type
)) {
416 print_indent(indent
, "if res == 0:\n");
417 print_indent(indent
, " raise Error\n");
418 print_indent(indent
, "string = "
419 "cast(res, c_char_p).value.decode('ascii')\n");
422 print_indent(indent
, "libc.free(res)\n");
424 print_indent(indent
, "return string\n");
425 } else if (is_isl_neg_error(return_type
)) {
426 print_indent(indent
, "if res < 0:\n");
427 print_indent(indent
, " raise Error\n");
428 if (is_isl_bool(return_type
))
429 print_indent(indent
, "return bool(res)\n");
430 else if (is_isl_size(return_type
))
431 print_indent(indent
, "return int(res)\n");
433 print_indent(indent
, "return res\n");
437 /* Print a python "get" method corresponding to the C function "fd"
438 * in class "clazz" using a name that includes the "get_" prefix.
440 * This method simply calls the variant without the "get_" prefix and
441 * returns its result.
442 * Note that static methods are not considered to be "get" methods.
444 void python_generator::print_get_method(const isl_class
&clazz
,
447 string get_name
= clazz
.base_method_name(fd
);
448 string name
= clazz
.method_name(fd
);
449 int num_params
= fd
->getNumParams();
451 print_method_header(false, get_name
, num_params
);
452 printf(" return arg0.%s(", name
.c_str());
453 print_method_arguments(1, num_params
);
457 /* Print a call to "method", along with the corresponding
458 * return statement, with the given indentation.
459 * "drop_ctx" is set if the first argument is an isl_ctx.
461 * A "ctx" variable is first initialized as it may be needed
462 * in the first call to print_arg_in_call and in print_method_return.
464 * If the method has any callback function, then any exception
465 * thrown in any callback also need to be rethrown.
467 void python_generator::print_method_call(int indent
, const isl_class
&clazz
,
468 FunctionDecl
*method
, const char *fmt
, int drop_ctx
)
470 string fullname
= method
->getName().str();
471 int num_params
= method
->getNumParams();
475 print_indent(indent
, "ctx = Context.getDefaultInstance()\n");
477 print_indent(indent
, "ctx = ");
481 print_indent(indent
, "res = isl.%s(", fullname
.c_str());
482 for (int i
= 0; i
< num_params
; ++i
) {
485 print_arg_in_call(method
, fmt
, i
, drop_ctx
+ drop_user
);
486 if (!is_callback_arg(method
, i
))
495 print_rethrow(indent
, "exc_info[0]");
497 print_method_return(indent
, clazz
, method
, fmt
);
500 /* Print a python method corresponding to the C function "method".
501 * "super" contains the superclasses of the class to which the method belongs,
502 * with the first element corresponding to the annotation that appears
503 * closest to the annotated type. This superclass is the least
504 * general extension of the annotated type in the linearization
505 * of the class hierarchy.
507 * If the first argument of "method" is something other than an instance
508 * of the class, then mark the python method as static.
509 * If, moreover, this first argument is an isl_ctx, then remove
510 * it from the arguments of the Python method.
512 * If the function has any callback arguments, then it also has corresponding
513 * "user" arguments. Since Python has closures, there is no need for such
514 * user arguments in the Python interface, so we simply drop them.
515 * We also create a wrapper ("cb{arg}") for each callback.
517 * If the function consumes a reference, then we pass it a copy of
518 * the actual argument.
520 * For methods that are identified as "get" methods, also
521 * print a variant of the method using a name that includes
524 void python_generator::print_method(const isl_class
&clazz
,
525 FunctionDecl
*method
, vector
<string
> super
)
527 string cname
= clazz
.method_name(method
);
528 int num_params
= method
->getNumParams();
530 int drop_ctx
= first_arg_is_isl_ctx(method
);
532 for (int i
= 1; i
< num_params
; ++i
) {
533 if (is_callback_arg(method
, i
))
537 print_method_header(is_static(clazz
, method
), cname
,
538 num_params
- drop_ctx
- drop_user
);
540 print_type_checks(cname
, method
, drop_ctx
,
543 for (int i
= 1; i
< num_params
; ++i
) {
544 ParmVarDecl
*param
= method
->getParamDecl(i
);
545 QualType type
= param
->getOriginalType();
546 if (!is_callback(type
))
548 print_callback(param
, i
- drop_ctx
- drop_user
);
551 print_method_call(8, clazz
, method
, fixed_arg_fmt
, drop_ctx
);
553 if (clazz
.is_get_method(method
))
554 print_get_method(clazz
, method
);
557 /* Print a condition that checks whether Python method argument "i"
558 * corresponds to the C function argument type "type".
560 static void print_argument_check(QualType type
, int i
)
562 if (generator::is_isl_type(type
)) {
564 type_str
= generator::extract_type(type
);
565 type_str
= type2python(type_str
);
566 printf("args[%d].__class__ is %s", i
, type_str
.c_str());
567 } else if (type
->isPointerType()) {
568 printf("type(args[%d]) == str", i
);
570 printf("type(args[%d]) == int", i
);
574 /* Is any element of "vector" set?
576 static bool any(const std::vector
<bool> &vector
)
578 return std::find(vector
.begin(), vector
.end(), true) != vector
.end();
581 /* Print a test that checks whether the arguments passed
582 * to the Python method correspond to the arguments
583 * expected by "fd" and
584 * check if the object on which the method is called, if any,
585 * is of the right type.
586 * "drop_ctx" is set if the first argument of "fd" is an isl_ctx,
587 * which does not appear as an argument to the Python method.
589 * If an automatic conversion function is available for any
590 * of the argument types, then also allow the argument
591 * to be of the type as prescribed by the second input argument
592 * of the conversion function.
593 * The corresponding arguments are then converted to the expected types
595 * The object on which the method is called is also converted if needed.
596 * The argument tuple first needs to be converted to a list
597 * in order to be able to modify the entries.
599 void python_generator::print_argument_checks(const isl_class
&clazz
,
600 FunctionDecl
*fd
, int drop_ctx
)
602 int num_params
= fd
->getNumParams();
603 bool is_static
= generator::is_static(clazz
, fd
);
604 int first
= is_static
? drop_ctx
: 1;
605 std::vector
<bool> convert(num_params
);
607 printf(" if len(args) == %d", num_params
- drop_ctx
);
608 for (int i
= first
; i
< num_params
; ++i
) {
609 ParmVarDecl
*param
= fd
->getParamDecl(i
);
610 QualType type
= param
->getOriginalType();
611 const Type
*ptr
= type
.getTypePtr();
614 if (conversions
.count(ptr
) == 0) {
615 print_argument_check(type
, i
- drop_ctx
);
617 QualType type2
= conversions
.at(ptr
)->getOriginalType();
620 print_argument_check(type
, i
- drop_ctx
);
622 print_argument_check(type2
, i
- drop_ctx
);
628 if (is_static
&& !any(convert
))
630 print_indent(12, "args = list(args)\n");
631 first
= is_static
? drop_ctx
: 0;
632 for (int i
= first
; i
< num_params
; ++i
) {
633 bool is_self
= !is_static
&& i
== 0;
634 ParmVarDecl
*param
= fd
->getParamDecl(i
);
637 if (!is_self
&& !convert
[i
])
639 type
= type2python(extract_type(param
->getOriginalType()));
640 print_type_check(12, type
, var_arg_fmt
,
641 i
- drop_ctx
, false, "", "", -1);
645 /* Print part of an overloaded python method corresponding to the C function
647 * "drop_ctx" is set if the first argument of "method" is an isl_ctx.
649 * In particular, print code to test whether the arguments passed to
650 * the python method correspond to the arguments expected by "method"
651 * and to call "method" if they do.
653 void python_generator::print_method_overload(const isl_class
&clazz
,
654 FunctionDecl
*method
)
656 int drop_ctx
= first_arg_is_isl_ctx(method
);
658 print_argument_checks(clazz
, method
, drop_ctx
);
659 print_method_call(12, clazz
, method
, var_arg_fmt
, drop_ctx
);
662 /* Print a python method with a name derived from "fullname"
663 * corresponding to the C functions "methods".
664 * "super" contains the superclasses of the class to which the method belongs.
666 * If "methods" consists of a single element that is not marked overloaded,
667 * the use print_method to print the method.
668 * Otherwise, print an overloaded method with pieces corresponding
669 * to each function in "methods".
671 void python_generator::print_method(const isl_class
&clazz
,
672 const string
&fullname
, const function_set
&methods
,
673 vector
<string
> super
)
676 function_set::const_iterator it
;
677 FunctionDecl
*any_method
;
679 any_method
= *methods
.begin();
680 if (methods
.size() == 1 && !is_overload(any_method
)) {
681 print_method(clazz
, any_method
, super
);
685 cname
= clazz
.method_name(any_method
);
687 print_method_def(is_static(clazz
, any_method
), cname
);
688 printf("(*args):\n");
690 for (it
= methods
.begin(); it
!= methods
.end(); ++it
)
691 print_method_overload(clazz
, *it
);
692 printf(" raise Error\n");
695 /* Print a python method "name" corresponding to "fd" setting
696 * the enum value "value".
697 * "super" contains the superclasses of the class to which the method belongs,
698 * with the first element corresponding to the annotation that appears
699 * closest to the annotated type.
701 * The last argument of the C function does not appear in the method call,
702 * but is fixed to "value" instead.
703 * Other than that, the method printed here is similar to one
704 * printed by python_generator::print_method, except that
705 * some of the special cases do not occur.
707 void python_generator::print_set_enum(const isl_class
&clazz
,
708 FunctionDecl
*fd
, int value
, const string
&name
,
709 const vector
<string
> &super
)
711 string fullname
= fd
->getName().str();
712 int num_params
= fd
->getNumParams();
714 print_method_header(is_static(clazz
, fd
), name
, num_params
- 1);
716 print_type_checks(name
, fd
, false, num_params
- 1, super
);
717 printf(" ctx = arg0.ctx\n");
718 printf(" res = isl.%s(", fullname
.c_str());
719 for (int i
= 0; i
< num_params
- 1; ++i
) {
722 print_arg_in_call(fd
, fixed_arg_fmt
, i
, 0);
724 printf(", %d", value
);
726 print_method_return(8, clazz
, fd
, fixed_arg_fmt
);
729 /* Print python methods corresponding to "fd", which sets an enum.
730 * "super" contains the superclasses of the class to which the method belongs,
731 * with the first element corresponding to the annotation that appears
732 * closest to the annotated type.
734 * A method is generated for each value in the enum, setting
735 * the enum to that value.
737 void python_generator::print_set_enum(const isl_class
&clazz
,
738 FunctionDecl
*fd
, const vector
<string
> &super
)
740 vector
<set_enum
>::const_iterator it
;
741 const vector
<set_enum
> &set_enums
= clazz
.set_enums
.at(fd
);
743 for (it
= set_enums
.begin(); it
!= set_enums
.end(); ++it
)
744 print_set_enum(clazz
, fd
, it
->value
, it
->method_name
, super
);
747 /* Print part of the constructor for this isl_class.
749 * In particular, check if the actual arguments correspond to the
750 * formal arguments of "cons" and if so call "cons" and put the
751 * result in self.ptr and a reference to the default context in self.ctx.
753 void python_generator::print_constructor(const isl_class
&clazz
,
756 string fullname
= cons
->getName().str();
757 string cname
= clazz
.method_name(cons
);
758 int num_params
= cons
->getNumParams();
759 int drop_ctx
= first_arg_is_isl_ctx(cons
);
761 print_argument_checks(clazz
, cons
, drop_ctx
);
762 printf(" self.ctx = Context.getDefaultInstance()\n");
763 printf(" self.ptr = isl.%s(", fullname
.c_str());
766 for (int i
= drop_ctx
; i
< num_params
; ++i
) {
769 print_arg_in_call(cons
, var_arg_fmt
, i
, drop_ctx
);
775 /* The definition of the part of constructor for the "id" class
776 * that construct an object from a name and a user object,
777 * without the initial newline.
779 * Just like the parts generated by python_generator::print_constructor,
780 * the result of the isl_id_alloc call is stored in self.ptr and
781 * a reference to the default context is stored in self.ctx.
782 * Also, just like any other constructor or method with a string argument,
783 * the python string is first encoded as a byte sequence,
784 * using 'ascii' as encoding.
786 * Since the isl_id keeps a reference to the Python user object,
787 * the reference count of the Python object needs to be incremented,
788 * but only if the construction of the isl_id is successful.
789 * The reference count of the Python object is decremented again
790 * by Context.free_user when the reference count of the isl_id
793 static const char *const id_constructor_user
= &R
"(
794 if len(args) == 2 and type(args[0]) == str:
795 self.ctx = Context.getDefaultInstance()
796 name = args[0].encode('ascii')
797 self.ptr = isl.isl_id_alloc(self.ctx, name, args[1])
798 self.ptr = isl.isl_id_set_free_user(self.ptr, Context.free_user)
799 if self.ptr is not None:
800 pythonapi.Py_IncRef(py_object(args[1]))
804 /* Print any special constructor parts of this class that are not
805 * automatically derived from the C interface.
807 * In particular, print a special constructor part for the "id" class.
809 void python_generator::print_special_constructors(const isl_class
&clazz
)
811 if (clazz
.name
!= "isl_id")
814 printf("%s", id_constructor_user
);
817 /* The definition of an "id" method
818 * for retrieving the user object associated to the identifier,
819 * without the initial newline.
821 * The isl_id needs to have been created by the constructor
822 * in id_constructor_user. That is, it needs to have a user pointer and
823 * it needs to have its free_user callback set to Context.free_user.
824 * The functions need to be cast to c_void_p to be able to compare
827 * Return None if any of the checks fail.
828 * Note that isl_id_get_user returning NULL automatically results in None.
830 static const char *const id_user
= &R
"(
832 free_user = cast(Context.free_user, c_void_p)
833 id_free_user = cast(isl.isl_id_get_free_user(self.ptr), c_void_p)
834 if id_free_user.value != free_user.value:
836 return isl.isl_id_get_user(self.ptr)
839 /* Print any special methods of this class that are not
840 * automatically derived from the C interface.
842 * In particular, print a special method for the "id" class.
844 void python_generator::print_special_methods(const isl_class
&clazz
)
846 if (clazz
.name
!= "isl_id")
849 printf("%s", id_user
);
852 /* If "clazz" has a type function describing subclasses,
853 * then add constructors that allow each of these subclasses
854 * to be treated as an object to the superclass.
856 void python_generator::print_upcast_constructors(const isl_class
&clazz
)
858 map
<int, string
>::const_iterator i
;
863 for (i
= clazz
.type_subclasses
.begin();
864 i
!= clazz
.type_subclasses
.end(); ++i
) {
865 printf(" if len(args) == 1 and "
866 "isinstance(args[0], %s):\n",
867 type2python(i
->second
).c_str());
868 printf(" self.ctx = args[0].ctx\n");
869 printf(" self.ptr = isl.%s_copy(args[0].ptr)\n",
875 /* Print the header of the class "name" with superclasses "super".
876 * The order of the superclasses is the opposite of the order
877 * in which the corresponding annotations appear in the source code.
878 * If "clazz" is a subclass derived from a type function,
879 * then the immediate superclass is recorded in "clazz" itself.
881 void python_generator::print_class_header(const isl_class
&clazz
,
882 const string
&name
, const vector
<string
> &super
)
884 printf("class %s", name
.c_str());
885 if (super
.size() > 0) {
887 for (unsigned i
= 0; i
< super
.size(); ++i
) {
890 printf("%s", type2python(super
[i
]).c_str());
893 } else if (clazz
.is_type_subclass()) {
894 printf("(%s)", type2python(clazz
.superclass_name
).c_str());
901 /* Tell ctypes about the return type of "fd".
902 * In particular, if "fd" returns a pointer to an isl object,
903 * then tell ctypes it returns a "c_void_p".
904 * If "fd" returns a char *, then simply tell ctypes.
906 * Nothing needs to be done for functions returning
907 * isl_bool, isl_stat or isl_size since they are represented by an int and
908 * ctypes assumes that a function returns int by default.
910 void python_generator::print_restype(FunctionDecl
*fd
)
912 string fullname
= fd
->getName().str();
913 QualType type
= fd
->getReturnType();
914 if (is_isl_type(type
))
915 printf("isl.%s.restype = c_void_p\n", fullname
.c_str());
916 else if (is_string(type
))
917 printf("isl.%s.restype = POINTER(c_char)\n", fullname
.c_str());
920 /* Tell ctypes about the types of the arguments of the function "fd".
922 * Any callback argument is followed by a user pointer argument.
923 * Each such pair or arguments is handled together.
925 void python_generator::print_argtypes(FunctionDecl
*fd
)
927 string fullname
= fd
->getName().str();
928 int n
= fd
->getNumParams();
930 printf("isl.%s.argtypes = [", fullname
.c_str());
931 for (int i
= 0; i
< n
; ++i
) {
932 ParmVarDecl
*param
= fd
->getParamDecl(i
);
933 QualType type
= param
->getOriginalType();
936 if (is_isl_ctx(type
))
938 else if (is_isl_type(type
))
940 else if (is_callback(type
))
941 printf("c_void_p, c_void_p");
942 else if (is_string(type
))
944 else if (is_long(type
))
949 if (is_callback(type
))
955 /* Print type definitions for the method 'fd'.
957 void python_generator::print_method_type(FunctionDecl
*fd
)
963 /* If "clazz" has a type function describing subclasses or
964 * if it is one of those type subclasses, then print a __new__ method.
966 * In the superclass, the __new__ method constructs an object
967 * of the subclass type specified by the type function,
968 * raising an error on an error type.
969 * In the subclass, the __new__ method reverts to the original behavior.
971 void python_generator::print_new(const isl_class
&clazz
,
972 const string
&python_name
)
974 if (!clazz
.fn_type
&& !clazz
.is_type_subclass())
977 printf(" def __new__(cls, *args, **keywords):\n");
980 map
<int, string
>::const_iterator i
;
982 printf(" if \"ptr\" in keywords:\n");
983 printf(" type = isl.%s(keywords[\"ptr\"])\n",
984 clazz
.fn_type
->getNameAsString().c_str());
986 for (i
= clazz
.type_subclasses
.begin();
987 i
!= clazz
.type_subclasses
.end(); ++i
) {
988 printf(" if type == %d:\n", i
->first
);
989 printf(" return %s(**keywords)\n",
990 type2python(i
->second
).c_str());
992 printf(" raise Error\n");
995 printf(" return super(%s, cls).__new__(cls)\n",
996 python_name
.c_str());
999 /* Print declarations for methods printing the class representation,
1000 * provided there is a corresponding *_to_str function.
1002 * In particular, provide an implementation of __str__ and __repr__ methods to
1003 * override the default representation used by python. Python uses __str__ to
1004 * pretty print the class (e.g., when calling print(obj)) and uses __repr__
1005 * when printing a precise representation of an object (e.g., when dumping it
1006 * in the REPL console).
1008 * Check the type of the argument before calling the *_to_str function
1009 * on it in case the method was called on an object from a subclass.
1011 * The return value of the *_to_str function is decoded to a python string
1012 * assuming an 'ascii' encoding. This is necessary for python 3 compatibility.
1014 void python_generator::print_representation(const isl_class
&clazz
,
1015 const string
&python_name
)
1017 if (!clazz
.fn_to_str
)
1020 printf(" def __str__(arg0):\n");
1021 print_type_check(8, python_name
, fixed_arg_fmt
, 0, false, "", "", -1);
1022 printf(" ptr = isl.%s(arg0.ptr)\n",
1023 string(clazz
.fn_to_str
->getName()).c_str());
1024 printf(" res = cast(ptr, c_char_p).value.decode('ascii')\n");
1025 printf(" libc.free(ptr)\n");
1026 printf(" return res\n");
1027 printf(" def __repr__(self):\n");
1028 printf(" s = str(self)\n");
1029 printf(" if '\"' in s:\n");
1030 printf(" return 'isl.%s(\"\"\"%%s\"\"\")' %% s\n",
1031 python_name
.c_str());
1033 printf(" return 'isl.%s(\"%%s\")' %% s\n",
1034 python_name
.c_str());
1037 /* If "clazz" has any persistent callbacks, then print the definition
1038 * of a "copy_callbacks" function that copies the persistent callbacks
1039 * from one object to another.
1041 void python_generator::print_copy_callbacks(const isl_class
&clazz
)
1043 const set
<FunctionDecl
*> &callbacks
= clazz
.persistent_callbacks
;
1044 set
<FunctionDecl
*>::const_iterator in
;
1046 if (!clazz
.has_persistent_callbacks())
1049 printf(" def copy_callbacks(self, obj):\n");
1050 for (in
= callbacks
.begin(); in
!= callbacks
.end(); ++in
) {
1051 string callback_name
= clazz
.persistent_callback_name(*in
);
1053 printf(" if hasattr(obj, '%s'):\n",
1054 callback_name
.c_str());
1055 printf(" self.%s = obj.%s\n",
1056 callback_name
.c_str(), callback_name
.c_str());
1060 /* Print code to set method type signatures.
1062 * To be able to call C functions it is necessary to explicitly set their
1063 * argument and result types. Do this for all exported constructors and
1064 * methods (including those that set a persistent callback and
1065 * those that set an enum value),
1066 * as well as for the *_to_str and the type function, if they exist.
1067 * Assuming each exported class has a *_copy and a *_free method,
1068 * also unconditionally set the type of such methods.
1070 void python_generator::print_method_types(const isl_class
&clazz
)
1072 function_set::const_iterator in
;
1073 map
<string
, function_set
>::const_iterator it
;
1074 map
<FunctionDecl
*, vector
<set_enum
> >::const_iterator ie
;
1075 const set
<FunctionDecl
*> &callbacks
= clazz
.persistent_callbacks
;
1077 for (in
= clazz
.constructors
.begin(); in
!= clazz
.constructors
.end();
1079 print_method_type(*in
);
1081 for (in
= callbacks
.begin(); in
!= callbacks
.end(); ++in
)
1082 print_method_type(*in
);
1083 for (it
= clazz
.methods
.begin(); it
!= clazz
.methods
.end(); ++it
)
1084 for (in
= it
->second
.begin(); in
!= it
->second
.end(); ++in
)
1085 print_method_type(*in
);
1086 for (ie
= clazz
.set_enums
.begin(); ie
!= clazz
.set_enums
.end(); ++ie
)
1087 print_method_type(ie
->first
);
1089 print_method_type(clazz
.fn_copy
);
1090 print_method_type(clazz
.fn_free
);
1091 if (clazz
.fn_to_str
)
1092 print_method_type(clazz
.fn_to_str
);
1094 print_method_type(clazz
.fn_type
);
1097 /* Print out the definition of this isl_class.
1099 * We first check if this isl_class is a subclass of one or more other classes.
1100 * If it is, we make sure those superclasses are printed out first.
1102 * Then we print a constructor with several cases, one for constructing
1103 * a Python object from a return value, one for each function that
1104 * was marked as a constructor, a class specific constructor, if any, and
1105 * one for each type based subclass.
1107 * Next, we print out some common methods, class specific methods and
1108 * the methods corresponding
1109 * to functions that are not marked as constructors, including those
1110 * that set a persistent callback and those that set an enum value.
1112 * Finally, we tell ctypes about the types of the arguments of the
1113 * constructor functions and the return types of those function returning
1116 void python_generator::print(const isl_class
&clazz
)
1118 string p_name
= type2python(clazz
.subclass_name
);
1119 vector
<string
> super
= find_superclasses(clazz
.type
);
1120 const set
<FunctionDecl
*> &callbacks
= clazz
.persistent_callbacks
;
1122 for (unsigned i
= 0; i
< super
.size(); ++i
)
1123 if (done
.find(super
[i
]) == done
.end())
1124 print(classes
[super
[i
]]);
1125 if (clazz
.is_type_subclass() && done
.find(clazz
.name
) == done
.end())
1126 print(classes
[clazz
.name
]);
1127 done
.insert(clazz
.subclass_name
);
1130 print_class_header(clazz
, p_name
, super
);
1131 printf(" def __init__(self, *args, **keywords):\n");
1133 printf(" if \"ptr\" in keywords:\n");
1134 printf(" self.ctx = keywords[\"ctx\"]\n");
1135 printf(" self.ptr = keywords[\"ptr\"]\n");
1136 printf(" return\n");
1138 for (const auto &cons
: clazz
.constructors
)
1139 print_constructor(clazz
, cons
);
1140 print_special_constructors(clazz
);
1141 print_upcast_constructors(clazz
);
1142 printf(" raise Error\n");
1143 printf(" def __del__(self):\n");
1144 printf(" if hasattr(self, 'ptr'):\n");
1145 printf(" isl.%s_free(self.ptr)\n", clazz
.name
.c_str());
1147 print_new(clazz
, p_name
);
1148 print_representation(clazz
, p_name
);
1149 print_copy_callbacks(clazz
);
1151 print_special_methods(clazz
);
1152 for (const auto &callback
: callbacks
)
1153 print_method(clazz
, callback
, super
);
1154 for (const auto &kvp
: clazz
.methods
)
1155 print_method(clazz
, kvp
.first
, kvp
.second
, super
);
1156 for (const auto &kvp
: clazz
.set_enums
)
1157 print_set_enum(clazz
, kvp
.first
, super
);
1161 print_method_types(clazz
);
1164 /* Generate a python interface based on the extracted types and
1167 * Print out each class in turn. If one of these is a subclass of some
1168 * other class, make sure the superclass is printed out first.
1171 void python_generator::generate()
1173 map
<string
, isl_class
>::iterator ci
;
1175 for (ci
= classes
.begin(); ci
!= classes
.end(); ++ci
) {
1176 if (done
.find(ci
->first
) == done
.end())