Merge pull request #1662 from YosysHQ/dave/opt-reduce-move-check
[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 if candidate.name == "void":
257 return None
258 cont.args.append(candidate)
259 return cont
260
261 #Translators between Python and C++ containers
262 #Base Type
263 class Translator:
264 tmp_cntr = 0
265 typename = "DefaultType"
266 orig_name = "DefaultCpp"
267
268 @classmethod
269 def gen_type(c, types):
270 return "\nImplement a function that outputs the c++ type of this container here\n"
271
272 @classmethod
273 def translate(c, varname, types, prefix):
274 return "\nImplement a function translating a python container to a c++ container here\n"
275
276 @classmethod
277 def translate_cpp(c, varname, types, prefix, ref):
278 return "\nImplement a function translating a c++ container to a python container here\n"
279
280 #Translates list-types (vector, pool, set), that only differ in their name and
281 #the name of the insertion function
282 class PythonListTranslator(Translator):
283 typename = "boost::python::list"
284 insert_name = "Default"
285
286 #generate the c++ type string
287 @classmethod
288 def gen_type(c, types):
289 text = c.orig_name + "<"
290 if types[0].name in primitive_types:
291 text += types[0].name
292 elif types[0].name in known_containers:
293 text += known_containers[types[0].name].gen_type(types[0].cont.args)
294 else:
295 text += class_by_name(types[0].name).namespace + "::" + types[0].name
296 if types[0].attr_type == attr_types.star:
297 text += "*"
298 text += ">"
299 return text
300
301 #Generate C++ code to translate from a boost::python::list
302 @classmethod
303 def translate(c, varname, types, prefix):
304 text = prefix + c.gen_type(types) + " " + varname + "___tmp;"
305 cntr_name = "cntr_" + str(Translator.tmp_cntr)
306 Translator.tmp_cntr = Translator.tmp_cntr + 1
307 text += prefix + "for(int " + cntr_name + " = 0; " + cntr_name + " < len(" + varname + "); " + cntr_name + "++)"
308 text += prefix + "{"
309 tmp_name = "tmp_" + str(Translator.tmp_cntr)
310 Translator.tmp_cntr = Translator.tmp_cntr + 1
311 if types[0].name in known_containers:
312 text += prefix + "\t" + known_containers[types[0].name].typename + " " + tmp_name + " = boost::python::extract<" + known_containers[types[0].name].typename + ">(" + varname + "[" + cntr_name + "]);"
313 text += known_containers[types[0].name].translate(tmp_name, types[0].cont.args, prefix+"\t")
314 tmp_name = tmp_name + "___tmp"
315 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(" + tmp_name + ");"
316 elif types[0].name in classnames:
317 text += prefix + "\t" + types[0].name + "* " + tmp_name + " = boost::python::extract<" + types[0].name + "*>(" + varname + "[" + cntr_name + "]);"
318 if types[0].attr_type == attr_types.star:
319 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(" + tmp_name + "->get_cpp_obj());"
320 else:
321 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(*" + tmp_name + "->get_cpp_obj());"
322 else:
323 text += prefix + "\t" + types[0].name + " " + tmp_name + " = boost::python::extract<" + types[0].name + ">(" + varname + "[" + cntr_name + "]);"
324 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(" + tmp_name + ");"
325 text += prefix + "}"
326 return text
327
328 #Generate C++ code to translate to a boost::python::list
329 @classmethod
330 def translate_cpp(c, varname, types, prefix, ref):
331 text = prefix + c.typename + " " + varname + "___tmp;"
332 tmp_name = "tmp_" + str(Translator.tmp_cntr)
333 Translator.tmp_cntr = Translator.tmp_cntr + 1
334 if ref:
335 text += prefix + "for(auto " + tmp_name + " : *" + varname + ")"
336 else:
337 text += prefix + "for(auto " + tmp_name + " : " + varname + ")"
338 text += prefix + "{"
339 if types[0].name in classnames:
340 if types[0].attr_type == attr_types.star:
341 text += prefix + "\t" + varname + "___tmp.append(" + types[0].name + "::get_py_obj(" + tmp_name + "));"
342 else:
343 text += prefix + "\t" + varname + "___tmp.append(*" + types[0].name + "::get_py_obj(&" + tmp_name + "));"
344 elif types[0].name in known_containers:
345 text += known_containers[types[0].name].translate_cpp(tmp_name, types[0].cont.args, prefix + "\t", types[0].attr_type == attr_types.star)
346 text += prefix + "\t" + varname + "___tmp.append(" + tmp_name + "___tmp);"
347 else:
348 text += prefix + "\t" + varname + "___tmp.append(" + tmp_name + ");"
349 text += prefix + "}"
350 return text
351
352 #Sub-type for std::set
353 class SetTranslator(PythonListTranslator):
354 insert_name = "insert"
355 orig_name = "std::set"
356
357 #Sub-type for std::vector
358 class VectorTranslator(PythonListTranslator):
359 insert_name = "push_back"
360 orig_name = "std::vector"
361
362 #Sub-type for pool
363 class PoolTranslator(PythonListTranslator):
364 insert_name = "insert"
365 orig_name = "pool"
366
367 #Translates dict-types (dict, std::map), that only differ in their name and
368 #the name of the insertion function
369 class PythonDictTranslator(Translator):
370 typename = "boost::python::dict"
371 insert_name = "Default"
372
373 @classmethod
374 def gen_type(c, types):
375 text = c.orig_name + "<"
376 if types[0].name in primitive_types:
377 text += types[0].name
378 elif types[0].name in known_containers:
379 text += known_containers[types[0].name].gen_type(types[0].cont.args)
380 else:
381 text += class_by_name(types[0].name).namespace + "::" + types[0].name
382 if types[0].attr_type == attr_types.star:
383 text += "*"
384 text += ", "
385 if types[1].name in primitive_types:
386 text += types[1].name
387 elif types[1].name in known_containers:
388 text += known_containers[types[1].name].gen_type(types[1].cont.args)
389 else:
390 text += class_by_name(types[1].name).namespace + "::" + types[1].name
391 if types[1].attr_type == attr_types.star:
392 text += "*"
393 text += ">"
394 return text
395
396 #Generate c++ code to translate from a boost::python::dict
397 @classmethod
398 def translate(c, varname, types, prefix):
399 text = prefix + c.gen_type(types) + " " + varname + "___tmp;"
400 text += prefix + "boost::python::list " + varname + "_keylist = " + varname + ".keys();"
401 cntr_name = "cntr_" + str(Translator.tmp_cntr)
402 Translator.tmp_cntr = Translator.tmp_cntr + 1
403 text += prefix + "for(int " + cntr_name + " = 0; " + cntr_name + " < len(" + varname + "_keylist); " + cntr_name + "++)"
404 text += prefix + "{"
405 key_tmp_name = "key_tmp_" + str(Translator.tmp_cntr)
406 val_tmp_name = "val_tmp_" + str(Translator.tmp_cntr)
407 Translator.tmp_cntr = Translator.tmp_cntr + 1
408
409 if types[0].name in known_containers:
410 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 + " ]);"
411 text += known_containers[types[0].name].translate(key_tmp_name, types[0].cont.args, prefix+"\t")
412 key_tmp_name = key_tmp_name + "___tmp"
413 elif types[0].name in classnames:
414 text += prefix + "\t" + types[0].name + "* " + key_tmp_name + " = boost::python::extract<" + types[0].name + "*>(" + varname + "_keylist[ " + cntr_name + " ]);"
415 else:
416 text += prefix + "\t" + types[0].name + " " + key_tmp_name + " = boost::python::extract<" + types[0].name + ">(" + varname + "_keylist[ " + cntr_name + " ]);"
417
418 if types[1].name in known_containers:
419 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 + " ]]);"
420 text += known_containers[types[1].name].translate(val_tmp_name, types[1].cont.args, prefix+"\t")
421 val_tmp_name = val_tmp_name + "___tmp"
422 elif types[1].name in classnames:
423 text += prefix + "\t" + types[1].name + "* " + val_tmp_name + " = boost::python::extract<" + types[1].name + "*>(" + varname + "[" + varname + "_keylist[ " + cntr_name + " ]]);"
424 else:
425 text += prefix + "\t" + types[1].name + " " + val_tmp_name + " = boost::python::extract<" + types[1].name + ">(" + varname + "[" + varname + "_keylist[ " + cntr_name + " ]]);"
426
427 text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(std::pair<" + types[0].gen_text_cpp() + ", " + types[1].gen_text_cpp() + ">("
428
429 if types[0].name not in classnames:
430 text += key_tmp_name
431 else:
432 if types[0].attr_type != attr_types.star:
433 text += "*"
434 text += key_tmp_name + "->get_cpp_obj()"
435
436 text += ", "
437 if types[1].name not in classnames:
438 text += val_tmp_name
439 else:
440 if types[1].attr_type != attr_types.star:
441 text += "*"
442 text += val_tmp_name + "->get_cpp_obj()"
443 text += "));\n" + prefix + "}"
444 return text
445
446 #Generate c++ code to translate to a boost::python::dict
447 @classmethod
448 def translate_cpp(c, varname, types, prefix, ref):
449 text = prefix + c.typename + " " + varname + "___tmp;"
450 tmp_name = "tmp_" + str(Translator.tmp_cntr)
451 Translator.tmp_cntr = Translator.tmp_cntr + 1
452 if ref:
453 text += prefix + "for(auto " + tmp_name + " : *" + varname + ")"
454 else:
455 text += prefix + "for(auto " + tmp_name + " : " + varname + ")"
456 text += prefix + "{"
457 if types[1].name in known_containers:
458 text += prefix + "\tauto " + tmp_name + "_second = " + tmp_name + ".second;"
459 text += known_containers[types[1].name].translate_cpp(tmp_name + "_second", types[1].cont.args, prefix + "\t", types[1].attr_type == attr_types.star)
460
461 if types[0].name in classnames:
462 text += prefix + "\t" + varname + "___tmp[" + types[0].name + "::get_py_obj(" + tmp_name + ".first)] = "
463 elif types[0].name not in known_containers:
464 text += prefix + "\t" + varname + "___tmp[" + tmp_name + ".first] = "
465
466 if types[1].name in classnames:
467 if types[1].attr_type == attr_types.star:
468 text += types[1].name + "::get_py_obj(" + tmp_name + ".second);"
469 else:
470 text += "*" + types[1].name + "::get_py_obj(&" + tmp_name + ".second);"
471 elif types[1].name in known_containers:
472 text += tmp_name + "_second___tmp;"
473 else:
474 text += tmp_name + ".second;"
475 text += prefix + "}"
476 return text
477
478 #Sub-type for dict
479 class DictTranslator(PythonDictTranslator):
480 insert_name = "insert"
481 orig_name = "dict"
482
483 #Sub_type for std::map
484 class MapTranslator(PythonDictTranslator):
485 insert_name = "insert"
486 orig_name = "std::map"
487
488 #Translator for std::pair. Derived from PythonDictTranslator because the
489 #gen_type function is the same (because both have two template parameters)
490 class TupleTranslator(PythonDictTranslator):
491 typename = "boost::python::tuple"
492 orig_name = "std::pair"
493
494 #Generate c++ code to translate from a boost::python::tuple
495 @classmethod
496 def translate(c, varname, types, prefix):
497 text = prefix + types[0].name + " " + varname + "___tmp_0 = boost::python::extract<" + types[0].name + ">(" + varname + "[0]);"
498 text += prefix + types[1].name + " " + varname + "___tmp_1 = boost::python::extract<" + types[1].name + ">(" + varname + "[1]);"
499 text += prefix + TupleTranslator.gen_type(types) + " " + varname + "___tmp("
500 if types[0].name.split(" ")[-1] in primitive_types:
501 text += varname + "___tmp_0, "
502 else:
503 text += varname + "___tmp_0.get_cpp_obj(), "
504 if types[1].name.split(" ")[-1] in primitive_types:
505 text += varname + "___tmp_1);"
506 else:
507 text += varname + "___tmp_1.get_cpp_obj());"
508 return text
509
510 #Generate c++ code to translate to a boost::python::tuple
511 @classmethod
512 def translate_cpp(c, varname, types, prefix, ref):
513 # if the tuple is a pair of SigSpecs (aka SigSig), then we need
514 # to call get_py_obj() on each item in the tuple
515 if types[0].name in classnames:
516 first_var = types[0].name + "::get_py_obj(" + varname + ".first)"
517 else:
518 first_var = varname + ".first"
519 if types[1].name in classnames:
520 second_var = types[1].name + "::get_py_obj(" + varname + ".second)"
521 else:
522 second_var = varname + ".second"
523 text = prefix + TupleTranslator.typename + " " + varname + "___tmp = boost::python::make_tuple(" + first_var + ", " + second_var + ");"
524 return text
525
526 #Associate the Translators with their c++ type
527 known_containers = {
528 "std::set" : SetTranslator,
529 "std::vector" : VectorTranslator,
530 "pool" : PoolTranslator,
531 "dict" : DictTranslator,
532 "std::pair" : TupleTranslator,
533 "std::map" : MapTranslator
534 }
535
536 class Attribute:
537 wtype = None
538 varname = None
539 is_const = False
540 default_value = None
541 pos = None
542 pos_counter = 0
543
544 def __init__(self, wtype, varname, is_const = False, default_value = None):
545 self.wtype = wtype
546 self.varname = varname
547 self.is_const = is_const
548 self.default_value = None
549 self.container = None
550
551 @staticmethod
552 def from_string(str_def, containing_file, line_number):
553 if len(str_def) < 3:
554 return None
555 orig = str_def
556 arg = Attribute(None, None)
557 prefix = ""
558 arg.wtype = None
559 arg.varname = None
560 arg.is_const = False
561 arg.default_value = None
562 arg.container = None
563 if str.startswith(str_def, "const "):
564 arg.is_const = True
565 str_def = str_def[6:]
566 if str.startswith(str_def, "unsigned "):
567 prefix = "unsigned "
568 str_def = str_def[9:]
569 while str.startswith(str_def, "long "):
570 prefix= "long " + prefix
571 str_def = str_def[5:]
572 while str.startswith(str_def, "short "):
573 prefix = "short " + prefix
574 str_def = str_def[6:]
575
576 if str_def.find("<") != -1 and str_def.find("<") < str_def.find(" "):
577 closing = find_closing(str_def[str_def.find("<"):], "<", ">") + str_def.find("<") + 1
578 arg.wtype = WType.from_string(str_def[:closing].strip(), containing_file, line_number)
579 str_def = str_def[closing+1:]
580 else:
581 if str_def.count(" ") > 0:
582 arg.wtype = WType.from_string(prefix + str_def[:str_def.find(" ")].strip(), containing_file, line_number)
583 str_def = str_def[str_def.find(" ")+1:]
584 else:
585 arg.wtype = WType.from_string(prefix + str_def.strip(), containing_file, line_number)
586 str_def = ""
587 arg.varname = ""
588
589 if arg.wtype == None:
590 return None
591 if str_def.count("=") == 0:
592 arg.varname = str_def.strip()
593 if arg.varname.find(" ") > 0:
594 return None
595 else:
596 arg.varname = str_def[:str_def.find("=")].strip()
597 if arg.varname.find(" ") > 0:
598 return None
599 str_def = str_def[str_def.find("=")+1:].strip()
600 arg.default_value = str_def[arg.varname.find("=")+1:].strip()
601 if len(arg.varname) == 0:
602 arg.varname = None
603 return arg
604 if arg.varname[0] == '*':
605 arg.wtype.attr_type = attr_types.star
606 arg.varname = arg.varname[1:]
607 elif arg.varname[0] == '&':
608 if arg.wtype.attr_type != attr_types.default:
609 return None
610 if arg.varname[1] == '&':
611 arg.wtype.attr_type = attr_types.ampamp
612 arg.varname = arg.varname[2:]
613 else:
614 arg.wtype.attr_type = attr_types.amp
615 arg.varname = arg.varname[1:]
616 return arg
617
618 #Generates the varname. If the attribute has no name in the header file,
619 #a name is generated
620 def gen_varname(self):
621 if self.varname != None:
622 return self.varname
623 if self.wtype.name == "void":
624 return ""
625 if self.pos == None:
626 self.pos = Attribute.pos_counter
627 Attribute.pos_counter = Attribute.pos_counter + 1
628 return "gen_varname_" + str(self.pos)
629
630 #Generates the text for the function headers with wrapper types
631 def gen_listitem(self):
632 prefix = ""
633 if self.is_const:
634 prefix = "const "
635 if self.wtype.name in classnames:
636 return prefix + self.wtype.name + "* " + self.gen_varname()
637 if self.wtype.name in known_containers:
638 return prefix + known_containers[self.wtype.name].typename + " " + self.gen_varname()
639 return prefix + self.wtype.name + " " + self.gen_varname()
640
641 #Generates the test for the function headers with c++ types
642 def gen_listitem_cpp(self):
643 prefix = ""
644 if self.is_const:
645 prefix = "const "
646 infix = ""
647 if self.wtype.attr_type == attr_types.star:
648 infix = "*"
649 elif self.wtype.attr_type == attr_types.amp:
650 infix = "&"
651 elif self.wtype.attr_type == attr_types.ampamp:
652 infix = "&&"
653 if self.wtype.name in known_containers:
654 return prefix + known_containers[self.wtype.name].gen_type(self.wtype.cont.args) + " " + infix + self.gen_varname()
655 if self.wtype.name in classnames:
656 return prefix + class_by_name(self.wtype.name).namespace + "::" + self.wtype.name + " " + infix + self.gen_varname()
657 return prefix + self.wtype.name + " " + infix + self.gen_varname()
658
659 #Generates the listitem withtout the varname, so the signature can be
660 #compared
661 def gen_listitem_hash(self):
662 prefix = ""
663 if self.is_const:
664 prefix = "const "
665 if self.wtype.name in classnames:
666 return prefix + self.wtype.name + "* "
667 if self.wtype.name in known_containers:
668 return known_containers[self.wtype.name].typename
669 return prefix + self.wtype.name
670
671 #Generate Translation code for the attribute
672 def gen_translation(self):
673 if self.wtype.name in known_containers:
674 return known_containers[self.wtype.name].translate(self.gen_varname(), self.wtype.cont.args, "\n\t\t")
675 return ""
676
677 #Generate Translation code from c++ for the attribute
678 def gen_translation_cpp(self):
679 if self.wtype.name in known_containers:
680 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)
681 return ""
682
683 #Generate Text for the call
684 def gen_call(self):
685 ret = self.gen_varname()
686 if self.wtype.name in known_containers:
687 if self.wtype.attr_type == attr_types.star:
688 return "&" + ret + "___tmp"
689 return ret + "___tmp"
690 if self.wtype.name in classnames:
691 if self.wtype.attr_type != attr_types.star:
692 ret = "*" + ret
693 return ret + "->get_cpp_obj()"
694 if self.wtype.name == "char *" and self.gen_varname() in ["format", "fmt"]:
695 return "\"%s\", " + self.gen_varname()
696 if self.wtype.attr_type == attr_types.star:
697 return "&" + ret
698 return ret
699
700 def gen_call_cpp(self):
701 ret = self.gen_varname()
702 if self.wtype.name.split(" ")[-1] in primitive_types or self.wtype.name in enum_names:
703 if self.wtype.attr_type == attr_types.star:
704 return "&" + ret
705 return ret
706 if self.wtype.name not in classnames:
707 if self.wtype.attr_type == attr_types.star:
708 return "&" + ret + "___tmp"
709 return ret + "___tmp"
710 if self.wtype.attr_type != attr_types.star:
711 ret = "*" + ret
712 return self.wtype.name + "::get_py_obj(" + self.gen_varname() + ")"
713
714 #Generate cleanup code
715 def gen_cleanup(self):
716 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):
717 return ""
718 return "\n\t\tdelete " + self.gen_varname() + "___tmp;"
719
720 class WClass:
721 name = None
722 namespace = None
723 link_type = None
724 id_ = None
725 string_id = None
726 hash_id = None
727 needs_clone = False
728 found_funs = []
729 found_vars = []
730 found_constrs = []
731
732 def __init__(self, name, link_type, id_, string_id = None, hash_id = None, needs_clone = False):
733 self.name = name
734 self.namespace = None
735 self.link_type = link_type
736 self.id_ = id_
737 self.string_id = string_id
738 self.hash_id = hash_id
739 self.needs_clone = needs_clone
740 self.found_funs = []
741 self.found_vars = []
742 self.found_constrs = []
743
744 def printable_constrs(self):
745 ret = 0
746 for con in self.found_constrs:
747 if not con.protected:
748 ret += 1
749 return ret
750
751 def gen_decl(self, filename):
752 long_name = self.namespace + "::" + self.name
753
754 text = "\n\t// WRAPPED from " + filename
755 text += "\n\tstruct " + self.name
756 if self.link_type == link_types.derive:
757 text += " : public " + self.namespace + "::" + self.name
758 text += "\n\t{\n"
759
760 if self.link_type != link_types.derive:
761
762 text += "\t\t" + long_name + "* ref_obj;\n"
763
764 if self.link_type == link_types.ref_copy or self.link_type == link_types.pointer:
765 text += "\n\t\t" + long_name + "* get_cpp_obj() const\n\t\t{\n\t\t\treturn ref_obj;\n\t\t}\n"
766 elif self.link_type == link_types.global_list:
767 text += "\t\t" + self.id_.wtype.name + " " + self.id_.varname + ";\n"
768 text += "\n\t\t" + long_name + "* get_cpp_obj() const\n\t\t{"
769 text += "\n\t\t\t" + long_name + "* ret = " + long_name + "::get_all_" + self.name.lower() + "s()->at(this->" + self.id_.varname + ");"
770 text += "\n\t\t\tif(ret != NULL && ret == this->ref_obj)"
771 text += "\n\t\t\t\treturn ret;"
772 text += "\n\t\t\tthrow std::runtime_error(\"" + self.name + "'s c++ object does not exist anymore.\");"
773 text += "\n\t\t\treturn NULL;"
774 text += "\n\t\t}\n"
775
776 #if self.link_type != link_types.pointer:
777 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + "* ref)\n\t\t{"
778 text += "\n\t\t\tif(ref == nullptr){"
779 text += "\n\t\t\t\tthrow std::runtime_error(\"" + self.name + " does not exist.\");"
780 text += "\n\t\t\t}"
781 text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
782 if self.link_type == link_types.pointer:
783 text += "\n\t\t\tret->ref_obj = ref;"
784 if self.link_type == link_types.ref_copy:
785 if self.needs_clone:
786 text += "\n\t\t\tret->ref_obj = ref->clone();"
787 else:
788 text += "\n\t\t\tret->ref_obj = new "+long_name+"(*ref);"
789 if self.link_type == link_types.global_list:
790 text += "\n\t\t\tret->ref_obj = ref;"
791 text += "\n\t\t\tret->" + self.id_.varname + " = ret->ref_obj->" + self.id_.varname + ";"
792 text += "\n\t\t\treturn ret;"
793 text += "\n\t\t}\n"
794
795 if self.link_type == link_types.ref_copy:
796 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + " ref)\n\t\t{"
797 text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
798 if self.needs_clone:
799 text += "\n\t\t\tret->ref_obj = ref.clone();"
800 else:
801 text += "\n\t\t\tret->ref_obj = new "+long_name+"(ref);"
802 text += "\n\t\t\treturn ret;"
803 text += "\n\t\t}\n"
804
805 for con in self.found_constrs:
806 text += con.gen_decl()
807 for var in self.found_vars:
808 text += var.gen_decl()
809 for fun in self.found_funs:
810 text += fun.gen_decl()
811
812
813 if self.link_type == link_types.derive:
814 duplicates = {}
815 for fun in self.found_funs:
816 if fun.name in duplicates:
817 fun.gen_alias()
818 duplicates[fun.name].gen_alias()
819 else:
820 duplicates[fun.name] = fun
821
822 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"
823 text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + "* ref)\n\t\t{"
824 text += "\n\t\t\treturn (" + self.name + "*)ref;"
825 text += "\n\t\t}\n"
826
827 for con in self.found_constrs:
828 text += con.gen_decl_derive()
829 for var in self.found_vars:
830 text += var.gen_decl()
831 for fun in self.found_funs:
832 text += fun.gen_decl_virtual()
833
834 if self.hash_id != None:
835 text += "\n\t\tunsigned int get_hash_py()"
836 text += "\n\t\t{"
837 text += "\n\t\t\treturn get_cpp_obj()->" + self.hash_id + ";"
838 text += "\n\t\t}"
839
840 text += "\n\t};\n"
841
842 if self.link_type == link_types.derive:
843 text += "\n\tstruct " + self.name + "Wrap : " + self.name + ", boost::python::wrapper<" + self.name + ">"
844 text += "\n\t{"
845
846 for con in self.found_constrs:
847 text += con.gen_decl_wrapperclass()
848 for fun in self.found_funs:
849 text += fun.gen_default_impl()
850
851 text += "\n\t};"
852
853 text += "\n\tstd::ostream &operator<<(std::ostream &ostr, const " + self.name + " &ref)"
854 text += "\n\t{"
855 text += "\n\t\tostr << \"" + self.name
856 if self.string_id != None:
857 text +=" \\\"\""
858 text += " << ref.get_cpp_obj()->" + self.string_id
859 text += " << \"\\\"\""
860 else:
861 text += " at \" << ref.get_cpp_obj()"
862 text += ";"
863 text += "\n\t\treturn ostr;"
864 text += "\n\t}"
865 text += "\n"
866
867 return text
868
869 def gen_funs(self, filename):
870 text = ""
871 if self.link_type != link_types.derive:
872 for con in self.found_constrs:
873 text += con.gen_def()
874 for var in self.found_vars:
875 text += var.gen_def()
876 for fun in self.found_funs:
877 text += fun.gen_def()
878 else:
879 for var in self.found_vars:
880 text += var.gen_def()
881 for fun in self.found_funs:
882 text += fun.gen_def_virtual()
883 return text
884
885 def gen_boost_py_body(self):
886 text = ""
887 if self.printable_constrs() == 0 or not self.contains_default_constr():
888 text += ", no_init"
889 text += ")"
890 text += "\n\t\t\t.def(boost::python::self_ns::str(boost::python::self_ns::self))"
891 text += "\n\t\t\t.def(boost::python::self_ns::repr(boost::python::self_ns::self))"
892 for con in self.found_constrs:
893 text += con.gen_boost_py()
894 for var in self.found_vars:
895 text += var.gen_boost_py()
896 static_funs = []
897 for fun in self.found_funs:
898 text += fun.gen_boost_py()
899 if fun.is_static and fun.alias not in static_funs:
900 static_funs.append(fun.alias)
901 for fun in static_funs:
902 text += "\n\t\t\t.staticmethod(\"" + fun + "\")"
903
904 if self.hash_id != None:
905 text += "\n\t\t\t.def(\"__hash__\", &" + self.name + "::get_hash_py)"
906 text += "\n\t\t\t;\n"
907 return text
908
909 def gen_boost_py(self):
910 body = self.gen_boost_py_body()
911 if self.link_type == link_types.derive:
912 text = "\n\t\tclass_<" + self.name + ">(\"Cpp" + self.name + "\""
913 text += body
914 text += "\n\t\tclass_<" + self.name
915 text += "Wrap, boost::noncopyable"
916 text += ">(\"" + self.name + "\""
917 text += body
918 else:
919 text = "\n\t\tclass_<" + self.name + ">(\"" + self.name + "\""
920 text += body
921 return text
922
923
924 def contains_default_constr(self):
925 for c in self.found_constrs:
926 if len(c.args) == 0:
927 return True
928 return False
929
930 #CONFIGURE HEADER-FILES TO BE PARSED AND CLASSES EXPECTED IN THEM HERE
931
932 sources = [
933 Source("kernel/celltypes",[
934 WClass("CellType", link_types.pointer, None, None, "type.hash()", True),
935 WClass("CellTypes", link_types.pointer, None, None, None, True)
936 ]
937 ),
938 Source("kernel/consteval",[
939 WClass("ConstEval", link_types.pointer, None, None, None, True)
940 ]
941 ),
942 Source("kernel/log",[]),
943 Source("kernel/register",[
944 WClass("Pass", link_types.derive, None, None, None, True),
945 ]
946 ),
947 Source("kernel/rtlil",[
948 WClass("IdString", link_types.ref_copy, None, "str()", "hash()"),
949 WClass("Const", link_types.ref_copy, None, "as_string()", "hash()"),
950 WClass("AttrObject", link_types.ref_copy, None, None, None),
951 WClass("Selection", link_types.ref_copy, None, None, None),
952 WClass("Monitor", link_types.derive, None, None, None),
953 WClass("CaseRule",link_types.ref_copy, None, None, None, True),
954 WClass("SwitchRule",link_types.ref_copy, None, None, None, True),
955 WClass("SyncRule", link_types.ref_copy, None, None, None, True),
956 WClass("Process", link_types.ref_copy, None, "name.c_str()", "name.hash()"),
957 WClass("SigChunk", link_types.ref_copy, None, None, None),
958 WClass("SigBit", link_types.ref_copy, None, None, "hash()"),
959 WClass("SigSpec", link_types.ref_copy, None, None, "hash()"),
960 WClass("Cell", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
961 WClass("Wire", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
962 WClass("Memory", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
963 WClass("Module", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
964 WClass("Design", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "hashidx_", "hash()")
965 ]
966 ),
967 #Source("kernel/satgen",[
968 # ]
969 # ),
970 #Source("libs/ezsat/ezsat",[
971 # ]
972 # ),
973 #Source("libs/ezsat/ezminisat",[
974 # ]
975 # ),
976 Source("kernel/sigtools",[
977 WClass("SigMap", link_types.pointer, None, None, None, True)
978 ]
979 ),
980 Source("kernel/yosys",[
981 ]
982 ),
983 Source("kernel/cost",[])
984 ]
985
986 blacklist_methods = ["YOSYS_NAMESPACE::Pass::run_register", "YOSYS_NAMESPACE::Module::Pow", "YOSYS_NAMESPACE::Module::Bu0", "YOSYS_NAMESPACE::CaseRule::optimize"]
987
988 enum_names = ["State","SyncType","ConstFlags"]
989
990 enums = [] #Do not edit
991 glbls = []
992
993 unowned_functions = []
994
995 classnames = []
996 for source in sources:
997 for wclass in source.classes:
998 classnames.append(wclass.name)
999
1000 def class_by_name(name):
1001 for source in sources:
1002 for wclass in source.classes:
1003 if wclass.name == name:
1004 return wclass
1005 return None
1006
1007 def enum_by_name(name):
1008 for e in enums:
1009 if e.name == name:
1010 return e
1011 return None
1012
1013 def find_closing(text, open_tok, close_tok):
1014 if text.find(open_tok) == -1 or text.find(close_tok) <= text.find(open_tok):
1015 return text.find(close_tok)
1016 return text.find(close_tok) + find_closing(text[text.find(close_tok)+1:], open_tok, close_tok) + 1
1017
1018 def unpretty_string(s):
1019 s = s.strip()
1020 while s.find(" ") != -1:
1021 s = s.replace(" "," ")
1022 while s.find("\t") != -1:
1023 s = s.replace("\t"," ")
1024 s = s.replace(" (","(")
1025 return s
1026
1027 class WEnum:
1028 name = None
1029 namespace = None
1030 values = []
1031
1032 def from_string(str_def, namespace, line_number):
1033 str_def = str_def.strip()
1034 if not str.startswith(str_def, "enum "):
1035 return None
1036 if str_def.count(";") != 1:
1037 return None
1038 str_def = str_def[5:]
1039 enum = WEnum()
1040 split = str_def.split(":")
1041 if(len(split) != 2):
1042 return None
1043 enum.name = split[0].strip()
1044 if enum.name not in enum_names:
1045 return None
1046 str_def = split[1]
1047 if str_def.count("{") != str_def.count("}") != 1:
1048 return None
1049 if len(str_def) < str_def.find("}")+2 or str_def[str_def.find("}")+1] != ';':
1050 return None
1051 str_def = str_def.split("{")[-1].split("}")[0]
1052 enum.values = []
1053 for val in str_def.split(','):
1054 enum.values.append(val.strip().split('=')[0].strip())
1055 enum.namespace = namespace
1056 return enum
1057
1058 def gen_boost_py(self):
1059 text = "\n\t\tenum_<" + self.namespace + "::" + self.name + ">(\"" + self.name + "\")\n"
1060 for value in self.values:
1061 text += "\t\t\t.value(\"" + value + "\"," + self.namespace + "::" + value + ")\n"
1062 text += "\t\t\t;\n"
1063 return text
1064
1065 def __str__(self):
1066 ret = "Enum " + self.namespace + "::" + self.name + "(\n"
1067 for val in self.values:
1068 ret = ret + "\t" + val + "\n"
1069 return ret + ")"
1070
1071 def __repr__(self):
1072 return __str__(self)
1073
1074 class WConstructor:
1075 orig_text = None
1076 args = []
1077 containing_file = None
1078 member_of = None
1079 duplicate = False
1080 protected = False
1081
1082 def __init__(self, containing_file, class_):
1083 self.orig_text = "Auto generated default constructor"
1084 self.args = []
1085 self.containing_file = containing_file
1086 self.member_of = class_
1087 self.protected = False
1088
1089 def from_string(str_def, containing_file, class_, line_number, protected = False):
1090 if class_ == None:
1091 return None
1092 if str_def.count("delete;") > 0:
1093 return None
1094 con = WConstructor(containing_file, class_)
1095 con.orig_text = str_def
1096 con.args = []
1097 con.duplicate = False
1098 con.protected = protected
1099 if str.startswith(str_def, "inline "):
1100 str_def = str_def[7:]
1101 if not str.startswith(str_def, class_.name + "("):
1102 return None
1103 str_def = str_def[len(class_.name)+1:]
1104 found = find_closing(str_def, "(", ")")
1105 if found == -1:
1106 return None
1107 str_def = str_def[0:found].strip()
1108 if len(str_def) == 0:
1109 return con
1110 for arg in split_list(str_def, ","):
1111 parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
1112 if parsed == None:
1113 return None
1114 con.args.append(parsed)
1115 return con
1116
1117 def gen_decl(self):
1118 if self.duplicate or self.protected:
1119 return ""
1120 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1121 text += "\n\t\t" + self.member_of.name + "("
1122 for arg in self.args:
1123 text += arg.gen_listitem() + ", "
1124 if len(self.args) > 0:
1125 text = text[:-2]
1126 text += ");\n"
1127 return text
1128
1129 def gen_decl_derive(self):
1130 if self.duplicate or self.protected:
1131 return ""
1132 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1133 text += "\n\t\t" + self.member_of.name + "("
1134 for arg in self.args:
1135 text += arg.gen_listitem() + ", "
1136 if len(self.args) > 0:
1137 text = text[:-2]
1138 text += ")"
1139 if len(self.args) == 0:
1140 return text + "{}"
1141 text += " : "
1142 text += self.member_of.namespace + "::" + self.member_of.name + "("
1143 for arg in self.args:
1144 text += arg.gen_call() + ", "
1145 if len(self.args) > 0:
1146 text = text[:-2]
1147 text += "){}\n"
1148 return text
1149
1150 def gen_decl_wrapperclass(self):
1151 if self.duplicate or self.protected:
1152 return ""
1153 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1154 text += "\n\t\t" + self.member_of.name + "Wrap("
1155 for arg in self.args:
1156 text += arg.gen_listitem() + ", "
1157 if len(self.args) > 0:
1158 text = text[:-2]
1159 text += ")"
1160 if len(self.args) == 0:
1161 return text + "{}"
1162 text += " : "
1163 text += self.member_of.name + "("
1164 for arg in self.args:
1165 text += arg.gen_call() + ", "
1166 if len(self.args) > 0:
1167 text = text[:-2]
1168 text += "){}\n"
1169 return text
1170
1171 def gen_decl_hash_py(self):
1172 text = self.member_of.name + "("
1173 for arg in self.args:
1174 text += arg.gen_listitem_hash() + ", "
1175 if len(self.args) > 0:
1176 text = text[:-2]
1177 text += ");"
1178 return text
1179
1180 def gen_def(self):
1181 if self.duplicate or self.protected:
1182 return ""
1183 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1184 text += "\n\t" + self.member_of.name + "::" + self.member_of.name + "("
1185 for arg in self.args:
1186 text += arg.gen_listitem() + ", "
1187 if len(self.args) > 0:
1188 text = text[:-2]
1189 text +=")\n\t{"
1190 for arg in self.args:
1191 text += arg.gen_translation()
1192 if self.member_of.link_type != link_types.derive:
1193 text += "\n\t\tthis->ref_obj = new " + self.member_of.namespace + "::" + self.member_of.name + "("
1194 for arg in self.args:
1195 text += arg.gen_call() + ", "
1196 if len(self.args) > 0:
1197 text = text[:-2]
1198 if self.member_of.link_type != link_types.derive:
1199 text += ");"
1200 if self.member_of.link_type == link_types.global_list:
1201 text += "\n\t\tthis->" + self.member_of.id_.varname + " = this->ref_obj->" + self.member_of.id_.varname + ";"
1202 for arg in self.args:
1203 text += arg.gen_cleanup()
1204 text += "\n\t}\n"
1205 return text
1206
1207 def gen_boost_py(self):
1208 if self.duplicate or self.protected or len(self.args) == 0:
1209 return ""
1210 text = "\n\t\t\t.def(init"
1211 text += "<"
1212 for a in self.args:
1213 text += a.gen_listitem_hash() + ", "
1214 text = text[0:-2] + ">())"
1215 return text
1216
1217 class WFunction:
1218 orig_text = None
1219 is_static = False
1220 is_inline = False
1221 is_virtual = False
1222 ret_attr_type = attr_types.default
1223 is_operator = False
1224 ret_type = None
1225 name = None
1226 alias = None
1227 args = []
1228 containing_file = None
1229 member_of = None
1230 duplicate = False
1231 namespace = ""
1232
1233 def from_string(str_def, containing_file, class_, line_number, namespace):
1234 if str_def.count("delete;") > 0:
1235 return None
1236 func = WFunction()
1237 func.is_static = False
1238 func.is_inline = False
1239 func.is_virtual = False
1240 func.ret_attr_type = attr_types.default
1241 func.is_operator = False
1242 func.member_of = None
1243 func.orig_text = str_def
1244 func.args = []
1245 func.containing_file = containing_file
1246 func.member_of = class_
1247 func.duplicate = False
1248 func.namespace = namespace
1249 str_def = str_def.replace("operator ","operator")
1250 if str.startswith(str_def, "static "):
1251 func.is_static = True
1252 str_def = str_def[7:]
1253 else:
1254 func.is_static = False
1255 if str.startswith(str_def, "inline "):
1256 func.is_inline = True
1257 str_def = str_def[7:]
1258 else:
1259 func.is_inline = False
1260 if str.startswith(str_def, "virtual "):
1261 func.is_virtual = True
1262 str_def = str_def[8:]
1263 else:
1264 func.is_virtual = False
1265
1266 if str_def.count(" ") == 0:
1267 return None
1268
1269 parts = split_list(str_def.strip(), " ")
1270
1271 prefix = ""
1272 i = 0
1273 for part in parts:
1274 if part in ["unsigned", "long", "short"]:
1275 prefix += part + " "
1276 i += 1
1277 else:
1278 break
1279 parts = parts[i:]
1280
1281 if len(parts) <= 1:
1282 return None
1283
1284 func.ret_type = WType.from_string(prefix + parts[0], containing_file, line_number)
1285
1286 if func.ret_type == None:
1287 return None
1288
1289 str_def = parts[1]
1290 for part in parts[2:]:
1291 str_def = str_def + " " + part
1292
1293 found = str_def.find("(")
1294 if found == -1 or (str_def.find(" ") != -1 and found > str_def.find(" ")):
1295 return None
1296 func.name = str_def[:found]
1297 str_def = str_def[found:]
1298 if func.name.find("operator") != -1 and str.startswith(str_def, "()("):
1299 func.name += "()"
1300 str_def = str_def[2:]
1301 str_def = str_def[1:]
1302 if func.name.find("operator") != -1:
1303 func.is_operator = True
1304 if func.name.find("*") == 0:
1305 func.name = func.name.replace("*", "")
1306 func.ret_type.attr_type = attr_types.star
1307 if func.name.find("&&") == 0:
1308 func.name = func.name.replace("&&", "")
1309 func.ret_type.attr_type = attr_types.ampamp
1310 if func.name.find("&") == 0:
1311 func.name = func.name.replace("&", "")
1312 func.ret_type.attr_type = attr_types.amp
1313
1314 found = find_closing(str_def, "(", ")")
1315 if found == -1:
1316 return None
1317 str_def = str_def[0:found]
1318 if func.name in blacklist_methods:
1319 return None
1320 if func.namespace != None and func.namespace != "":
1321 if (func.namespace + "::" + func.name) in blacklist_methods:
1322 return None
1323 if func.member_of != None:
1324 if (func.namespace + "::" + func.member_of.name + "::" + func.name) in blacklist_methods:
1325 return None
1326 if func.is_operator and func.name.replace(" ","").replace("operator","").split("::")[-1] not in wrappable_operators:
1327 return None
1328
1329 testname = func.name
1330 if func.is_operator:
1331 testname = testname[:testname.find("operator")]
1332 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:
1333 return None
1334
1335 func.alias = func.name
1336 if func.name in keyword_aliases:
1337 func.alias = keyword_aliases[func.name]
1338 str_def = str_def[:found].strip()
1339 if(len(str_def) == 0):
1340 return func
1341 for arg in split_list(str_def, ","):
1342 if arg.strip() == "...":
1343 continue
1344 parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
1345 if parsed == None:
1346 return None
1347 func.args.append(parsed)
1348 return func
1349
1350 def gen_alias(self):
1351 self.alias = self.name
1352 for arg in self.args:
1353 self.alias += "__" + arg.wtype.gen_text_cpp().replace("::", "_").replace("<","_").replace(">","_").replace(" ","").replace("*","").replace(",","")
1354
1355 def gen_decl(self):
1356 if self.duplicate:
1357 return ""
1358 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1359 text += "\n\t\t"
1360 if self.is_static:
1361 text += "static "
1362 text += self.ret_type.gen_text() + " " + self.alias + "("
1363 for arg in self.args:
1364 text += arg.gen_listitem()
1365 text += ", "
1366 if len(self.args) > 0:
1367 text = text[:-2]
1368 text += ");\n"
1369 return text
1370
1371 def gen_decl_virtual(self):
1372 if self.duplicate:
1373 return ""
1374 if not self.is_virtual:
1375 return self.gen_decl()
1376 text = "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1377 text += "\n\t\tvirtual "
1378 if self.is_static:
1379 text += "static "
1380 text += self.ret_type.gen_text() + " py_" + self.alias + "("
1381 for arg in self.args:
1382 text += arg.gen_listitem()
1383 text += ", "
1384 if len(self.args) > 0:
1385 text = text[:-2]
1386 text += ")"
1387 if len(self.args) == 0:
1388 text += "{}"
1389 else:
1390 text += "\n\t\t{"
1391 for arg in self.args:
1392 text += "\n\t\t\t(void)" + arg.gen_varname() + ";"
1393 text += "\n\t\t}\n"
1394 text += "\n\t\tvirtual "
1395 if self.is_static:
1396 text += "static "
1397 text += self.ret_type.gen_text() + " " + self.name + "("
1398 for arg in self.args:
1399 text += arg.gen_listitem_cpp()
1400 text += ", "
1401 if len(self.args) > 0:
1402 text = text[:-2]
1403 text += ") YS_OVERRIDE;\n"
1404 return text
1405
1406 def gen_decl_hash_py(self):
1407 text = self.ret_type.gen_text() + " " + self.alias + "("
1408 for arg in self.args:
1409 text += arg.gen_listitem_hash() + ", "
1410 if len(self.args) > 0:
1411 text = text[:-2]
1412 text += ");"
1413 return text
1414
1415 def gen_def(self):
1416 if self.duplicate:
1417 return ""
1418 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1419 text += "\n\t" + self.ret_type.gen_text() + " "
1420 if self.member_of != None:
1421 text += self.member_of.name + "::"
1422 text += self.alias + "("
1423 for arg in self.args:
1424 text += arg.gen_listitem()
1425 text += ", "
1426 if len(self.args) > 0:
1427 text = text[:-2]
1428 text +=")\n\t{"
1429 for arg in self.args:
1430 text += arg.gen_translation()
1431 text += "\n\t\t"
1432 if self.ret_type.name != "void":
1433 if self.ret_type.name in known_containers:
1434 text += self.ret_type.gen_text_cpp()
1435 else:
1436 text += self.ret_type.gen_text()
1437 if self.ret_type.name in classnames or (self.ret_type.name in known_containers and self.ret_type.attr_type == attr_types.star):
1438 text += "*"
1439 text += " ret_ = "
1440 if self.ret_type.name in classnames:
1441 text += self.ret_type.name + "::get_py_obj("
1442 if self.member_of == None:
1443 text += "::" + self.namespace + "::" + self.alias + "("
1444 elif self.is_static:
1445 text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
1446 else:
1447 text += "this->get_cpp_obj()->" + self.name + "("
1448 for arg in self.args:
1449 text += arg.gen_call() + ", "
1450 if len(self.args) > 0:
1451 text = text[:-2]
1452 if self.ret_type.name in classnames:
1453 text += ")"
1454 text += ");"
1455 for arg in self.args:
1456 text += arg.gen_cleanup()
1457 if self.ret_type.name != "void":
1458 if self.ret_type.name in classnames:
1459 text += "\n\t\treturn *ret_;"
1460 elif self.ret_type.name in known_containers:
1461 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)
1462 text += "\n\t\treturn ret____tmp;"
1463 else:
1464 text += "\n\t\treturn ret_;"
1465 text += "\n\t}\n"
1466 return text
1467
1468 def gen_def_virtual(self):
1469 if self.duplicate:
1470 return ""
1471 if not self.is_virtual:
1472 return self.gen_def()
1473 text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
1474 text += "\n\t"
1475 if self.is_static:
1476 text += "static "
1477 text += self.ret_type.gen_text() + " " + self.member_of.name + "::" + self.name + "("
1478 for arg in self.args:
1479 text += arg.gen_listitem_cpp()
1480 text += ", "
1481 if len(self.args) > 0:
1482 text = text[:-2]
1483 text += ")\n\t{"
1484 for arg in self.args:
1485 text += arg.gen_translation_cpp()
1486 text += "\n\t\t"
1487 if self.member_of == None:
1488 text += "::" + self.namespace + "::" + self.alias + "("
1489 elif self.is_static:
1490 text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
1491 else:
1492 text += "py_" + self.alias + "("
1493 for arg in self.args:
1494 text += arg.gen_call_cpp() + ", "
1495 if len(self.args) > 0:
1496 text = text[:-2]
1497 if self.ret_type.name in classnames:
1498 text += ")"
1499 text += ");"
1500 for arg in self.args:
1501 text += arg.gen_cleanup()
1502 text += "\n\t}\n"
1503 return text
1504
1505 def gen_default_impl(self):
1506 if self.duplicate:
1507 return ""
1508 if not self.is_virtual:
1509 return ""
1510 text = "\n\n\t\t" + self.ret_type.gen_text() + " 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
1516 call_string = "py_" + self.alias + "("
1517 for arg in self.args:
1518 call_string += arg.gen_varname() + ", "
1519 if len(self.args) > 0:
1520 call_string = call_string[0:-2]
1521 call_string += ");"
1522
1523 text += ")\n\t\t{"
1524 text += "\n\t\t\tif(boost::python::override py_" + self.alias + " = this->get_override(\"py_" + self.alias + "\"))"
1525 text += "\n\t\t\t\t" + call_string
1526 text += "\n\t\t\telse"
1527 text += "\n\t\t\t\t" + self.member_of.name + "::" + call_string
1528 text += "\n\t\t}"
1529
1530 text += "\n\n\t\t" + self.ret_type.gen_text() + " default_py_" + self.alias + "("
1531 for arg in self.args:
1532 text += arg.gen_listitem() + ", "
1533 if len(self.args) > 0:
1534 text = text[:-2]
1535 text += ")\n\t\t{"
1536 text += "\n\t\t\tthis->" + self.member_of.name + "::" + call_string
1537 text += "\n\t\t}"
1538 return text
1539
1540
1541 def gen_boost_py(self):
1542 if self.duplicate:
1543 return ""
1544 if self.member_of == None:
1545 text = "\n\t\tdef"
1546 else:
1547 text = "\n\t\t\t.def"
1548 if len(self.args) > -1:
1549 if self.ret_type.name in known_containers:
1550 text += "<" + known_containers[self.ret_type.name].typename + " "
1551 else:
1552 text += "<" + self.ret_type.name + " "
1553 if self.member_of == None or self.is_static:
1554 text += "(*)("
1555 else:
1556 text += "(" + self.member_of.name + "::*)("
1557 for a in self.args:
1558 text += a.gen_listitem_hash() + ", "
1559 if len(self.args) > 0:
1560 text = text[0:-2] + ")>"
1561 else:
1562 text += "void)>"
1563
1564 if self.is_operator:
1565 text += "(\"" + wrappable_operators[self.name.replace("operator","")] + "\""
1566 else:
1567 if self.member_of != None and self.member_of.link_type == link_types.derive and self.is_virtual:
1568 text += "(\"py_" + self.alias + "\""
1569 else:
1570 text += "(\"" + self.alias + "\""
1571 if self.member_of != None:
1572 text += ", &" + self.member_of.name + "::"
1573 if self.member_of.link_type == link_types.derive and self.is_virtual:
1574 text += "py_" + self.alias
1575 text += ", &" + self.member_of.name + "Wrap::default_py_" + self.alias
1576 else:
1577 text += self.alias
1578
1579 text += ")"
1580 else:
1581 text += ", " + "YOSYS_PYTHON::" + self.alias + ");"
1582 return text
1583
1584 class WMember:
1585 orig_text = None
1586 wtype = attr_types.default
1587 name = None
1588 containing_file = None
1589 member_of = None
1590 namespace = ""
1591 is_const = False
1592
1593 def from_string(str_def, containing_file, class_, line_number, namespace):
1594 member = WMember()
1595 member.orig_text = str_def
1596 member.wtype = None
1597 member.name = ""
1598 member.containing_file = containing_file
1599 member.member_of = class_
1600 member.namespace = namespace
1601 member.is_const = False
1602
1603 if str.startswith(str_def, "const "):
1604 member.is_const = True
1605 str_def = str_def[6:]
1606
1607 if str_def.count(" ") == 0:
1608 return None
1609
1610 parts = split_list(str_def.strip(), " ")
1611
1612 prefix = ""
1613 i = 0
1614 for part in parts:
1615 if part in ["unsigned", "long", "short"]:
1616 prefix += part + " "
1617 i += 1
1618 else:
1619 break
1620 parts = parts[i:]
1621
1622 if len(parts) <= 1:
1623 return None
1624
1625 member.wtype = WType.from_string(prefix + parts[0], containing_file, line_number)
1626
1627 if member.wtype == None:
1628 return None
1629
1630 str_def = parts[1]
1631 for part in parts[2:]:
1632 str_def = str_def + " " + part
1633
1634 if str_def.find("(") != -1 or str_def.find(")") != -1 or str_def.find("{") != -1 or str_def.find("}") != -1:
1635 return None
1636
1637 found = str_def.find(";")
1638 if found == -1:
1639 return None
1640
1641 found_eq = str_def.find("=")
1642 if found_eq != -1:
1643 found = found_eq
1644
1645 member.name = str_def[:found]
1646 str_def = str_def[found+1:]
1647 if member.name.find("*") == 0:
1648 member.name = member.name.replace("*", "")
1649 member.wtype.attr_type = attr_types.star
1650 if member.name.find("&&") == 0:
1651 member.name = member.name.replace("&&", "")
1652 member.wtype.attr_type = attr_types.ampamp
1653 if member.name.find("&") == 0:
1654 member.name = member.name.replace("&", "")
1655 member.wtype.attr_type = attr_types.amp
1656
1657 if(len(str_def.strip()) != 0):
1658 return None
1659
1660 if len(member.name.split(",")) > 1:
1661 member_list = []
1662 for name in member.name.split(","):
1663 name = name.strip();
1664 member_list.append(WMember())
1665 member_list[-1].orig_text = member.orig_text
1666 member_list[-1].wtype = member.wtype
1667 member_list[-1].name = name
1668 member_list[-1].containing_file = member.containing_file
1669 member_list[-1].member_of = member.member_of
1670 member_list[-1].namespace = member.namespace
1671 member_list[-1].is_const = member.is_const
1672 return member_list
1673
1674 return member
1675
1676 def gen_decl(self):
1677 text = "\n\t\t" + self.wtype.gen_text() + " get_var_py_" + self.name + "();\n"
1678 if self.is_const:
1679 return text
1680 if self.wtype.name in classnames:
1681 text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs);\n"
1682 else:
1683 text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs);\n"
1684 return text
1685
1686 def gen_def(self):
1687 text = "\n\t" + self.wtype.gen_text() + " " + self.member_of.name +"::get_var_py_" + self.name + "()"
1688 text += "\n\t{\n\t\t"
1689 if self.wtype.attr_type == attr_types.star:
1690 text += "if(this->get_cpp_obj()->" + self.name + " == NULL)\n\t\t\t"
1691 text += "throw std::runtime_error(\"Member \\\"" + self.name + "\\\" is NULL\");\n\t\t"
1692 if self.wtype.name in known_containers:
1693 text += self.wtype.gen_text_cpp()
1694 else:
1695 text += self.wtype.gen_text()
1696
1697 if self.wtype.name in classnames or (self.wtype.name in known_containers and self.wtype.attr_type == attr_types.star):
1698 text += "*"
1699 text += " ret_ = "
1700 if self.wtype.name in classnames:
1701 text += self.wtype.name + "::get_py_obj("
1702 if self.wtype.attr_type != attr_types.star:
1703 text += "&"
1704 text += "this->get_cpp_obj()->" + self.name
1705 if self.wtype.name in classnames:
1706 text += ")"
1707 text += ";"
1708
1709 if self.wtype.name in classnames:
1710 text += "\n\t\treturn *ret_;"
1711 elif self.wtype.name in known_containers:
1712 text += known_containers[self.wtype.name].translate_cpp("ret_", self.wtype.cont.args, "\n\t\t", self.wtype.attr_type == attr_types.star)
1713 text += "\n\t\treturn ret____tmp;"
1714 else:
1715 text += "\n\t\treturn ret_;"
1716 text += "\n\t}\n"
1717
1718 if self.is_const:
1719 return text
1720
1721 ret = Attribute(self.wtype, "rhs");
1722
1723 if self.wtype.name in classnames:
1724 text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs)"
1725 else:
1726 text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs)"
1727 text += "\n\t{"
1728 text += ret.gen_translation()
1729 text += "\n\t\tthis->get_cpp_obj()->" + self.name + " = " + ret.gen_call() + ";"
1730 text += "\n\t}\n"
1731
1732 return text;
1733
1734 def gen_boost_py(self):
1735 text = "\n\t\t\t.add_property(\"" + self.name + "\", &" + self.member_of.name + "::get_var_py_" + self.name
1736 if not self.is_const:
1737 text += ", &" + self.member_of.name + "::set_var_py_" + self.name
1738 text += ")"
1739 return text
1740
1741 class WGlobal:
1742 orig_text = None
1743 wtype = attr_types.default
1744 name = None
1745 containing_file = None
1746 namespace = ""
1747 is_const = False
1748
1749 def from_string(str_def, containing_file, line_number, namespace):
1750 glbl = WGlobal()
1751 glbl.orig_text = str_def
1752 glbl.wtype = None
1753 glbl.name = ""
1754 glbl.containing_file = containing_file
1755 glbl.namespace = namespace
1756 glbl.is_const = False
1757
1758 if not str.startswith(str_def, "extern"):
1759 return None
1760 str_def = str_def[7:]
1761
1762 if str.startswith(str_def, "const "):
1763 glbl.is_const = True
1764 str_def = str_def[6:]
1765
1766 if str_def.count(" ") == 0:
1767 return None
1768
1769 parts = split_list(str_def.strip(), " ")
1770
1771 prefix = ""
1772 i = 0
1773 for part in parts:
1774 if part in ["unsigned", "long", "short"]:
1775 prefix += part + " "
1776 i += 1
1777 else:
1778 break
1779 parts = parts[i:]
1780
1781 if len(parts) <= 1:
1782 return None
1783
1784 glbl.wtype = WType.from_string(prefix + parts[0], containing_file, line_number)
1785
1786 if glbl.wtype == None:
1787 return None
1788
1789 str_def = parts[1]
1790 for part in parts[2:]:
1791 str_def = str_def + " " + part
1792
1793 if str_def.find("(") != -1 or str_def.find(")") != -1 or str_def.find("{") != -1 or str_def.find("}") != -1:
1794 return None
1795
1796 found = str_def.find(";")
1797 if found == -1:
1798 return None
1799
1800 found_eq = str_def.find("=")
1801 if found_eq != -1:
1802 found = found_eq
1803
1804 glbl.name = str_def[:found]
1805 str_def = str_def[found+1:]
1806 if glbl.name.find("*") == 0:
1807 glbl.name = glbl.name.replace("*", "")
1808 glbl.wtype.attr_type = attr_types.star
1809 if glbl.name.find("&&") == 0:
1810 glbl.name = glbl.name.replace("&&", "")
1811 glbl.wtype.attr_type = attr_types.ampamp
1812 if glbl.name.find("&") == 0:
1813 glbl.name = glbl.name.replace("&", "")
1814 glbl.wtype.attr_type = attr_types.amp
1815
1816 if(len(str_def.strip()) != 0):
1817 return None
1818
1819 if len(glbl.name.split(",")) > 1:
1820 glbl_list = []
1821 for name in glbl.name.split(","):
1822 name = name.strip();
1823 glbl_list.append(WGlobal())
1824 glbl_list[-1].orig_text = glbl.orig_text
1825 glbl_list[-1].wtype = glbl.wtype
1826 glbl_list[-1].name = name
1827 glbl_list[-1].containing_file = glbl.containing_file
1828 glbl_list[-1].namespace = glbl.namespace
1829 glbl_list[-1].is_const = glbl.is_const
1830 return glbl_list
1831
1832 return glbl
1833
1834 def gen_def(self):
1835 text = "\n\t"
1836 if self.is_const:
1837 text += "const "
1838 text += self.wtype.gen_text() + " get_var_py_" + self.name + "()"
1839 text += "\n\t{\n\t\t"
1840 if self.wtype.attr_type == attr_types.star:
1841 text += "if(" + self.namespace + "::" + self.name + " == NULL)\n\t\t\t"
1842 text += "throw std::runtime_error(\"" + self.namespace + "::" + self.name + " is NULL\");\n\t\t"
1843 if self.wtype.name in known_containers:
1844 text += self.wtype.gen_text_cpp()
1845 else:
1846 if self.is_const:
1847 text += "const "
1848 text += self.wtype.gen_text()
1849
1850 if self.wtype.name in classnames or (self.wtype.name in known_containers and self.wtype.attr_type == attr_types.star):
1851 text += "*"
1852 text += " ret_ = "
1853 if self.wtype.name in classnames:
1854 text += self.wtype.name + "::get_py_obj("
1855 if self.wtype.attr_type != attr_types.star:
1856 text += "&"
1857 text += self.namespace + "::" + self.name
1858 if self.wtype.name in classnames:
1859 text += ")"
1860 text += ";"
1861
1862 if self.wtype.name in classnames:
1863 text += "\n\t\treturn *ret_;"
1864 elif self.wtype.name in known_containers:
1865 text += known_containers[self.wtype.name].translate_cpp("ret_", self.wtype.cont.args, "\n\t\t", self.wtype.attr_type == attr_types.star)
1866 text += "\n\t\treturn ret____tmp;"
1867 else:
1868 text += "\n\t\treturn ret_;"
1869 text += "\n\t}\n"
1870
1871 if self.is_const:
1872 return text
1873
1874 ret = Attribute(self.wtype, "rhs");
1875
1876 if self.wtype.name in classnames:
1877 text += "\n\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs)"
1878 else:
1879 text += "\n\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs)"
1880 text += "\n\t{"
1881 text += ret.gen_translation()
1882 text += "\n\t\t" + self.namespace + "::" + self.name + " = " + ret.gen_call() + ";"
1883 text += "\n\t}\n"
1884
1885 return text;
1886
1887 def gen_boost_py(self):
1888 text = "\n\t\t\t.add_static_property(\"" + self.name + "\", &" + "YOSYS_PYTHON::get_var_py_" + self.name
1889 if not self.is_const:
1890 text += ", &YOSYS_PYTHON::set_var_py_" + self.name
1891 text += ")"
1892 return text
1893
1894 def concat_namespace(tuple_list):
1895 if len(tuple_list) == 0:
1896 return ""
1897 ret = ""
1898 for namespace in tuple_list:
1899 ret += "::" + namespace[0]
1900 return ret[2:]
1901
1902 def calc_ident(text):
1903 if len(text) == 0 or text[0] != ' ':
1904 return 0
1905 return calc_ident(text[1:]) + 1
1906
1907 def assure_length(text, length, left = False):
1908 if len(text) > length:
1909 return text[:length]
1910 if left:
1911 return text + " "*(length - len(text))
1912 return " "*(length - len(text)) + text
1913
1914 def parse_header(source):
1915 debug("Parsing " + source.name + ".pyh",1)
1916 source_file = open(source.name + ".pyh", "r")
1917
1918 source_text = []
1919 in_line = source_file.readline()
1920
1921 namespaces = []
1922
1923 while(in_line):
1924 if(len(in_line)>1):
1925 source_text.append(in_line.replace("char *", "char_p ").replace("char* ", "char_p "))
1926 in_line = source_file.readline()
1927
1928 i = 0
1929
1930 namespaces = []
1931 class_ = None
1932 private_segment = False
1933
1934 while i < len(source_text):
1935 line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", " namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END"," }")
1936 ugly_line = unpretty_string(line)
1937
1938 # for anonymous unions, ignore union enclosure by skipping start line and replacing end line with new line
1939 if 'union {' in line:
1940 j = i+1
1941 while j < len(source_text):
1942 union_line = source_text[j]
1943 if '};' in union_line:
1944 source_text[j] = '\n'
1945 break
1946 j += 1
1947 if j != len(source_text):
1948 i += 1
1949 continue
1950
1951 if str.startswith(ugly_line, "namespace "):# and ugly_line.find("std") == -1 and ugly_line.find("__") == -1:
1952 namespace_name = ugly_line[10:].replace("{","").strip()
1953 namespaces.append((namespace_name, ugly_line.count("{")))
1954 debug("-----NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1955 i += 1
1956 continue
1957
1958 if len(namespaces) != 0:
1959 namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
1960 if namespaces[-1][1] == 0:
1961 debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
1962 del namespaces[-1]
1963 i += 1
1964 continue
1965
1966 if class_ == None and (str.startswith(ugly_line, "struct ") or str.startswith(ugly_line, "class")) and ugly_line.count(";") == 0:
1967
1968 struct_name = ugly_line.split(" ")[1].split("::")[-1]
1969 impl_namespaces = ugly_line.split(" ")[1].split("::")[:-1]
1970 complete_namespace = concat_namespace(namespaces)
1971 for namespace in impl_namespaces:
1972 complete_namespace += "::" + namespace
1973 debug("\tFound " + struct_name + " in " + complete_namespace,2)
1974 class_ = (class_by_name(struct_name), ugly_line.count("{"))#calc_ident(line))
1975 if struct_name in classnames:
1976 class_[0].namespace = complete_namespace
1977 i += 1
1978 continue
1979
1980 if class_ != None:
1981 class_ = (class_[0], class_[1] + ugly_line.count("{") - ugly_line.count("}"))
1982 if class_[1] == 0:
1983 if class_[0] == None:
1984 debug("\tExiting unknown class", 3)
1985 else:
1986 debug("\tExiting class " + class_[0].name, 3)
1987 class_ = None
1988 private_segment = False
1989 i += 1
1990 continue
1991
1992 if class_ != None and (line.find("private:") != -1 or line.find("protected:") != -1):
1993 private_segment = True
1994 i += 1
1995 continue
1996 if class_ != None and line.find("public:") != -1:
1997 private_segment = False
1998 i += 1
1999 continue
2000
2001 candidate = None
2002
2003 if private_segment and class_ != None and class_[0] != None:
2004 candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i, True)
2005 if candidate != None:
2006 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
2007 class_[0].found_constrs.append(candidate)
2008 i += 1
2009 continue
2010
2011 if not private_segment and (class_ == None or class_[0] != None):
2012 if class_ != None:
2013 candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
2014 else:
2015 candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
2016 if candidate != None and candidate.name.find("::") == -1:
2017 if class_ == None:
2018 debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
2019 unowned_functions.append(candidate)
2020 else:
2021 debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
2022 class_[0].found_funs.append(candidate)
2023 else:
2024 candidate = WEnum.from_string(ugly_line, concat_namespace(namespaces), i)
2025 if candidate != None:
2026 enums.append(candidate)
2027 debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
2028 elif class_ != None and class_[1] == 1:
2029 candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i)
2030 if candidate != None:
2031 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
2032 class_[0].found_constrs.append(candidate)
2033 else:
2034 candidate = WMember.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
2035 if candidate != None:
2036 if type(candidate) == list:
2037 for c in candidate:
2038 debug("\t\tFound member \"" + c.name + "\" of class \"" + class_[0].name + "\" of type \"" + c.wtype.name + "\"", 2)
2039 class_[0].found_vars.extend(candidate)
2040 else:
2041 debug("\t\tFound member \"" + candidate.name + "\" of class \"" + class_[0].name + "\" of type \"" + candidate.wtype.name + "\"", 2)
2042 class_[0].found_vars.append(candidate)
2043 if candidate == None and class_ == None:
2044 candidate = WGlobal.from_string(ugly_line, source.name, i, concat_namespace(namespaces))
2045 if candidate != None:
2046 if type(candidate) == list:
2047 for c in candidate:
2048 glbls.append(c)
2049 debug("\tFound global \"" + c.name + "\" in namespace " + concat_namespace(namespaces), 2)
2050 else:
2051 glbls.append(candidate)
2052 debug("\tFound global \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces), 2)
2053
2054 j = i
2055 line = unpretty_string(line)
2056 while candidate == None and j+1 < len(source_text) and line.count(';') <= 1 and line.count("(") >= line.count(")"):
2057 j += 1
2058 line = line + "\n" + unpretty_string(source_text[j])
2059 if class_ != None:
2060 candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
2061 else:
2062 candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
2063 if candidate != None and candidate.name.find("::") == -1:
2064 if class_ == None:
2065 debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
2066 unowned_functions.append(candidate)
2067 else:
2068 debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
2069 class_[0].found_funs.append(candidate)
2070 continue
2071 candidate = WEnum.from_string(line, concat_namespace(namespaces), i)
2072 if candidate != None:
2073 enums.append(candidate)
2074 debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
2075 continue
2076 if class_ != None:
2077 candidate = WConstructor.from_string(line, source.name, class_[0], i)
2078 if candidate != None:
2079 debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
2080 class_[0].found_constrs.append(candidate)
2081 continue
2082 if class_ == None:
2083 candidate = WGlobal.from_string(line, source.name, i, concat_namespace(namespaces))
2084 if candidate != None:
2085 if type(candidate) == list:
2086 for c in candidate:
2087 glbls.append(c)
2088 debug("\tFound global \"" + c.name + "\" in namespace " + concat_namespace(namespaces), 2)
2089 else:
2090 glbls.append(candidate)
2091 debug("\tFound global \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces), 2)
2092 continue
2093 if candidate != None:
2094 while i < j:
2095 i += 1
2096 line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", " namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END"," }")
2097 ugly_line = unpretty_string(line)
2098 if len(namespaces) != 0:
2099 namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
2100 if namespaces[-1][1] == 0:
2101 debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
2102 del namespaces[-1]
2103 if class_ != None:
2104 class_ = (class_[0] , class_[1] + ugly_line.count("{") - ugly_line.count("}"))
2105 if class_[1] == 0:
2106 if class_[0] == None:
2107 debug("\tExiting unknown class", 3)
2108 else:
2109 debug("\tExiting class " + class_[0].name, 3)
2110 class_ = None
2111 private_segment = False
2112 i += 1
2113 else:
2114 i += 1
2115
2116 def debug(message, level):
2117 if level <= debug.debug_level:
2118 print(message)
2119
2120 def expand_function(f):
2121 fun_list = []
2122 arg_list = []
2123 for arg in f.args:
2124 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")):
2125 fi = copy.deepcopy(f)
2126 fi.args = copy.deepcopy(arg_list)
2127 fun_list.append(fi)
2128 arg_list.append(arg)
2129 fun_list.append(f)
2130 return fun_list
2131
2132 def expand_functions():
2133 global unowned_functions
2134 new_funs = []
2135 for fun in unowned_functions:
2136 new_funs.extend(expand_function(fun))
2137 unowned_functions = new_funs
2138 for source in sources:
2139 for class_ in source.classes:
2140 new_funs = []
2141 for fun in class_.found_funs:
2142 new_funs.extend(expand_function(fun))
2143 class_.found_funs = new_funs
2144
2145 def clean_duplicates():
2146 for source in sources:
2147 for class_ in source.classes:
2148 known_decls = {}
2149 for fun in class_.found_funs:
2150 if fun.gen_decl_hash_py() in known_decls:
2151 debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
2152 other = known_decls[fun.gen_decl_hash_py()]
2153 other.gen_alias()
2154 fun.gen_alias()
2155 if fun.gen_decl_hash_py() == other.gen_decl_hash_py():
2156 fun.duplicate = True
2157 debug("Disabled \"" + fun.gen_decl_hash_py() + "\"", 3)
2158 else:
2159 known_decls[fun.gen_decl_hash_py()] = fun
2160 known_decls = []
2161 for con in class_.found_constrs:
2162 if con.gen_decl_hash_py() in known_decls:
2163 debug("Multiple declarations of " + con.gen_decl_hash_py(),3)
2164 con.duplicate = True
2165 else:
2166 known_decls.append(con.gen_decl_hash_py())
2167 known_decls = []
2168 for fun in unowned_functions:
2169 if fun.gen_decl_hash_py() in known_decls:
2170 debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
2171 fun.duplicate = True
2172 else:
2173 known_decls.append(fun.gen_decl_hash_py())
2174
2175 def gen_wrappers(filename, debug_level_ = 0):
2176 debug.debug_level = debug_level_
2177 for source in sources:
2178 parse_header(source)
2179
2180 expand_functions()
2181 clean_duplicates()
2182
2183 import shutil
2184 import math
2185 col = shutil.get_terminal_size((80,20)).columns
2186 debug("-"*col, 1)
2187 debug("-"*math.floor((col-7)/2)+"SUMMARY"+"-"*math.ceil((col-7)/2), 1)
2188 debug("-"*col, 1)
2189 for source in sources:
2190 for class_ in source.classes:
2191 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)
2192 if len(class_.found_constrs) == 0:
2193 class_.found_constrs.append(WConstructor(source.name, class_))
2194 debug(str(len(unowned_functions)) + " functions are unowned", 1)
2195 debug(str(len(unowned_functions)) + " global variables", 1)
2196 for enum in enums:
2197 debug("Enum " + assure_length(enum.name, len(max(enum_names, key=len)), True) + " contains " + assure_length(str(len(enum.values)), 2, False) + " values", 1)
2198 debug("-"*col, 1)
2199 wrapper_file = open(filename, "w+")
2200 wrapper_file.write(
2201 """/*
2202 * yosys -- Yosys Open SYnthesis Suite
2203 *
2204 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
2205 *
2206 * Permission to use, copy, modify, and/or distribute this software for any
2207 * purpose with or without fee is hereby granted, provided that the above
2208 * copyright notice and this permission notice appear in all copies.
2209 *
2210 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
2211 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
2212 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
2213 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
2214 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
2215 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
2216 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2217 *
2218 * This is a generated file and can be overwritten by make
2219 */
2220
2221 #ifdef WITH_PYTHON
2222 """)
2223 for source in sources:
2224 wrapper_file.write("#include \""+source.name+".h\"\n")
2225 wrapper_file.write("""
2226 #include <boost/python/module.hpp>
2227 #include <boost/python/class.hpp>
2228 #include <boost/python/wrapper.hpp>
2229 #include <boost/python/call.hpp>
2230 #include <boost/python.hpp>
2231 #include <iosfwd> // std::streamsize
2232 #include <iostream>
2233 #include <boost/iostreams/concepts.hpp> // boost::iostreams::sink
2234 #include <boost/iostreams/stream.hpp>
2235 USING_YOSYS_NAMESPACE
2236
2237 namespace YOSYS_PYTHON {
2238
2239 struct YosysStatics{};
2240 """)
2241
2242 for source in sources:
2243 for wclass in source.classes:
2244 wrapper_file.write("\n\tstruct " + wclass.name + ";")
2245
2246 wrapper_file.write("\n")
2247
2248 for source in sources:
2249 for wclass in source.classes:
2250 wrapper_file.write(wclass.gen_decl(source.name))
2251
2252 wrapper_file.write("\n")
2253
2254 for source in sources:
2255 for wclass in source.classes:
2256 wrapper_file.write(wclass.gen_funs(source.name))
2257
2258 for fun in unowned_functions:
2259 wrapper_file.write(fun.gen_def())
2260
2261 for glbl in glbls:
2262 wrapper_file.write(glbl.gen_def())
2263
2264 wrapper_file.write(""" struct Initializer
2265 {
2266 Initializer() {
2267 if(!Yosys::yosys_already_setup())
2268 {
2269 Yosys::log_streams.push_back(&std::cout);
2270 Yosys::log_error_stderr = true;
2271 Yosys::yosys_setup();
2272 }
2273 }
2274
2275 Initializer(Initializer const &) {}
2276
2277 ~Initializer() {
2278 Yosys::yosys_shutdown();
2279 }
2280 };
2281
2282
2283 /// source: https://stackoverflow.com/questions/26033781/converting-python-io-object-to-stdostream-when-using-boostpython?noredirect=1&lq=1
2284 /// @brief Type that implements the Boost.IOStream's Sink and Flushable
2285 /// concept for writing data to Python object that support:
2286 /// n = object.write(str) # n = None or bytes written
2287 /// object.flush() # if flush exists, then it is callable
2288 class PythonOutputDevice
2289 {
2290 public:
2291
2292 // This class models both the Sink and Flushable concepts.
2293 struct category
2294 : boost::iostreams::sink_tag,
2295 boost::iostreams::flushable_tag
2296 {};
2297
2298 explicit
2299 PythonOutputDevice(boost::python::object object)
2300 : object_(object)
2301 {}
2302
2303 // Sink concept.
2304 public:
2305
2306 typedef char char_type;
2307
2308 std::streamsize write(const char* buffer, std::streamsize buffer_size)
2309 {
2310 namespace python = boost::python;
2311 // Copy the buffer to a python string.
2312 python::str data(buffer, buffer_size);
2313
2314 // Invoke write on the python object, passing in the data. The following
2315 // is equivalent to:
2316 // n = object_.write(data)
2317 python::extract<std::streamsize> bytes_written(
2318 object_.attr("write")(data));
2319
2320 // Per the Sink concept, return the number of bytes written. If the
2321 // Python return value provides a numeric result, then use it. Otherwise,
2322 // such as the case of a File object, use the buffer_size.
2323 return bytes_written.check()
2324 ? bytes_written
2325 : buffer_size;
2326 }
2327
2328 // Flushable concept.
2329 public:
2330
2331 bool flush()
2332 {
2333 // If flush exists, then call it.
2334 boost::python::object flush = object_.attr("flush");
2335 if (!flush.is_none())
2336 {
2337 flush();
2338 }
2339
2340 // Always return true. If an error occurs, an exception should be thrown.
2341 return true;
2342 }
2343
2344 private:
2345 boost::python::object object_;
2346 };
2347
2348 /// @brief Use an auxiliary function to adapt the legacy function.
2349 void log_to_stream(boost::python::object object)
2350 {
2351 // Create an ostream that delegates to the python object.
2352 boost::iostreams::stream<PythonOutputDevice>* output = new boost::iostreams::stream<PythonOutputDevice>(object);
2353 Yosys::log_streams.insert(Yosys::log_streams.begin(), output);
2354 };
2355
2356
2357 BOOST_PYTHON_MODULE(libyosys)
2358 {
2359 using namespace boost::python;
2360
2361 class_<Initializer>("Initializer");
2362 scope().attr("_hidden") = new Initializer();
2363
2364 def("log_to_stream", &log_to_stream);
2365 """)
2366
2367 for enum in enums:
2368 wrapper_file.write(enum.gen_boost_py())
2369
2370 for source in sources:
2371 for wclass in source.classes:
2372 wrapper_file.write(wclass.gen_boost_py())
2373
2374 for fun in unowned_functions:
2375 wrapper_file.write(fun.gen_boost_py())
2376
2377 wrapper_file.write("\n\n\t\tclass_<YosysStatics>(\"Yosys\")\n")
2378 for glbl in glbls:
2379 wrapper_file.write(glbl.gen_boost_py())
2380 wrapper_file.write("\t\t;\n")
2381
2382 wrapper_file.write("\n\t}\n}\n#endif")
2383
2384 def print_includes():
2385 for source in sources:
2386 print(source.name + ".pyh")