Debian Codegraph @

rpython/rlib/rope.py

raw symbols SCIP
1 import py
2 import sys
3 import math
4
5 from rpython.rlib.rarithmetic import intmask, ovfcheck
6 from rpython.rlib.rarithmetic import r_uint, LONG_BIT
7
8 LOG2 = math.log(2)
9 NBITS = int(math.log(sys.maxint) / LOG2) + 2
10
11 # XXX should optimize the numbers
12 NEW_NODE_WHEN_LENGTH = 32
13 CONVERT_WHEN_SMALLER = 8
14 MAX_DEPTH = 32 # maybe should be smaller
15 CONCATENATE_WHEN_MULTIPLYING = 128
16 HIGHEST_BIT_SET = intmask(1L << (NBITS - 1))
17
18 def find_fib_index(l):
19 if l == 0:
20 return -1
21 a, b = 1, 2
22 i = 0
23 while 1:
24 if a <= l < b:
25 return i
26 a, b = b, a + b
27 i += 1
28
29 mul_by_1000003_pow_table = [intmask(pow(1000003, 2**_i, 2**LONG_BIT))
30 for _i in range(LONG_BIT)]
31
32 def masked_mul_by_1000003_pow(a, b):
33 """Computes intmask(a * (1000003**b))."""
34 index = 0
35 b = r_uint(b)
36 while b:
37 if b & 1:
38 a = intmask(a * mul_by_1000003_pow_table[index])
39 b >>= 1
40 index += 1
41 return a
42
43
44 class GlobalRopeInfo(object):
45 """contains data that is "global" to the whole string, e.g. requires
46 an iteration over the whole string"""
47 def __init__(self):
48 self.charbitmask = 0
49 self.hash = 0
50 self.is_bytestring = False
51 self.is_ascii = False
52
53 def combine(self, other, rightlength):
54 result = GlobalRopeInfo()
55 result.charbitmask = self.charbitmask | other.charbitmask
56 h1 = self.hash
57 h2 = other.hash
58 x = intmask(h2 + masked_mul_by_1000003_pow(h1, rightlength))
59 x |= HIGHEST_BIT_SET
60 result.hash = x
61 result.is_ascii = self.is_ascii and other.is_ascii
62 result.is_bytestring = self.is_bytestring and other.is_bytestring
63 return result
64
65
66 class StringNode(object):
67 _additional_info = None
68 def additional_info(self):
69 addinfo = self._additional_info
70 if addinfo is None:
71 return self.compute_additional_info()
72 return addinfo
73
74 def compute_additional_info(self):
75 raise NotImplementedError("base class")
76
77 def length(self):
78 raise NotImplementedError("base class")
79
80 def is_ascii(self):
81 raise NotImplementedError("base class")
82
83 def is_bytestring(self):
84 raise NotImplementedError("base class")
85
86 def depth(self):
87 return 0
88
89 def hash_part(self):
90 raise NotImplementedError("base class")
91
92 def charbitmask(self):
93 raise NotImplementedError("base class")
94
95 def check_balanced(self):
96 return True
97
98 def getchar(self, index):
99 raise NotImplementedError("abstract base class")
100
101 def getunichar(self, index):
102 raise NotImplementedError("abstract base class")
103
104 def getint(self, index):
105 raise NotImplementedError("abstract base class")
106
107 def getrope(self, index):
108 raise NotImplementedError("abstract base class")
109
110 def getslice(self, start, stop):
111 raise NotImplementedError("abstract base class")
112
113 def can_contain_int(self, value):
114 return True #conservative default
115
116 def view(self):
117 view([self])
118
119 def rebalance(self):
120 return self
121
122 def flatten_string(self):
123 raise NotImplementedError("abstract base class")
124
125 def flatten_unicode(self):
126 raise NotImplementedError("abstract base class")
127
128 def _concat(self, other):
129 raise NotImplementedError("abstract base class")
130
131 def __add__(self, other):
132 return concatenate(self, other)
133
134 def _cleanup_(self):
135 self.additional_info()
136
137 class LiteralNode(StringNode):
138 def find_int(self, what, start, stop):
139 raise NotImplementedError("abstract base class")
140
141
142
143 class LiteralStringNode(LiteralNode):
144 def __init__(self, s):
145 assert isinstance(s, str)
146 self.s = s
147
148 def length(self):
149 return len(self.s)
150
151 def is_ascii(self):
152 return self.additional_info().is_ascii
153
154 def is_bytestring(self):
155 return True
156
157 def flatten_string(self):
158 return self.s
159
160 def flatten_unicode(self):
161 return self.s.decode('latin-1')
162
163 def hash_part(self):
164 return self.additional_info().hash
165
166 def compute_additional_info(self):
167 additional_info = GlobalRopeInfo()
168 is_ascii = True
169 charbitmask = 0
170 partial_hash = 0
171 for c in self.s:
172 ordc = ord(c)
173 partial_hash = (1000003*partial_hash) + ord(c)
174 if ordc >= 128:
175 is_ascii = False
176 charbitmask |= intmask(1 << (ordc & 0x1F))
177 partial_hash = intmask(partial_hash)
178 partial_hash |= HIGHEST_BIT_SET
179
180 additional_info.hash = partial_hash
181 additional_info.is_ascii = is_ascii
182 additional_info.charbitmask = charbitmask
183 additional_info.is_bytestring = True
184 self._additional_info = additional_info
185 return additional_info
186
187 def charbitmask(self):
188 return self.additional_info().charbitmask
189
190 def getchar(self, index):
191 return self.s[index]
192
193 def getunichar(self, index):
194 return unichr(ord(self.s[index]))
195
196 def getint(self, index):
197 return ord(self.s[index])
198
199 def getrope(self, index):
200 return LiteralStringNode.PREBUILT[ord(self.s[index])]
201
202 def can_contain_int(self, value):
203 if value > 255:
204 return False
205 if self.is_ascii() and value > 127:
206 return False
207 return (1 << (value & 0x1f)) & self.charbitmask()
208
209 def getslice(self, start, stop):
210 assert 0 <= start <= stop
211 return LiteralStringNode(self.s[start:stop])
212
213
214 def find_int(self, what, start, stop):
215 if not self.can_contain_int(what):
216 return -1
217 return self.s.find(chr(what), start, stop)
218
219 def _concat(self, other):
220 if (isinstance(other, LiteralStringNode) and
221 len(other.s) + len(self.s) < NEW_NODE_WHEN_LENGTH):
222 return LiteralStringNode(self.s + other.s)
223 elif (isinstance(other, LiteralUnicodeNode) and
224 len(other.u) + len(self.s) < NEW_NODE_WHEN_LENGTH and
225 len(self.s) < CONVERT_WHEN_SMALLER):
226 return LiteralUnicodeNode(self.s.decode("latin-1") + other.u)
227 return BinaryConcatNode(self, other)
228
229 def dot(self, seen, toplevel=False):
230 if self in seen:
231 return
232 seen[self] = True
233 addinfo = str(self.s).replace('"', "'") or "_"
234 if len(addinfo) > 10:
235 addinfo = addinfo[:3] + "..." + addinfo[-3:]
236 yield ('"%s" [shape=box,label="length: %s\\n%s"];' % (
237 id(self), len(self.s),
238 repr(addinfo).replace('"', '').replace("\\", "\\\\")))
239 LiteralStringNode.EMPTY = LiteralStringNode("")
240 LiteralStringNode.PREBUILT = [LiteralStringNode(chr(i)) for i in range(256)]
241 del i
242
243
244 class LiteralUnicodeNode(LiteralNode):
245 def __init__(self, u):
246 assert isinstance(u, unicode)
247 self.u = u
248
249 def length(self):
250 return len(self.u)
251
252 def flatten_unicode(self):
253 return self.u
254
255 def is_ascii(self):
256 return False # usually not
257
258 def is_bytestring(self):
259 return False
260
261 def hash_part(self):
262 return self.additional_info().hash
263
264 def compute_additional_info(self):
265 additional_info = GlobalRopeInfo()
266 charbitmask = 0
267 partial_hash = 0
268 for c in self.u:
269 ordc = ord(c)
270 charbitmask |= intmask(1 << (ordc & 0x1F))
271 partial_hash = (1000003*partial_hash) + ordc
272 partial_hash = intmask(partial_hash)
273 partial_hash |= HIGHEST_BIT_SET
274
275 additional_info.charbitmask = intmask(charbitmask)
276 additional_info.hash = partial_hash
277 self._additional_info = additional_info
278 return additional_info
279
280 def charbitmask(self):
281 return self.additional_info().charbitmask
282
283 def getunichar(self, index):
284 return self.u[index]
285
286 def getint(self, index):
287 return ord(self.u[index])
288
289 def getrope(self, index):
290 ch = ord(self.u[index])
291 if ch < 256:
292 return LiteralStringNode.PREBUILT[ch]
293 if len(self.u) == 1:
294 return self
295 return LiteralUnicodeNode(unichr(ch))
296
297 def can_contain_int(self, value):
298 return (1 << (value & 0x1f)) & self.charbitmask()
299
300 def getslice(self, start, stop):
301 assert 0 <= start <= stop
302 return LiteralUnicodeNode(self.u[start:stop])
303
304 def find_int(self, what, start, stop):
305 if not self.can_contain_int(what):
306 return -1
307 return self.u.find(unichr(what), start, stop)
308
309 def _concat(self, other):
310 if (isinstance(other, LiteralUnicodeNode) and
311 len(other.u) + len(self.u) < NEW_NODE_WHEN_LENGTH):
312 return LiteralUnicodeNode(self.u + other.u)
313 elif (isinstance(other, LiteralStringNode) and
314 len(other.s) + len(self.u) < NEW_NODE_WHEN_LENGTH and
315 len(other.s) < CONVERT_WHEN_SMALLER):
316 return LiteralUnicodeNode(self.u + other.s.decode("latin-1"))
317 return BinaryConcatNode(self, other)
318
319 def dot(self, seen, toplevel=False):
320 if self in seen:
321 return
322 seen[self] = True
323 addinfo = repr(self.u).replace('"', "'") or "_"
324 if len(addinfo) > 10:
325 addinfo = addinfo[:3] + "..." + addinfo[-3:]
326 yield ('"%s" [shape=box,label="length: %s\\n%s"];' % (
327 id(self), len(self.u),
328 repr(addinfo).replace('"', '').replace("\\", "\\\\")))
329
330 def make_binary_get(getter):
331 def get(self, index):
332 while isinstance(self, BinaryConcatNode):
333 llen = self.left.length()
334 if index >= llen:
335 self = self.right
336 index -= llen
337 else:
338 self = self.left
339 return getattr(self, getter)(index)
340 return get
341
342 class BinaryConcatNode(StringNode):
343 def __init__(self, left, right, balanced=False):
344 self.left = left
345 self.right = right
346 try:
347 self.len = ovfcheck(left.length() + right.length())
348 except OverflowError:
349 raise
350 self._depth = 0
351 # XXX the balance should become part of the depth
352 self.balanced = balanced
353 if balanced:
354 self.balance_known = True
355 else:
356 self.balance_known = False
357
358 def is_ascii(self):
359 return self.additional_info().is_ascii
360
361 def is_bytestring(self):
362 return self.additional_info().is_bytestring
363
364 def check_balanced(self):
365 if self.balance_known:
366 return self.balanced
367 # balance calculation
368 # XXX improve?
369 if not self.left.check_balanced() or not self.right.check_balanced():
370 balanced = False
371 else:
372 balanced = (find_fib_index(self.len // (NEW_NODE_WHEN_LENGTH / 2)) >=
373 self._depth)
374 self.balanced = balanced
375 self.balance_known = True
376 return balanced
377
378 def length(self):
379 return self.len
380
381 def depth(self):
382 depth = self._depth
383 if not depth:
384 depth = self._depth = max(self.left.depth(),
385 self.right.depth()) + 1
386 return depth
387
388 getchar = make_binary_get("getchar")
389 getunichar = make_binary_get("getunichar")
390 getint = make_binary_get("getint")
391 getrope = make_binary_get("getrope")
392
393 def can_contain_int(self, value):
394 if self.is_bytestring() and value > 255:
395 return False
396 if self.is_ascii() and value > 127:
397 return False
398 return (1 << (value & 0x1f)) & self.charbitmask()
399
400 def getslice(self, start, stop):
401 if start == 0:
402 if stop == self.length():
403 return self
404 return getslice_left(self, stop)
405 if stop == self.length():
406 return getslice_right(self, start)
407 return concatenate(
408 getslice_right(self.left, start),
409 getslice_left(self.right, stop - self.left.length()))
410
411 def flatten_string(self):
412 f = fringe(self)
413 return "".join([node.flatten_string() for node in f])
414
415 def flatten_unicode(self):
416 f = fringe(self)
417 return u"".join([node.flatten_unicode() for node in f])
418
419 def hash_part(self):
420 return self.additional_info().hash
421
422 def compute_additional_info(self):
423 leftaddinfo = self.left.additional_info()
424 rightaddinfo = self.right.additional_info()
425 additional_info = leftaddinfo.combine(rightaddinfo,
426 self.right.length())
427 self._additional_info = additional_info
428 return additional_info
429
430 def charbitmask(self):
431 return self.additional_info().charbitmask
432
433 def rebalance(self):
434 if self.balanced:
435 return self
436 return rebalance([self], self.len)
437
438
439 def _concat(self, other):
440 if isinstance(other, LiteralNode):
441 r = self.right
442 if isinstance(r, LiteralNode):
443 return BinaryConcatNode(self.left,
444 r._concat(other))
445 return BinaryConcatNode(self, other)
446
447 def dot(self, seen, toplevel=False):
448 if self in seen:
449 return
450 seen[self] = True
451 if toplevel:
452 addition = ", fillcolor=red"
453 elif self.check_balanced():
454 addition = ", fillcolor=yellow"
455 else:
456 addition = ""
457 yield '"%s" [shape=octagon,label="+\\ndepth=%s, length=%s"%s];' % (
458 id(self), self.depth(), self.len, addition)
459 for child in [self.left, self.right]:
460 yield '"%s" -> "%s";' % (id(self), id(child))
461 for line in child.dot(seen):
462 yield line
463
464
465 def concatenate(node1, node2):
466 if node1.length() == 0:
467 return node2
468 if node2.length() == 0:
469 return node1
470 result = node1._concat(node2)
471 if rebalance and result.depth() > MAX_DEPTH: #XXX better check
472 return result.rebalance()
473 return result
474
475
476 def getslice(node, start, stop, step, slicelength=-1):
477 if slicelength == -1:
478 # XXX for testing only
479 slicelength = len(xrange(start, stop, step))
480 start, stop, node = find_straddling(node, start, stop)
481 if step != 1:
482 iter = SeekableItemIterator(node)
483 iter.seekforward(start)
484 if node.is_bytestring():
485 result = [iter.nextchar()]
486 for i in range(slicelength - 1):
487 iter.seekforward(step - 1)
488 result.append(iter.nextchar())
489 return rope_from_charlist(result)
490 else:
491 result = [iter.nextunichar()]
492 for i in range(slicelength - 1):
493 iter.seekforward(step - 1)
494 result.append(iter.nextunichar())
495 return rope_from_unicharlist(result)
496 return node.getslice(start, stop)
497
498 def getslice_one(node, start, stop):
499 start, stop, node = find_straddling(node, start, stop)
500 return node.getslice(start, stop)
501
502 def find_straddling(node, start, stop):
503 while 1:
504 if isinstance(node, BinaryConcatNode):
505 llen = node.left.length()
506 if start >= llen:
507 node = node.right
508 start = start - llen
509 stop = stop - llen
510 continue
511 if stop <= llen:
512 node = node.left
513 continue
514 return start, stop, node
515
516 def getslice_right(node, start):
517 while 1:
518 if start == 0:
519 return node
520 if isinstance(node, BinaryConcatNode):
521 llen = node.left.length()
522 if start >= llen:
523 node = node.right
524 start = start - llen
525 continue
526 else:
527 return concatenate(getslice_right(node.left, start),
528 node.right)
529 return node.getslice(start, node.length())
530
531 def getslice_left(node, stop):
532 while 1:
533 if stop == node.length():
534 return node
535 if isinstance(node, BinaryConcatNode):
536 llen = node.left.length()
537 if stop <= llen:
538 node = node.left
539 continue
540 else:
541 return concatenate(node.left,
542 getslice_left(node.right, stop - llen))
543 return node.getslice(0, stop)
544
545
546 def multiply(node, times):
547 if times <= 0:
548 return LiteralStringNode.EMPTY
549 if times == 1:
550 return node
551 twopower = node
552 number = 1
553 result = None
554 while number <= times:
555 if number & times:
556 if result is None:
557 result = twopower
558 elif result.length() < CONCATENATE_WHEN_MULTIPLYING:
559 result = concatenate(result, twopower)
560 else:
561 result = BinaryConcatNode(result, twopower)
562 try:
563 number = ovfcheck(number * 2)
564 except OverflowError:
565 break
566 if twopower.length() < CONCATENATE_WHEN_MULTIPLYING:
567 twopower = concatenate(twopower, twopower)
568 else:
569 twopower = BinaryConcatNode(twopower, twopower)
570 return result
571
572
573 def join(node, l):
574 if node.length() == 0:
575 return rebalance(l)
576 nodelist = [None] * (2 * len(l) - 1)
577 length = 0
578 for i in range(len(l)):
579 nodelist[2 * i] = l[i]
580 length += l[i].length()
581 for i in range(len(l) - 1):
582 nodelist[2 * i + 1] = node
583 length += (len(l) - 1) * node.length()
584 return rebalance(nodelist, length)
585
586 def rebalance(nodelist, sizehint=-1):
587 if sizehint < 0:
588 sizehint = 0
589 for node in nodelist:
590 sizehint += node.length()
591 if sizehint == 0:
592 return LiteralStringNode.EMPTY
593 nodelist.reverse()
594
595 # this code is based on the Fibonacci identity:
596 # sum(fib(i) for i in range(n+1)) == fib(n+2)
597 l = [None] * (find_fib_index(sizehint) + 2)
598 stack = nodelist
599 empty_up_to = len(l)
600 a = b = sys.maxint
601 first_node = None
602 while stack:
603 curr = stack.pop()
604 while isinstance(curr, BinaryConcatNode) and not curr.check_balanced():
605 stack.append(curr.right)
606 curr = curr.left
607
608 currlen = curr.length()
609 if currlen == 0:
610 continue
611
612 if currlen < a:
613 # we can put 'curr' to its preferred location, which is in
614 # the known empty part at the beginning of 'l'
615 a, b = 1, 2
616 empty_up_to = 0
617 while not (currlen < b):
618 empty_up_to += 1
619 a, b = b, a+b
620 else:
621 # sweep all elements up to the preferred location for 'curr'
622 while not (currlen < b and l[empty_up_to] is None):
623 if l[empty_up_to] is not None:
624 curr = l[empty_up_to]._concat(curr)
625 l[empty_up_to] = None
626 currlen = curr.length()
627 else:
628 empty_up_to += 1
629 a, b = b, a+b
630
631 if empty_up_to == len(l):
632 return curr
633 l[empty_up_to] = curr
634 first_node = curr
635
636 # sweep all elements
637 curr = first_node
638 for index in range(empty_up_to + 1, len(l)):
639 if l[index] is not None:
640 curr = BinaryConcatNode(l[index], curr)
641 assert curr is not None
642 return curr
643
644 # __________________________________________________________________________
645 # construction from normal strings
646
647 def rope_from_charlist(charlist):
648 nodelist = []
649 size = 0
650 for i in range(0, len(charlist), NEW_NODE_WHEN_LENGTH):
651 chars = charlist[i: min(len(charlist), i + NEW_NODE_WHEN_LENGTH)]
652 nodelist.append(LiteralStringNode("".join(chars)))
653 size += len(chars)
654 return rebalance(nodelist, size)
655
656 def rope_from_unicharlist(charlist):
657 nodelist = []
658 length = len(charlist)
659 if not length:
660 return LiteralStringNode.EMPTY
661 i = 0
662 while i < length:
663 unichunk = []
664 while i < length:
665 c = ord(charlist[i])
666 if c < 256:
667 break
668 unichunk.append(unichr(c))
669 i += 1
670 if unichunk:
671 nodelist.append(LiteralUnicodeNode(u"".join(unichunk)))
672 strchunk = []
673 while i < length:
674 c = ord(charlist[i])
675 if c >= 256:
676 break
677 strchunk.append(chr(c))
678 i += 1
679 if strchunk:
680 nodelist.append(LiteralStringNode("".join(strchunk)))
681 return rebalance(nodelist, length)
682
683 def rope_from_unicode(uni):
684 nodelist = []
685 length = len(uni)
686 if not length:
687 return LiteralStringNode.EMPTY
688 i = 0
689 while i < length:
690 start = i
691 while i < length:
692 c = ord(uni[i])
693 if c < 256:
694 break
695 i += 1
696 if i != start:
697 nodelist.append(LiteralUnicodeNode(uni[start:i]))
698 start = i
699 while i < length:
700 c = ord(uni[i])
701 if c >= 256:
702 break
703 i += 1
704 if i != start:
705 nodelist.append(LiteralStringNode(uni[start:i].encode("latin-1")))
706 return rebalance(nodelist, length)
707
708 def rope_from_unichar(unichar):
709 intval = ord(unichar)
710 if intval > 256:
711 return LiteralUnicodeNode(unichar)
712 return LiteralStringNode.PREBUILT[intval]
713
714 # __________________________________________________________________________
715 # searching
716
717 def find_int(node, what, start=0, stop=-1):
718 offset = 0
719 length = node.length()
720 if stop == -1:
721 stop = length
722 if start != 0 or stop != length:
723 newstart, newstop, node = find_straddling(node, start, stop)
724 offset = start - newstart
725 start = newstart
726 stop = newstop
727 assert 0 <= start <= stop
728 if isinstance(node, LiteralNode):
729 pos = node.find_int(what, start, stop)
730 if pos == -1:
731 return pos
732 return pos + offset
733 if not node.can_contain_int(what):
734 return -1
735 # invariant: stack should only contain nodes that can contain the int what
736 stack = [node]
737 i = 0
738 while stack:
739 curr = stack.pop()
740 while isinstance(curr, BinaryConcatNode):
741 if curr.left.can_contain_int(what):
742 if curr.right.can_contain_int(what):
743 stack.append(curr.right)
744 curr = curr.left
745 else:
746 i += curr.left.length()
747 # if left cannot contain what, then right must contain it
748 curr = curr.right
749 nodelength = curr.length()
750 fringenode = curr
751 if i + nodelength <= start:
752 i += nodelength
753 continue
754 searchstart = max(0, start - i)
755 searchstop = min(stop - i, nodelength)
756 if searchstop <= 0:
757 return -1
758 assert isinstance(fringenode, LiteralNode)
759 pos = fringenode.find_int(what, searchstart, searchstop)
760 if pos != -1:
761 return pos + i + offset
762 i += nodelength
763 return -1
764
765 def find(node, subnode, start=0, stop=-1):
766
767 len1 = node.length()
768 len2 = subnode.length()
769 if stop > len1 or stop == -1:
770 stop = len1
771 if stop - start < 0:
772 return -1
773 if len2 == 1:
774 return find_int(node, subnode.getint(0), start, stop)
775 if len2 == 0:
776 return start
777 if len2 > stop - start:
778 return -1
779 restart = construct_restart_positions_node(subnode)
780 return _find_node(node, subnode, start, stop, restart)
781
782 def _find_node(node, subnode, start, stop, restart):
783 len2 = subnode.length()
784 m = start
785 iter = SeekableItemIterator(node)
786 iter.seekforward(start)
787 c = iter.nextint()
788 i = 0
789 subiter = SeekableItemIterator(subnode)
790 d = subiter.nextint()
791 while m + i < stop:
792 if c == d:
793 i += 1
794 if i == len2:
795 return m
796 d = subiter.nextint()
797 if m + i < stop:
798 c = iter.nextint()
799 else:
800 # mismatch, go back to the last possible starting pos
801 if i == 0:
802 m += 1
803 if m + i < stop:
804 c = iter.nextint()
805 else:
806 e = restart[i - 1]
807 new_m = m + i - e
808 assert new_m <= m + i
809 seek = m + i - new_m
810 if seek:
811 iter.seekback(m + i - new_m)
812 c = iter.nextint()
813 m = new_m
814 subiter.seekback(i - e + 1)
815 d = subiter.nextint()
816 i = e
817 return -1
818
819 def construct_restart_positions_node(node):
820 length = node.length()
821 restart = [0] * length
822 restart[0] = 0
823 i = 1
824 j = 0
825 iter1 = ItemIterator(node)
826 iter1.nextint()
827 c1 = iter1.nextint()
828 iter2 = SeekableItemIterator(node)
829 c2 = iter2.nextint()
830 while 1:
831 if c1 == c2:
832 j += 1
833 if j < length:
834 c2 = iter2.nextint()
835 restart[i] = j
836 i += 1
837 if i < length:
838 c1 = iter1.nextint()
839 else:
840 break
841 elif j>0:
842 new_j = restart[j-1]
843 assert new_j < j
844 iter2.seekback(j - new_j + 1)
845 c2 = iter2.nextint()
846 j = new_j
847 else:
848 restart[i] = 0
849 i += 1
850 if i < length:
851 c1 = iter1.nextint()
852 else:
853 break
854 j = 0
855 iter2 = SeekableItemIterator(node)
856 c2 = iter2.nextint()
857 return restart
858
859 def view(objs):
860 from dotviewer import graphclient
861 content = ["digraph G{"]
862 seen = {}
863 for i, obj in enumerate(objs):
864 if obj is None:
865 content.append(str(i) + ";")
866 else:
867 content.extend(obj.dot(seen, toplevel=True))
868 content.append("}")
869 p = py.test.ensuretemp("automaton").join("temp.dot")
870 p.write("\n".join(content))
871 graphclient.display_dot_file(str(p))
872
873
874 # __________________________________________________________________________
875 # iteration
876
877 class FringeIterator(object):
878 def __init__(self, node):
879 self.stack = [node]
880
881 def next(self):
882 while self.stack:
883 curr = self.stack.pop()
884 while 1:
885 if isinstance(curr, BinaryConcatNode):
886 self.stack.append(curr.right)
887 curr = curr.left
888 else:
889 return curr
890 raise StopIteration
891
892 def _seekforward(self, length):
893 """seek forward up to n characters, returning the number remaining chars.
894 experimental api"""
895 curr = None
896 while self.stack:
897 curr = self.stack.pop()
898 if length < curr.length():
899 break
900 length -= curr.length()
901 else:
902 raise StopIteration
903 while isinstance(curr, BinaryConcatNode):
904 left_length = curr.left.length()
905 if length < left_length:
906 self.stack.append(curr.right)
907 curr = curr.left
908 else:
909 length -= left_length
910 curr = curr.right
911 self.stack.append(curr)
912 return length
913
914
915 def fringe(node):
916 result = []
917 iter = FringeIterator(node)
918 while 1:
919 try:
920 result.append(iter.next())
921 except StopIteration:
922 return result
923
924
925 class ReverseFringeIterator(object):
926 def __init__(self, node):
927 self.stack = [node]
928
929 def next(self):
930 while self.stack:
931 curr = self.stack.pop()
932 while 1:
933 if isinstance(curr, BinaryConcatNode):
934 self.stack.append(curr.left)
935 curr = curr.right
936 else:
937 return curr
938 raise StopIteration
939
940
941 class ItemIterator(object):
942 def __init__(self, node, start=0):
943 self.iter = FringeIterator(node)
944 self.node = None
945 self.nodelength = 0
946 self.index = 0
947 if start:
948 self._advance_to(start)
949
950 def _advance_to(self, index):
951 self.index = self.iter._seekforward(index)
952 self.node = self.iter.next()
953 self.nodelength = self.node.length()
954
955 def getnode(self):
956 node = self.node
957 if node is None:
958 while 1:
959 node = self.node = self.iter.next()
960 nodelength = self.nodelength = node.length()
961 if nodelength != 0:
962 self.index = 0
963 return node
964 return node
965
966 def advance_index(self):
967 index = self.index
968 if index == self.nodelength - 1:
969 self.node = None
970 else:
971 self.index = index + 1
972
973 def nextchar(self):
974 node = self.getnode()
975 result = node.getchar(self.index)
976 self.advance_index()
977 return result
978
979 def nextunichar(self):
980 node = self.getnode()
981 result = node.getunichar(self.index)
982 self.advance_index()
983 return result
984
985 def nextrope(self):
986 node = self.getnode()
987 result = node.getrope(self.index)
988 self.advance_index()
989 return result
990
991 def nextint(self):
992 node = self.getnode()
993 result = node.getint(self.index)
994 self.advance_index()
995 return result
996
997 class ReverseItemIterator(object):
998 def __init__(self, node):
999 self.iter = ReverseFringeIterator(node)
1000 self.node = None
1001 self.index = 0
1002
1003 def getnode(self):
1004 node = self.node
1005 index = self.index
1006 if node is None:
1007 while 1:
1008 node = self.node = self.iter.next()
1009 index = self.index = node.length() - 1
1010 if index != -1:
1011 return node
1012 return node
1013
1014
1015 def advance_index(self):
1016 if self.index == 0:
1017 self.node = None
1018 else:
1019 self.index -= 1
1020
1021 def nextchar(self):
1022 node = self.getnode()
1023 result = node.getchar(self.index)
1024 self.advance_index()
1025 return result
1026
1027 def nextint(self):
1028 node = self.getnode()
1029 result = node.getint(self.index)
1030 self.advance_index()
1031 return result
1032
1033 def nextunichar(self):
1034 node = self.getnode()
1035 result = node.getunichar(self.index)
1036 self.advance_index()
1037 return result
1038
1039 def make_seekable_method(resultgetter, backward=False):
1040 if backward:
1041 direction = -1
1042 else:
1043 direction = 1
1044 def next(self):
1045 node = self.getnode()
1046 result = getattr(node, resultgetter)(self.index)
1047 self.index += direction
1048 return result
1049 return next
1050
1051 class SeekableItemIterator(object):
1052 def __init__(self, node):
1053 self.stack = []
1054 self.tookleft = []
1055 self.find_downward(node)
1056 assert False not in self.tookleft
1057
1058 def find_downward(self, node, items=0):
1059 assert 0 <= items < node.length()
1060 while isinstance(node, BinaryConcatNode):
1061 self.stack.append(node)
1062 left = node.left
1063 if items >= left.length():
1064 items -= left.length()
1065 node = node.right
1066 self.tookleft.append(False)
1067 else:
1068 node = node.left
1069 self.tookleft.append(True)
1070 assert len(self.tookleft) == len(self.stack)
1071 self.node = node
1072 self.nodelength = node.length()
1073 self.index = items
1074 return self.node
1075
1076 def getnode(self):
1077 if self.index == self.nodelength:
1078 self.seekforward(0)
1079 if self.index == -1:
1080 self.seekback(0)
1081 return self.node
1082
1083 nextchar = make_seekable_method("getchar")
1084 nextunichar = make_seekable_method("getunichar")
1085 nextint = make_seekable_method("getint")
1086 lastchar = make_seekable_method("getchar", backward=True)
1087 lastunichar = make_seekable_method("getunichar", backward=True)
1088 lastint = make_seekable_method("getint", backward=True)
1089
1090 def seekforward(self, numchars):
1091 if numchars < (self.nodelength - self.index):
1092 self.index += numchars
1093 return
1094 numchars -= self.nodelength - self.index
1095 while self.stack:
1096 tookleft = self.tookleft.pop()
1097 if tookleft:
1098 node = self.stack[-1]
1099 assert isinstance(node, BinaryConcatNode)
1100 right = node.right
1101 if right.length() > numchars:
1102 self.tookleft.append(False)
1103 self.find_downward(right, numchars)
1104 return
1105 numchars -= right.length()
1106 self.stack.pop()
1107 raise StopIteration
1108
1109
1110 def seekback(self, numchars):
1111 if numchars <= self.index:
1112 self.index -= numchars
1113 return
1114 numchars -= self.index
1115 while self.stack:
1116 tookleft = self.tookleft.pop()
1117 if not tookleft:
1118 node = self.stack[-1]
1119 assert isinstance(node, BinaryConcatNode)
1120 left = node.left
1121 if left.length() >= numchars:
1122 self.tookleft.append(True)
1123 self.find_downward(left, left.length() - numchars)
1124 return
1125 numchars -= left.length()
1126 self.stack.pop()
1127 raise StopIteration
1128
1129
1130 class FindIterator(object):
1131 def __init__(self, node, sub, start=0, stop=-1):
1132 self.node = node
1133 self.sub = sub
1134 len1 = self.length = node.length()
1135 len2 = sub.length()
1136 self.search_length = len2
1137 self.start = start
1138 if stop == -1 or stop > len1:
1139 stop = len1
1140 self.stop = stop
1141 if len2 == 0:
1142 self.restart_positions = None
1143 elif len2 == 1:
1144 self.restart_positions = None
1145 elif len2 > stop - start:
1146 self.restart_positions = None
1147 # ensure that a StopIteration is immediately raised
1148 self.stop = self.start
1149 else:
1150 self.restart_positions = construct_restart_positions_node(sub)
1151
1152 def next(self):
1153 if self.search_length == 0:
1154 if (self.stop - self.start) < 0:
1155 raise StopIteration
1156 start = self.start
1157 self.start += 1
1158 return start
1159 elif self.search_length == 1:
1160 result = find_int(self.node, self.sub.getint(0),
1161 self.start, self.stop)
1162 if result == -1:
1163 self.start = self.length
1164 raise StopIteration
1165 self.start = result + 1
1166 return result
1167 if self.start >= self.stop:
1168 raise StopIteration
1169 result = _find_node(self.node, self.sub, self.start,
1170 self.stop, self.restart_positions)
1171 if result == -1:
1172 self.start = self.length
1173 raise StopIteration
1174 self.start = result + self.search_length
1175 return result
1176
1177 # __________________________________________________________________________
1178 # comparison
1179
1180
1181 def eq(node1, node2):
1182 if node1 is node2:
1183 return True
1184 if node1.length() != node2.length():
1185 return False
1186 if hash_rope(node1) != hash_rope(node2):
1187 return False
1188 if (isinstance(node1, LiteralStringNode) and
1189 isinstance(node2, LiteralStringNode)):
1190 return node1.s == node2.s
1191 if (isinstance(node1, LiteralUnicodeNode) and
1192 isinstance(node2, LiteralUnicodeNode)):
1193 return node1.u == node2.u
1194 iter1 = ItemIterator(node1)
1195 iter2 = ItemIterator(node2)
1196 # XXX could be cleverer and detect partial equalities
1197 while 1:
1198 try:
1199 c = iter1.nextint()
1200 except StopIteration:
1201 return True
1202 if c != iter2.nextint():
1203 return False
1204
1205 def compare(node1, node2):
1206 len1 = node1.length()
1207 len2 = node2.length()
1208 if not len1:
1209 if not len2:
1210 return 0
1211 return -1
1212 if not len2:
1213 return 1
1214
1215 cmplen = min(len1, len2)
1216 i = 0
1217 iter1 = ItemIterator(node1)
1218 iter2 = ItemIterator(node2)
1219 while i < cmplen:
1220 diff = iter1.nextint() - iter2.nextint()
1221 if diff != 0:
1222 return diff
1223 i += 1
1224 return len1 - len2
1225
1226
1227 def startswith(self, prefix, start, end):
1228 if prefix.length() == 0:
1229 return True
1230 if self.length() == 0:
1231 return False
1232 stop = start + prefix.length()
1233 if stop > end:
1234 return False
1235 iter1 = ItemIterator(self, start)
1236 iter2 = ItemIterator(prefix)
1237 for i in range(prefix.length()):
1238 if iter1.nextint() != iter2.nextint():
1239 return False
1240 return True
1241
1242 def endswith(self, suffix, start, end):
1243 if suffix.length() == 0:
1244 return True
1245 if self.length() == 0:
1246 return False
1247 begin = end - suffix.length()
1248 if begin < start:
1249 return False
1250 iter1 = ItemIterator(self, begin)
1251 iter2 = ItemIterator(suffix)
1252 for i in range(suffix.length()):
1253 if iter1.nextint() != iter2.nextint():
1254 return False
1255 return True
1256
1257 def strip(node, left=True, right=True, predicate=lambda i: chr(i).isspace(),
1258 *extraargs):
1259 length = node.length()
1260
1261 lpos = 0
1262 rpos = length
1263
1264 if left:
1265 iter = ItemIterator(node)
1266 while lpos < rpos and predicate(iter.nextint(), *extraargs):
1267 lpos += 1
1268
1269 if right:
1270 iter = ReverseItemIterator(node)
1271 while rpos > lpos and predicate(iter.nextint(), *extraargs):
1272 rpos -= 1
1273
1274 assert rpos >= lpos
1275 return getslice_one(node, lpos, rpos)
1276 strip._annspecialcase_ = "specialize:arg(3)"
1277
1278 def split(node, sub, maxsplit=-1):
1279 startidx = 0
1280 substrings = []
1281 iter = FindIterator(node, sub)
1282 while maxsplit != 0:
1283 try:
1284 foundidx = iter.next()
1285 except StopIteration:
1286 break
1287 substrings.append(getslice_one(node, startidx, foundidx))
1288 startidx = foundidx + sub.length()
1289 maxsplit = maxsplit - 1
1290 substrings.append(getslice_one(node, startidx, node.length()))
1291 return substrings
1292
1293
1294 def split_chars(node, maxsplit=-1, predicate=lambda x: chr(x).isspace()):
1295 result = []
1296 length = node.length()
1297 if not length:
1298 return result
1299 i = 0
1300 iter = ItemIterator(node)
1301 while True:
1302 # find the beginning of the next word
1303 while i < length:
1304 if not predicate(iter.nextint()):
1305 break # found
1306 i += 1
1307 else:
1308 break # end of string, finished
1309
1310 # find the end of the word
1311 if maxsplit == 0:
1312 j = length # take all the rest of the string
1313 else:
1314 j = i + 1
1315 while j < length and not predicate(iter.nextint()):
1316 j += 1
1317 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
1318
1319 # the word is value[i:j]
1320 result.append(getslice_one(node, i, j))
1321
1322 # continue to look from the character following the space after the word
1323 i = j + 1
1324 return result
1325
1326
1327 def rsplit_chars(node, maxsplit=-1, predicate=lambda x: chr(x).isspace()):
1328 result = []
1329 length = node.length()
1330 i = length - 1
1331 iter = ReverseItemIterator(node)
1332 while True:
1333 # starting from the end, find the end of the next word
1334 while i >= 0:
1335 if not predicate(iter.nextint()):
1336 break # found
1337 i -= 1
1338 else:
1339 break # end of string, finished
1340
1341 # find the start of the word
1342 # (more precisely, 'j' will be the space character before the word)
1343 if maxsplit == 0:
1344 j = -1 # take all the rest of the string
1345 else:
1346 j = i - 1
1347 while j >= 0 and not predicate(iter.nextint()):
1348 j -= 1
1349 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
1350
1351 # the word is value[j+1:i+1]
1352 j1 = j + 1
1353 assert j1 >= 0
1354 result.append(getslice_one(node, j1, i + 1))
1355
1356 # continue to look from the character before the space before the word
1357 i = j - 1
1358
1359 result.reverse()
1360 return result
1361
1362
1363 def split_completely(node, maxsplit=-1):
1364 upper = node.length()
1365 if maxsplit > 0 and maxsplit < upper + 2:
1366 upper = maxsplit - 1
1367 assert upper >= 0
1368 substrings = [by]
1369 iter = ItemIterator(node)
1370 for i in range(upper):
1371 substrings.append(iter.nextrope())
1372 substrings.append(rope.getslice_one(node, upper, length))
1373
1374
1375 def splitlines(node, keepends=False):
1376 length = node.length()
1377 if length == 0:
1378 return []
1379
1380 result = []
1381 iter = ItemIterator(node)
1382 i = j = 0
1383 last = ord(" ")
1384 char = iter.nextint()
1385 while i < length:
1386 # Find a line and append it
1387 while char != ord('\n') and char != ord('\r'):
1388 try:
1389 i += 1
1390 last = char
1391 char = iter.nextint()
1392 except StopIteration:
1393 break
1394 # Skip the line break reading CRLF as one line break
1395 eol = i
1396 i += 1
1397 last = char
1398 try:
1399 char = iter.nextint()
1400 except StopIteration:
1401 pass
1402 else:
1403 if last == ord('\r') and char == ord('\n'):
1404 i += 1
1405 try:
1406 last = char
1407 char = iter.nextint()
1408 except StopIteration:
1409 pass
1410 if keepends:
1411 eol = i
1412 result.append(getslice_one(node, j, eol))
1413 j = i
1414
1415 if j == 0:
1416 result.append(node)
1417 elif j < length:
1418 result.append(getslice_one(node, j, length))
1419
1420 return result
1421
1422 # __________________________________________________________________________
1423 # misc
1424
1425 def hash_rope(rope):
1426 length = rope.length()
1427 if length == 0:
1428 return -1
1429 x = rope.hash_part()
1430 x <<= 1 # get rid of the bit that is always set
1431 x ^= rope.getint(0)
1432 x ^= rope.length()
1433 return intmask(x)
1434
1435 # ____________________________________________________________
1436 # to and from unicode conversion
1437
1438 def str_decode_ascii(rope):
1439 assert rope.is_bytestring()
1440 if rope.is_ascii():
1441 return rope
1442 return None
1443
1444 def str_decode_latin1(rope):
1445 assert rope.is_bytestring()
1446 return rope
1447
1448 def str_decode_utf8(rope):
1449 from rpython.rlib.runicode import str_decode_utf_8
1450 if rope.is_ascii():
1451 return rope
1452 elif isinstance(rope, BinaryConcatNode):
1453 lresult = str_decode_utf8(rope.left)
1454 if lresult is not None:
1455 return BinaryConcatNode(lresult,
1456 str_decode_utf8(rope.right))
1457 elif isinstance(rope, LiteralStringNode):
1458 try:
1459 result, consumed = str_decode_utf_8(rope.s, len(rope.s), "strict",
1460 False)
1461 except UnicodeDecodeError:
1462 return None
1463 if consumed < len(rope.s):
1464 return None
1465 return rope_from_unicode(result)
1466 s = rope.flatten_string()
1467 try:
1468 result, consumed = str_decode_utf_8(s, len(s), "strict", True)
1469 return rope_from_unicode(result)
1470 except UnicodeDecodeError:
1471 pass
1472
1473
1474 def unicode_encode_ascii(rope):
1475 if rope.is_ascii():
1476 return rope
1477
1478 def unicode_encode_latin1(rope):
1479 if rope.is_bytestring():
1480 return rope
1481
1482 def unicode_encode_utf8(rope, allow_surrogates=False):
1483 from rpython.rlib.runicode import unicode_encode_utf_8
1484 if rope.is_ascii():
1485 return rope
1486 elif isinstance(rope, BinaryConcatNode):
1487 return BinaryConcatNode(unicode_encode_utf8(rope.left),
1488 unicode_encode_utf8(rope.right))
1489 elif isinstance(rope, LiteralUnicodeNode):
1490 return LiteralStringNode(
1491 unicode_encode_utf_8(rope.u, len(rope.u), "strict",
1492 allow_surrogates=allow_surrogates))
1493 elif isinstance(rope, LiteralStringNode):
1494 return LiteralStringNode(_str_encode_utf_8(rope.s))
1495
1496 def _str_encode_utf_8(s):
1497 size = len(s)
1498 result = []
1499 i = 0
1500 while i < size:
1501 ch = ord(s[i])
1502 i += 1
1503 if (ch < 0x80):
1504 # Encode ASCII
1505 result.append(chr(ch))
1506 continue
1507 # Encode Latin-1
1508 result.append(chr((0xc0 | (ch >> 6))))
1509 result.append(chr((0x80 | (ch & 0x3f))))
1510 return "".join(result)