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"
42 #include "generator.h"
44 /* Drop the "isl_" initial part of the type name "name".
46 static string
type2python(string name
)
48 return name
.substr(4);
51 /* Print the header of the method "name" with "n_arg" arguments.
52 * If "is_static" is set, then mark the python method as static.
54 * If the method is called "from", then rename it to "convert_from"
55 * because "from" is a python keyword.
57 void python_generator::print_method_header(bool is_static
, const string
&name
,
63 printf(" @staticmethod\n");
69 printf(" def %s(", s
);
70 for (int i
= 0; i
< n_arg
; ++i
) {
78 /* Print a check that the argument in position "pos" is of type "type".
79 * If this fails and if "upcast" is set, then convert the first
80 * argument to "super" and call the method "name" on it, passing
81 * the remaining of the "n" arguments.
82 * If the check fails and "upcast" is not set, then simply raise
84 * If "upcast" is not set, then the "super", "name" and "n" arguments
85 * to this function are ignored.
87 void python_generator::print_type_check(const string
&type
, int pos
,
88 bool upcast
, const string
&super
, const string
&name
, int n
)
91 printf(" if not arg%d.__class__ is %s:\n",
93 printf(" arg%d = %s(arg%d)\n",
94 pos
, type
.c_str(), pos
);
97 printf(" return %s(arg0).%s(",
98 type2python(super
).c_str(), name
.c_str());
99 for (int i
= 1; i
< n
; ++i
) {
109 /* Construct a wrapper for a callback argument (at position "arg").
110 * Assign the wrapper to "cb". We assume here that a function call
111 * has at most one callback argument.
113 * The wrapper converts the arguments of the callback to python types.
114 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
115 * and returns -1. Otherwise the wrapper returns 0.
117 void python_generator::print_callback(QualType type
, int arg
)
119 const FunctionProtoType
*fn
= type
->getAs
<FunctionProtoType
>();
120 unsigned n_arg
= fn
->getNumArgs();
122 printf(" exc_info = [None]\n");
123 printf(" fn = CFUNCTYPE(c_int");
124 for (unsigned i
= 0; i
< n_arg
- 1; ++i
) {
125 if (!is_isl_type(fn
->getArgType(i
)))
126 die("Argument has non-isl type");
127 printf(", c_void_p");
129 printf(", c_void_p)\n");
130 printf(" def cb_func(");
131 for (unsigned i
= 0; i
< n_arg
; ++i
) {
134 printf("cb_arg%d", i
);
137 for (unsigned i
= 0; i
< n_arg
- 1; ++i
) {
139 arg_type
= type2python(extract_type(fn
->getArgType(i
)));
140 printf(" cb_arg%d = %s(ctx=arg0.ctx, "
141 "ptr=cb_arg%d)\n", i
, arg_type
.c_str(), i
);
144 printf(" arg%d(", arg
);
145 for (unsigned i
= 0; i
< n_arg
- 1; ++i
) {
148 printf("cb_arg%d", i
);
151 printf(" except:\n");
152 printf(" import sys\n");
153 printf(" exc_info[0] = sys.exc_info()\n");
154 printf(" return -1\n");
155 printf(" return 0\n");
156 printf(" cb = fn(cb_func)\n");
159 /* Print the argument at position "arg" in call to "fd".
160 * "skip" is the number of initial arguments of "fd" that are
161 * skipped in the Python method.
163 * If the argument is a callback, then print a reference to
164 * the callback wrapper "cb".
165 * Otherwise, if the argument is marked as consuming a reference,
166 * then pass a copy of the the pointer stored in the corresponding
167 * argument passed to the Python method.
168 * Otherwise, if the argument is a pointer, then pass this pointer itself.
169 * Otherwise, pass the argument directly.
171 void python_generator::print_arg_in_call(FunctionDecl
*fd
, int arg
, int skip
)
173 ParmVarDecl
*param
= fd
->getParamDecl(arg
);
174 QualType type
= param
->getOriginalType();
175 if (is_callback(type
)) {
177 } else if (takes(param
)) {
178 string type_s
= extract_type(type
);
179 printf("isl.%s_copy(arg%d.ptr)", type_s
.c_str(), arg
- skip
);
180 } else if (type
->isPointerType()) {
181 printf("arg%d.ptr", arg
- skip
);
183 printf("arg%d", arg
- skip
);
187 /* Print the return statement of the python method corresponding
188 * to the C function "method".
190 * If the return type is a (const) char *, then convert the result
191 * to a Python string, raising an error on NULL and freeing
192 * the C string if needed. For python 3 compatibility, the string returned
193 * by isl is explicitly decoded as an 'ascii' string. This is correct
194 * as all strings returned by isl are expected to be 'ascii'.
196 * If the return type is isl_bool, then convert the result to
197 * a Python boolean, raising an error on isl_bool_error.
199 void python_generator::print_method_return(FunctionDecl
*method
)
201 QualType return_type
= method
->getReturnType();
203 if (is_isl_type(return_type
)) {
206 type
= type2python(extract_type(return_type
));
207 printf(" return %s(ctx=ctx, ptr=res)\n", type
.c_str());
208 } else if (is_string(return_type
)) {
209 printf(" if res == 0:\n");
212 "cast(res, c_char_p).value.decode('ascii')\n");
215 printf(" libc.free(res)\n");
217 printf(" return string\n");
218 } else if (is_isl_bool(return_type
)) {
219 printf(" if res < 0:\n");
221 printf(" return bool(res)\n");
223 printf(" return res\n");
227 /* Print a python method corresponding to the C function "method".
228 * "super" contains the superclasses of the class to which the method belongs,
229 * with the first element corresponding to the annotation that appears
230 * closest to the annotated type. This superclass is the least
231 * general extension of the annotated type in the linearization
232 * of the class hierarchy.
234 * If the first argument of "method" is something other than an instance
235 * of the class, then mark the python method as static.
236 * If, moreover, this first argument is an isl_ctx, then remove
237 * it from the arguments of the Python method.
239 * If the function has a callback argument, then it also has a "user"
240 * argument. Since Python has closures, there is no need for such
241 * a user argument in the Python interface, so we simply drop it.
242 * We also create a wrapper ("cb") for the callback.
244 * For each argument of the function that refers to an isl structure,
245 * including the object on which the method is called,
246 * we check if the corresponding actual argument is of the right type.
247 * If not, we try to convert it to the right type.
248 * If that doesn't work and if "super" contains at least one element, we try
249 * to convert self to the type of the first superclass in "super" and
250 * call the corresponding method.
252 * If the function consumes a reference, then we pass it a copy of
253 * the actual argument.
255 void python_generator::print_method(const isl_class
&clazz
,
256 FunctionDecl
*method
, vector
<string
> super
)
258 string fullname
= method
->getName();
259 string cname
= fullname
.substr(clazz
.name
.length() + 1);
260 int num_params
= method
->getNumParams();
262 int drop_ctx
= first_arg_is_isl_ctx(method
);
264 for (int i
= 1; i
< num_params
; ++i
) {
265 ParmVarDecl
*param
= method
->getParamDecl(i
);
266 QualType type
= param
->getOriginalType();
267 if (is_callback(type
))
271 print_method_header(is_static(clazz
, method
), cname
,
272 num_params
- drop_ctx
- drop_user
);
274 for (int i
= drop_ctx
; i
< num_params
; ++i
) {
275 ParmVarDecl
*param
= method
->getParamDecl(i
);
277 if (!is_isl_type(param
->getOriginalType()))
279 type
= type2python(extract_type(param
->getOriginalType()));
280 if (!drop_ctx
&& i
> 0 && super
.size() > 0)
281 print_type_check(type
, i
- drop_ctx
, true, super
[0],
282 cname
, num_params
- drop_user
);
284 print_type_check(type
, i
- drop_ctx
, false, "",
287 for (int i
= 1; i
< num_params
; ++i
) {
288 ParmVarDecl
*param
= method
->getParamDecl(i
);
289 QualType type
= param
->getOriginalType();
290 if (!is_callback(type
))
292 print_callback(type
->getPointeeType(), i
- drop_ctx
);
295 printf(" ctx = Context.getDefaultInstance()\n");
297 printf(" ctx = arg0.ctx\n");
298 printf(" res = isl.%s(", fullname
.c_str());
302 print_arg_in_call(method
, 0, 0);
303 for (int i
= 1; i
< num_params
- drop_user
; ++i
) {
305 print_arg_in_call(method
, i
, drop_ctx
);
312 printf(" if exc_info[0] != None:\n");
313 printf(" raise (exc_info[0][0], "
314 "exc_info[0][1], exc_info[0][2])\n");
317 print_method_return(method
);
320 /* Print part of an overloaded python method corresponding to the C function
323 * In particular, print code to test whether the arguments passed to
324 * the python method correspond to the arguments expected by "method"
325 * and to call "method" if they do.
327 void python_generator::print_method_overload(const isl_class
&clazz
,
328 FunctionDecl
*method
)
330 string fullname
= method
->getName();
331 int num_params
= method
->getNumParams();
335 first
= is_static(clazz
, method
) ? 0 : 1;
338 for (int i
= first
; i
< num_params
; ++i
) {
341 ParmVarDecl
*param
= method
->getParamDecl(i
);
342 if (is_isl_type(param
->getOriginalType())) {
344 type
= extract_type(param
->getOriginalType());
345 type
= type2python(type
);
346 printf("arg%d.__class__ is %s", i
, type
.c_str());
348 printf("type(arg%d) == str", i
);
351 printf(" res = isl.%s(", fullname
.c_str());
352 print_arg_in_call(method
, 0, 0);
353 for (int i
= 1; i
< num_params
; ++i
) {
355 print_arg_in_call(method
, i
, 0);
358 type
= type2python(extract_type(method
->getReturnType()));
359 printf(" return %s(ctx=arg0.ctx, ptr=res)\n", type
.c_str());
362 /* Print a python method with a name derived from "fullname"
363 * corresponding to the C functions "methods".
364 * "super" contains the superclasses of the class to which the method belongs.
366 * If "methods" consists of a single element that is not marked overloaded,
367 * the use print_method to print the method.
368 * Otherwise, print an overloaded method with pieces corresponding
369 * to each function in "methods".
371 void python_generator::print_method(const isl_class
&clazz
,
372 const string
&fullname
, const set
<FunctionDecl
*> &methods
,
373 vector
<string
> super
)
376 set
<FunctionDecl
*>::const_iterator it
;
378 FunctionDecl
*any_method
;
380 any_method
= *methods
.begin();
381 if (methods
.size() == 1 && !is_overload(any_method
)) {
382 print_method(clazz
, any_method
, super
);
386 cname
= fullname
.substr(clazz
.name
.length() + 1);
387 num_params
= any_method
->getNumParams();
389 print_method_header(is_static(clazz
, any_method
), cname
, num_params
);
391 for (it
= methods
.begin(); it
!= methods
.end(); ++it
)
392 print_method_overload(clazz
, *it
);
395 /* Print part of the constructor for this isl_class.
397 * In particular, check if the actual arguments correspond to the
398 * formal arguments of "cons" and if so call "cons" and put the
399 * result in self.ptr and a reference to the default context in self.ctx.
401 * If the function consumes a reference, then we pass it a copy of
402 * the actual argument.
404 * If the function takes a string argument, the python string is first
405 * encoded as a byte sequence, using 'ascii' as encoding. This assumes
406 * that all strings passed to isl can be converted to 'ascii'.
408 void python_generator::print_constructor(const isl_class
&clazz
,
411 string fullname
= cons
->getName();
412 string cname
= fullname
.substr(clazz
.name
.length() + 1);
413 int num_params
= cons
->getNumParams();
414 int drop_ctx
= first_arg_is_isl_ctx(cons
);
416 printf(" if len(args) == %d", num_params
- drop_ctx
);
417 for (int i
= drop_ctx
; i
< num_params
; ++i
) {
418 ParmVarDecl
*param
= cons
->getParamDecl(i
);
419 QualType type
= param
->getOriginalType();
420 if (is_isl_type(type
)) {
422 s
= type2python(extract_type(type
));
423 printf(" and args[%d].__class__ is %s",
424 i
- drop_ctx
, s
.c_str());
425 } else if (type
->isPointerType()) {
426 printf(" and type(args[%d]) == str", i
- drop_ctx
);
428 printf(" and type(args[%d]) == int", i
- drop_ctx
);
432 printf(" self.ctx = Context.getDefaultInstance()\n");
433 printf(" self.ptr = isl.%s(", fullname
.c_str());
436 for (int i
= drop_ctx
; i
< num_params
; ++i
) {
437 ParmVarDecl
*param
= cons
->getParamDecl(i
);
438 QualType type
= param
->getOriginalType();
441 if (is_isl_type(type
)) {
444 type
= extract_type(param
->getOriginalType());
445 printf("isl.%s_copy(args[%d].ptr)",
446 type
.c_str(), i
- drop_ctx
);
448 printf("args[%d].ptr", i
- drop_ctx
);
449 } else if (is_string(type
)) {
450 printf("args[%d].encode('ascii')", i
- drop_ctx
);
452 printf("args[%d]", i
- drop_ctx
);
459 /* Print the header of the class "name" with superclasses "super".
460 * The order of the superclasses is the opposite of the order
461 * in which the corresponding annotations appear in the source code.
463 void python_generator::print_class_header(const isl_class
&clazz
,
464 const string
&name
, const vector
<string
> &super
)
466 printf("class %s", name
.c_str());
467 if (super
.size() > 0) {
469 for (unsigned i
= 0; i
< super
.size(); ++i
) {
472 printf("%s", type2python(super
[i
]).c_str());
481 /* Tell ctypes about the return type of "fd".
482 * In particular, if "fd" returns a pointer to an isl object,
483 * then tell ctypes it returns a "c_void_p".
484 * Similarly, if "fd" returns an isl_bool,
485 * then tell ctypes it returns a "c_bool".
486 * If "fd" returns a char *, then simply tell ctypes.
488 void python_generator::print_restype(FunctionDecl
*fd
)
490 string fullname
= fd
->getName();
491 QualType type
= fd
->getReturnType();
492 if (is_isl_type(type
))
493 printf("isl.%s.restype = c_void_p\n", fullname
.c_str());
494 else if (is_isl_bool(type
))
495 printf("isl.%s.restype = c_bool\n", fullname
.c_str());
496 else if (is_string(type
))
497 printf("isl.%s.restype = POINTER(c_char)\n", fullname
.c_str());
500 /* Tell ctypes about the types of the arguments of the function "fd".
502 void python_generator::print_argtypes(FunctionDecl
*fd
)
504 string fullname
= fd
->getName();
505 int n
= fd
->getNumParams();
508 printf("isl.%s.argtypes = [", fullname
.c_str());
509 for (int i
= 0; i
< n
- drop_user
; ++i
) {
510 ParmVarDecl
*param
= fd
->getParamDecl(i
);
511 QualType type
= param
->getOriginalType();
512 if (is_callback(type
))
516 if (is_isl_ctx(type
))
518 else if (is_isl_type(type
) || is_callback(type
))
520 else if (is_string(type
))
526 printf(", c_void_p");
530 /* Print type definitions for the method 'fd'.
532 void python_generator::print_method_type(FunctionDecl
*fd
)
538 /* Print declarations for methods printing the class representation,
539 * provided there is a corresponding *_to_str function.
541 * In particular, provide an implementation of __str__ and __repr__ methods to
542 * override the default representation used by python. Python uses __str__ to
543 * pretty print the class (e.g., when calling print(obj)) and uses __repr__
544 * when printing a precise representation of an object (e.g., when dumping it
545 * in the REPL console).
547 * Check the type of the argument before calling the *_to_str function
548 * on it in case the method was called on an object from a subclass.
550 * The return value of the *_to_str function is decoded to a python string
551 * assuming an 'ascii' encoding. This is necessary for python 3 compatibility.
553 void python_generator::print_representation(const isl_class
&clazz
,
554 const string
&python_name
)
556 if (!clazz
.fn_to_str
)
559 printf(" def __str__(arg0):\n");
560 print_type_check(python_name
, 0, false, "", "", -1);
561 printf(" ptr = isl.%s(arg0.ptr)\n",
562 string(clazz
.fn_to_str
->getName()).c_str());
563 printf(" res = cast(ptr, c_char_p).value.decode('ascii')\n");
564 printf(" libc.free(ptr)\n");
565 printf(" return res\n");
566 printf(" def __repr__(self):\n");
567 printf(" s = str(self)\n");
568 printf(" if '\"' in s:\n");
569 printf(" return 'isl.%s(\"\"\"%%s\"\"\")' %% s\n",
570 python_name
.c_str());
572 printf(" return 'isl.%s(\"%%s\")' %% s\n",
573 python_name
.c_str());
576 /* Print code to set method type signatures.
578 * To be able to call C functions it is necessary to explicitly set their
579 * argument and result types. Do this for all exported constructors and
580 * methods, as well as for the *_to_str method, if it exists.
581 * Assuming each exported class has a *_copy and a *_free method,
582 * also unconditionally set the type of such methods.
584 void python_generator::print_method_types(const isl_class
&clazz
)
586 set
<FunctionDecl
*>::const_iterator in
;
587 map
<string
, set
<FunctionDecl
*> >::const_iterator it
;
589 for (in
= clazz
.constructors
.begin(); in
!= clazz
.constructors
.end();
591 print_method_type(*in
);
593 for (it
= clazz
.methods
.begin(); it
!= clazz
.methods
.end(); ++it
)
594 for (in
= it
->second
.begin(); in
!= it
->second
.end(); ++in
)
595 print_method_type(*in
);
597 print_method_type(clazz
.fn_copy
);
598 print_method_type(clazz
.fn_free
);
600 print_method_type(clazz
.fn_to_str
);
603 /* Print out the definition of this isl_class.
605 * We first check if this isl_class is a subclass of one or more other classes.
606 * If it is, we make sure those superclasses are printed out first.
608 * Then we print a constructor with several cases, one for constructing
609 * a Python object from a return value and one for each function that
610 * was marked as a constructor.
612 * Next, we print out some common methods and the methods corresponding
613 * to functions that are not marked as constructors.
615 * Finally, we tell ctypes about the types of the arguments of the
616 * constructor functions and the return types of those function returning
619 void python_generator::print(const isl_class
&clazz
)
621 string p_name
= type2python(clazz
.name
);
622 set
<FunctionDecl
*>::const_iterator in
;
623 map
<string
, set
<FunctionDecl
*> >::const_iterator it
;
624 vector
<string
> super
= find_superclasses(clazz
.type
);
626 for (unsigned i
= 0; i
< super
.size(); ++i
)
627 if (done
.find(super
[i
]) == done
.end())
628 print(classes
[super
[i
]]);
629 done
.insert(clazz
.name
);
632 print_class_header(clazz
, p_name
, super
);
633 printf(" def __init__(self, *args, **keywords):\n");
635 printf(" if \"ptr\" in keywords:\n");
636 printf(" self.ctx = keywords[\"ctx\"]\n");
637 printf(" self.ptr = keywords[\"ptr\"]\n");
640 for (in
= clazz
.constructors
.begin(); in
!= clazz
.constructors
.end();
642 print_constructor(clazz
, *in
);
643 printf(" raise Error\n");
644 printf(" def __del__(self):\n");
645 printf(" if hasattr(self, 'ptr'):\n");
646 printf(" isl.%s_free(self.ptr)\n", clazz
.name
.c_str());
648 print_representation(clazz
, p_name
);
650 for (it
= clazz
.methods
.begin(); it
!= clazz
.methods
.end(); ++it
)
651 print_method(clazz
, it
->first
, it
->second
, super
);
655 print_method_types(clazz
);
658 /* Generate a python interface based on the extracted types and
661 * Print out each class in turn. If one of these is a subclass of some
662 * other class, make sure the superclass is printed out first.
665 void python_generator::generate()
667 map
<string
, isl_class
>::iterator ci
;
669 for (ci
= classes
.begin(); ci
!= classes
.end(); ++ci
) {
670 if (done
.find(ci
->first
) == done
.end())