Debian Codegraph @

rpython/rtyper/test/test_rbuiltin.py

raw symbols SCIP
1 import math
2 import os
3 import sys
4
5 import py
6
7 from rpython.rlib.objectmodel import instantiate, compute_unique_id, current_object_addr_as_int
8 from rpython.rlib.rarithmetic import (intmask, longlongmask, r_int64, is_valid_int,
9 r_int, r_uint, r_longlong, r_ulonglong)
10 from rpython.rlib.rstring import StringBuilder, UnicodeBuilder
11 from rpython.rtyper.annlowlevel import hlstr, LowLevelAnnotatorPolicy
12 from rpython.rtyper.lltypesystem import lltype, rffi
13 from rpython.rtyper.test import test_llinterp
14 from rpython.rtyper.test.tool import BaseRtypingTest
15 from rpython.tool import udir
16 from rpython.translator.translator import graphof
17
18 IS_PYPY = "__pypy__" in sys.builtin_module_names
19 MACOS = sys.platform == "darwin"
20
21 def enum_direct_calls(translator, func):
22 graph = graphof(translator, func)
23 for block in graph.iterblocks():
24 for op in block.operations:
25 if op.opname == 'direct_call':
26 yield op
27
28
29 def skip_if_m1():
30 return True
31 """ Bugs in libffi linked against cpython make ll2ctypes unusable
32 for variadic functions on m1 platform, skip those tests
33 """
34 import platform
35 if MACOS and not IS_PYPY and platform.machine() == 'arm64':
36 py.test.skip("Variadic functions on m1 unsupported on ll2ctypes")
37
38 class TestRbuiltin(BaseRtypingTest):
39
40 def test_method_join(self):
41 # this is tuned to catch a specific bug:
42 # a wrong rtyper_makekey() for BuiltinMethodRepr
43 def f():
44 lst1 = ['abc', 'def']
45 s1 = ', '.join(lst1)
46 lst2 = ['1', '2', '3']
47 s2 = ''.join(lst2)
48 return s1 + s2
49 res = self.interpret(f, [])
50 assert self.ll_to_string(res) == 'abc, def123'
51
52 def test_method_repr(self):
53 def g(n):
54 if n >= 0:
55 return "egg"
56 else:
57 return "spam"
58 def f(n):
59 # this is designed for a specific bug: conversions between
60 # BuiltinMethodRepr. The append method of the list is passed
61 # around, and g(-1) below causes a reflowing at the beginning
62 # of the loop (but not inside the loop). This situation creates
63 # a newlist returning a SomeList() which '==' but 'is not' the
64 # SomeList() inside the loop.
65 x = len([ord(c) for c in g(1)])
66 g(-1)
67 return x
68 res = self.interpret(f, [0])
69 assert res == 3
70
71 def test_chr(self):
72 def f(x=int):
73 try:
74 return chr(x)
75 except ValueError:
76 return '?'
77 res = self.interpret(f, [65])
78 assert res == 'A'
79 res = self.interpret(f, [256])
80 assert res == '?'
81 res = self.interpret(f, [-1])
82 assert res == '?'
83
84 def test_intmask(self):
85 def f(x=r_uint):
86 try:
87 return intmask(x)
88 except ValueError:
89 return 0
90
91 res = self.interpret(f, [r_uint(5)])
92 assert type(res) is int and res == 5
93
94 def test_longlongmask(self):
95 def f(x=r_ulonglong):
96 try:
97 return longlongmask(x)
98 except ValueError:
99 return 0
100
101 res = self.interpret(f, [r_ulonglong(5)])
102 assert type(res) is r_int64 and res == 5
103
104 def test_rbuiltin_list(self):
105 def f():
106 l = list((1,2,3))
107 return l == [1,2,3]
108 def g():
109 l = list(('he', 'llo'))
110 return l == ['he', 'llo']
111 def r():
112 l = ['he','llo']
113 l1 = list(l)
114 return l == l1 and l is not l1
115 result = self.interpret(f, [])
116 assert result
117
118 result = self.interpret(g, [])
119 assert result
120
121 result = self.interpret(r, [])
122 assert result
123
124 def test_int_min(self):
125 def fn(i, j):
126 return min(i ,j)
127 ev_fun = self.interpret(fn, [0, 0])
128 assert self.interpret(fn, (1, 2)) == 1
129 assert self.interpret(fn, (1, -1)) == -1
130 assert self.interpret(fn, (2, 2)) == 2
131 assert self.interpret(fn, (-1, -12)) == -12
132
133 def test_int_max(self):
134 def fn(i, j):
135 return max(i,j)
136 assert self.interpret(fn, (1, 2)) == 2
137 assert self.interpret(fn, (1, -1)) == 1
138 assert self.interpret(fn, (2, 2)) == 2
139 assert self.interpret(fn, (-1, -12)) == -1
140
141 def test_float_min(self):
142 def fn(i, j):
143 return min(i, j)
144 assert self.interpret(fn, (1.9, 2.)) == 1.9
145 assert self.interpret(fn, (1.5, -1.4)) == -1.4
146
147 def test_float_int_min(self):
148 def fn(i, j):
149 return min(i, j)
150 assert self.interpret(fn, (1.9, 2)) == 1.9
151 assert self.interpret(fn, (1.5, -1)) == -1
152
153 def test_float_max(self):
154 def fn(i, j):
155 return max(i,j)
156 assert self.interpret(fn, (1.0, 2.)) == 2
157 assert self.interpret(fn, (1.1, -1)) == 1.1
158
159 def test_builtin_math_floor(self):
160 def fn(f):
161 return math.floor(f)
162 for i in range(5):
163 rv = 1000 * float(i-10)
164 res = self.interpret(fn, [rv])
165 assert fn(rv) == res
166
167 def test_builtin_math_fmod(self):
168 def fn(f,y):
169 return math.fmod(f,y)
170
171 for i in range(10):
172 for j in range(10):
173 rv = 1000 * float(i-10)
174 ry = 100 * float(i-10) +0.1
175 assert self.float_eq(fn(rv,ry), self.interpret(fn, (rv, ry)))
176
177 def test_builtin_math_frexp(self):
178 def fn(f):
179 return math.frexp(f)
180 for x in (.5, 1, 1.5, 10/3.0):
181 for y in (1, -1):
182 res = self.interpret(fn, [x*y])
183 mantissa, exponent = math.frexp(x*y)
184 assert (self.float_eq(res.item0, mantissa) and
185 self.float_eq(res.item1, exponent))
186
187 def test_builtin_math_ldexp(self):
188 def fn(a, b):
189 return math.ldexp(a, b)
190 assert self.interpret(fn, [1, 2]) == 4
191 self.interpret_raises(OverflowError, fn, [1, 100000])
192
193 def test_builtin_math_modf(self):
194 def fn(f):
195 return math.modf(f)
196 res = self.interpret(fn, [10/3.0])
197 intpart, fracpart = math.modf(10/3.0)
198 assert self.float_eq(res.item0, intpart) and self.float_eq(res.item1, fracpart)
199
200 def test_os_getcwd(self):
201 def fn():
202 return os.getcwd()
203 res = self.interpret(fn, [])
204 assert self.ll_to_string(res) == fn()
205
206 def test_os_write(self):
207 skip_if_m1()
208 tmpdir = str(udir.udir.join("os_write_test"))
209 def wr_open(fname):
210 fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
211 os.write(fd, "hello world")
212 return fd
213 def f():
214 return wr_open(tmpdir)
215 res = self.interpret(f, [])
216 os.close(res)
217 hello = open(tmpdir).read()
218 assert hello == "hello world"
219 fd = os.open(tmpdir, os.O_WRONLY|os.O_CREAT, 777)
220 os.close(fd)
221 py.test.raises(OSError, os.write, fd, "hello world")
222
223 def test_os_write_single_char(self):
224 skip_if_m1()
225 tmpdir = str(udir.udir.join("os_write_test_char"))
226 def wr_open(fname):
227 fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
228 os.write(fd, "x")
229 return fd
230 def f():
231 return wr_open(tmpdir)
232 res = self.interpret(f, [])
233 os.close(res)
234 hello = open(tmpdir).read()
235 assert hello == "x"
236
237 def test_os_read(self):
238 tmpfile = str(udir.udir.join("os_read_test"))
239 f = file(tmpfile, 'w')
240 f.write('hello world')
241 f.close()
242 def fn():
243 fd = os.open(tmpfile, os.O_RDONLY, 0777)
244 return os.read(fd, 4096)
245 res = self.interpret(fn, [])
246 assert self.ll_to_string(res) == 'hello world'
247
248 def test_os_lseek(self):
249 self._skip_llinterpreter("os.lseek")
250 tmpfile = str(udir.udir.join("os_lseek_test"))
251 f = file(tmpfile, 'w')
252 f.write('0123456789')
253 f.close()
254 SEEK_SET = 0
255 SEEK_CUR = 1
256 SEEK_END = 2
257 def fn():
258 fd = os.open(tmpfile, os.O_RDONLY, 0777)
259 res = ''
260 os.lseek(fd, 5, SEEK_SET)
261 res += os.read(fd, 1)
262 os.lseek(fd, 2, SEEK_CUR)
263 res += os.read(fd, 1)
264 os.lseek(fd, -2, SEEK_CUR)
265 res += os.read(fd, 1)
266 os.lseek(fd, -1, SEEK_END)
267 res += os.read(fd, 1)
268 os.close(fd)
269 return res
270 res1 = fn()
271 res2 = self.ll_to_string(self.interpret(fn, []))
272 assert res1 == res2
273
274 def test_os_dup(self):
275 def fn(fd):
276 return os.dup(fd)
277 res = self.interpret(fn, [0])
278 try:
279 os.close(res)
280 except OSError:
281 pass
282 count = 0
283 for dir_call in enum_direct_calls(test_llinterp.typer.annotator.translator, fn):
284 cfptr = dir_call.args[0]
285 assert self.get_callable(cfptr.value).__name__.startswith('dup')
286 count += 1
287 assert count == 1
288
289 def test_os_open(self):
290 tmpdir = str(udir.udir.join("os_open_test"))
291 def wr_open(fname):
292 return os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
293 def f():
294 return wr_open(tmpdir)
295 res = self.interpret(f, [])
296 os.close(res)
297 count = 0
298 for dir_call in enum_direct_calls(test_llinterp.typer.annotator.translator, wr_open):
299 cfptr = dir_call.args[0]
300 assert self.get_callable(cfptr.value).__name__ == 'open'
301 count += 1
302 assert count == 1
303
304 def test_os_path_exists(self):
305 self._skip_llinterpreter("os.stat()")
306
307 def f(fn):
308 fn = hlstr(fn)
309 return os.path.exists(fn)
310 filename = self.string_to_ll(str(py.path.local(__file__)))
311 assert self.interpret(f, [filename]) == True
312 #assert self.interpret(f, [
313 # self.string_to_ll("strange_filename_that_looks_improbable.sde")]) == False
314
315 def test_os_isdir(self):
316 self._skip_llinterpreter("os.stat()")
317
318 def f(fn):
319 fn = hlstr(fn)
320 return os.path.isdir(fn)
321 assert self.interpret(f, [self.string_to_ll("/")]) == True
322 assert self.interpret(f, [self.string_to_ll(str(py.path.local(__file__)))]) == False
323 assert self.interpret(f, [self.string_to_ll("another/unlikely/directory/name")]) == False
324
325 def test_pbc_isTrue(self):
326 class C:
327 def f(self):
328 pass
329
330 def g(obj):
331 return bool(obj)
332 def fn(neg):
333 c = C.f
334 return g(c)
335 assert self.interpret(fn, [True])
336 def fn(neg):
337 c = None
338 return g(c)
339 assert not self.interpret(fn, [True])
340
341 def test_const_isinstance(self):
342 class B(object):
343 pass
344 def f():
345 b = B()
346 return isinstance(b, B)
347 res = self.interpret(f, [])
348 assert res is True
349
350 def test_isinstance(self):
351 class A(object):
352 pass
353 class B(A):
354 pass
355 class C(A):
356 pass
357 def f(x, y):
358 if x == 1:
359 a = A()
360 elif x == 2:
361 a = B()
362 else:
363 a = C()
364 if y == 1:
365 res = isinstance(a, A)
366 cls = A
367 elif y == 2:
368 res = isinstance(a, B)
369 cls = B
370 else:
371 res = isinstance(a, C)
372 cls = C
373 return int(res) + 2 * isinstance(a, cls)
374 for x in [1, 2, 3]:
375 for y in [1, 2, 3]:
376 res = self.interpret(f, [x, y])
377 assert res == isinstance([A(), B(), C()][x-1], [A, B, C][y-1]) * 3
378
379 def test_isinstance_list(self):
380 def g():
381 pass
382 def f(i):
383 if i == 0:
384 l = []
385 else:
386 l = None
387 g()
388 return isinstance(l, list)
389 res = self.interpret(f, [0])
390 assert res is True
391 res = self.interpret(f, [1])
392 assert res is False
393
394 def test_isinstance_str(self):
395 def g():
396 pass
397 def f(i):
398 if i == 0:
399 l = "foobar"
400 else:
401 l = None
402 g()
403 return isinstance(l, str)
404 res = self.interpret(f, [0])
405 assert res is True
406 res = self.interpret(f, [1])
407 assert res is False
408
409 def test_isinstance_unicode(self):
410 def g():
411 pass
412 def f(i):
413 if i == 0:
414 l = u"foobar"
415 else:
416 l = None
417 g()
418 return isinstance(l, unicode)
419 res = self.interpret(f, [0])
420 assert res is True
421 res = self.interpret(f, [1])
422 assert res is False
423
424 def test_instantiate(self):
425 class A:
426 pass
427 def f():
428 return instantiate(A)
429 res = self.interpret(f, [])
430 assert self.class_name(res) == 'A'
431
432 def test_instantiate_multiple(self):
433 class A:
434 pass
435 class B(A):
436 pass
437 def f(i):
438 if i == 1:
439 cls = A
440 else:
441 cls = B
442 return instantiate(cls)
443 res = self.interpret(f, [1])
444 assert self.class_name(res) == 'A'
445 res = self.interpret(f, [2])
446 assert self.class_name(res) == 'B'
447
448 def test_instantiate_nonmovable(self):
449 class A:
450 pass
451 def f():
452 return instantiate(A, nonmovable=True) # no effect before GC
453 res = self.interpret(f, [])
454 assert self.class_name(res) == 'A'
455
456 def test_os_path_join(self):
457 def fn(a, b):
458 return os.path.join(a, b)
459 res = self.ll_to_string(self.interpret(fn, ['a', 'b']))
460 assert res == os.path.join('a', 'b')
461
462 def test_exceptions(self):
463 def fn(a):
464 try:
465 a += int(str(int(a)))
466 a += int(int(a > 5))
467 finally:
468 return a
469 res = self.interpret(fn, [3.25])
470 assert res == 7.25
471
472 def test_id(self):
473 class A:
474 pass
475 def fn():
476 a1 = A()
477 a2 = A()
478 return (compute_unique_id(a1), current_object_addr_as_int(a1),
479 compute_unique_id(a2), current_object_addr_as_int(a2))
480 res = self.interpret(fn, [])
481 x0, x1, x2, x3 = self.ll_unpack_tuple(res, 4)
482 assert isinstance(x0, (int, r_longlong))
483 assert isinstance(x1, int)
484 assert isinstance(x2, (int, r_longlong))
485 assert isinstance(x3, int)
486 assert x0 != x2
487 # the following checks are probably too precise, but work at
488 # least on top of llinterp
489 assert x1 == intmask(x0)
490 assert x3 == intmask(x2)
491
492 def test_id_on_builtins(self):
493 def fn():
494 return (compute_unique_id("foo"),
495 compute_unique_id(u"bar"),
496 compute_unique_id([1]),
497 compute_unique_id({"foo": 3}),
498 compute_unique_id(StringBuilder()),
499 compute_unique_id(UnicodeBuilder()))
500 res = self.interpret(fn, [])
501 for id in self.ll_unpack_tuple(res, 6):
502 assert isinstance(id, (int, r_longlong))
503
504 def test_uniqueness_of_id_on_strings(self):
505 def fn(s1, s2):
506 return (compute_unique_id(s1), compute_unique_id(s2))
507
508 s1 = "foo"
509 s2 = ''.join(['f','oo'])
510 res = self.interpret(fn, [self.string_to_ll(s1), self.string_to_ll(s2)])
511 i1, i2 = self.ll_unpack_tuple(res, 2)
512 assert i1 != i2
513
514 def test_cast_primitive(self):
515 def llf(u):
516 return lltype.cast_primitive(lltype.Signed, u)
517 res = self.interpret(llf, [r_uint(-1)], policy=LowLevelAnnotatorPolicy())
518 assert res == -1
519 res = self.interpret(llf, ['x'], policy=LowLevelAnnotatorPolicy())
520 assert res == ord('x')
521 def llf(v):
522 return lltype.cast_primitive(lltype.Unsigned, v)
523 res = self.interpret(llf, [-1], policy=LowLevelAnnotatorPolicy())
524 assert res == r_uint(-1)
525 res = self.interpret(llf, [u'x'], policy=LowLevelAnnotatorPolicy())
526 assert res == ord(u'x')
527 res = self.interpret(llf, [1.0], policy=LowLevelAnnotatorPolicy())
528 assert res == r_uint(1)
529 def llf(v):
530 return lltype.cast_primitive(lltype.Char, v)
531 res = self.interpret(llf, [ord('x')], policy=LowLevelAnnotatorPolicy())
532 assert res == 'x'
533 def llf(v):
534 return lltype.cast_primitive(lltype.UniChar, v)
535 res = self.interpret(llf, [ord('x')], policy=LowLevelAnnotatorPolicy())
536 assert res == u'x'
537 def llf(v):
538 return lltype.cast_primitive(rffi.SHORT, v)
539 res = self.interpret(llf, [123], policy=LowLevelAnnotatorPolicy())
540 assert res == 123
541 def llf(v):
542 return lltype.cast_primitive(lltype.Signed, v)
543 res = self.interpret(llf, [rffi.r_short(123)], policy=LowLevelAnnotatorPolicy())
544 assert res == 123
545 def llf(v):
546 return lltype.cast_primitive(lltype.Bool, v)
547 res = self.interpret(llf, [2**24], policy=LowLevelAnnotatorPolicy())
548 assert res == True
549 def llf(v):
550 return lltype.cast_primitive(lltype.Bool, v)
551 res = self.interpret(llf, [rffi.r_longlong(2**48)], policy=LowLevelAnnotatorPolicy())
552 assert res == True
553
554 def test_force_cast(self):
555 def llfn(v):
556 return rffi.cast(rffi.SHORT, v)
557 res = self.interpret(llfn, [0x12345678])
558 assert res == 0x5678
559
560 def test_builtin_next(self):
561 def f(n):
562 x = [1, n, 2]
563 s = iter(x)
564 return next(s) + next(s)
565 res = self.interpret(f, [10])
566 assert res == 11
567
568 def test_builtin_next_stop_iteration(self):
569 def f(n):
570 x = [n]
571 s = iter(x)
572 try:
573 return next(s) + next(s)
574 except StopIteration:
575 return n + 500
576
577 res = self.interpret(f, [12])
578 assert res == 512
579
580 def test_cast(self):
581 def llfn(v):
582 return rffi.cast(rffi.VOIDP, v)
583 res = self.interpret(llfn, [r_ulonglong(0)])
584 assert res == lltype.nullptr(rffi.VOIDP.TO)
585 #
586 def llfn(v):
587 return rffi.cast(rffi.LONGLONG, v)
588 res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
589 assert res == 0
590 if r_longlong is not r_int:
591 assert isinstance(res, r_longlong)
592 else:
593 assert is_valid_int(res)
594 #
595 def llfn(v):
596 return rffi.cast(rffi.ULONGLONG, v)
597 res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
598 assert res == 0
599 assert isinstance(res, r_ulonglong)