Debian Codegraph @

rpython/translator/c/test/test_genc.py

raw symbols SCIP
1 import ctypes
2 import math
3 import re
4 from collections import OrderedDict
5
6 import py
7
8 from rpython.rlib.rfloat import NAN, INFINITY
9 from rpython.rlib.entrypoint import entrypoint_highlevel
10 from rpython.rlib.unroll import unrolling_iterable
11 from rpython.rlib.rarithmetic import r_longlong, r_ulonglong, r_uint, intmask
12 from rpython.rlib.objectmodel import specialize
13 from rpython.rtyper.lltypesystem import lltype
14 from rpython.rtyper.lltypesystem.lltype import *
15 from rpython.rtyper.lltypesystem.rstr import STR
16 from rpython.tool.nullpath import NullPyPathLocal
17 from rpython.translator.c import genc
18 from rpython.translator.backendopt.merge_if_blocks import merge_if_blocks
19 from rpython.translator.interactive import Translation
20 from rpython.translator.translator import TranslationContext, graphof
21
22 signed_ffffffff = r_longlong(0xffffffff)
23 unsigned_ffffffff = r_ulonglong(0xffffffff)
24
25 def llrepr_in(v):
26 if r_uint is not r_ulonglong and isinstance(v, r_ulonglong):
27 return "%d:%d" % (intmask(v >> 32), intmask(v & unsigned_ffffffff))
28 elif isinstance(v, r_longlong):
29 return "%d:%d" % (intmask(v >> 32), intmask(v & signed_ffffffff))
30 elif isinstance(v, float):
31 return repr(v) # extra precision than str(v)
32 elif isinstance(v, str):
33 if v.isalnum():
34 return v
35 else: # escape the string
36 return '/' + ','.join([str(ord(c)) for c in v])
37 return str(v)
38
39 @specialize.argtype(0)
40 def llrepr_out(v):
41 if isinstance(v, float):
42 from rpython.rlib.rfloat import formatd, DTSF_ADD_DOT_0
43 return formatd(v, 'r', 0, DTSF_ADD_DOT_0)
44 return str(v) # always return a string, to get consistent types
45
46 def parse_longlong(a):
47 p0, p1 = a.split(":")
48 return (r_longlong(int(p0)) << 32) + (r_longlong(int(p1)) &
49 signed_ffffffff)
50
51 def parse_ulonglong(a):
52 p0, p1 = a.split(":")
53 return (r_ulonglong(int(p0)) << 32) + (r_ulonglong(int(p1)) &
54 unsigned_ffffffff)
55
56 def compile(fn, argtypes, view=False, gcpolicy="none", backendopt=True,
57 annotatorpolicy=None, thread=False,
58 return_stderr=False, **kwds):
59 argtypes_unroll = unrolling_iterable(enumerate(argtypes))
60
61 for argtype in argtypes:
62 if argtype not in [int, float, str, bool, r_ulonglong, r_longlong,
63 r_uint]:
64 raise Exception("Unsupported argtype, %r" % (argtype,))
65
66 def entry_point(argv):
67 args = ()
68 for i, argtype in argtypes_unroll:
69 a = argv[i + 1]
70 if argtype is int:
71 args += (int(a),)
72 elif argtype is r_uint:
73 args += (r_uint(int(a)),)
74 elif argtype is r_longlong:
75 args += (parse_longlong(a),)
76 elif argtype is r_ulonglong:
77 args += (parse_ulonglong(a),)
78 elif argtype is bool:
79 if a == 'True':
80 args += (True,)
81 else:
82 assert a == 'False'
83 args += (False,)
84 elif argtype is float:
85 if a == 'inf':
86 args += (INFINITY,)
87 elif a == '-inf':
88 args += (-INFINITY,)
89 elif a == 'nan':
90 args += (NAN,)
91 else:
92 args += (float(a),)
93 else:
94 if a.startswith('/'): # escaped string
95 if len(a) == 1:
96 a = ''
97 else:
98 l = a[1:].split(',')
99 a = ''.join([chr(int(x)) for x in l])
100 args += (a,)
101 res = fn(*args)
102 print "THE RESULT IS:", llrepr_out(res), ";"
103 return 0
104
105 t = Translation(entry_point, None, gc=gcpolicy, backend="c",
106 policy=annotatorpolicy, thread=thread, **kwds)
107 if not backendopt:
108 t.disable(["backendopt_lltype"])
109 t.driver.config.translation.countmallocs = True
110 t.annotate()
111 try:
112 if py.test.config.option.view:
113 t.view()
114 except AttributeError:
115 pass
116 t.rtype()
117 if backendopt:
118 t.backendopt()
119 try:
120 if py.test.config.option.view:
121 t.view()
122 except AttributeError:
123 pass
124 t.compile_c()
125 ll_res = graphof(t.context, fn).getreturnvar().concretetype
126
127 def output(stdout):
128 for line in stdout.splitlines(False):
129 if len(repr(line)) == len(line) + 2: # no escaped char
130 print line
131 else:
132 print 'REPR:', repr(line)
133
134 def f(*args, **kwds):
135 expected_extra_mallocs = kwds.pop('expected_extra_mallocs', 0)
136 expected_exception_name = kwds.pop('expected_exception_name', None)
137 assert not kwds
138 assert len(args) == len(argtypes)
139 for arg, argtype in zip(args, argtypes):
140 assert isinstance(arg, argtype)
141
142 stdout = t.driver.cbuilder.cmdexec(
143 " ".join([llrepr_in(arg) for arg in args]),
144 expect_crash=(expected_exception_name is not None),
145 err=return_stderr)
146 #
147 if expected_exception_name is not None:
148 stdout, stderr = stdout
149 print '--- stdout ---'
150 output(stdout)
151 print '--- stderr ---'
152 output(stderr)
153 print '--------------'
154 stderr, prevline, lastline, empty = stderr.rsplit('\n', 3)
155 assert empty == ''
156 expected = 'Fatal RPython error: ' + expected_exception_name
157 assert lastline == expected or prevline == expected
158 return None
159
160 if return_stderr:
161 stdout, stderr = stdout
162 output(stdout)
163 stdout, lastline, empty = stdout.rsplit('\n', 2)
164 assert empty == ''
165 assert lastline.startswith('MALLOC COUNTERS: ')
166 mallocs, frees = map(int, lastline.split()[2:])
167 assert stdout.endswith(' ;')
168 pos = stdout.rindex('THE RESULT IS: ')
169 res = stdout[pos + len('THE RESULT IS: '):-2]
170 #
171 if isinstance(expected_extra_mallocs, int):
172 assert mallocs - frees == expected_extra_mallocs
173 else:
174 assert mallocs - frees in expected_extra_mallocs
175 #
176 if return_stderr:
177 return stderr
178 if ll_res in [lltype.Signed, lltype.Unsigned, lltype.SignedLongLong,
179 lltype.UnsignedLongLong]:
180 return int(res)
181 elif ll_res == lltype.Bool:
182 return bool(int(res))
183 elif ll_res == lltype.Char:
184 assert len(res) == 1
185 return res
186 elif ll_res == lltype.Float:
187 return float(res)
188 elif ll_res == lltype.Ptr(STR):
189 return res
190 elif ll_res == lltype.Void:
191 return None
192 raise NotImplementedError("parsing %s" % (ll_res,))
193
194 class CompilationResult(object):
195 def __repr__(self):
196 return 'CompilationResult(%s)' % (fn.__name__,)
197 def __call__(self, *args, **kwds):
198 return f(*args, **kwds)
199
200 cr = CompilationResult()
201 cr.t = t
202 cr.builder = t.driver.cbuilder
203 return cr
204
205
206 def test_simple():
207 def f(x):
208 return x * 2
209
210 f1 = compile(f, [int])
211
212 assert f1(5) == 10
213 assert f1(-123) == -246
214
215 py.test.raises(Exception, f1, "world") # check that it's really typed
216
217
218 def test_int_becomes_float():
219 # used to crash "very often": the long chain of mangle() calls end
220 # up converting the return value of f() from an int to a float, but
221 # if blocks are followed in random order by the annotator, it will
222 # very likely first follow the call to llrepr_out() done after the
223 # call to f(), getting an int first (and a float only later).
224 @specialize.arg(1)
225 def mangle(x, chain):
226 if chain:
227 return mangle(x, chain[1:])
228 return x - 0.5
229 def f(x):
230 if x > 10:
231 x = mangle(x, (1,1,1,1,1,1,1,1,1,1))
232 return x + 1
233
234 f1 = compile(f, [int])
235
236 assert f1(5) == 6
237 assert f1(12) == 12.5
238
239
240 def test_string_arg():
241 def f(s):
242 total = 0
243 for c in s:
244 total += ord(c)
245 return total + len(s)
246
247 f1 = compile(f, [str])
248
249 for check in ['x', '', '\x00', '\x01', '\n', '\x7f', '\xff',
250 '\x00\x00', '\x00\x01']:
251 assert f1(check) == len(check) + sum(map(ord, check))
252
253
254 def test_dont_write_source_files():
255 from rpython.annotator.listdef import s_list_of_strings
256 def f(argv):
257 return len(argv)*2
258 t = TranslationContext()
259 t.buildannotator().build_types(f, [s_list_of_strings])
260 t.buildrtyper().specialize()
261
262 t.config.translation.countmallocs = True
263 t.config.translation.dont_write_c_files = True
264 builder = genc.CStandaloneBuilder(t, f, config=t.config)
265 builder.generate_source()
266 assert isinstance(builder.targetdir, NullPyPathLocal)
267 for f in builder.targetdir.listdir():
268 assert not str(f).endswith('.c')
269
270
271 def test_rlist():
272 def f(x):
273 l = [x]
274 l.append(x+1)
275 return l[0] * l[-1]
276 f1 = compile(f, [int])
277 assert f1(5) == 30
278 #assert f1(x=5) == 30
279
280
281 def test_rptr():
282 S = GcStruct('testing', ('x', Signed), ('y', Signed))
283 def f(i):
284 if i < 0:
285 p = nullptr(S)
286 else:
287 p = malloc(S)
288 p.x = i*2
289 if i > 0:
290 return p.x
291 else:
292 return -42
293 f1 = compile(f, [int])
294 assert f1(5) == 10
295 #assert f1(i=5) == 10
296 assert f1(1) == 2
297 assert f1(0) == -42
298 assert f1(-1) == -42
299 assert f1(-5) == -42
300
301
302 def test_empty_string():
303 A = Array(Char, hints={'nolength': True})
304 p = malloc(A, 1, immortal=True)
305 def f():
306 return p[0]
307 f1 = compile(f, [])
308 assert f1() == '\x00'
309
310
311 def test_rstr():
312 def fn(i):
313 return "hello"[i]
314 f1 = compile(fn, [int])
315 res = f1(1)
316 assert res == 'e'
317
318
319 def test_recursive_struct():
320 # B has an A as its super field, and A has a pointer to B.
321 class A:
322 pass
323 class B(A):
324 pass
325 def fn(i):
326 a = A()
327 b = B()
328 a.b = b
329 b.i = i
330 return a.b.i
331 f1 = compile(fn, [int])
332 res = f1(42)
333 assert res == 42
334
335 def test_recursive_struct_2():
336 class L:
337 def __init__(self, target):
338 self.target = target
339 class RL(L):
340 pass
341 class SL(L):
342 pass
343 class B:
344 def __init__(self, exits):
345 self.exits = exits
346 def fn(i):
347 rl = RL(None)
348 b = B([rl])
349 sl = SL(b)
350 f1 = compile(fn, [int])
351 f1(42)
352
353 def test_infinite_float():
354 x = 1.0
355 while x != x / 2:
356 x *= 3.1416
357 def fn():
358 return x
359 f1 = compile(fn, [])
360 res = f1()
361 assert res > 0 and res == res / 2
362 def fn():
363 return -x
364 f1 = compile(fn, [])
365 res = f1()
366 assert res < 0 and res == res / 2
367 class Box:
368
369 def __init__(self, d):
370 self.d = d
371 b1 = Box(x)
372 b2 = Box(-x)
373 b3 = Box(1.5)
374
375 def f(i):
376 if i==0:
377 b = b1
378 elif i==1:
379 b = b2
380 else:
381 b = b3
382 return b.d
383
384 f1 = compile(f, [int])
385 res = f1(0)
386 assert res > 0 and res == res / 2
387 res = f1(1)
388 assert res < 0 and res == res / 2
389 res = f1(3)
390 assert res == 1.5
391
392 def test_infinite_float_in_array():
393 from rpython.rlib.rfloat import INFINITY, NAN
394 lst = [INFINITY, -INFINITY, NAN]
395 def fn(i):
396 return lst[i]
397 f1 = compile(fn, [int])
398 res = f1(0)
399 assert res == INFINITY
400 res = f1(1)
401 assert res == -INFINITY
402 res = f1(2)
403 assert math.isnan(res)
404
405 def test_nan_and_special_values():
406 from rpython.rlib.rfloat import isfinite
407 inf = 1e300 * 1e300
408 assert math.isinf(inf)
409 nan = inf/inf
410 assert math.isnan(nan)
411 values_and_checkers = [
412 (inf, lambda x: math.isinf(x) and x > 0.0),
413 (-inf, lambda x: math.isinf(x) and x < 0.0),
414 (nan, math.isnan),
415 (42.0, isfinite),
416 (0.0, lambda x: not x and math.copysign(1., x) == 1.),
417 (-0.0, lambda x: not x and math.copysign(1., x) == -1.),
418 ]
419 unrolling_values = unrolling_iterable(enumerate(values_and_checkers))
420 l = [[value] for value, _ in values_and_checkers]
421 l2 = [[(-value, -value), (value, value)] for value, _ in values_and_checkers]
422
423 def f(variant, index, x):
424 if variant == 0:
425 for i, (value, _) in unrolling_values:
426 if index == i:
427 return value
428 assert 0
429 if variant == 1:
430 return l[index][x]
431 if variant == 2:
432 return l2[index][x][1]
433 assert 0
434 f1 = compile(f, [int, int, int])
435
436 for index, (value, checker) in enumerate(values_and_checkers):
437 res = f1(0, index, -1)
438 assert checker(res)
439
440 res = f1(1, index, 0)
441 assert checker(res)
442
443 res = f1(2, index, 1)
444 assert checker(res)
445
446 def test_prebuilt_instance_with_dict():
447 class A:
448 pass
449 a = A()
450 a.d = {}
451 a.d['hey'] = 42
452 def t():
453 a.d['hey'] = 2
454 return a.d['hey']
455 f = compile(t, [])
456 assert f() == 2
457
458 def test_long_strings():
459 s1 = 'hello'
460 s2 = ''.join([chr(i) for i in range(256)])
461 s3 = 'abcd'*17
462 s4 = open(__file__, 'rb').read(2049)
463 choices = [s1, s2, s3, s4]
464 def f(i, j):
465 return choices[i][j]
466 f1 = compile(f, [int, int])
467 for i, s in enumerate(choices):
468 j = 0
469 while j < len(s):
470 c = s[j]
471 assert f1(i, j) == c
472 j += 1
473 if j > 100:
474 j += 10
475
476 def test_keepalive():
477 from rpython.rlib import objectmodel
478 def f():
479 x = [1]
480 y = ['b']
481 objectmodel.keepalive_until_here(x, y)
482 return 1
483
484 f1 = compile(f, [])
485 assert f1() == 1
486
487 def test_print():
488 def f():
489 for i in range(10):
490 print "xxx"
491
492 fn = compile(f, [])
493 fn()
494
495 def test_name():
496 def f():
497 return 3
498
499 f.c_name = 'pypy_xyz_f'
500 f.exported_symbol = True
501
502 t = Translation(f, [], backend="c")
503 t.annotate()
504 t.compile_c()
505 if py.test.config.option.view:
506 t.view()
507 assert hasattr(ctypes.CDLL(str(t.driver.c_entryp)), 'pypy_xyz_f')
508
509 def test_entrypoints():
510 def f():
511 return 3
512
513 key = "test_entrypoints42"
514 @entrypoint_highlevel(key, [int], "foobar")
515 def g(x):
516 return x + 42
517
518 t = Translation(f, [], backend="c", secondaryentrypoints="test_entrypoints42")
519 t.annotate()
520 t.compile_c()
521 if py.test.config.option.view:
522 t.view()
523 assert hasattr(ctypes.CDLL(str(t.driver.c_entryp)), 'foobar')
524
525 def test_exportstruct():
526 from rpython.translator.tool.cbuild import ExternalCompilationInfo
527 from rpython.rlib.exports import export_struct
528 def f():
529 return 42
530 FOO = Struct("FOO", ("field1", Signed))
531 foo = malloc(FOO, flavor="raw")
532 foo.field1 = 43
533 export_struct("BarStruct", foo._obj)
534 t = Translation(f, [], backend="c")
535 t.annotate()
536 t.compile_c()
537 if py.test.config.option.view:
538 t.view()
539 assert hasattr(ctypes.CDLL(str(t.driver.c_entryp)), 'BarStruct')
540 free(foo, flavor="raw")
541
542 def test_recursive_llhelper():
543 from rpython.rtyper.annlowlevel import llhelper
544 from rpython.rtyper.lltypesystem import lltype
545 from rpython.rlib.objectmodel import specialize
546 FT = lltype.ForwardReference()
547 FTPTR = lltype.Ptr(FT)
548 STRUCT = lltype.Struct("foo", ("bar", FTPTR))
549 FT.become(lltype.FuncType([lltype.Ptr(STRUCT)], lltype.Signed))
550
551 class A:
552 def __init__(self, func, name):
553 self.func = func
554 self.name = name
555 def _freeze_(self):
556 return True
557 @specialize.memo()
558 def make_func(self):
559 f = getattr(self, "_f", None)
560 if f is not None:
561 return f
562 f = lambda *args: self.func(*args)
563 f.c_name = self.name
564 f.relax_sig_check = True
565 f.__name__ = "WRAP%s" % (self.name, )
566 self._f = f
567 return f
568 def get_llhelper(self):
569 return llhelper(FTPTR, self.make_func())
570 def f(s):
571 if s.bar == t.bar:
572 lltype.free(s, flavor="raw")
573 return 1
574 lltype.free(s, flavor="raw")
575 return 0
576 def g(x):
577 return 42
578 def chooser(x):
579 s = lltype.malloc(STRUCT, flavor="raw")
580 if x:
581 s.bar = llhelper(FTPTR, a_f.make_func())
582 else:
583 s.bar = llhelper(FTPTR, a_g.make_func())
584 return f(s)
585 a_f = A(f, "f")
586 a_g = A(g, "g")
587 t = lltype.malloc(STRUCT, flavor="raw", immortal=True)
588 t.bar = llhelper(FTPTR, a_f.make_func())
589 fn = compile(chooser, [bool])
590 assert fn(True)
591
592 def test_ordered_dict():
593 expected = [('ea', 1), ('bb', 2), ('c', 3), ('d', 4), ('e', 5),
594 ('ef', 6)]
595 d = OrderedDict(expected)
596
597 def f():
598 assert d.items() == expected
599
600 fn = compile(f, [])
601 fn()
602
603 def test_inhibit_tail_call():
604 def foobar_fn(n):
605 return 42
606 foobar_fn._dont_inline_ = True
607 def main(n):
608 return foobar_fn(n)
609 #
610 t = Translation(main, [int], backend="c")
611 t.rtype()
612 t.context._graphof(foobar_fn).inhibit_tail_call = True
613 t.source_c()
614 lines = t.driver.cbuilder.c_source_filename.join('..',
615 'rpython_translator_c_test.c').readlines()
616 for i, line in enumerate(lines):
617 if '= pypy_g_foobar_fn' in line:
618 break
619 else:
620 assert 0, "the call was not found in the C source"
621 assert 'PYPY_INHIBIT_TAIL_CALL();' in lines[i+1]
622
623 def get_generated_c_source(fn, types):
624 """Return the generated C source for fn."""
625 t = Translation(fn, types, backend="c")
626 t.annotate()
627 merge_if_blocks(t.driver.translator.graphs[0])
628 c_filename_path = t.source_c()
629 return t.driver.cbuilder.c_source_filename.join('..',
630 'rpython_translator_c_test.c').read()
631
632 def test_generated_c_source_no_gotos():
633 # We want simple functions to have no indirection/goto.
634 # Instead, PyPy can inline blocks when they aren't reused.
635
636 def main(x):
637 return x + 1
638
639 c_src = get_generated_c_source(main, [int])
640 assert 'goto' not in c_src
641 assert not re.search(r'block\w*:(?! \(inlined\))', c_src)