Debian Codegraph @

pypy/interpreter/pyparser/test/test_pytokenizer.py

raw symbols SCIP
1 # -*- coding: utf-8 -* -
2 import pytest
3 from pypy.interpreter.astcompiler import consts
4 from pypy.interpreter.pyparser import pytokenizer
5 from pypy.interpreter.pyparser.parser import Token
6 from pypy.interpreter.pyparser.pygram import tokens
7 from pypy.interpreter.pyparser.error import TokenError
8
9 def tokenize(s, flags=0):
10 source_lines = s.splitlines(True)
11 if source_lines and not source_lines[-1].endswith("\n"):
12 source_lines[-1] += '\n'
13 return pytokenizer.generate_tokens(source_lines, flags)
14
15 def check_token_error(s, msg=None, pos=-1, line=-1):
16 error = pytest.raises(TokenError, tokenize, s)
17 if msg is not None:
18 assert error.value.msg == msg
19 if pos != -1:
20 assert error.value.offset == pos
21 if line != -1:
22 assert error.value.lineno == line
23
24
25 class TestTokenizer(object):
26
27 def test_simple(self):
28 line = "a+1\n"
29 tks = tokenize(line)
30 assert tks[:-3] == [
31 Token(tokens.NAME, 'a', 1, 0, line, 1, 1),
32 Token(tokens.PLUS, '+', 1, 1, line, 1, 2),
33 Token(tokens.NUMBER, '1', 1, 2, line, 1, 3),
34 ]
35
36 def test_error_parenthesis(self):
37 for paren in "([{":
38 check_token_error(paren + "1 + 2",
39 "'%s' was never closed" % paren,
40 1)
41
42 for paren in ")]}":
43 check_token_error("1 + 2" + paren,
44 "unmatched '%s'" % (paren, ),
45 6)
46
47 for i, opening in enumerate("([{"):
48 for j, closing in enumerate(")]}"):
49 if i == j:
50 continue
51 check_token_error(opening + "1\n" + closing,
52 "closing parenthesis '%s' does not match opening parenthesis '%s' on line 1" % (closing, opening),
53 pos=1, line=2)
54 check_token_error(opening + "1" + closing,
55 "closing parenthesis '%s' does not match opening parenthesis '%s'" % (closing, opening),
56 pos=3, line=1)
57 check_token_error(opening + closing,
58 "closing parenthesis '%s' does not match opening parenthesis '%s'" % (closing, opening),
59 pos=2, line=1)
60
61
62 def test_unknown_char(self):
63 check_token_error("?", "invalid character '?' (U+003F)", 1)
64 check_token_error("$", "invalid character '$' (U+0024)", 1)
65 check_token_error("⫛", "invalid character '⫛' (U+2ADB)", 1)
66 check_token_error("\x17", "invalid non-printable character U+0017", 1)
67
68 def test_eol_string(self):
69 check_token_error("x = 'a", pos=5, line=1)
70
71 def test_eof_triple_quoted(self):
72 check_token_error("'''", pos=1, line=1)
73
74 def test_type_comments(self):
75 line = "a = 5 # type: int\n"
76 tks = tokenize(line, flags=consts.PyCF_TYPE_COMMENTS)
77 assert tks[:-3] == [
78 Token(tokens.NAME, 'a', 1, 0, line, 1, 1),
79 Token(tokens.EQUAL, '=', 1, 2, line, 1, 3),
80 Token(tokens.NUMBER, '5', 1, 4, line, 1, 5),
81 Token(tokens.TYPE_COMMENT, 'int', 1, 6, line),
82 ]
83
84 def test_type_comment_bug(self):
85 lines = ['# type: int\n', '']
86 pytokenizer.generate_tokens(lines, flags=consts.PyCF_TYPE_COMMENTS)
87
88 def test_type_ignore(self):
89 line = "a = 5 # type: ignore@teyit\n"
90 tks = tokenize(line, flags=consts.PyCF_TYPE_COMMENTS)
91 assert tks[:-3] == [
92 Token(tokens.NAME, 'a', 1, 0, line, 1, 1),
93 Token(tokens.EQUAL, '=', 1, 2, line, 1, 3),
94 Token(tokens.NUMBER, '5', 1, 4, line, 1, 5),
95 Token(tokens.TYPE_IGNORE, '@teyit', 1, 6, line),
96 ]
97
98 def test_walrus(self):
99 line = "a:=1\n"
100 tks = tokenize(line)
101 assert tks[:-3] == [
102 Token(tokens.NAME, 'a', 1, 0, line, 1, 1),
103 Token(tokens.COLONEQUAL, ':=', 1, 1, line, 1, 3),
104 Token(tokens.NUMBER, '1', 1, 3, line, 1, 4),
105 ]
106
107 def test_triple_quoted(self):
108 input = '''x = """
109 hello
110 content
111 whatisthis""" + "a"\n'''
112 s = '''"""
113 hello
114 content
115 whatisthis"""'''
116 tks = tokenize(input)
117 lines = input.splitlines(True)
118 assert tks[:3] == [
119 Token(tokens.NAME, 'x', 1, 0, lines[0], 1, 1),
120 Token(tokens.EQUAL, '=', 1, 2, lines[0], 1, 3),
121 Token(tokens.STRING, s, 1, 4, lines[3], 4, 13),
122 ]
123
124 def test_parenthesis_positions(self):
125 input = '( ( ( a ) ) ) ( )'
126 tks = tokenize(input)[:-3]
127 columns = [t.column for t in tks]
128 assert columns == [0, 2, 4, 6, 8, 10, 12, 14, 16]
129 assert [t.end_column - 1 for t in tks] == columns
130
131 def test_PyCF_DONT_IMPLY_DEDENT(self):
132 input = "if 1:\n 1\n"
133 # regular mode
134 tks = tokenize(input)
135 lines = input.splitlines(True)
136 del tks[-2] # new parser deletes one newline anyway
137 assert tks == [
138 Token(tokens.NAME, 'if', 1, 0, lines[0], 1, 2),
139 Token(tokens.NUMBER, '1', 1, 3, lines[0], 1, 4),
140 Token(tokens.COLON, ':', 1, 4, lines[0], 1, 5),
141 Token(tokens.NEWLINE, '', 1, 5, lines[0], -1, -1),
142 Token(tokens.INDENT, ' ', 2, 0, lines[1], 2, 2),
143 Token(tokens.NUMBER, '1', 2, 2, lines[1], 2, 3),
144 Token(tokens.NEWLINE, '', 2, 3, lines[1], -1, -1),
145 Token(tokens.DEDENT, '', 2, 0, '', -1, -1),
146 Token(tokens.ENDMARKER, '', 2, 0, '', -1, -1),
147 ]
148 # single mode
149 tks = tokenize(input, flags=consts.PyCF_DONT_IMPLY_DEDENT)
150 lines = input.splitlines(True)
151 del tks[-2] # new parser deletes one newline anyway
152 assert tks == [
153 Token(tokens.NAME, 'if', 1, 0, lines[0], 1, 2),
154 Token(tokens.NUMBER, '1', 1, 3, lines[0], 1, 4),
155 Token(tokens.COLON, ':', 1, 4, lines[0], 1, 5),
156 Token(tokens.NEWLINE, '', 1, 5, lines[0], -1, -1),
157 Token(tokens.INDENT, ' ', 2, 0, lines[1], 2, 2),
158 Token(tokens.NUMBER, '1', 2, 2, lines[1], 2, 3),
159 Token(tokens.NEWLINE, '', 2, 3, lines[1], -1, -1),
160 Token(tokens.ENDMARKER, '', 2, 0, '', -1, -1),
161 ]
162
163 def test_ignore_just_linecont(self):
164 input = "pass\n \\\n\npass"
165 tks = tokenize(input)
166 tps = [tk.token_type for tk in tks]
167 assert tps == [tokens.NAME, tokens.NEWLINE, tokens.NAME,
168 tokens.NEWLINE, tokens.NEWLINE, tokens.ENDMARKER]
169
170 def test_error_linecont(self):
171 check_token_error("a \\ b",
172 "unexpected character after line continuation character",
173 4)
174
175 def test_continuation_and_indentation_levels(self):
176 # Make sure the '\` generates indent/dedent tokens
177 input1 = r"""\
178 def fib(n):
179 \
180 '''Print a Fibonacci series up to n.'''
181 \
182 a, b = 0, 1
183 """
184 input2 = r"""\
185 def fib(n):
186 '''Print a Fibonacci series up to n.'''
187 a, b = 0, 1
188 """
189 def base_eq(tok1, tok2):
190 # Line numbers differ because of `\`, so only compare type and value
191 return all([(t1.token_type == t2.token_type and t1.value == t2.value) for t1, t2 in zip(tok1, tok2)])
192 tks1 = tokenize(input1)
193 tks2 = tokenize(input2)
194 if not base_eq(tks1, tks2):
195 # get better error message
196 assert tks1 == tks2
197
198 def test_formfeed1(self):
199 # issue gh-5221
200 input = " \\\n \ndef(a=1,b:bool=False): pass"
201 tks = tokenize(input)
202 assert tks[0].token_type != tokens.INDENT
203
204 def test_formfeed2(self):
205 # issue gh-5221
206 input = " \\\n#\n"
207 tks = tokenize(input)
208 assert tks[0].token_type != tokens.INDENT
209
210 def test_backslash_before_indent1(self):
211 # issue gh-5221
212 input1 = r"""\
213 class AnotherCase:
214 '''Some Docstring
215 '''"""
216 input2 = r"""\
217 class AnotherCase:
218 \
219 '''Some Docstring
220 '''"""
221 tks1 = tokenize(input1)
222 tps1 = [tk.token_type for tk in tks1]
223 tks2 = tokenize(input2)
224 tps2 = [tk.token_type for tk in tks2]
225 assert tps1 == tps2
226
227 def test_backslash_before_indent2(self):
228 # issue gh-5221
229 input1 = r"""\
230 class Plotter:
231 \
232 pass
233 """
234 input2 = r"""\
235 class Plotter:
236 pass
237 """
238 tks1 = tokenize(input1)
239 tps1 = [tk.token_type for tk in tks1]
240 tks2 = tokenize(input2)
241 tps2 = [tk.token_type for tk in tks2]
242 assert tps1 == tps2
243
244 def test_error_integers(self):
245 check_token_error("0b106",
246 "invalid digit '6' in binary literal",
247 5)
248 check_token_error("0b10_6",
249 "invalid digit '6' in binary literal",
250 5)
251 check_token_error("0b6",
252 "invalid digit '6' in binary literal",
253 3)
254 check_token_error("0b \n",
255 "invalid binary literal",
256 2)
257 check_token_error("0o129",
258 "invalid digit '9' in octal literal",
259 5)
260 check_token_error("0o12_9",
261 "invalid digit '9' in octal literal",
262 5)
263 check_token_error("0o9",
264 "invalid digit '9' in octal literal",
265 3)
266 check_token_error("0o \n",
267 "invalid octal literal",
268 2)
269 check_token_error("0x1__ \n",
270 "invalid hexadecimal literal",
271 4)
272 check_token_error("0x\n",
273 "invalid hexadecimal literal",
274 2)
275 check_token_error("1_ \n",
276 "invalid decimal literal",
277 2)
278 check_token_error("0b1_ \n",
279 "invalid binary literal",
280 3)
281 check_token_error("01212 \n",
282 "leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers",
283 1)
284 tokenize("1 2 \n") # does not raise
285 tokenize("1 _ \n") # does not raise
286
287
288 def test_invalid_identifier(self):
289 check_token_error("aänc€",
290 "invalid character '€' (U+20AC)",
291 6)
292 check_token_error("a\xc2\xa0b",
293 "invalid non-printable character U+00A0",
294 2)
295
296
297 class TestTokenizer310Changes(object):
298 def test_single_quoted(self):
299 check_token_error('s = "abc\n', "unterminated string literal (detected at line 1)", pos=5)
300
301 def test_triple_quoted(self):
302 check_token_error('"""abc\n', "unterminated triple-quoted string literal (detected at line 1)")
303
304 def test_single_quoted_detected(self):
305 check_token_error('s = "abc\n', "unterminated string literal (detected at line 1)")
306 check_token_error('s = "abc\\\na\\\nb\n', "unterminated string literal (detected at line 3)", pos=5)
307
308 def test_triple_quoted_detected(self):
309 check_token_error('s = """', "unterminated triple-quoted string literal (detected at line 1)")
310 check_token_error('s = """abc\\\na\\\nb\n\n\n\n\n', "unterminated triple-quoted string literal (detected at line 7)")
311
312 def test_warn_number_followed_by_keyword(self):
313 line = "0x1for\n"
314 tks = tokenize(line)
315 assert tks[:-3] == [
316 Token(tokens.NUMBER, '0x1f', 1, 0, line, 1, 4),
317 Token(tokens.WARNING, 'invalid hexadecimal literal', 1, 0, line),
318 Token(tokens.NAME, 'or', 1, 4, line, 1, 6),
319 ]
320
321 for line in ("1in 3", "0b01010111and 4", "1 if 0o21231else 2"):
322 tks = tokenize(line)
323 assert any(tokens.WARNING == tok.token_type for tok in tks)
324
325
326 def test_error_number_by_non_keyword_name(self):
327 check_token_error("1a 2", "invalid decimal literal")
328
329 def test_levels(self):
330 line = 'a b (c + d) [[e, f]]'
331 tks = tokenize(line)
332 levels = [token.level for token in tks]
333 assert levels == [0, 0, 1, 1, 1, 1, 0, 1, 2, 2, 2, 2, 1, 0, 0, 0, 0]
334
335 def test_non_utf8_error_message(self):
336 # Error message should match CPython: "Non-UTF-8 code starting with '\xNN' in file"
337 error = pytest.raises(TokenError, tokenize, "\x89")
338 assert error.value.msg.startswith("Non-UTF-8 code starting with '\\x89' in file")
339
340 def test_invalid_float_exponent(self):
341 # 32e-+4 has an invalid exponent; should match CPython: "invalid decimal literal" at offset=8
342 check_token_error("x = 32e-+4", "invalid decimal literal", pos=8)
343