Debian Codegraph @

rpython/rtyper/test/test_rstr.py

raw symbols SCIP
1 import random
2
3 import py
4
5 from rpython.flowspace.model import summary
6 from rpython.annotator.model import AnnotatorError
7 from rpython.rtyper.lltypesystem.lltype import typeOf, Signed, malloc
8 from rpython.rtyper.lltypesystem.rstr import LLHelpers, STR
9 from rpython.rtyper.rstr import AbstractLLHelpers
10 from rpython.rtyper.rtyper import TyperError
11 from rpython.rtyper.test.tool import BaseRtypingTest
12 from rpython.rtyper.annlowlevel import llstr, hlstr
13 from rpython.rtyper.llinterp import LLAssertFailure
14
15
16 def test_parse_fmt():
17 parse = AbstractLLHelpers.parse_fmt_string
18 assert parse('a') == ['a']
19 assert parse('%s') == [('s',)]
20 assert parse("name '%s' is not defined") == ["name '", ("s",), "' is not defined"]
21
22
23 class AbstractTestRstr(BaseRtypingTest):
24 def test_simple(self):
25 const = self.const
26 def fn(i):
27 s = const('hello')
28 return s[i]
29 for i in range(5):
30 res = self.interpret(fn, [i])
31 expected = fn(i)
32 assert res == expected
33 assert res.__class__ is expected.__class__
34
35 def test_implicit_index_error(self):
36 const = self.const
37 def fn(i):
38 s = const('hello')
39 try:
40 return s[i]
41 except IndexError:
42 return const('*')
43 for i in range(-5, 5):
44 res = self.interpret(fn, [i])
45 expected = fn(i)
46 assert res == expected
47 assert res.__class__ is expected.__class__
48 res = self.interpret(fn, [5])
49 assert res == '*'
50 res = self.interpret(fn, [6])
51 assert res == '*'
52 res = self.interpret(fn, [-42])
53 assert res == '*'
54
55 def test_nonzero(self):
56 const = self.const
57 def fn(i, j):
58 s = [const(''), const('xx')][j]
59 if i < 0:
60 s = None
61 if i > -2:
62 return bool(s)
63 else:
64 return False
65 for i in [-2, -1, 0]:
66 for j in range(2):
67 res = self.interpret(fn, [i, j])
68 assert res is fn(i, j)
69
70 def test_concat(self):
71 const = self.const
72 def fn(i, j):
73 s1 = [const(''), const('a'), const('ab')]
74 s2 = [const(''), const('x'), const('xy')]
75 return s1[i] + s2[j]
76 for i in range(3):
77 for j in range(3):
78 res = self.interpret(fn, [i,j])
79 assert self.ll_to_string(res) == fn(i, j)
80
81 def test_iter(self):
82 const = self.const
83 def fn(i):
84 s = [const(''), const('a'), const('hello')][i]
85 i = 0
86 for c in s:
87 if c != s[i]:
88 return False
89 i += 1
90 if i == len(s):
91 return True
92 return False
93
94 for i in range(3):
95 res = self.interpret(fn, [i])
96 assert res is True
97
98 def test_iter_over_char(self):
99 const = self.const
100 def fn(i):
101 for c in const('a'):
102 i += ord(c) + 10000
103 return i
104 res = self.interpret(fn, [0])
105 assert res == ord('a') + 10000
106
107 def test_iter_over_nonconst_char(self):
108 const = self.const
109 def fn(i):
110 if i > 0:
111 c = const('a')
112 else:
113 c = const('A')
114 for c in c:
115 i += ord(c) + 10000
116 return i
117 res = self.interpret(fn, [1])
118 assert res == 1 + ord('a') + 10000
119
120 def test_str_iterator_reversed_unsupported(self):
121 const = self.const
122 def fn():
123 total = 0
124 t = const('foo')
125 for x in reversed(t):
126 total += ord(x)
127 return total
128 py.test.raises(TyperError, self.interpret, fn, [])
129
130 def test_char_constant(self):
131 const = self.const
132 def fn(s):
133 return s + const('.')
134 res = self.interpret(fn, [const('x')])
135 res = self.ll_to_string(res)
136 assert len(res) == 2
137 assert res[0] == const('x')
138 assert res[1] == const('.')
139
140 def test_char_isxxx(self):
141 constchar = self.constchar
142 def fn(s):
143 return (s.isspace() |
144 s.isdigit() << 1 |
145 s.isalpha() << 2 |
146 s.isalnum() << 3 |
147 s.isupper() << 4 |
148 s.islower() << 5)
149 for i in range(128):
150 ch = constchar(i)
151 res = self.interpret(fn, [ch])
152 assert res == fn(ch)
153
154 def test_char_index_0(self):
155 def fn(c):
156 return c[0]
157 x = self.interpret(fn, [self.constchar(65)])
158 assert x == chr(65)
159 def f():
160 return ord(fn('a')) + ord(fn('b'))
161 t, typer, fgraph = self.gengraph(f, [], backendopt=True)
162 # all constant folded
163 assert not summary(fgraph)
164
165 def fn(c):
166 return c[-1] # not optimized, works anyway
167 x = self.interpret(fn, [self.constchar(65)])
168 assert x == chr(65)
169
170 def test_char_index_0_checked(self):
171 constchar = self.constchar
172 errorres = constchar(ord('?'))
173 def fn(c):
174 try:
175 return c[0]
176 except IndexError:
177 return errorres
178 x = self.interpret(fn, [constchar(65)])
179 assert x == constchar(65)
180 def f():
181 return ord(fn(constchar(65))) + ord(constchar(66))
182 t, typer, fgraph = self.gengraph(f, [], backendopt=True)
183 # all constant folded
184 assert not summary(fgraph)
185
186 def test_isdigit(self):
187 const = self.const
188
189 def fn(i):
190 consts = [const(''), const('anc'), const('abc123'), const('123')]
191 return consts[i].isdigit()
192 for i in xrange(3):
193 assert self.interpret(fn, [i]) == fn(i)
194
195 def test_str_isalpha(self):
196 const = self.const
197
198 def fn(i):
199 consts = [const(''), const('anc'), const('abc123')]
200 return consts[i].isalpha()
201 for i in xrange(3):
202 assert self.interpret(fn, [i]) == fn(i)
203
204 def test_str_isalnum(self):
205 const = self.const
206
207 def fn(i):
208 consts = [const(''), const('abc'), const('abc123'), const('abc123!')]
209 return consts[i].isalnum()
210 for i in xrange(3):
211 assert self.interpret(fn, [i]) == fn(i)
212
213 def test_char_compare(self):
214 const = self.const
215 res = self.interpret(lambda c1, c2: c1 == c2, [const('a'),
216 const('b')])
217 assert res is False
218 res = self.interpret(lambda c1, c2: c1 == c2, [const('a'),
219 const('a')])
220 assert res is True
221 res = self.interpret(lambda c1, c2: c1 <= c2, [const('z'),
222 const('a')])
223 assert res is False
224
225 def test_char_string_compare(self):
226 const = self.const
227 lst = [const('a'), const('abc')]
228 res = self.interpret(lambda i1, c2: (lst[i1],) == (c2,),
229 [1, const('b')])
230 assert res is False
231 res = self.interpret(lambda i1, c2: (c2,) == (lst[i1],),
232 [1, const('b')])
233 assert res is False
234
235 def test_char_mul(self):
236 const = self.const
237 def fn(c, mul):
238 s = c * mul
239 res = 0
240 for i in range(len(s)):
241 res = res*10 + ord(const(s[i])[0]) - ord(const('0')[0])
242 c2 = c
243 c2 *= mul
244 res = 10 * res + (c2 == s)
245 return res
246 res = self.interpret(fn, [const('3'), 5])
247 assert res == 333331
248 res = self.interpret(fn, [const('5'), 3])
249 assert res == 5551
250
251 def test_str_mul(self):
252 const = self.const
253 def fn(i, mul):
254 s = ["", "a", "aba"][i]
255 return s * mul + mul * s
256 for i in xrange(3):
257 for m in [0, 1, 4]:
258 res1 = fn(i, m)
259 res = self.interpret(fn, [i, m])
260 assert self.ll_to_string(res) == res1
261
262 def test_is_none(self):
263 const = self.const
264 def fn(i):
265 s1 = [const('foo'), None][i]
266 return s1 is None
267 assert self.interpret(fn, [0]) == False
268 assert self.interpret(fn, [1]) == True
269
270 def test_str_compare(self):
271 const = self.const
272 def fn(i, j):
273 s1 = [const('one'), const('two'), None]
274 s2 = [const('one'), const('two'), const('o'),
275 const('on'), const('twos'), const('foobar'), None]
276 return s1[i] == s2[j]
277 for i in range(3):
278 for j in range(7):
279 res = self.interpret(fn, [i,j])
280 assert res is fn(i, j)
281
282 def fn(i, j):
283 s1 = [const('one'), const('two')]
284 s2 = [const('one'), const('two'), const('o'), const('on'), const('twos'), const('foobar')]
285 return s1[i] != s2[j]
286 for i in range(2):
287 for j in range(6):
288 res = self.interpret(fn, [i, j])
289 assert res is fn(i, j)
290
291 def fn(i, j):
292 s1 = [const('one'), const('two')]
293 s2 = [const('one'), const('two'), const('o'), const('on'), const('twos'), const('foobar')]
294 return s1[i] < s2[j]
295 for i in range(2):
296 for j in range(6):
297 res = self.interpret(fn, [i,j])
298 assert res is fn(i, j)
299
300 def fn(i, j):
301 s1 = [const('one'), const('two')]
302 s2 = [const('one'), const('two'), const('o'), const('on'), const('twos'), const('foobar')]
303 return s1[i] <= s2[j]
304 for i in range(2):
305 for j in range(6):
306 res = self.interpret(fn, [i,j])
307 assert res is fn(i, j)
308
309 def fn(i, j):
310 s1 = [const('one'), const('two')]
311 s2 = [const('one'), const('two'), const('o'), const('on'), const('twos'), const('foobar')]
312 return s1[i] >= s2[j]
313 for i in range(2):
314 for j in range(6):
315 res = self.interpret(fn, [i,j])
316 assert res is fn(i, j)
317
318 def fn(i, j):
319 s1 = [const('one'), const('two')]
320 s2 = [const('one'), const('two'), const('o'), const('on'), const('twos'), const('foobar')]
321 return s1[i] > s2[j]
322 for i in range(2):
323 for j in range(6):
324 res = self.interpret(fn, [i,j])
325 assert res is fn(i, j)
326
327 def test_startswith(self):
328 const = self.const
329 def fn(i, j):
330 s1 = [const(''), const('one'), const('two')]
331 s2 = [const(''), const('one'), const('two'), const('o'), const('on'), const('ne'), const('e'), const('twos'), const('foobar'), const('fortytwo')]
332 return s1[i].startswith(s2[j])
333 for i in range(3):
334 for j in range(10):
335 res = self.interpret(fn, [i,j])
336 assert res is fn(i, j)
337
338 def test_startswith_char(self):
339 const = self.const
340 def fn(i):
341 s = [const(''), const('one'), const('two'), const('o'), const('on'), const('ne'), const('e'), const('twos'), const('foobar'), const('fortytwo')]
342 return s[i].startswith(const('o'))
343 for i in range(10):
344 res = self.interpret(fn, [i])
345 assert res == fn(i)
346
347 def test_endswith(self):
348 const = self.const
349 def fn(i, j):
350 s1 = [const(''), const('one'), const('two')]
351 s2 = [const(''), const('one'), const('two'), const('o'), const('on'), const('ne'), const('e'), const('twos'), const('foobar'), const('fortytwo')]
352 return s1[i].endswith(s2[j])
353 for i in range(3):
354 for j in range(10):
355 res = self.interpret(fn, [i,j])
356 assert res is fn(i, j)
357
358 def test_endswith_char(self):
359 const = self.const
360 def fn(i):
361 s = [const(''), const('one'), const('two'), const('o'), const('on'), const('ne'), const('e'), const('twos'), const('foobar'), const('fortytwo')]
362 return s[i].endswith(const('e'))
363 for i in range(10):
364 res = self.interpret(fn, [i])
365 assert res == fn(i)
366
367 def test_find(self):
368 const = self.const
369 def fn(i, j):
370 s1 = [const('one two three'), const('abc abcdab abcdabcdabde')]
371 s2 = [const('one'), const('two'), const('abcdab'), const('one tou'), const('abcdefgh'), const('fortytwo'), const('')]
372 return s1[i].find(s2[j])
373 for i in range(2):
374 for j in range(7):
375 res = self.interpret(fn, [i,j])
376 assert res == fn(i, j)
377
378
379 def test_contains_str(self):
380 const = self.const
381 def fn(i, j):
382 s1 = [const('one two three'), const('abc abcdab abcdabcdabde')]
383 s2 = [const('one'), const('two'), const('abcdab'), const('one tou'), const('abcdefgh'), const('fortytwo'), const('')]
384 return s2[j] in s1[i]
385 for i in range(2):
386 for j in range(7):
387 res = self.interpret(fn, [i,j])
388 assert res == fn(i, j)
389
390 def test_find_with_start(self):
391 const = self.const
392 def fn(i):
393 assert i >= 0
394 return const('ababcabc').find(const('abc'), i)
395 for i in range(9):
396 res = self.interpret(fn, [i])
397 assert res == fn(i)
398
399 def test_find_with_start_end(self):
400 const = self.const
401 def fn(i, j):
402 assert i >= 0
403 assert j >= 0
404 return (const('ababcabc').find(const('abc'), i, j) +
405 const('ababcabc').find(const('b'), i, j) * 100)
406 for (i, j) in [(1,7), (2,6), (3,7), (3,8), (4,99), (7, 99)]:
407 res = self.interpret(fn, [i, j])
408 assert res == fn(i, j)
409
410 def test_find_AnnotatorError(self):
411 const = self.const
412 def f():
413 s = const('abc')
414 s.find(s, 0, -10)
415 py.test.raises(AnnotatorError, self.interpret, f, ())
416 def f():
417 s = const('abc')
418 s.find(s, -10)
419 py.test.raises(AnnotatorError, self.interpret, f, ())
420
421 def test_find_empty_string(self):
422 const = self.const
423 def f(i):
424 assert i >= 0
425 s = const("abc")
426 x = s.find(const(''))
427 x+= s.find(const(''), i)*10
428 x+= s.find(const(''), i, i)*100
429 x+= s.find(const(''), i, i+1)*1000
430 return x
431 for i, expected in enumerate([0, 1110, 2220, 3330, -1110, -1110]):
432 res = self.interpret(f, [i])
433 assert res == expected
434
435 def test_rfind(self):
436 const = self.const
437 def fn():
438 # string-searching versions
439 return (const('aaa').rfind(const('aa')) +
440 const('aaa').rfind(const('aa'), 1) * 10 +
441 const('aaa').rfind(const('aa'), 1, 2) * 100 +
442 const('aaa').rfind(const('aa'), 3, 42) * 1000 +
443 # char-searching versions
444 const('aaa').rfind(const('a')) * 10000 +
445 const('aaa').rfind(const('a'), 1) * 100000 +
446 const('aaa').rfind(const('a'), 1, 2) * 1000000 +
447 const('aaa').rfind(const('a'), 3, 42) * 10000000)
448 res = self.interpret(fn, [])
449 assert res == fn()
450
451 def test_rfind_empty_string(self):
452 const = self.const
453 def f(i):
454 assert i >= 0
455 s = const("abc")
456 x = s.rfind(const(''))
457 x+= s.rfind(const(''), i)*10
458 x+= s.rfind(const(''), i, i)*100
459 x+= s.rfind(const(''), i, i+1)*1000
460 return x
461 for i, expected in enumerate([1033, 2133, 3233, 3333, 3-1110, 3-1110]):
462 res = self.interpret(f, [i])
463 assert res == expected
464
465 def test_rfind_error_message(self):
466 const = self.const
467 def f(i):
468 return const("abc").rfind(const(''), i)
469 e = py.test.raises(AnnotatorError, self.interpret, f, [-5])
470 assert "rfind: not proven to have non-negative start" in str(e.value)
471
472 def test_find_char(self):
473 const = self.const
474 def fn(ch):
475 pos1 = const('aiuwraz 483').find(ch)
476 pos2 = const('aiuwraz 483').rfind(ch)
477 return pos1 + (pos2*100)
478 for ch in const('a ?3'):
479 res = self.interpret(fn, [ch])
480 assert res == fn(ch)
481
482 def test_strip(self):
483 const = self.const
484 def both():
485 return const('!ab!').strip(const('!'))
486 def left():
487 return const('!ab!').lstrip(const('!'))
488 def right():
489 return const('!ab!').rstrip(const('!'))
490 def empty():
491 return const(' ').strip(' ')
492 def left2():
493 return const('a ').strip(' ')
494 def leftall():
495 return const('!!').lstrip(const('!'))
496 res = self.interpret(both, [])
497 assert self.ll_to_string(res) == const('ab')
498 res = self.interpret(left, [])
499 assert self.ll_to_string(res) == const('ab!')
500 res = self.interpret(right, [])
501 assert self.ll_to_string(res) == const('!ab')
502 res = self.interpret(empty, [])
503 assert self.ll_to_string(res) == const('')
504 res = self.interpret(left2, [])
505 assert self.ll_to_string(res) == const('a')
506 res = self.interpret(leftall, [])
507 assert self.ll_to_string(res) == const('')
508
509 def test_strip_multiple_chars(self):
510 const = self.const
511 def both():
512 return const('!ab!').strip(const('!a'))
513 def left():
514 return const('!+ab!').lstrip(const('!+'))
515 def right():
516 return const('!ab!+').rstrip(const('!+'))
517 def empty():
518 return const(' \t\t ').strip('\t ')
519 def left2():
520 return const('a ').strip(' \t')
521 def leftall():
522 return const('!ab!').lstrip(const('!ab'))
523 res = self.interpret(both, [])
524 assert self.ll_to_string(res) == const('b')
525 res = self.interpret(left, [])
526 assert self.ll_to_string(res) == const('ab!')
527 res = self.interpret(right, [])
528 assert self.ll_to_string(res) == const('!ab')
529 res = self.interpret(empty, [])
530 assert self.ll_to_string(res) == const('')
531 res = self.interpret(left2, [])
532 assert self.ll_to_string(res) == const('a')
533 res = self.interpret(leftall, [])
534 assert self.ll_to_string(res) == const('')
535
536 def test_upper(self):
537 const = self.const
538 constchar = self.constchar
539 strings = [const(''), const(' '), const('upper'), const('UpPeR'), const(',uppEr,')]
540 for i in range(256): strings.append(constchar(i))
541 def fn(i):
542 return strings[i].upper()
543 for i in range(len(strings)):
544 res = self.interpret(fn, [i])
545 assert self.ll_to_string(res) == fn(i)
546
547 def test_lower(self):
548 const = self.const
549 strings = [const(''), const(' '), const('lower'), const('LoWeR'), const(',lowEr,')]
550 for i in range(256): strings.append(chr(i))
551 def fn(i):
552 return strings[i].lower()
553 for i in range(len(strings)):
554 res = self.interpret(fn, [i])
555 assert self.ll_to_string(res) == fn(i)
556
557 def test_join(self):
558 const = self.const
559 res = self.interpret(lambda: const('').join([]), [])
560 assert self.ll_to_string(res) == ""
561
562 res = self.interpret(lambda: const('').join([const('a'), const('b'), const('c')]), [])
563 assert self.ll_to_string(res) == "abc"
564
565 res = self.interpret(lambda: const('').join([const('abc'), const('de'), const('fghi')]), [])
566 assert self.ll_to_string(res) == "abcdefghi"
567
568 res = self.interpret(lambda: const('.').join([const('abc'), const('def')]), [])
569 assert self.ll_to_string(res) == const('abc.def')
570
571 def fn(i, j):
572 s1 = [ const(''), const(','), const(' and ')]
573 s2 = [ [], [const('foo')], [const('bar'), const('baz'), const('bazz')]]
574 return s1[i].join(s2[j])
575 for i in range(3):
576 for j in range(3):
577 res = self.interpret(fn, [i,j])
578 assert self.ll_to_string(res) == fn(i, j)
579
580 def fn(i, j):
581 s1 = [ const(''), const(','), const(' and ')]
582 s2 = [ [], [const('foo')], [const('bar'), const('baz'), const('bazz')]]
583 s2[1].extend([const('x')])
584 return s1[i].join(s2[j])
585 for i in range(3):
586 for j in range(3):
587 res = self.interpret(fn, [i,j])
588 assert self.ll_to_string(res) == fn(i, j)
589
590 def fn(i):
591 c = ["a", "b", "c"]
592 assert i >= 0
593 return const('').join(c[i:])
594 res = self.interpret(fn, [0])
595 assert self.ll_to_string(res) == const("abc")
596
597 def test_str_slice(self):
598 const = self.const
599 def fn(n):
600 s = [const('hello'), const('world')][n] # non-constant
601 s1 = s[:3]
602 s2 = s[3:]
603 s3 = s[3:10]
604 s4 = s[42:44]
605 return (s1+s2 == s and
606 s2+s1 == const('lohel') and
607 s1+s3 == s and
608 s4 == const(''))
609 res = self.interpret(fn, [0])
610 assert res
611
612 def test_str_slice_minusone(self):
613 const = self.const
614 def fn(n):
615 s = const('hello')
616 z = const('h')
617 lst = [s, z] # uncontantify s and z
618 s = lst[n]
619 z = lst[n+1]
620 return s[:-1]+z[:-1]
621 res = self.interpret(fn, [0])
622 assert self.ll_to_string(res) == const('hell')
623
624 def test_strformat(self):
625 const = self.const
626 def percentS(s):
627 return const("before %s after") % (s,)
628
629 res = self.interpret(percentS, [const('1')])
630 assert self.ll_to_string(res) == const('before 1 after')
631
632 def percentD(i):
633 return "bing %d bang" % (i,)
634
635 res = self.interpret(percentD, [23])
636 assert self.ll_to_string(res) == const('bing 23 bang')
637
638 def percentX(i):
639 return const("bing %x bang") % (i,)
640
641 res = self.interpret(percentX, [23])
642 assert self.ll_to_string(res) == const('bing 17 bang')
643
644 res = self.interpret(percentX, [-123])
645 assert self.ll_to_string(res) == const('bing -7b bang')
646
647 def percentO(i):
648 return const("bing %o bang") % (i,)
649
650 res = self.interpret(percentO, [23])
651 assert self.ll_to_string(res) == const('bing 27 bang')
652
653 res = self.interpret(percentO, [-123])
654 assert self.ll_to_string(res) == const('bing -173 bang')
655
656 def moreThanOne(s, d, x, o):
657 return const("string: %s decimal: %d hex: %x oct: %o") % (s, d, x, o)
658
659 args = const('a'), 2, 3, 4
660 res = self.interpret(moreThanOne, list(args))
661 assert self.ll_to_string(res) == moreThanOne(*args)
662
663 def test_strformat_nontuple(self):
664 const = self.const
665 def percentD(i):
666 return const("before %d after") % i
667
668 res = self.interpret(percentD, [1])
669 assert self.ll_to_string(res) == const('before 1 after')
670
671 def percentS(i):
672 return const("before %s after") % i
673
674 res = self.interpret(percentS, [const('D')])
675 assert self.ll_to_string(res) == const('before D after')
676
677 def test_strformat_instance(self):
678 class C:
679 pass
680 class D(C):
681 pass
682 def dummy(i):
683 if i:
684 x = C()
685 else:
686 x = D()
687 return str(x)
688
689 res = self.ll_to_string(self.interpret(dummy, [1]))
690 assert res.startswith('<')
691 assert res.find('C object') != -1
692 assert res.endswith('>')
693
694 res = self.ll_to_string(self.interpret(dummy, [0]))
695 assert res.startswith('<')
696 assert res.find('D object') != -1
697 assert res.endswith('>')
698
699 def test_percentformat_instance(self):
700 class C:
701 pass
702 class D(C):
703 pass
704
705 def dummy(i):
706 if i:
707 x = C()
708 y = D()
709 else:
710 x = D()
711 y = C()
712 return "what a nice %s, much nicer than %r"%(x, y)
713
714 res = self.ll_to_string(self.interpret(dummy, [1]))
715 res = res.replace('rpython.rtyper.test.test_rstr.', '')
716 assert res.find('what a nice <C object') != -1
717 assert res.find('>, much nicer than <D object') != -1
718
719 res = self.ll_to_string(self.interpret(dummy, [0]))
720 res = res.replace('rpython.rtyper.test.test_rstr.', '')
721 assert res.find('what a nice <D object') != -1
722 assert res.find('>, much nicer than <C object') != -1
723
724 def test_percentformat_tuple(self):
725 for t, expected in [((), "<<<()>>>"),
726 ((5,), "<<<(5,)>>>"),
727 ((5, 6), "<<<(5, 6)>>>"),
728 ((5, 6, 7), "<<<(5, 6, 7)>>>")]:
729 def getter():
730 return t
731 def dummy():
732 return "<<<%s>>>" % (getter(),)
733
734 res = self.ll_to_string(self.interpret(dummy, []))
735 assert res == expected
736
737 def test_percentformat_list(self):
738 for t, expected in [([], "<<<[]>>>"),
739 ([5], "<<<[5]>>>"),
740 ([5, 6], "<<<[5, 6]>>>"),
741 ([5, 6, 7], "<<<[5, 6, 7]>>>")]:
742 def getter():
743 return t
744 def dummy():
745 return "<<<%s>>>" % (getter(),)
746
747 res = self.ll_to_string(self.interpret(dummy, []))
748 assert res == expected
749
750 def test_splitlines(self):
751 const = self.const
752 def f(i, newlines):
753 s = [const(''), const("\n"), const("\n\n"), const("hi\n"),
754 const("random data\r\n"), const("\r\n"), const("\rdata")]
755 test_string = s[i]
756 if newlines:
757 return len(test_string.splitlines(True))
758 else:
759 return len(test_string.splitlines())
760 for newlines in (True, False):
761 for i in xrange(5):
762 res = self.interpret(f, [i, newlines])
763 assert res == f(i, newlines)
764
765 def _make_split_test(self, split_fn):
766 const = self.const
767 def fn(i):
768 try:
769 s = [const(''), const('0.1.2.4.8'), const('.1.2'), const('1.2.'), const('.1.2.4.')][i]
770 l = getattr(s, split_fn)(const('.'))
771 sum = 0
772 for num in l:
773 if len(num):
774 sum += ord(num[0]) - ord(const('0')[0])
775 return sum + len(l) * 100
776 except MemoryError:
777 return 42
778 return fn
779
780 def test_split(self):
781 fn = self._make_split_test('split')
782 for i in range(5):
783 res = self.interpret(fn, [i])
784 assert res == fn(i)
785
786 def test_split_multichar(self):
787 l = ["abc::z", "abc", "abc::def:::x"]
788 exp = [["abc", "z"], ["abc"], ["abc", "def", ":x"]]
789 exp2 = [["abc", "z"], ["abc"], ["abc", "def:::x"]]
790
791 def f(i):
792 s = l[i]
793 return s.split("::") == exp[i] and s.split("::", 1) == exp2[i]
794
795 for i in range(3):
796 res = self.interpret(f, [i])
797 assert res == True
798
799 def test_rsplit_multichar(self):
800 l = ["abc::z", "abc", "abc::def:::x"]
801 exp = [["abc", "z"], ["abc"], ["abc", "def:", "x"]]
802 exp2 = [["abc", "z"], ["abc"], ["abc::def:", "x"]]
803
804 def f(i):
805 s = l[i]
806 return s.rsplit("::") == exp[i] and s.rsplit("::", 1) == exp2[i]
807
808 for i in range(3):
809 res = self.interpret(f, [i])
810 assert res == True
811
812 def test_rsplit(self):
813 fn = self._make_split_test('rsplit')
814 for i in range(5):
815 res = self.interpret(fn, [i])
816 assert res == fn(i)
817
818 def _make_split_limit_test(self, split_fn):
819 const = self.const
820 def fn(i, j):
821 s = [const(''), const('0.1.2.4.8'), const('.1.2'), const('1.2.'), const('.1.2.4.')][i]
822 l = getattr(s, split_fn)(const('.'), j)
823 sum = 0
824 for num in l:
825 if len(num):
826 sum += ord(num[0]) - ord(const('0')[0])
827 return sum + len(l) * 100
828 return fn
829
830 def test_split_limit(self):
831 fn = self._make_split_limit_test('split')
832 for i in range(5):
833 for j in range(4):
834 res = self.interpret(fn, [i, j])
835 assert res == fn(i, j)
836
837 def test_rsplit_limit(self):
838 fn = self._make_split_limit_test('rsplit')
839 for i in range(5):
840 for j in range(4):
841 res = self.interpret(fn, [i, j])
842 assert res == fn(i, j)
843
844 def test_contains(self):
845 const = self.const
846 constchar = self.constchar
847 def fn(i):
848 s = const('Hello world')
849 return constchar(i) in s
850 for i in range(256):
851 res = self.interpret(fn, [i])#, view=i==42)
852 assert res == fn(i)
853
854 def test_replace(self):
855 const = self.const
856 def fn(c1, c2):
857 s = const('abbccc')
858 s = s.replace(c1, c2)
859 res = 0
860 for c in s:
861 if c == c2:
862 res += 1
863 return res
864 res = self.interpret(fn, [const('a'), const('c')])
865 assert res == 4
866 res = self.interpret(fn, [const('c'), const('b')])
867 assert res == 5
868
869 def test_replace_TyperError(self):
870 const = self.const
871 def fn():
872 s = const('abbccc')
873 s = s.replace(const('a'), const('baz'))
874 py.test.raises(TyperError, self.interpret, fn, ())
875 def fn():
876 s = const('abbccc')
877 s = s.replace(const('abb'), const('c'))
878 py.test.raises(TyperError, self.interpret, fn, ())
879
880 def test_int(self):
881 const = self.const
882 s1 = [ const('42'), const('01001'), const('abc'), const('ABC'), const('4aBc'), const(' 12ef '), const('+42'), const('foo'), const('42foo'), const('42.1'), const(''), const('+ 42')]
883 def fn(i, base):
884 s = s1[i]
885 res = int(s, base)
886 return res
887 for j in (10, 16, 2, 1, 36, 42, -3):
888 for i in range(len(s1)):
889 try:
890 expected = fn(i, j)
891 except ValueError:
892 self.interpret_raises(ValueError, fn, [i, j])
893 else:
894 res = self.interpret(fn, [i, j])
895 assert res == expected
896
897 def test_int_valueerror(self):
898 const = self.const
899 s1 = [const('42g'), const('?'), const('+'), const('+ ')]
900 def fn(i):
901 try:
902 return int(s1[i])
903 except ValueError:
904 return -654
905 res = self.interpret(fn, [0])
906 assert res == -654
907 res = self.interpret(fn, [1])
908 assert res == -654
909 res = self.interpret(fn, [2])
910 assert res == -654
911
912 def test_float(self):
913 const = self.const
914 f = [const(''), const(' '), const('0'), const('1'), const('-1.5'), const('1.5E2'), const('2.5e-1'), const(' 0 '), const('?')]
915 def fn(i):
916 s = f[i]
917 return float(s)
918
919 for i in range(len(f)):
920 try:
921 expected = fn(i)
922 except ValueError:
923 self.interpret_raises(ValueError, fn, [i])
924 else:
925 res = self.interpret(fn, [i])
926 assert res == expected
927
928 def test_char_mul_n(self):
929 const = self.const
930 def f(c, n):
931 return c*n
932 res = self.interpret(f, [const('a'), 4])
933 assert self.ll_to_string(res) == 'a'*4
934 res = self.interpret(f, [const('a'), 0])
935 assert self.ll_to_string(res) == ""
936
937 def test_char_mul_negative(self):
938 const = self.const
939 def f(c):
940 return c * -3
941
942 res = self.interpret(f, [const('a')])
943 assert self.ll_to_string(res) == ''
944
945 def test_n_mul_char(self):
946 const = self.const
947 def f(c, n):
948 return n*c
949 res = self.interpret(f, [const('a'), 4])
950 assert self.ll_to_string(res) == 'a'*4
951 res = self.interpret(f, [const('a'), 0])
952 assert self.ll_to_string(res) == ""
953
954 EMPTY_STRING_HASH = -1 # unless overridden
955
956 def test_hash(self):
957 from rpython.rlib.objectmodel import compute_hash
958 const = self.const
959 def fn(i):
960 if i == 0:
961 s = const('')
962 else:
963 s = const("xxx")
964 return compute_hash(s)
965 res = self.interpret(fn, [0])
966 assert res == self.EMPTY_STRING_HASH
967 res = self.interpret(fn, [1])
968 assert typeOf(res) == Signed
969
970 def test_call_str_on_string(self):
971 const = self.const
972 def fn(i):
973 s = const("x") * i
974 return const(s)
975 res = self.interpret(fn, [3])
976 assert self.ll_to_string(res) == 'xxx'
977
978 def test_count_char(self):
979 const = self.const
980 def fn(i):
981 s = const("").join([const("abcasd")] * i)
982 return s.count(const("a")) + s.count(const("a"), 2) + \
983 s.count(const("b"), 1, 6) + s.count(const("a"), 5, 99)
984 res = self.interpret(fn, [4])
985 assert res == 8 + 7 + 1 + 6
986
987 def test_count(self):
988 const = self.const
989 def fn(i):
990 s = const("").join([const("abcabsd")] * i)
991 one = i / i # confuse the annotator
992 return (s.count(const("abc")) + const("abcde").count(const("")) +
993 const("abcda").count(const("a") * one) +
994 s.count(const("ab"), 0, 999))
995 res = self.interpret(fn, [4])
996 assert res == 4 + 6 + 2 + 8
997
998 def test_count_overlapping_occurences(self):
999 const = self.const
1000 def fn():
1001 return const('ababa').count(const('aba'))
1002 res = self.interpret(fn, [])
1003 assert res == 1
1004
1005 def test_count_AnnotatorError(self):
1006 const = self.const
1007 def f():
1008 s = const('abc')
1009 s.count(s, 0, -10)
1010 py.test.raises(AnnotatorError, self.interpret, f, ())
1011 def f():
1012 s = const('abc')
1013 s.count(s, -10)
1014 py.test.raises(AnnotatorError, self.interpret, f, ())
1015
1016 def test_count_in_empty_string(self):
1017 const = self.const
1018 def fn():
1019 return const('').count(const('ab'))
1020 res = self.interpret(fn, [])
1021 assert res == 0
1022
1023 def test_getitem_exc(self):
1024 const = self.const
1025 def f(x):
1026 s = const("z")
1027 return s[x]
1028
1029 res = self.interpret(f, [0])
1030 assert res == 'z'
1031 with py.test.raises(LLAssertFailure):
1032 self.interpret(f, [1])
1033
1034 def f(x):
1035 s = const("z")
1036 try:
1037 return s[x]
1038 except IndexError:
1039 return const('X')
1040 except Exception:
1041 return const(' ')
1042
1043 res = self.interpret(f, [0])
1044 assert res == 'z'
1045 res = self.interpret(f, [1])
1046 assert res == 'X'
1047
1048 def f(x):
1049 s = const("z")
1050 try:
1051 return s[x]
1052 except Exception:
1053 return const(' ')
1054
1055 res = self.interpret(f, [0])
1056 assert res == 'z'
1057 res = self.interpret(f, [1])
1058 assert res == ' '
1059
1060 def f(x):
1061 s = const("z")
1062 try:
1063 return s[x]
1064 except ValueError:
1065 return const(' ')
1066
1067 res = self.interpret(f, [0])
1068 assert res == 'z'
1069 with py.test.raises(LLAssertFailure):
1070 self.interpret(f, [1])
1071
1072 def test_fold_concat(self):
1073 const = self.const
1074 def g(tail):
1075 return const("head")+tail
1076 def f():
1077 return g(const("tail"))
1078 from rpython.conftest import option
1079
1080 t, typer, fgraph = self.gengraph(f, [], backendopt=True)
1081 if option.view:
1082 t.view()
1083 assert summary(fgraph) == {}
1084
1085 def test_inplace_add(self):
1086 from rpython.rtyper.annlowlevel import hlstr
1087 const = self.const
1088 def f(x, y):
1089 y = const(hlstr(y))
1090 if x > 0:
1091 l = [const('a'), const('b')]
1092 else:
1093 l = [const('a')]
1094 l += y # list += string
1095 return const('').join(l)
1096
1097 assert self.ll_to_string(self.interpret(f, [1,
1098 self.string_to_ll('abc')])) == 'ababc'
1099
1100 def test_hlstr(self):
1101 const = self.const
1102 from rpython.rtyper.annlowlevel import hlstr
1103 def f(s):
1104 return const("*")+const(hlstr(s))+const("*") == const("*abba*")
1105
1106 res = self.interpret(f, [self.string_to_ll(const("abba"))])
1107 assert res
1108
1109 def test_prebuilt_ll_strings(self):
1110 llstr0 = self.string_to_ll(None)
1111 assert not llstr0
1112 llstr1 = self.string_to_ll("hello")
1113 def f(i):
1114 if i == 0:
1115 return llstr0
1116 else:
1117 return llstr1
1118 res = self.interpret(f, [0])
1119 assert self.ll_to_string(res) is None
1120 res = self.interpret(f, [1])
1121 assert self.ll_to_string(res) == "hello"
1122
1123 def test_str_unichar(self):
1124 def f(i):
1125 c = u"abc"
1126 return str(c[i])[0]
1127 assert self.interpret(f, [1]) == "b"
1128
1129 def test_encode_char(self):
1130 def f(i):
1131 c = u"abc"
1132 return c[i].encode("ascii")
1133 assert self.ll_to_string(self.interpret(f, [0])) == "a"
1134
1135 def test_encode_char_latin1(self):
1136 def f(i):
1137 c = u"abc"
1138 return c[i].encode("latin-1")
1139 assert self.ll_to_string(self.interpret(f, [0])) == "a"
1140
1141 def test_str_none(self):
1142 const = self.const
1143 def g():
1144 pass
1145 def f(i):
1146 if i > 5:
1147 u = None
1148 else:
1149 u = const('xxx')
1150 g() # hack for flow object space
1151 return str(u)
1152 assert self.ll_to_string(self.interpret(f, [3])) == 'xxx'
1153 got = self.interpret(f, [7])
1154 assert self.ll_to_string(got) == 'None'
1155
1156 def test_enumerate(self):
1157 const = self.const
1158 def fn(n):
1159 s = const('abcde')
1160 for i, x in enumerate(s):
1161 if i == n:
1162 return x
1163 return const('x')
1164 res = self.interpret(fn, [2])
1165 assert res == 'c'
1166
1167
1168 def FIXME_test_str_to_pystringobj():
1169 def f(n):
1170 if n >= 0:
1171 return "hello"[n:]
1172 else:
1173 return None
1174 def g(n):
1175 if n == -2:
1176 return 42
1177 return f(n)
1178 res = interpret(g, [-1])
1179 assert res._obj.value == None
1180 res = interpret(g, [1])
1181 assert res._obj.value == "ello"
1182 res = interpret(g, [-2])
1183 assert res._obj.value == 42
1184
1185 class TestRstr(AbstractTestRstr):
1186 const = str
1187 constchar = chr
1188
1189 def test_lower_char(self):
1190 def fn(i):
1191 return chr(i).lower()
1192 for c in ["a", "A", "1"]:
1193 assert self.interpret(fn, [ord(c)]) == c.lower()
1194
1195 def test_upper_char(self):
1196 def fn(i):
1197 return chr(i).upper()
1198 for c in ["a", "A", "1"]:
1199 assert self.interpret(fn, [ord(c)]) == c.upper()
1200
1201 def test_ll_find_rfind(self):
1202 llstr = self.string_to_ll
1203
1204 for i in range(50):
1205 n1 = random.randint(0, 10)
1206 s1 = ''.join([random.choice("ab") for i in range(n1)])
1207 n2 = random.randint(0, 5)
1208 s2 = ''.join([random.choice("ab") for i in range(n2)])
1209 res = LLHelpers.ll_find(llstr(s1), llstr(s2), 0, n1)
1210 assert res == s1.find(s2)
1211 res = LLHelpers.ll_rfind(llstr(s1), llstr(s2), 0, n1)
1212 assert res == s1.rfind(s2)
1213
1214 def test_hash_via_type(self):
1215 from rpython.rlib.objectmodel import compute_hash
1216
1217 def f(n):
1218 s = malloc(STR, n)
1219 s.hash = 0
1220 for i in range(n):
1221 s.chars[i] = chr(i)
1222 return s.gethash() - compute_hash('\x00\x01\x02\x03\x04')
1223
1224 res = self.interpret(f, [5])
1225 assert res == 0
1226
1227 def test_copy_string_to_raw(self):
1228 from rpython.rtyper.lltypesystem import lltype, llmemory
1229 from rpython.rtyper.annlowlevel import llstr
1230 from rpython.rtyper.lltypesystem.rstr import copy_string_to_raw
1231
1232 def f(buf, n):
1233 s = 'abc' * n
1234 ll_s = llstr(s)
1235 copy_string_to_raw(ll_s, buf, 0, n*3)
1236
1237 TP = lltype.Array(lltype.Char)
1238 array = lltype.malloc(TP, 12, flavor='raw')
1239 f(array, 4)
1240 assert list(array) == list('abc'*4)
1241 lltype.free(array, flavor='raw')
1242
1243 array = lltype.malloc(TP, 12, flavor='raw')
1244 self.interpret(f, [array, 4])
1245 assert list(array) == list('abc'*4)
1246 lltype.free(array, flavor='raw')
1247
1248 def test_strip_no_arg(self):
1249 strings = [" xyz ", "", "\t\vx"]
1250
1251 def f(i):
1252 return strings[i].strip()
1253
1254 res = self.interpret(f, [0])
1255 assert hlstr(res) == "xyz"
1256 res = self.interpret(f, [1])
1257 assert hlstr(res) == ""
1258 res = self.interpret(f, [2])
1259 assert hlstr(res) == "x"