Update example for GW1NR-9
[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\tif(ref == nullptr){"
777 text += "\n\t\t\t\tthrow std::runtime_error(\"" + self.name + " does not exist.\");"
778 text += "\n\t\t\t}"
779 text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
780 if self.link_type == link_types.pointer:
781 text += "\n\t\t\tret->ref_obj = ref;"
782 if self.link_type == link_types.ref_copy:
783 if self.needs_clone:
784 text += "\n\t\t\tret->ref_obj = ref->clone();"
785 else:
786 text += "\n\t\t\tret->ref_obj = new "+long_name+"(*ref);"
787 if self.link_type == link_types.global_list:
788 text += "\n\t\t\tret->ref_obj = ref;"
789 text += "\n\t\t\tret->" + self.id_.varname + " = ret->ref_obj->" + self.id_.varname + ";"
790 text += "\n\t\t\treturn ret;"
791 text += "\n\t\t}\n"
792
793 if self.link_type == link_types.ref_copy:
794 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + " ref)\n\t\t{"
795 text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
796 if self.needs_clone:
797 text += "\n\t\t\tret->ref_obj = ref.clone();"
798 else:
799 text += "\n\t\t\tret->ref_obj = new "+long_name+"(ref);"
800 text += "\n\t\t\treturn ret;"
801 text += "\n\t\t}\n"
802
803 for con in self.found_constrs:
804 text += con.gen_decl()
805 for var in self.found_vars:
806 text += var.gen_decl()
807 for fun in self.found_funs:
808 text += fun.gen_decl()
809
810
811 if self.link_type == link_types.derive:
812 duplicates = {}
813 for fun in self.found_funs:
814 if fun.name in duplicates:
815 fun.gen_alias()
816 duplicates[fun.name].gen_alias()
817 else:
818 duplicates[fun.name] = fun
819
820 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"
821 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + "* ref)\n\t\t{"
822 text += "\n\t\t\treturn (" + self.name + "*)ref;"
823 text += "\n\t\t}\n"
824
825 for con in self.found_constrs:
826 text += con.gen_decl_derive()
827 for var in self.found_vars:
828 text += var.gen_decl()
829 for fun in self.found_funs:
830 text += fun.gen_decl_virtual()
831
832 if self.hash_id != None:
833 text += "\n\t\tunsigned int get_hash_py()"
834 text += "\n\t\t{"
835 text += "\n\t\t\treturn get_cpp_obj()->" + self.hash_id + ";"
836 text += "\n\t\t}"
837
838 text += "\n\t};\n"
839
840 if self.link_type == link_types.derive:
841 text += "\n\tstruct " + self.name + "Wrap : " + self.name + ", boost::python::wrapper<" + self.name + ">"
842 text += "\n\t{"
843
844 for con in self.found_constrs:
845 text += con.gen_decl_wrapperclass()
846 for fun in self.found_funs:
847 text += fun.gen_default_impl()
848
849 text += "\n\t};"
850
851 text += "\n\tstd::ostream &operator<<(std::ostream &ostr, const " + self.name + " &ref)"
852 text += "\n\t{"
853 text += "\n\t\tostr << \"" + self.name
854 if self.string_id != None:
855 text +=" \\\"\""
856 text += " << ref.get_cpp_obj()->" + self.string_id
857 text += " << \"\\\"\""
858 else:
859 text += " at \" << ref.get_cpp_obj()"
860 text += ";"
861 text += "\n\t\treturn ostr;"
862 text += "\n\t}"
863 text += "\n"
864
865 return text
866
867 def gen_funs(self, filename):
868 text = ""
869 if self.link_type != link_types.derive:
870 for con in self.found_constrs:
871 text += con.gen_def()
872 for var in self.found_vars:
873 text += var.gen_def()
874 for fun in self.found_funs:
875 text += fun.gen_def()
876 else:
877 for var in self.found_vars:
878 text += var.gen_def()
879 for fun in self.found_funs:
880 text += fun.gen_def_virtual()
881 return text
882
883 def gen_boost_py(self):
884 text = "\n\t\tclass_<" + self.name
885 if self.link_type == link_types.derive:
886 text += "Wrap, boost::noncopyable"
887 text += ">(\"" + self.name + "\""
888 if self.printable_constrs() == 0 or not self.contains_default_constr():
889 text += ", no_init"
890 text += ")"
891 text += "\n\t\t\t.def(boost::python::self_ns::str(boost::python::self_ns::self))"
892 text += "\n\t\t\t.def(boost::python::self_ns::repr(boost::python::self_ns::self))"
893 for con in self.found_constrs:
894 text += con.gen_boost_py()
895 for var in self.found_vars:
896 text += var.gen_boost_py()
897 static_funs = []
898 for fun in self.found_funs:
899 text += fun.gen_boost_py()
900 if fun.is_static and fun.alias not in static_funs:
901 static_funs.append(fun.alias)
902 for fun in static_funs:
903 text += "\n\t\t\t.staticmethod(\"" + fun + "\")"
904
905 if self.hash_id != None:
906 text += "\n\t\t\t.def(\"__hash__\", &" + self.name + "::get_hash_py)"
907 text += "\n\t\t\t;\n"
908 return text
909
910 def contains_default_constr(self):
911 for c in self.found_constrs:
912 if len(c.args) == 0:
913 return True
914 return False
915
916 #CONFIGURE HEADER-FILES TO BE PARSED AND CLASSES EXPECTED IN THEM HERE
917
918 sources = [
919 Source("kernel/celltypes",[
920 WClass("CellType", link_types.pointer, None, None, "type.hash()", True),
921 WClass("CellTypes", link_types.pointer, None, None, None, True)
922 ]
923 ),
924 Source("kernel/consteval",[
925 WClass("ConstEval", link_types.pointer, None, None, None, True)
926 ]
927 ),
928 Source("kernel/log",[]),
929 Source("kernel/register",[
930 WClass("Pass", link_types.derive, None, None, None, True),
931 ]
932 ),
933 Source("kernel/rtlil",[
934 WClass("IdString", link_types.ref_copy, None, "str()", "hash()"),
935 WClass("Const", link_types.ref_copy, None, "as_string()", "hash()"),
936 WClass("AttrObject", link_types.ref_copy, None, None, None),
937 WClass("Selection", link_types.ref_copy, None, None, None),
938 WClass("Monitor", link_types.derive, None, None, None),
939 WClass("CaseRule",link_types.ref_copy, None, None, None, True),
940 WClass("SwitchRule",link_types.ref_copy, None, None, None, True),
941 WClass("SyncRule", link_types.ref_copy, None, None, None, True),
942 WClass("Process", link_types.ref_copy, None, "name.c_str()", "name.hash()"),
943 WClass("SigChunk", link_types.ref_copy, None, None, None),
944 WClass("SigBit", link_types.ref_copy, None, None, "hash()"),
945 WClass("SigSpec", link_types.ref_copy, None, None, "hash()"),
946 WClass("Cell", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
947 WClass("Wire", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
948 WClass("Memory", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
949 WClass("Module", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
950 WClass("Design", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "hashidx_", "hash()")
951 ]
952 ),
953 #Source("kernel/satgen",[
954 # ]
955 # ),
956 #Source("libs/ezsat/ezsat",[
957 # ]
958 # ),
959 #Source("libs/ezsat/ezminisat",[
960 # ]
961 # ),
962 Source("kernel/sigtools",[
963 WClass("SigMap", link_types.pointer, None, None, None, True)
964 ]
965 ),
966 Source("kernel/yosys",[
967 ]
968 ),
969 Source("kernel/cost",[])
970 ]
971
972 blacklist_methods = ["YOSYS_NAMESPACE::Pass::run_register", "YOSYS_NAMESPACE::Module::Pow", "YOSYS_NAMESPACE::Module::Bu0", "YOSYS_NAMESPACE::CaseRule::optimize"]
973
974 enum_names = ["State","SyncType","ConstFlags"]
975
976 enums = [] #Do not edit
977
978 unowned_functions = []
979
980 classnames = []
981 for source in sources:
982 for wclass in source.classes:
983 classnames.append(wclass.name)
984
985 def class_by_name(name):
986 for source in sources:
987 for wclass in source.classes:
988 if wclass.name == name:
989 return wclass
990 return None
991
992 def enum_by_name(name):
993 for e in enums:
994 if e.name == name:
995 return e
996 return None
997
998 def find_closing(text, open_tok, close_tok):
999 if text.find(open_tok) == -1 or text.find(close_tok) <= text.find(open_tok):
1000 return text.find(close_tok)
1001 return text.find(close_tok) + find_closing(text[text.find(close_tok)+1:], open_tok, close_tok) + 1
1002
1003 def unpretty_string(s):
1004 s = s.strip()
1005 while s.find(" ") != -1:
1006 s = s.replace(" "," ")
1007 while s.find("\t") != -1:
1008 s = s.replace("\t"," ")
1009 s = s.replace(" (","(")
1010 return s
1011
1012 class WEnum:
1013 name = None
1014 namespace = None
1015 values = []
1016
1017 def from_string(str_def, namespace, line_number):
1018 str_def = str_def.strip()
1019 if not str.startswith(str_def, "enum "):
1020 return None
1021 if str_def.count(";") != 1:
1022 return None
1023 str_def = str_def[5:]
1024 enum = WEnum()
1025 split = str_def.split(":")
1026 if(len(split) != 2):
1027 return None
1028 enum.name = split[0].strip()
1029 if enum.name not in enum_names:
1030 return None
1031 str_def = split[1]
1032 if str_def.count("{") != str_def.count("}") != 1:
1033 return None
1034 if len(str_def) < str_def.find("}")+2 or str_def[str_def.find("}")+1] != ';':
1035 return None
1036 str_def = str_def.split("{")[-1].split("}")[0]
1037 enum.values = []
1038 for val in str_def.split(','):
1039 enum.values.append(val.strip().split('=')[0].strip())
1040 enum.namespace = namespace
1041 return enum
1042
1043 def gen_boost_py(self):
1044 text = "\n\t\tenum_<" + self.namespace + "::" + self.name + ">(\"" + self.name + "\")\n"
1045 for value in self.values:
1046 text += "\t\t\t.value(\"" + value + "\"," + self.namespace + "::" + value + ")\n"
1047 text += "\t\t\t;\n"
1048 return text
1049
1050 def __str__(self):
1051 ret = "Enum " + self.namespace + "::" + self.name + "(\n"
1052 for val in self.values:
1053 ret = ret + "\t" + val + "\n"
1054 return ret + ")"
1055
1056 def __repr__(self):
1057 return __str__(self)
1058
1059 class WConstructor:
1060 orig_text = None
1061 args = []
1062 containing_file = None
1063 member_of = None
1064 duplicate = False
1065 protected = False
1066
1067 def __init__(self, containing_file, class_):
1068 self.orig_text = "Auto generated default constructor"
1069 self.args = []
1070 self.containing_file = containing_file
1071 self.member_of = class_
1072 self.protected = False
1073
1074 def from_string(str_def, containing_file, class_, line_number, protected = False):
1075 if class_ == None:
1076 return None
1077 if str_def.count("delete;") > 0:
1078 return None
1079 con = WConstructor(containing_file, class_)
1080 con.orig_text = str_def
1081 con.args = []
1082 con.duplicate = False
1083 con.protected = protected
1084 if not str.startswith(str_def, class_.name + "("):
1085 return None
1086 str_def = str_def[len(class_.name)+1:]
1087 found = find_closing(str_def, "(", ")")
1088 if found == -1:
1089 return None
1090 str_def = str_def[0:found].strip()
1091 if len(str_def) == 0:
1092 return con
1093 for arg in split_list(str_def, ","):
1094 parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
1095 if parsed == None:
1096 return None
1097 con.args.append(parsed)
1098 return con
1099
1100 def gen_decl(self):
1101 if self.duplicate or self.protected:
1102 return ""
1103 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1104 text += "\n\t\t" + self.member_of.name + "("
1105 for arg in self.args:
1106 text += arg.gen_listitem() + ", "
1107 if len(self.args) > 0:
1108 text = text[:-2]
1109 text += ");\n"
1110 return text
1111
1112 def gen_decl_derive(self):
1113 if self.duplicate or self.protected:
1114 return ""
1115 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1116 text += "\n\t\t" + self.member_of.name + "("
1117 for arg in self.args:
1118 text += arg.gen_listitem() + ", "
1119 if len(self.args) > 0:
1120 text = text[:-2]
1121 text += ")"
1122 if len(self.args) == 0:
1123 return text + "{}"
1124 text += " : "
1125 text += self.member_of.namespace + "::" + self.member_of.name + "("
1126 for arg in self.args:
1127 text += arg.gen_call() + ", "
1128 if len(self.args) > 0:
1129 text = text[:-2]
1130 text += "){}\n"
1131 return text
1132
1133 def gen_decl_wrapperclass(self):
1134 if self.duplicate or self.protected:
1135 return ""
1136 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1137 text += "\n\t\t" + self.member_of.name + "Wrap("
1138 for arg in self.args:
1139 text += arg.gen_listitem() + ", "
1140 if len(self.args) > 0:
1141 text = text[:-2]
1142 text += ")"
1143 if len(self.args) == 0:
1144 return text + "{}"
1145 text += " : "
1146 text += self.member_of.name + "("
1147 for arg in self.args:
1148 text += arg.gen_call() + ", "
1149 if len(self.args) > 0:
1150 text = text[:-2]
1151 text += "){}\n"
1152 return text
1153
1154 def gen_decl_hash_py(self):
1155 text = self.member_of.name + "("
1156 for arg in self.args:
1157 text += arg.gen_listitem_hash() + ", "
1158 if len(self.args) > 0:
1159 text = text[:-2]
1160 text += ");"
1161 return text
1162
1163 def gen_def(self):
1164 if self.duplicate or self.protected:
1165 return ""
1166 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1167 text += "\n\t" + self.member_of.name + "::" + self.member_of.name + "("
1168 for arg in self.args:
1169 text += arg.gen_listitem() + ", "
1170 if len(self.args) > 0:
1171 text = text[:-2]
1172 text +=")\n\t{"
1173 for arg in self.args:
1174 text += arg.gen_translation()
1175 if self.member_of.link_type != link_types.derive:
1176 text += "\n\t\tthis->ref_obj = new " + self.member_of.namespace + "::" + self.member_of.name + "("
1177 for arg in self.args:
1178 text += arg.gen_call() + ", "
1179 if len(self.args) > 0:
1180 text = text[:-2]
1181 if self.member_of.link_type != link_types.derive:
1182 text += ");"
1183 if self.member_of.link_type == link_types.global_list:
1184 text += "\n\t\tthis->" + self.member_of.id_.varname + " = this->ref_obj->" + self.member_of.id_.varname + ";"
1185 for arg in self.args:
1186 text += arg.gen_cleanup()
1187 text += "\n\t}\n"
1188 return text
1189
1190 def gen_boost_py(self):
1191 if self.duplicate or self.protected or len(self.args) == 0:
1192 return ""
1193 text = "\n\t\t\t.def(init"
1194 text += "<"
1195 for a in self.args:
1196 text += a.gen_listitem_hash() + ", "
1197 text = text[0:-2] + ">())"
1198 return text
1199
1200 class WFunction:
1201 orig_text = None
1202 is_static = False
1203 is_inline = False
1204 is_virtual = False
1205 ret_attr_type = attr_types.default
1206 is_operator = False
1207 ret_type = None
1208 name = None
1209 alias = None
1210 args = []
1211 containing_file = None
1212 member_of = None
1213 duplicate = False
1214 namespace = ""
1215
1216 def from_string(str_def, containing_file, class_, line_number, namespace):
1217 if str_def.count("delete;") > 0:
1218 return None
1219 func = WFunction()
1220 func.is_static = False
1221 func.is_inline = False
1222 func.is_virtual = False
1223 func.ret_attr_type = attr_types.default
1224 func.is_operator = False
1225 func.member_of = None
1226 func.orig_text = str_def
1227 func.args = []
1228 func.containing_file = containing_file
1229 func.member_of = class_
1230 func.duplicate = False
1231 func.namespace = namespace
1232 str_def = str_def.replace("operator ","operator")
1233 if str.startswith(str_def, "static "):
1234 func.is_static = True
1235 str_def = str_def[7:]
1236 else:
1237 func.is_static = False
1238 if str.startswith(str_def, "inline "):
1239 func.is_inline = True
1240 str_def = str_def[7:]
1241 else:
1242 func.is_inline = False
1243 if str.startswith(str_def, "virtual "):
1244 func.is_virtual = True
1245 str_def = str_def[8:]
1246 else:
1247 func.is_virtual = False
1248
1249 if str_def.count(" ") == 0:
1250 return None
1251
1252 parts = split_list(str_def.strip(), " ")
1253
1254 prefix = ""
1255 i = 0
1256 for part in parts:
1257 if part in ["unsigned", "long", "short"]:
1258 prefix += part + " "
1259 i += 1
1260 else:
1261 break
1262 parts = parts[i:]
1263
1264 if len(parts) <= 1:
1265 return None
1266
1267 func.ret_type = WType.from_string(prefix + parts[0], containing_file, line_number)
1268
1269 if func.ret_type == None:
1270 return None
1271
1272 str_def = parts[1]
1273 for part in parts[2:]:
1274 str_def = str_def + " " + part
1275
1276 found = str_def.find("(")
1277 if found == -1 or (str_def.find(" ") != -1 and found > str_def.find(" ")):
1278 return None
1279 func.name = str_def[:found]
1280 str_def = str_def[found:]
1281 if func.name.find("operator") != -1 and str.startswith(str_def, "()("):
1282 func.name += "()"
1283 str_def = str_def[2:]
1284 str_def = str_def[1:]
1285 if func.name.find("operator") != -1:
1286 func.is_operator = True
1287 if func.name.find("*") == 0:
1288 func.name = func.name.replace("*", "")
1289 func.ret_type.attr_type = attr_types.star
1290 if func.name.find("&&") == 0:
1291 func.name = func.name.replace("&&", "")
1292 func.ret_type.attr_type = attr_types.ampamp
1293 if func.name.find("&") == 0:
1294 func.name = func.name.replace("&", "")
1295 func.ret_type.attr_type = attr_types.amp
1296
1297 found = find_closing(str_def, "(", ")")
1298 if found == -1:
1299 return None
1300 str_def = str_def[0:found]
1301 if func.name in blacklist_methods:
1302 return None
1303 if func.namespace != None and func.namespace != "":
1304 if (func.namespace + "::" + func.name) in blacklist_methods:
1305 return None
1306 if func.member_of != None:
1307 if (func.namespace + "::" + func.member_of.name + "::" + func.name) in blacklist_methods:
1308 return None
1309 if func.is_operator and func.name.replace(" ","").replace("operator","").split("::")[-1] not in wrappable_operators:
1310 return None
1311
1312 testname = func.name
1313 if func.is_operator:
1314 testname = testname[:testname.find("operator")]
1315 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:
1316 return None
1317
1318 func.alias = func.name
1319 if func.name in keyword_aliases:
1320 func.alias = keyword_aliases[func.name]
1321 str_def = str_def[:found].strip()
1322 if(len(str_def) == 0):
1323 return func
1324 for arg in split_list(str_def, ","):
1325 if arg.strip() == "...":
1326 continue
1327 parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
1328 if parsed == None:
1329 return None
1330 func.args.append(parsed)
1331 return func
1332
1333 def gen_alias(self):
1334 self.alias = self.name
1335 for arg in self.args:
1336 self.alias += "__" + arg.wtype.gen_text_cpp().replace("::", "_").replace("<","_").replace(">","_").replace(" ","").replace("*","").replace(",","")
1337
1338 def gen_decl(self):
1339 if self.duplicate:
1340 return ""
1341 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1342 text += "\n\t\t"
1343 if self.is_static:
1344 text += "static "
1345 text += self.ret_type.gen_text() + " " + self.alias + "("
1346 for arg in self.args:
1347 text += arg.gen_listitem()
1348 text += ", "
1349 if len(self.args) > 0:
1350 text = text[:-2]
1351 text += ");\n"
1352 return text
1353
1354 def gen_decl_virtual(self):
1355 if self.duplicate:
1356 return ""
1357 if not self.is_virtual:
1358 return self.gen_decl()
1359 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1360 text += "\n\t\tvirtual "
1361 if self.is_static:
1362 text += "static "
1363 text += self.ret_type.gen_text() + " py_" + self.alias + "("
1364 for arg in self.args:
1365 text += arg.gen_listitem()
1366 text += ", "
1367 if len(self.args) > 0:
1368 text = text[:-2]
1369 text += ")"
1370 if len(self.args) == 0:
1371 text += "{}"
1372 else:
1373 text += "\n\t\t{"
1374 for arg in self.args:
1375 text += "\n\t\t\t(void)" + arg.gen_varname() + ";"
1376 text += "\n\t\t}\n"
1377 text += "\n\t\tvirtual "
1378 if self.is_static:
1379 text += "static "
1380 text += self.ret_type.gen_text() + " " + self.name + "("
1381 for arg in self.args:
1382 text += arg.gen_listitem_cpp()
1383 text += ", "
1384 if len(self.args) > 0:
1385 text = text[:-2]
1386 text += ") YS_OVERRIDE;\n"
1387 return text
1388
1389 def gen_decl_hash_py(self):
1390 text = self.ret_type.gen_text() + " " + self.alias + "("
1391 for arg in self.args:
1392 text += arg.gen_listitem_hash() + ", "
1393 if len(self.args) > 0:
1394 text = text[:-2]
1395 text += ");"
1396 return text
1397
1398 def gen_def(self):
1399 if self.duplicate:
1400 return ""
1401 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1402 text += "\n\t" + self.ret_type.gen_text() + " "
1403 if self.member_of != None:
1404 text += self.member_of.name + "::"
1405 text += self.alias + "("
1406 for arg in self.args:
1407 text += arg.gen_listitem()
1408 text += ", "
1409 if len(self.args) > 0:
1410 text = text[:-2]
1411 text +=")\n\t{"
1412 for arg in self.args:
1413 text += arg.gen_translation()
1414 text += "\n\t\t"
1415 if self.ret_type.name != "void":
1416 if self.ret_type.name in known_containers:
1417 text += self.ret_type.gen_text_cpp()
1418 else:
1419 text += self.ret_type.gen_text()
1420 if self.ret_type.name in classnames or (self.ret_type.name in known_containers and self.ret_type.attr_type == attr_types.star):
1421 text += "*"
1422 text += " ret_ = "
1423 if self.ret_type.name in classnames:
1424 text += self.ret_type.name + "::get_py_obj("
1425 if self.member_of == None:
1426 text += "::" + self.namespace + "::" + self.alias + "("
1427 elif self.is_static:
1428 text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
1429 else:
1430 text += "this->get_cpp_obj()->" + self.name + "("
1431 for arg in self.args:
1432 text += arg.gen_call() + ", "
1433 if len(self.args) > 0:
1434 text = text[:-2]
1435 if self.ret_type.name in classnames:
1436 text += ")"
1437 text += ");"
1438 for arg in self.args:
1439 text += arg.gen_cleanup()
1440 if self.ret_type.name != "void":
1441 if self.ret_type.name in classnames:
1442 text += "\n\t\treturn *ret_;"
1443 elif self.ret_type.name in known_containers:
1444 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)
1445 text += "\n\t\treturn ret____tmp;"
1446 else:
1447 text += "\n\t\treturn ret_;"
1448 text += "\n\t}\n"
1449 return text
1450
1451 def gen_def_virtual(self):
1452 if self.duplicate:
1453 return ""
1454 if not self.is_virtual:
1455 return self.gen_def()
1456 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1457 text += "\n\t"
1458 if self.is_static:
1459 text += "static "
1460 text += self.ret_type.gen_text() + " " + self.member_of.name + "::" + self.name + "("
1461 for arg in self.args:
1462 text += arg.gen_listitem_cpp()
1463 text += ", "
1464 if len(self.args) > 0:
1465 text = text[:-2]
1466 text += ")\n\t{"
1467 for arg in self.args:
1468 text += arg.gen_translation_cpp()
1469 text += "\n\t\t"
1470 if self.member_of == None:
1471 text += "::" + self.namespace + "::" + self.alias + "("
1472 elif self.is_static:
1473 text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
1474 else:
1475 text += "py_" + self.alias + "("
1476 for arg in self.args:
1477 text += arg.gen_call_cpp() + ", "
1478 if len(self.args) > 0:
1479 text = text[:-2]
1480 if self.ret_type.name in classnames:
1481 text += ")"
1482 text += ");"
1483 for arg in self.args:
1484 text += arg.gen_cleanup()
1485 text += "\n\t}\n"
1486 return text
1487
1488 def gen_default_impl(self):
1489 if self.duplicate:
1490 return ""
1491 if not self.is_virtual:
1492 return ""
1493 text = "\n\n\t\t" + self.ret_type.gen_text() + " py_" + self.alias + "("
1494 for arg in self.args:
1495 text += arg.gen_listitem() + ", "
1496 if len(self.args) > 0:
1497 text = text[:-2]
1498
1499 call_string = "py_" + self.alias + "("
1500 for arg in self.args:
1501 call_string += arg.gen_varname() + ", "
1502 if len(self.args) > 0:
1503 call_string = call_string[0:-2]
1504 call_string += ");"
1505
1506 text += ")\n\t\t{"
1507 text += "\n\t\t\tif(boost::python::override py_" + self.alias + " = this->get_override(\"py_" + self.alias + "\"))"
1508 text += "\n\t\t\t\t" + call_string
1509 text += "\n\t\t\telse"
1510 text += "\n\t\t\t\t" + self.member_of.name + "::" + call_string
1511 text += "\n\t\t}"
1512
1513 text += "\n\n\t\t" + self.ret_type.gen_text() + " default_py_" + self.alias + "("
1514 for arg in self.args:
1515 text += arg.gen_listitem() + ", "
1516 if len(self.args) > 0:
1517 text = text[:-2]
1518 text += ")\n\t\t{"
1519 text += "\n\t\t\tthis->" + self.member_of.name + "::" + call_string
1520 text += "\n\t\t}"
1521 return text
1522
1523
1524 def gen_boost_py(self):
1525 if self.duplicate:
1526 return ""
1527 if self.member_of == None:
1528 text = "\n\t\tdef"
1529 else:
1530 text = "\n\t\t\t.def"
1531 if len(self.args) > -1:
1532 if self.ret_type.name in known_containers:
1533 text += "<" + known_containers[self.ret_type.name].typename + " "
1534 else:
1535 text += "<" + self.ret_type.name + " "
1536 if self.member_of == None or self.is_static:
1537 text += "(*)("
1538 else:
1539 text += "(" + self.member_of.name + "::*)("
1540 for a in self.args:
1541 text += a.gen_listitem_hash() + ", "
1542 if len(self.args) > 0:
1543 text = text[0:-2] + ")>"
1544 else:
1545 text += "void)>"
1546
1547 if self.is_operator:
1548 text += "(\"" + wrappable_operators[self.name.replace("operator","")] + "\""
1549 else:
1550 if self.member_of != None and self.member_of.link_type == link_types.derive and self.is_virtual:
1551 text += "(\"py_" + self.alias + "\""
1552 else:
1553 text += "(\"" + self.alias + "\""
1554 if self.member_of != None:
1555 text += ", &" + self.member_of.name + "::"
1556 if self.member_of.link_type == link_types.derive and self.is_virtual:
1557 text += "py_" + self.alias
1558 text += ", &" + self.member_of.name + "Wrap::default_py_" + self.alias
1559 else:
1560 text += self.alias
1561
1562 text += ")"
1563 else:
1564 text += ", " + "YOSYS_PYTHON::" + self.alias + ");"
1565 return text
1566
1567 class WMember:
1568 orig_text = None
1569 wtype = attr_types.default
1570 name = None
1571 containing_file = None
1572 member_of = None
1573 namespace = ""
1574 is_const = False
1575
1576 def from_string(str_def, containing_file, class_, line_number, namespace):
1577 member = WMember()
1578 member.orig_text = str_def
1579 member.wtype = None
1580 member.name = ""
1581 member.containing_file = containing_file
1582 member.member_of = class_
1583 member.namespace = namespace
1584 member.is_const = False
1585
1586 if str.startswith(str_def, "const "):
1587 member.is_const = True
1588 str_def = str_def[6:]
1589
1590 if str_def.count(" ") == 0:
1591 return None
1592
1593 parts = split_list(str_def.strip(), " ")
1594
1595 prefix = ""
1596 i = 0
1597 for part in parts:
1598 if part in ["unsigned", "long", "short"]:
1599 prefix += part + " "
1600 i += 1
1601 else:
1602 break
1603 parts = parts[i:]
1604
1605 if len(parts) <= 1:
1606 return None
1607
1608 member.wtype = WType.from_string(prefix + parts[0], containing_file, line_number)
1609
1610 if member.wtype == None:
1611 return None
1612
1613 str_def = parts[1]
1614 for part in parts[2:]:
1615 str_def = str_def + " " + part
1616
1617 if str_def.find("(") != -1 or str_def.find(")") != -1 or str_def.find("{") != -1 or str_def.find("}") != -1:
1618 return None
1619
1620 found = str_def.find(";")
1621 if found == -1:
1622 return None
1623
1624 found_eq = str_def.find("=")
1625 if found_eq != -1:
1626 found = found_eq
1627
1628 member.name = str_def[:found]
1629 str_def = str_def[found+1:]
1630 if member.name.find("*") == 0:
1631 member.name = member.name.replace("*", "")
1632 member.wtype.attr_type = attr_types.star
1633 if member.name.find("&&") == 0:
1634 member.name = member.name.replace("&&", "")
1635 member.wtype.attr_type = attr_types.ampamp
1636 if member.name.find("&") == 0:
1637 member.name = member.name.replace("&", "")
1638 member.wtype.attr_type = attr_types.amp
1639
1640 if(len(str_def.strip()) != 0):
1641 return None
1642
1643 if len(member.name.split(",")) > 1:
1644 member_list = []
1645 for name in member.name.split(","):
1646 name = name.strip();
1647 member_list.append(WMember())
1648 member_list[-1].orig_text = member.orig_text
1649 member_list[-1].wtype = member.wtype
1650 member_list[-1].name = name
1651 member_list[-1].containing_file = member.containing_file
1652 member_list[-1].member_of = member.member_of
1653 member_list[-1].namespace = member.namespace
1654 member_list[-1].is_const = member.is_const
1655 return member_list
1656
1657 return member
1658
1659 def gen_decl(self):
1660 text = "\n\t\t" + self.wtype.gen_text() + " get_var_py_" + self.name + "();\n"
1661 if self.is_const:
1662 return text
1663 if self.wtype.name in classnames:
1664 text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs);\n"
1665 else:
1666 text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs);\n"
1667 return text
1668
1669 def gen_def(self):
1670 text = "\n\t" + self.wtype.gen_text() + " " + self.member_of.name +"::get_var_py_" + self.name + "()"
1671 text += "\n\t{\n\t\t"
1672 if self.wtype.attr_type == attr_types.star:
1673 text += "if(this->get_cpp_obj()->" + self.name + " == NULL)\n\t\t\t"
1674 text += "throw std::runtime_error(\"Member \\\"" + self.name + "\\\" is NULL\");\n\t\t"
1675 if self.wtype.name in known_containers:
1676 text += self.wtype.gen_text_cpp()
1677 else:
1678 text += self.wtype.gen_text()
1679
1680 if self.wtype.name in classnames or (self.wtype.name in known_containers and self.wtype.attr_type == attr_types.star):
1681 text += "*"
1682 text += " ret_ = "
1683 if self.wtype.name in classnames:
1684 text += self.wtype.name + "::get_py_obj("
1685 if self.wtype.attr_type != attr_types.star:
1686 text += "&"
1687 text += "this->get_cpp_obj()->" + self.name
1688 if self.wtype.name in classnames:
1689 text += ")"
1690 text += ";"
1691
1692 if self.wtype.name in classnames:
1693 text += "\n\t\treturn *ret_;"
1694 elif self.wtype.name in known_containers:
1695 text += known_containers[self.wtype.name].translate_cpp("ret_", self.wtype.cont.args, "\n\t\t", self.wtype.attr_type == attr_types.star)
1696 text += "\n\t\treturn ret____tmp;"
1697 else:
1698 text += "\n\t\treturn ret_;"
1699 text += "\n\t}\n"
1700
1701 if self.is_const:
1702 return text
1703
1704 ret = Attribute(self.wtype, "rhs");
1705
1706 if self.wtype.name in classnames:
1707 text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs)"
1708 else:
1709 text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs)"
1710 text += "\n\t{"
1711 text += ret.gen_translation()
1712 text += "\n\t\tthis->get_cpp_obj()->" + self.name + " = " + ret.gen_call() + ";"
1713 text += "\n\t}\n"
1714
1715 return text;
1716
1717 def gen_boost_py(self):
1718 text = "\n\t\t\t.add_property(\"" + self.name + "\", &" + self.member_of.name + "::get_var_py_" + self.name
1719 if not self.is_const:
1720 text += ", &" + self.member_of.name + "::set_var_py_" + self.name
1721 text += ")"
1722 return text
1723
1724 def concat_namespace(tuple_list):
1725 if len(tuple_list) == 0:
1726 return ""
1727 ret = ""
1728 for namespace in tuple_list:
1729 ret += "::" + namespace[0]
1730 return ret[2:]
1731
1732 def calc_ident(text):
1733 if len(text) == 0 or text[0] != ' ':
1734 return 0
1735 return calc_ident(text[1:]) + 1
1736
1737 def assure_length(text, length, left = False):
1738 if len(text) > length:
1739 return text[:length]
1740 if left:
1741 return text + " "*(length - len(text))
1742 return " "*(length - len(text)) + text
1743
1744 def parse_header(source):
1745 debug("Parsing " + source.name + ".pyh",1)
1746 source_file = open(source.name + ".pyh", "r")
1747
1748 source_text = []
1749 in_line = source_file.readline()
1750
1751 namespaces = []
1752
1753 while(in_line):
1754 if(len(in_line)>1):
1755 source_text.append(in_line.replace("char *", "char_p ").replace("char* ", "char_p "))
1756 in_line = source_file.readline()
1757
1758 i = 0
1759
1760 namespaces = []
1761 class_ = None
1762 private_segment = False
1763
1764 while i < len(source_text):
1765 line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", " namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END"," }")
1766 ugly_line = unpretty_string(line)
1767
1768 if str.startswith(ugly_line, "namespace "):# and ugly_line.find("std") == -1 and ugly_line.find("__") == -1:
1769 namespace_name = ugly_line[10:].replace("{","").strip()
1770 namespaces.append((namespace_name, ugly_line.count("{")))
1771 debug("-----NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1772 i += 1
1773 continue
1774
1775 if len(namespaces) != 0:
1776 namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
1777 if namespaces[-1][1] == 0:
1778 debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1779 del namespaces[-1]
1780 i += 1
1781 continue
1782
1783 if class_ == None and (str.startswith(ugly_line, "struct ") or str.startswith(ugly_line, "class")) and ugly_line.count(";") == 0:
1784
1785 struct_name = ugly_line.split(" ")[1].split("::")[-1]
1786 impl_namespaces = ugly_line.split(" ")[1].split("::")[:-1]
1787 complete_namespace = concat_namespace(namespaces)
1788 for namespace in impl_namespaces:
1789 complete_namespace += "::" + namespace
1790 debug("\tFound " + struct_name + " in " + complete_namespace,2)
1791 class_ = (class_by_name(struct_name), ugly_line.count("{"))#calc_ident(line))
1792 if struct_name in classnames:
1793 class_[0].namespace = complete_namespace
1794 i += 1
1795 continue
1796
1797 if class_ != None:
1798 class_ = (class_[0], class_[1] + ugly_line.count("{") - ugly_line.count("}"))
1799 if class_[1] == 0:
1800 if class_[0] == None:
1801 debug("\tExiting unknown class", 3)
1802 else:
1803 debug("\tExiting class " + class_[0].name, 3)
1804 class_ = None
1805 private_segment = False
1806 i += 1
1807 continue
1808
1809 if class_ != None and (line.find("private:") != -1 or line.find("protected:") != -1):
1810 private_segment = True
1811 i += 1
1812 continue
1813 if class_ != None and line.find("public:") != -1:
1814 private_segment = False
1815 i += 1
1816 continue
1817
1818 candidate = None
1819
1820 if private_segment and class_ != None and class_[0] != None:
1821 candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i, True)
1822 if candidate != None:
1823 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1824 class_[0].found_constrs.append(candidate)
1825 i += 1
1826 continue
1827
1828 if not private_segment and (class_ == None or class_[0] != None):
1829 if class_ != None:
1830 candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
1831 else:
1832 candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
1833 if candidate != None and candidate.name.find("::") == -1:
1834 if class_ == None:
1835 debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1836 unowned_functions.append(candidate)
1837 else:
1838 debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1839 class_[0].found_funs.append(candidate)
1840 else:
1841 candidate = WEnum.from_string(ugly_line, concat_namespace(namespaces), i)
1842 if candidate != None:
1843 enums.append(candidate)
1844 debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1845 elif class_ != None and class_[1] == 1:
1846 candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i)
1847 if candidate != None:
1848 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1849 class_[0].found_constrs.append(candidate)
1850 else:
1851 candidate = WMember.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
1852 if candidate != None:
1853 if type(candidate) == list:
1854 for c in candidate:
1855 debug("\t\tFound member \"" + c.name + "\" of class \"" + class_[0].name + "\" of type \"" + c.wtype.name + "\"", 2)
1856 class_[0].found_vars.extend(candidate)
1857 else:
1858 debug("\t\tFound member \"" + candidate.name + "\" of class \"" + class_[0].name + "\" of type \"" + candidate.wtype.name + "\"", 2)
1859 class_[0].found_vars.append(candidate)
1860
1861 j = i
1862 line = unpretty_string(line)
1863 while candidate == None and j+1 < len(source_text) and line.count(';') <= 1 and line.count("(") >= line.count(")"):
1864 j += 1
1865 line = line + "\n" + unpretty_string(source_text[j])
1866 if class_ != None:
1867 candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
1868 else:
1869 candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
1870 if candidate != None and candidate.name.find("::") == -1:
1871 if class_ == None:
1872 debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1873 unowned_functions.append(candidate)
1874 else:
1875 debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1876 class_[0].found_funs.append(candidate)
1877 continue
1878 candidate = WEnum.from_string(line, concat_namespace(namespaces), i)
1879 if candidate != None:
1880 enums.append(candidate)
1881 debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
1882 continue
1883 if class_ != None:
1884 candidate = WConstructor.from_string(line, source.name, class_[0], i)
1885 if candidate != None:
1886 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
1887 class_[0].found_constrs.append(candidate)
1888 continue
1889 if candidate != None:
1890 while i < j:
1891 i += 1
1892 line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", " namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END"," }")
1893 ugly_line = unpretty_string(line)
1894 if len(namespaces) != 0:
1895 namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
1896 if namespaces[-1][1] == 0:
1897 debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1898 del namespaces[-1]
1899 if class_ != None:
1900 class_ = (class_[0] , class_[1] + ugly_line.count("{") - ugly_line.count("}"))
1901 if class_[1] == 0:
1902 if class_[0] == None:
1903 debug("\tExiting unknown class", 3)
1904 else:
1905 debug("\tExiting class " + class_[0].name, 3)
1906 class_ = None
1907 private_segment = False
1908 i += 1
1909 else:
1910 i += 1
1911
1912 def debug(message, level):
1913 if level <= debug.debug_level:
1914 print(message)
1915
1916 def expand_function(f):
1917 fun_list = []
1918 arg_list = []
1919 for arg in f.args:
1920 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")):
1921 fi = copy.deepcopy(f)
1922 fi.args = copy.deepcopy(arg_list)
1923 fun_list.append(fi)
1924 arg_list.append(arg)
1925 fun_list.append(f)
1926 return fun_list
1927
1928 def expand_functions():
1929 global unowned_functions
1930 new_funs = []
1931 for fun in unowned_functions:
1932 new_funs.extend(expand_function(fun))
1933 unowned_functions = new_funs
1934 for source in sources:
1935 for class_ in source.classes:
1936 new_funs = []
1937 for fun in class_.found_funs:
1938 new_funs.extend(expand_function(fun))
1939 class_.found_funs = new_funs
1940
1941 def clean_duplicates():
1942 for source in sources:
1943 for class_ in source.classes:
1944 known_decls = {}
1945 for fun in class_.found_funs:
1946 if fun.gen_decl_hash_py() in known_decls:
1947 debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
1948 other = known_decls[fun.gen_decl_hash_py()]
1949 other.gen_alias()
1950 fun.gen_alias()
1951 if fun.gen_decl_hash_py() == other.gen_decl_hash_py():
1952 fun.duplicate = True
1953 debug("Disabled \"" + fun.gen_decl_hash_py() + "\"", 3)
1954 else:
1955 known_decls[fun.gen_decl_hash_py()] = fun
1956 known_decls = []
1957 for con in class_.found_constrs:
1958 if con.gen_decl_hash_py() in known_decls:
1959 debug("Multiple declarations of " + con.gen_decl_hash_py(),3)
1960 con.duplicate = True
1961 else:
1962 known_decls.append(con.gen_decl_hash_py())
1963 known_decls = []
1964 for fun in unowned_functions:
1965 if fun.gen_decl_hash_py() in known_decls:
1966 debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
1967 fun.duplicate = True
1968 else:
1969 known_decls.append(fun.gen_decl_hash_py())
1970
1971 def gen_wrappers(filename, debug_level_ = 0):
1972 debug.debug_level = debug_level_
1973 for source in sources:
1974 parse_header(source)
1975
1976 expand_functions()
1977 clean_duplicates()
1978
1979 import shutil
1980 import math
1981 col = shutil.get_terminal_size((80,20)).columns
1982 debug("-"*col, 1)
1983 debug("-"*math.floor((col-7)/2)+"SUMMARY"+"-"*math.ceil((col-7)/2), 1)
1984 debug("-"*col, 1)
1985 for source in sources:
1986 for class_ in source.classes:
1987 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)
1988 if len(class_.found_constrs) == 0:
1989 class_.found_constrs.append(WConstructor(source.name, class_))
1990 debug(str(len(unowned_functions)) + " functions are unowned", 1)
1991 for enum in enums:
1992 debug("Enum " + assure_length(enum.name, len(max(enum_names, key=len)), True) + " contains " + assure_length(str(len(enum.values)), 2, False) + " values", 1)
1993 debug("-"*col, 1)
1994 wrapper_file = open(filename, "w+")
1995 wrapper_file.write(
1996 """/*
1997 * yosys -- Yosys Open SYnthesis Suite
1998 *
1999 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
2000 *
2001 * Permission to use, copy, modify, and/or distribute this software for any
2002 * purpose with or without fee is hereby granted, provided that the above
2003 * copyright notice and this permission notice appear in all copies.
2004 *
2005 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
2006 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
2007 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
2008 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
2009 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
2010 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
2011 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2012 *
2013 * This is a generated file and can be overwritten by make
2014 */
2015
2016 #ifdef WITH_PYTHON
2017 """)
2018 for source in sources:
2019 wrapper_file.write("#include \""+source.name+".h\"\n")
2020 wrapper_file.write("""
2021 #include <boost/python/module.hpp>
2022 #include <boost/python/class.hpp>
2023 #include <boost/python/wrapper.hpp>
2024 #include <boost/python/call.hpp>
2025 #include <boost/python.hpp>
2026
2027 USING_YOSYS_NAMESPACE
2028
2029 namespace YOSYS_PYTHON {
2030 """)
2031
2032 for source in sources:
2033 for wclass in source.classes:
2034 wrapper_file.write("\n\tstruct " + wclass.name + ";")
2035
2036 wrapper_file.write("\n")
2037
2038 for source in sources:
2039 for wclass in source.classes:
2040 wrapper_file.write(wclass.gen_decl(source.name))
2041
2042 wrapper_file.write("\n")
2043
2044 for source in sources:
2045 for wclass in source.classes:
2046 wrapper_file.write(wclass.gen_funs(source.name))
2047
2048 for fun in unowned_functions:
2049 wrapper_file.write(fun.gen_def())
2050
2051 wrapper_file.write(""" struct Initializer
2052 {
2053 Initializer() {
2054 if(!Yosys::yosys_already_setup())
2055 {
2056 Yosys::log_streams.push_back(&std::cout);
2057 Yosys::log_error_stderr = true;
2058 Yosys::yosys_setup();
2059 }
2060 }
2061
2062 Initializer(Initializer const &) {}
2063
2064 ~Initializer() {
2065 Yosys::yosys_shutdown();
2066 }
2067 };
2068
2069 BOOST_PYTHON_MODULE(libyosys)
2070 {
2071 using namespace boost::python;
2072
2073 class_<Initializer>("Initializer");
2074 scope().attr("_hidden") = new Initializer();
2075 """)
2076
2077 for enum in enums:
2078 wrapper_file.write(enum.gen_boost_py())
2079
2080 for source in sources:
2081 for wclass in source.classes:
2082 wrapper_file.write(wclass.gen_boost_py())
2083
2084 for fun in unowned_functions:
2085 wrapper_file.write(fun.gen_boost_py())
2086
2087 wrapper_file.write("\n\t}\n}\n#endif")
2088
2089 def print_includes():
2090 for source in sources:
2091 print(source.name + ".pyh")