[a9481d]: parsers.py Maximize Restore History

Download this file

parsers.py    188 lines (170 with data), 5.2 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 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
#!/usr/bin/python
import time
import compiler
from compiler.ast import Function, Class
import keyword
import os
eol = os.linesep
#def new_kwl():
# kwl = {}
# for i in keyword.kwlist:
# kwl[i] = []
# return kwl
def detectLineEndings(text):
crlf_ = text.count('\r\n')
lf_ = text.count('\n')
cr_ = text.count('\r')
mx = max(lf_, cr_)
if not mx:
return eol
elif crlf_ >= mx/2:
return '\r\n'
elif lf_ is mx:
return '\n'
else:# cr_ is mx:
return '\r'
def recur_compiled(obj, hier, lines):
if isinstance(obj, Function) or isinstance(obj, Class):
h = hier + [obj.name]
if obj.doc is None:
docstring = {obj.name: ['']}
else:
docstring = {obj.name: [obj.doc]}
if isinstance(obj, Function):
n = 'def '+obj.name
if not obj.doc:
docstring[obj.name][0] = "%s(%s) %s"%(obj.name, ', '.join(obj.argnames), '.'.join(h))
if obj.name == '__init__':
if hier:
if hier[-1] in docstring:
docstring[hier[-1]].append(docstring[obj.name][0])
else:
docstring[hier[-1]] = [docstring[obj.name][0]]
else:# isinstance(obj, Class)
n = 'class '+obj.name
out = [(n, (n.lower(), obj.lineno-1), leading(lines[obj.lineno-1]), [])]
ot = out[0][-1]
else:
h = hier
docstring = {}
out = []
ot = out
for i in obj.getChildNodes():
o, d = recur_compiled(i, h, lines)
ot.extend(o)
for nam, dsl in d.iteritems():
if nam in docstring: docstring[nam].extend(dsl)
else: docstring[nam] = dsl
return out, docstring
def slow_parser(source, line_ending, flat=0):
#docstring = new_kwl()
lines = source.split(line_ending)
mod = compiler.parse(source)
hier, docstring = recur_compiled(mod, [], lines)
#for nam, dsl in ds.iteritems():
# if nam in docstring: docstring[nam].extend(dsl)
# else: docstring[nam] = dsl
new_ds = {}
for i,j in docstring.iteritems():
#pulling out all the unused ones
new_ds[i] = filter(None, j)
if flat == 0:
return hier, new_ds.keys()
elif flat == 1:
return new_ds
else:
return hier, new_ds.keys(), new_ds
def leading(line):
cur = 0
while line[cur:cur+1] == ' ':
cur += 1
return cur
def fast_parser(source, line_ending, flat=0):
lines = source.replace('\t', 8*' ').split(line_ending)
docstring = {} #new_kwl()
out = []
stk = []
line_no = -1
for line in lines:
line_no += 1
ls = line.strip()
na = ls.find('(')
if na == -1:
na = ls.find(':')
for i, li in [('def ', 4), ('class ', 6)]:
if ls[:li] == i:
if na != -1:
fn = ls[li:na].strip()
if fn:
lead = leading(line)
while stk and (stk[-1][2] >= lead):
prev = stk.pop()
if stk: stk[-1][-1].append(prev)
else: out.append(prev)
nam = i+fn
nl = nam.lower()
if not fn in docstring: docstring[fn] = []
stk.append([nam, (nl, line_no), lead, []])
break
#else non-function or non-class definition lines
while len(stk)>1:
a = stk.pop()
stk[-1][-1].append(a)
out.extend(stk)
if flat == 0:
return out, docstring.keys()
elif flat==1:
return docstring
else:
return out, docstring.keys(), docstring
def tim(p=1, ct = [None]):
if ct[0] == None:
ct[0] = time.time()
else:
ret = time.time() - ct[0]
ct[0] = time.time()
if p: print ret,
return ret
def test():
import sys, time
if len(sys.argv)>1:
fil = open(sys.argv[1], 'r')
txt = fil.read()
fil.close()
tim();print 'fast parser...',
fast_parser(txt, detectLineEndings(txt))
tim();print 'done.\nslow parser...',
a,b,c = slow_parser(txt, detectLineEndings(txt), 2)
tim();print 'done.'
import pprint
pprint.pprint(c)
else:
print 'usage:\n python parsers.py <source file>'
def main():
import fileinput
import sys
#get the lines to the parsable file
lines = []
fil = '-'
if len(sys.argv)>1 and sys.argv[1]:
fil = sys.argv[1]
for line in fileinput.input(fil):
lines.append(line)
#parse the file
toparse = ''.join(lines)
le = detectLineEndings(toparse)
try:
toprint = slow_parser(toparse, le, 2)
except:
toprint = fast_parser(toparse, le)
#print parsed representation
if fil == '-':
print repr(toprint)
else:
print fil
os.remove(fil)
a = open("%s.out"%fil, 'w')
a.write(repr(toprint))
a.close()
if __name__ == '__main__':
main()