aboutsummaryrefslogtreecommitdiffstats
path: root/bigint/BigUnsigned.cc
diff options
context:
space:
mode:
Diffstat (limited to 'bigint/BigUnsigned.cc')
0 files changed, 0 insertions, 0 deletions
'>54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
#
#  yosys -- Yosys Open SYnthesis Suite
#
#  Copyright (C) 2012  Claire Xenia Wolf <claire@yosyshq.com>
#
#  Permission to use, copy, modify, and/or distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
#
#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
#  Author Benedikt Tutzer
#

import copy

#Map c++ operator Syntax to Python functions
wrappable_operators = {
		"<" : "__lt__",
		"==": "__eq__",
		"!=": "__ne__",
		"+" : "__add__",
		"-" : "__sub__",
		"*" : "__mul__",
		"/" : "__div__",
		"()": "__call__"
	}

#Restrict certain strings from being function names in Python
keyword_aliases = {
		"in" : "in_",
		"False" : "False_",
		"None" : "None_",
		"True" : "True_",
		"and" : "and_",
		"as" : "as_",
		"assert" : "assert_",
		"break" : "break_",
		"class" : "class_",
		"continue" : "continue_",
		"def" : "def_",
		"del" : "del_",
		"elif" : "elif_",
		"else" : "else_",
		"except" : "except_",
		"for" : "for_",
		"from" : "from_",
		"global" : "global_",
		"if" : "if_",
		"import" : "import_",
		"in" : "in_",
		"is" : "is_",
		"lambda" : "lambda_",
		"nonlocal" : "nonlocal_",
		"not" : "not_",
		"or" : "or_",
		"pass" : "pass_",
		"raise" : "raise_",
		"return" : "return_",
		"try" : "try_",
		"while" : "while_",
		"with" : "with_",
		"yield" : "yield_"
	}

#These can be used without any explicit conversion
primitive_types = ["void", "bool", "int", "double", "size_t", "std::string",
		"string", "State", "char_p"]

from enum import Enum

#Ways to link between Python- and C++ Objects
class link_types(Enum):
	global_list = 1		#Manage a global list of objects in C++, the Python
						#object contains a key to find the corresponding C++
						#object and a Pointer to the object to verify it is
						#still the same, making collisions unlikely to happen
	ref_copy = 2		#The Python object contains a copy of the C++ object.
						#The C++ object is deleted when the Python object gets
						#deleted
	pointer = 3			#The Python Object contains a pointer to it's C++
						#counterpart
	derive = 4			#The Python-Wrapper is derived from the C++ object.

class attr_types(Enum):
	star = "*"
	amp = "&"
	ampamp = "&&"
	default = ""

#For source-files
class Source:
	name = ""
	classes = []

	def __init__(self, name, classes):
		self.name = name
		self.classes = classes

#Splits a list by the given delimiter, without splitting strings inside
#pointy-brackets (< and >)
def split_list(str_def, delim):
	str_def = str_def.strip()
	if len(str_def) == 0:
		return []
	if str_def.count(delim) == 0:
		return [str_def]
	if str_def.count("<") == 0:
		return str_def.split(delim)
	if str_def.find("<") < str_def.find(" "):
		closing = find_closing(str_def[str_def.find("<")+1:], "<", ">") + str_def.find("<")
		comma = str_def[closing:].find(delim)
		if comma == -1:
			return [str_def]
		comma = closing  + comma
	else:
		comma = str_def.find(delim)
	rest = split_list(str_def[comma+1:], delim)
	ret = [str_def[:comma]]
	if rest != None and len(rest) != 0:
		ret.extend(rest)
	return ret

#Represents a Type
class WType:
	name = ""
	cont = None
	attr_type = attr_types.default

	def __init__(self, name = "", cont = None, attr_type = attr_types.default):
		self.name = name
		self.cont = cont
		self.attr_type = attr_type

	#Python type-string
	def gen_text(self):
		text = self.name
		if self.name in enum_names:
			text = enum_by_name(self.name).namespace + "::" + self.name
		if self.cont != None:
			return known_containers[self.name].typename
		return text

	#C++ type-string
	def gen_text_cpp(self):
		postfix = ""
		if self.attr_type == attr_types.star:
			postfix = "*"
		if self.name in primitive_types:
			return self.name + postfix
		if self.name in enum_names:
			return enum_by_name(self.name).namespace + "::" + self.name + postfix
		if self.name in classnames:
			return class_by_name(self.name).namespace + "::" + self.name + postfix
		text = self.name
		if self.cont != None:
			text += "<"
			for a in self.cont.args:
				text += a.gen_text_cpp() + ", "
			text = text[:-2]
			text += ">"
		return text

	@staticmethod
	def from_string(str_def, containing_file, line_number):
		str_def = str_def.strip()
		if len(str_def) == 0:
			return None
		str_def = str_def.replace("RTLIL::SigSig", "std::pair<SigSpec, SigSpec>").replace("SigSig", "std::pair<SigSpec, SigSpec>")
		t = WType()
		t.name = ""
		t.cont = None
		t.attr_type = attr_types.default
		if str_def.find("<") != -1:# and str_def.find("<") < str_def.find(" "):
			candidate = WContainer.from_string(str_def, containing_file, line_number)
			if candidate == None:
				return None
			t.name = str_def[:str_def.find("<")]

			if t.name.count("*") + t.name.count("&") > 1:
				return None

			if t.name.count("*") == 1 or str_def[0] == '*' or str_def[-1] == '*':
				t.attr_type = attr_types.star
				t.name = t.name.replace("*","")
			elif t.name.count("&&") == 1:
				t.attr_type = attr_types.ampamp
				t.name = t.name.replace("&&","")
			elif t.name.count("&") == 1 or str_def[0] == '&' or str_def[-1] == '&':
				t.attr_type = attr_types.amp
				t.name = t.name.replace("&","")

			t.cont = candidate
			if(t.name not in known_containers):
				return None	
			return t

		prefix = ""

		if str.startswith(str_def, "unsigned "):
			prefix = "unsigned "
			str_def = str_def[9:]
		while str.startswith(str_def, "long "):
			prefix= "long " + prefix
			str_def = str_def[5:]
		while str.startswith(str_def, "short "):
			prefix = "short " + prefix
			str_def = str_def[6:]

		str_def = str_def.split("::")[-1]

		if str_def.count("*") + str_def.count("&") >= 2:
			return None

		if str_def.count("*") == 1:
			t.attr_type = attr_types.star
			str_def = str_def.replace("*","")
		elif str_def.count("&&") == 1:
			t.attr_type = attr_types.ampamp
			str_def = str_def.replace("&&","")
		elif str_def.count("&") == 1:
			t.attr_type = attr_types.amp
			str_def = str_def.replace("&","")

		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:
			return None

		if str_def.count(" ") == 0:
			t.name = (prefix + str_def).replace("char_p", "char *")
			t.cont = None
			return t
		return None

#Represents a container-type
class WContainer:
	name = ""
	args = []

	def from_string(str_def, containing_file, line_number):
		if str_def == None or len(str_def) < 4:
			return None
		cont = WContainer()
		cont.name = str_def[:str_def.find("<")]
		str_def = str_def[str_def.find("<")+1:find_closing(str_def, "<", ">")]
		cont.args = []
		for arg in split_list(str_def, ","):
			candidate = WType.from_string(arg.strip(), containing_file, line_number)
			if candidate == None:
				return None
			if candidate.name == "void":
				return None
			cont.args.append(candidate)
		return cont

#Translators between Python and C++ containers
#Base Type
class Translator:
	tmp_cntr = 0
	typename = "DefaultType"
	orig_name = "DefaultCpp"

	@classmethod
	def gen_type(c, types):
		return "\nImplement a function that outputs the c++ type of this container here\n"

	@classmethod
	def translate(c, varname, types, prefix):
		return "\nImplement a function translating a python container to a c++ container here\n"

	@classmethod
	def translate_cpp(c, varname, types, prefix, ref):
		return "\nImplement a function translating a c++ container to a python container here\n"

#Translates list-types (vector, pool, set), that only differ in their name and
#the name of the insertion function
class PythonListTranslator(Translator):
	typename = "boost::python::list"
	insert_name = "Default"

	#generate the c++ type string
	@classmethod
	def gen_type(c, types):
		text = c.orig_name + "<"
		if types[0].name in primitive_types:
			text += types[0].name
		elif types[0].name in known_containers:
			text += known_containers[types[0].name].gen_type(types[0].cont.args)
		else:
			text += class_by_name(types[0].name).namespace + "::" + types[0].name
			if types[0].attr_type == attr_types.star:
				text += "*"
		text += ">"
		return text

	#Generate C++ code to translate from a boost::python::list
	@classmethod
	def translate(c, varname, types, prefix):
		text  = prefix + c.gen_type(types) + " " + varname + "___tmp;"
		cntr_name = "cntr_" + str(Translator.tmp_cntr)
		Translator.tmp_cntr = Translator.tmp_cntr + 1
		text += prefix + "for(int " + cntr_name + " = 0; " + cntr_name + " < len(" + varname + "); " + cntr_name + "++)"
		text += prefix + "{"
		tmp_name = "tmp_" + str(Translator.tmp_cntr)
		Translator.tmp_cntr = Translator.tmp_cntr + 1
		if types[0].name in known_containers:
			text += prefix + "\t" + known_containers[types[0].name].typename + " " + tmp_name + " = boost::python::extract<" + known_containers[types[0].name].typename + ">(" + varname + "[" + cntr_name + "]);"
			text += known_containers[types[0].name].translate(tmp_name, types[0].cont.args, prefix+"\t")
			tmp_name = tmp_name + "___tmp"
			text += prefix + "\t" + varname + "___tmp" + c.insert_name + "(" + tmp_name + ");"
		elif types[0].name in classnames:
			text += prefix + "\t" + types[0].name + "* " + tmp_name + " = boost::python::extract<" + types[0].name + "*>(" + varname + "[" + cntr_name + "]);"
			if types[0].attr_type == attr_types.star:
				text += prefix + "\t" + varname + "___tmp" + c.insert_name + "(" + tmp_name + "->get_cpp_obj());"
			else:
				text += prefix + "\t" + varname + "___tmp" + c.insert_name + "(*" + tmp_name + "->get_cpp_obj());"
		else:
			text += prefix + "\t" + types[0].name + " " + tmp_name + " = boost::python::extract<" + types[0].name + ">(" + varname + "[" + cntr_name + "]);"
			text += prefix + "\t" + varname + "___tmp" + c.insert_name + "(" + tmp_name + ");"
		text += prefix + "}"
		return text

	#Generate C++ code to translate to a boost::python::list
	@classmethod
	def translate_cpp(c, varname, types, prefix, ref):
		text  = prefix + c.typename + " " + varname + "___tmp;"
		tmp_name = "tmp_" + str(Translator.tmp_cntr)
		Translator.tmp_cntr = Translator.tmp_cntr + 1
		if ref:
			text += prefix + "for(auto " + tmp_name + " : *" + varname + ")"
		else:
			text += prefix + "for(auto " + tmp_name + " : " + varname + ")"
		text += prefix + "{"
		if types[0].name in classnames:
			if types[0].attr_type == attr_types.star:
				text += prefix + "\t" + varname + "___tmp.append(" + types[0].name + "::get_py_obj(" + tmp_name + "));"
			else:
				text += prefix + "\t" + varname + "___tmp.append(*" + types[0].name + "::get_py_obj(&" + tmp_name + "));"
		elif types[0].name in known_containers:
			text += known_containers[types[0].name].translate_cpp(tmp_name, types[0].cont.args, prefix + "\t", types[0].attr_type == attr_types.star)
			text += prefix + "\t" + varname + "___tmp.append(" + tmp_name + "___tmp);"
		else:
			text += prefix + "\t" + varname + "___tmp.append(" + tmp_name + ");"
		text += prefix + "}"
		return text

class IDictTranslator(PythonListTranslator):
	typename = "boost::python::list"
	orig_name = "idict"
	insert_name = ""

#Sub-type for std::set
class SetTranslator(PythonListTranslator):
	insert_name = ".insert"
	orig_name = "std::set"

#Sub-type for std::vector
class VectorTranslator(PythonListTranslator):
	insert_name = ".push_back"
	orig_name = "std::vector"

#Sub-type for pool
class PoolTranslator(PythonListTranslator):
	insert_name = ".insert"
	orig_name = "pool"

#Translates dict-types (dict, std::map), that only differ in their name and
#the name of the insertion function
class PythonDictTranslator(Translator):
	typename = "boost::python::dict"
	insert_name = "Default"

	@classmethod
	def gen_type(c, types):
		text = c.orig_name + "<"
		if types[0].name in primitive_types:
			text += types[0].name
		elif types[0].name in known_containers:
			text += known_containers[types[0].name].gen_type(types[0].cont.args)
		else:
			text += class_by_name(types[0].name).namespace + "::" + types[0].name
			if types[0].attr_type == attr_types.star:
				text += "*"
		text += ", "
		if types[1].name in primitive_types:
			text += types[1].name
		elif types[1].name in known_containers:
			text += known_containers[types[1].name].gen_type(types[1].cont.args)
		else:
			text += class_by_name(types[1].name).namespace + "::" + types[1].name
			if types[1].attr_type == attr_types.star:
				text += "*"
		text += ">"
		return text

	#Generate c++ code to translate from a boost::python::dict
	@classmethod
	def translate(c, varname, types, prefix):
		text  = prefix + c.gen_type(types) + " " + varname + "___tmp;"
		text += prefix + "boost::python::list " + varname + "_keylist = " + varname + ".keys();"
		cntr_name = "cntr_" + str(Translator.tmp_cntr)
		Translator.tmp_cntr = Translator.tmp_cntr + 1
		text += prefix + "for(int " + cntr_name + " = 0; " + cntr_name + " < len(" + varname + "_keylist); " + cntr_name + "++)"
		text += prefix + "{"
		key_tmp_name = "key_tmp_" + str(Translator.tmp_cntr)
		val_tmp_name = "val_tmp_" + str(Translator.tmp_cntr)
		Translator.tmp_cntr = Translator.tmp_cntr + 1

		if types[0].name in known_containers:
			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 + " ]);"
			text += known_containers[types[0].name].translate(key_tmp_name, types[0].cont.args, prefix+"\t")
			key_tmp_name = key_tmp_name + "___tmp"
		elif types[0].name in classnames:
			text += prefix + "\t" + types[0].name + "* " + key_tmp_name + " = boost::python::extract<" + types[0].name + "*>(" + varname + "_keylist[ " + cntr_name + " ]);"
		else:
			text += prefix + "\t" + types[0].name + " " + key_tmp_name + " = boost::python::extract<" + types[0].name + ">(" + varname + "_keylist[ " + cntr_name + " ]);"

		if types[1].name in known_containers:
			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 + " ]]);"
			text += known_containers[types[1].name].translate(val_tmp_name, types[1].cont.args, prefix+"\t")
			val_tmp_name = val_tmp_name + "___tmp"
		elif types[1].name in classnames:
			text += prefix + "\t" + types[1].name + "* " + val_tmp_name + " = boost::python::extract<" + types[1].name + "*>(" + varname + "[" + varname + "_keylist[ " + cntr_name + " ]]);"
		else:
			text += prefix + "\t" + types[1].name + " " + val_tmp_name + " = boost::python::extract<" + types[1].name + ">(" + varname + "[" + varname + "_keylist[ " + cntr_name + " ]]);"

		text += prefix + "\t" + varname + "___tmp." + c.insert_name + "(std::pair<" + types[0].gen_text_cpp() + ", " + types[1].gen_text_cpp() + ">("

		if types[0].name not in classnames:
			text += key_tmp_name
		else:
			if types[0].attr_type != attr_types.star:
				text += "*"
			text += key_tmp_name + "->get_cpp_obj()"
		
		text += ", "
		if types[1].name not in classnames:
			text += val_tmp_name
		else:
			if types[1].attr_type != attr_types.star:
				text += "*"
			text += val_tmp_name + "->get_cpp_obj()"
		text += "));\n" + prefix + "}"
		return text
	
	#Generate c++ code to translate to a boost::python::dict
	@classmethod
	def translate_cpp(c, varname, types, prefix, ref):
		text  = prefix + c.typename + " " + varname + "___tmp;"
		tmp_name = "tmp_" + str(Translator.tmp_cntr)
		Translator.tmp_cntr = Translator.tmp_cntr + 1
		if ref:
			text += prefix + "for(auto " + tmp_name + " : *" + varname + ")"
		else:
			text += prefix + "for(auto " + tmp_name + " : " + varname + ")"
		text += prefix + "{"
		if types[1].name in known_containers:
			text += prefix + "\tauto " + tmp_name + "_second = " + tmp_name + ".second;"
			text += known_containers[types[1].name].translate_cpp(tmp_name + "_second", types[1].cont.args, prefix + "\t", types[1].attr_type == attr_types.star)

		if types[0].name in classnames:
			text += prefix + "\t" + varname + "___tmp[" + types[0].name + "::get_py_obj(" + tmp_name + ".first)] = "
		elif types[0].name not in known_containers:
			text += prefix + "\t" + varname + "___tmp[" + tmp_name + ".first] = "

		if types[1].name in classnames:
			if types[1].attr_type == attr_types.star:
				text += types[1].name + "::get_py_obj(" + tmp_name + ".second);"
			else:
				text += "*" + types[1].name + "::get_py_obj(&" + tmp_name + ".second);"
		elif types[1].name in known_containers:
			text += tmp_name + "_second___tmp;"
		else:
			text += tmp_name + ".second;"
		text += prefix + "}"
		return text

#Sub-type for dict
class DictTranslator(PythonDictTranslator):
	insert_name = "insert"
	orig_name = "dict"

#Sub_type for std::map
class MapTranslator(PythonDictTranslator):
	insert_name = "insert"
	orig_name = "std::map"	

#Translator for std::pair. Derived from PythonDictTranslator because the
#gen_type function is the same (because both have two template parameters)
class TupleTranslator(PythonDictTranslator):
	typename = "boost::python::tuple"
	orig_name = "std::pair"

	#Generate c++ code to translate from a boost::python::tuple
	@classmethod
	def translate(c, varname, types, prefix):
		text  = prefix + types[0].name + " " + varname + "___tmp_0 = boost::python::extract<" + types[0].name + ">(" + varname + "[0]);"
		text += prefix + types[1].name + " " + varname + "___tmp_1 = boost::python::extract<" + types[1].name + ">(" + varname + "[1]);"
		text += prefix + TupleTranslator.gen_type(types) + " " + varname + "___tmp("
		if types[0].name.split(" ")[-1] in primitive_types:
			text += varname + "___tmp_0, "
		else:
			text += varname + "___tmp_0.get_cpp_obj(), "
		if types[1].name.split(" ")[-1] in primitive_types:
			text += varname + "___tmp_1);"
		else:
			text += varname + "___tmp_1.get_cpp_obj());"
		return text

	#Generate c++ code to translate to a boost::python::tuple
	@classmethod
	def translate_cpp(c, varname, types, prefix, ref):
		# if the tuple is a pair of SigSpecs (aka SigSig), then we need
		# to call get_py_obj() on each item in the tuple
		if types[0].name in classnames:
			first_var = types[0].name + "::get_py_obj(" + varname + ".first)"
		else:
			first_var = varname + ".first"
		if types[1].name in classnames:
			second_var = types[1].name + "::get_py_obj(" + varname + ".second)"
		else:
			second_var = varname + ".second"
		text  = prefix + TupleTranslator.typename + " " + varname + "___tmp = boost::python::make_tuple(" + first_var + ", " + second_var + ");"
		return text

#Associate the Translators with their c++ type
known_containers = {
	"std::set"		:	SetTranslator,
	"std::vector"	:	VectorTranslator,
	"pool"			:	PoolTranslator,
	"idict"			:	IDictTranslator,
	"dict"			:	DictTranslator,
	"std::pair"		:	TupleTranslator,
	"std::map"		:	MapTranslator
}

class Attribute:
	wtype = None
	varname = None
	is_const = False
	default_value = None
	pos = None
	pos_counter = 0

	def __init__(self, wtype, varname, is_const = False, default_value = None):
		self.wtype = wtype
		self.varname = varname
		self.is_const = is_const
		self.default_value = None
		self.container = None

	@staticmethod
	def from_string(str_def, containing_file, line_number):
		if len(str_def) < 3:
			return None
		orig = str_def
		arg = Attribute(None, None)
		prefix = ""
		arg.wtype = None
		arg.varname = None
		arg.is_const = False
		arg.default_value = None
		arg.container = None
		if str.startswith(str_def, "const "):
			arg.is_const = True
			str_def = str_def[6:]
		if str.startswith(str_def, "unsigned "):
			prefix = "unsigned "
			str_def = str_def[9:]
		while str.startswith(str_def, "long "):
			prefix= "long " + prefix
			str_def = str_def[5:]
		while str.startswith(str_def, "short "):
			prefix = "short " + prefix
			str_def = str_def[6:]

		if str_def.find("<") != -1 and str_def.find("<") < str_def.find(" "):
			closing = find_closing(str_def[str_def.find("<"):], "<", ">") + str_def.find("<") + 1
			arg.wtype = WType.from_string(str_def[:closing].strip(), containing_file, line_number)
			str_def = str_def[closing+1:]
		else:
			if str_def.count(" ") > 0:
				arg.wtype = WType.from_string(prefix + str_def[:str_def.find(" ")].strip(), containing_file, line_number)
				str_def = str_def[str_def.find(" ")+1:]
			else:
				arg.wtype = WType.from_string(prefix + str_def.strip(), containing_file, line_number)
				str_def = ""
				arg.varname = ""

		if arg.wtype == None:
			return None
		if str_def.count("=") == 0:
			arg.varname = str_def.strip()
			if arg.varname.find(" ") > 0:
				return None
		else:
			arg.varname = str_def[:str_def.find("=")].strip()
			if arg.varname.find(" ") > 0:
				return None
			str_def = str_def[str_def.find("=")+1:].strip()
			arg.default_value = str_def[arg.varname.find("=")+1:].strip()
		if len(arg.varname) == 0:
			arg.varname = None
			return arg
		if arg.varname[0] == '*':
			arg.wtype.attr_type = attr_types.star
			arg.varname = arg.varname[1:]
		elif arg.varname[0] == '&':
			if arg.wtype.attr_type != attr_types.default:
				return None
			if arg.varname[1] == '&':
				arg.wtype.attr_type = attr_types.ampamp
				arg.varname = arg.varname[2:]
			else:
				arg.wtype.attr_type = attr_types.amp
				arg.varname = arg.varname[1:]
		return arg

	#Generates the varname. If the attribute has no name in the header file,
	#a name is generated
	def gen_varname(self):
		if self.varname != None:
			return self.varname
		if self.wtype.name == "void":
			return ""
		if self.pos == None:
			self.pos = Attribute.pos_counter
			Attribute.pos_counter = Attribute.pos_counter + 1
		return "gen_varname_" + str(self.pos)

	#Generates the text for the function headers with wrapper types
	def gen_listitem(self):
		prefix = ""
		if self.is_const:
			prefix = "const "
		if self.wtype.name in classnames:
			return prefix + self.wtype.name + "* " + self.gen_varname()
		if self.wtype.name in known_containers:
			return prefix + known_containers[self.wtype.name].typename + " " + self.gen_varname()
		return prefix + self.wtype.name + " " + self.gen_varname()

	#Generates the test for the function headers with c++ types
	def gen_listitem_cpp(self):
		prefix = ""
		if self.is_const:
			prefix = "const "
		infix = ""
		if self.wtype.attr_type == attr_types.star:
			infix = "*"
		elif self.wtype.attr_type == attr_types.amp:
			infix = "&"
		elif self.wtype.attr_type == attr_types.ampamp:
			infix = "&&"
		if self.wtype.name in known_containers:
			return prefix + known_containers[self.wtype.name].gen_type(self.wtype.cont.args) + " " + infix + self.gen_varname()
		if self.wtype.name in classnames:
			return prefix + class_by_name(self.wtype.name).namespace + "::" + self.wtype.name + " " + infix + self.gen_varname()
		return prefix + self.wtype.name + " " + infix + self.gen_varname()

	#Generates the listitem withtout the varname, so the signature can be
	#compared
	def gen_listitem_hash(self):
		prefix = ""
		if self.is_const:
			prefix = "const "
		if self.wtype.name in classnames:
			return prefix + self.wtype.name + "* "
		if self.wtype.name in known_containers:
			return known_containers[self.wtype.name].typename
		return prefix + self.wtype.name
		
	#Generate Translation code for the attribute
	def gen_translation(self):
		if self.wtype.name in known_containers:
			return known_containers[self.wtype.name].translate(self.gen_varname(), self.wtype.cont.args, "\n\t\t")
		return ""

	#Generate Translation code from c++ for the attribute
	def gen_translation_cpp(self):
		if self.wtype.name in known_containers:
			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)
		return ""

	#Generate Text for the call
	def gen_call(self):
		ret = self.gen_varname()
		if self.wtype.name in known_containers:
			if self.wtype.attr_type == attr_types.star:
				return "&" + ret + "___tmp"
			return ret + "___tmp"
		if self.wtype.name in classnames:
			if self.wtype.attr_type != attr_types.star:
				ret = "*" + ret
			return ret + "->get_cpp_obj()"
		if self.wtype.name == "char *" and self.gen_varname() in ["format", "fmt"]:
			return "\"%s\", " + self.gen_varname()
		if self.wtype.attr_type == attr_types.star:
			return "&" + ret
		return ret

	def gen_call_cpp(self):
		ret = self.gen_varname()
		if self.wtype.name.split(" ")[-1] in primitive_types or self.wtype.name in enum_names:
			if self.wtype.attr_type == attr_types.star:
				return "&" + ret
			return ret
		if self.wtype.name not in classnames:
			if self.wtype.attr_type == attr_types.star:
				return "&" + ret + "___tmp"
			return ret + "___tmp"
		if self.wtype.attr_type != attr_types.star:
			ret = "*" + ret
		return self.wtype.name + "::get_py_obj(" + self.gen_varname()  + ")"

	#Generate cleanup code
	def gen_cleanup(self):
		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):
			return ""
		return "\n\t\tdelete " + self.gen_varname() + "___tmp;"

class WClass:
	name = None
	namespace = None
	link_type = None
	base_class = None
	id_ = None
	string_id = None
	hash_id = None
	needs_clone = False
	found_funs = []
	found_vars = []
	found_constrs = []

	def __init__(self, name, link_type, id_, string_id = None, hash_id = None, needs_clone = False):
		self.name = name
		self.namespace = None
		self.base_class = None
		self.link_type = link_type
		self.id_ = id_
		self.string_id = string_id
		self.hash_id = hash_id
		self.needs_clone = needs_clone
		self.found_funs = []
		self.found_vars = []
		self.found_constrs = []

	def printable_constrs(self):
		ret = 0
		for con in self.found_constrs:
			if not con.protected:
				ret += 1
		return ret

	def gen_decl(self, filename):
		long_name = self.namespace + "::" + self.name

		text = "\n\t// WRAPPED from " + filename
		text += "\n\tstruct " + self.name
		if self.link_type == link_types.derive:
			text += " : public " + self.namespace + "::" + self.name
		text += "\n\t{\n"

		if self.link_type != link_types.derive:

			text += "\t\t" + long_name + "* ref_obj;\n"

			if self.link_type == link_types.ref_copy or self.link_type == link_types.pointer:
				text += "\n\t\t" + long_name + "* get_cpp_obj() const\n\t\t{\n\t\t\treturn ref_obj;\n\t\t}\n"
			elif self.link_type == link_types.global_list:
				text += "\t\t" + self.id_.wtype.name + " " + self.id_.varname + ";\n"
				text += "\n\t\t" + long_name + "* get_cpp_obj() const\n\t\t{"
				text += "\n\t\t\t" + long_name + "* ret = " + long_name + "::get_all_" + self.name.lower() + "s()->at(this->" + self.id_.varname + ");"
				text += "\n\t\t\tif(ret != NULL && ret == this->ref_obj)"
				text += "\n\t\t\t\treturn ret;"
				text += "\n\t\t\tthrow std::runtime_error(\"" + self.name + "'s c++ object does not exist anymore.\");"
				text += "\n\t\t\treturn NULL;"
				text += "\n\t\t}\n"

			#if self.link_type != link_types.pointer:
			text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + "* ref)\n\t\t{"
			text += "\n\t\t\tif(ref == nullptr){"
			text += "\n\t\t\t\tthrow std::runtime_error(\"" + self.name + " does not exist.\");"
			text += "\n\t\t\t}"
			text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
			if self.link_type == link_types.pointer:
				text += "\n\t\t\tret->ref_obj = ref;"
			if self.link_type == link_types.ref_copy:
				if self.needs_clone:
					text += "\n\t\t\tret->ref_obj = ref->clone();"
				else:
					text += "\n\t\t\tret->ref_obj = new "+long_name+"(*ref);"
			if self.link_type == link_types.global_list:
				text += "\n\t\t\tret->ref_obj = ref;"
				text += "\n\t\t\tret->" + self.id_.varname + " = ret->ref_obj->" + self.id_.varname + ";"
			text += "\n\t\t\treturn ret;"
			text += "\n\t\t}\n"

			if self.link_type == link_types.ref_copy:
				text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + " ref)\n\t\t{"
				text += "\n\t\t\t" + self.name + "* ret = (" + self.name + "*)malloc(sizeof(" + self.name + "));"
				if self.needs_clone:
					text += "\n\t\t\tret->ref_obj = ref.clone();"
				else:
					text += "\n\t\t\tret->ref_obj = new "+long_name+"(ref);"
				text += "\n\t\t\treturn ret;"
				text += "\n\t\t}\n"

			for con in self.found_constrs:
				text += con.gen_decl()
			if self.base_class is not None:
				text += "\n\t\tvirtual ~" + self.name + "() { };"
			for var in self.found_vars:
				text += var.gen_decl()
			for fun in self.found_funs:
				text += fun.gen_decl()


		if self.link_type == link_types.derive:
			duplicates = {}
			for fun in self.found_funs:
				if fun.name in duplicates:
					fun.gen_alias()
					duplicates[fun.name].gen_alias()
				else:
					duplicates[fun.name] = fun

			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"
			text += "\n\t\tstatic " + self.name + "* get_py_obj(" + long_name + "* ref)\n\t\t{"
			text += "\n\t\t\treturn (" + self.name + "*)ref;"
			text += "\n\t\t}\n"

			for con in self.found_constrs:
				text += con.gen_decl_derive()
			for var in self.found_vars:
				text += var.gen_decl()
			for fun in self.found_funs:
				text += fun.gen_decl_virtual()

		if self.hash_id != None:
			text += "\n\t\tunsigned int get_hash_py()"
			text += "\n\t\t{"
			text += "\n\t\t\treturn get_cpp_obj()->" + self.hash_id + ";"
			text += "\n\t\t}"

		text += "\n\t};\n"

		if self.link_type == link_types.derive:
			text += "\n\tstruct " + self.name + "Wrap : " + self.name + ", boost::python::wrapper<" + self.name + ">"
			text += "\n\t{"

			for con in self.found_constrs:
				text += con.gen_decl_wrapperclass()
			for fun in self.found_funs:
				text += fun.gen_default_impl()

			text += "\n\t};"

		text += "\n\tstd::ostream &operator<<(std::ostream &ostr, const " + self.name + " &ref)"
		text += "\n\t{"
		text += "\n\t\tostr << \"" + self.name
		if self.string_id != None:
			text +=" \\\"\""
			text += " << ref.get_cpp_obj()->" + self.string_id
			text += " << \"\\\"\""
		else:
			text += " at \" << ref.get_cpp_obj()"
		text += ";"
		text += "\n\t\treturn ostr;"
		text += "\n\t}"
		text += "\n"

		return text

	def gen_funs(self, filename):
		text = ""
		if self.link_type != link_types.derive:
			for con in self.found_constrs:
				text += con.gen_def()
			for var in self.found_vars:
				text += var.gen_def()
			for fun in self.found_funs:
				text += fun.gen_def()
		else:
			for var in self.found_vars:
				text += var.gen_def()
			for fun in self.found_funs:
				text += fun.gen_def_virtual()
		return text

	def gen_boost_py_body(self):
		text = ""
		if self.printable_constrs() == 0 or not self.contains_default_constr():
			text += ", no_init"
		text += ")"
		text += "\n\t\t\t.def(boost::python::self_ns::str(boost::python::self_ns::self))"
		text += "\n\t\t\t.def(boost::python::self_ns::repr(boost::python::self_ns::self))"
		for con in self.found_constrs:
			text += con.gen_boost_py()
		for var in self.found_vars:
			text += var.gen_boost_py()
		static_funs = []
		for fun in self.found_funs:
			text += fun.gen_boost_py()
			if fun.is_static and fun.alias not in static_funs:
				static_funs.append(fun.alias)
		for fun in static_funs:
			text += "\n\t\t\t.staticmethod(\"" + fun + "\")"

		if self.hash_id != None:
			text += "\n\t\t\t.def(\"__hash__\", &" + self.name + "::get_hash_py)"
		text += "\n\t\t\t;\n"
		return text

	def gen_boost_py(self):
		body = self.gen_boost_py_body()
		base_info = ""
		if self.base_class is not None:
			base_info = ", bases<" + (self.base_class.name) + ">"

		if self.link_type == link_types.derive:
			text = "\n\t\tclass_<" + self.name + base_info + ">(\"Cpp" + self.name + "\""
			text += body
			text += "\n\t\tclass_<" + self.name
			text += "Wrap, boost::noncopyable"
			text += ">(\"" + self.name + "\""
			text += body
		else:
			text = "\n\t\tclass_<" + self.name + base_info + ">(\"" + self.name + "\""
			text += body
		return text
	

	def contains_default_constr(self):
		for c in self.found_constrs:
			if len(c.args) == 0:
				return True
		return False

#CONFIGURE HEADER-FILES TO BE PARSED AND CLASSES EXPECTED IN THEM HERE

sources = [
	Source("kernel/celltypes",[
		WClass("CellType", link_types.pointer, None, None, "type.hash()", True),
		WClass("CellTypes", link_types.pointer, None, None, None, True)
		]
		),
	Source("kernel/consteval",[
		WClass("ConstEval", link_types.pointer, None, None, None, True)
		]
		),
	Source("kernel/log",[]),
	Source("kernel/register",[
		WClass("Pass", link_types.derive, None, None, None, True),
		]
		),
	Source("kernel/rtlil",[
		WClass("IdString", link_types.ref_copy, None, "str()", "hash()"),
		WClass("Const", link_types.ref_copy, None, "as_string()", "hash()"),
		WClass("AttrObject", link_types.ref_copy, None, None, None),
		WClass("Selection", link_types.ref_copy, None, None, None),
		WClass("Monitor", link_types.derive, None, None, None),
		WClass("CaseRule",link_types.ref_copy, None, None, None, True),
		WClass("SwitchRule",link_types.ref_copy, None, None, None, True),
		WClass("SyncRule", link_types.ref_copy, None, None, None, True),
		WClass("Process",  link_types.ref_copy, None, "name.c_str()", "name.hash()"),
		WClass("SigChunk", link_types.ref_copy, None, None, None),
		WClass("SigBit", link_types.ref_copy, None, None, "hash()"),
		WClass("SigSpec", link_types.ref_copy, None, None, "hash()"),
		WClass("Cell", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
		WClass("Wire", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
		WClass("Memory", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
		WClass("Module", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "name.c_str()", "hash()"),
		WClass("Design", link_types.global_list, Attribute(WType("unsigned int"), "hashidx_"), "hashidx_", "hash()")
		]
		),
	#Source("kernel/satgen",[
	#	]
	#	),
	#Source("libs/ezsat/ezsat",[
	#	]
	#	),
	#Source("libs/ezsat/ezminisat",[
	#	]
	#	),
	Source("kernel/sigtools",[
		WClass("SigMap", link_types.pointer, None, None, None, True)
		]
		),
	Source("kernel/yosys",[
		]
		),
	Source("kernel/cost",[])
	]

blacklist_methods = ["YOSYS_NAMESPACE::Pass::run_register", "YOSYS_NAMESPACE::Module::Pow"]

enum_names = ["State","SyncType","ConstFlags"]

enums = [] #Do not edit
glbls = []

unowned_functions = []

classnames = []
for source in sources:
	for wclass in source.classes:
		classnames.append(wclass.name)

def class_by_name(name):
	for source in sources:
		for wclass in source.classes:
			if wclass.name == name:
				return wclass
	return None

def enum_by_name(name):
	for e in enums:
		if e.name == name:
			return e
	return None

def find_closing(text, open_tok, close_tok):
	if text.find(open_tok) == -1 or text.find(close_tok) <= text.find(open_tok):
		return text.find(close_tok)
	return text.find(close_tok) + find_closing(text[text.find(close_tok)+1:], open_tok, close_tok) + 1

def unpretty_string(s):
	s = s.strip()
	while s.find("  ") != -1:
		s = s.replace("  "," ")
	while s.find("\t") != -1:
		s = s.replace("\t"," ")
	s = s.replace(" (","(")
	return s

class WEnum:
	name = None
	namespace = None
	values = []

	def from_string(str_def, namespace, line_number):
		str_def = str_def.strip()
		if not str.startswith(str_def, "enum "):
			return None
		if str_def.count(";") != 1:
			return None
		str_def = str_def[5:]
		enum = WEnum()
		split = str_def.split(":")
		if(len(split) != 2):
			return None
		enum.name = split[0].strip()
		if enum.name not in enum_names:
			return None
		str_def = split[1]
		if str_def.count("{") != str_def.count("}") != 1:
			return None
		if len(str_def) < str_def.find("}")+2 or str_def[str_def.find("}")+1] != ';':
			return None
		str_def = str_def.split("{")[-1].split("}")[0]
		enum.values = []
		for val in str_def.split(','):
			enum.values.append(val.strip().split('=')[0].strip())
		enum.namespace = namespace
		return enum

	def gen_boost_py(self):
		text = "\n\t\tenum_<" + self.namespace + "::" + self.name + ">(\"" + self.name + "\")\n"
		for value in self.values:
			text += "\t\t\t.value(\"" + value + "\"," + self.namespace + "::" + value + ")\n"
		text += "\t\t\t;\n"
		return text

	def __str__(self):
		ret = "Enum " + self.namespace + "::" + self.name + "(\n"
		for val in self.values:
			ret = ret + "\t" + val + "\n"
		return ret + ")"

	def __repr__(self):
		return __str__(self)

class WConstructor:
	orig_text = None
	args = []
	containing_file = None
	member_of = None
	duplicate = False
	protected = False

	def __init__(self, containing_file, class_):
		self.orig_text = "Auto generated default constructor"
		self.args = []
		self.containing_file = containing_file
		self.member_of = class_
		self.protected = False

	def from_string(str_def, containing_file, class_, line_number, protected = False):
		if class_ == None:
			return None
		if str_def.count("delete;") > 0:
			return None
		con = WConstructor(containing_file, class_)
		con.orig_text = str_def
		con.args = []
		con.duplicate = False
		con.protected = protected
		if str.startswith(str_def, "inline "):
			str_def = str_def[7:]
		if not str.startswith(str_def, class_.name + "("):
			return None
		str_def = str_def[len(class_.name)+1:]
		found = find_closing(str_def, "(", ")")
		if found == -1:
			return None
		str_def = str_def[0:found].strip()
		if len(str_def) == 0:
			return con
		for arg in split_list(str_def, ","):
			parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
			if parsed == None:
				return None
			con.args.append(parsed)
		return con

	def gen_decl(self):
		if self.duplicate or self.protected:
			return ""
		text =  "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t\t" + self.member_of.name + "("
		for arg in self.args:
			text += arg.gen_listitem() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ");\n"
		return text

	def gen_decl_derive(self):
		if self.duplicate or self.protected:
			return ""
		text =  "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t\t" + self.member_of.name + "("
		for arg in self.args:
			text += arg.gen_listitem() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ")"
		if len(self.args) == 0:
			return text + "{}"
		text += " : "
		text += self.member_of.namespace + "::" + self.member_of.name + "("
		for arg in self.args:
			text += arg.gen_call() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += "){}\n"
		return text

	def gen_decl_wrapperclass(self):
		if self.duplicate or self.protected:
			return ""
		text =  "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t\t" + self.member_of.name + "Wrap("
		for arg in self.args:
			text += arg.gen_listitem() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ")"
		if len(self.args) == 0:
			return text + "{}"
		text += " : "
		text += self.member_of.name + "("
		for arg in self.args:
			text += arg.gen_call() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += "){}\n"
		return text

	def gen_decl_hash_py(self):
		text = self.member_of.name + "("
		for arg in self.args:
			text += arg.gen_listitem_hash() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ");"
		return text

	def gen_def(self):
		if self.duplicate or self.protected:
			return ""
		text = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t" + self.member_of.name + "::" + self.member_of.name + "("
		for arg in self.args:
			text += arg.gen_listitem() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text +=")\n\t{"
		for arg in self.args:
			text += arg.gen_translation()
		if self.member_of.link_type != link_types.derive:
			text += "\n\t\tthis->ref_obj = new " + self.member_of.namespace + "::" + self.member_of.name + "("
		for arg in self.args:
			text += arg.gen_call() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		if self.member_of.link_type != link_types.derive:
			text += ");"
		if self.member_of.link_type == link_types.global_list:
			text += "\n\t\tthis->" + self.member_of.id_.varname + " = this->ref_obj->" + self.member_of.id_.varname + ";"
		for arg in self.args:
			text += arg.gen_cleanup()
		text += "\n\t}\n"
		return text

	def gen_boost_py(self):
		if self.duplicate or self.protected or len(self.args) == 0:
			return ""
		text  = "\n\t\t\t.def(init"
		text += "<"
		for a in self.args:
			text += a.gen_listitem_hash() + ", "
		text = text[0:-2] + ">())"
		return text

class WFunction:
	orig_text = None
	is_static = False
	is_inline = False
	is_virtual = False
	ret_attr_type = attr_types.default
	is_operator = False
	ret_type = None
	name = None
	alias = None
	args = []
	containing_file = None
	member_of = None
	duplicate = False
	namespace = ""

	def from_string(str_def, containing_file, class_, line_number, namespace):
		if str_def.count("delete;") > 0:
			return None
		func = WFunction()
		func.is_static = False
		func.is_inline = False
		func.is_virtual = False
		func.ret_attr_type = attr_types.default
		func.is_operator = False
		func.member_of = None
		func.orig_text = str_def
		func.args = []
		func.containing_file = containing_file
		func.member_of = class_
		func.duplicate = False
		func.namespace = namespace
		str_def = str_def.replace("operator ","operator")
		if str.startswith(str_def, "static "):
			func.is_static = True
			str_def = str_def[7:]
		else:
			func.is_static = False
		if str.startswith(str_def, "inline "):
			func.is_inline = True
			str_def = str_def[7:]
		else:
			func.is_inline = False
		if str.startswith(str_def, "virtual "):
			func.is_virtual = True
			str_def = str_def[8:]
		else:
			func.is_virtual = False

		if str_def.count(" ") == 0:
			return None

		parts = split_list(str_def.strip(), " ")

		prefix = ""
		i = 0
		for part in parts:
			if part in ["unsigned", "long", "short"]:
				prefix += part + " "
				i += 1
			else:
				break
		parts = parts[i:]

		if len(parts) <= 1:
			return None

		func.ret_type = WType.from_string(prefix + parts[0], containing_file, line_number)

		if func.ret_type == None:
			return None

		str_def = parts[1]
		for part in parts[2:]:
			str_def = str_def + " " + part

		found = str_def.find("(")
		if found == -1 or (str_def.find(" ") != -1 and found > str_def.find(" ")):
			return None
		func.name = str_def[:found]
		str_def = str_def[found:]
		if func.name.find("operator") != -1 and str.startswith(str_def, "()("):
				func.name += "()"
				str_def = str_def[2:]
		str_def = str_def[1:]
		if func.name.find("operator") != -1:
			func.is_operator = True
		if func.name.find("*") == 0:
			func.name = func.name.replace("*", "")
			func.ret_type.attr_type = attr_types.star
		if func.name.find("&&") == 0:
			func.name = func.name.replace("&&", "")
			func.ret_type.attr_type = attr_types.ampamp
		if func.name.find("&") == 0:
			func.name = func.name.replace("&", "")
			func.ret_type.attr_type = attr_types.amp

		found = find_closing(str_def, "(", ")")
		if found == -1:
			return None
		str_def = str_def[0:found]
		if func.name in blacklist_methods:
			return None
		if func.namespace != None and func.namespace != "":
			if (func.namespace + "::" + func.name) in blacklist_methods:
				return None
			if func.member_of != None:
				if (func.namespace + "::" + func.member_of.name + "::" + func.name) in blacklist_methods:
					return None
		if func.is_operator and func.name.replace(" ","").replace("operator","").split("::")[-1] not in wrappable_operators:
			return None

		testname = func.name
		if func.is_operator:
			testname = testname[:testname.find("operator")]
		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:
			return None

		func.alias = func.name
		if func.name in keyword_aliases:
			func.alias = keyword_aliases[func.name]
		str_def = str_def[:found].strip()
		if(len(str_def) == 0):
			return func
		for arg in split_list(str_def, ","):
			if arg.strip() == "...":
				continue
			parsed = Attribute.from_string(arg.strip(), containing_file, line_number)
			if parsed == None:
				return None
			func.args.append(parsed)
		return func

	def gen_alias(self):
		self.alias = self.name
		for arg in self.args:
			self.alias += "__" + arg.wtype.gen_text_cpp().replace("::", "_").replace("<","_").replace(">","_").replace(" ","").replace("*","").replace(",","")

	def gen_decl(self):
		if self.duplicate:
			return ""
		text =  "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t\t"
		if self.is_static:
			text += "static "
		text += self.ret_type.gen_text() + " " + self.alias + "("
		for arg in self.args:
			text += arg.gen_listitem()
			text += ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ");\n"
		return text

	def gen_decl_virtual(self):
		if self.duplicate:
			return ""
		if not self.is_virtual:
			return self.gen_decl()
		text =  "\n\t\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t\tvirtual "
		if self.is_static:
			text += "static "
		text += self.ret_type.gen_text() + " py_" + self.alias + "("
		for arg in self.args:
			text += arg.gen_listitem()
			text += ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ")"
		if len(self.args) == 0:
			text += "{}"
		else:
			text += "\n\t\t{"
			for arg in self.args:
				text += "\n\t\t\t(void)" + arg.gen_varname() + ";"
			text += "\n\t\t}\n"
		text += "\n\t\tvirtual "
		if self.is_static:
			text += "static "
		text += self.ret_type.gen_text() + " " + self.name + "("
		for arg in self.args:
			text += arg.gen_listitem_cpp()
			text += ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ") override;\n"
		return text

	def gen_decl_hash_py(self):
		text = self.ret_type.gen_text() + " " + self.alias + "("
		for arg in self.args:
			text += arg.gen_listitem_hash() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ");"
		return text

	def gen_def(self):
		if self.duplicate:
			return ""
		text  = "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t" + self.ret_type.gen_text() + " "
		if self.member_of != None:
			text += self.member_of.name + "::"
		text += self.alias + "("
		for arg in self.args:
			text += arg.gen_listitem()
			text += ", "
		if len(self.args) > 0:
			text = text[:-2]
		text +=")\n\t{"
		for arg in self.args:
			text += arg.gen_translation()
		text += "\n\t\t"
		if self.ret_type.name != "void":
			if self.ret_type.name in known_containers:
				text += self.ret_type.gen_text_cpp()
			else:
				text += self.ret_type.gen_text()
			if self.ret_type.name in classnames or (self.ret_type.name in known_containers and self.ret_type.attr_type == attr_types.star):
				text += "*"
			text += " ret_ = "
			if self.ret_type.name in classnames:
				text += self.ret_type.name + "::get_py_obj("
		if self.member_of == None:
			text += "::" + self.namespace + "::" + self.alias + "("
		elif self.is_static:
			text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
		else:
			text += "this->get_cpp_obj()->" + self.name + "("
		for arg in self.args:
			text += arg.gen_call() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		if self.ret_type.name in classnames:
			text += ")"
		text += ");"
		for arg in self.args:
			text += arg.gen_cleanup()
		if self.ret_type.name != "void":
			if self.ret_type.name in classnames:
				text += "\n\t\treturn *ret_;"
			elif self.ret_type.name in known_containers:
				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)
				text += "\n\t\treturn ret____tmp;"
			else:
				text += "\n\t\treturn ret_;"
		text += "\n\t}\n"
		return text

	def gen_def_virtual(self):
		if self.duplicate:
			return ""
		if not self.is_virtual:
			return self.gen_def()
		text =  "\n\t// WRAPPED from \"" + self.orig_text.replace("\n"," ") + "\" in " + self.containing_file
		text += "\n\t"
		if self.is_static:
			text += "static "
		text += self.ret_type.gen_text() + " " + self.member_of.name + "::" + self.name + "("
		for arg in self.args:
			text += arg.gen_listitem_cpp()
			text += ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ")\n\t{"
		for arg in self.args:
			text += arg.gen_translation_cpp()
		text += "\n\t\t"
		if self.member_of == None:
			text += "::" + self.namespace + "::" + self.alias + "("
		elif self.is_static:
			text += self.member_of.namespace + "::" + self.member_of.name + "::" + self.name + "("
		else:
			text += "py_" + self.alias + "("
		for arg in self.args:
			text += arg.gen_call_cpp() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		if self.ret_type.name in classnames:
			text += ")"
		text += ");"
		for arg in self.args:
			text += arg.gen_cleanup()
		text += "\n\t}\n"
		return text

	def gen_default_impl(self):
		if self.duplicate:
			return ""
		if not self.is_virtual:
			return ""
		text = "\n\n\t\t" + self.ret_type.gen_text() + " py_" + self.alias + "("
		for arg in self.args:
			text += arg.gen_listitem() + ", "
		if len(self.args) > 0:
			text = text[:-2]

		call_string = "py_" + self.alias + "("
		for arg in self.args:
			call_string += arg.gen_varname() + ", "
		if len(self.args) > 0:
			call_string = call_string[0:-2]
		call_string += ");"

		text += ")\n\t\t{"
		text += "\n\t\t\tif(boost::python::override py_" + self.alias + " = this->get_override(\"py_" + self.alias + "\"))"
		text += "\n\t\t\t\t" + call_string
		text += "\n\t\t\telse"
		text += "\n\t\t\t\t" + self.member_of.name + "::" + call_string
		text += "\n\t\t}"

		text += "\n\n\t\t" + self.ret_type.gen_text() + " default_py_" + self.alias + "("
		for arg in self.args:
			text += arg.gen_listitem() + ", "
		if len(self.args) > 0:
			text = text[:-2]
		text += ")\n\t\t{"
		text += "\n\t\t\tthis->" + self.member_of.name + "::" + call_string
		text += "\n\t\t}"
		return text


	def gen_boost_py(self):
		if self.duplicate:
			return ""
		if self.member_of == None:
			text = "\n\t\tdef"
		else:
			text = "\n\t\t\t.def"
		if len(self.args) > -1:
			if self.ret_type.name in known_containers:
				text += "<" + known_containers[self.ret_type.name].typename + " "
			else:
				text += "<" + self.ret_type.name + " "
			if self.member_of == None or self.is_static:
				text += "(*)("
			else:
				text += "(" + self.member_of.name + "::*)("
			for a in self.args:
				text += a.gen_listitem_hash() + ", "
			if len(self.args) > 0:
				text = text[0:-2] + ")>"
			else:
				text += "void)>"

		if self.is_operator:
			text += "(\"" + wrappable_operators[self.name.replace("operator","")] + "\""
		else:
			if self.member_of != None and self.member_of.link_type == link_types.derive and self.is_virtual:
				text += "(\"py_" + self.alias + "\""
			else:
				text += "(\"" + self.alias + "\""
		if self.member_of != None:
			text += ", &" + self.member_of.name + "::"
			if self.member_of.link_type == link_types.derive and self.is_virtual:
				text += "py_" + self.alias
				text += ", &" + self.member_of.name + "Wrap::default_py_" + self.alias
			else:
				text += self.alias

			text += ")"
		else:
			text += ", " + "YOSYS_PYTHON::" + self.alias + ");"
		return text

class WMember:
	orig_text = None
	wtype = attr_types.default
	name = None
	containing_file = None
	member_of = None
	namespace = ""
	is_const = False

	def from_string(str_def, containing_file, class_, line_number, namespace):
		member = WMember()
		member.orig_text = str_def
		member.wtype = None
		member.name = ""
		member.containing_file = containing_file
		member.member_of = class_
		member.namespace = namespace
		member.is_const = False

		if str.startswith(str_def, "const "):
			member.is_const = True
			str_def = str_def[6:]

		if str_def.count(" ") == 0:
			return None

		parts = split_list(str_def.strip(), " ")

		prefix = ""
		i = 0
		for part in parts:
			if part in ["unsigned", "long", "short"]:
				prefix += part + " "
				i += 1
			else:
				break
		parts = parts[i:]

		if len(parts) <= 1:
			return None

		member.wtype = WType.from_string(prefix + parts[0], containing_file, line_number)

		if member.wtype == None:
			return None

		str_def = parts[1]
		for part in parts[2:]:
			str_def = str_def + " " + part

		if str_def.find("(") != -1 or str_def.find(")") != -1 or str_def.find("{") != -1 or str_def.find("}") != -1:
			return None

		found = str_def.find(";")
		if found == -1:
			return None

		found_eq = str_def.find("=")
		if found_eq != -1:
			found = found_eq

		member.name = str_def[:found]
		str_def = str_def[found+1:]
		if member.name.find("*") == 0:
			member.name = member.name.replace("*", "")
			member.wtype.attr_type = attr_types.star
		if member.name.find("&&") == 0:
			member.name = member.name.replace("&&", "")
			member.wtype.attr_type = attr_types.ampamp
		if member.name.find("&") == 0:
			member.name = member.name.replace("&", "")
			member.wtype.attr_type = attr_types.amp

		if(len(str_def.strip()) != 0):
			return None

		if len(member.name.split(",")) > 1:
			member_list = []
			for name in member.name.split(","):
				name = name.strip();
				member_list.append(WMember())
				member_list[-1].orig_text = member.orig_text
				member_list[-1].wtype = member.wtype
				member_list[-1].name = name
				member_list[-1].containing_file = member.containing_file
				member_list[-1].member_of = member.member_of
				member_list[-1].namespace = member.namespace
				member_list[-1].is_const = member.is_const
			return member_list

		return member

	def gen_decl(self):
		text = "\n\t\t" + self.wtype.gen_text() + " get_var_py_" + self.name + "();\n"
		if self.is_const:
			return text
		if self.wtype.name in classnames:
			text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs);\n"
		else:
			text += "\n\t\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs);\n"
		return text

	def gen_def(self):
		text = "\n\t" + self.wtype.gen_text() + " " + self.member_of.name +"::get_var_py_" + self.name + "()"
		text += "\n\t{\n\t\t"
		if self.wtype.attr_type == attr_types.star:
			text += "if(this->get_cpp_obj()->" + self.name + " == NULL)\n\t\t\t"
			text += "throw std::runtime_error(\"Member \\\"" + self.name + "\\\" is NULL\");\n\t\t"
		if self.wtype.name in known_containers:
			text += self.wtype.gen_text_cpp()
		else:
			text += self.wtype.gen_text()

		if self.wtype.name in classnames or (self.wtype.name in known_containers and self.wtype.attr_type == attr_types.star):
			text += "*"
		text += " ret_ = "
		if self.wtype.name in classnames:
			text += self.wtype.name + "::get_py_obj("
			if self.wtype.attr_type != attr_types.star:
				text += "&"
		text += "this->get_cpp_obj()->" + self.name
		if self.wtype.name in classnames:
			text += ")"
		text += ";"
		
		if self.wtype.name in classnames:
			text += "\n\t\treturn *ret_;"
		elif self.wtype.name in known_containers:
			text += known_containers[self.wtype.name].translate_cpp("ret_", self.wtype.cont.args, "\n\t\t", self.wtype.attr_type == attr_types.star)
			text += "\n\t\treturn ret____tmp;"
		else:
			text += "\n\t\treturn ret_;"
		text += "\n\t}\n"

		if self.is_const:
			return text

		ret = Attribute(self.wtype, "rhs");

		if self.wtype.name in classnames:
			text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs)"
		else:
			text += "\n\tvoid " + self.member_of.name+ "::set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs)"
		text += "\n\t{"
		text += ret.gen_translation()
		text += "\n\t\tthis->get_cpp_obj()->" + self.name + " = " + ret.gen_call() + ";"
		text += "\n\t}\n"		

		return text;

	def gen_boost_py(self):
		text = "\n\t\t\t.add_property(\"" + self.name + "\", &" + self.member_of.name + "::get_var_py_" + self.name 
		if not self.is_const:
			text += ", &" + self.member_of.name + "::set_var_py_" + self.name
		text += ")"
		return text

class WGlobal:
	orig_text = None
	wtype = attr_types.default
	name = None
	containing_file = None
	namespace = ""
	is_const = False

	def from_string(str_def, containing_file, line_number, namespace):
		glbl = WGlobal()
		glbl.orig_text = str_def
		glbl.wtype = None
		glbl.name = ""
		glbl.containing_file = containing_file
		glbl.namespace = namespace
		glbl.is_const = False

		if not str.startswith(str_def, "extern"):
			return None
		str_def = str_def[7:]

		if str.startswith(str_def, "const "):
			glbl.is_const = True
			str_def = str_def[6:]

		if str_def.count(" ") == 0:
			return None

		parts = split_list(str_def.strip(), " ")

		prefix = ""
		i = 0
		for part in parts:
			if part in ["unsigned", "long", "short"]:
				prefix += part + " "
				i += 1
			else:
				break
		parts = parts[i:]

		if len(parts) <= 1:
			return None

		glbl.wtype = WType.from_string(prefix + parts[0], containing_file, line_number)

		if glbl.wtype == None:
			return None

		str_def = parts[1]
		for part in parts[2:]:
			str_def = str_def + " " + part

		if str_def.find("(") != -1 or str_def.find(")") != -1 or str_def.find("{") != -1 or str_def.find("}") != -1:
			return None

		found = str_def.find(";")
		if found == -1:
			return None

		found_eq = str_def.find("=")
		if found_eq != -1:
			found = found_eq

		glbl.name = str_def[:found]
		str_def = str_def[found+1:]
		if glbl.name.find("*") == 0:
			glbl.name = glbl.name.replace("*", "")
			glbl.wtype.attr_type = attr_types.star
		if glbl.name.find("&&") == 0:
			glbl.name = glbl.name.replace("&&", "")
			glbl.wtype.attr_type = attr_types.ampamp
		if glbl.name.find("&") == 0:
			glbl.name = glbl.name.replace("&", "")
			glbl.wtype.attr_type = attr_types.amp

		if(len(str_def.strip()) != 0):
			return None

		if len(glbl.name.split(",")) > 1:
			glbl_list = []
			for name in glbl.name.split(","):
				name = name.strip();
				glbl_list.append(WGlobal())
				glbl_list[-1].orig_text = glbl.orig_text
				glbl_list[-1].wtype = glbl.wtype
				glbl_list[-1].name = name
				glbl_list[-1].containing_file = glbl.containing_file
				glbl_list[-1].namespace = glbl.namespace
				glbl_list[-1].is_const = glbl.is_const
			return glbl_list

		return glbl

	def gen_def(self):
		text = "\n\t"
		if self.is_const:
			text += "const "
		text += self.wtype.gen_text() + " get_var_py_" + self.name + "()"
		text += "\n\t{\n\t\t"
		if self.wtype.attr_type == attr_types.star:
			text += "if(" + self.namespace + "::" + self.name + " == NULL)\n\t\t\t"
			text += "throw std::runtime_error(\"" + self.namespace + "::" + self.name + " is NULL\");\n\t\t"
		if self.wtype.name in known_containers:
			text += self.wtype.gen_text_cpp()
		else:
			if self.is_const:
				text += "const "
			text += self.wtype.gen_text()

		if self.wtype.name in classnames or (self.wtype.name in known_containers and self.wtype.attr_type == attr_types.star):
			text += "*"
		text += " ret_ = "
		if self.wtype.name in classnames:
			text += self.wtype.name + "::get_py_obj("
			if self.wtype.attr_type != attr_types.star:
				text += "&"
		text += self.namespace + "::" + self.name
		if self.wtype.name in classnames:
			text += ")"
		text += ";"
		
		if self.wtype.name in classnames:
			text += "\n\t\treturn *ret_;"
		elif self.wtype.name in known_containers:
			text += known_containers[self.wtype.name].translate_cpp("ret_", self.wtype.cont.args, "\n\t\t", self.wtype.attr_type == attr_types.star)
			text += "\n\t\treturn ret____tmp;"
		else:
			text += "\n\t\treturn ret_;"
		text += "\n\t}\n"

		if self.is_const:
			return text

		ret = Attribute(self.wtype, "rhs");

		if self.wtype.name in classnames:
			text += "\n\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " *rhs)"
		else:
			text += "\n\tvoid set_var_py_" + self.name + "(" + self.wtype.gen_text() + " rhs)"
		text += "\n\t{"
		text += ret.gen_translation()
		text += "\n\t\t" + self.namespace + "::" + self.name + " = " + ret.gen_call() + ";"
		text += "\n\t}\n"		

		return text;

	def gen_boost_py(self):
		text = "\n\t\t\t.add_static_property(\"" + self.name + "\", &" + "YOSYS_PYTHON::get_var_py_" + self.name 
		if not self.is_const:
			text += ", &YOSYS_PYTHON::set_var_py_" + self.name
		text += ")"
		return text

def concat_namespace(tuple_list):
	if len(tuple_list) == 0:
		return ""
	ret = ""
	for namespace in tuple_list:
		ret += "::" + namespace[0]
	return ret[2:]

def calc_ident(text):
	if len(text) == 0 or text[0] != ' ':
		return 0
	return calc_ident(text[1:]) + 1

def assure_length(text, length, left = False):
	if len(text) > length:
		return text[:length]
	if left:
		return text + " "*(length - len(text))
	return " "*(length - len(text)) + text
	
def parse_header(source):
	debug("Parsing " + source.name + ".pyh",1)
	source_file = open(source.name + ".pyh", "r")

	source_text = []
	in_line = source_file.readline()

	namespaces = []

	while(in_line):
		if(len(in_line)>1):
			source_text.append(in_line.replace("char *", "char_p ").replace("char* ", "char_p "))
		in_line = source_file.readline()

	i = 0

	namespaces = []
	class_ = None
	private_segment = False

	while i < len(source_text):
		line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", "                    namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END","                    }")
		ugly_line = unpretty_string(line)

		# for anonymous unions, ignore union enclosure by skipping start line and replacing end line with new line
		if 'union {' in line:
			j = i+1
			while j < len(source_text):
				union_line = source_text[j]
				if '};' in union_line:
					source_text[j] = '\n'
					break
				j += 1
			if j != len(source_text):
				i += 1
				continue

		if str.startswith(ugly_line, "namespace "):# and ugly_line.find("std") == -1 and ugly_line.find("__") == -1:
			namespace_name = ugly_line[10:].replace("{","").strip()
			namespaces.append((namespace_name, ugly_line.count("{")))
			debug("-----NAMESPACE " + concat_namespace(namespaces) + "-----",3)
			i += 1
			continue

		if len(namespaces) != 0:
			namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
			if namespaces[-1][1] == 0:
				debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
				del namespaces[-1]
				i += 1
				continue

		if class_ == None and (str.startswith(ugly_line, "struct ") or str.startswith(ugly_line, "class")) and ugly_line.count(";") == 0:

			struct_name = ugly_line.split(" ")[1].split("::")[-1]
			impl_namespaces = ugly_line.split(" ")[1].split("::")[:-1]
			complete_namespace = concat_namespace(namespaces)
			for namespace in impl_namespaces:
				complete_namespace += "::" + namespace
			debug("\tFound " + struct_name + " in " + complete_namespace,2)

			base_class_name = None
			if len(ugly_line.split(" : ")) > 1: # class is derived
				deriv_str = ugly_line.split(" : ")[1]
				if len(deriv_str.split("::")) > 1: # namespace of base class is given
					base_class_name = deriv_str.split("::", 1)[1]
				else:
					base_class_name = deriv_str.split(" ")[0]
				debug("\t  " + struct_name + " is derived from " + base_class_name,2)
			base_class = class_by_name(base_class_name)

			class_ = (class_by_name(struct_name), ugly_line.count("{"))#calc_ident(line))
			if struct_name in classnames:
				class_[0].namespace = complete_namespace
				class_[0].base_class = base_class
			i += 1
			continue

		if class_ != None:
			class_ = (class_[0], class_[1] + ugly_line.count("{") - ugly_line.count("}"))
			if class_[1] == 0:
				if class_[0] == None:
					debug("\tExiting unknown class", 3)
				else:
					debug("\tExiting class " + class_[0].name, 3)
				class_ = None
				private_segment = False
				i += 1
				continue

		if class_ != None and (line.find("private:") != -1 or line.find("protected:") != -1):
			private_segment = True
			i += 1
			continue
		if class_ != None and line.find("public:") != -1:
			private_segment = False
			i += 1
			continue

		candidate = None

		if private_segment and class_ != None and class_[0] != None:
			candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i, True)
			if candidate != None:
				debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
				class_[0].found_constrs.append(candidate)
				i += 1
				continue

		if not private_segment and (class_ == None or class_[0] != None):
			if class_ != None:
				candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
			else:
				candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
			if candidate != None and candidate.name.find("::") == -1:
				if class_ == None:
					debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
					unowned_functions.append(candidate)
				else:
					debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
					class_[0].found_funs.append(candidate)
			else:
				candidate = WEnum.from_string(ugly_line, concat_namespace(namespaces), i)
				if candidate != None:
					enums.append(candidate)
					debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
				elif class_ != None and class_[1] == 1:
					candidate = WConstructor.from_string(ugly_line, source.name, class_[0], i)
					if candidate != None:
						debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
						class_[0].found_constrs.append(candidate)
					else:
						candidate = WMember.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
						if candidate != None:
							if type(candidate) == list:
								for c in candidate:
									debug("\t\tFound member \"" + c.name + "\" of class \"" + class_[0].name + "\" of type \"" + c.wtype.name + "\"", 2)
								class_[0].found_vars.extend(candidate)
							else:
								debug("\t\tFound member \"" + candidate.name + "\" of class \"" + class_[0].name + "\" of type \"" + candidate.wtype.name + "\"", 2)
								class_[0].found_vars.append(candidate)
				if candidate == None and class_ == None:
					candidate = WGlobal.from_string(ugly_line, source.name, i, concat_namespace(namespaces))
					if candidate != None:
						if type(candidate) == list:
							for c in candidate:
								glbls.append(c)
								debug("\tFound global \"" + c.name + "\" in namespace " + concat_namespace(namespaces), 2)
						else:
							glbls.append(candidate)
							debug("\tFound global \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces), 2)

			j = i
			line = unpretty_string(line)
			while candidate == None and j+1 < len(source_text) and  line.count(';') <= 1 and line.count("(") >= line.count(")"):
				j += 1
				line = line + "\n" + unpretty_string(source_text[j])
				if class_ != None:
					candidate = WFunction.from_string(ugly_line, source.name, class_[0], i, concat_namespace(namespaces))
				else:
					candidate = WFunction.from_string(ugly_line, source.name, None, i, concat_namespace(namespaces))
				if candidate != None and candidate.name.find("::") == -1:
					if class_ == None:
						debug("\tFound unowned function \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
						unowned_functions.append(candidate)
					else:
						debug("\t\tFound function \"" + candidate.name + "\" of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
						class_[0].found_funs.append(candidate)
					continue
				candidate = WEnum.from_string(line, concat_namespace(namespaces), i)
				if candidate != None:
					enums.append(candidate)
					debug("\tFound enum \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces),2)
					continue
				if class_ != None:
					candidate = WConstructor.from_string(line, source.name, class_[0], i)
					if candidate != None:
						debug("\t\tFound constructor of class \"" + class_[0].name + "\" in namespace " + concat_namespace(namespaces),2)
						class_[0].found_constrs.append(candidate)
						continue
				if class_ == None:
					candidate = WGlobal.from_string(line, source.name, i, concat_namespace(namespaces))
					if candidate != None:
						if type(candidate) == list:
							for c in candidate:
								glbls.append(c)
								debug("\tFound global \"" + c.name + "\" in namespace " + concat_namespace(namespaces), 2)
						else:
							glbls.append(candidate)
							debug("\tFound global \"" + candidate.name + "\" in namespace " + concat_namespace(namespaces), 2)
						continue
		if candidate != None:
			while i < j:
				i += 1
				line = source_text[i].replace("YOSYS_NAMESPACE_BEGIN", "                    namespace YOSYS_NAMESPACE{").replace("YOSYS_NAMESPACE_END","                    }")
				ugly_line = unpretty_string(line)
				if len(namespaces) != 0:
					namespaces[-1] = (namespaces[-1][0], namespaces[-1][1] + ugly_line.count("{") - ugly_line.count("}"))
					if namespaces[-1][1] == 0:
						debug("-----END NAMESPACE " + concat_namespace(namespaces) + "-----",3)
						del namespaces[-1]
				if class_ != None:
					class_ = (class_[0] , class_[1] + ugly_line.count("{") - ugly_line.count("}"))
					if class_[1] == 0:
						if class_[0] == None:
							debug("\tExiting unknown class", 3)
						else:
							debug("\tExiting class " + class_[0].name, 3)
						class_ = None
						private_segment = False
			i += 1
		else:
			i += 1

def debug(message, level):
	if level <= debug.debug_level:
		print(message)

def expand_function(f):
	fun_list = []
	arg_list = []
	for arg in f.args:
		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")):
			fi = copy.deepcopy(f)
			fi.args = copy.deepcopy(arg_list)
			fun_list.append(fi)
		arg_list.append(arg)
	fun_list.append(f)
	return fun_list

def expand_functions():
	global unowned_functions
	new_funs = []
	for fun in unowned_functions:
		new_funs.extend(expand_function(fun))
	unowned_functions = new_funs
	for source in sources:
		for class_ in source.classes:
			new_funs = []
			for fun in class_.found_funs:
				new_funs.extend(expand_function(fun))
			class_.found_funs = new_funs

def inherit_members():
	for source in sources:
		for class_ in source.classes:
			if class_.base_class:
				base_funs = copy.deepcopy(class_.base_class.found_funs)
				for fun in base_funs:
					fun.member_of = class_
					fun.namespace = class_.namespace
				base_vars = copy.deepcopy(class_.base_class.found_vars)
				for var in base_vars:
					var.member_of = class_
					var.namespace = class_.namespace
				class_.found_funs.extend(base_funs)
				class_.found_vars.extend(base_vars)

def clean_duplicates():
	for source in sources:
		for class_ in source.classes:
			known_decls = {}
			for fun in class_.found_funs:
				if fun.gen_decl_hash_py() in known_decls:
					debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
					other = known_decls[fun.gen_decl_hash_py()]
					other.gen_alias()
					fun.gen_alias()
					if fun.gen_decl_hash_py() == other.gen_decl_hash_py():
						fun.duplicate = True
						debug("Disabled \"" + fun.gen_decl_hash_py() + "\"", 3)
				else:
					known_decls[fun.gen_decl_hash_py()] = fun
			known_decls = []
			for con in class_.found_constrs:
				if con.gen_decl_hash_py() in known_decls:
					debug("Multiple declarations of " + con.gen_decl_hash_py(),3)
					con.duplicate = True
				else:
					known_decls.append(con.gen_decl_hash_py())
	known_decls = []
	for fun in unowned_functions:
		if fun.gen_decl_hash_py() in known_decls:
			debug("Multiple declarations of " + fun.gen_decl_hash_py(),3)
			fun.duplicate = True
		else:
			known_decls.append(fun.gen_decl_hash_py())

def gen_wrappers(filename, debug_level_ = 0):
	debug.debug_level = debug_level_
	for source in sources:
		parse_header(source)

	expand_functions()
	inherit_members()
	clean_duplicates()

	import shutil
	import math
	col = shutil.get_terminal_size((80,20)).columns
	debug("-"*col, 1)
	debug("-"*math.floor((col-7)/2)+"SUMMARY"+"-"*math.ceil((col-7)/2), 1)
	debug("-"*col, 1)
	for source in sources:
		for class_ in source.classes:
			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)
			if len(class_.found_constrs) == 0:
				class_.found_constrs.append(WConstructor(source.name, class_))
	debug(str(len(unowned_functions)) + " functions are unowned", 1)
	debug(str(len(unowned_functions)) + " global variables", 1)
	for enum in enums:
		debug("Enum " + assure_length(enum.name, len(max(enum_names, key=len)), True) + " contains " + assure_length(str(len(enum.values)), 2, False) + " values", 1)
	debug("-"*col, 1)
	wrapper_file = open(filename, "w+")
	wrapper_file.write(
"""/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Claire Xenia Wolf <claire@yosyshq.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 *  This is a generated file and can be overwritten by make
 */

#ifdef WITH_PYTHON
""")
	for source in sources:
		wrapper_file.write("#include \""+source.name+".h\"\n")
	wrapper_file.write("""
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/wrapper.hpp>
#include <boost/python/call.hpp>
#include <boost/python.hpp>
#include <iosfwd> // std::streamsize
#include <iostream>
#include <boost/iostreams/concepts.hpp>	// boost::iostreams::sink
#include <boost/iostreams/stream.hpp>
USING_YOSYS_NAMESPACE

namespace YOSYS_PYTHON {

	struct YosysStatics{};
""")

	for source in sources:
		for wclass in source.classes:
			wrapper_file.write("\n\tstruct " + wclass.name + ";")

	wrapper_file.write("\n")

	for source in sources:
		for wclass in source.classes:
			wrapper_file.write(wclass.gen_decl(source.name))

	wrapper_file.write("\n")

	for source in sources:
		for wclass in source.classes:
			wrapper_file.write(wclass.gen_funs(source.name))

	for fun in unowned_functions:
		wrapper_file.write(fun.gen_def())

	for glbl in glbls:
		wrapper_file.write(glbl.gen_def())

	wrapper_file.write("""	struct Initializer
	{
		Initializer() {
			if(!Yosys::yosys_already_setup())
			{
				Yosys::log_streams.push_back(&std::cout);
				Yosys::log_error_stderr = true;
				Yosys::yosys_setup();
			}
		}

		Initializer(Initializer const &) {}

		~Initializer() {
			Yosys::yosys_shutdown();
		}
	};


	/// source: https://stackoverflow.com/questions/26033781/converting-python-io-object-to-stdostream-when-using-boostpython?noredirect=1&lq=1
	/// @brief Type that implements the Boost.IOStream's Sink and Flushable
	///        concept for writing data to Python object that support:
	///          n = object.write(str) # n = None or bytes written
	///          object.flush()        # if flush exists, then it is callable
	class PythonOutputDevice
	{
	public:

		// This class models both the Sink and Flushable concepts.
		struct category
			: boost::iostreams::sink_tag,
				boost::iostreams::flushable_tag
		{};

		explicit
		PythonOutputDevice(boost::python::object object)
			: object_(object)
		{}

	// Sink concept.
	public:

		typedef char char_type;

		std::streamsize write(const char* buffer, std::streamsize buffer_size)
		{
			namespace python = boost::python;
			// Copy the buffer to a python string.
			python::str data(buffer, buffer_size);

			// Invoke write on the python object, passing in the data.	The following
			// is equivalent to:
			//	 n = object_.write(data)
			python::extract<std::streamsize> bytes_written(
				object_.attr("write")(data));

			// Per the Sink concept, return the number of bytes written.	If the
			// Python return value provides a numeric result, then use it.	Otherwise,
			// such as the case of a File object, use the buffer_size.
			return bytes_written.check()
				? bytes_written
				: buffer_size;
		}

	// Flushable concept.
	public:

		bool flush()
		{
			// If flush exists, then call it.
			boost::python::object flush = object_.attr("flush");
			if (!flush.is_none())
			{
				flush();
			}

			// Always return true.	If an error occurs, an exception should be thrown.
				return true;
		}

	private:
		boost::python::object object_;
	};

	/// @brief Use an auxiliary function to adapt the legacy function.
	void log_to_stream(boost::python::object object)
	{
		// Create an ostream that delegates to the python object.
		boost::iostreams::stream<PythonOutputDevice>* output = new boost::iostreams::stream<PythonOutputDevice>(object);
		Yosys::log_streams.insert(Yosys::log_streams.begin(), output);
	};


	BOOST_PYTHON_MODULE(libyosys)
	{
		using namespace boost::python;

		class_<Initializer>("Initializer");
		scope().attr("_hidden") = new Initializer();

		def("log_to_stream", &log_to_stream);
""")

	for enum in enums:
		wrapper_file.write(enum.gen_boost_py())

	for source in sources:
		for wclass in source.classes:
			wrapper_file.write(wclass.gen_boost_py())

	for fun in unowned_functions:
		wrapper_file.write(fun.gen_boost_py())

	wrapper_file.write("\n\n\t\tclass_<YosysStatics>(\"Yosys\")\n")
	for glbl in glbls:
		wrapper_file.write(glbl.gen_boost_py())
	wrapper_file.write("\t\t;\n")

	wrapper_file.write("\n\t}\n}\n#endif")

def print_includes():
	for source in sources:
		print(source.name + ".pyh")