Debian Codegraph @

rpython/rtyper/lltypesystem/test/test_lltype.py

raw symbols SCIP
1 import py
2 import sys
3 from rpython.rtyper.lltypesystem.lltype import *
4 from rpython.rtyper.lltypesystem import lltype, rffi
5 from rpython.tool.identity_dict import identity_dict
6 from rpython.tool import leakfinder
7 from rpython.annotator.annrpython import RPythonAnnotator
8 from rpython.rtyper.rtyper import RPythonTyper
9
10 def isweak(p, T):
11 try:
12 typeOf(p)
13 except TypeError:
14 return True
15 return False
16
17 def test_basics():
18 S0 = GcStruct("s0", ('a', Signed), ('b', Signed))
19 assert S0.a == Signed
20 assert S0.b == Signed
21 s0 = malloc(S0)
22 assert typeOf(s0) == Ptr(S0)
23 py.test.raises(UninitializedMemoryAccess, "s0.a")
24 s0.a = 1
25 s0.b = s0.a
26 assert s0.a == 1
27 assert s0.b == 1
28 assert typeOf(s0.a) == Signed
29 # simple array
30 Ar = GcArray(('v', Signed))
31 x = malloc(Ar,0)
32 print x
33 assert len(x) == 0
34 x = malloc(Ar,3)
35 print x
36 assert typeOf(x) == Ptr(Ar)
37 assert isweak(x[0], Ar.OF)
38 x[0].v = 1
39 x[1].v = 2
40 x[2].v = 3
41 assert typeOf(x[0].v) == Signed
42 assert [x[z].v for z in range(3)] == [1, 2, 3]
43 #
44 def define_list(T):
45 List_typ = GcStruct("list",
46 ("items", Ptr(GcArray(('item',T)))))
47 def newlist():
48 l = malloc(List_typ)
49 items = malloc(List_typ.items.TO, 0)
50 l.items = items
51 return l
52
53 def append(l, newitem):
54 length = len(l.items)
55 newitems = malloc(List_typ.items.TO, length+1)
56 i = 0
57 while i < length:
58 newitems[i].item = l.items[i].item
59 i += 1
60 newitems[length].item = newitem
61 l.items = newitems
62
63 def item(l, i):
64 return l.items[i].item
65
66 return List_typ, newlist, append, item
67
68 List_typ, inewlist, iappend, iitem = define_list(Signed)
69
70 l = inewlist()
71 assert typeOf(l) == Ptr(List_typ)
72 iappend(l, 2)
73 iappend(l, 3)
74 assert len(l.items) == 2
75 assert iitem(l, 0) == 2
76 assert iitem(l, 1) == 3
77
78 IWrap = GcStruct("iwrap", ('v', Signed))
79 List_typ, iwnewlist, iwappend, iwitem = define_list(Ptr(IWrap))
80
81 l = iwnewlist()
82 assert typeOf(l) == Ptr(List_typ)
83 iw2 = malloc(IWrap)
84 iw3 = malloc(IWrap)
85 iw2.v = 2
86 iw3.v = 3
87 assert iw3.v == 3
88 iwappend(l, iw2)
89 iwappend(l, iw3)
90 assert len(l.items) == 2
91 assert iwitem(l, 0).v == 2
92 assert iwitem(l, 1).v == 3
93
94 # not allowed
95 S = Struct("s", ('v', Signed))
96 List_typ, iwnewlistzzz, iwappendzzz, iwitemzzz = define_list(S) # works but
97 l = iwnewlistzzz()
98 S1 = GcStruct("strange", ('s', S))
99 py.test.raises(TypeError, "iwappendzzz(l, malloc(S1).s)")
100
101 def test_varsizestruct():
102 S1 = GcStruct("s1", ('a', Signed), ('rest', Array(('v', Signed))))
103 py.test.raises(TypeError, "malloc(S1)")
104 s1 = malloc(S1, 4)
105 s1.a = 0
106 assert s1.a == 0
107 assert isweak(s1.rest, S1.rest)
108 assert len(s1.rest) == 4
109 assert isweak(s1.rest[0], S1.rest.OF)
110 s1.rest[0].v = 0
111 assert typeOf(s1.rest[0].v) == Signed
112 assert s1.rest[0].v == 0
113 py.test.raises(IndexError, "s1.rest[4]")
114 py.test.raises(IndexError, "s1.rest[-1]")
115
116 s1.a = 17
117 s1.rest[3].v = 5
118 assert s1.a == 17
119 assert s1.rest[3].v == 5
120
121 py.test.raises(TypeError, "Struct('invalid', ('rest', Array(('v', Signed))), ('a', Signed))")
122 py.test.raises(TypeError, "Struct('invalid', ('rest', GcArray(('v', Signed))), ('a', Signed))")
123 py.test.raises(TypeError, "Struct('invalid', ('x', Struct('s1', ('a', Signed), ('rest', Array(('v', Signed))))))")
124 py.test.raises(TypeError, "Struct('invalid', ('x', S1))")
125
126 def test_substructure_ptr():
127 S3 = Struct("s3", ('a', Signed))
128 S2 = Struct("s2", ('s3', S3))
129 S1 = GcStruct("s1", ('sub1', S2), ('sub2', S2))
130 p1 = malloc(S1)
131 assert isweak(p1.sub1, S2)
132 assert isweak(p1.sub2, S2)
133 assert isweak(p1.sub1.s3, S3)
134 p2 = p1.sub1
135 assert isweak(p2.s3, S3)
136
137 def test_gc_substructure_ptr():
138 S1 = GcStruct("s2", ('a', Signed))
139 S2 = Struct("s3", ('a', Signed))
140 S0 = GcStruct("s1", ('sub1', S1), ('sub2', S2))
141 p1 = malloc(S0)
142 assert typeOf(p1.sub1) == Ptr(S1)
143 assert isweak(p1.sub2, S2)
144
145 def test_cast_simple_widening():
146 S2 = Struct("s2", ('a', Signed))
147 S1 = Struct("s1", ('sub1', S2), ('sub2', S2))
148 p1 = malloc(S1, immortal=True)
149 p2 = p1.sub1
150 p3 = p2
151 assert typeOf(p3) == Ptr(S2)
152 p4 = cast_pointer(Ptr(S1), p3)
153 assert typeOf(p4) == Ptr(S1)
154 assert p4 == p1
155 py.test.raises(TypeError, "cast_pointer(Ptr(S1), p1.sub2)")
156 SUnrelated = Struct("unrelated")
157 py.test.raises(TypeError, "cast_pointer(Ptr(SUnrelated), p3)")
158 S1bis = Struct("s1b", ('sub1', S2))
159 p1b = malloc(S1bis, immortal=True)
160 p2 = p1b.sub1
161 py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p2)")
162
163 def test_cast_simple_widening2():
164 S2 = GcStruct("s2", ('a', Signed))
165 S1 = GcStruct("s1", ('sub1', S2))
166 p1 = malloc(S1)
167 p2 = p1.sub1
168 assert typeOf(p2) == Ptr(S2)
169 p3 = cast_pointer(Ptr(S1), p2)
170 assert p3 == p1
171 p2 = malloc(S2)
172 py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p2)")
173
174 def test_cast_pointer():
175 S3 = GcStruct("s3", ('a', Signed))
176 S2 = GcStruct("s3", ('sub', S3))
177 S1 = GcStruct("s1", ('sub', S2))
178 p1 = malloc(S1)
179 p2 = p1.sub
180 p3 = p2.sub
181 assert typeOf(p3) == Ptr(S3)
182 assert typeOf(p2) == Ptr(S2)
183 p12 = cast_pointer(Ptr(S1), p2)
184 assert p12 == p1
185 p13 = cast_pointer(Ptr(S1), p3)
186 assert p13 == p1
187 p21 = cast_pointer(Ptr(S2), p1)
188 assert p21 == p2
189 p23 = cast_pointer(Ptr(S2), p3)
190 assert p23 == p2
191 p31 = cast_pointer(Ptr(S3), p1)
192 assert p31 == p3
193 p32 = cast_pointer(Ptr(S3), p2)
194 assert p32 == p3
195 p3 = malloc(S3)
196 p2 = malloc(S2)
197 py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p3)")
198 py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p2)")
199 py.test.raises(RuntimeError, "cast_pointer(Ptr(S2), p3)")
200 S0 = GcStruct("s0", ('sub', S1))
201 p0 = malloc(S0)
202 assert p0 == cast_pointer(Ptr(S0), p0)
203 p3 = cast_pointer(Ptr(S3), p0)
204 p03 = cast_pointer(Ptr(S0), p3)
205 assert p0 == p03
206 S1bis = GcStruct("s1b", ('sub', S2))
207 assert S1bis != S1
208 p1b = malloc(S1bis)
209 p3 = p1b.sub.sub
210 assert typeOf(p3) == Ptr(S3)
211 assert p1b == cast_pointer(Ptr(S1bis), p3)
212 py.test.raises(RuntimeError, "cast_pointer(Ptr(S1), p3)")
213
214 def test_examples():
215 A1 = GcArray(('v', Signed))
216 S = GcStruct("s", ('v', Signed))
217 St = GcStruct("st", ('v', Signed),('trail', Array(('v', Signed))))
218
219 PA1 = Ptr(A1)
220 PS = Ptr(S)
221 PSt = Ptr(St)
222
223 ex_pa1 = PA1._example()
224 ex_ps = PS._example()
225 ex_pst = PSt._example()
226
227 assert typeOf(ex_pa1) == PA1
228 assert typeOf(ex_ps) == PS
229 assert typeOf(ex_pst) == PSt
230
231 assert ex_pa1[0].v == 0
232 assert ex_ps.v == 0
233 assert ex_pst.v == 0
234 assert ex_pst.trail[0].v == 0
235
236 def test_functions():
237 F = FuncType((Signed,), Signed)
238 py.test.raises(TypeError, "Struct('x', ('x', F))")
239
240 PF = Ptr(F)
241 pf = PF._example()
242 assert pf(0) == 0
243 py.test.raises(TypeError, pf, 0, 0)
244 py.test.raises(TypeError, pf, 'a')
245
246 def test_truargs():
247 F = FuncType((Void, Signed, Void, Unsigned), Float)
248 assert Void not in F._trueargs()
249
250 def test_inconsistent_gc_containers():
251 A = GcArray(('y', Signed))
252 S = GcStruct('b', ('y', Signed))
253 py.test.raises(TypeError, "Struct('a', ('x', S))")
254 py.test.raises(TypeError, "GcStruct('a', ('x', Signed), ('y', S))")
255 py.test.raises(TypeError, "Array(('x', S))")
256 py.test.raises(TypeError, "GcArray(('x', S))")
257 py.test.raises(TypeError, "Struct('a', ('x', A))")
258 py.test.raises(TypeError, "GcStruct('a', ('x', A))")
259
260 def test_forward_reference():
261 F = GcForwardReference()
262 S = GcStruct('abc', ('x', Ptr(F)))
263 F.become(S)
264 assert S.x == Ptr(S)
265 py.test.raises(TypeError, "GcForwardReference().become(Struct('abc'))")
266 ForwardReference().become(Struct('abc'))
267 hash(S)
268
269 def test_nullptr():
270 S = Struct('s')
271 p0 = nullptr(S)
272 assert not p0
273 assert typeOf(p0) == Ptr(S)
274
275
276 def test_nullptr_cast():
277 S = Struct('s')
278 p0 = nullptr(S)
279 assert not p0
280 S1 = Struct("s1", ('s', S))
281 p10 = cast_pointer(Ptr(S1), p0)
282 assert typeOf(p10) == Ptr(S1)
283 assert not p10
284
285 def test_nullptr_opaque_cast():
286 S = Struct('S')
287 p0 = nullptr(S)
288 O1 = OpaqueType('O1')
289 O2 = OpaqueType('O2')
290 p1 = cast_opaque_ptr(Ptr(O1), p0)
291 assert not p1
292 p2 = cast_opaque_ptr(Ptr(O2), p1)
293 assert not p2
294 p3 = cast_opaque_ptr(Ptr(S), p2)
295 assert not p3
296
297
298 def test_hash():
299 S = ForwardReference()
300 S.become(Struct('S', ('p', Ptr(S))))
301 assert S == S
302 hash(S) # assert no crash, and force the __cached_hash computation
303 S1 = Struct('S', ('p', Ptr(S)))
304 assert S1 == S
305 assert S == S1
306 assert hash(S1) == hash(S)
307
308 def test_array_with_non_container_elements():
309 As = GcArray(Signed)
310 a = malloc(As, 3)
311 assert typeOf(a) == Ptr(As)
312 py.test.raises(UninitializedMemoryAccess, "a[0]")
313 a[1] = 3
314 assert a[1] == 3
315 S = GcStruct('s', ('x', Signed))
316 s = malloc(S)
317 py.test.raises(TypeError, "a[1] = s")
318 S = GcStruct('s', ('x', Signed))
319 py.test.raises(TypeError, "Array(S)")
320 py.test.raises(TypeError, "Array(As)")
321 S = Struct('s', ('x', Signed))
322 A = GcArray(S)
323 a = malloc(A, 2)
324 s = S._container_example() # should not happen anyway
325 py.test.raises(TypeError, "a[0] = s")
326 S = Struct('s', ('last', Array(S)))
327 py.test.raises(TypeError, "Array(S)")
328
329 def test_immortal_parent():
330 S1 = GcStruct('substruct', ('x', Signed))
331 S = GcStruct('parentstruct', ('s1', S1))
332 p = malloc(S, immortal=True)
333 p1 = p.s1
334 p1.x = 5
335 del p
336 p = cast_pointer(Ptr(S), p1)
337 assert p.s1.x == 5
338
339 def test_getRuntimeTypeInfo():
340 S = GcStruct('s', ('x', Signed))
341 py.test.raises(ValueError, "getRuntimeTypeInfo(S)")
342 S = GcStruct('s', ('x', Signed), rtti=True)
343 pinfx = getRuntimeTypeInfo(S)
344 pinf0 = attachRuntimeTypeInfo(S) # no-op, really
345 assert pinf0._obj.about == S
346 assert pinf0 == pinfx
347 pinf = getRuntimeTypeInfo(S)
348 assert pinf == pinf0
349 pinf1 = getRuntimeTypeInfo(S)
350 assert pinf == pinf1
351 Z = GcStruct('z', ('x', Unsigned), rtti=True)
352 assert getRuntimeTypeInfo(Z) != pinf0
353 Sbis = GcStruct('s', ('x', Signed), rtti=True)
354 assert getRuntimeTypeInfo(Sbis) != pinf0
355 assert Sbis != S # the attached runtime type info distinguishes them
356 Ster = GcStruct('s', ('x', Signed), rtti=True)
357 assert Sbis != Ster # the attached runtime type info distinguishes them
358
359 def test_getRuntimeTypeInfo_destrpointer():
360 S = GcStruct('s', ('x', Signed), rtti=True)
361 def f(s):
362 s.x = 1
363 def type_info_S(p):
364 return getRuntimeTypeInfo(S)
365 qp = functionptr(FuncType([Ptr(S)], Ptr(RuntimeTypeInfo)),
366 "type_info_S",
367 _callable=type_info_S)
368 dp = functionptr(FuncType([Ptr(S)], Void),
369 "destructor_funcptr",
370 _callable=f)
371 pinf0 = attachRuntimeTypeInfo(S, qp, destrptr=dp)
372 assert pinf0._obj.about == S
373 pinf = getRuntimeTypeInfo(S)
374 assert pinf == pinf0
375 pinf1 = getRuntimeTypeInfo(S)
376 assert pinf == pinf1
377 assert pinf._obj.destructor_funcptr == dp
378 assert pinf._obj.query_funcptr == qp
379
380 def test_runtime_type_info():
381 S = GcStruct('s', ('x', Signed), rtti=True)
382 attachRuntimeTypeInfo(S)
383 s = malloc(S)
384 s.x = 0
385 assert runtime_type_info(s) == getRuntimeTypeInfo(S)
386 S1 = GcStruct('s1', ('sub', S), ('x', Signed), rtti=True)
387 attachRuntimeTypeInfo(S1)
388 s1 = malloc(S1)
389 s1.sub.x = 0
390 s1.x = 0
391 assert runtime_type_info(s1) == getRuntimeTypeInfo(S1)
392 assert runtime_type_info(s1.sub) == getRuntimeTypeInfo(S1)
393 assert runtime_type_info(cast_pointer(Ptr(S), s1)) == getRuntimeTypeInfo(S1)
394 def dynamic_type_info_S(p):
395 if p.x == 0:
396 return getRuntimeTypeInfo(S)
397 else:
398 return getRuntimeTypeInfo(S1)
399 fp = functionptr(FuncType([Ptr(S)], Ptr(RuntimeTypeInfo)),
400 "dynamic_type_info_S",
401 _callable=dynamic_type_info_S)
402 attachRuntimeTypeInfo(S, fp)
403 assert s.x == 0
404 assert runtime_type_info(s) == getRuntimeTypeInfo(S)
405 s.x = 1
406 py.test.raises(RuntimeError, "runtime_type_info(s)")
407 assert s1.sub.x == 0
408 py.test.raises(RuntimeError, "runtime_type_info(s1.sub)")
409 s1.sub.x = 1
410 assert runtime_type_info(s1.sub) == getRuntimeTypeInfo(S1)
411
412 def test_flavor_malloc():
413 def isweak(p, T):
414 return p._weak and typeOf(p).TO == T
415 S = Struct('s', ('x', Signed))
416 py.test.raises(TypeError, malloc, S)
417 p = malloc(S, flavor="raw")
418 assert typeOf(p).TO == S
419 assert not isweak(p, S)
420 p.x = 2
421 free(p, flavor="raw")
422 py.test.raises(RuntimeError, "p.x")
423 T = GcStruct('T', ('y', Signed))
424 p = malloc(T, flavor="gc")
425 assert typeOf(p).TO == T
426 assert not isweak(p, T)
427
428 def test_opaque():
429 O = OpaqueType('O')
430 p1 = opaqueptr(O, 'p1', hello="world")
431 assert typeOf(p1) == Ptr(O)
432 assert p1._obj.hello == "world"
433 assert parentlink(p1._obj) == (None, None)
434 S = GcStruct('S', ('stuff', O))
435 p2 = malloc(S)
436 assert typeOf(p2) == Ptr(S)
437 assert typeOf(p2.stuff) == Ptr(O)
438 assert parentlink(p2.stuff._obj) == (p2._obj, 'stuff')
439
440 def test_cast_opaque_ptr():
441 O = GcOpaqueType('O')
442 Q = GcOpaqueType('Q')
443 S = GcStruct('S', ('x', Signed))
444 s = malloc(S)
445 o = cast_opaque_ptr(Ptr(O), s)
446 assert typeOf(o).TO == O
447 q = cast_opaque_ptr(Ptr(Q), o)
448 assert typeOf(q).TO == Q
449 p = cast_opaque_ptr(Ptr(S), q)
450 assert typeOf(p).TO == S
451 assert p == s
452 O1 = OpaqueType('O')
453 S1 = Struct('S1', ('x', Signed))
454 s1 = malloc(S1, immortal=True)
455 o1 = cast_opaque_ptr(Ptr(O1), s1)
456 assert typeOf(o1).TO == O1
457 p1 = cast_opaque_ptr(Ptr(S1), o1)
458 assert typeOf(p1).TO == S1
459 assert p1 == s1
460 py.test.raises(TypeError, "cast_opaque_ptr(Ptr(S), o1)")
461 py.test.raises(TypeError, "cast_opaque_ptr(Ptr(O1), s)")
462 S2 = Struct('S2', ('z', Signed))
463 py.test.raises(InvalidCast, "cast_opaque_ptr(Ptr(S2), o1)")
464
465 BIG = GcStruct('BIG', ('s', S))
466 UNRELATED = GcStruct('UNRELATED')
467 big = malloc(BIG)
468 unrelated = malloc(UNRELATED)
469 p1 = cast_opaque_ptr(Ptr(O), big)
470 p2 = cast_opaque_ptr(Ptr(O), big)
471 assert p1 == p2
472 p3 = cast_opaque_ptr(Ptr(O), big.s)
473 assert p1 == p3
474 p4 = cast_opaque_ptr(Ptr(O), unrelated)
475 assert p1 != p4
476 assert p3 != p4
477
478 def test_is_atomic():
479 U = Struct('inlined', ('z', Signed))
480 A = Ptr(RuntimeTypeInfo)
481 P = Ptr(GcStruct('p'))
482 Q = GcStruct('q', ('i', Signed), ('u', U), ('p', P))
483 O = OpaqueType('O')
484 F = GcForwardReference()
485 assert A._is_atomic() is True
486 assert P._is_atomic() is False
487 assert Q.i._is_atomic() is True
488 assert Q.u._is_atomic() is True
489 assert Q.p._is_atomic() is False
490 assert Q._is_atomic() is False
491 assert O._is_atomic() is False
492 assert F._is_atomic() is False
493
494 def test_adtmeths():
495 def h_newstruct():
496 return malloc(S)
497
498 S = GcStruct('s', ('x', Signed),
499 adtmeths={"h_newstruct": h_newstruct})
500
501 s = S.h_newstruct()
502
503 assert typeOf(s) == Ptr(S)
504
505 def h_alloc(n):
506 return malloc(A, n)
507
508 def h_length(a):
509 return len(a)
510
511 A = GcArray(Signed,
512 adtmeths={"h_alloc": h_alloc,
513 "h_length": h_length,
514 "stuff": 12})
515
516 a = A.h_alloc(10)
517
518 assert typeOf(a) == Ptr(A)
519 assert len(a) == 10
520
521 assert a.h_length() == 10
522 assert a._lookup_adtmeth("h_length")() == 10
523 assert a.stuff == 12
524 assert a._lookup_adtmeth("stuff") == 12
525
526 def test_adt_typemethod():
527 def h_newstruct(S):
528 return malloc(S)
529 h_newstruct = typeMethod(h_newstruct)
530
531 S = GcStruct('s', ('x', Signed),
532 adtmeths={"h_newstruct": h_newstruct})
533
534 s = S.h_newstruct()
535
536 assert typeOf(s) == Ptr(S)
537
538 Sprime = GcStruct('s', ('x', Signed),
539 adtmeths={"h_newstruct": h_newstruct})
540
541 assert S == Sprime
542
543 class Frozen(object):
544 def _freeze_(self):
545 return True
546
547 @py.test.mark.parametrize('x', [
548 1, sys.maxint, 1.5, 'a', 'abc', u'abc', None, [],
549 lambda: None,
550 {1.23: 'abc'},
551 (1, 'x', [2, 3.],),
552 Frozen(),])
553 def test_typeOf_const(x):
554 a = RPythonAnnotator()
555 bk = a.bookkeeper
556 rtyper = RPythonTyper(a)
557 s_x = bk.immutablevalue(x)
558 r_x = rtyper.getrepr(s_x)
559 assert typeOf(r_x.convert_const(x)) == r_x.lowleveltype
560
561 def test_cast_primitive():
562 cases = [
563 (Float, 1, 1.0),
564 (Float, r_singlefloat(2.1), float(r_singlefloat(2.1))),
565 (Signed, 1.0, 1),
566 (Unsigned, 1.0, 1),
567 (Signed, r_uint(-1), -1),
568 (Unsigned, -1, r_uint(-1)),
569 (Char, ord('a'), 'a'),
570 (Char, False, chr(0)),
571 (Signed, 'x', ord('x')),
572 (Unsigned, u"x", ord(u'x')),
573 ]
574 for TGT, orig_val, expect in cases:
575 res = cast_primitive(TGT, orig_val)
576 assert typeOf(res) == TGT
577 assert res == expect
578 res = cast_primitive(SingleFloat, 2.1)
579 assert isinstance(res, r_singlefloat)
580 assert float(res) == float(r_singlefloat(2.1))
581
582 def test_cast_identical_array_ptr_types():
583 A = GcArray(Signed)
584 PA = Ptr(A)
585 a = malloc(A, 2)
586 assert cast_pointer(PA, a) == a
587
588 def test_array_with_no_length():
589 A = GcArray(Signed, hints={'nolength': True})
590 a = malloc(A, 10)
591 py.test.raises(TypeError, len, a)
592
593 def test_dissect_ll_instance():
594 assert list(dissect_ll_instance(1)) == [(Signed, 1)]
595 GcS = GcStruct("S", ('x', Signed))
596 s = malloc(GcS)
597 s.x = 1
598 assert list(dissect_ll_instance(s)) == [(Ptr(GcS), s), (GcS, s._obj), (Signed, 1)]
599
600 A = GcArray(('x', Signed))
601 a = malloc(A, 10)
602 for i in range(10):
603 a[i].x = i
604 expected = [(Ptr(A), a), (A, a._obj)]
605 for t in [((A.OF, a._obj.items[i]), (Signed, i)) for i in range(10)]:
606 expected.extend(t)
607 assert list(dissect_ll_instance(a)) == expected
608
609 R = GcStruct("R", ('r', Ptr(GcForwardReference())))
610 R.r.TO.become(R)
611
612 r = malloc(R)
613 r.r = r
614 r_expected = [(Ptr(R), r), (R, r._obj)]
615 assert list(dissect_ll_instance(r)) == r_expected
616
617 B = GcArray(Ptr(R))
618 b = malloc(B, 2)
619 b[0] = b[1] = r
620 b_expected = [(Ptr(B), b), (B, b._obj)]
621 assert list(dissect_ll_instance(b)) == b_expected + r_expected
622
623 memo = identity_dict()
624 assert list(dissect_ll_instance(r, None, memo)) == r_expected
625 assert list(dissect_ll_instance(b, None, memo)) == b_expected
626
627 def test_fixedsizearray():
628 A = FixedSizeArray(Signed, 5)
629 assert A.OF == Signed
630 assert A.length == 5
631 assert A.item0 == A.item1 == A.item2 == A.item3 == A.item4 == Signed
632 assert A._names == ('item0', 'item1', 'item2', 'item3', 'item4')
633 a = malloc(A, immortal=True)
634 a[0] = 5
635 a[4] = 83
636 assert a[0] == 5
637 assert a[4] == 83
638 assert a.item4 == 83
639 py.test.raises(IndexError, "a[5] = 183")
640 py.test.raises(IndexError, "a[-1]")
641 assert len(a) == 5
642
643 S = GcStruct('S', ('n1', Signed),
644 ('a', A),
645 ('n2', Signed))
646 s = malloc(S)
647 s.a[3] = 17
648 assert s.a[3] == 17
649 assert len(s.a) == 5
650 py.test.raises(TypeError, "s.a = a")
651
652 def test_direct_arrayitems():
653 for a in [malloc(GcArray(Signed), 5),
654 malloc(FixedSizeArray(Signed, 5), immortal=True)]:
655 a[0] = 0
656 a[1] = 10
657 a[2] = 20
658 a[3] = 30
659 a[4] = 40
660 b0 = direct_arrayitems(a)
661 assert typeOf(b0) == Ptr(FixedSizeArray(Signed, 1))
662 b1 = direct_ptradd(b0, 1)
663 b2 = direct_ptradd(b1, 1)
664 b3 = direct_ptradd(b0, 3)
665 assert b0[0] == 0
666 assert b0[1] == 10
667 assert b0[4] == 40
668 assert b1[0] == 10
669 assert b1[1] == 20
670 assert b2[0] == 20
671 assert b2[1] == 30
672 assert b3[-2] == 10
673 assert b3[0] == 30
674 assert b3[1] == 40
675 assert b2[-2] == 0
676 assert b1[3] == 40
677 b2[0] = 23
678 assert a[2] == 23
679 b1[1] += 1
680 assert a[2] == 24
681 py.test.raises(IndexError, "b0[-1]")
682 py.test.raises(IndexError, "b3[2]")
683 py.test.raises(IndexError, "b1[4]")
684
685 def test_direct_fieldptr():
686 S = GcStruct('S', ('x', Signed), ('y', Signed))
687 s = malloc(S)
688 a = direct_fieldptr(s, 'y')
689 a[0] = 34
690 assert s.y == 34
691 py.test.raises(IndexError, "a[1]")
692
693 def test_odd_ints():
694 T = GcStruct('T')
695 S = GcStruct('S', ('t', T))
696 s = cast_int_to_ptr(Ptr(S), 21)
697 assert typeOf(s) == Ptr(S)
698 assert cast_ptr_to_int(s) == 21
699 t = cast_pointer(Ptr(T), s)
700 assert typeOf(t) == Ptr(T)
701 assert cast_ptr_to_int(t) == 21
702 assert s == cast_pointer(Ptr(S), t)
703
704 def test_str_of_dead_ptr():
705 S = Struct('S', ('x', Signed))
706 T = GcStruct('T', ('s', S))
707 t = malloc(T)
708 s = t.s
709 del t
710 import gc
711 gc.collect()
712 repr(s)
713
714 def test_name_clash():
715 import re
716 fn = lltype.__file__
717 if fn.lower().endswith('pyc') or fn.lower().endswith('pyo'):
718 fn = fn[:-1]
719 f = open(fn, 'r')
720 data = f.read()
721 f.close()
722 words = dict.fromkeys(re.compile(r"[a-zA-Z][_a-zA-Z0-9]*").findall(data))
723 words = words.keys()
724 S = GcStruct('name_clash', *[(word, Signed) for word in words])
725 s = malloc(S)
726 for i, word in enumerate(words):
727 setattr(s, word, i)
728 for i, word in enumerate(words):
729 assert getattr(s, word) == i
730
731 def test_subarray_keeps_array_alive():
732 A = Array(Signed)
733 ptr = malloc(A, 10, immortal=True)
734 ptr2 = direct_arrayitems(ptr)
735 del ptr
736 import gc; gc.collect(); gc.collect()
737 ptr2[0] = 5 # crashes if the array was deallocated
738
739 def test_identityhash():
740 S = GcStruct('S', ('x', Signed))
741 S2 = GcStruct('S2', ('super', S))
742 S3 = GcStruct('S3', ('super', S2))
743
744 py.test.raises(AssertionError, identityhash, nullptr(S2))
745
746 s3 = malloc(S3)
747 hash3 = identityhash(s3.super)
748 assert hash3 == identityhash(s3)
749 assert hash3 == identityhash(s3.super)
750 assert hash3 == identityhash(s3.super.super)
751
752 from rpython.rtyper.lltypesystem import llmemory
753 p3 = cast_opaque_ptr(llmemory.GCREF, s3)
754 assert hash3 == identityhash(p3)
755
756 A = GcArray(Signed)
757 a = malloc(A, 3)
758 hash1 = identityhash(a)
759 assert hash1 == identityhash(a)
760 p = cast_opaque_ptr(llmemory.GCREF, a)
761 assert hash1 == identityhash(p)
762
763 def test_immutable_hint():
764 S = GcStruct('S', ('x', lltype.Signed))
765 assert S._immutable_field('x') == False
766 #
767 S = GcStruct('S', ('x', lltype.Signed), hints={'immutable': True})
768 assert S._immutable_field('x') == True
769 #
770 class FieldListAccessor(object):
771 def __init__(self, fields):
772 self.fields = fields
773 S = GcStruct('S', ('x', lltype.Signed),
774 hints={'immutable_fields': FieldListAccessor({'x': 1234})})
775 assert S._immutable_field('x') == 1234
776
777 def test_typedef():
778 T = Typedef(Signed, 'T')
779 assert T == Signed
780 assert Signed == T
781 T2 = Typedef(T, 'T2')
782 assert T2 == T
783 assert T2.OF is Signed
784 py.test.raises(TypeError, Ptr, T)
785 assert rffi.CArrayPtr(T) == rffi.CArrayPtr(Signed)
786 assert rffi.CArrayPtr(Signed) == rffi.CArrayPtr(T)
787
788 F = FuncType((T,), T)
789 assert F.RESULT == Signed
790 assert F.ARGS == (Signed,)
791
792 def test_cannot_inline_random_stuff_in_gcstruct():
793 S = GcStruct('S')
794 GcStruct('X', ('a', S)) # works
795 py.test.raises(TypeError, GcStruct, 'X', ('a', Signed), ('b', S))
796 GcStruct('X', ('a', Array(Signed))) # works
797 py.test.raises(TypeError, GcStruct, 'X', ('a', Array(Signed)),
798 ('b', Signed))
799 Struct('X', ('a', Array(Signed, hints={'nolength': True}))) # works
800 py.test.raises(TypeError, GcStruct, 'X',
801 ('a', Array(Signed, hints={'nolength': True})))
802 GcStruct('X', ('a', OpaqueType('foo'))) # works
803 py.test.raises(TypeError, GcStruct, 'X', ('a', GcOpaqueType('foo')))
804
805
806 class TestTrackAllocation:
807 def test_automatic_tracking(self):
808 # calls to start_tracking_allocations/stop_tracking_allocations
809 # should occur automatically from pypy/conftest.py. Check that.
810 assert leakfinder.TRACK_ALLOCATIONS
811
812 def test_track_allocation(self):
813 """A malloc'd buffer fills the ALLOCATED dictionary"""
814 assert leakfinder.TRACK_ALLOCATIONS
815 assert not leakfinder.ALLOCATED
816 buf = malloc(Array(Signed), 1, flavor="raw")
817 assert len(leakfinder.ALLOCATED) == 1
818 assert leakfinder.ALLOCATED.keys() == [buf._obj]
819 free(buf, flavor="raw")
820 assert not leakfinder.ALLOCATED
821
822 def test_str_from_buffer(self):
823 """gc-managed memory does not need to be freed"""
824 size = 50
825 raw_buf, gc_buf, case_num = rffi.alloc_buffer(size)
826 for i in range(size): raw_buf[i] = 'a'
827 rstr = rffi.str_from_buffer(raw_buf, gc_buf, case_num, size, size)
828 rffi.keep_buffer_alive_until_here(raw_buf, gc_buf, case_num)
829 assert not leakfinder.ALLOCATED
830
831 def test_leak_traceback(self):
832 """Test info stored for allocated items"""
833 buf = malloc(Array(Signed), 1, flavor="raw")
834 traceback = leakfinder.ALLOCATED.values()[0]
835 lines = traceback.splitlines()
836 assert 'malloc(' in lines[-1] and 'flavor="raw")' in lines[-1]
837
838 # The traceback should not be too long
839 print traceback
840
841 free(buf, flavor="raw")
842
843 def test_no_tracking(self):
844 p1 = malloc(Array(Signed), 1, flavor='raw', track_allocation=False)
845 p2 = malloc(Array(Signed), 1, flavor='raw', track_allocation=False)
846 free(p2, flavor='raw', track_allocation=False)
847 # p1 is not freed
848
849 def test_scoped_allocator(self):
850 with scoped_alloc(Array(Signed), 1) as array:
851 array[0] = -42
852 x = array[0]
853 assert x == -42