source: vendor/python/2.5/Tools/modulator/genmodule.py

Last change on this file was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 4.7 KB
RevLine 
[3225]1#
2# Genmodule - A python program to help you build (template) modules.
3#
4# Usage:
5#
6# o = genmodule.object()
7# o.name = 'dwarve object'
8# o.abbrev = 'dw'
9# o.funclist = ['new', 'dealloc', 'getattr', 'setattr']
10# o.methodlist = ['dig']
11#
12# m = genmodule.module()
13# m.name = 'beings'
14# m.abbrev = 'be'
15# m.methodlist = ['newdwarve']
16# m.objects = [o]
17#
18# genmodule.write(sys.stdout, m)
19#
20import sys
21import os
22import varsubst
23
24error = 'genmodule.error'
25
26#
27# Names of functions in the object-description struct.
28#
29FUNCLIST = ['new', 'tp_dealloc', 'tp_print', 'tp_getattr', 'tp_setattr',
30 'tp_compare', 'tp_repr', 'tp_hash', 'tp_call', 'tp_str']
31TYPELIST = ['tp_as_number', 'tp_as_sequence', 'tp_as_mapping', 'structure']
32
33#
34# writer is a base class for the object and module classes
35# it contains code common to both.
36#
37class writer:
38 def __init__(self):
39 self._subst = None
40
41 def makesubst(self):
42 if not self._subst:
43 if not self.__dict__.has_key('abbrev'):
44 self.abbrev = self.name
45 self.Abbrev = self.abbrev[0].upper()+self.abbrev[1:]
46 subst = varsubst.Varsubst(self.__dict__)
47 subst.useindent(1)
48 self._subst = subst.subst
49
50 def addcode(self, name, fp):
51 ifp = self.opentemplate(name)
52 self.makesubst()
53 d = ifp.read()
54 d = self._subst(d)
55 fp.write(d)
56
57 def opentemplate(self, name):
58 for p in sys.path:
59 fn = os.path.join(p, name)
60 if os.path.exists(fn):
61 return open(fn, 'r')
62 fn = os.path.join(p, 'Templates')
63 fn = os.path.join(fn, name)
64 if os.path.exists(fn):
65 return open(fn, 'r')
66 raise error, 'Template '+name+' not found for '+self._type+' '+ \
67 self.name
68
69class module(writer):
70 _type = 'module'
71
72 def writecode(self, fp):
73 self.addcode('copyright', fp)
74 self.addcode('module_head', fp)
75 for o in self.objects:
76 o.writehead(fp)
77 for o in self.objects:
78 o.writebody(fp)
79 new_ml = ''
80 for fn in self.methodlist:
81 self.method = fn
82 self.addcode('module_method', fp)
83 new_ml = new_ml + (
84 '{"%s",\t(PyCFunction)%s_%s,\tMETH_VARARGS,\t%s_%s__doc__},\n'
85 %(fn, self.abbrev, fn, self.abbrev, fn))
86 self.methodlist = new_ml
87 self.addcode('module_tail', fp)
88
89class object(writer):
90 _type = 'object'
91 def __init__(self):
92 self.typelist = []
93 self.methodlist = []
94 self.funclist = ['new']
95 writer.__init__(self)
96
97 def writecode(self, fp):
98 self.addcode('copyright', fp)
99 self.writehead(fp)
100 self.writebody(fp)