pypy-stm-logging / pypy / rpython / lltypesystem / test / test_lltype.py

The branch 'sepcomp' does not exist.
  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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
from pypy.rpython.lltypesystem.lltype import *

def isweak(p, T):
    try:
        typeOf(p)
    except TypeError:
        return True
    return False

def test_basics():
    S0 = GcStruct("s0", ('a', Signed), ('b', Signed))
    assert S0.a == Signed
    assert S0.b == Signed
    s0 = malloc(S0)
    print s0
    assert typeOf(s0) == Ptr(S0)
    py.test.raises(UninitializedMemoryAccess, "s0.a")
    s0.a = 1
    s0.b = s0.a
    assert s0.a == 1
    assert s0.b == 1
    assert typeOf(s0.a) == Signed
    # simple array
    Ar = GcArray(('v', Signed))
    x = malloc(Ar,0)
    print x
    assert len(x) == 0
    x = malloc(Ar,3)
    print x
    assert typeOf(x) == Ptr(Ar)
    assert isweak(x[0], Ar.OF)
    x[0].v = 1
    x[1].v = 2
    x[2].v = 3
    assert typeOf(x[0].v) == Signed
    assert [x[z].v for z in range(3)] == [1, 2, 3]
    #
    def define_list(T):
        List_typ = GcStruct("list",
                ("items", Ptr(GcArray(('item',T)))))
        def newlist():
            l = malloc(List_typ)
            items = malloc(List_typ.items.TO, 0)
            l.items = items
            return l

        def append(l, newitem):
            length = len(l.items)
            newitems = malloc(List_typ.items.TO, length+1)
            i = 0
            while i<length:
              newitems[i].item = l.items[i].item
              i += 1
            newitems[length].item = newitem
            l.items = newitems

        def item(l, i):
            return l.items[i].item

        return List_typ, newlist, append, item

    List_typ, inewlist, iappend, iitem = define_list(Signed)

    l = inewlist()
    assert typeOf(l) == Ptr(List_typ)
    iappend(l, 2)
    iappend(l, 3)
    assert len(l.items) == 2
    assert iitem(l, 0) == 2
    assert iitem(l, 1) == 3

    IWrap = GcStruct("iwrap", ('v', Signed))
    List_typ, iwnewlist, iwappend, iwitem = define_list(Ptr(IWrap))

    l = iwnewlist()
    assert typeOf(l) == Ptr(List_typ)
    iw2 = malloc(IWrap)
    iw3 = malloc(IWrap)
    iw2.v = 2
    iw3.v = 3
    assert iw3.v == 3
    iwappend(l, iw2)
    iwappend(l, iw3)
    assert len(l.items) == 2
    assert iwitem(l, 0).v == 2
    assert iwitem(l, 1).v == 3

    # not allowed
    S = Struct("s", ('v', Signed))
    List_typ, iwnewlistzzz, iwappendzzz, iwitemzzz = define_list(S) # works but
    l = iwnewlistzzz()
    S1 = GcStruct("strange", ('s', S))
    py.test.raises(TypeError, "iwappendzzz(l, malloc(S1).s)")

def test_varsizestruct():
    S1 = GcStruct("s1", ('a', Signed), ('rest', Array(('v', Signed))))
    py.test.raises(TypeError, "malloc(S1)")
    s1 = malloc(S1, 4)
    s1.a = 0
    assert s1.a == 0
    assert isweak(s1.rest, S1.rest)
    assert len(s1.rest) == 4
    assert isweak(s1.rest[0], S1.rest.OF)
    s1.rest[0].v = 0
    assert typeOf(s1.rest[0].v) == Signed
    assert s1.rest[0].v == 0
    py.test.raises(IndexError, "s1.rest[4]")
    py.test.raises(IndexError, "s1.rest[-1]")

    s1.a = 17
    s1.rest[3].v = 5
    assert s1.a == 17
    assert s1.rest[3].v == 5

    py.test.raises(TypeError, "Struct('invalid', ('rest', Array(('v', Signed))), ('a', Signed))")
    py.test.raises(TypeError, "Struct('invalid', ('rest', GcArray(('v', Signed))), ('a', Signed))")
    py.test.raises(TypeError, "Struct('invalid', ('x', Struct('s1', ('a', Signed), ('rest', Array(('v', Signed))))))")
    py.test.raises(TypeError, "Struct('invalid', ('x', S1))")

def test_substructure_ptr():
    S3 = Struct("s3", ('a', Signed))
    S2 = Struct("s2", ('s3', S3))
    S1 = GcStruct("s1", ('sub1', S2), ('sub2', S2))
    p1 = malloc(S1)
    assert isweak(p1.sub1, S2)
    assert isweak(p1.sub2, S2)
    assert isweak(p1.sub1.s3, S3)
    p2 = p1.sub1
    assert isweak(p2.s3, S3)

def test_gc_substructure_ptr():
    S1 = GcStruct("s2", ('a', Signed))
    S2 = Struct("s3", ('a', Signed))
    S0 = GcStruct("s1", ('sub1', S1), ('sub2', S2))
    p1 = malloc(S0)
    assert typeOf(p1.sub1) == Ptr(S1)
    assert isweak(p1.sub2, S2)

def test_cast_simple_widening():
    S2 = Struct("s2", ('a', Signed))
    S1 = Struct("s1", ('sub1', S2), ('sub2', S2))
    p1 = malloc(S1, immortal=True)
    p2 = p1.sub1
    p3 = p2
    assert typeOf(p3) == Ptr(S2)
    p4 = cast_pointer(Ptr(S1), p3)
    assert typeOf(p4) == Ptr(S1)
    assert p4 == p1
    py.test.raises(TypeError, "cast_pointer(Ptr(S1), p1.sub2)")
    SUnrelated = Struct("unrelated")
    py.test.raises(TypeError, "cast_pointer(Ptr(SUnrelated), p3)")
    S1bis = Struct("s1b", ('sub1', S2))
    p1b = malloc(S1bis, immortal=True)
    p2 = p1b.sub1
    py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p2)")

def test_cast_simple_widening2():
    S2 = GcStruct("s2", ('a', Signed))
    S1 = GcStruct("s1", ('sub1', S2))
    p1 = malloc(S1)
    p2 = p1.sub1
    assert typeOf(p2) == Ptr(S2)
    p3 = cast_pointer(Ptr(S1), p2)
    assert p3 == p1
    p2 = malloc(S2)
    py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p2)")

def test_cast_pointer():
    S3 = GcStruct("s3", ('a', Signed))
    S2 = GcStruct("s3", ('sub', S3))
    S1 = GcStruct("s1", ('sub', S2))
    p1 = malloc(S1)
    p2 = p1.sub
    p3 = p2.sub
    assert typeOf(p3) == Ptr(S3)
    assert typeOf(p2) == Ptr(S2)
    p12 = cast_pointer(Ptr(S1), p2)
    assert p12 == p1
    p13 = cast_pointer(Ptr(S1), p3)
    assert p13 == p1
    p21 = cast_pointer(Ptr(S2), p1)
    assert p21 == p2
    p23 = cast_pointer(Ptr(S2), p3)
    assert p23 == p2
    p31 = cast_pointer(Ptr(S3), p1)
    assert p31 == p3
    p32 = cast_pointer(Ptr(S3), p2)
    assert p32 == p3
    p3 = malloc(S3)
    p2 = malloc(S2)
    py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p3)")
    py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p2)")
    py.test.raises(RuntimeError, "cast_pointer(Ptr(S2), p3)")
    S0 = GcStruct("s0", ('sub', S1))
    p0 = malloc(S0)
    assert p0 == cast_pointer(Ptr(S0), p0)
    p3 = cast_pointer(Ptr(S3), p0)
    p03 = cast_pointer(Ptr(S0), p3)
    assert p0 == p03
    S1bis = GcStruct("s1b", ('sub', S2))
    assert S1bis != S1
    p1b = malloc(S1bis)
    p3 = p1b.sub.sub
    assert typeOf(p3) == Ptr(S3)
    assert p1b == cast_pointer(Ptr(S1bis), p3)
    py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p3)")

def test_best_effort_gced_parent_detection():
    py.test.skip("test not relevant any more")
    S2 = Struct("s2", ('a', Signed))
    S1 = GcStruct("s1", ('sub1', S2), ('sub2', S2), ('tail', Array(('e', Signed))))
    p1 = malloc(S1, 1)
    p2 = p1.sub2
    p3 = p1.tail
    p3[0].e = 1
    assert p3[0].e == 1
    del p1
    import gc
    gc.collect()
    py.test.raises(RuntimeError, "p2.a")
    py.test.raises(RuntimeError, "p3[0]")

def test_best_effort_gced_parent_for_arrays():
    py.test.skip("test not relevant any more")
    A1 = GcArray(('v', Signed))
    p1 = malloc(A1, 10)
    p1[5].v=3
    assert p1[5].v == 3
    p1_5 = p1[5]
    del p1
    import gc
    gc.collect()
    py.test.raises(RuntimeError, "p1_5.v")        

def test_examples():
    A1 = GcArray(('v', Signed))
    S = GcStruct("s", ('v', Signed))
    St = GcStruct("st", ('v', Signed),('trail', Array(('v', Signed))))

    PA1 = Ptr(A1)
    PS = Ptr(S)
    PSt = Ptr(St)

    ex_pa1 = PA1._example()
    ex_ps  = PS._example()
    ex_pst = PSt._example()

    assert typeOf(ex_pa1) == PA1
    assert typeOf(ex_ps) == PS
    assert typeOf(ex_pst) == PSt

    assert ex_pa1[0].v == 0
    assert ex_ps.v == 0
    assert ex_pst.v == 0
    assert ex_pst.trail[0].v == 0

def test_functions():
    F = FuncType((Signed,), Signed)
    py.test.raises(TypeError, "Struct('x', ('x', F))")

    PF = Ptr(F)
    pf = PF._example()
    assert pf(0) == 0
    py.test.raises(TypeError, pf, 0, 0)
    py.test.raises(TypeError, pf, 'a')

def test_truargs():
    F = FuncType((Void, Signed, Void, Unsigned), Float)
    assert Void not in F._trueargs()

def test_inconsistent_gc_containers():
    A = GcArray(('y', Signed))
    S = GcStruct('b', ('y', Signed))
    py.test.raises(TypeError, "Struct('a', ('x', S))")
    py.test.raises(TypeError, "GcStruct('a', ('x', Signed), ('y', S))")
    py.test.raises(TypeError, "Array(('x', S))")
    py.test.raises(TypeError, "GcArray(('x', S))")
    py.test.raises(TypeError, "Struct('a', ('x', A))")
    py.test.raises(TypeError, "GcStruct('a', ('x', A))")

def test_forward_reference():
    F = GcForwardReference()
    S = GcStruct('abc', ('x', Ptr(F)))
    F.become(S)
    assert S.x == Ptr(S)
    py.test.raises(TypeError, "GcForwardReference().become(Struct('abc'))")
    ForwardReference().become(Struct('abc'))
    hash(S)

def test_nullptr():
    S = Struct('s')
    p0 = nullptr(S)
    assert not p0
    assert typeOf(p0) == Ptr(S)


def test_nullptr_cast():
    S = Struct('s')
    p0 = nullptr(S)
    assert not p0
    S1 = Struct("s1", ('s', S))
    p10 = cast_pointer(Ptr(S1), p0)
    assert typeOf(p10) == Ptr(S1)
    assert not p10

def test_nullptr_opaque_cast():
    S = Struct('S')
    p0 = nullptr(S)
    O1 = OpaqueType('O1')
    O2 = OpaqueType('O2')
    p1 = cast_opaque_ptr(Ptr(O1), p0)
    assert not p1
    p2 = cast_opaque_ptr(Ptr(O2), p1)
    assert not p2
    p3 = cast_opaque_ptr(Ptr(S), p2)
    assert not p3


def test_hash():
    S = ForwardReference()
    S.become(Struct('S', ('p', Ptr(S))))
    assert S == S
    hash(S)   # assert no crash, and force the __cached_hash computation
    S1 = Struct('S', ('p', Ptr(S)))
    assert S1 == S
    assert S == S1
    assert hash(S1) == hash(S)


def test_pickle():
    S = ForwardReference()
    S.become(Struct('S', ('p', Ptr(S))))
    assert S == S
    hash(S)
    from pickle import dumps, loads
    S_pickle = dumps(S)
    S_loaded = loads(S_pickle)
    assert S_loaded == S
    assert hash(S_loaded) == hash(S)


def test_array_with_non_container_elements():
    As = GcArray(Signed)
    a = malloc(As, 3)
    assert typeOf(a) == Ptr(As)
    py.test.raises(UninitializedMemoryAccess, "a[0]")
    a[1] = 3
    assert a[1] == 3
    S = GcStruct('s', ('x', Signed))
    s = malloc(S)
    py.test.raises(TypeError, "a[1] = s")
    S = GcStruct('s', ('x', Signed))
    py.test.raises(TypeError, "Array(S)")
    py.test.raises(TypeError, "Array(As)")
    S = Struct('s', ('x', Signed))
    A = GcArray(S)
    a = malloc(A, 2)
    s = S._container_example() # should not happen anyway
    py.test.raises(TypeError, "a[0] = s")
    S = Struct('s', ('last', Array(S)))
    py.test.raises(TypeError, "Array(S)")

def test_immortal_parent():
    S1 = GcStruct('substruct', ('x', Signed))
    S  = GcStruct('parentstruct', ('s1', S1))
    p = malloc(S, immortal=True)
    p1 = p.s1
    p1.x = 5
    del p
    p = cast_pointer(Ptr(S), p1)
    assert p.s1.x == 5

def test_getRuntimeTypeInfo():
    S = GcStruct('s', ('x', Signed))
    py.test.raises(ValueError, "getRuntimeTypeInfo(S)")
    pinf0 = attachRuntimeTypeInfo(S)
    assert pinf0._obj.about == S
    pinf = getRuntimeTypeInfo(S)
    assert pinf == pinf0
    pinf1 = getRuntimeTypeInfo(S)
    assert pinf == pinf1
    Z = GcStruct('z', ('x', Unsigned))
    attachRuntimeTypeInfo(Z)
    assert getRuntimeTypeInfo(Z) != pinf0
    Sbis = GcStruct('s', ('x', Signed))
    attachRuntimeTypeInfo(Sbis)
    assert getRuntimeTypeInfo(Sbis) != pinf0
    assert Sbis != S # the attached runtime type info distinguishes them

def test_getRuntimeTypeInfo_destrpointer():
    S = GcStruct('s', ('x', Signed))
    def f(s):
        s.x = 1
    def type_info_S(p):
        return getRuntimeTypeInfo(S)
    qp = functionptr(FuncType([Ptr(S)], Ptr(RuntimeTypeInfo)), 
                     "type_info_S", 
                     _callable=type_info_S)
    dp = functionptr(FuncType([Ptr(S)], Void), 
                     "destructor_funcptr", 
                     _callable=f)
    pinf0 = attachRuntimeTypeInfo(S, qp, destrptr=dp)
    assert pinf0._obj.about == S
    pinf = getRuntimeTypeInfo(S)
    assert pinf == pinf0
    pinf1 = getRuntimeTypeInfo(S)
    assert pinf == pinf1
    assert pinf._obj.destructor_funcptr == dp
    assert pinf._obj.query_funcptr == qp

def test_runtime_type_info():
    S = GcStruct('s', ('x', Signed))
    attachRuntimeTypeInfo(S)
    s = malloc(S)
    s.x = 0
    assert runtime_type_info(s) == getRuntimeTypeInfo(S)
    S1 = GcStruct('s1', ('sub', S), ('x', Signed))
    attachRuntimeTypeInfo(S1)
    s1 = malloc(S1)
    s1.sub.x = 0
    s1.x = 0
    assert runtime_type_info(s1) == getRuntimeTypeInfo(S1)
    assert runtime_type_info(s1.sub) == getRuntimeTypeInfo(S1)
    assert runtime_type_info(cast_pointer(Ptr(S), s1)) == getRuntimeTypeInfo(S1)
    def dynamic_type_info_S(p):
        if p.x == 0:
            return getRuntimeTypeInfo(S)
        else:
            return getRuntimeTypeInfo(S1)
    fp = functionptr(FuncType([Ptr(S)], Ptr(RuntimeTypeInfo)), 
                     "dynamic_type_info_S", 
                     _callable=dynamic_type_info_S)
    attachRuntimeTypeInfo(S, fp)
    assert s.x == 0
    assert runtime_type_info(s) == getRuntimeTypeInfo(S)
    s.x = 1
    py.test.raises(RuntimeError, "runtime_type_info(s)")
    assert s1.sub.x == 0
    py.test.raises(RuntimeError, "runtime_type_info(s1.sub)")
    s1.sub.x = 1
    assert runtime_type_info(s1.sub) == getRuntimeTypeInfo(S1)
    
def test_flavor_malloc():
    def isweak(p, T):
        return p._weak and typeOf(p).TO == T
    S = Struct('s', ('x', Signed))
    py.test.raises(TypeError, malloc, S)
    p = malloc(S, flavor="raw")
    assert typeOf(p).TO == S
    assert not isweak(p, S)
    p.x = 2
    free(p, flavor="raw")
    py.test.raises(RuntimeError, "p.x")
    T = GcStruct('T', ('y', Signed))
    p = malloc(T, flavor="gc")
    assert typeOf(p).TO == T
    assert not isweak(p, T)
    
def test_opaque():
    O = OpaqueType('O')
    p1 = opaqueptr(O, 'p1', hello="world")
    assert typeOf(p1) == Ptr(O)
    assert p1._obj.hello == "world"
    assert parentlink(p1._obj) == (None, None)
    S = GcStruct('S', ('stuff', O))
    p2 = malloc(S)
    assert typeOf(p2) == Ptr(S)
    assert typeOf(p2.stuff) == Ptr(O)
    assert parentlink(p2.stuff._obj) == (p2._obj, 'stuff')

def test_cast_opaque_ptr():
    O = GcOpaqueType('O')
    Q = GcOpaqueType('Q')
    S = GcStruct('S', ('x', Signed))
    s = malloc(S)
    o = cast_opaque_ptr(Ptr(O), s)
    assert typeOf(o).TO == O
    q = cast_opaque_ptr(Ptr(Q), o)
    assert typeOf(q).TO == Q
    p = cast_opaque_ptr(Ptr(S), q)
    assert typeOf(p).TO == S
    assert p == s
    O1 = OpaqueType('O')
    S1 = Struct('S1', ('x', Signed))
    s1 = malloc(S1, immortal=True)
    o1 = cast_opaque_ptr(Ptr(O1), s1)
    assert typeOf(o1).TO == O1
    p1 = cast_opaque_ptr(Ptr(S1), o1)
    assert typeOf(p1).TO == S1
    assert p1 == s1
    py.test.raises(TypeError, "cast_opaque_ptr(Ptr(S), o1)")
    py.test.raises(TypeError, "cast_opaque_ptr(Ptr(O1), s)")
    S2 = Struct('S2', ('z', Signed))
    py.test.raises(InvalidCast, "cast_opaque_ptr(Ptr(S2), o1)")

    BIG = GcStruct('BIG', ('s', S))
    UNRELATED = GcStruct('UNRELATED')
    big = malloc(BIG)
    unrelated = malloc(UNRELATED)
    p1 = cast_opaque_ptr(Ptr(O), big)
    p2 = cast_opaque_ptr(Ptr(O), big)
    assert p1 == p2
    p3 = cast_opaque_ptr(Ptr(O), big.s)
    assert p1 == p3
    p4 = cast_opaque_ptr(Ptr(O), unrelated)
    assert p1 != p4
    assert p3 != p4

def test_is_atomic():
    U = Struct('inlined', ('z', Signed))
    A = Ptr(RuntimeTypeInfo)
    P = Ptr(GcStruct('p'))
    Q = GcStruct('q', ('i', Signed), ('u', U), ('p', P))
    O = OpaqueType('O')
    F = GcForwardReference()
    assert A._is_atomic() is True
    assert P._is_atomic() is False
    assert Q.i._is_atomic() is True
    assert Q.u._is_atomic() is True
    assert Q.p._is_atomic() is False
    assert Q._is_atomic() is False
    assert O._is_atomic() is False
    assert F._is_atomic() is False

def test_adtmeths():
    def h_newstruct():
        return malloc(S)
    
    S = GcStruct('s', ('x', Signed), 
                 adtmeths={"h_newstruct": h_newstruct})

    s = S.h_newstruct()

    assert typeOf(s) == Ptr(S)

    def h_alloc(n):
        return malloc(A, n)

    def h_length(a):
        return len(a)

    A = GcArray(Signed,
                adtmeths={"h_alloc": h_alloc,
                          "h_length": h_length})

    a = A.h_alloc(10)

    assert typeOf(a) == Ptr(A)
    assert len(a) == 10

    assert a.h_length() == 10

def test_adt_typemethod():
    def h_newstruct(S):
        return malloc(S)
    h_newstruct = typeMethod(h_newstruct)
    
    S = GcStruct('s', ('x', Signed), 
                 adtmeths={"h_newstruct": h_newstruct})

    s = S.h_newstruct()

    assert typeOf(s) == Ptr(S)

    Sprime = GcStruct('s', ('x', Signed), 
                      adtmeths={"h_newstruct": h_newstruct})

    assert S == Sprime

def test_cast_primitive():
    cases = [
        (Float, 1, 1.0),
        (Float, r_singlefloat(2.1), float(r_singlefloat(2.1))),
        (Signed, 1.0, 1),
        (Unsigned, 1.0, 1),
        (Signed, r_uint(-1), -1),
        (Unsigned, -1, r_uint(-1)),
        (Char, ord('a'), 'a'),
        (Char, False,  chr(0)),
        (Signed, 'x', ord('x')),
        (Unsigned, u"x", ord(u'x')),
    ]
    for TGT, orig_val, expect in cases:
         res = cast_primitive(TGT, orig_val)
         assert typeOf(res) == TGT
         assert res == expect
    res = cast_primitive(SingleFloat, 2.1)
    assert isinstance(res, r_singlefloat)
    assert float(res) == float(r_singlefloat(2.1))

def test_cast_identical_array_ptr_types():
    A = GcArray(Signed)
    PA = Ptr(A)
    a = malloc(A, 2)
    assert cast_pointer(PA, a) == a
        
def test_array_with_no_length():
    A = GcArray(Signed, hints={'nolength': True})
    a = malloc(A, 10)
    py.test.raises(TypeError, len, a)

def test_dissect_ll_instance():
    assert list(dissect_ll_instance(1)) == [(Signed, 1)]
    GcS = GcStruct("S", ('x', Signed))
    s = malloc(GcS)
    s.x = 1
    assert list(dissect_ll_instance(s)) == [(Ptr(GcS), s), (GcS, s._obj), (Signed, 1)]
    
    A = GcArray(('x', Signed))
    a = malloc(A, 10)
    for i in range(10):
        a[i].x = i
    expected = [(Ptr(A), a), (A, a._obj)]
    for t in [((A.OF, a._obj.items[i]), (Signed, i)) for i in range(10)]:
        expected.extend(t)
    assert list(dissect_ll_instance(a)) == expected

    R = GcStruct("R", ('r', Ptr(GcForwardReference())))
    R.r.TO.become(R)

    r = malloc(R)
    r.r = r
    r_expected = [(Ptr(R), r), (R, r._obj)]
    assert list(dissect_ll_instance(r)) == r_expected

    B = GcArray(Ptr(R))
    b = malloc(B, 2)
    b[0] = b[1] = r
    b_expected = [(Ptr(B), b), (B, b._obj)]
    assert list(dissect_ll_instance(b)) == b_expected + r_expected

    memo = {}
    assert list(dissect_ll_instance(r, None, memo)) == r_expected
    assert list(dissect_ll_instance(b, None, memo)) == b_expected

def test_fixedsizearray():
    A = FixedSizeArray(Signed, 5)
    assert A.OF == Signed
    assert A.length == 5
    assert A.item0 == A.item1 == A.item2 == A.item3 == A.item4 == Signed
    assert A._names == ('item0', 'item1', 'item2', 'item3', 'item4')
    a = malloc(A, immortal=True)
    a[0] = 5
    a[4] = 83
    assert a[0] == 5
    assert a[4] == 83
    assert a.item4 == 83
    py.test.raises(IndexError, "a[5] = 183")
    py.test.raises(IndexError, "a[-1]")
    assert len(a) == 5

    S = GcStruct('S', ('n1', Signed),
                      ('a', A),
                      ('n2', Signed))
    s = malloc(S)
    s.a[3] = 17
    assert s.a[3] == 17
    assert len(s.a) == 5
    py.test.raises(TypeError, "s.a = a")

def test_direct_arrayitems():
    for a in [malloc(GcArray(Signed), 5),
              malloc(FixedSizeArray(Signed, 5), immortal=True)]:
        a[0] = 0
        a[1] = 10
        a[2] = 20
        a[3] = 30
        a[4] = 40
        b0 = direct_arrayitems(a)
        b1 = direct_ptradd(b0, 1)
        b2 = direct_ptradd(b1, 1)
        b3 = direct_ptradd(b0, 3)
        assert b0[0] == 0
        assert b0[1] == 10
        assert b0[4] == 40
        assert b1[0] == 10
        assert b1[1] == 20
        assert b2[0] == 20
        assert b2[1] == 30
        assert b3[-2] == 10
        assert b3[0] == 30
        assert b3[1] == 40
        assert b2[-2] == 0
        assert b1[3] == 40
        b2[0] = 23
        assert a[2] == 23
        b1[1] += 1
        assert a[2] == 24
        py.test.raises(IndexError, "b0[-1]")
        py.test.raises(IndexError, "b3[2]")
        py.test.raises(IndexError, "b1[4]")

def test_direct_fieldptr():
    S = GcStruct('S', ('x', Signed), ('y', Signed))
    s = malloc(S)
    a = direct_fieldptr(s, 'y')
    a[0] = 34
    assert s.y == 34
    py.test.raises(IndexError, "a[1]")

def test_odd_ints():
    T = GcStruct('T')
    S = GcStruct('S', ('t', T))
    s = cast_int_to_ptr(Ptr(S), 21)
    assert typeOf(s) == Ptr(S)
    assert cast_ptr_to_int(s) == 21
    t = cast_pointer(Ptr(T), s)
    assert typeOf(t) == Ptr(T)
    assert cast_ptr_to_int(t) == 21
    assert s == cast_pointer(Ptr(S), t)

def test_str_of_dead_ptr():
    S = Struct('S', ('x', Signed))
    T = GcStruct('T', ('s', S))
    t = malloc(T)
    s = t.s
    del t
    import gc
    gc.collect()
    repr(s)

def test_pyobject():
    p = pyobjectptr({42: 84})
    assert typeOf(p) == Ptr(PyObject)

def test_name_clash():
    import re
    from pypy.rpython.lltypesystem import lltype
    fn = lltype.__file__
    if fn.lower().endswith('pyc') or fn.lower().endswith('pyo'):
        fn = fn[:-1]
    f = open(fn, 'r')
    data = f.read()
    f.close()
    words = dict.fromkeys(re.compile(r"[a-zA-Z][_a-zA-Z0-9]*").findall(data))
    words = words.keys()
    S = GcStruct('name_clash', *[(word, Signed) for word in words])
    s = malloc(S)
    for i, word in enumerate(words):
        setattr(s, word, i)
    for i, word in enumerate(words):
        assert getattr(s, word) == i

def test_subarray_keeps_array_alive():
    A = Array(Signed)
    ptr = malloc(A, 10, immortal=True)
    ptr2 = direct_arrayitems(ptr)
    del ptr
    import gc; gc.collect(); gc.collect()
    ptr2[0] = 5    # crashes if the array was deallocated
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.