• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1from bgenOutput import *
2from bgenGeneratorGroup import GeneratorGroup
3
4class Module(GeneratorGroup):
5
6    def __init__(self, name, prefix = None,
7             includestuff = None,
8             finalstuff = None,
9             initstuff = None,
10             variablestuff = None,
11             longname = None):
12        GeneratorGroup.__init__(self, prefix or name)
13        self.name = name
14        if longname:
15            self.longname = longname
16        else:
17            self.longname = name
18        self.includestuff = includestuff
19        self.initstuff = initstuff
20        self.finalstuff = finalstuff
21        self.variablestuff = variablestuff
22        self.typeobjects = []
23
24    def addobject(self, od):
25        self.generators.append(od)
26        self.typeobjects.append(od)
27        od.setmodulename(self.longname)
28
29    def generate(self):
30        OutHeader1("Module " + self.name)
31        Output("#include \"Python.h\"")
32        Output()
33
34        if self.includestuff:
35            Output()
36            Output("%s", self.includestuff)
37
38        self.declareModuleVariables()
39
40        GeneratorGroup.generate(self)
41
42        if self.finalstuff:
43            Output()
44            Output("%s", self.finalstuff)
45
46        Output()
47        Output("void init%s(void)", self.name)
48        OutLbrace()
49        Output("PyObject *m;")
50        Output("PyObject *d;")
51        Output()
52
53        if self.initstuff:
54            Output("%s", self.initstuff)
55            Output()
56
57        Output("m = Py_InitModule(\"%s\", %s_methods);",
58               self.name, self.prefix)
59        Output("d = PyModule_GetDict(m);")
60        self.createModuleVariables()
61        OutRbrace()
62        OutHeader1("End module " + self.name)
63
64    def declareModuleVariables(self):
65        self.errorname = self.prefix + "_Error"
66        Output("static PyObject *%s;", self.errorname)
67
68    def createModuleVariables(self):
69        Output("""%s = %s;""", self.errorname, self.exceptionInitializer())
70        Output("""if (%s == NULL ||""", self.errorname)
71        Output("""    PyDict_SetItemString(d, "Error", %s) != 0)""",
72                                                       self.errorname)
73        IndentLevel()
74        Output("""return;""")
75        DedentLevel()
76        for tp in self.typeobjects:
77            tp.outputTypeObjectInitializer()
78        if self.variablestuff:
79            Output("%s", self.variablestuff)
80            Output()
81
82    def exceptionInitializer(self):
83        return """PyErr_NewException("%s.Error", NULL, NULL)""" % self.name
84
85
86def _test():
87    from bgenGenerator import FunctionGenerator
88    m = Module("spam", "", "#include <stdio.h>")
89    g = FunctionGenerator(None, "bacon")
90    m.add(g)
91    m.generate()
92
93if __name__ == "__main__":
94    _test()
95