48a54b64306ac6bf7d5c84d72bb1fdfc59d14b8f
[yosys.git] / misc / py_wrap_generator.py
1 #
2 # yosys -- Yosys Open SYnthesis Suite
3 #
4 # Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 #
6 # Permission to use, copy, modify, and/or distribute this software for any
7 # purpose with or without fee is hereby granted, provided that the above
8 # copyright notice and this permission notice appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #
18 # Author Benedikt Tutzer
19 #
20
21 import copy
22
23 #Map c++ operator Syntax to Python functions
24 wrappable_operators = {
25 "<" : "__lt__",
26 "==": "__eq__",
27 "!=": "__ne__",
28 "+" : "__add__",
29 "-" : "__sub__",
30 "*" : "__mul__",
31 "/" : "__div__",
32 "()": "__call__"
33 }
34
35 #Restrict certain strings from being function names in Python
36 keyword_aliases = {
37 "in" : "in_",
38 "False" : "False_",
39 "None" : "None_",
40 "True" : "True_",
41 "and" : "and_",
42 "as" : "as_",
43 "assert" : "assert_",
44 "break" : "break_",
45 "class" : "class_",
46 "continue" : "continue_",
47 "def" : "def_",
48 "del" : "del_",
49 "elif" : "elif_",
50 "else" : "else_",
51 "except" : "except_",
52 "for" : "for_",
53 "from" : "from_",
54 "global" : "global_",
55 "if" : "if_",
56 "import" : "import_",
57 "in" : "in_",
58 "is" : "is_",
59 "lambda" : "lambda_",
60 "nonlocal" : "nonlocal_",
61 "not" : "not_",
62 "or" : "or_",
63 "pass" : "pass_",
64 "raise" : "raise_",
65 "return" : "return_",
66 "try" : "try_",
67 "while" : "while_",
68 "with" : "with_",
69 "yield" : "yield_"
70 }
71
72 #These can be used without any explicit conversion
73 primitive_types = ["void", "bool", "int", "double", "size_t", "std::string",
74 "string", "State", "char_p"]
75
76 from enum import Enum
77
78 #Ways to link between Python- and C++ Objects
79 class link_types(Enum):
80 global_list = 1 #Manage a global list of objects in C++, the Python
81 #object contains a key to find the corresponding C++
82 #object and a Pointer to the object to verify it is
83 #still the same, making collisions unlikely to happen
84 ref_copy = 2 #The Python object contains a copy of the C++ object.
85 #The C++ object is deleted when the Python object gets
86 #deleted
87 pointer = 3 #The Python Object contains a pointer to it's C++
88 #counterpart
89 derive = 4 #The Python-Wrapper is derived from the C++ object.
90
91 class attr_types(Enum):
92 star = "*"
93 amp = "&"
94 ampamp = "&&"
95 default = ""
96
97 #For source-files
98 class Source:
99 name = ""
100 classes = []
101
102 def __init__(self, name, classes):
103 self.name = name
104 self.classes = classes
105
106 #Splits a list by the given delimiter, without splitting strings inside
107 #pointy-brackets (< and >)
108 def split_list(str_def, delim):
109 str_def = str_def.strip()
110 if len(str_def) == 0:
111 return []
112 if str_def.count(delim) == 0:
113 return [str_def]
114 if str_def.count("<") == 0:
115 return str_def.split(delim)
116 if str_def.find("<") < str_def.find(" "):
117 closing = find_closing(str_def[str_def.find("<")+1:], "<", ">") + str_def.find("<")
118 comma = str_def[closing:].find(delim)
119 if comma == -1:
120 return [str_def]
121 comma = closing + comma
122 else:
123 comma = str_def.find(delim)
124 rest = split_list(str_def[comma+1:], delim)
125 ret = [str_def[:comma]]
126 if rest != None and len(rest) != 0:
127 ret.extend(rest)
128 return ret
129
130 #Represents a Type
131 class WType:
132 name = ""
133 cont = None
134 attr_type = attr_types.default
135
136 def __init__(self, name = "", cont = None, attr_type = attr_types.default):
137 self.name = name
138 self.cont = cont
139 self.attr_type = attr_type
140
141 #Python type-string
142 def gen_text(self):
143 text = self.name
144 if self.name in enum_names:
145 text = enum_by_name(self.name).namespace + "::" + self.name
146 if self.cont != None:
147 return known_containers[self.name].typename
148 return text
149
150 #C++ type-string
151 def gen_text_cpp(self):
152 postfix = ""
153 if self.attr_type == attr_types.star:
154 postfix = "*"
155 if self.name in primitive_types:
156 return self.name + postfix
157 if self.name in enum_names:
158 return enum_by_name(self.name).namespace + "::" + self.name + postfix
159 if self.name in classnames:
160 return class_by_name(self.name).namespace + "::" + self.name + postfix
161 text = self.name
162 if self.cont != None:
163 text += "<"
164 for a in self.cont.args:
165 text += a.gen_text_cpp() + ", "
166 text = text[:-2]
167 text += ">"
168 return text
169
170 @staticmethod
171 def from_string(str_def, containing_file, line_number):
172 str_def = str_def.strip()
173 if len(str_def) == 0:
174 return None
175 str_def = str_def.replace("RTLIL::SigSig", "std::pair<SigSpec, SigSpec>").replace("SigSig", "std::pair<SigSpec, SigSpec>")
176 t = WType()
177 t.name = ""
178 t.cont = None
179 t.attr_type = attr_types.default
180 if str_def.find("<") != -1:# and str_def.find("<") < str_def.find(" "):
181 candidate = WContainer.from_string(str_def, containing_file, line_number)
182 if candidate == None:
183 return None
184 t.name = str_def[:str_def.find("<")]
185
186 if t.name.count("*") + t.name.count("&") > 1:
187 return None
188
189 if t.name.count("*") == 1 or str_def[0] == '*' or str_def[-1] == '*':
190 t.attr_type = attr_types.star
191 t.name = t.name.replace("*","")
192 elif t.name.count("&&") == 1:
193 t.attr_type = attr_types.ampamp
194 t.name = t.name.replace("&&","")
195 elif t.name.count("&") == 1 or str_def[0] == '&' or str_def[-1] == '&':
196 t.attr_type = attr_types.amp
197 t.name = t.name.replace("&","")
198
199 t.cont = candidate
200 if(t.name not in known_containers):
201 return None
202 return t
203
204 prefix = ""
205
206 if str.startswith(str_def, "unsigned "):
207 prefix = "unsigned "
208 str_def = str_def[9:]
209 while str.startswith(str_def, "long "):
210 prefix= "long " + prefix
211 str_def = str_def[5:]
212 while str.startswith(str_def, "short "):
213 prefix = "short " + prefix
214 str_def = str_def[6:]
215
216 str_def = str_def.split("::")[-1]
217
218 if str_def.count("*") + str_def.count("&") >= 2:
219 return None
220
221 if str_def.count("*") == 1:
222 t.attr_type = attr_types.star
223 str_def = str_def.replace("*","")
224 elif str_def.count("&&") == 1:
225 t.attr_type = attr_types.ampamp
226 str_def = str_def.replace("&&","")
227 elif str_def.count("&") == 1:
228 t.attr_type = attr_types.amp
229 str_def = str_def.replace("&","")
230
231 if len(str_def) > 0 and str_def.split("::")[-1] not in primitive_types and str_def.split("::")[-1] not in classnames and str_def.split("::")[-1] not in enum_names:
232 return None
233
234 if str_def.count(" ") == 0:
235 t.name = (prefix + str_def).replace("char_p", "char *")
236 t.cont = None
237 return t
238 return None
239
240 #Represents a container-type
241 class WContainer:
242 name = ""
243 args = []
244
245 def from_string(str_def, containing_file, line_number):
246 if str_def == None or len(str_def) < 4:
247 return None
248 cont = WContainer()
249 cont.name = str_def[:str_def.find("<")]
250 str_def = str_def[str_def.find("<")+1:find_closing(str_def, "<", ">")]
251 cont.args = []
252 for arg in split_list(str_def, ","):
253 candidate = WType.from_string(arg.strip(), containing_file, line_number)
254 if candidate == None:
255 return None
256 cont.args.append(candidate)
257 return cont
258
259 #Translators between Python and C++ containers
260 #Base Type
261 class Translator:
262 tmp_cntr = 0
263 typename = "DefaultType"
264 orig_name = "DefaultCpp"
265
266 @classmethod
267 def gen_type(c, types):
268 return "\nImplement a function that outputs the c++ type of this container here\n"
269
270 @classmethod
271 def translate(c, varname, types, prefix):
272 return "\nImplement a function translating a python container to a c++ container here\n"
273
274 @classmethod
275 def translate_cpp(c, varname, types, prefix, ref):
276 return "\nImplement a function translating a c++ container to a python container here\n"
277
278 #Translates list-types (vector, pool, set), that only differ in their name and
279 #the name of the insertion function
280 class PythonListTranslator(Translator):
281 typename = "boost::python::list"
282 insert_name = "Default"
283
284 #generate the c++ type string
285 @classmethod
286 def gen_type(c, types):
287 text = c.orig_name + "<"
288 if types[0].name in primitive_types:
289 text += types[0].name
290 elif types[0].name in known_containers:
291 text += known_containers[types[0].name].gen_type(types[0].cont.args)
292 else:
293 text += class_by_name(types[0].name).namespace + "::" + types[0].name
294 if types[0].attr_type == attr_types.star:
295 text += "*"
296 text += ">"
297 return text
298
299 #Generate C++ code to translate from a boost::python::list
300 @classmethod
301 def translate(c, varname, types, prefix):
302 text = prefix + c.gen_type(types) + " " + varname + "___tmp;"
303 cntr_name = "cntr_" + str(Translator.tmp_cntr)
304 Translator.tmp_cntr = Translator.tmp_cntr + 1
305 text += prefix + "for(int " + cntr_name + " = 0; " + cntr_name + " < len(" + varname + "); " + cntr_name + "++)"
306 text += prefix + "{"
307 tmp_name = "tmp_" + str(Translator.tmp_cntr)
308 Translator.tmp_cntr = Translator.tmp_cntr + 1
309 if types[0].name in known_containers:
310 text += prefix + "\t" + known_containers[types[0].name].typename + " " + tmp_name + " = boost::python::extract<" + known_containers[types[0].name].typename + ">(" + varname + "[" + cntr_name + "]);"
311 text += known_containers[types[0].name].translate(tmp_name, types[0].cont.args, prefix+"\t")
312 tmp_name = tmp_name + "___tmp"
313 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(" + tmp_name + ");"
314 elif types[0].name in classnames:
315 text += prefix + "\t" + types[0].name + "* " + tmp_name + " = boost::python::extract<" + types[0].name + "*>(" + varname + "[" + cntr_name + "]);"
316 if types[0].attr_type == attr_types.star:
317 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(" + tmp_name + "->get_cpp_obj());"
318 else:
319 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(*" + tmp_name + "->get_cpp_obj());"
320 else:
321 text += prefix + "\t" + types[0].name + " " + tmp_name + " = boost::python::extract<" + types[0].name + ">(" + varname + "[" + cntr_name + "]);"
322 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(" + tmp_name + ");"
323 text += prefix + "}"
324 return text
325
326 #Generate C++ code to translate to a boost::python::list
327 @classmethod
328 def translate_cpp(c, varname, types, prefix, ref):
329 text = prefix + c.typename + " " + varname + "___tmp;"
330 tmp_name = "tmp_" + str(Translator.tmp_cntr)
331 Translator.tmp_cntr = Translator.tmp_cntr + 1
332 if ref:
333 text += prefix + "for(auto " + tmp_name + " : *" + varname + ")"
334 else:
335 text += prefix + "for(auto " + tmp_name + " : " + varname + ")"
336 text += prefix + "{"
337 if types[0].name in classnames:
338 if types[0].attr_type == attr_types.star:
339 text += prefix + "\t" + varname + "___tmp.append(" + types[0].name + "::get_py_obj(" + tmp_name + "));"
340 else:
341 text += prefix + "\t" + varname + "___tmp.append(*" + types[0].name + "::get_py_obj(&" + tmp_name + "));"
342 elif types[0].name in known_containers:
343 text += known_containers[types[0].name].translate_cpp(tmp_name, types[0].cont.args, prefix + "\t", types[0].attr_type == attr_types.star)
344 text += prefix + "\t" + varname + "___tmp.append(" + tmp_name + "___tmp);"
345 else:
346 text += prefix + "\t" + varname + "___tmp.append(" + tmp_name + ");"
347 text += prefix + "}"
348 return text
349
350 #Sub-type for std::set
351 class SetTranslator(PythonListTranslator):
352 insert_name = "insert"
353 orig_name = "std::set"
354
355 #Sub-type for std::vector
356 class VectorTranslator(PythonListTranslator):
357 insert_name = "push_back"
358 orig_name = "std::vector"
359
360 #Sub-type for pool
361 class PoolTranslator(PythonListTranslator):
362 insert_name = "insert"
363 orig_name = "pool"
364
365 #Translates dict-types (dict, std::map), that only differ in their name and
366 #the name of the insertion function
367 class PythonDictTranslator(Translator):
368 typename = "boost::python::dict"
369 insert_name = "Default"
370
371 @classmethod
372 def gen_type(c, types):
373 text = c.orig_name + "<"
374 if types[0].name in primitive_types:
375 text += types[0].name
376 elif types[0].name in known_containers:
377 text += known_containers[types[0].name].gen_type(types[0].cont.args)
378 else:
379 text += class_by_name(types[0].name).namespace + "::" + types[0].name
380 if types[0].attr_type == attr_types.star:
381 text += "*"
382 text += ", "
383 if types[1].name in primitive_types:
384 text += types[1].name
385 elif types[1].name in known_containers:
386 text += known_containers[types[1].name].gen_type(types[1].cont.args)
387 else:
388 text += class_by_name(types[1].name).namespace + "::" + types[1].name
389 if types[1].attr_type == attr_types.star:
390 text += "*"
391 text += ">"
392 return text
393
394 #Generate c++ code to translate from a boost::python::dict
395 @classmethod
396 def translate(c, varname, types, prefix):
397 text = prefix + c.gen_type(types) + " " + varname + "___tmp;"
398 text += prefix + "boost::python::list " + varname + "_keylist = " + varname + ".keys();"
399 cntr_name = "cntr_" + str(Translator.tmp_cntr)
400 Translator.tmp_cntr = Translator.tmp_cntr + 1
401 text += prefix + "for(int " + cntr_name + " = 0; " + cntr_name + " < len(" + varname + "_keylist); " + cntr_name + "++)"
402 text += prefix + "{"
403 key_tmp_name = "key_tmp_" + str(Translator.tmp_cntr)
404 val_tmp_name = "val_tmp_" + str(Translator.tmp_cntr)
405 Translator.tmp_cntr = Translator.tmp_cntr + 1
406
407 if types[0].name in known_containers:
408 text += prefix + "\t" + known_containers[types[0].name].typename + " " + key_tmp_name + " = boost::python::extract<" + known_containers[types[0].name].typename + ">(" + varname + "_keylist[ " + cntr_name + " ]);"
409 text += known_containers[types[0].name].translate(key_tmp_name, types[0].cont.args, prefix+"\t")
410 key_tmp_name = key_tmp_name + "___tmp"
411 elif types[0].name in classnames:
412 text += prefix + "\t" + types[0].name + "* " + key_tmp_name + " = boost::python::extract<" + types[0].name + "*>(" + varname + "_keylist[ " + cntr_name + " ]);"
413 else:
414 text += prefix + "\t" + types[0].name + " " + key_tmp_name + " = boost::python::extract<" + types[0].name + ">(" + varname + "_keylist[ " + cntr_name + " ]);"
415
416 if types[1].name in known_containers:
417 text += prefix + "\t" + known_containers[types[1].name].typename + " " + val_tmp_name + " = boost::python::extract<" + known_containers[types[1].name].typename + ">(" + varname + "[" + varname + "_keylist[ " + cntr_name + " ]]);"
418 text += known_containers[types[1].name].translate(val_tmp_name, types[1].cont.args, prefix+"\t")
419 val_tmp_name = val_tmp_name + "___tmp"
420 elif types[1].name in classnames:
421 text += prefix + "\t" + types[1].name + "* " + val_tmp_name + " = boost::python::extract<" + types[1].name + "*>(" + varname + "[" + varname + "_keylist[ " + cntr_name + " ]]);"
422 else:
423 text += prefix + "\t" + types[1].name + " " + val_tmp_name + " = boost::python::extract<" + types[1].name + ">(" + varname + "[" + varname + "_keylist[ " + cntr_name + " ]]);"
424
425 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(std::pair<" + types[0].gen_text_cpp() + ", " + types[1].gen_text_cpp() + ">("
426
427 if types[0].name not in classnames:
428 text += key_tmp_name
429 else:
430 if types[0].attr_type != attr_types.star:
431 text += "*"
432 text += key_tmp_name + "->get_cpp_obj()"
433
434 text += ", "
435 if types[1].name not in classnames:
436 text += val_tmp_name
437 else:
438 if types[1].attr_type != attr_types.star:
439 text += "*"
440 text += val_tmp_name + "->get_cpp_obj()"
441 text += "));\n" + prefix + "}"
442 return text
443
444 #Generate c++ code to translate to a boost::python::dict
445 @classmethod
446 def translate_cpp(c, varname, types, prefix, ref):
447 text = prefix + c.typename + " " + varname + "___tmp;"
448 tmp_name = "tmp_" + str(Translator.tmp_cntr)
449 Translator.tmp_cntr = Translator.tmp_cntr + 1
450 if ref:
451 text += prefix + "for(auto " + tmp_name + " : *" + varname + ")"
452 else:
453 text += prefix + "for(auto " + tmp_name + " : " + varname + ")"
454 text += prefix + "{"
455 if types[1].name in known_containers:
456 text += prefix + "\tauto " + tmp_name + "_second = " + tmp_name + ".second;"
457 text += known_containers[types[1].name].translate_cpp(tmp_name + "_second", types[1].cont.args, prefix + "\t", types[1].attr_type == attr_types.star)
458
459 if types[0].name in classnames:
460 text += prefix + "\t" + varname + "___tmp[" + types[0].name + "::get_py_obj(" + tmp_name + ".first)] = "
461 elif types[0].name not in known_containers:
462 text += prefix + "\t" + varname + "___tmp[" + tmp_name + ".first] = "
463
464 if types[1].name in classnames:
465 if types[1].attr_type == attr_types.star:
466 text += types[1].name + "::get_py_obj(" + tmp_name + ".second);"
467 else:
468 text += "*" + types[1].name + "::get_py_obj(&" + tmp_name + ".second);"
469 elif types[1].name in known_containers:
470 text += tmp_name + "_second___tmp;"
471 else:
472 text += tmp_name + ".second;"
473 text += prefix + "}"
474 return text
475
476 #Sub-type for dict
477 class DictTranslator(PythonDictTranslator):
478 insert_name = "insert"
479 orig_name = "dict"
480
481 #Sub_type for std::map
482 class MapTranslator(PythonDictTranslator):
483 insert_name = "insert"
484 orig_name = "std::map"
485
486 #Translator for std::pair. Derived from PythonDictTranslator because the
487 #gen_type function is the same (because both have two template parameters)
488 class TupleTranslator(PythonDictTranslator):
489 typename = "boost::python::tuple"
490 orig_name = "std::pair"
491
492 #Generate c++ code to translate from a boost::python::tuple
493 @classmethod
494 def translate(c, varname, types, prefix):
495 text = prefix + types[0].name + " " + varname + "___tmp_0 = boost::python::extract<" + types[0].name + ">(" + varname + "[0]);"
496 text += prefix + types[1].name + " " + varname + "___tmp_1 = boost::python::extract<" + types[1].name + ">(" + varname + "[1]);"
497 text += prefix + TupleTranslator.gen_type(types) + " " + varname + "___tmp("
498 if types[0].name.split(" ")[-1] in primitive_types:
499 text += varname + "___tmp_0, "
500 else:
501 text += varname + "___tmp_0.get_cpp_obj(), "
502 if types[1].name.split(" ")[-1] in primitive_types:
503 text += varname + "___tmp_1);"
504 else:
505 text += varname + "___tmp_1.get_cpp_obj());"
506 return text
507
508 #Generate c++ code to translate to a boost::python::tuple
509 @classmethod
510 def translate_cpp(c, varname, types, prefix, ref):
511 # if the tuple is a pair of SigSpecs (aka SigSig), then we need
512 # to call get_py_obj() on each item in the tuple
513 if types[0].name in classnames:
514 first_var = types[0].name + "::get_py_obj(" + varname + ".first)"
515 else:
516 first_var = varname + ".first"
517 if types[1].name in classnames:
518 second_var = types[1].name + "::get_py_obj(" + varname + ".second)"
519 else:
520 second_var = varname + ".second"
521 text = prefix + TupleTranslator.typename + " " + varname + "___tmp = boost::python::make_tuple(" + first_var + ", " + second_var + ");"
522 return text
523
524 #Associate the Translators with their c++ type
525 known_containers = {
526 "std::set" : SetTranslator,
527 "std::vector" : VectorTranslator,
528 "pool" : PoolTranslator,
529 "dict" : DictTranslator,
530 "std::pair" : TupleTranslator,
531 "std::map" : MapTranslator
532 }
533
534 class Attribute:
535 wtype = None
536 varname = None
537 is_const = False
538 default_value = None
539 pos = None
540 pos_counter = 0
541
542 def __init__(self, wtype, varname, is_const = False, default_value = None):
543 self.wtype = wtype
544 self.varname = varname
545 self.is_const = is_const
546 self.default_value = None
547 self.container = None
548
549 @staticmethod
550 def from_string(str_def, containing_file, line_number):
551 if len(str_def) < 3:
552 return None
553 orig = str_def
554 arg = Attribute(None, None)
555 prefix = ""
556 arg.wtype = None
557 arg.varname = None
558 arg.is_const = False
559 arg.default_value = None
560 arg.container = None
561 if str.startswith(str_def, "const "):
562 arg.is_const = True
563 str_def = str_def[6:]
564 if str.startswith(str_def, "unsigned "):
565 prefix = "unsigned "
566 str_def = str_def[9:]
567 while str.startswith(str_def, "long "):
568 prefix= "long " + prefix
569 str_def = str_def[5:]
570 while str.startswith(str_def, "short "):
571 prefix = "short " + prefix
572 str_def = str_def[6:]
573
574 if str_def.find("<") != -1 and str_def.find("<") < str_def.find(" "):
575 closing = find_closing(str_def[str_def.find("<"):], "<", ">") + str_def.find("<") + 1
576 arg.wtype = WType.from_string(str_def[:closing].strip(), containing_file, line_number)
577 str_def = str_def[closing+1:]
578 else:
579 if str_def.count(" ") > 0:
580 arg.wtype = WType.from_string(prefix + str_def[:str_def.find(" ")].strip(), containing_file, line_number)
581 str_def = str_def[str_def.find(" ")+1:]
582 else:
583 arg.wtype = WType.from_string(prefix + str_def.strip(), containing_file, line_number)
584 str_def = ""
585 arg.varname = ""
586
587 if arg.wtype == None:
588 return None
589 if str_def.count("=") == 0:
590 arg.varname = str_def.strip()
591 if arg.varname.find(" ") > 0:
592 return None
593 else:
594 arg.varname = str_def[:str_def.find("=")].strip()
595 if arg.varname.find(" ") > 0:
596 return None
597 str_def = str_def[str_def.find("=")+1:].strip()
598 arg.default_value = str_def[arg.varname.find("=")+1:].strip()
599 if len(arg.varname) == 0:
600 arg.varname = None
601 return arg
602 if arg.varname[0] == '*':
603 arg.wtype.attr_type = attr_types.star
604 arg.varname = arg.varname[1:]
605 elif arg.varname[0] == '&':
606 if arg.wtype.attr_type != attr_types.default:
607 return None
608 if arg.varname[1] == '&':
609 arg.wtype.attr_type = attr_types.ampamp
610 arg.varname = arg.varname[2:]
611 else:
612 arg.wtype.attr_type = attr_types.amp
613 arg.varname = arg.varname[1:]
614 return arg
615
616 #Generates the varname. If the attribute has no name in the header file,
617 #a name is generated
618 def gen_varname(self):
619 if self.varname != None:
620 return self.varname
621 if self.wtype.name == "void":
622 return ""
623 if self.pos == None:
624 self.pos = Attribute.pos_counter
625 Attribute.pos_counter = Attribute.pos_counter + 1
626 return "gen_varname_" + str(self.pos)
627
628 #Generates the text for the function headers with wrapper types
629 def gen_listitem(self):
630 prefix = ""
631 if self.is_const:
632 prefix = "const "
633 if self.wtype.name in classnames:
634 return prefix + self.wtype.name + "* " + self.gen_varname()
635 if self.wtype.name in known_containers:
636 return prefix + known_containers[self.wtype.name].typename + " " + self.gen_varname()
637 return prefix + self.wtype.name + " " + self.gen_varname()
638
639 #Generates the test for the function headers with c++ types
640 def gen_listitem_cpp(self):
641 prefix = ""
642 if self.is_const:
643 prefix = "const "
644 infix = ""
645 if self.wtype.attr_type == attr_types.star:
646 infix = "*"
647 elif self.wtype.attr_type == attr_types.amp:
648 infix = "&"
649 elif self.wtype.attr_type == attr_types.ampamp:
650 infix = "&&"
651 if self.wtype.name in known_containers:
652 return prefix + known_containers[self.wtype.name].gen_type(self.wtype.cont.args) + " " + infix + self.gen_varname()
653 if self.wtype.name in classnames:
654 return prefix + class_by_name(self.wtype.name).namespace + "::" + self.wtype.name + " " + infix + self.gen_varname()
655 return prefix + self.wtype.name + " " + infix + self.gen_varname()
656
657 #Generates the listitem withtout the varname, so the signature can be
658 #compared
659 def gen_listitem_hash(self):
660 prefix = ""
661 if self.is_const:
662 prefix = "const "
663 if self.wtype.name in classnames:
664 return prefix + self.wtype.name + "* "
665 if self.wtype.name in known_containers:
666 return known_containers[self.wtype.name].typename
667 return prefix + self.wtype.name
668
669 #Generate Translation code for the attribute
670 def gen_translation(self):
671 if self.wtype.name in known_containers:
672 return known_containers[self.wtype.name].translate(self.gen_varname(), self.wtype.cont.args, "\n\t\t")
673 return ""
674
675 #Generate Translation code from c++ for the attribute
676 def gen_translation_cpp(self):
677 if self.wtype.name in known_containers:
678 return known_containers[self.wtype.name].translate_cpp(self.gen_varname(), self.wtype.cont.args, "\n\t\t", self.wtype.attr_type == attr_types.star)
679 return ""
680
681 #Generate Text for the call
682 def gen_call(self):
683 ret = self.gen_varname()
684 if self.wtype.name in known_containers:
685 if self.wtype.attr_type == attr_types.star:
686 return "&" + ret + "___tmp"
687 return ret + "___tmp"
688 if self.wtype.name in classnames:
689 if self.wtype.attr_type != attr_types.star:
690 ret = "*" + ret
691 return ret + "->get_cpp_obj()"
692 if self.wtype.name == "char *" and self.gen_varname() in ["format", "fmt"]:
693 return "\"%s\", " + self.gen_varname()
694 if self.wtype.attr_type == attr_types.star:
695 return "&" + ret
696 return ret
697
698 def gen_call_cpp(self):
699 ret = self.gen_varname()
700 if self.wtype.name.split(" ")[-1] in primitive_types or self.wtype.name in enum_names:
701 if self.wtype.attr_type == attr_types.star:
702 return "&" + ret
703 return ret
704 if self.wtype.name not in classnames:
705 if self.wtype.attr_type == attr_types.star:
706 return "&" + ret + "___tmp"
707 return ret + "___tmp"
708 if self.wtype.attr_type != attr_types.star:
709 ret = "*" + ret
710 return self.wtype.name + "::get_py_obj(" + self.gen_varname() + ")"
711
712 #Generate cleanup code
713 def gen_cleanup(self):
714 if self.wtype.name in primitive_types or self.wtype.name in classnames or self.wtype.name in enum_names or not self.wtype.attr_type == attr_types.star or (self.wtype.name in known_containers and self.wtype.attr_type == attr_types.star):
715 return ""
716 return "\n\t\tdelete " + self.gen_varname() + "___tmp;"
717
718 class WClass:
719 name = None
720 namespace = None
721 link_type = None
722 id_ = None
723 string_id = None
724 hash_id = None
725 needs_clone = False
726 found_funs = []
727 found_vars = []
728 found_constrs = []
729
730 def __init__(self, name, link_type, id_, string_id = None, hash_id = None, needs_clone = False):
731 self.name = name
732 self.namespace = None
733 self.link_type = link_type
734 self.id_ = id_
735 self.string_id = string_id
736 self.hash_id = hash_id
737 self.needs_clone = needs_clone
738 self.found_funs = []
739 self.found_vars = []
740 self.found_constrs = []
741
742 def printable_constrs(self):
743 ret = 0
744 for con in self.found_constrs:
745 if not con.protected:
746 ret += 1
747 return ret
748
749 def gen_decl(self, filename):
750 long_name = self.namespace + "::" + self.name
751
752 text = "\n\t// WRAPPED from " + filename
753 text += "\n\tstruct " + self.name
754 if self.link_type == link_types.derive:
755 text += " : public " + self.namespace + "::" + self.name
756 text += "\n\t{\n"
757
758 if self.link_type != link_types.derive:
759
760 text += "\t\t" + long_name + "* ref_obj;\n"
761
762 if self.link_type == link_types.ref_copy or self.link_type == link_types.pointer:
763 text += "\n\t\t" + long_name + "* get_cpp_obj() const\n\t\t{\n\t\t\treturn ref_obj;\n\t\t}\n"
764 elif self.link_type == link_types.global_list:
765 text += "\t\t" + self.id_.wtype.name + " " + self.id_.varname + ";\n"
766 text += "\n\t\t" + long_name + "* get_cpp_obj() const\n\t\t{"
767 text += "\n\t\t\t" + long_name + "* ret = " + long_name + "::get_all_" + self.name.lower() + "s()->at(this->" + self.id_.varname + ");"
768 text += "\n\t\t\tif(ret != NULL && ret == this->ref_obj)"
769 text += "\n\t\t\t\treturn ret;"
770 text += "\n\t\t\tthrow std::runtime_error(\"" + self.name + "'s c++ object does not exist anymore.\");"
771 text += "\n\t\t\treturn NULL;"
772 text += "\n\t\t}\n"
773
774 #if self.link_type != link_types.pointer:
775 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + "* ref)\n\t\t{"
776 text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
777 if self.link_type == link_types.pointer:
778 text += "\n\t\t\tret->ref_obj = ref;"
779 if self.link_type == link_types.ref_copy:
780 if self.needs_clone:
781 text += "\n\t\t\tret->ref_obj = ref->clone();"
782 else:
783 text += "\n\t\t\tret->ref_obj = new "+long_name+"(*ref);"
784 if self.link_type == link_types.global_list:
785 text += "\n\t\t\tret->ref_obj = ref;"
786 text += "\n\t\t\tret->" + self.id_.varname + " = ret->ref_obj->" + self.id_.varname + ";"
787 text += "\n\t\t\treturn ret;"
788 text += "\n\t\t}\n"
789
790 if self.link_type == link_types.ref_copy:
791 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + " ref)\n\t\t{"
792 text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
793 if self.needs_clone:
794 text += "\n\t\t\tret->ref_obj = ref.clone();"
795 else:
796 text += "\n\t\t\tret->ref_obj = new "+long_name+"(ref);"
797 text += "\n\t\t\treturn ret;"
798 text += "\n\t\t}\n"
799
800 for con in self.found_constrs:
801 text += con.gen_decl()
802 for var in self.found_vars:
803 text += var.gen_decl()
804 for fun in self.found_funs:
805 text += fun.gen_decl()
806
807
808 if self.link_type == link_types.derive:
809 duplicates = {}
810 for fun in self.found_funs:
811 if fun.name in duplicates:
812 fun.gen_alias()
813 duplicates[fun.name].gen_alias()
814 else:
815 duplicates[fun.name] = fun
816
817 text += "\n\t\t" + long_name + "* get_cpp_obj() const\n\t\t{\n\t\t\treturn (" + self.namespace + "::" + self.name +"*)this;\n\t\t}\n"
818 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + "* ref)\n\t\t{"
819 text += "\n\t\t\treturn (" + self.name + "*)ref;"
820 text += "\n\t\t}\n"
821
822 for con in self.found_constrs:
823 text += con.gen_decl_derive()
824 for var in self.found_vars:
825 text += var.gen_decl()
826 for fun in self.found_funs:
827 text += fun.gen_decl_virtual()
828
829 if self.hash_id != None:
830 text += "\n\t\tunsigned int get_hash_py()"
831 text += "\n\t\t{"
832 text += "\n\t\t\treturn get_cpp_obj()->" + self.hash_id + ";"
833 text += "\n\t\t}"
834
835 text += "\n\t};\n"
836
837 if self.link_type == link_types.derive:
838 text += "\n\tstruct " + self.name + "Wrap : " + self.name + ", boost::python::wrapper<" + self.name + ">"
839 text += "\n\t{"
840
841 for con in self.found_constrs:
842 text += con.gen_decl_wrapperclass()
843 for fun in self.found_funs:
844 text += fun.gen_default_impl()
845
846 text += "\n\t};"
847
848 text += "\n\tstd::ostream &operator<<(std::ostream &ostr, const " + self.name + " &ref)"
849 text += "\n\t{"
850 text += "\n\t\tostr << \"" + self.name
851 if self.string_id != None:
852 text +=" \\\"\""
853 text += " << ref.get_cpp_obj()->" + self.string_id
854 text += " << \"\\\"\""
855 else:
856 text += " at \" << ref.get_cpp_obj()"
857 text += ";"
858 text += "\n\t\treturn ostr;"
859 text += "\n\t}"
860 text += "\n"
861
862 return text
863
864 def gen_funs(self, filename):
865 text = ""
866 if self.link_type != link_types.derive:
867 for con in self.found_constrs:
868 text += con.gen_def()
869 for var in self.found_vars:
870 text += var.gen_def()
871 for fun in self.found_funs:
872 text += fun.gen_def()
873 else:
874 for var in self.found_vars:
875 text += var.gen_def()
876 for fun in self.found_funs:
877 text += fun.gen_def_virtual()
878 return text
879
880 def gen_boost_py(self):
881 text = "\n\t\tclass_<" + self.name
882 if self.link_type == link_types.derive:
883 text += "Wrap, boost::noncopyable"
884 text += ">(\"" + self.name + "\""
885 if self.printable_constrs() == 0 or not self.contains_default_constr():
886 text += ", no_init"
887 text += ")"
888 text += "\n\t\t\t.def(boost::python::self_ns::str(boost::python::self_ns::self))"
889 text += "\n\t\t\t.def(boost::python::self_ns::repr(boost::python::self_ns::self))"
890 for con in self.found_constrs:
891 text += con.gen_boost_py()
892 for var in self.found_vars:
893 text += var.gen_boost_py()
894 static_funs = []
895 for fun in self.found_funs:
896 text += fun.gen_boost_py()
897 if fun.is_static and fun.alias not in static_funs:
898 static_funs.append(fun.alias)
899 for fun in static_funs:
900 text += "\n\t\t\t.staticmethod(\"" + fun + "\")"
901
902 if self.hash_id != None:
903 text += "\n\t\t\t.def(\"__hash__\", &" + self.name + "::get_hash_py)"
904 text += "\n\t\t\t;\n"
905 return text
906
907 def contains_default_constr(self):
908 for c in self.found_constrs:
909 if len(c.args) == 0:
910 return True
911 return False
912
913 #CONFIGURE HEADER-FILES TO BE PARSED AND CLASSES EXPECTED IN THEM HERE
914
915 sources = [
916 Source("kernel/celltypes",[
917 WClass("CellType", link_types.pointer, None, None, "type.hash()", True),
918 WClass("CellTypes", link_types.pointer, None, None, None, True)
919 ]
920 ),
921 Source("kernel/consteval",[
922 WClass("ConstEval", link_types.pointer, None, None, None, True)
923 ]
924 ),
925 Source("kernel/log",[]),
926 Source("kernel/register",[
927 WClass("Pass", link_types.derive, None, None, None, True),
928 ]
929 ),
930 Source("kernel/rtlil",[
931 WClass("IdString", link_types.ref_copy, None, "str()", "hash()"),
932 WClass("Const", link_types.ref_copy, None, "as_string()", "hash()"),
933 WClass("AttrObject", link_types.ref_copy, None, None, None),
934 WClass("Selection", link_types.ref_copy, None, None, None),
935 WClass("Monitor", link_types.derive, None, None, None),
936 WClass("CaseRule",link_types.ref_copy, None, None, None, True),
937 WClass("SwitchRule",link_types.ref_copy, None, None, None, True),
938 WClass("SyncRule", link_types.ref_copy, None, None, None, True),
939 WClass("Process", link_types.ref_copy, None, "name.c_str()", "name.hash()"),
940 WClass("SigChunk", link_types.ref_copy, None, None, None),
941 WClass("SigBit", link_types.ref_copy, None, None, "hash()"),
942 WClass("SigSpec", link_types.ref_copy, None, None, "hash()"),
943 WClass("Cell", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
944 WClass("Wire", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
945 WClass("Memory", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
946 WClass("Module", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
947 WClass("Design", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "hashidx_", "hash()")
948 ]
949 ),
950 #Source("kernel/satgen",[
951 # ]
952 # ),
953 #Source("libs/ezsat/ezsat",[
954 # ]
955 # ),
956 #Source("libs/ezsat/ezminisat",[
957 # ]
958 # ),
959 Source("kernel/sigtools",[
960 WClass("SigMap", link_types.pointer, None, None, None, True)
961 ]
962 ),
963 Source("kernel/yosys",[
964 ]
965 ),
966 Source("kernel/cost",[])
967 ]
968
969 blacklist_methods = ["YOSYS_NAMESPACE::Pass::run_register", "YOSYS_NAMESPACE::Module::Pow", "YOSYS_NAMESPACE::Module::Bu0", "YOSYS_NAMESPACE::CaseRule::optimize"]
970
971 enum_names = ["State","SyncType","ConstFlags"]
972
973 enums = [] #Do not edit
974
975 unowned_functions = []
976
977 classnames = []
978 for source in sources:
979 for wclass in source.classes:
980 classnames.append(wclass.name)
981
982 def class_by_name(name):
983 for source in sources:
984 for wclass in source.classes:
985 if wclass.name == name:
986 return wclass
987 return None
988
989 def enum_by_name(name):
990 for e in enums:
991 if e.name == name:
992 return e
993 return None
994
995 def find_closing(text, open_tok, close_tok):
996 if text.find(open_tok) == -1 or text.find(close_tok) <= text.find(open_tok):
997 return text.find(close_tok)
998 return text.find(close_tok) + find_closing(text[text.find(close_tok)+1:], open_tok, close_tok) + 1
999
1000 def unpretty_string(s):
1001 s = s.strip()
1002 while s.find(" ") != -1:
1003 s = s.replace(" "," ")
1004 while s.find("\t") != -1:
1005 s = s.replace("\t"," ")
1006 s = s.replace(" (","(")
1007 return s
1008
1009 class WEnum:
1010 name = None
1011 namespace = None
1012 values = []
1013
1014 def from_string(str_def, namespace, line_number):
1015 str_def = str_def.strip()
1016 if not str.startswith(str_def, "enum "):
1017 return None
1018 if str_def.count(";") != 1:
1019 return None
1020 str_def = str_def[5:]
1021 enum = WEnum()
1022 split = str_def.split(":")
1023 if(len(split) != 2):
1024 return None
1025 enum.name = split[0].strip()
1026 if enum.name not in enum_names:
1027 return None
1028 str_def = split[1]
1029 if str_def.count("{") != str_def.count("}") != 1:
1030 return None
1031 if len(str_def) < str_def.find("}")+2 or str_def[str_def.find("}")+1] != ';':
1032 return None
1033 str_def = str_def.split("{")[-1].split("}")[0]
1034 enum.values = []
1035 for val in str_def.split(','):
1036 enum.values.append(val.strip().split('=')[0].strip())
1037 enum.namespace = namespace
1038 return enum
1039
1040 def gen_boost_py(self):
1041 text = "\n\t\tenum_<" + self.namespace + "::" + self.name + ">(\"" + self.name + "\")\n"
1042 for value in self.values:
1043 text += "\t\t\t.value(\"" + value + "\"," + self.namespace + "::" + value + ")\n"
1044 text += "\t\t\t;\n"
1045 return text
1046
1047 def __str__(self):
1048 ret = "Enum " + self.namespace + "::" + self.name + "(\n"
1049 for val in self.values:
1050 ret = ret + "\t" + val + "\n"
1051 return ret + ")"
1052
1053 def __repr__(self):
1054 return __str__(self)
1055
1056 class WConstructor:
1057 orig_text = None
1058 args = []
1059 containing_file = None
1060 member_of = None
1061 duplicate = False
1062 protected = False
1063
1064 def __init__(self, containing_file, class_):
1065 self.orig_text = "Auto generated default constructor"
1066 self.args = []
1067 self.containing_file = containing_file
1068 self.member_of = class_
1069 self.protected = False
1070
1071 def from_string(str_def, containing_file, class_, line_number, protected = False):
1072 if class_ == None:
1073 return None
1074 if str_def.count("delete;") > 0:
1075 return None
1076 con = WConstructor(containing_file, class_)
1077 con.orig_text = str_def
1078 con.args = []
1079 con.duplicate = False
1080 con.protected = protected
1081 if not str.startswith(str_def, class_.name + "("):
1082 return None
1083 str_def = str_def[len(class_.name)+1:]
1084 found = find_closing(str_def, "(", ")")
1085 if found == -1:
1086 return None
1087 str_def = str_def[0:found].strip()
1088 if len(str_def) == 0:
1089 return con
1090 for arg in split_list(str_def, ","):
1091 parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
1092 if parsed == None:
1093 return None
1094 con.args.append(parsed)
1095 return con
1096
1097 def gen_decl(self):
1098 if self.duplicate or self.protected:
1099 return ""
1100 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1101 text += "\n\t\t" + self.member_of.name + "("
1102 for arg in self.args:
1103 text += arg.gen_listitem() + ", "
1104 if len(self.args) > 0:
1105 text = text[:-2]
1106 text += ");\n"
1107 return text
1108
1109 def gen_decl_derive(self):
1110 if self.duplicate or self.protected:
1111 return ""
1112 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1113 text += "\n\t\t" + self.member_of.name + "("
1114 for arg in self.args:
1115 text += arg.gen_listitem() + ", "
1116 if len(self.args) > 0:
1117 text = text[:-2]
1118 text += ")"
1119 if len(self.args) == 0:
1120 return text + "{}"
1121 text += " : "
1122 text += self.member_of.namespace + "::" + self.member_of.name + "("
1123 for arg in self.args:
1124 text += arg.gen_call() + ", "
1125 if len(self.args) > 0:
1126 text = text[:-2]
1127 text += "){}\n"
1128 return text
1129
1130 def gen_decl_wrapperclass(self):
1131 if self.duplicate or self.protected:
1132 return ""
1133 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1134 text += "\n\t\t" + self.member_of.name + "Wrap("
1135 for arg in self.args:
1136 text += arg.gen_listitem() + ", "
1137 if len(self.args) > 0:
1138 text = text[:-2]
1139 text += ")"
1140 if len(self.args) == 0:
1141 return text + "{}"
1142 text += " : "
1143 text += self.member_of.name + "("
1144 for arg in self.args:
1145 text += arg.gen_call() + ", "
1146 if len(self.args) > 0:
1147 text = text[:-2]
1148 text += "){}\n"
1149 return text
1150
1151 def gen_decl_hash_py(self):
1152 text = self.member_of.name + "("
1153 for arg in self.args:
1154 text += arg.gen_listitem_hash() + ", "
1155 if len(self.args) > 0:
1156 text = text[:-2]
1157 text += ");"
1158 return text
1159
1160 def gen_def(self):
1161 if self.duplicate or self.protected:
1162 return ""
1163 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1164 text += "\n\t" + self.member_of.name + "::" + self.member_of.name + "("
1165 for arg in self.args:
1166 text += arg.gen_listitem() + ", "
1167 if len(self.args) > 0:
1168 text = text[:-2]
1169 text +=")\n\t{"
1170 for arg in self.args:
1171 text += arg.gen_translation()
1172 if self.member_of.link_type != link_types.derive:
1173 text += "\n\t\tthis->ref_obj = new " + self.member_of.namespace + "::" + self.member_of.name + "("
1174 for arg in self.args:
1175 text += arg.gen_call() + ", "
1176 if len(self.args) > 0:
1177 text = text[:-2]
1178 if self.member_of.link_type != link_types.derive:
1179 text += ");"
1180 if self.member_of.link_type == link_types.global_list:
1181 text += "\n\t\tthis->" + self.member_of.id_.varname + " = this->ref_obj->" + self.member_of.id_.varname + ";"
1182 for arg in self.args:
1183 text += arg.gen_cleanup()
1184 text += "\n\t}\n"
1185 return text
1186
1187 def gen_boost_py(self):
1188 if self.duplicate or self.protected or len(self.args) == 0:
1189 return ""
1190 text = "\n\t\t\t.def(init"
1191 text += "<"
1192 for a in self.args:
1193 text += a.gen_listitem_hash() + ", "
1194 text = text[0:-2] + ">())"
1195 return text
1196
1197 class WFunction:
1198 orig_text = None
1199 is_static = False
1200 is_inline = False
1201 is_virtual = False
1202 ret_attr_type = attr_types.default
1203 is_operator = False
1204 ret_type = None
1205 name = None
1206 alias = None
1207 args = []
1208 containing_file = None
1209 member_of = None
1210 duplicate = False
1211 namespace = ""
1212
1213 def from_string(str_def, containing_file, class_, line_number, namespace):
1214 if str_def.count("delete;") > 0:
1215 return None
1216 func = WFunction()
1217 func.is_static = False
1218 func.is_inline = False
1219 func.is_virtual = False
1220 func.ret_attr_type = attr_types.default
1221 func.is_operator = False
1222 func.member_of = None
1223 func.orig_text = str_def
1224 func.args = []
1225 func.containing_file = containing_file
1226 func.member_of = class_
1227 func.duplicate = False
1228 func.namespace = namespace
1229 str_def = str_def.replace("operator ","operator")
1230 if str.startswith(str_def, "static "):
1231 func.is_static = True
1232 str_def = str_def[7:]
1233 else:
1234 func.is_static = False
1235 if str.startswith(str_def, "inline "):
1236 func.is_inline = True
1237 str_def = str_def[7:]
1238 else:
1239 func.is_inline = False
1240 if str.startswith(str_def, "virtual "):
1241 func.is_virtual = True
1242 str_def = str_def[8:]
1243 else:
1244 func.is_virtual = False
1245
1246 if str_def.count(" ") == 0:
1247 return None
1248
1249 parts = split_list(str_def.strip(), " ")
1250
1251 prefix = ""
1252 i = 0
1253 for part in parts:
1254 if part in ["unsigned", "long", "short"]:
1255 prefix += part + " "
1256 i += 1
1257 else:
1258 break
1259 parts = parts[i:]
1260
1261 if len(parts) <= 1:
1262 return None
1263
1264 func.ret_type = WType.from_string(prefix + parts[0], containing_file, line_number)
1265
1266 if func.ret_type == None:
1267 return None
1268
1269 str_def = parts[1]
1270 for part in parts[2:]:
1271 str_def = str_def + " " + part
1272
1273 found = str_def.find("(")
1274 if found == -1 or (str_def.find(" ") != -1 and found > str_def.find(" ")):
1275 return None
1276 func.name = str_def[:found]
1277 str_def = str_def[found:]
1278 if func.name.find("operator") != -1 and str.startswith(str_def, "()("):
1279 func.name += "()"
1280 str_def = str_def[2:]
1281 str_def = str_def[1:]
1282 if func.name.find("operator") != -1:
1283 func.is_operator = True
1284 if func.name.find("*") == 0:
1285 func.name = func.name.replace("*", "")
1286 func.ret_type.attr_type = attr_types.star
1287 if func.name.find("&&") == 0:
1288 func.name = func.name.replace("&&", "")
1289 func.ret_type.attr_type = attr_types.ampamp
1290 if func.name.find("&") == 0:
1291 func.name = func.name.replace("&", "")
1292 func.ret_type.attr_type = attr_types.amp
1293
1294 found = find_closing(str_def, "(", ")")
1295 if found == -1:
1296 return None
1297 str_def = str_def[0:found]
1298 if func.name in blacklist_methods:
1299 return None
1300 if func.namespace != None and func.namespace != "":
1301 if (func.namespace + "::" + func.name) in blacklist_methods:
1302 return None
1303 if func.member_of != None:
1304 if (func.namespace + "::" + func.member_of.name + "::" + func.name) in blacklist_methods:
1305 return None
1306 if func.is_operator and func.name.replace(" ","").replace("operator","").split("::")[-1] not in wrappable_operators:
1307 return None
1308
1309 testname = func.name
1310 if func.is_operator:
1311 testname = testname[:testname.find("operator")]
1312 if testname.count(")") != 0 or testname.count("(") != 0 or testname.count("~") != 0 or testname.count(";") != 0 or testname.count(">") != 0 or testname.count("<") != 0 or testname.count("throw") != 0:
1313 return None
1314
1315 func.alias = func.name
1316 if func.name in keyword_aliases:
1317 func.alias = keyword_aliases[func.name]
1318 str_def = str_def[:found].strip()
1319 if(len(str_def) == 0):
1320 return func
1321 for arg in split_list(str_def, ","):
1322 if arg.strip() == "...":
1323 continue
1324 parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
1325 if parsed == None:
1326 return None
1327 func.args.append(parsed)
1328 return func
1329
1330 def gen_alias(self):
1331 self.alias = self.name
1332 for arg in self.args:
1333 self.alias += "__" + arg.wtype.gen_text_cpp().replace("::", "_").replace("<","_").replace(">","_").replace(" ","").replace("*","").replace(",","")
1334
1335 def gen_decl(self):
1336 if self.duplicate:
1337 return ""
1338 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1339 text += "\n\t\t"
1340 if self.is_static:
1341 text += "static "
1342 text += self.ret_type.gen_text() + " " + self.alias + "("
1343 for arg in self.args:
1344 text += arg.gen_listitem()
1345 text += ", "
1346 if len(self.args) > 0:
1347 text = text[:-2]
1348 text += ");\n"
1349 return text
1350
1351 def gen_decl_virtual(self):
1352 if self.duplicate:
1353 return ""
1354 if not self.is_virtual:
1355 return self.gen_decl()
1356 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1357 text += "\n\t\tvirtual "
1358 if self.is_static:
1359 text += "static "
1360 text += self.ret_type.gen_text() + " py_" + self.alias + "("
1361 for arg in self.args:
1362 text += arg.gen_listitem()
1363 text += ", "
1364 if len(self.args) > 0:
1365 text = text[:-2]
1366 text += ")"
1367 if len(self.args) == 0:
1368 text += "{}"
1369 else:
1370 text += "\n\t\t{"
1371 for arg in self.args:
1372 text += "\n\t\t\t(void)" + arg.gen_varname() + ";"
1373 text += "\n\t\t}\n"
1374 text += "\n\t\tvirtual "
1375 if self.is_static:
1376 text += "static "
1377 text += self.ret_type.gen_text() + " " + self.name + "("
1378 for arg in self.args:
1379 text += arg.gen_listitem_cpp()
1380 text += ", "
1381 if len(self.args) > 0:
1382 text = text[:-2]
1383 text += ") YS_OVERRIDE;\n"
1384 return text
1385
1386 def gen_decl_hash_py(self):
1387 text = self.ret_type.gen_text() + " " + self.alias + "("
1388 for arg in self.args:
1389 text += arg.gen_listitem_hash() + ", "
1390 if len(self.args) > 0:
1391 text = text[:-2]
1392 text += ");"
1393 return text
1394
1395 def gen_def(self):
1396 if self.duplicate:
1397 return ""
1398 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1399 text += "\n\t" + self.ret_type.gen_text() + " "
1400 if self.member_of != None:
1401 text += self.member_of.name + "::"
1402 text += self.alias + "("
1403 for arg in self.args:
1404 text += arg.gen_listitem()
1405 text += ", "
1406 if len(self.args) > 0:
1407 text = text[:-2]
1408 text +=")\n\t{"
1409 for arg in self.args:
1410 text += arg.gen_translation()
1411 text += "\n\t\t"
1412 if self.ret_type.name != "void":
1413 if self.ret_type.name in known_containers:
1414 text += self.ret_type.gen_text_cpp()
1415 else:
1416 text += self.ret_type.gen_text()
1417 if self.ret_type.name in classnames or (self.ret_type.name in known_containers and self.ret_type.attr_type == attr_types.star):
1418 text += "*"
1419 text += " ret_ = "
1420 if self.ret_type.name in classnames:
1421 text += self.ret_type.name + "::get_py_obj("
1422 if self.member_of == None:
1423 text += "::" + self.namespace + "::" + self.alias + "("
1424 elif self.is_static:
1425 text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
1426 else:
1427 text += "this->get_cpp_obj()->" + self.name + "("
1428 for arg in self.args:
1429 text += arg.gen_call() + ", "
1430 if len(self.args) > 0:
1431 text = text[:-2]
1432 if self.ret_type.name in classnames:
1433 text += ")"
1434 text += ");"
1435 for arg in self.args:
1436 text += arg.gen_cleanup()
1437 if self.ret_type.name != "void":
1438 if self.ret_type.name in classnames:
1439 text += "\n\t\treturn *ret_;"
1440 elif self.ret_type.name in known_containers:
1441 text += known_containers[self.ret_type.name].translate_cpp("ret_", self.ret_type.cont.args, "\n\t\t", self.ret_type.attr_type == attr_types.star)
1442 text += "\n\t\treturn ret____tmp;"
1443 else:
1444 text += "\n\t\treturn ret_;"
1445 text += "\n\t}\n"
1446 return text
1447
1448 def gen_def_virtual(self):
1449 if self.duplicate:
1450 return ""
1451 if not self.is_virtual:
1452 return self.gen_def()
1453 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1454 text += "\n\t"
1455 if self.is_static:
1456 text += "static "
1457 text += self.ret_type.gen_text() + " " + self.member_of.name + "::" + self.name + "("
1458 for arg in self.args:
1459 text += arg.gen_listitem_cpp()
1460 text += ", "
1461 if len(self.args) > 0:
1462 text = text[:-2]
1463 text += ")\n\t{"
1464 for arg in self.args:
1465 text += arg.gen_translation_cpp()
1466 text += "\n\t\t"
1467 if self.member_of == None:
1468 text += "::" + self.namespace + "::" + self.alias + "("
1469 elif self.is_static:
1470 text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
1471 else:
1472 text += "py_" + self.alias + "("
1473 for arg in self.args:
1474 text += arg.gen_call_cpp() + ", "
1475 if len(self.args) > 0:
1476 text = text[:-2]
1477 if self.ret_type.name in classnames:
1478 text += ")"
1479 text += ");"
1480 for arg in self.args:
1481 text += arg.gen_cleanup()
1482 text += "\n\t}\n"
1483 return text
1484
1485 def gen_default_impl(self):
1486 if self.duplicate:
1487 return ""
1488 if not self.is_virtual:
1489 return ""
1490 text = "\n\n\t\t" + self.ret_type.gen_text() + " py_" + self.alias + "("
1491 for arg in self.args:
1492 text += arg.gen_listitem() + ", "
1493 if len(self.args) > 0:
1494 text = text[:-2]
1495
1496 call_string = "py_" + self.alias + "("
1497 for arg in self.args:
1498 call_string += arg.gen_varname() + ", "
1499 if len(self.args) > 0:
1500 call_string = call_string[0:-2]
1501 call_string += ");"
1502
1503 text += ")\n\t\t{"
1504 text += "\n\t\t\tif(boost::python::override py_" + self.alias + " = this->get_override(\"py_" + self.alias + "\"))"
1505 text += "\n\t\t\t\t" + call_string
1506 text += "\n\t\t\telse"
1507 text += "\n\t\t\t\t" + self.member_of.name + "::" + call_string
1508 text += "\n\t\t}"
1509
1510 text += "\n\n\t\t" + self.ret_type.gen_text() + " default_py_" + self.alias + "("
1511 for arg in self.args:
1512 text += arg.gen_listitem() + ", "
1513 if len(self.args) > 0:
1514 text = text[:-2]
1515 text += ")\n\t\t{"
1516 text += "\n\t\t\tthis->" + self.member_of.name + "::" + call_string
1517 text += "\n\t\t}"
1518 return text
1519
1520
1521 def gen_boost_py(self):
1522 if self.duplicate:
1523 return ""
1524 if self.member_of == None:
1525 text = "\n\t\tdef"
1526 else:
1527 text = "\n\t\t\t.def"
1528 if len(self.args) > -1:
1529 if self.ret_type.name in known_containers:
1530 text += "<" + known_containers[self.ret_type.name].typename + " "
1531 else:
1532 text += "<" + self.ret_type.name + " "
1533 if self.member_of == None or self.is_static:
1534 text += "(*)("
1535 else:
1536 text += "(" + self.member_of.name + "::*)("
1537 for a in self.args:
1538 text += a.gen_listitem_hash() + ", "
1539 if len(self.args) > 0:
1540 text = text[0:-2] + ")>"
1541 else:
1542 text += "void)>"
1543
1544 if self.is_operator:
1545 text += "(\"" + wrappable_operators[self.name.replace("operator","")] + "\""
1546 else:
1547 if self.member_of != None and self.member_of.link_type == link_types.derive and self.is_virtual:
1548 text += "(\"py_" + self.alias + "\""
1549 else:
1550 text += "(\"" + self.alias + "\""
1551 if self.member_of != None:
1552 text += ", &" + self.member_of.name + "::"
1553 if self.member_of.link_type == link_types.derive and self.is_virtual:
1554 text += "py_" + self.alias
1555 text += ", &" + self.member_of.name + "Wrap::default_py_" + self.alias
1556 else:
1557 text += self.alias
1558
1559 text += ")"
1560 else:
1561 text += ", " + "YOSYS_PYTHON::" + self.alias + ");"
1562 return text
1563
1564 class WMember:
1565 orig_text = None
1566 wtype = attr_types.default
1567 name = None
1568 containing_file = None
1569 member_of = None
1570 namespace = ""
1571 is_const = False
1572
1573 def from_string(str_def, containing_file, class_, line_number, namespace):
1574 member = WMember()
1575 member.orig_text = str_def
1576 member.wtype = None
1577 member.name = ""
1578 member.containing_file = containing_file
1579 member.member_of = class_
1580 member.namespace = namespace
1581 member.is_const = False
1582
1583 if str.startswith(str_def, "const "):
1584 member.is_const = True
1585 str_def = str_def[6:]
1586
1587 if str_def.count(" ") == 0:
1588 return None
1589
1590 parts = split_list(str_def.strip(), " ")
1591
1592 prefix = ""
1593 i = 0
1594 for part in parts:
1595 if part in ["unsigned", "long", "short"]:
1596 prefix += part + " "
1597 i += 1
1598 else:
1599 break
1600 parts = parts[i:]
1601
1602 if len(parts) <= 1:
1603 return None
1604
1605 member.wtype = WType.from_string(prefix + parts[0], containing_file, line_number)
1606
1607 if member.wtype == None:
1608 return None
1609
1610 str_def = parts[1]
1611 for part in parts[2:]:
1612 str_def = str_def + " " + part
1613
1614 if str_def.find("(") != -1 or str_def.find(")") != -1 or str_def.find("{") != -1 or str_def.find("}") != -1:
1615 return None
1616
1617 found = str_def.find(";")
1618 if found == -1:
1619 return None
1620
1621 found_eq = str_def.find("=")
1622 if found_eq != -1:
1623 found = found_eq
1624
1625 member.name = str_def[:found]
1626 str_def = str_def[found+1:]
1627 if member.name.find("*") == 0:
1628 member.name = member.name.replace("*", "")
1629 member.wtype.attr_type = attr_types.star
1630 if member.name.find("&&") == 0:
1631 member.name = member.name.replace("&&", "")
1632 member.wtype.attr_type = attr_types.ampamp
1633 if member.name.find("&") == 0:
1634 member.name = member.name.replace("&", "")
1635 member.wtype.attr_type = attr_types.amp
1636
1637 if(len(str_def.strip()) != 0):
1638 return None
1639
1640 if len(member.name.split(",")) > 1:
1641 member_list = []
1642 for name in member.name.split(","):
1643 name = name.strip();
1644 member_list.append(WMember())
1645 member_list[-1].orig_text = member.orig_text
1646 member_list[-1].wtype = member.wtype
1647 member_list[-1].name = name
1648 member_list[-1].containing_file = member.containing_file
1649 member_list[-1].member_of = member.member_of
1650 member_list[-1].namespace = member.namespace
1651 member_list[-1].is_const = member.is_const
1652 return member_list
1653
1654 return member
1655
1656 def gen_decl(self):
1657 text = "\n\t\t" + self.wtype.gen_text() + " get_var_py_" + self.name + "();\n"
1658 if self.is_const:
1659 return text
1660 if self.wtype.name in classnames:
1661 text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs);\n"
1662 else:
1663 text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs);\n"
1664 return text
1665
1666 def gen_def(self):
1667 text = "\n\t" + self.wtype.gen_text() + " " + self.member_of.name +"::get_var_py_" + self.name + "()"
1668 text += "\n\t{\n\t\t"
1669 if self.wtype.attr_type == attr_types.star:
1670 text += "if(this->get_cpp_obj()->" + self.name + " == NULL)\n\t\t\t"
1671 text += "throw std::runtime_error(\"Member \\\"" + self.name + "\\\" is NULL\");\n\t\t"
1672 if self.wtype.name in known_containers:
1673 text += self.wtype.gen_text_cpp()
1674 else:
1675 text += self.wtype.gen_text()
1676
1677 if self.wtype.name in classnames or (self.wtype.name in known_containers and self.wtype.attr_type == attr_types.star):
1678 text += "*"
1679 text += " ret_ = "
1680 if self.wtype.name in classnames:
1681 text += self.wtype.name + "::get_py_obj("
1682 if self.wtype.attr_type != attr_types.star:
1683 text += "&"
1684 text += "this->get_cpp_obj()->" + self.name
1685 if self.wtype.name in classnames:
1686 text += ")"
1687 text += ";"
1688
1689 if self.wtype.name in classnames:
1690 text += "\n\t\treturn *ret_;"
1691 elif self.wtype.name in known_containers:
1692 text += known_containers[self.wtype.name].translate_cpp("ret_", self.wtype.cont.args, "\n\t\t", self.wtype.attr_type == attr_types.star)
1693 text += "\n\t\treturn ret____tmp;"
1694 else:
1695 text += "\n\t\treturn ret_;"
1696 text += "\n\t}\n"
1697
1698 if self.is_const:
1699 return text
1700
1701 ret = Attribute(self.wtype, "rhs");
1702
1703 if self.wtype.name in classnames:
1704 text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs)"
1705 else:
1706 text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs)"
1707 text += "\n\t{"
1708 text += ret.gen_translation()
1709 text += "\n\t\tthis->get_cpp_obj()->" + self.name + " = " + ret.gen_call() + ";"
1710 text += "\n\t}\n"
1711
1712 return text;
1713
1714 def gen_boost_py(self):
1715 text = "\n\t\t\t.add_property(\"" + self.name + "\", &" + self.member_of.name + "::get_var_py_" + self.name
1716 if not self.is_const:
1717 text += ", &" + self.member_of.name + "::set_var_py_" + self.name
1718 text += ")"
1719 return text
1720
1721 def concat_namespace(tuple_list):
1722 if len(tuple_list) == 0:
1723 return ""
1724 ret = ""
1725 for namespace in tuple_list:
1726 ret += "::" + namespace[0]
1727 return ret[2:]
1728
1729 def calc_ident(text):
1730 if len(text) == 0 or text[0] != ' ':
1731 return 0
1732 return calc_ident(text[1:]) + 1
1733
1734 def assure_length(text, length, left = False):
1735 if len(text) > length:
1736 return text[:length]
1737 if left:
1738 return text + " "*(length - len(text))
1739 return " "*(length - len(text)) + text
1740
1741 def parse_header(source):
1742 debug("Parsing " + source.name + ".pyh",1)
1743 source_file = open(source.name + ".pyh", "r")
1744
1745 source_text = []
1746 in_line = source_file.readline()
1747
1748 namespaces = []
1749
1750 while(in_line):
1751 if(len(in_line)>1):
1752 source_text.append(in_line.replace("char *", "char_p ").replace("char* ", "char_p "))
1753 in_line = source_file.readline()
1754
1755 i = 0
1756
1757 namespaces = []
1758 class_ = None
1759 private_segment = False
1760
1761 while i < len(source_text):
1762 line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", " namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END"," }")
1763 ugly_line = unpretty_string(line)
1764
1765 if str.startswith(ugly_line, "namespace "):# and ugly_line.find("std") == -1 and ugly_line.find("__") == -1:
1766 namespace_name = ugly_line[10:].replace("{","").strip()
1767 namespaces.append((namespace_name, ugly_line.count("{")))
1768 debug("-----NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1769 i += 1
1770 continue
1771
1772 if len(namespaces) != 0:
1773 namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
1774 if namespaces[-1][1] == 0:
1775 debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1776 del namespaces[-1]
1777 i += 1
1778 continue
1779
1780 if class_ == None and (str.startswith(ugly_line, "struct ") or str.startswith(ugly_line, "class")) and ugly_line.count(";") == 0:
1781
1782 struct_name = ugly_line.split(" ")[1].split("::")[-1]
1783 impl_namespaces = ugly_line.split(" ")[1].split("::")[:-1]
1784 complete_namespace = concat_namespace(namespaces)
1785 for namespace in impl_namespaces:
1786 complete_namespace += "::" + namespace
1787 debug("\tFound " + struct_name + " in " + complete_namespace,2)
1788 class_ = (class_by_name(struct_name), ugly_line.count("{"))#calc_ident(line))
1789 if struct_name in classnames:
1790 class_[0].namespace = complete_namespace
1791 i += 1
1792 continue
1793
1794 if class_ != None:
1795 class_ = (class_[0], class_[1] + ugly_line.count("{") - ugly_line.count("}"))
1796 if class_[1] == 0:
1797 if class_[0] == None:
1798 debug("\tExiting unknown class", 3)
1799 else:
1800 debug("\tExiting class " + class_[0].name, 3)
1801 class_ = None
1802 private_segment = False
1803 i += 1
1804 continue
1805
1806 if class_ != None and (line.find("private:") != -1 or line.find("protected:") != -1):
1807 private_segment = True
1808 i += 1
1809 continue
1810 if class_ != None and line.find("public:") != -1:
1811 private_segment = False
1812 i += 1
1813 continue
1814
1815 candidate = None
1816
1817 if private_segment and class_ != None and class_[0] != None:
1818 candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i, True)
1819 if candidate != None:
1820 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1821 class_[0].found_constrs.append(candidate)
1822 i += 1
1823 continue
1824
1825 if not private_segment and (class_ == None or class_[0] != None):
1826 if class_ != None:
1827 candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
1828 else:
1829 candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
1830 if candidate != None and candidate.name.find("::") == -1:
1831 if class_ == None:
1832 debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1833 unowned_functions.append(candidate)
1834 else:
1835 debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1836 class_[0].found_funs.append(candidate)
1837 else:
1838 candidate = WEnum.from_string(ugly_line, concat_namespace(namespaces), i)
1839 if candidate != None:
1840 enums.append(candidate)
1841 debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1842 elif class_ != None and class_[1] == 1:
1843 candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i)
1844 if candidate != None:
1845 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1846 class_[0].found_constrs.append(candidate)
1847 else:
1848 candidate = WMember.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
1849 if candidate != None:
1850 if type(candidate) == list:
1851 for c in candidate:
1852 debug("\t\tFound member \"" + c.name + "\" of class \"" + class_[0].name + "\" of type \"" + c.wtype.name + "\"", 2)
1853 class_[0].found_vars.extend(candidate)
1854 else:
1855 debug("\t\tFound member \"" + candidate.name + "\" of class \"" + class_[0].name + "\" of type \"" + candidate.wtype.name + "\"", 2)
1856 class_[0].found_vars.append(candidate)
1857
1858 j = i
1859 line = unpretty_string(line)
1860 while candidate == None and j+1 < len(source_text) and line.count(';') <= 1 and line.count("(") >= line.count(")"):
1861 j += 1
1862 line = line + "\n" + unpretty_string(source_text[j])
1863 if class_ != None:
1864 candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
1865 else:
1866 candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
1867 if candidate != None and candidate.name.find("::") == -1:
1868 if class_ == None:
1869 debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1870 unowned_functions.append(candidate)
1871 else:
1872 debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1873 class_[0].found_funs.append(candidate)
1874 continue
1875 candidate = WEnum.from_string(line, concat_namespace(namespaces), i)
1876 if candidate != None:
1877 enums.append(candidate)
1878 debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1879 continue
1880 if class_ != None:
1881 candidate = WConstructor.from_string(line, source.name, class_[0], i)
1882 if candidate != None:
1883 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1884 class_[0].found_constrs.append(candidate)
1885 continue
1886 if candidate != None:
1887 while i < j:
1888 i += 1
1889 line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", " namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END"," }")
1890 ugly_line = unpretty_string(line)
1891 if len(namespaces) != 0:
1892 namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
1893 if namespaces[-1][1] == 0:
1894 debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1895 del namespaces[-1]
1896 if class_ != None:
1897 class_ = (class_[0] , class_[1] + ugly_line.count("{") - ugly_line.count("}"))
1898 if class_[1] == 0:
1899 if class_[0] == None:
1900 debug("\tExiting unknown class", 3)
1901 else:
1902 debug("\tExiting class " + class_[0].name, 3)
1903 class_ = None
1904 private_segment = False
1905 i += 1
1906 else:
1907 i += 1
1908
1909 def debug(message, level):
1910 if level <= debug.debug_level:
1911 print(message)
1912
1913 def expand_function(f):
1914 fun_list = []
1915 arg_list = []
1916 for arg in f.args:
1917 if arg.default_value != None and (arg.wtype.name.split(" ")[-1] in primitive_types or arg.wtype.name in enum_names or (arg.wtype.name in classnames and arg.default_value == "nullptr")):
1918 fi = copy.deepcopy(f)
1919 fi.args = copy.deepcopy(arg_list)
1920 fun_list.append(fi)
1921 arg_list.append(arg)
1922 fun_list.append(f)
1923 return fun_list
1924
1925 def expand_functions():
1926 global unowned_functions
1927 new_funs = []
1928 for fun in unowned_functions:
1929 new_funs.extend(expand_function(fun))
1930 unowned_functions = new_funs
1931 for source in sources:
1932 for class_ in source.classes:
1933 new_funs = []
1934 for fun in class_.found_funs:
1935 new_funs.extend(expand_function(fun))
1936 class_.found_funs = new_funs
1937
1938 def clean_duplicates():
1939 for source in sources:
1940 for class_ in source.classes:
1941 known_decls = {}
1942 for fun in class_.found_funs:
1943 if fun.gen_decl_hash_py() in known_decls:
1944 debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
1945 other = known_decls[fun.gen_decl_hash_py()]
1946 other.gen_alias()
1947 fun.gen_alias()
1948 if fun.gen_decl_hash_py() == other.gen_decl_hash_py():
1949 fun.duplicate = True
1950 debug("Disabled \"" + fun.gen_decl_hash_py() + "\"", 3)
1951 else:
1952 known_decls[fun.gen_decl_hash_py()] = fun
1953 known_decls = []
1954 for con in class_.found_constrs:
1955 if con.gen_decl_hash_py() in known_decls:
1956 debug("Multiple declarations of " + con.gen_decl_hash_py(),3)
1957 con.duplicate = True
1958 else:
1959 known_decls.append(con.gen_decl_hash_py())
1960 known_decls = []
1961 for fun in unowned_functions:
1962 if fun.gen_decl_hash_py() in known_decls:
1963 debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
1964 fun.duplicate = True
1965 else:
1966 known_decls.append(fun.gen_decl_hash_py())
1967
1968 def gen_wrappers(filename, debug_level_ = 0):
1969 debug.debug_level = debug_level_
1970 for source in sources:
1971 parse_header(source)
1972
1973 expand_functions()
1974 clean_duplicates()
1975
1976 import shutil
1977 import math
1978 col = shutil.get_terminal_size((80,20)).columns
1979 debug("-"*col, 1)
1980 debug("-"*math.floor((col-7)/2)+"SUMMARY"+"-"*math.ceil((col-7)/2), 1)
1981 debug("-"*col, 1)
1982 for source in sources:
1983 for class_ in source.classes:
1984 debug("Class " + assure_length(class_.name, len(max(classnames, key=len)), True) + " contains " + assure_length(str(len(class_.found_vars)), 3, False) + " member variables, "+ assure_length(str(len(class_.found_funs)), 3, False) + " methods and " + assure_length(str(len(class_.found_constrs)), 2, False) + " constructors", 1)
1985 if len(class_.found_constrs) == 0:
1986 class_.found_constrs.append(WConstructor(source.name, class_))
1987 debug(str(len(unowned_functions)) + " functions are unowned", 1)
1988 for enum in enums:
1989 debug("Enum " + assure_length(enum.name, len(max(enum_names, key=len)), True) + " contains " + assure_length(str(len(enum.values)), 2, False) + " values", 1)
1990 debug("-"*col, 1)
1991 wrapper_file = open(filename, "w+")
1992 wrapper_file.write(
1993 """/*
1994 * yosys -- Yosys Open SYnthesis Suite
1995 *
1996 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
1997 *
1998 * Permission to use, copy, modify, and/or distribute this software for any
1999 * purpose with or without fee is hereby granted, provided that the above
2000 * copyright notice and this permission notice appear in all copies.
2001 *
2002 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
2003 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
2004 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
2005 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
2006 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
2007 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
2008 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2009 *
2010 * This is a generated file and can be overwritten by make
2011 */
2012
2013 #ifdef WITH_PYTHON
2014 """)
2015 for source in sources:
2016 wrapper_file.write("#include \""+source.name+".h\"\n")
2017 wrapper_file.write("""
2018 #include <boost/python/module.hpp>
2019 #include <boost/python/class.hpp>
2020 #include <boost/python/wrapper.hpp>
2021 #include <boost/python/call.hpp>
2022 #include <boost/python.hpp>
2023
2024 USING_YOSYS_NAMESPACE
2025
2026 namespace YOSYS_PYTHON {
2027 """)
2028
2029 for source in sources:
2030 for wclass in source.classes:
2031 wrapper_file.write("\n\tstruct " + wclass.name + ";")
2032
2033 wrapper_file.write("\n")
2034
2035 for source in sources:
2036 for wclass in source.classes:
2037 wrapper_file.write(wclass.gen_decl(source.name))
2038
2039 wrapper_file.write("\n")
2040
2041 for source in sources:
2042 for wclass in source.classes:
2043 wrapper_file.write(wclass.gen_funs(source.name))
2044
2045 for fun in unowned_functions:
2046 wrapper_file.write(fun.gen_def())
2047
2048 wrapper_file.write(""" struct Initializer
2049 {
2050 Initializer() {
2051 if(!Yosys::yosys_already_setup())
2052 {
2053 Yosys::log_streams.push_back(&std::cout);
2054 Yosys::log_error_stderr = true;
2055 Yosys::yosys_setup();
2056 }
2057 }
2058
2059 Initializer(Initializer const &) {}
2060
2061 ~Initializer() {
2062 Yosys::yosys_shutdown();
2063 }
2064 };
2065
2066 BOOST_PYTHON_MODULE(libyosys)
2067 {
2068 using namespace boost::python;
2069
2070 class_<Initializer>("Initializer");
2071 scope().attr("_hidden") = new Initializer();
2072 """)
2073
2074 for enum in enums:
2075 wrapper_file.write(enum.gen_boost_py())
2076
2077 for source in sources:
2078 for wclass in source.classes:
2079 wrapper_file.write(wclass.gen_boost_py())
2080
2081 for fun in unowned_functions:
2082 wrapper_file.write(fun.gen_boost_py())
2083
2084 wrapper_file.write("\n\t}\n}\n#endif")
2085
2086 def print_includes():
2087 for source in sources:
2088 print(source.name + ".pyh")