3
from framer import template
4
from framer.util import cstring, unindent
7
METH_NOARGS = "METH_NOARGS"
8
METH_VARARGS = "METH_VARARGS"
18
def __init__(self, name):
20
self.ctype = "PyObject *"
24
return "%s%s" % (self.ctype, self.name)
26
def setfmt(self, code):
27
self.ctype = self._codes[code]
28
if self.ctype[-1] != "*":
31
_codes = {"O": "PyObject *",
36
if self.default is None:
37
return str(self) + ";"
39
return "%s = %s;" % (self, self.default)
41
class _ArgumentList(object):
43
# these instance variables should be initialized by subclasses
47
def __init__(self, args):
48
self.args = map(Argument, args)
53
def __getitem__(self, i):
56
def dump_decls(self, f):
59
class NoArgs(_ArgumentList):
61
def __init__(self, args):
63
super(NoArgs, self).__init__(args)
64
self.ml_meth = METH_NOARGS
67
return "PyObject *self"
69
class OneArg(_ArgumentList):
71
def __init__(self, args):
73
super(OneArg, self).__init__(args)
77
return "PyObject *self, %s" % self.args[0]
79
class VarArgs(_ArgumentList):
81
def __init__(self, args, fmt=None):
82
super(VarArgs, self).__init__(args)
83
self.ml_meth = METH_VARARGS
87
for code in parsefmt(fmt):
88
self.args[i].setfmt(code)
92
return "PyObject *self, PyObject *args"
95
return ", ".join(["&%s" % a.name for a in self.args])
97
def dump_decls(self, f):
99
print >> f, " %s" % a.decl()
101
def ArgumentList(func, method):
102
code = func.func_code
103
args = code.co_varnames[:code.co_argcount]
106
pyarg = getattr(func, "pyarg", None)
107
if pyarg is not None:
108
args = VarArgs(args, pyarg)
109
if func.func_defaults:
110
L = list(func.func_defaults)
112
i = len(args) - ndefault
114
args[i].default = L.pop(0)
128
def __init__(self, func, parent):
130
self._parent = parent
135
def p(templ, vars=None): # helper function to generate output
138
print >> f, templ % vars
141
p(template.docstring)
143
d = {"name" : self.vars["CName"],
144
"args" : self.args.c_args(),
146
p(template.funcdef_start, d)
148
self.args.dump_decls(f)
150
if self.args.ml_meth == METH_VARARGS:
153
p(template.funcdef_end)
156
self.__doc__ = self._func.__doc__
157
self.args = ArgumentList(self._func, self.method)
161
v["PythonName"] = self._func.__name__
162
s = v["CName"] = "%s_%s" % (self._parent.name, self._func.__name__)
163
v["DocstringVar"] = s + "_doc"
164
v["MethType"] = self.args.ml_meth
166
v["Docstring"] = cstring(unindent(self.__doc__))
167
if self.args.fmt is not None:
168
v["ArgParse"] = self.args.fmt
169
v["ArgTargets"] = self.args.targets()
171
class Method(Function):