| 1 |
import re |
| 2 |
from os import listdir |
| 3 |
from sys import stdin, stdout, stderr |
| 4 |
from pypy import pypydir |
| 5 |
|
| 6 |
where = pypydir + '/objspace/std/' |
| 7 |
quote = '(' + "'" + '|' + '"' + ')' |
| 8 |
triplequotes = '(' + "'''" + '|' + '"""' + ')' |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
def mk_std_filelist(): |
| 13 |
''' go to pypy/objs/std and get all the *type.py files, except for |
| 14 |
typetype.py which has to be patched by hand.''' |
| 15 |
filelist = [] |
| 16 |
filenames = listdir(where) |
| 17 |
for f in filenames: |
| 18 |
if f.endswith('type.py'): |
| 19 |
if f != 'typetype.py': |
| 20 |
filelist.append(f) |
| 21 |
return filelist |
| 22 |
|
| 23 |
|
| 24 |
def compile_doc(): |
| 25 |
return re.compile(r"__doc__\s+=\s+" + triplequotes + |
| 26 |
r"(?P<docstring>.*)"+ triplequotes , |
| 27 |
re.DOTALL |
| 28 |
) |
| 29 |
|
| 30 |
def compile_typedef(typ): |
| 31 |
return re.compile(r"(?P<whitespace>\s+)" |
| 32 |
+ r"(?P<typeassign>" + typ |
| 33 |
+ "_typedef = StdTypeDef+\s*\(\s*" |
| 34 |
+ quote + typ + quote + ",).*" |
| 35 |
+ r"(?P<indent>^\s+)" |
| 36 |
+ r"(?P<newassign>__new__\s*=\s*newmethod)", |
| 37 |
re.DOTALL | re.MULTILINE) |
| 38 |
|
| 39 |
def get_pypydoc(sourcefile): |
| 40 |
doc = compile_doc() |
| 41 |
|
| 42 |
try: |
| 43 |
pypydoc = doc.search(sourcefile).group('docstring') |
| 44 |
|
| 45 |
except AttributeError: |
| 46 |
return None |
| 47 |
|
| 48 |
return pypydoc |
| 49 |
|
| 50 |
def get_cpydoc(typ): |
| 51 |
|
| 52 |
try: |
| 53 |
cpydoc = eval(typ + '.__doc__') |
| 54 |
|
| 55 |
except NameError: |
| 56 |
cpydoc = None |
| 57 |
return cpydoc |
| 58 |
|
| 59 |
def add_docstring(typ, sourcefile): |
| 60 |
pypydoc = get_pypydoc(sourcefile) |
| 61 |
cpydoc = get_cpydoc(typ) |
| 62 |
|
| 63 |
if pypydoc: |
| 64 |
stderr.write('%s: already has a pypy docstring\n' % typ) |
| 65 |
return None |
| 66 |
elif not cpydoc: |
| 67 |
stderr.write('%s: does not have a cpython docstring\n' % typ) |
| 68 |
return None |
| 69 |
else: |
| 70 |
docstring="__doc__ = '''" + cpydoc + "'''," |
| 71 |
|
| 72 |
typedef = compile_typedef(typ) |
| 73 |
newsearch = typedef.search(sourcefile) |
| 74 |
if not newsearch: |
| 75 |
stderr.write('%s: has a cpython docstring, but no __new__, to determine where to put it.\n' % typ) |
| 76 |
return None |
| 77 |
else: |
| 78 |
return re.sub(newsearch.group('indent') + |
| 79 |
newsearch.group('newassign'), |
| 80 |
newsearch.group('indent') + |
| 81 |
docstring + '\n' + |
| 82 |
newsearch.group('indent') + |
| 83 |
newsearch.group('newassign'), |
| 84 |
sourcefile) |
| 85 |
|
| 86 |
if __name__ == '__main__': |
| 87 |
|
| 88 |
filenames = mk_std_filelist() |
| 89 |
|
| 90 |
for f in filenames: |
| 91 |
inf = file(where + f).read() |
| 92 |
outs = add_docstring(f[:-7], inf) |
| 93 |
if outs is not None: |
| 94 |
outf = file(where + f, 'w') |
| 95 |
outf.write(outs) |