Debian Codegraph @

pypy/interpreter/pyparser/gendfa.py

raw symbols SCIP
1 #! /usr/bin/env python
2 """Module gendfa
3
4 Generates finite state automata for recognizing Python tokens. These are hand
5 coded versions of the regular expressions originally appearing in Ping's
6 tokenize module in the Python standard library.
7
8 When run from the command line, this should pretty print the DFA machinery.
9
10 To regenerate the dfa, run::
11
12 $ python gendfa.py > dfa_generated.py
13
14 $Id: genPytokenize.py,v 1.1 2003/10/02 17:37:17 jriehl Exp $
15 """
16
17 from pypy.interpreter.pyparser.pylexer import *
18 from pypy.interpreter.pyparser.automata import NonGreedyDFA, DFA, DEFAULT
19 from pypy.interpreter.pyparser import pytoken
20
21 NON_ASCII = "\x80"
22
23 def makePyPseudoDFA ():
24 import string
25 states = []
26 def makeEOL():
27 return group(states,
28 newArcPair(states, "\n"),
29 chain(states,
30 newArcPair(states, "\r"),
31 maybe(states, newArcPair(states, "\n"))))
32 # ____________________________________________________________
33 def makeLineCont ():
34 return chain(states,
35 newArcPair(states, "\\"),
36 makeEOL())
37 # ____________________________________________________________
38 # Ignore stuff
39 def makeWhitespace ():
40 return any(states, groupStr(states, " \f\t"))
41 # ____________________________________________________________
42 def makeComment ():
43 return chain(states,
44 newArcPair(states, "#"),
45 any(states, notGroupStr(states, "\r\n")))
46 # ____________________________________________________________
47 #ignore = chain(states,
48 # makeWhitespace(),
49 # any(states, chain(states,
50 # makeLineCont(),
51 # makeWhitespace())),
52 # maybe(states, makeComment()))
53 # ____________________________________________________________
54 # Names
55 name = chain(states,
56 groupStr(states, string.letters + "_" + NON_ASCII),
57 any(states, groupStr(states,
58 string.letters + string.digits + "_" +
59 NON_ASCII)))
60 # ____________________________________________________________
61 # Digits
62 def makeDigits ():
63 return groupStr(states, "0123456789")
64 def makeDigitsChain (digits="0123456789", first=None,
65 allow_leading_underscore=False):
66 if first is None:
67 first = digits
68 if allow_leading_underscore:
69 return group(states,
70 makeDigitsChain(digits=digits),
71 chain(states,
72 newArcPair(states, "_"),
73 makeDigitsChain(digits=digits)))
74 return chain(states,
75 groupStr(states, first),
76 any(states, groupStr(states, digits)),
77 any(states,
78 chain(states,
79 newArcPair(states, "_"),
80 atleastonce(states, groupStr(states, digits)))))
81
82 # ____________________________________________________________
83 # Integer numbers
84 hexNumber = chain(states,
85 newArcPair(states, "0"),
86 groupStr(states, "xX"),
87 makeDigitsChain("0123456789abcdefABCDEF",
88 allow_leading_underscore=True))
89 octNumber = chain(states,
90 newArcPair(states, "0"),
91 groupStr(states, "oO"),
92 makeDigitsChain("01234567",
93 allow_leading_underscore=True))
94 binNumber = chain(states,
95 newArcPair(states, "0"),
96 groupStr(states, "bB"),
97 makeDigitsChain("01",
98 allow_leading_underscore=True))
99 decNumber = makeDigitsChain(first="123456789")
100 zero = makeDigitsChain("0")
101 intNumber = group(states, hexNumber, octNumber, binNumber, decNumber, zero)
102 # ____________________________________________________________
103 # Exponents
104 def makeExp ():
105 return chain(states,
106 groupStr(states, "eE"),
107 maybe(states, groupStr(states, "+-")),
108 makeDigitsChain())
109
110 # ____________________________________________________________
111 # Floating point numbers
112 def makePointFloat ():
113 return group(states,
114 chain(states,
115 makeDigitsChain(),
116 newArcPair(states, "."),
117 any(states, makeDigitsChain())),
118 chain(states,
119 newArcPair(states, "."),
120 makeDigitsChain()))
121 def makeFloat ():
122 pointFloat = group(states,
123 makePointFloat(),
124 chain(states,
125 makePointFloat(),
126 makeExp()))
127 expFloat = chain(states,
128 makeDigitsChain(),
129 makeExp())
130 return group(states, pointFloat, expFloat)
131 # ____________________________________________________________
132 # Imaginary numbers
133 imagNumber = group(states,
134 chain(states,
135 makeDigitsChain(),
136 groupStr(states, "jJ")),
137 chain(states,
138 makeFloat(),
139 groupStr(states, "jJ")))
140 # ____________________________________________________________
141 # Any old number.
142 number = group(states, imagNumber, makeFloat(), intNumber)
143 # ____________________________________________________________
144 # Funny
145 # generate from pytoken
146 funny = []
147 for op in sorted(pytoken.python_opmap):
148 if op == "$NUM":
149 continue
150 funny.append(chainStr(states, op))
151 revdb_metavar = chain(states,
152 groupStr(states, "$"),
153 atleastonce(states, makeDigits()))
154 funny.append(revdb_metavar)
155 funny.append(makeEOL())
156 funny = group(states, *funny)
157 # ____________________________________________________________
158 def makeStrPrefix ():
159 return group(states,
160 chain(states,
161 maybe(states, groupStr(states, "rR")),
162 maybe(states, groupStr(states, "bBfF"))),
163 chain(states,
164 maybe(states, groupStr(states, "bBfF")),
165 maybe(states, groupStr(states, "rR"))),
166 maybe(states, groupStr(states, "uU")))
167 # ____________________________________________________________
168 contStr = group(states,
169 chain(states,
170 makeStrPrefix(),
171 newArcPair(states, "'"),
172 any(states,
173 notGroupStr(states, "\r\n'\\")),
174 any(states,
175 chain(states,
176 newArcPair(states, "\\"),
177 newArcPair(states, DEFAULT),
178 any(states,
179 notGroupStr(states, "\r\n'\\")))),
180 group(states,
181 newArcPair(states, "'"),
182 makeLineCont())),
183 chain(states,
184 makeStrPrefix(),
185 newArcPair(states, '"'),
186 any(states,
187 notGroupStr(states, '\r\n"\\')),
188 any(states,
189 chain(states,
190 newArcPair(states, "\\"),
191 newArcPair(states, DEFAULT),
192 any(states,
193 notGroupStr(states, '\r\n"\\')))),
194 group(states,
195 newArcPair(states, '"'),
196 makeLineCont())))
197 triple = chain(states,
198 makeStrPrefix(),
199 group(states,
200 chainStr(states, "'''"),
201 chainStr(states, '"""')))
202 pseudoExtras = group(states,
203 makeLineCont(),
204 makeComment(),
205 triple)
206 pseudoToken = chain(states,
207 makeWhitespace(),
208 group(states,
209 newArcPair(states, EMPTY),
210 pseudoExtras, number, funny, contStr, name))
211 dfaStates, dfaAccepts = nfaToDfa(states, *pseudoToken)
212 return DFA(dfaStates, dfaAccepts), dfaStates
213
214 # ______________________________________________________________________
215
216 def makePyEndDFAMap ():
217 states = []
218 single = chain(states,
219 any(states, notGroupStr(states, "'\\")),
220 any(states,
221 chain(states,
222 newArcPair(states, "\\"),
223 newArcPair(states, DEFAULT),
224 any(states, notGroupStr(states, "'\\")))),
225 newArcPair(states, "'"))
226 states, accepts = nfaToDfa(states, *single)
227 singleDFA = DFA(states, accepts)
228 states_singleDFA = states
229 states = []
230 double = chain(states,
231 any(states, notGroupStr(states, '"\\')),
232 any(states,
233 chain(states,
234 newArcPair(states, "\\"),
235 newArcPair(states, DEFAULT),
236 any(states, notGroupStr(states, '"\\')))),
237 newArcPair(states, '"'))
238 states, accepts = nfaToDfa(states, *double)
239 doubleDFA = DFA(states, accepts)
240 states_doubleDFA = states
241 states = []
242 single3 = chain(states,
243 any(states, notGroupStr(states, "'\\")),
244 any(states,
245 chain(states,
246 group(states,
247 chain(states,
248 newArcPair(states, "\\"),
249 newArcPair(states, DEFAULT)),
250 chain(states,
251 newArcPair(states, "'"),
252 notChainStr(states, "''"))),
253 any(states, notGroupStr(states, "'\\")))),
254 chainStr(states, "'''"))
255 states, accepts = nfaToDfa(states, *single3)
256 single3DFA = NonGreedyDFA(states, accepts)
257 states_single3DFA = states
258 states = []
259 double3 = chain(states,
260 any(states, notGroupStr(states, '"\\')),
261 any(states,
262 chain(states,
263 group(states,
264 chain(states,
265 newArcPair(states, "\\"),
266 newArcPair(states, DEFAULT)),
267 chain(states,
268 newArcPair(states, '"'),
269 notChainStr(states, '""'))),
270 any(states, notGroupStr(states, '"\\')))),
271 chainStr(states, '"""'))
272 states, accepts = nfaToDfa(states, *double3)
273 double3DFA = NonGreedyDFA(states, accepts)
274 states_double3DFA = states
275 return {"'" : (singleDFA, states_singleDFA),
276 '"' : (doubleDFA, states_doubleDFA),
277 "'''": (single3DFA, states_single3DFA),
278 '"""': (double3DFA, states_double3DFA)}
279
280 # ______________________________________________________________________
281
282 def output(name, dfa_class, dfa, states):
283 import textwrap
284 lines = []
285 i = 0
286 for line in textwrap.wrap(repr(dfa.accepts), width = 50):
287 if i == 0:
288 lines.append("accepts = ")
289 else:
290 lines.append(" ")
291 lines.append(line)
292 lines.append("\n")
293 i += 1
294 import StringIO
295 lines.append("states = [\n")
296 for numstate, state in enumerate(states):
297 lines.append(" # ")
298 lines.append(str(numstate))
299 lines.append("\n")
300 s = StringIO.StringIO()
301 i = 0
302 for k, v in sorted(state.items()):
303 i += 1
304 if k == DEFAULT:
305 k = "automata.DEFAULT"
306 else:
307 k = repr(k)
308 s.write(k)
309 s.write('::')
310 s.write(repr(v))
311 if i < len(state):
312 s.write(', ')
313 s.write('},')
314 i = 0
315 if len(state) <= 4:
316 text = [s.getvalue()]
317 else:
318 text = textwrap.wrap(s.getvalue(), width=36)
319 for line in text:
320 line = line.replace('::', ': ')
321 if i == 0:
322 lines.append(' {')
323 else:
324 lines.append(' ')
325 lines.append(line)
326 lines.append('\n')
327 i += 1
328 lines.append(" ]\n")
329 lines.append("%s = automata.%s(states, accepts)\n" % (name, dfa_class))
330 return ''.join(lines)
331
332 def main ():
333 print "# THIS FILE IS AUTOMATICALLY GENERATED BY gendfa.py"
334 print "# DO NOT EDIT"
335 print "# TO REGENERATE THE FILE, RUN:"
336 print "# python gendfa.py > dfa_generated.py"
337 print
338 print "from pypy.interpreter.pyparser import automata"
339 pseudoDFA, states_pseudoDFA = makePyPseudoDFA()
340 print output("pseudoDFA", "DFA", pseudoDFA, states_pseudoDFA)
341 endDFAMap = makePyEndDFAMap()
342 dfa, states = endDFAMap['"""']
343 print output("double3DFA", "NonGreedyDFA", dfa, states)
344 dfa, states = endDFAMap["'''"]
345 print output("single3DFA", "NonGreedyDFA", dfa, states)
346 dfa, states = endDFAMap["'"]
347 print output("singleDFA", "DFA", dfa, states)
348 dfa, states = endDFAMap['"']
349 print output("doubleDFA", "DFA", dfa, states)
350
351 # ______________________________________________________________________
352
353 if __name__ == "__main__":
354 main()