Debian Codegraph @

pypy/interpreter/test/test_code.py

raw symbols SCIP
1 from pypy.interpreter.pycode import PyCode
2 from pypy.interpreter import gateway
3 from pypy.interpreter.astcompiler import consts
4 import py
5
6 class TestCode:
7 def test_code_eq_corner_cases(self):
8 space = self.space
9 def make_code_with_const(w_obj):
10 return PyCode(space, 0, 0, 0, 0, 1, 0, '', [w_obj], [], [], '', '', '', 0, '', [], [], False)
11 def cmp_code_consts(w_obj1, w_obj2):
12 w_code1 = make_code_with_const(w_obj1)
13 w_code2 = make_code_with_const(w_obj2)
14
15 # code objects in co_consts are compared by identity
16 # (we never share them in the bytecode compiler, it happens
17 # extremely rarely and is not useful anyway)
18
19 res1 = space.is_true(space.eq(w_code1, w_code2))
20 res2 = space.is_true(space.eq(w_code2, w_code1))
21 if res1:
22 # if the code objects are equal, the hash should be the same
23 h1 = space.int_w(w_code1.descr_code__hash__())
24 h2 = space.int_w(w_code2.descr_code__hash__())
25 assert h1 == h2
26
27 # check reflexivity
28 assert res1 == res2
29
30
31 # wrapping as code doesn't change the result
32 w_codecode1 = make_code_with_const(w_code1)
33 w_codecode2 = make_code_with_const(w_code2)
34 assert space.is_true(space.eq(w_codecode1, w_codecode2)) == res1
35
36 # check that tupleization doesn't change the result
37 if not space.isinstance_w(w_obj1, space.w_tuple):
38 res3 = cmp_code_consts(space.newtuple([space.w_None, w_obj1]),
39 space.newtuple([space.w_None, w_obj2]))
40 assert res3 == res1
41 return res1
42
43 assert cmp_code_consts(space.w_None, space.w_None)
44
45 # floats
46 assert not cmp_code_consts(space.newfloat(0.0), space.newfloat(-0.0))
47 assert cmp_code_consts(space.newfloat(float('nan')), space.newfloat(float('nan')))
48
49 # complex
50 assert not cmp_code_consts(space.newcomplex(0.0, 0.0), space.newcomplex(0.0, -0.0))
51 assert not cmp_code_consts(space.newcomplex(0.0, 0.0), space.newcomplex(-0.0, 0.0))
52 assert not cmp_code_consts(space.newcomplex(0.0, 0.0), space.newcomplex(-0.0, -0.0))
53 assert not cmp_code_consts(space.newcomplex(-0.0, 0.0), space.newcomplex(0.0, -0.0))
54 assert not cmp_code_consts(space.newcomplex(-0.0, 0.0), space.newcomplex(-0.0, -0.0))
55 assert not cmp_code_consts(space.newcomplex(0.0, -0.0), space.newcomplex(-0.0, -0.0))
56
57 # code objects: we compare them by identity, PyPy doesn't share them ever
58
59
60 class AppTestCodeIntrospection:
61 def setup_class(cls):
62 filename = __file__
63 if filename[-3:] != '.py':
64 filename = filename[:-1]
65
66 cls.w_file = cls.space.wrap(filename)
67 cls.w_CO_NOFREE = cls.space.wrap(consts.CO_NOFREE)
68
69 def test_attributes(self):
70 def f(): pass
71 def g(x, *y, **z): "docstring"
72 assert hasattr(f.__code__, 'co_code')
73 assert hasattr(g.__code__, 'co_code')
74
75 testcases = [
76 (f.__code__, {'co_name': 'f',
77 'co_names': (),
78 'co_varnames': (),
79 'co_argcount': 0,
80 'co_posonlyargcount': 0,
81 'co_kwonlyargcount': 0,
82 'co_consts': (None,)
83 }),
84 (g.__code__, {'co_name': 'g',
85 'co_names': (),
86 'co_varnames': ('x', 'y', 'z'),
87 'co_argcount': 1,
88 'co_posonlyargcount': 0,
89 'co_kwonlyargcount': 0,
90 'co_consts': ("docstring", None),
91 }),
92 ]
93
94 import sys
95 if hasattr(sys, 'pypy_objspaceclass'):
96 testcases += [
97 (abs.__code__, {'co_name': 'abs',
98 'co_varnames': ('val',),
99 'co_argcount': 1,
100 'co_posonlyargcount': 0,
101 'co_kwonlyargcount': 0,
102 'co_flags': 0,
103 'co_consts': ("abs(number) -> number\n\nReturn the absolute value of the argument.",),
104 }),
105 (object.__init__.__code__,
106 {#'co_name': '__init__', XXX getting descr__init__
107 'co_varnames': ('obj', 'args', 'keywords'),
108 'co_argcount': 1,
109 'co_posonlyargcount': 0,
110 'co_kwonlyargcount': 0,
111 'co_flags': 0x000C, # VARARGS|VARKEYWORDS
112 }),
113 ]
114
115 # in PyPy, built-in functions have code objects
116 # that emulate some attributes
117 for code, expected in testcases:
118 assert hasattr(code, '__class__')
119 assert not hasattr(code,'__dict__')
120 for key, value in expected.items():
121 assert getattr(code, key) == value
122
123
124 def test_posonlyargcount(self):
125 """
126 def f(a, b, /, c): pass
127 assert f.__code__.co_argcount == 3
128 assert f.__code__.co_posonlyargcount == 2
129 """
130
131
132 def test_kwonlyargcount(self):
133 """
134 def f(*args, a, b, **kw): pass
135 assert f.__code__.co_kwonlyargcount == 2
136 """
137
138 def test_co_names(self):
139 src = '''if 1:
140 def foo():
141 pass
142
143 g = 3
144
145 def f(x, y):
146 z = x + y
147 foo(g)
148 '''
149 d = {}
150 exec(src, d)
151
152 assert list(sorted(d['f'].__code__.co_names)) == ['foo', 'g']
153
154 def test_hash(self):
155 d1 = {}
156 exec("def f(): pass", d1)
157 d2 = {}
158 exec("def f(): pass", d2)
159 assert d1['f'].__code__ == d2['f'].__code__
160 assert hash(d1['f'].__code__) == hash(d2['f'].__code__)
161
162 def test_repr(self):
163 def f():
164 xxx
165 res = repr(f.__code__)
166 assert res.startswith("<code object f at 0x")
167 assert ', file "%s", line ' % f.__code__.co_filename in res
168 assert res.endswith('>')
169
170 def test_code_extra(self):
171 assert compile("x = x + 1", 'baz', 'exec').co_flags & self.CO_NOFREE
172
173 d = {}
174 exec("""if 1:
175 def f():
176 "docstring"
177 'stuff'
178 56
179 """, d)
180
181 # check for new flag, CO_NOFREE
182 assert d['f'].__code__.co_flags & self.CO_NOFREE
183
184 exec("""if 1:
185 def f(x):
186 def g(y):
187 return x+y
188 return g
189 """, d)
190
191 # CO_NESTED
192 assert d['f'](4).__code__.co_flags & 0x10
193 assert d['f'].__code__.co_flags & 0x10 == 0
194
195 def test_code_eq_non_code(self):
196 class A(object):
197 def __eq__(self, other):
198 return 23
199 def __ne__(self, other):
200 return 41
201 def f(): pass
202 assert (f.__code__ == A()) == 23
203 assert (f.__code__ != A()) == 41
204
205 def test_issue1844(self):
206 import types
207 args = (1, 0, 0, 1, 0, 0, b'', (), (), (), '', 'operator', 'operator', 0, b'')
208 # previously raised a MemoryError when translated
209 types.CodeType(*args)
210
211 def test_replace(self):
212 co = compile("x = x + 1", 'baz', 'exec')
213 co2 = co.replace(co_flags=co.co_flags | 0x100)
214 assert co2.co_name == co.co_name # in theory need to check them all
215 assert co2.co_flags == co.co_flags | 0x100
216
217 with raises(TypeError):
218 co.replace(1)
219 with raises(TypeError):
220 co.replace(abc=123)
221
222 def test_varname_from_oparg(self):
223 def outer(cell):
224 def inner(x):
225 return cell
226 return inner
227
228 inner = outer(42)
229
230 for (c, e_varnames, e_cellvars, e_freevars) in [
231 (outer.__code__, ('cell', 'inner',), ('cell',), ()),
232 (inner.__code__, ('x',), (), ('cell',)),
233 ]:
234 print(c.co_varnames, c.co_cellvars, c.co_freevars)
235 assert c.co_varnames == e_varnames
236 assert c.co_cellvars == e_cellvars
237 assert c.co_freevars == e_freevars
238 localsplus = e_varnames + e_cellvars + e_freevars
239 assert tuple(c._varname_from_oparg(i) for i in range(len(localsplus))) == localsplus
240 raises(IndexError, c._varname_from_oparg, -1)
241 raises(IndexError, c._varname_from_oparg, len(localsplus))