Debian Codegraph @

pypy/interpreter/test/test_compiler.py

raw symbols SCIP
1 # encoding: utf-8
2 import pytest
3 import py, sys
4 from pypy.interpreter.pycompiler import PythonAstCompiler
5 from pypy.interpreter.pycode import PyCode
6 from pypy.interpreter.error import OperationError
7 from pypy.interpreter.argument import Arguments
8 from pypy.tool import stdlib___future__ as __future__
9
10 class TestPythonAstCompiler:
11 def setup_method(self, method):
12 self.compiler = self.space.createcompiler()
13
14 def eval_string(self, string, kind='eval'):
15 space = self.space
16 code = self.compiler.compile(string, '<>', kind, 0)
17 return code.exec_code(space, space.newdict(), space.newdict())
18
19 def test_compile(self):
20 code = self.compiler.compile('6*7', '<hello>', 'eval', 0)
21 assert isinstance(code, PyCode)
22 assert code.co_filename == '<hello>'
23 space = self.space
24 w_res = code.exec_code(space, space.newdict(), space.newdict())
25 assert space.int_w(w_res) == 42
26
27 def test_eval_unicode(self):
28 assert (eval(unicode('u"\xc3\xa5"', 'utf8')) ==
29 unicode('\xc3\xa5', 'utf8'))
30
31 def test_compile_command(self):
32 for mode in ('single', 'exec'):
33 c0 = self.compiler.compile_command('\t # hello\n ', '?', mode, 0)
34 c1 = self.compiler.compile_command('print(6*7)', '?', mode, 0)
35 c2 = self.compiler.compile_command('if 1:\n x\n', '?', mode, 0)
36 c8 = self.compiler.compile_command('x = 5', '?', mode, 0)
37 c9 = self.compiler.compile_command('x = 5 ', '?', mode, 0)
38 assert c0 is not None
39 assert c1 is not None
40 assert c2 is not None
41 assert c8 is not None
42 assert c9 is not None
43 c4 = self.compiler.compile_command('x = (', '?', mode, 0)
44 c5 = self.compiler.compile_command('x = (\n', '?', mode, 0)
45 c6 = self.compiler.compile_command('x = (\n\n', '?', mode, 0)
46 c7 = self.compiler.compile_command('x = """a\n', '?', mode, 0)
47 assert c4 is None
48 assert c5 is None
49 assert c6 is None
50 assert c7 is None
51 space = self.space
52 space.raises_w(space.w_SyntaxError, self.compiler.compile_command,
53 'if 1:\n x x', '?', mode, 0)
54 space.raises_w(space.w_SyntaxError, self.compiler.compile_command,
55 ')', '?', mode, 0)
56 c3 = self.compiler.compile_command('if 1:\n x', '?', 'single', 0)
57 assert c3 is None
58
59 def test_compile_bug(self):
60 self.compiler.compile_command("if 1: pass", "", "single", 0)
61
62 def test_hidden_applevel(self):
63 code = self.compiler.compile("def f(x): pass", "<test>", "exec", 0,
64 True)
65 assert code.hidden_applevel
66 for w_const in code.co_consts_w:
67 if isinstance(w_const, PyCode):
68 assert code.hidden_applevel
69
70 def test_indentation_error(self):
71 space = self.space
72 space.raises_w(space.w_SyntaxError, self.compiler.compile_command,
73 'if 1:\n x\n y\n', '?', 'exec', 0)
74
75 def test_getcodeflags(self):
76 code = self.compiler.compile('from __future__ import division, annotations\n',
77 '<hello>', 'exec', 0)
78 flags = self.compiler.getcodeflags(code)
79 assert flags & __future__.division.compiler_flag == 0
80 assert flags & __future__.annotations.compiler_flag
81 # check that we don't get more flags than the compiler can accept back
82 code2 = self.compiler.compile('print(6*7)', '<hello>', 'exec', flags)
83 # check that the flag remains in force
84 flags2 = self.compiler.getcodeflags(code2)
85 assert flags == flags2
86
87 def test_interactivemode(self):
88 code = self.compiler.compile('a = 1', '<hello>', 'single', 0)
89 assert isinstance(code, PyCode)
90 assert code.co_filename == '<hello>'
91 space = self.space
92 w_globals = space.newdict()
93 code.exec_code(space, w_globals, w_globals)
94 w_a = space.getitem(w_globals, space.wrap('a'))
95 assert space.int_w(w_a) == 1
96
97 def test_scope_unoptimized_clash1(self):
98 # mostly taken from test_scope.py
99 e = py.test.raises(OperationError, self.compiler.compile, """if 1:
100 def unoptimized_clash1(strip):
101 def f(s):
102 from string import *
103 return strip(s) # ambiguity: free or local
104 return f""", '', 'exec', 0)
105 ex = e.value
106 assert ex.match(self.space, self.space.w_SyntaxError)
107
108 def test_scope_unoptimized_clash1_b(self):
109 # as far as I can tell, this case can be handled correctly
110 # by the interpreter so a SyntaxError is not required, but
111 # let's give one anyway for "compatibility"...
112
113 # mostly taken from test_scope.py
114 e = py.test.raises(OperationError, self.compiler.compile, """if 1:
115 def unoptimized_clash1(strip):
116 def f():
117 from string import *
118 return s # ambiguity: free or local (? no, global or local)
119 return f""", '', 'exec', 0)
120 ex = e.value
121 assert ex.match(self.space, self.space.w_SyntaxError)
122
123 def test_scope_exec_in_nested(self):
124 e = py.test.raises(OperationError, self.compiler.compile, """if 1:
125 def unoptimized_clash1(x):
126 def f():
127 exec "z=3"
128 return x
129 return f""", '', 'exec', 0)
130 ex = e.value
131 assert ex.match(self.space, self.space.w_SyntaxError)
132
133 def test_scope_exec_with_nested_free(self):
134 e = py.test.raises(OperationError, self.compiler.compile, """if 1:
135 def unoptimized_clash1(x):
136 exec "z=3"
137 def f():
138 return x
139 return f""", '', 'exec', 0)
140 ex = e.value
141 assert ex.match(self.space, self.space.w_SyntaxError)
142
143 def test_scope_importstar_in_nested(self):
144 e = py.test.raises(OperationError, self.compiler.compile, """if 1:
145 def unoptimized_clash1(x):
146 def f():
147 from string import *
148 return x
149 return f""", '', 'exec', 0)
150 ex = e.value
151 assert ex.match(self.space, self.space.w_SyntaxError)
152
153 def test_scope_importstar_with_nested_free(self):
154 e = py.test.raises(OperationError, self.compiler.compile, """if 1:
155 def clash(x):
156 from string import *
157 def f(s):
158 return strip(s)
159 return f""", '', 'exec', 0)
160 ex = e.value
161 assert ex.match(self.space, self.space.w_SyntaxError)
162
163 def test_try_except_finally(self):
164 s = py.code.Source("""
165 def f():
166 try:
167 1/0
168 except ZeroDivisionError:
169 pass
170 finally:
171 return 3
172 """)
173 self.compiler.compile(str(s), '', 'exec', 0)
174 s = py.code.Source("""
175 def f():
176 try:
177 1/0
178 except:
179 pass
180 else:
181 pass
182 finally:
183 return 2
184 """)
185 self.compiler.compile(str(s), '', 'exec', 0)
186
187 def test_toplevel_docstring(self):
188 space = self.space
189 code = self.compiler.compile('"spam"; "bar"; x=5', '<hello>', 'exec', 0)
190 w_locals = space.newdict()
191 code.exec_code(space, space.newdict(), w_locals)
192 w_x = space.getitem(w_locals, space.wrap('x'))
193 assert space.eq_w(w_x, space.wrap(5))
194 w_doc = space.getitem(w_locals, space.wrap('__doc__'))
195 assert space.eq_w(w_doc, space.wrap("spam"))
196 #
197 code = self.compiler.compile('"spam"; "bar"; x=5',
198 '<hello>', 'single', 0)
199 w_locals = space.newdict()
200 code.exec_code(space, space.newdict(), w_locals)
201 w_x = space.getitem(w_locals, space.wrap('x'))
202 assert space.eq_w(w_x, space.wrap(5))
203 w_doc = space.call_method(w_locals, 'get', space.wrap('__doc__'))
204 assert space.is_w(w_doc, space.w_None) # "spam" is not a docstring
205
206 def test_barestringstmts_disappear(self):
207 space = self.space
208 code = self.compiler.compile('"a"\n"b"\n"c"\n', '<hello>', 'exec', 0)
209 for w_const in code.co_consts_w:
210 # "a" should show up as a docstring, but "b" and "c" should not
211 assert not space.eq_w(w_const, space.wrap("b"))
212 assert not space.eq_w(w_const, space.wrap("c"))
213
214 def test_unicodeliterals(self):
215 e = py.test.raises(OperationError, self.eval_string, "u'\\Ufffffffe'")
216 ex = e.value
217 ex.normalize_exception(self.space)
218 assert ex.match(self.space, self.space.w_SyntaxError)
219
220 e = py.test.raises(OperationError, self.eval_string, "u'\\Uffffffff'")
221 ex = e.value
222 ex.normalize_exception(self.space)
223 assert ex.match(self.space, self.space.w_SyntaxError)
224
225 e = py.test.raises(OperationError, self.eval_string, "u'\\U%08x'" % 0x110000)
226 ex = e.value
227 ex.normalize_exception(self.space)
228 assert ex.match(self.space, self.space.w_SyntaxError)
229
230 def test_unicode_docstring(self):
231 space = self.space
232 code = self.compiler.compile('"hello"\n', '<hello>', 'exec', 0)
233 assert space.eq_w(code.co_consts_w[0], space.wrap("hello"))
234 assert space.is_w(space.type(code.co_consts_w[0]), space.w_unicode)
235
236 def test_argument_handling(self):
237 for expr in 'lambda a,a:0', 'lambda a,a=1:0', 'lambda a=1,a=1:0':
238 e = py.test.raises(OperationError, self.eval_string, expr)
239 ex = e.value
240 ex.normalize_exception(self.space)
241 assert ex.match(self.space, self.space.w_SyntaxError)
242
243 for code in 'def f(a, a): pass', 'def f(a = 0, a = 1): pass', 'def f(a): global a; a = 1':
244 e = py.test.raises(OperationError, self.eval_string, code, 'exec')
245 ex = e.value
246 ex.normalize_exception(self.space)
247 assert ex.match(self.space, self.space.w_SyntaxError)
248
249 def test_argument_order(self):
250 code = 'def f(a=1, (b, c)): pass'
251 e = py.test.raises(OperationError, self.eval_string, code, 'exec')
252 ex = e.value
253 ex.normalize_exception(self.space)
254 assert ex.match(self.space, self.space.w_SyntaxError)
255
256 def test_debug_assignment(self):
257 code = '__debug__ = 1'
258 e = py.test.raises(OperationError, self.compiler.compile, code, '', 'single', 0)
259 ex = e.value
260 ex.normalize_exception(self.space)
261 assert ex.match(self.space, self.space.w_SyntaxError)
262
263 def test_return_in_generator(self):
264 code = 'def f():\n return None\n yield 19\n'
265 self.compiler.compile(code, '', 'single', 0)
266
267 def test_yield_in_finally(self):
268 code ='def f():\n try:\n yield 19\n finally:\n pass\n'
269 self.compiler.compile(code, '', 'single', 0)
270
271 def test_none_assignment(self):
272 stmts = [
273 'None = 0',
274 'None += 0',
275 '__builtins__.None = 0',
276 'def None(): pass',
277 'class None: pass',
278 '(a, None) = 0, 0',
279 'for None in range(10): pass',
280 'def f(None): pass',
281 ]
282 for stmt in stmts:
283 stmt += '\n'
284 for kind in 'single', 'exec':
285 e = py.test.raises(OperationError, self.compiler.compile, stmt,
286 '', kind, 0)
287 ex = e.value
288 ex.normalize_exception(self.space)
289 assert ex.match(self.space, self.space.w_SyntaxError)
290
291 def test_import(self):
292 succeed = [
293 'import sys',
294 'import os, sys',
295 'from __future__ import nested_scopes, generators',
296 'from __future__ import (nested_scopes,\ngenerators)',
297 'from __future__ import (nested_scopes,\ngenerators,)',
298 'from __future__ import (\nnested_scopes,\ngenerators)',
299 'from __future__ import(\n\tnested_scopes,\n\tgenerators)',
300 'from __future__ import(\n\t\nnested_scopes)',
301 'from sys import stdin, stderr, stdout',
302 'from sys import (stdin, stderr,\nstdout)',
303 'from sys import (stdin, stderr,\nstdout,)',
304 'from sys import (stdin\n, stderr, stdout)',
305 'from sys import (stdin\n, stderr, stdout,)',
306 'from sys import stdin as si, stdout as so, stderr as se',
307 'from sys import (stdin as si, stdout as so, stderr as se)',
308 'from sys import (stdin as si, stdout as so, stderr as se,)',
309 ]
310 fail = [
311 'import (os, sys)',
312 'import (os), (sys)',
313 'import ((os), (sys))',
314 'import (sys',
315 'import sys)',
316 'import (os,)',
317 'from (sys) import stdin',
318 'from __future__ import (nested_scopes',
319 'from __future__ import nested_scopes)',
320 'from __future__ import nested_scopes,\ngenerators',
321 'from sys import (stdin',
322 'from sys import stdin)',
323 'from sys import stdin, stdout,\nstderr',
324 'from sys import stdin si',
325 'from sys import stdin,'
326 'from sys import (*)',
327 'from sys import (stdin,, stdout, stderr)',
328 'from sys import (stdin, stdout),',
329 ]
330 for stmt in succeed:
331 self.compiler.compile(stmt, 'tmp', 'exec', 0)
332 for stmt in fail:
333 e = py.test.raises(OperationError, self.compiler.compile,
334 stmt, 'tmp', 'exec', 0)
335 ex = e.value
336 ex.normalize_exception(self.space)
337 assert ex.match(self.space, self.space.w_SyntaxError)
338
339 def test_future_error_offset(self):
340 space = self.space
341 with pytest.raises(OperationError) as excinfo:
342 self.compiler.compile("from __future__ import bogus", "tmp", "exec", 0)
343 ex = excinfo.value
344 assert ex.match(space, space.w_SyntaxError)
345 ex.normalize_exception(space)
346 w_exc = ex.get_w_value(space)
347 assert space.int_w(w_exc.w_offset) == 1
348
349 def test_globals_warnings(self):
350 space = self.space
351 w_mod = space.appexec((), '():\n import warnings\n return warnings\n') #sys.getmodule('warnings')
352 w_filterwarnings = space.getattr(w_mod, space.wrap('filterwarnings'))
353 filter_arg = Arguments(space, [ space.wrap('error') ], [space.newtext("module")],
354 [space.wrap("<tmp>")])
355
356 for code in ('''
357 def wrong1():
358 a = 1
359 b = 2
360 global a
361 global b
362 ''', '''
363 def wrong2():
364 print x
365 global x
366 ''', '''
367 def wrong3():
368 print x
369 x = 2
370 global x
371 '''):
372
373 space.call_args(w_filterwarnings, filter_arg)
374 e = py.test.raises(OperationError, self.compiler.compile,
375 code, '<tmp>', 'exec', 0)
376 space.call_method(w_mod, 'resetwarnings')
377 ex = e.value
378 ex.normalize_exception(space)
379 assert ex.match(space, space.w_SyntaxError)
380
381 def test_no_warning_run(self):
382 space = self.space
383 w_mod = space.appexec((), '():\n import warnings\n return warnings\n') #sys.getmodule('warnings')
384 w_filterwarnings = space.getattr(w_mod, space.wrap('filterwarnings'))
385 filter_arg = Arguments(space, [ space.wrap('error') ], [space.newtext("module")],
386 [space.wrap("<tmp>")])
387 for code in ['''
388 def testing():
389 __class__ = 0
390 def f():
391 nonlocal __class__
392 __class__ = 42
393 f()
394 return __class__
395 ''', '''
396 class Y:
397 class X:
398 nonlocal __class__
399 __class__ = 42
400 assert locals()['__class__'] == 42
401 # ^^^ but at the same place, reading '__class__' gives a NameError
402 # in CPython 3.5.2. Looks like a bug to me
403 def testing():
404 return 42
405 ''', '''
406 class Y:
407 def f():
408 __class__
409 __class__ = 42
410 def testing():
411 return Y.__dict__['__class__']
412 ''', '''
413 class X:
414 foobar = 42
415 def f(self):
416 return __class__.__dict__['foobar']
417 def testing():
418 return X().f()
419 ''',
420 #--------XXX the following case is not implemented for now
421 #'''
422 #class X:
423 # foobar = 42
424 # def f(self):
425 # class Y:
426 # Xcls = __class__
427 # return Y.Xcls.__dict__['foobar']
428 #def testing():
429 # return X().f()
430 #'''
431 ]:
432 space.call_args(w_filterwarnings, filter_arg)
433 pycode = self.compiler.compile(code, '<tmp>', 'exec', 0)
434 space.call_method(w_mod, 'resetwarnings')
435 w_d = space.newdict()
436 pycode.exec_code(space, w_d, w_d)
437 w_res = space.call_function(
438 space.getitem(w_d, space.wrap('testing')))
439 assert space.unwrap(w_res) == 42
440
441 def test_firstlineno(self):
442 snippet = str(py.code.Source(r'''
443 def f(): "line 2"
444 if 3 and \
445 (4 and
446 5):
447 def g(): "line 6"
448 fline = f.__code__.co_firstlineno
449 gline = g.__code__.co_firstlineno
450 '''))
451 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
452 space = self.space
453 w_d = space.newdict()
454 code.exec_code(space, w_d, w_d)
455 w_fline = space.getitem(w_d, space.wrap('fline'))
456 w_gline = space.getitem(w_d, space.wrap('gline'))
457 assert space.int_w(w_fline) == 2
458 assert space.int_w(w_gline) == 6
459
460 def test_firstlineno_decorators(self):
461 snippet = str(py.code.Source(r'''
462 def foo(x): return x
463 @foo # line 3
464 @foo # line 4
465 def f(): # line 5
466 pass # line 6
467 fline = f.__code__.co_firstlineno
468 '''))
469 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
470 space = self.space
471 w_d = space.newdict()
472 code.exec_code(space, w_d, w_d)
473 w_fline = space.getitem(w_d, space.wrap('fline'))
474 assert space.int_w(w_fline) == 3
475
476 def test_firstlineno_decorators_class(self):
477 snippet = str(py.code.Source(r'''
478 def foo(x): return x
479 def f():
480 @foo # line 4
481 @foo # line 5
482 class AWrong:
483 pass # line 7
484 Aline = f.__code__.co_consts[1].co_firstlineno
485 '''))
486 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
487 space = self.space
488 w_d = space.newdict()
489 code.exec_code(space, w_d, w_d)
490 w_fline = space.getitem(w_d, space.wrap('Aline'))
491 assert space.int_w(w_fline) == 4
492
493 def test_mangling(self):
494 snippet = str(py.code.Source(r'''
495 __g = "42"
496 class X(object):
497 def __init__(self, u):
498 self.__u = u
499 def __f(__self, __n):
500 global __g
501 __NameError = NameError
502 try:
503 yield "found: " + __g
504 except __NameError as __e:
505 yield "not found: " + str(__e)
506 del __NameError
507 for __i in range(__self.__u * __n):
508 yield locals()
509 result = X(2)
510 assert not hasattr(result, "__f")
511 result = list(result._X__f(3))
512 assert len(result) == 7
513 assert result[0].startswith("not found: ")
514 for d in result[1:]:
515 for key, value in d.items():
516 assert not key.startswith('__')
517 '''))
518 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
519 space = self.space
520 w_d = space.newdict()
521 space.exec_(code, w_d, w_d)
522
523 def test_ellipsis(self):
524 snippet = str(py.code.Source(r'''
525 d = {}
526 d[...] = 12
527 assert next(iter(d)) is Ellipsis
528 '''))
529 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
530 space = self.space
531 w_d = space.newdict()
532 space.exec_(code, w_d, w_d)
533 snip = "d[. . .]"
534 space.raises_w(space.w_SyntaxError, self.compiler.compile,
535 snip, '<test>', 'exec', 0)
536
537 def test_chained_access_augassign(self):
538 snippet = str(py.code.Source(r'''
539 class R(object):
540 count = 0
541 c = 0
542 for i in [0,1,2]:
543 c += 1
544 r = R()
545 for i in [0,1,2]:
546 r.count += 1
547 c += r.count
548 l = [0]
549 for i in [0,1,2]:
550 l[0] += 1
551 c += l[0]
552 l = [R()]
553 for i in [0]:
554 l[0].count += 1
555 c += l[0].count
556 r.counters = [0]
557 for i in [0,1,2]:
558 r.counters[0] += 1
559 c += r.counters[0]
560 r = R()
561 f = lambda : r
562 for i in [0,1,2]:
563 f().count += 1
564 c += f().count
565 '''))
566 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
567 space = self.space
568 w_d = space.newdict()
569 space.exec_(code, w_d, w_d)
570 assert space.int_w(space.getitem(w_d, space.wrap('c'))) == 16
571
572 def test_augassign_with_tuple_subscript(self):
573 snippet = str(py.code.Source(r'''
574 class D(object):
575 def __getitem__(self, key):
576 assert key == self.lastkey
577 return self.lastvalue
578 def __setitem__(self, key, value):
579 self.lastkey = key
580 self.lastvalue = value
581 def one(return_me=[1]):
582 return return_me.pop()
583 d = D()
584 a = 15
585 d[1,2+a,3:7,...,1,] = 6
586 d[one(),17,slice(3,7),...,1] *= 7
587 result = d[1,17,3:7,Ellipsis,1]
588 '''))
589 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
590 space = self.space
591 w_d = space.newdict()
592 space.exec_(code, w_d, w_d)
593 assert space.int_w(space.getitem(w_d, space.wrap('result'))) == 42
594
595 def test_continue_in_finally(self):
596 space = self.space
597 snippet = str(py.code.Source(r'''
598 def test():
599 for abc in range(10):
600 try: pass
601 finally:
602 continue # 'continue' inside 'finally'
603
604 test()
605 '''))
606 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
607 space = self.space
608 w_d = space.newdict()
609 space.exec_(code, w_d, w_d)
610
611 def test_continue_in_nested_finally(self):
612 space = self.space
613 snippet = str(py.code.Source(r'''
614 def test():
615 for abc in range(10):
616 try: pass
617 finally:
618 try:
619 continue # 'continue' inside 'finally'
620 except:
621 pass
622 test()
623 '''))
624 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
625 space = self.space
626 w_d = space.newdict()
627 space.exec_(code, w_d, w_d)
628
629 def test_really_nested_stuff(self):
630 space = self.space
631 snippet = str(py.code.Source(r'''
632 def f(self):
633 def get_nested_class():
634 self
635 class Test(object):
636 def _STOP_HERE_(self):
637 return _STOP_HERE_(self)
638 get_nested_class()
639 f(42)
640 '''))
641 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
642 space = self.space
643 w_d = space.newdict()
644 space.exec_(code, w_d, w_d)
645 # assert did not crash
646
647 def test_free_vars_across_class(self):
648 space = self.space
649 snippet = str(py.code.Source(r'''
650 def f(x):
651 class Test(object):
652 def meth(self):
653 return x + 1
654 return Test()
655 res = f(42).meth()
656 '''))
657 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
658 space = self.space
659 w_d = space.newdict()
660 space.exec_(code, w_d, w_d)
661 assert space.int_w(space.getitem(w_d, space.wrap('res'))) == 43
662
663 def test_pick_global_names(self):
664 space = self.space
665 snippet = str(py.code.Source(r'''
666 def f(x):
667 def g():
668 global x
669 def h():
670 return x
671 return h()
672 return g()
673 x = "global value"
674 res = f("local value")
675 '''))
676 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
677 space = self.space
678 w_d = space.newdict()
679 space.exec_(code, w_d, w_d)
680 w_res = space.getitem(w_d, space.wrap('res'))
681 assert space.text_w(w_res) == "global value"
682
683 def test_method_and_var(self):
684 space = self.space
685 snippet = str(py.code.Source(r'''
686 def f():
687 method_and_var = "var"
688 class Test(object):
689 def method_and_var(self):
690 return "method"
691 def test(self):
692 return method_and_var
693 return Test().test()
694 res = f()
695 '''))
696 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
697 space = self.space
698 w_d = space.newdict()
699 space.exec_(code, w_d, w_d)
700 w_res = space.getitem(w_d, space.wrap('res'))
701 assert space.eq_w(w_res, space.wrap("var"))
702
703 def test_yield_from(self):
704 space = self.space
705 snippet = str(py.code.Source(r'''
706 def f():
707 def generator2():
708 yield 8
709 def generator():
710 yield from generator2()
711 return next(generator())
712 res = f()
713 '''))
714 code = self.compiler.compile(snippet, '<tmp>', 'exec', 0)
715 space = self.space
716 w_d = space.newdict()
717 space.exec_(code, w_d, w_d)
718 w_res = space.getitem(w_d, space.wrap('res'))
719 assert space.eq_w(w_res, space.wrap(8))
720
721 def test_dont_inherit_flag(self):
722 # this test checks that compile() don't inherit the __future__ flags
723 # of the hosting code.
724 space = self.space
725 s1 = str(py.code.Source("""
726 from __future__ import barry_as_FLUFL
727 # not a syntax error inside the exec!
728 exec(compile('x = 1 != 2', '?', 'exec', 0, 1))
729 """))
730 w_result = space.appexec([space.wrap(s1)], """(s1):
731 ns = {}
732 exec(s1, ns)
733 return ns['x']
734 """)
735 assert space.is_true(w_result)
736
737 def test_dont_inherit_across_import(self):
738 from rpython.tool.udir import udir
739 udir.join('test_dont_inherit_across_import.py').write('x = 1 != 2\n')
740 space = self.space
741 s1 = str(py.code.Source("""
742 from __future__ import barry_as_FLUFL
743 from test_dont_inherit_across_import import x
744 """))
745 w_result = space.appexec([space.wrap(str(udir)), space.wrap(s1)],
746 """(udir, s1):
747 import sys
748 copy = sys.path[:]
749 sys.path.insert(0, udir)
750 ns = {}
751 try:
752 exec(s1, ns)
753 finally:
754 sys.path[:] = copy
755 return ns['x']
756 """)
757 assert space.is_true(w_result)
758
759 def test_filename_in_syntaxerror(self):
760 e = py.test.raises(OperationError, self.compiler.compile, """if 1:
761 'unmatched_quote
762 """, 'hello_world', 'exec', 0)
763 ex = e.value
764 space = self.space
765 assert ex.match(space, space.w_SyntaxError)
766 assert 'hello_world' in space.text_w(space.str(ex.get_w_value(space)))
767
768 def test_del_None(self):
769 snippet = '''if 1:
770 try:
771 del None
772 except NameError:
773 pass
774 '''
775 e = py.test.raises(OperationError, self.compiler.compile,
776 snippet, '<tmp>', 'exec', 0)
777 ex = e.value
778 space = self.space
779 assert ex.match(space, space.w_SyntaxError)
780
781 def test_from_future_import(self):
782 source = """from __future__ import with_statement
783 with somtehing as stuff:
784 pass
785 """
786 code = self.compiler.compile(source, '<filename>', 'exec', 0)
787 assert isinstance(code, PyCode)
788 assert code.co_filename == '<filename>'
789
790 source2 = "with = 3"
791
792 code = self.compiler.compile(source, '<filename2>', 'exec', 0)
793 assert isinstance(code, PyCode)
794 assert code.co_filename == '<filename2>'
795
796 def test_assign_to_yield(self):
797 code = 'def f(): (yield bar) += y'
798 try:
799 self.compiler.compile(code, '', 'single', 0)
800 except OperationError as e:
801 if not e.match(self.space, self.space.w_SyntaxError):
802 raise
803 else:
804 py.test.fail("Did not raise")
805
806 def test_invalid_genexp(self):
807 code = 'dict(a = i for i in xrange(10))'
808 try:
809 self.compiler.compile(code, '', 'single', 0)
810 except OperationError as e:
811 if not e.match(self.space, self.space.w_SyntaxError):
812 raise
813 else:
814 py.test.fail("Did not raise")
815
816 def test_signature_kwargname(self):
817 from pypy.interpreter.pycode import make_signature
818 from pypy.interpreter.signature import Signature
819
820 def find_func(code):
821 for w_const in code.co_consts_w:
822 if isinstance(w_const, PyCode):
823 return w_const
824
825 snippet = 'def f(a, b, m=1, n=2, **kwargs):\n pass\n'
826 containing_co = self.compiler.compile(snippet, '<string>', 'single', 0)
827 co = find_func(containing_co)
828 sig = make_signature(co)
829 assert sig == Signature(['a', 'b', 'm', 'n'], None, 'kwargs')
830
831 snippet = 'def f(a, b, *, m=1, n=2, **kwargs):\n pass\n'
832 containing_co = self.compiler.compile(snippet, '<string>', 'single', 0)
833 co = find_func(containing_co)
834 sig = make_signature(co)
835 assert sig == Signature(['a', 'b', 'm', 'n'], None, 'kwargs', 2)
836
837 # a variant with varargname, which was buggy before issue2996
838 snippet = 'def f(*args, offset=42):\n pass\n'
839 containing_co = self.compiler.compile(snippet, '<string>', 'single', 0)
840 co = find_func(containing_co)
841 sig = make_signature(co)
842 assert sig == Signature(['offset'], 'args', None, 1)
843
844
845 class AppTestCompiler(object):
846
847 def setup_class(cls):
848 cls.w_runappdirect = cls.space.wrap(cls.runappdirect)
849 cls.w_host_is_pypy = cls.space.wrap(
850 '__pypy__' in sys.builtin_module_names)
851
852 def w_is_pypy(self):
853 import sys
854 return (not self.runappdirect) or '__pypy__' in sys.modules
855
856 def test_bom_with_future(self):
857 s = b'\xef\xbb\xbffrom __future__ import division\nx = 1/2'
858 ns = {}
859 exec(s, ns)
860 assert ns["x"] == .5
861
862 def test_noop_future_import(self):
863 code1 = compile("from __future__ import division", "<test>", "exec")
864 code2 = compile("", "<test>", "exec")
865 assert code1.co_flags == code2.co_flags
866
867 def test_values_of_different_types(self):
868 ns = {}
869 exec("a = 0; c = 0.0; d = 0j", ns)
870 assert type(ns['a']) is int
871 assert type(ns['c']) is float
872 assert type(ns['d']) is complex
873
874 def test_values_of_different_types_in_tuples(self):
875 ns = {}
876 exec("a = ((0,),); c = ((0.0,),); d = ((0j,),)", ns)
877 assert type(ns['a'][0][0]) is int
878 assert type(ns['c'][0][0]) is float
879 assert type(ns['d'][0][0]) is complex
880
881 def test_zeros_not_mixed(self):
882 import math, sys
883 code = compile("x = -0.0; y = 0.0", "<test>", "exec")
884 consts = code.co_consts
885 if self.is_pypy():
886 # Hard to test on CPython, since co_consts is randomly ordered
887 x, y, z = consts
888 assert isinstance(x, float) and isinstance(y, float)
889 assert math.copysign(1, x) != math.copysign(1, y)
890 ns = {}
891 exec("z1, z2 = 0j, -0j", ns)
892 assert math.atan2(ns["z1"].imag, -1.) == math.atan2(0., -1.)
893 assert math.atan2(ns["z2"].imag, -1.) == math.atan2(-0., -1.)
894
895 def test_zeros_not_mixed_in_tuples(self):
896 import math
897 ns = {}
898 exec("a = (0.0, 0.0); b = (-0.0, 0.0); c = (-0.0, -0.0)", ns)
899 assert math.copysign(1., ns['a'][0]) == 1.0
900 assert math.copysign(1., ns['a'][1]) == 1.0
901 assert math.copysign(1., ns['b'][0]) == -1.0
902 assert math.copysign(1., ns['b'][1]) == 1.0
903 assert math.copysign(1., ns['c'][0]) == -1.0
904 assert math.copysign(1., ns['c'][1]) == -1.0
905
906 def test_ellipsis_anywhere(self):
907 """
908 x = ...
909 assert x is Ellipsis
910 """
911
912 def test_keywordonly_syntax_errors(self):
913 cases = ("def f(p, *):\n pass\n",
914 "def f(p1, *, p1=100):\n pass\n",
915 "def f(p1, *k1, k1=100):\n pass\n",
916 "def f(p1, *, k1, k1=100):\n pass\n",
917 "def f(p1, *, **k1):\n pass\n",
918 "def f(p1, *, k1, **k1):\n pass\n",
919 "def f(p1, *, None, **k1):\n pass\n",
920 "def f(p, *, (k1, k2), **kw):\n pass\n")
921 for case in cases:
922 raises(SyntaxError, compile, case, "<test>", "exec")
923
924 def test_barry_as_bdfl(self):
925 # from test_flufl.py :-)
926 import __future__
927 code = "from __future__ import barry_as_FLUFL; 2 {0} 3"
928 compile(code.format('<>'), '<BDFL test>', 'exec',
929 __future__.CO_FUTURE_BARRY_AS_BDFL)
930 with raises(SyntaxError) as excinfo:
931 compile(code.format('!='),
932 '<FLUFL test>', 'exec',
933 __future__.CO_FUTURE_BARRY_AS_BDFL)
934 assert excinfo.value.msg == "with Barry as BDFL, use '<>' instead of '!='"
935
936 def test_guido_as_bdfl(self):
937 # from test_flufl.py :-)
938 code = '2 {0} 3'
939 compile(code.format('!='), '<BDFL test>', 'exec')
940 raises(SyntaxError, compile, code.format('<>'),
941 '<FLUFL test>', 'exec')
942
943 def test_surrogate(self):
944 s = '\udcff'
945 raises(UnicodeEncodeError, compile, s, 'foo', 'exec')
946
947 def test_pep3131(self):
948 r"""
949 # XXX: the 4th name is currently mishandled by narrow builds
950 class T:
951 ä = 1
952 µ = 2 # this is a compatibility character
953 蟒 = 3
954 #x󠄀 = 4
955 assert getattr(T, '\xe4') == 1
956 assert getattr(T, '\u03bc') == 2
957 assert getattr(T, '\u87d2') == 3
958 #assert getattr(T, 'x\U000E0100') == 4
959 expected = ("['__dict__', '__doc__', '__module__', '__weakref__', "
960 # "x󠄀", "'ä', 'μ', '蟒']")
961 "'ä', 'μ', '蟒']")
962 assert expected in str(sorted(T.__dict__.keys()))
963 """
964
965 def test_unicode_identifier(self):
966 c = compile("# coding=latin-1\n\u00c6 = '\u00c6'", "dummy", "exec")
967 d = {}
968 exec(c, d)
969 assert d['\xc6'] == '\xc6'
970 c = compile("日本 = 8; 日本2 = 日本 + 1; del 日本;", "dummy", "exec")
971 exec(c, d)
972 assert '日本2' in d
973 assert d['日本2'] == 9
974 assert '日本' not in d
975
976 raises(SyntaxError, eval, b'\xff\x20')
977 raises(SyntaxError, eval, b'\xef\xbb\x20')
978
979 def test_unicode_identifier_error_offset(self):
980 info = raises(SyntaxError, eval, b'\xe2\x82\xac = 1')
981 assert info.value.offset == 1
982 assert raises(SyntaxError, eval, b'\xc3\xa4 + \xe2\x82\xac').value.offset == 5
983
984 def test_import_nonascii(self):
985 c = compile('from os import 日本', '', 'exec')
986 assert ('日本',) in c.co_consts
987
988 def test_class_nonascii(self):
989 """
990 class 日本:
991 pass
992 assert 日本.__name__ == '日本'
993 assert 日本.__qualname__ == 'test_class_nonascii.<locals>.日本'
994 assert '日本' in repr(日本)
995 """
996
997 def test_cpython_issue2301(self):
998 try:
999 compile(b"# coding: utf7\nprint '+XnQ-'", "dummy", "exec")
1000 except SyntaxError as v:
1001 assert v.text == "print '\u5e74'\n"
1002 else:
1003 assert False, "Expected SyntaxError"
1004
1005 def test_invalid_utf8(self):
1006 e = raises(SyntaxError, compile, b'\x80', "dummy", "exec")
1007 assert str(e.value).startswith('Non-UTF-8 code')
1008 assert 'but no encoding declared' in str(e.value)
1009 e = raises(SyntaxError, compile, b'# coding: utf-8\n\x80',
1010 "dummy", "exec")
1011 assert str(e.value).startswith('Non-UTF-8 code')
1012 assert 'but no encoding declared' not in str(e.value)
1013
1014 def test_invalid_utf8_in_comments_or_strings(self):
1015 import sys
1016 compile(b"# coding: latin1\n#\xfd\n", "dummy", "exec")
1017 raises(SyntaxError, compile, b"# coding: utf-8\n'\xfd'\n",
1018 "dummy", "exec") #1
1019 excinfo = raises(SyntaxError, compile, b'# coding: utf-8\nx=5\nb"\xfd"\n',
1020 "dummy", "exec") #2
1021 assert excinfo.value.lineno == 3
1022 # the following example still fails on CPython 3.5.2, skip if -A
1023 if '__pypy__' in sys.builtin_module_names:
1024 raises(SyntaxError, compile, b"# coding: utf-8\n#\xfd\n",
1025 "dummy", "exec") #3
1026
1027 def test_invalid_utf8_in_multiline_string(self):
1028 # gh96611: non-UTF-8 byte inside a multiline string literal should
1029 # produce "Non-UTF-8 code starting with '\xNN'" not a codec error
1030 excinfo = raises(SyntaxError, compile, b'print("""\n\xb1""")\n',
1031 "dummy", "exec")
1032 assert str(excinfo.value).startswith("Non-UTF-8 code starting with '\\xb1'")
1033
1034 def test_cpython_issues_24022_25388(self):
1035 from _ast import PyCF_ACCEPT_NULL_BYTES
1036 raises(SyntaxError, compile, b'0000\x00\n00000000000\n\x00\n\x9e\n',
1037 "dummy", "exec", PyCF_ACCEPT_NULL_BYTES)
1038 raises(SyntaxError, compile, b"#\x00\n#\xfd\n", "dummy", "exec",
1039 PyCF_ACCEPT_NULL_BYTES)
1040 raises(SyntaxError, compile, b"#\x00\nx=5#\xfd\n", "dummy", "exec",
1041 PyCF_ACCEPT_NULL_BYTES)
1042
1043 def test_correct_offset_in_many_bytes(self):
1044 excinfo = raises(SyntaxError, compile, b'# coding: utf-8\nx = b"a" b"c" b"\xfd"\n',
1045 "dummy", "exec")
1046 assert excinfo.value.lineno == 2
1047 assert excinfo.value.offset == 17
1048
1049 def test_zeros_not_mixed_in_lambdas(self):
1050 import math
1051 code = compile("x = lambda: -0.0; y = lambda: 0.0", "<test>", "exec")
1052 consts = code.co_consts
1053 x, y, z = consts
1054 assert isinstance(x, type(code)) and isinstance(y, type(code))
1055 assert x is not y
1056 assert x != y
1057
1058 @py.test.mark.skipif('config.option.runappdirect')
1059 def test_dont_share_lambdas(self):
1060 # the two lambdas's codes aren't shared (CPython does that but it's
1061 # completely pointless: it only applies to identical lambdas that are
1062 # defined on the same line)
1063 code = compile("x = lambda: 0; y = lambda: 0", "<test>", "exec")
1064 consts = code.co_consts
1065 x, y, z = consts
1066 assert isinstance(x, type(code)) and isinstance(y, type(code))
1067 assert x is not y
1068 assert x == y
1069
1070 def test_dict_and_set_literal_order(self):
1071 x = 1
1072 l1 = list({1:'a', 3:'b', 2:'c', 4:'d'})
1073 l2 = list({1, 3, 2, 4})
1074 l3 = list({x:'a', 3:'b', 2:'c', 4:'d'})
1075 l4 = list({x, 3, 2, 4})
1076 if not self.host_is_pypy:
1077 # the full test relies on the host Python providing ordered dicts
1078 assert set(l1) == set(l2) == set(l3) == set(l4) == {1, 3, 2, 4}
1079 else:
1080 assert l1 == l2 == l3 == l4 == [1, 3, 2, 4]
1081
1082 def test_freevars_order(self):
1083 # co_cellvars and co_freevars are guaranteed to appear in
1084 # alphabetical order. See CPython Issue #15368 (which does
1085 # not come with tests).
1086 source = """if 1:
1087 def f1(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15):
1088 def g1():
1089 return (x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15)
1090 return g1
1091 def f2(x15,x14,x13,x12,x11,x10,x9,x8,x7,x6,x5,x4,x3,x2,x1):
1092 def g2():
1093 return (x15,x14,x13,x12,x11,x10,x9,x8,x7,x6,x5,x4,x3,x2,x1)
1094 return g2
1095 c1 = f1(*range(15)).__code__.co_freevars
1096 c2 = f2(*range(15)).__code__.co_freevars
1097 r1 = f1.__code__.co_cellvars
1098 r2 = f2.__code__.co_cellvars
1099 """
1100 d = {}
1101 exec(source, d)
1102 assert d['c1'] == d['c2']
1103 # the test above is important for a few bytecode hacks,
1104 # but actually we get them in alphabetical order, so check that:
1105 assert d['c1'] == tuple(sorted(d['c1']))
1106 assert d['r1'] == d['r2'] == d['c1']
1107
1108 def test_code_equality(self):
1109 import _ast
1110 sample_code = [
1111 ['<assign>', 'x = 5'],
1112 ['<ifblock>', """if True:\n pass\n"""],
1113 ['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
1114 ['<deffunc>', """def foo():\n pass\nfoo()\n"""],
1115 ]
1116
1117 for fname, code in sample_code:
1118 co1 = compile(code, '%s1' % fname, 'exec')
1119 ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
1120 assert type(ast) == _ast.Module
1121 co2 = compile(ast, '%s3' % fname, 'exec')
1122 assert co1 == co2
1123 # the code object's filename comes from the second compilation step
1124 assert co2.co_filename == '%s3' % fname
1125
1126 def test_invalid_ast(self):
1127 import _ast
1128 delete = _ast.Delete([])
1129 delete.lineno = 0
1130 delete.col_offset = 0
1131 mod = _ast.Module([delete], [])
1132 exc = raises(ValueError, compile, mod, 'filename', 'exec')
1133 assert str(exc.value) == "empty targets on Delete"
1134
1135 def test_evaluate_argument_definition_order(self): """
1136 lst = [1, 2, 3, 4]
1137 def f(a=lst.pop(), b=lst.pop(), *, c=lst.pop(), d=lst.pop()):
1138 return (a, b, c, d)
1139 assert f('a') == ('a', 3, 2, 1), repr(f('a'))
1140 assert f() == (4, 3, 2, 1), repr(f())
1141 #
1142 lst = [1, 2, 3, 4]
1143 f = lambda a=lst.pop(), b=lst.pop(), *, c=lst.pop(), d=lst.pop(): (
1144 a, b, c, d)
1145 assert f('a') == ('a', 3, 2, 1), repr(f('a'))
1146 assert f() == (4, 3, 2, 1), repr(f())
1147 """
1148
1149 # the following couple of tests are from test_super.py in the stdlib
1150
1151 def test_classcell(self):
1152 """
1153 test_class = None
1154 class Meta(type):
1155 def __new__(cls, name, bases, namespace):
1156 nonlocal test_class
1157 self = super().__new__(cls, name, bases, namespace)
1158 test_class = self.f()
1159 return self
1160 class A(metaclass=Meta):
1161 @staticmethod
1162 def f():
1163 return __class__
1164 assert test_class is A
1165 """
1166
1167 def test_classcell_missing(self):
1168 """
1169 # Some metaclasses may not pass the original namespace to type.__new__
1170 # We test that case here by forcibly deleting __classcell__
1171 class Meta(type):
1172 def __new__(cls, name, bases, namespace):
1173 namespace.pop('__classcell__', None)
1174 return super().__new__(cls, name, bases, namespace)
1175
1176 with raises(RuntimeError):
1177 class WithClassRef(metaclass=Meta):
1178 def f(self):
1179 return __class__
1180
1181 """
1182
1183 def test_classcell_overwrite(self):
1184 """
1185 # Overwriting __classcell__ with nonsense is explicitly prohibited
1186 class Meta(type):
1187 def __new__(cls, name, bases, namespace, cell):
1188 namespace['__classcell__'] = cell
1189 return super().__new__(cls, name, bases, namespace)
1190
1191 raises(TypeError, '''if 1:
1192 class A(metaclass=Meta, cell=object()):
1193 pass
1194 ''')
1195 """
1196
1197 def test_classcell_wrong_cell(self):
1198 """
1199 # Pointing the cell reference at the wrong class is prohibited
1200 class Meta(type):
1201 def __new__(cls, name, bases, namespace):
1202 cls = super().__new__(cls, name, bases, namespace)
1203 B = type("B", (), namespace)
1204 return cls
1205
1206 # works, no __class__
1207 class A(metaclass=Meta):
1208 pass
1209
1210 raises(TypeError, '''if 1:
1211 class A(metaclass=Meta):
1212 def f(self):
1213 return __class__
1214 ''')
1215
1216 """
1217
1218 def test_class_mro(self):
1219 """
1220 test_class = None
1221
1222 class Meta(type):
1223 def mro(self):
1224 # self.f() doesn't work yet...
1225 self.__dict__["f"]()
1226 return super().mro()
1227
1228 class A(metaclass=Meta):
1229 def f():
1230 nonlocal test_class
1231 test_class = __class__
1232
1233 assert test_class is A
1234 """
1235
1236
1237 class AppTestOptimizer(object):
1238 def setup_class(cls):
1239 cls.w_runappdirect = cls.space.wrap(cls.runappdirect)
1240
1241 def w_is_pypy(self):
1242 import sys
1243 return not self.runappdirect or '__pypy__' in sys.modules
1244
1245
1246 def test_remove_ending(self):
1247 source = """def f():
1248 return 3
1249 """
1250 ns = {}
1251 exec(source, ns)
1252 code = ns['f'].__code__
1253 import dis, sys
1254 from io import StringIO
1255 s = StringIO()
1256 so = sys.stdout
1257 sys.stdout = s
1258 try:
1259 dis.dis(code)
1260 finally:
1261 sys.stdout = so
1262 output = s.getvalue()
1263 assert output.count('LOAD_CONST') == 1
1264
1265 def test_constant_name(self):
1266 import opcode
1267 for name in "None", "True", "False":
1268 snip = "def f(): return " + name
1269 co = compile(snip, "<test>", "exec").co_consts[0]
1270 if self.is_pypy(): # This is a pypy optimization
1271 assert name not in co.co_names
1272 co = co.co_code
1273 op = co[0]
1274 assert op == opcode.opmap["LOAD_CONST"]
1275
1276 def test_and_or_folding(self):
1277 if not self.is_pypy():
1278 return # pypy-only
1279 def f1():
1280 return True or 1 + x
1281 assert len(f1.__code__.co_code) == 4 # load_const, return_value
1282 def f2():
1283 return 0 and 1 + x
1284 assert len(f2.__code__.co_code) == 4 # load_const, return_value
1285 def f3():
1286 return a or False or True or x
1287 assert len(f3.__code__.co_code) == 8 # load_global, jump, load_const, return_value
1288 def f4():
1289 return a and True and 0 and x
1290 assert len(f4.__code__.co_code) == 8 # load_global, jump, load_const, return_value
1291
1292
1293 def test_tuple_constants(self):
1294 ns = {}
1295 exec("x = (1, 0); y = (1, 0)", ns)
1296 assert isinstance(ns["x"][0], int)
1297 assert isinstance(ns["y"][0], int)
1298
1299 def test_ellipsis_truth(self):
1300 co = compile("if ...: x + 3\nelse: x + 4", "<test>", "exec")
1301 assert 4 not in co.co_consts
1302
1303 def test_division_folding(self):
1304 def code(source):
1305 return compile(source, "<test>", "exec")
1306 co = code("x = 10//4")
1307 if not self.is_pypy():
1308 assert 2 in co.co_consts
1309 else:
1310 # PyPy is more precise
1311 assert len(co.co_consts) == 2
1312 assert co.co_consts[0] == 2
1313 co = code("x = 10/4")
1314 if not self.is_pypy():
1315 assert 2.5 in co.co_consts
1316 else:
1317 assert len(co.co_consts) == 2
1318 assert co.co_consts[0] == 2.5
1319
1320 def test_tuple_folding(self):
1321 co = compile("x = (1, 2, 3)", "<test>", "exec")
1322 if self.is_pypy():
1323 # PyPy is more precise
1324 assert co.co_consts == ((1, 2, 3), None)
1325 else:
1326 assert (1, 2, 3) in co.co_consts
1327 assert None in co.co_consts
1328 co = compile("x = ()", "<test>", "exec")
1329 if self.is_pypy():
1330 # CPython does not constant-fold the empty tuple
1331 assert set(co.co_consts) == set(((), None))
1332
1333 def test_unary_folding(self):
1334 def check_const(co, value):
1335 assert value in co.co_consts
1336 if self.is_pypy():
1337 # This is a pypy optimization
1338 assert co.co_consts[0] == value
1339 co = compile("x = -(3)", "<test>", "exec")
1340 check_const(co, -3)
1341 co = compile("x = ~3", "<test>", "exec")
1342 check_const(co, ~3)
1343 co = compile("x = +(-3)", "<test>", "exec")
1344 check_const(co, -3)
1345 co = compile("x = not None", "<test>", "exec")
1346 if self.is_pypy():
1347 # CPython does not have this optimization
1348 assert co.co_consts == (True, None)
1349
1350 def test_folding_of_binops_on_constants(self):
1351 def disassemble(func):
1352 from io import StringIO
1353 import sys, dis
1354 f = StringIO()
1355 tmp = sys.stdout
1356 sys.stdout = f
1357 dis.dis(func)
1358 sys.stdout = tmp
1359 result = f.getvalue()
1360 f.close()
1361 return result
1362
1363 def dis_single(line):
1364 return disassemble(compile(line, '', 'single'))
1365
1366 for line, elem in (
1367 ('a = 2+3+4', '(9)'), # chained fold
1368 ('"@"*4', "('@@@@')"), # check string ops
1369 ('a="abc" + "def"', "('abcdef')"), # check string ops
1370 ('a = 3**4', '(81)'), # binary power
1371 ('a = 3*4', '(12)'), # binary multiply
1372 ('a = 13//4', '(3)'), # binary floor divide
1373 ('a = 14%4', '(2)'), # binary modulo
1374 ('a = 2+3', '(5)'), # binary add
1375 ('a = 13-4', '(9)'), # binary subtract
1376 ('a = (12,13)[1]', '(13)'), # binary subscr
1377 ('a = 13 << 2', '(52)'), # binary lshift
1378 ('a = 13 >> 2', '(3)'), # binary rshift
1379 ('a = 13 & 7', '(5)'), # binary and
1380 ('a = 13 ^ 7', '(10)'), # binary xor
1381 ('a = 13 | 7', '(15)'), # binary or
1382 ):
1383 asm = dis_single(line)
1384 print(asm)
1385 assert elem in asm, 'ELEMENT not in asm'
1386 assert 'BINARY_' not in asm, 'BINARY_in_asm'
1387
1388 # Verify that unfoldables are skipped
1389 asm = dis_single('a=2+"b"')
1390 assert '(2)' in asm
1391 assert "('b')" in asm
1392
1393 # Verify that large sequences do not result from folding
1394 asm = dis_single('a="x"*1000')
1395 assert '(1000)' in asm
1396
1397 def test_folding_of_binops_on_constants_crash(self):
1398 compile('()[...]', '', 'eval')
1399 # assert did not crash
1400
1401 def test_dis_stopcode(self):
1402 source = """def _f(a):
1403 print(a)
1404 return 1
1405 """
1406 ns = {}
1407 exec(source, ns)
1408 code = ns['_f'].__code__
1409
1410 import sys, dis
1411 from io import StringIO
1412 s = StringIO()
1413 save_stdout = sys.stdout
1414 sys.stdout = s
1415 try:
1416 dis.dis(code)
1417 finally:
1418 sys.stdout = save_stdout
1419 output = s.getvalue()
1420 assert "STOP_CODE" not in output
1421
1422 def test_optimize_list_comp(self):
1423 source = """def _f(a):
1424 return [x for x in a if None]
1425 """
1426 ns = {}
1427 exec(source, ns)
1428 code = ns['_f'].__code__
1429
1430 import sys, dis
1431 from io import StringIO
1432 s = StringIO()
1433 out = sys.stdout
1434 sys.stdout = s
1435 try:
1436 dis.dis(code)
1437 finally:
1438 sys.stdout = out
1439 output = s.getvalue()
1440 assert "LOAD_GLOBAL" not in output
1441
1442 def test_folding_of_list_constants(self):
1443 source = 'a in [1, 2, 3]'
1444 co = compile(source, '', 'exec')
1445 i = co.co_consts.index((1, 2, 3))
1446 assert i > -1
1447 assert isinstance(co.co_consts[i], tuple)
1448
1449 def test_folding_of_set_constants(self):
1450 source = 'a in {1, 2, 3}'
1451 co = compile(source, '', 'exec')
1452 i = co.co_consts.index(set([1, 2, 3]))
1453 assert i > -1
1454 assert isinstance(co.co_consts[i], frozenset)
1455
1456 def test_call_method_kwargs(self):
1457 if not self.is_pypy():
1458 skip("CALL_METHOD exists only on pypy")
1459 source = """def _f(a):
1460 return a.f(a=a)
1461 """
1462 ns = {}
1463 exec(source, ns)
1464 code = ns['_f'].__code__
1465
1466 import sys, dis
1467 from io import StringIO
1468 s = StringIO()
1469 out = sys.stdout
1470 sys.stdout = s
1471 try:
1472 dis.dis(code)
1473 finally:
1474 sys.stdout = out
1475 output = s.getvalue()
1476 assert "CALL_METHOD" in output, output
1477
1478 def test_interned_strings(self):
1479 source = """x = ('foo_bar42', 5); y = 'foo_bar42'; z = x[0]"""
1480 ns = {}
1481 exec(source, ns)
1482 assert ns['y'] is ns['z']
1483
1484
1485 class AppTestExceptions:
1486 def test_indentation_error(self):
1487 source = """if 1:
1488 x
1489 y
1490 """
1491 try:
1492 exec(source)
1493 except IndentationError:
1494 pass
1495 else:
1496 raise Exception("DID NOT RAISE")
1497
1498 def test_bad_oudent(self):
1499 source = """if 1:
1500 x
1501 y
1502 z
1503 """
1504 try:
1505 exec(source)
1506 except IndentationError as e:
1507 assert e.msg == 'unindent does not match any outer indentation level'
1508 else:
1509 raise Exception("DID NOT RAISE")
1510
1511 def test_outdentation_error_filename(self):
1512 source = """if 1:
1513 x
1514 y
1515 """
1516 try:
1517 exec(source)
1518 except IndentationError as e:
1519 assert e.filename == '<string>'
1520 else:
1521 raise Exception("DID NOT RAISE")
1522
1523 def test_taberror(self):
1524 source = """if 1:
1525 x
1526 \ty
1527 """
1528 try:
1529 exec(source)
1530 except TabError as e:
1531 pass
1532 else:
1533 raise Exception("DID NOT RAISE")
1534
1535 def test_repr_vs_str(self):
1536 source1 = "x = (\n"
1537 source2 = "x = (\n\n"
1538 try:
1539 exec(source1)
1540 except SyntaxError as e:
1541 err1 = e
1542 else:
1543 raise Exception("DID NOT RAISE")
1544 try:
1545 exec(source2)
1546 except SyntaxError as e:
1547 err2 = e
1548 else:
1549 raise Exception("DID NOT RAISE")
1550 assert str(err1) != str(err2)
1551 assert repr(err1) != repr(err2)
1552 err3 = eval(repr(err1))
1553 assert str(err3) == str(err1)
1554 assert repr(err3) == repr(err1)
1555
1556 def test_surrogate_filename(self):
1557 fname = '\udcff'
1558 co = compile("'dr cannon'", fname, 'exec')
1559 assert co.co_filename == fname
1560 try:
1561 compile("'dr", fname, 'exec')
1562 except SyntaxError as e:
1563 assert e.filename == fname
1564 else:
1565 assert False, 'SyntaxError expected'
1566
1567 def test_encoding(self):
1568 code = b'# -*- coding: badencoding -*-\npass\n'
1569 raises(SyntaxError, compile, code, 'tmp', 'exec')
1570 code = 'u"\xc2\xa4"\n'
1571 assert eval(code) == u'\xc2\xa4'
1572 code = u'u"\xc2\xa4"\n'
1573 assert eval(code) == u'\xc2\xa4'
1574 code = b'# -*- coding: latin1 -*-\nu"\xc2\xa4"\n'
1575 assert eval(code) == u'\xc2\xa4'
1576 code = b'# -*- coding: utf-8 -*-\nu"\xc2\xa4"\n'
1577 assert eval(code) == u'\xa4'
1578 code = b'# -*- coding: iso8859-15 -*-\nu"\xc2\xa4"\n'
1579 assert eval(code) == u'\xc2\u20ac'
1580 code = b'u"""\\\n# -*- coding: ascii -*-\n\xc2\xa4"""\n'
1581 assert eval(code) == u'# -*- coding: ascii -*-\n\xa4'
1582
1583
1584
1585 def test_asterror_has_line_without_file(self):
1586 code = u"print(1)\na/2 = 5\n"
1587 with raises(SyntaxError) as excinfo:
1588 compile(code, 'not a file!', 'exec')
1589 assert excinfo.value.text == "a/2 = 5\n"