2 * Copyright 2011 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
37 #include "extract_interface.h"
40 /* Is the given type declaration marked as being a subtype of some other
41 * type? If so, return that other type in "super".
43 static bool is_subclass(RecordDecl
*decl
, string
&super
)
45 if (!decl
->hasAttrs())
48 string sub
= "isl_subclass";
49 size_t len
= sub
.length();
50 AttrVec attrs
= decl
->getAttrs();
51 for (AttrVec::const_iterator i
= attrs
.begin() ; i
!= attrs
.end(); ++i
) {
52 const AnnotateAttr
*ann
= dyn_cast
<AnnotateAttr
>(*i
);
55 string s
= ann
->getAnnotation().str();
56 if (s
.substr(0, len
) == sub
) {
57 super
= s
.substr(len
+ 1, s
.length() - len
- 2);
65 /* Is decl marked as a constructor?
67 static bool is_constructor(Decl
*decl
)
69 return has_annotation(decl
, "isl_constructor");
72 /* Is decl marked as consuming a reference?
74 static bool takes(Decl
*decl
)
76 return has_annotation(decl
, "isl_take");
79 /* isl_class collects all constructors and methods for an isl "class".
80 * "name" is the name of the class.
81 * "type" is the declaration that introduces the type.
86 set
<FunctionDecl
*> constructors
;
87 set
<FunctionDecl
*> methods
;
89 void print(map
<string
, isl_class
> &classes
, set
<string
> &done
);
90 void print_constructor(FunctionDecl
*method
);
91 void print_method(FunctionDecl
*method
, bool subclass
, string super
);
94 /* Return the class that has a name that matches the initial part
95 * of the namd of function "fd".
97 static isl_class
&method2class(map
<string
, isl_class
> &classes
,
101 map
<string
, isl_class
>::iterator ci
;
102 string name
= fd
->getNameAsString();
104 for (ci
= classes
.begin(); ci
!= classes
.end(); ++ci
) {
105 if (name
.substr(0, ci
->first
.length()) == ci
->first
)
109 return classes
[best
];
112 /* Is "type" the type "isl_ctx *"?
114 static bool is_isl_ctx(QualType type
)
116 if (!type
->isPointerType())
118 type
= type
->getPointeeType();
119 if (type
.getAsString() != "isl_ctx")
125 /* Is the first argument of "fd" of type "isl_ctx *"?
127 static bool first_arg_is_isl_ctx(FunctionDecl
*fd
)
131 if (fd
->getNumParams() < 1)
134 param
= fd
->getParamDecl(0);
135 return is_isl_ctx(param
->getOriginalType());
138 /* Is "type" that of a pointer to an isl_* structure?
140 static bool is_isl_type(QualType type
)
142 if (type
->isPointerType()) {
143 string s
= type
->getPointeeType().getAsString();
144 return s
.substr(0, 4) == "isl_";
150 /* Is "type" that of a pointer to a function?
152 static bool is_callback(QualType type
)
154 if (!type
->isPointerType())
156 type
= type
->getPointeeType();
157 return type
->isFunctionType();
160 /* Is "type" that of "char *" of "const char *"?
162 static bool is_string(QualType type
)
164 if (type
->isPointerType()) {
165 string s
= type
->getPointeeType().getAsString();
166 return s
== "const char" || s
== "char";
172 /* Return the name of the type that "type" points to.
173 * The input "type" is assumed to be a pointer type.
175 static string
extract_type(QualType type
)
177 if (type
->isPointerType())
178 return type
->getPointeeType().getAsString();
182 /* Drop the "isl_" initial part of the type name "name".
184 static string
type2python(string name
)
186 return name
.substr(4);
189 /* Construct a wrapper for a callback argument (at position "arg").
190 * Assign the wrapper to "cb". We assume here that a function call
191 * has at most one callback argument.
193 * The wrapper converts the arguments of the callback to python types.
194 * If any exception is thrown, the wrapper keeps track of it in exc_info[0]
195 * and returns -1. Otherwise the wrapper returns 0.
197 static void print_callback(QualType type
, int arg
)
199 const FunctionProtoType
*fn
= type
->getAs
<FunctionProtoType
>();
200 unsigned n_arg
= fn
->getNumArgs();
202 printf(" exc_info = [None]\n");
203 printf(" fn = CFUNCTYPE(c_int");
204 for (int i
= 0; i
< n_arg
- 1; ++i
) {
205 QualType arg_type
= fn
->getArgType(i
);
206 assert(is_isl_type(arg_type
));
207 printf(", c_void_p");
209 printf(", c_void_p)\n");
210 printf(" def cb_func(");
211 for (int i
= 0; i
< n_arg
; ++i
) {
214 printf("cb_arg%d", i
);
217 for (int i
= 0; i
< n_arg
- 1; ++i
) {
219 arg_type
= type2python(extract_type(fn
->getArgType(i
)));
220 printf(" cb_arg%d = %s(ctx=self.ctx, ptr=cb_arg%d)\n",
221 i
, arg_type
.c_str(), i
);
224 printf(" arg%d(", arg
);
225 for (int i
= 0; i
< n_arg
- 1; ++i
) {
228 printf("cb_arg%d", i
);
231 printf(" except:\n");
232 printf(" import sys\n");
233 printf(" exc_info[0] = sys.exc_info()\n");
234 printf(" return -1\n");
235 printf(" return 0\n");
236 printf(" cb = fn(cb_func)\n");
239 /* Print a python method corresponding to the C function "method".
240 * "subclass" is set if the method belongs to a class that is a subclass
241 * of some other class ("super").
243 * If the function has a callback argument, then it also has a "user"
244 * argument. Since Python has closures, there is no need for such
245 * a user argument in the Python interface, so we simply drop it.
246 * We also create a wrapper ("cb") for the callback.
248 * If the function has additional arguments that refer to isl structures,
249 * then we check if the actual arguments are of the right type.
250 * If not, we try to convert it to the right type.
251 * It that doesn't work and if subclass is set, we try to convert self
252 * to the type of the superclass and call the corresponding method.
254 * If the function consumes a reference, then we pass it a copy of
255 * the actual argument.
257 void isl_class::print_method(FunctionDecl
*method
, bool subclass
, string super
)
259 string fullname
= method
->getName();
260 string cname
= fullname
.substr(name
.length() + 1);
261 int num_params
= method
->getNumParams();
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 printf(" def %s(self", cname
.c_str());
272 for (int i
= 1; i
< num_params
- drop_user
; ++i
)
273 printf(", arg%d", i
);
276 for (int i
= 1; i
< num_params
; ++i
) {
277 ParmVarDecl
*param
= method
->getParamDecl(i
);
279 if (!is_isl_type(param
->getOriginalType()))
281 type
= type2python(extract_type(param
->getOriginalType()));
283 printf(" if not arg%d.__class__ is %s:\n",
285 printf(" arg%d = %s(arg%d)\n",
287 printf(" except:\n");
289 printf(" return %s(self).%s(",
290 type2python(super
).c_str(), cname
.c_str());
291 for (int i
= 1; i
< num_params
- drop_user
; ++i
) {
300 for (int i
= 1; i
< num_params
; ++i
) {
301 ParmVarDecl
*param
= method
->getParamDecl(i
);
302 QualType type
= param
->getOriginalType();
303 if (!is_callback(type
))
305 print_callback(type
->getPointeeType(), i
);
307 printf(" res = isl.%s(", fullname
.c_str());
308 if (takes(method
->getParamDecl(0)))
309 printf("isl.%s_copy(self.ptr)", name
.c_str());
312 for (int i
= 1; i
< num_params
- drop_user
; ++i
) {
313 ParmVarDecl
*param
= method
->getParamDecl(i
);
314 QualType type
= param
->getOriginalType();
315 if (is_callback(type
))
317 else if (takes(param
)) {
318 string type_s
= extract_type(type
);
319 printf(", isl.%s_copy(arg%d.ptr)", type_s
.c_str(), i
);
321 printf(", arg%d.ptr", i
);
327 if (is_isl_type(method
->getResultType())) {
329 type
= type2python(extract_type(method
->getResultType()));
330 printf(" return %s(ctx=self.ctx, ptr=res)\n",
334 printf(" if exc_info[0] != None:\n");
335 printf(" raise exc_info[0][0], "
336 "exc_info[0][1], exc_info[0][2]\n");
338 printf(" return res\n");
342 /* Print part of the constructor for this isl_class.
344 * In particular, check if the actual arguments correspond to the
345 * formal arguments of "cons" and if so call "cons" and put the
346 * result in self.ptr and a reference to the default context in self.ctx.
348 * If the function consumes a reference, then we pass it a copy of
349 * the actual argument.
351 void isl_class::print_constructor(FunctionDecl
*cons
)
353 string fullname
= cons
->getName();
354 string cname
= fullname
.substr(name
.length() + 1);
355 int num_params
= cons
->getNumParams();
356 int drop_ctx
= first_arg_is_isl_ctx(cons
);
358 printf(" if len(args) == %d", num_params
- drop_ctx
);
359 for (int i
= drop_ctx
; i
< num_params
; ++i
) {
360 ParmVarDecl
*param
= cons
->getParamDecl(i
);
361 if (is_isl_type(param
->getOriginalType())) {
363 type
= extract_type(param
->getOriginalType());
364 type
= type2python(type
);
365 printf(" and args[%d].__class__ is %s",
366 i
- drop_ctx
, type
.c_str());
368 printf(" and type(args[%d]) == str", i
- drop_ctx
);
371 printf(" self.ctx = Context.getDefaultInstance()\n");
372 printf(" self.ptr = isl.%s(", fullname
.c_str());
375 for (int i
= drop_ctx
; i
< num_params
; ++i
) {
376 ParmVarDecl
*param
= cons
->getParamDecl(i
);
379 if (is_isl_type(param
->getOriginalType())) {
382 type
= extract_type(param
->getOriginalType());
383 printf("isl.%s_copy(args[%d].ptr)",
384 type
.c_str(), i
- drop_ctx
);
386 printf("args[%d].ptr", i
- drop_ctx
);
388 printf("args[%d]", i
- drop_ctx
);
394 /* Print out the definition of this isl_class.
396 * We first check if this isl_class is a subclass of some other class.
397 * If it is, we make sure the superclass is printed out first.
399 * Then we print a constructor with several cases, one for constructing
400 * a Python object from a return value and one for each function that
401 * was marked as a constructor.
403 * Next, we print out some common methods and the methods corresponding
404 * to functions that are not marked as constructors.
406 * Finally, we tell ctypes about the types of the arguments of the
407 * constructor functions and the return types of those function returning
410 void isl_class::print(map
<string
, isl_class
> &classes
, set
<string
> &done
)
413 string p_name
= type2python(name
);
414 set
<FunctionDecl
*>::iterator in
;
415 bool subclass
= is_subclass(type
, super
);
417 if (subclass
&& done
.find(super
) == done
.end())
418 classes
[super
].print(classes
, done
);
422 printf("class %s", p_name
.c_str());
424 printf("(%s)", type2python(super
).c_str());
426 printf(" def __init__(self, *args, **keywords):\n");
428 printf(" if \"ptr\" in keywords:\n");
429 printf(" self.ctx = keywords[\"ctx\"]\n");
430 printf(" self.ptr = keywords[\"ptr\"]\n");
433 for (in
= constructors
.begin(); in
!= constructors
.end(); ++in
)
434 print_constructor(*in
);
435 printf(" raise Error\n");
436 printf(" def __del__(self):\n");
437 printf(" if hasattr(self, 'ptr'):\n");
438 printf(" isl.%s_free(self.ptr)\n", name
.c_str());
439 printf(" def __str__(self):\n");
440 printf(" ptr = isl.%s_to_str(self.ptr)\n", name
.c_str());
441 printf(" res = str(cast(ptr, c_char_p).value)\n");
442 printf(" libc.free(ptr)\n");
443 printf(" return res\n");
444 printf(" def __repr__(self):\n");
445 printf(" return 'isl.%s(\"%%s\")' %% str(self)\n", p_name
.c_str());
447 for (in
= methods
.begin(); in
!= methods
.end(); ++in
)
448 print_method(*in
, subclass
, super
);
451 for (in
= constructors
.begin(); in
!= constructors
.end(); ++in
) {
452 string fullname
= (*in
)->getName();
453 printf("isl.%s.restype = c_void_p\n", fullname
.c_str());
454 printf("isl.%s.argtypes = [", fullname
.c_str());
455 for (int i
= 0; i
< (*in
)->getNumParams(); ++i
) {
456 ParmVarDecl
*param
= (*in
)->getParamDecl(i
);
457 QualType type
= param
->getOriginalType();
460 if (is_isl_ctx(type
))
462 else if (is_isl_type(type
))
464 else if (is_string(type
))
471 for (in
= methods
.begin(); in
!= methods
.end(); ++in
) {
472 string fullname
= (*in
)->getName();
473 if (is_isl_type((*in
)->getResultType()))
474 printf("isl.%s.restype = c_void_p\n", fullname
.c_str());
476 printf("isl.%s_free.argtypes = [c_void_p]\n", name
.c_str());
477 printf("isl.%s_to_str.argtypes = [c_void_p]\n", name
.c_str());
478 printf("isl.%s_to_str.restype = POINTER(c_char)\n", name
.c_str());
481 /* Generate a python interface based on the extracted types and functions.
482 * We first collect all functions that belong to a certain type,
483 * separating constructors from regular methods.
485 * Then we print out each class in turn. If one of these is a subclass
486 * of some other class, it will make sure the superclass is printed out first.
488 void generate_python(set
<RecordDecl
*> &types
, set
<FunctionDecl
*> functions
)
490 map
<string
, isl_class
> classes
;
491 map
<string
, isl_class
>::iterator ci
;
494 set
<RecordDecl
*>::iterator it
;
495 for (it
= types
.begin(); it
!= types
.end(); ++it
) {
496 RecordDecl
*decl
= *it
;
497 string name
= decl
->getName();
498 classes
[name
].name
= name
;
499 classes
[name
].type
= decl
;
502 set
<FunctionDecl
*>::iterator in
;
503 for (in
= functions
.begin(); in
!= functions
.end(); ++in
) {
504 isl_class
&c
= method2class(classes
, *in
);
505 if (is_constructor(*in
))
506 c
.constructors
.insert(*in
);
508 c
.methods
.insert(*in
);
511 for (ci
= classes
.begin(); ci
!= classes
.end(); ++ci
) {
512 if (done
.find(ci
->first
) == done
.end())
513 ci
->second
.print(classes
, done
);