1. Jeremy Thurgood
  2. pypy

Source

pypy / pypy / translator / c / test / test_genc.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import ctypes

import py

from pypy.rlib.entrypoint import entrypoint
from pypy.rlib.unroll import unrolling_iterable
from pypy.rlib.rarithmetic import r_longlong, r_ulonglong, intmask
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.lltypesystem.lltype import *
from pypy.rpython.lltypesystem.rstr import STR
from pypy.tool.nullpath import NullPyPathLocal
from pypy.translator.c import genc
from pypy.translator.interactive import Translation
from pypy.translator.translator import TranslationContext, graphof

def llrepr(v):
    if isinstance(v, r_ulonglong):
        return "%d:%d" % (intmask(v >> 32), intmask(v & 0xffffffff))
    elif isinstance(v, r_longlong):
        return "%d:%d" % (intmask(v >> 32), intmask(v & 0xffffffff))
    return str(v)

def parse_longlong(a):
    p0, p1 = a.split(":")
    return (r_longlong(int(p0)) << 32) + (r_longlong(int(p1)) & 0xffffffff)

def parse_ulonglong(a):
    p0, p1 = a.split(":")
    return (r_ulonglong(int(p0)) << 32) + (r_ulonglong(int(p1)) & 0xffffffff)

def compile(fn, argtypes, view=False, gcpolicy="none", backendopt=True,
            annotatorpolicy=None, thread=False):
    argtypes_unroll = unrolling_iterable(enumerate(argtypes))

    for argtype in argtypes:
        if argtype not in [int, float, str, bool, r_ulonglong, r_longlong]:
            raise Exception("Unsupported argtype, %r" % (argtype,))

    def entry_point(argv):
        args = ()
        for i, argtype in argtypes_unroll:
            a = argv[i + 1]
            if argtype is int:
                args += (int(a),)
            elif argtype is r_longlong:
                args += (parse_longlong(a),)
            elif argtype is r_ulonglong:
                args += (parse_ulonglong(a),)
            elif argtype is bool:
                if a == 'True':
                    args += (True,)
                else:
                    assert a == 'False'
                    args += (False,)
            elif argtype is float:
                args += (float(a),)
            else:
                args += (a,)
        res = fn(*args)
        print "THE RESULT IS:", res, ";"
        return 0

    t = Translation(entry_point, None, gc=gcpolicy, backend="c",
                    policy=annotatorpolicy, thread=thread)
    if not backendopt:
        t.disable(["backendopt_lltype"])
    t.annotate()
    t.compile_c()
    ll_res = graphof(t.context, fn).getreturnvar().concretetype
    try:
        if py.test.config.option.view:
            t.view()
    except AttributeError:
        pass
    def f(*args):
        assert len(args) == len(argtypes)
        for arg, argtype in zip(args, argtypes):
            assert isinstance(arg, argtype)
        stdout = t.driver.cbuilder.cmdexec(" ".join([llrepr(arg) for arg in args]))
        assert stdout.endswith(' ;\n')
        pos = stdout.rindex('THE RESULT IS: ')
        res = stdout[pos + len('THE RESULT IS: '):-3]
        if ll_res in [lltype.Signed, lltype.Unsigned, lltype.SignedLongLong,
                      lltype.UnsignedLongLong]:
            return int(res)
        elif ll_res == lltype.Bool:
            return bool(int(res))
        elif ll_res == lltype.Char:
            assert len(res) == 1
            return res
        elif ll_res == lltype.Float:
            return float(res)
        elif ll_res == lltype.Ptr(STR):
            return res
        elif ll_res == lltype.Void:
            return None
        raise NotImplementedError("parsing %s" % (ll_res,))
    f.__name__ = fn.__name__
    return f


def test_simple():
    def f(x):
        return x * 2

    f1 = compile(f, [int])

    assert f1(5) == 10
    assert f1(-123) == -246

    py.test.raises(Exception, f1, "world")  # check that it's really typed


def test_dont_write_source_files():
    def f(x):
        return x*2
    t = TranslationContext()
    t.buildannotator().build_types(f, [int])
    t.buildrtyper().specialize()

    t.config.translation.countmallocs = True
    t.config.translation.dont_write_c_files = True
    builder = genc.CStandaloneBuilder(t, f, config=t.config)
    builder.generate_source()
    assert isinstance(builder.targetdir, NullPyPathLocal)
    for f in builder.targetdir.listdir():
        assert not str(f).endswith('.c')


def test_rlist():
    def f(x):
        l = [x]
        l.append(x+1)
        return l[0] * l[-1]
    f1 = compile(f, [int])
    assert f1(5) == 30
    #assert f1(x=5) == 30


def test_rptr():
    S = GcStruct('testing', ('x', Signed), ('y', Signed))
    def f(i):
        if i < 0:
            p = nullptr(S)
        else:
            p = malloc(S)
            p.x = i*2
        if i > 0:
            return p.x
        else:
            return -42
    f1 = compile(f, [int])
    assert f1(5) == 10
    #assert f1(i=5) == 10
    assert f1(1) == 2
    assert f1(0) == -42
    assert f1(-1) == -42
    assert f1(-5) == -42


def test_empty_string():
    A = Array(Char, hints={'nolength': True})
    p = malloc(A, 1, immortal=True)
    def f():
        return p[0]
    f1 = compile(f, [])
    assert f1() == '\x00'


def test_rstr():
    def fn(i):
        return "hello"[i]
    f1 = compile(fn, [int])
    res = f1(1)
    assert res == 'e'


def test_recursive_struct():
    # B has an A as its super field, and A has a pointer to B.
    class A:
        pass
    class B(A):
        pass
    def fn(i):
        a = A()
        b = B()
        a.b = b
        b.i = i
        return a.b.i
    f1 = compile(fn, [int])
    res = f1(42)
    assert res == 42

def test_recursive_struct_2():
    class L:
        def __init__(self, target):
            self.target = target
    class RL(L):
        pass
    class SL(L):
        pass
    class B:
        def __init__(self, exits):
            self.exits = exits
    def fn(i):
        rl = RL(None)
        b = B([rl])
        sl = SL(b)
    f1 = compile(fn, [int])
    f1(42)

def test_infinite_float():
    x = 1.0
    while x != x / 2:
        x *= 3.1416
    def fn():
        return x
    f1 = compile(fn, [])
    res = f1()
    assert res > 0 and res == res / 2
    def fn():
        return -x
    f1 = compile(fn, [])
    res = f1()
    assert res < 0 and res == res / 2
    class Box:

        def __init__(self, d):
            self.d = d
    b1 = Box(x)
    b2 = Box(-x)
    b3 = Box(1.5)

    def f(i):
        if i==0:
            b = b1
        elif i==1:
            b = b2
        else:
            b = b3
        return b.d

    f1 = compile(f, [int])
    res = f1(0)
    assert res > 0 and res == res / 2
    res = f1(1)
    assert res < 0 and res == res / 2
    res = f1(3)
    assert res == 1.5

def test_nan_and_special_values():
    from pypy.rlib.rfloat import isnan, isinf, isfinite, copysign
    inf = 1e300 * 1e300
    assert isinf(inf)
    nan = inf/inf
    assert isnan(nan)

    for value, checker in [
            (inf,   lambda x: isinf(x) and x > 0.0),
            (-inf,  lambda x: isinf(x) and x < 0.0),
            (nan,   isnan),
            (42.0,  isfinite),
            (0.0,   lambda x: not x and copysign(1., x) == 1.),
            (-0.0,  lambda x: not x and copysign(1., x) == -1.),
            ]:
        def f():
            return value
        f1 = compile(f, [])
        res = f1()
        assert checker(res)

        l = [value]
        def g(x):
            return l[x]
        g2 = compile(g, [int])
        res = g2(0)
        assert checker(res)

        l2 = [(-value, -value), (value, value)]
        def h(x):
            return l2[x][1]
        h3 = compile(h, [int])
        res = h3(1)
        assert checker(res)

def test_prebuilt_instance_with_dict():
    class A:
        pass
    a = A()
    a.d = {}
    a.d['hey'] = 42
    def t():
        a.d['hey'] = 2
        return a.d['hey']
    f = compile(t, [])
    assert f() == 2

def test_long_strings():
    s1 = 'hello'
    s2 = ''.join([chr(i) for i in range(256)])
    s3 = 'abcd'*17
    s4 = open(__file__, 'rb').read(2049)
    choices = [s1, s2, s3, s4]
    def f(i, j):
        return choices[i][j]
    f1 = compile(f, [int, int])
    for i, s in enumerate(choices):
        j = 0
        while j < len(s):
            c = s[j]
            assert f1(i, j) == c
            j += 1
            if j > 100:
                j += 10

def test_keepalive():
    from pypy.rlib import objectmodel
    def f():
        x = [1]
        y = ['b']
        objectmodel.keepalive_until_here(x, y)
        return 1

    f1 = compile(f, [])
    assert f1() == 1

def test_print():
    def f():
        for i in range(10):
            print "xxx"

    fn = compile(f, [])
    fn()

def test_name():
    def f():
        return 3

    f.c_name = 'pypy_xyz_f'

    t = Translation(f, [], backend="c")
    t.annotate()
    t.compile_c()
    if py.test.config.option.view:
        t.view()
    assert hasattr(ctypes.CDLL(str(t.driver.c_entryp)), 'pypy_xyz_f')

def test_entrypoints():
    def f():
        return 3

    key = "test_entrypoints42"
    @entrypoint(key, [int], "foobar")
    def g(x):
        return x + 42

    t = Translation(f, [], backend="c", secondaryentrypoints="test_entrypoints42")
    t.annotate()
    t.compile_c()
    if py.test.config.option.view:
        t.view()
    assert hasattr(ctypes.CDLL(str(t.driver.c_entryp)), 'foobar')

def test_exportstruct():
    from pypy.rlib.exports import export_struct
    def f():
        return 42
    FOO = Struct("FOO", ("field1", Signed))
    foo = malloc(FOO, flavor="raw")
    foo.field1 = 43
    export_struct("BarStruct", foo._obj)
    t = Translation(f, [], backend="c")
    t.annotate()
    t.compile_c()
    if py.test.config.option.view:
        t.view()
    assert hasattr(ctypes.CDLL(str(t.driver.c_entryp)), 'BarStruct')
    free(foo, flavor="raw")

def test_recursive_llhelper():
    from pypy.rpython.annlowlevel import llhelper
    from pypy.rpython.lltypesystem import lltype
    from pypy.rlib.objectmodel import specialize
    FT = lltype.ForwardReference()
    FTPTR = lltype.Ptr(FT)
    STRUCT = lltype.Struct("foo", ("bar", FTPTR))
    FT.become(lltype.FuncType([lltype.Ptr(STRUCT)], lltype.Signed))

    class A:
        def __init__(self, func, name):
            self.func = func
            self.name = name
        def _freeze_(self):
            return True
        @specialize.memo()
        def make_func(self):
            f = getattr(self, "_f", None)
            if f is not None:
                return f
            f = lambda *args: self.func(*args)
            f.c_name = self.name
            f.relax_sig_check = True
            f.__name__ = "WRAP%s" % (self.name, )
            self._f = f
            return f
        def get_llhelper(self):
            return llhelper(FTPTR, self.make_func())
    def f(s):
        if s.bar == t.bar:
            lltype.free(s, flavor="raw")
            return 1
        lltype.free(s, flavor="raw")
        return 0
    def g(x):
        return 42
    def chooser(x):
        s = lltype.malloc(STRUCT, flavor="raw")
        if x:
            s.bar = llhelper(FTPTR, a_f.make_func())
        else:
            s.bar = llhelper(FTPTR, a_g.make_func())
        return f(s)
    a_f = A(f, "f")
    a_g = A(g, "g")
    t = lltype.malloc(STRUCT, flavor="raw", immortal=True)
    t.bar = llhelper(FTPTR, a_f.make_func())
    fn = compile(chooser, [bool])
    assert fn(True)

def test_inhibit_tail_call():
    def foobar_fn(n):
        return 42
    foobar_fn._dont_inline_ = True
    def main(n):
        return foobar_fn(n)
    #
    t = Translation(main, [int], backend="c")
    t.rtype()
    t.context._graphof(foobar_fn).inhibit_tail_call = True
    t.source_c()
    lines = t.driver.cbuilder.c_source_filename.join('..',
                              'pypy_translator_c_test_test_genc.c').readlines()
    for i, line in enumerate(lines):
        if '= pypy_g_foobar_fn' in line:
            break
    else:
        assert 0, "the call was not found in the C source"
    assert 'PYPY_INHIBIT_TAIL_CALL();' in lines[i+1]