Debian Codegraph @

rpython/rlib/parsing/test/test_pythonlexer.py

raw symbols SCIP
1 import py
2 from rpython.rlib.parsing.regexparse import parse_regex, make_runner
3 from rpython.rlib.parsing.lexer import Lexer, Token, SourcePos
4
5 # attempts at writing a Python-lexer
6
7 def group(*choices):
8 return '(' + '|'.join(choices) + ')'
9 def any(*choices):
10 return group(*choices) + '*'
11 def maybe(*choices):
12 return group(*choices) + '?'
13
14 #____________________________________________________________
15 # Numbers
16
17 Hexnumber = r'0[xX][0-9a-fA-F]*[lL]?' #XXX this parses 0xl, but shouldn't
18 Octnumber = r'0[0-7]*[lL]?'
19 Decnumber = r'[1-9][0-9]*[lL]?'
20 Intnumber = group(Hexnumber, Octnumber, Decnumber)
21 Exponent = r'[eE][\-\+]?[0-9]+'
22 Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
23 Expfloat = r'[0-9]+' + Exponent
24 Floatnumber = group(Pointfloat, Expfloat)
25 Imagnumber = group(r'(0|[1-9][0-9]*)[jJ]', Floatnumber + r'[jJ]')
26 Number = group(Imagnumber, Floatnumber, Intnumber)
27
28 #____________________________________________________________
29 # Strings
30
31 _stringheader = r"[uU]?[rR]?"
32
33 # ' or " string.
34 def make_single_string(delim):
35 normal_chars = r"[^\n\%s]*" % (delim, )
36 return "".join([_stringheader, delim, normal_chars,
37 any(r"\\." + normal_chars), delim])
38
39 # triple-quoted-strings
40 def make_triple_string(delim):
41 harmless = r"[^\%s]" % (delim, )
42 anyharmless = harmless + "*"
43 atleastoneharmless = harmless + "+"
44 normal_chars = anyharmless + any(group(delim, 2 * delim) +
45 atleastoneharmless)
46 triple = delim * 3
47 return "".join([_stringheader, triple, normal_chars,
48 any(r"\\." + normal_chars), triple])
49
50 def test_triple_regex():
51 delim = '"'
52 harmless = r"[^\%s]" % (delim, )
53 anyharmless = harmless + "*"
54 atleastoneharmless = harmless + "+"
55 normal_chars = anyharmless + any(group(delim, 2 * delim) +
56 atleastoneharmless)
57 runner = make_runner(normal_chars)
58 assert runner.recognize('""a""a""a""a')
59 assert not runner.recognize('""a""a"""a""a')
60
61 SingleString = group(make_single_string("'"),
62 make_single_string('"'))
63
64 TripleString = group(make_triple_string("'"),
65 make_triple_string('"'))
66
67 String = group(SingleString, TripleString)
68
69 #____________________________________________________________
70 # Ignored
71
72 Whitespace = r'[ \f\t]*'
73 Newline = r'\r?\n'
74 Linecontinue = r'\\' + Newline + any(Whitespace)
75 Comment = r'#[^\r\n]*'
76 Indent = Newline + any(Whitespace)
77 Simpleignore = Whitespace + any(Whitespace) + maybe(group(Comment, Linecontinue))
78 Ignore = group(Linecontinue, Comment, Simpleignore)
79
80 #____________________________________________________________
81
82 Special = r'[\:\;\.\,\`\@]'
83 Name = r'[a-zA-Z_][a-zA-Z0-9_]*'
84
85 Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
86 r"//=?",
87 r"[\+\-\*\/\%\&\|\^\=\<\>]=?",
88 r"~",
89 Special)
90
91 OpenBracket = r'[\[\(\{]'
92 CloseBracket = r'[\]\)\}]'
93
94 #____________________________________________________________
95 # all tokens
96
97 tokens = ["Number", "String", "Name", "Ignore", "Indent",
98 "OpenBracket", "CloseBracket", "Operator"]
99
100 def make_lexer():
101 return Lexer([parse_regex(globals()[r]) for r in tokens], tokens[:])
102
103 pythonlexer = make_lexer()
104
105 def postprocess(tokens):
106 parenthesis_level = 0
107 indentation_levels = [0]
108 output_tokens = []
109 for token in tokens:
110 if token.name == "OpenBracket":
111 parenthesis_level += 1
112 token.name = "Operator"
113 output_tokens.append(token)
114 elif token.name == "CloseBracket":
115 parenthesis_level -= 1
116 if parenthesis_level < 0:
117 XXX
118 token.name = "Operator"
119 output_tokens.append(token)
120 elif token.name == "Indent":
121 token.name = "Newline"
122 if parenthesis_level == 0:
123 s = token.source
124 length = len(s)
125 pos = 0
126 column = 0
127 # the token looks like this: \r?\n[ \f\t]*
128 if s[0] == '\n':
129 pos = 1
130 start = 1
131 else:
132 pos = 2
133 start = 2
134 while pos < length: # count the indentation depth of the whitespace
135 c = s[pos]
136 if c == ' ':
137 column = column + 1
138 elif c == '\t':
139 column = (column // tabsize + 1) * tabsize
140 elif c == '\f':
141 column = 0
142 pos = pos + 1
143 # split the token in two: one for the newline and one for the
144 output_tokens.append(Token("Newline", s[:start], token.source_pos))
145 if column > indentation_levels[-1]: # count indents or dedents
146 indentation_levels.append(column)
147 token.name = "Indent"
148 else:
149 dedented = False
150 while column < indentation_levels[-1]:
151 dedented = True
152 indentation_levels.pop()
153 if dedented:
154 token.name = "Dedent"
155 if token.name != "Newline":
156 token.source = s[start:]
157 token.source_pos.i += 1
158 token.source_pos.lineno += 1
159 token.source_pos.columnno = 0
160 output_tokens.append(token)
161 else:
162 pass # implicit line-continuations within parenthesis
163 elif token.name == "Ignore":
164 pass
165 else:
166 output_tokens.append(token)
167 return output_tokens
168
169 def pythonlex(s):
170 return postprocess(pythonlexer.tokenize(s))
171
172
173 def test_number():
174 for num in ['1.231e-4', '1j', '0J', '123J'
175 ]:
176 tokens = pythonlexer.tokenize(num)
177 token, = tokens
178 assert token.name == 'Number'
179 for intnum in ['1', '0', '0xABFfaf1928375']:
180 for suffix in ['', 'l', 'L']:
181 tokens = pythonlexer.tokenize(intnum + suffix)
182 token, = tokens
183 assert token.name == 'Number'
184
185 def test_single_quoted_string():
186 for s in ["""u'abc'""",
187 """ur'ab"c'""",
188 """UR'ab\\'c'""",
189 """'ab\\\nc'"""]:
190 tokens = pythonlexer.tokenize(s)
191 token, = tokens
192 assert token.name == 'String'
193
194 def test_triple_quoted_string():
195 for s in ["""'''abc'''""",
196 """'''a'b'c''d'f'''""",
197 """uR'''a\\''''""",
198 """'''\na\nk\n\"\"\"'''"""]:
199 tokens = pythonlexer.tokenize(s)
200 token, = tokens
201 assert token.name == 'String'
202
203 def test_name():
204 for s in ["abc",
205 "_",
206 "a_0",
207 "_0",
208 ]:
209 tokens = pythonlexer.tokenize(s)
210 token, = tokens
211 assert token.name == 'Name'
212
213 def test_long():
214 for s, numtoken in [
215 ("if x:\n print x", 8),
216 ("if x:#foo\n x *= 17", 11),
217 ("1 + \\\n 2", 5)]:
218 tokens = pythonlexer.tokenize(s)
219 assert len(tokens) == numtoken
220 print tokens
221
222 def test_complex_quoting():
223 s = '''"""u'abc'""",
224 """ur'ab"c'""",
225 """UR'ab\\'c'""",
226 """'ab\\\nc'"""'''
227 tokens = pythonlexer.tokenize(s)
228 assert len(tokens) == 10
229 for i in range(4):
230 assert tokens[i * 3].name == 'String'
231
232 def test_self():
233 fname = __file__
234 if fname.endswith('.pyc'):
235 fname = fname[:-1]
236 s = py.path.local(fname).read()
237 tokens = pythonlexer.tokenize(s)
238 print tokens
239
240 def test_indentation():
241 s = """a
242 b
243 c
244 d
245 e"""
246 tokens = pythonlex(s)
247 assert [t.name for t in tokens] == ["Name", "Newline", "Name", "Newline",
248 "Indent", "Name", "Newline", "Indent",
249 "Name", "Newline", "Dedent", "Name"]
250
251 def test_linecont():
252 s = "a + \\\n b"
253 tokens = pythonlex(s)
254 assert [t.name for t in tokens] == ["Name", "Operator", "Name"]
255
256 def test_parenthesis():
257 s = "(a + \n b)"
258 tokens = pythonlex(s)
259 assert [t.name for t in tokens] == ["Operator", "Name", "Operator", "Name",
260 "Operator"]
261
262 def dont_test_self_full():
263 equivalents = {
264 "nl": "newline",
265 "comment": "newline",
266 "op": "operator",
267 }
268 import tokenize, token
269 s = py.path.local(__file__).read()
270 tokens = pythonlex(s)
271 print [t.name for t in tokens][:20]
272 tokens2 = list(tokenize.generate_tokens(iter(s.splitlines(True)).next))
273 print [token.tok_name[t[0]] for t in tokens2][:20]
274 for i, (t1, t2) in enumerate(zip(tokens, tokens2)):
275 n1 = t1.name.lower()
276 n2 = token.tok_name[t2[0]].lower()
277 n2 = equivalents.get(n2, n2)
278 assert n1 == n2