Debian Codegraph @

rpython/rtyper/lltypesystem/rbuilder.py

raw symbols SCIP
1 from rpython.rlib import rgc, jit
2 from rpython.rlib.objectmodel import enforceargs, dont_inline, always_inline
3 from rpython.rlib.rarithmetic import ovfcheck, r_uint, intmask
4 from rpython.rtyper.debug import ll_assert
5 from rpython.rlib.unroll import unrolling_iterable
6 from rpython.rtyper.rptr import PtrRepr
7 from rpython.rtyper.lltypesystem import lltype, rffi, rstr
8 from rpython.rtyper.lltypesystem.lltype import staticAdtMethod, nullptr
9 from rpython.rtyper.lltypesystem.rstr import (STR, UNICODE, char_repr,
10 string_repr, unichar_repr, unicode_repr)
11 from rpython.rtyper.rbuilder import AbstractStringBuilderRepr
12 from rpython.tool.sourcetools import func_with_new_name
13 from rpython.rtyper.annlowlevel import llstr, llunicode
14
15
16
17 # ------------------------------------------------------------
18 # Basic idea:
19 #
20 # - A StringBuilder has a rstr.STR of the specified initial size
21 # (100 by default), which is filled gradually.
22 #
23 # - When it is full, we allocate extra buffers as an extra rstr.STR,
24 # and the already-filled one is added to a chained list of STRINGPIECE
25 # objects.
26 #
27 # - At build() time, we consolidate all these pieces into a single
28 # rstr.STR, which is both returned and re-attached to the StringBuilder,
29 # replacing the STRINGPIECEs.
30 #
31 # - The data is copied at most twice, and only once in case it fits
32 # into the initial size (and the GC supports shrinking the STR).
33 #
34 # XXX in build(), we could try keeping around a global weakref to the
35 # chain of STRINGPIECEs and reuse them the next time.
36 #
37 # ------------------------------------------------------------
38
39
40 STRINGPIECE = lltype.GcStruct('stringpiece',
41 ('buf', lltype.Ptr(STR)),
42 ('prev_piece', lltype.Ptr(lltype.GcForwardReference())))
43 STRINGPIECE.prev_piece.TO.become(STRINGPIECE)
44
45 STRINGBUILDER = lltype.GcStruct('stringbuilder',
46 ('current_buf', lltype.Ptr(STR)),
47 ('current_pos', lltype.Signed),
48 ('current_end', lltype.Signed),
49 ('total_size', lltype.Signed),
50 ('extra_pieces', lltype.Ptr(STRINGPIECE)),
51 adtmeths={
52 'copy_string_contents': staticAdtMethod(rstr.copy_string_contents),
53 'copy_raw_to_string': staticAdtMethod(rstr.copy_raw_to_string),
54 'mallocfn': staticAdtMethod(rstr.mallocstr),
55 }
56 )
57
58 UNICODEPIECE = lltype.GcStruct('unicodepiece',
59 ('buf', lltype.Ptr(UNICODE)),
60 ('prev_piece', lltype.Ptr(lltype.GcForwardReference())))
61 UNICODEPIECE.prev_piece.TO.become(UNICODEPIECE)
62
63 UNICODEBUILDER = lltype.GcStruct('unicodebuilder',
64 ('current_buf', lltype.Ptr(UNICODE)),
65 ('current_pos', lltype.Signed),
66 ('current_end', lltype.Signed),
67 ('total_size', lltype.Signed),
68 ('extra_pieces', lltype.Ptr(UNICODEPIECE)),
69 adtmeths={
70 'copy_string_contents': staticAdtMethod(rstr.copy_unicode_contents),
71 'copy_raw_to_string': staticAdtMethod(rstr.copy_raw_to_unicode),
72 'mallocfn': staticAdtMethod(rstr.mallocunicode),
73 }
74 )
75
76 # ------------------------------------------------------------
77 # The generic piece of code to append a string (or a slice of it)
78 # to a builder; it is inlined inside various functions below
79
80 @always_inline
81 def _ll_append(ll_builder, ll_str, start, size):
82 pos = ll_builder.current_pos
83 end = ll_builder.current_end
84 if (end - pos) < size:
85 ll_grow_and_append(ll_builder, ll_str, start, size)
86 else:
87 ll_builder.current_pos = pos + size
88 ll_builder.copy_string_contents(ll_str, ll_builder.current_buf,
89 start, pos, size)
90
91 # ------------------------------------------------------------
92 # Logic to grow a builder (by adding a new string to it)
93
94 @dont_inline
95 @enforceargs(None, int)
96 def ll_grow_by(ll_builder, needed):
97 try:
98 needed = ovfcheck(needed + ll_builder.total_size)
99 needed = ovfcheck(needed + 63) & ~63
100 total_size = ovfcheck(ll_builder.total_size + needed)
101 except OverflowError:
102 raise MemoryError
103 #
104 new_string = ll_builder.mallocfn(needed)
105 #
106 PIECE = lltype.typeOf(ll_builder.extra_pieces).TO
107 old_piece = lltype.malloc(PIECE)
108 old_piece.buf = ll_builder.current_buf
109 old_piece.prev_piece = ll_builder.extra_pieces
110 ll_assert(bool(old_piece.buf), "no buf??")
111 ll_builder.current_buf = new_string
112 ll_builder.current_pos = 0
113 ll_builder.current_end = needed
114 ll_builder.total_size = total_size
115 ll_builder.extra_pieces = old_piece
116
117 @dont_inline
118 def ll_grow_and_append(ll_builder, ll_str, start, size):
119 # A fast-path, meant for builders that only receive a single big
120 # string before build() is called. Also works in some other cases.
121 if (size > 1280 and ll_builder.current_pos == 0
122 and start == 0 and size == len(ll_str.chars)):
123 try:
124 total_size = ovfcheck(ll_builder.total_size + size)
125 except OverflowError:
126 pass
127 else:
128 PIECE = lltype.typeOf(ll_builder.extra_pieces).TO
129 old_piece = lltype.malloc(PIECE)
130 old_piece.buf = ll_str
131 old_piece.prev_piece = ll_builder.extra_pieces
132 ll_builder.total_size = total_size
133 ll_builder.extra_pieces = old_piece
134 return
135
136 # First, the part that still fits in the current piece
137 part1 = ll_builder.current_end - ll_builder.current_pos
138 ll_assert(part1 < size, "part1 >= size")
139 ll_builder.copy_string_contents(ll_str, ll_builder.current_buf,
140 start, ll_builder.current_pos,
141 part1)
142 start += part1
143 size -= part1
144 # Allocate the new piece
145 ll_grow_by(ll_builder, size)
146 ll_assert(ll_builder.current_pos == 0, "current_pos must be 0 after grow()")
147 # Finally, the second part of the string
148 ll_builder.current_pos = size
149 ll_builder.copy_string_contents(ll_str, ll_builder.current_buf,
150 start, 0, size)
151
152 # ------------------------------------------------------------
153 # builder.append()
154
155 @always_inline
156 def ll_append(ll_builder, ll_str):
157 if jit.we_are_jitted():
158 ll_jit_append(ll_builder, ll_str)
159 else:
160 # no-jit case: inline the logic of _ll_append() in the caller
161 _ll_append(ll_builder, ll_str, 0, len(ll_str.chars))
162
163 @dont_inline
164 def ll_jit_append(ll_builder, ll_str):
165 # jit case: first try special cases for known small lengths
166 if ll_jit_try_append_slice(ll_builder, ll_str, 0, len(ll_str.chars)):
167 return
168 # fall-back to do a residual call to ll_append_res0
169 ll_append_res0(ll_builder, ll_str)
170
171 @jit.dont_look_inside
172 def ll_append_res0(ll_builder, ll_str):
173 _ll_append(ll_builder, ll_str, 0, len(ll_str.chars))
174
175 # ------------------------------------------------------------
176 # builder.append_char()
177
178 @always_inline
179 def ll_append_char(ll_builder, char):
180 jit.conditional_call(ll_builder.current_pos == ll_builder.current_end,
181 ll_grow_by, ll_builder, 1)
182 pos = ll_builder.current_pos
183 ll_builder.current_pos = pos + 1
184 ll_builder.current_buf.chars[pos] = char
185
186 # ------------------------------------------------------------
187 # builder.append_slice()
188
189 @always_inline
190 def ll_append_slice(ll_builder, ll_str, start, end):
191 if jit.we_are_jitted():
192 ll_jit_append_slice(ll_builder, ll_str, start, end)
193 else:
194 # no-jit case: inline the logic of _ll_append() in the caller
195 _ll_append(ll_builder, ll_str, start, end - start)
196
197 @dont_inline
198 def ll_jit_append_slice(ll_builder, ll_str, start, end):
199 # jit case: first try special cases for known small lengths
200 if ll_jit_try_append_slice(ll_builder, ll_str, start, end - start):
201 return
202 # fall-back to do a residual call to ll_append_res_slice
203 ll_append_res_slice(ll_builder, ll_str, start, end)
204
205 @jit.dont_look_inside
206 def ll_append_res_slice(ll_builder, ll_str, start, end):
207 _ll_append(ll_builder, ll_str, start, end - start)
208
209 # ------------------------------------------------------------
210 # Special-casing for the JIT: appending strings (or slices) of
211 # a known length up to MAX_N. These functions all contain an
212 # inlined copy of _ll_append(), but with a known small N, gcc
213 # will compile the copy_string_contents() efficiently.
214
215 MAX_N = 10
216
217 def make_func_for_size(N):
218 @jit.dont_look_inside
219 def ll_append_0(ll_builder, ll_str):
220 _ll_append(ll_builder, ll_str, 0, N)
221 ll_append_0 = func_with_new_name(ll_append_0, "ll_append_0_%d" % N)
222 #
223 @jit.dont_look_inside
224 def ll_append_start(ll_builder, ll_str, start):
225 _ll_append(ll_builder, ll_str, start, N)
226 ll_append_start = func_with_new_name(ll_append_start,
227 "ll_append_start_%d" % N)
228 return ll_append_0, ll_append_start, N
229
230 unroll_func_for_size = unrolling_iterable([make_func_for_size(_n)
231 for _n in range(2, MAX_N + 1)])
232
233 @jit.unroll_safe
234 def ll_jit_try_append_slice(ll_builder, ll_str, start, size):
235 if jit.isconstant(size):
236 if size == 0:
237 return True
238 # a special case: if the builder's pos and end are still contants
239 # (typically if the builder is still virtual), and if 'size' fits,
240 # then we don't need any reallocation and can just set the
241 # characters in the buffer, in a way that won't force anything.
242 if (jit.isconstant(ll_builder.current_pos) and
243 jit.isconstant(ll_builder.current_end) and
244 size <= (ll_builder.current_end - ll_builder.current_pos) and
245 size <= 16):
246 pos = ll_builder.current_pos
247 buf = ll_builder.current_buf
248 stop = pos + size
249 ll_builder.current_pos = stop
250 while pos < stop:
251 buf.chars[pos] = ll_str.chars[start]
252 pos += 1
253 start += 1
254 return True
255 # turn appends of length 1 into ll_append_char().
256 if size == 1:
257 ll_append_char(ll_builder, ll_str.chars[start])
258 return True
259 # turn appends of length 2 to 10 into residual calls to
260 # specialized functions, for the lengths 2 to 10, where
261 # gcc will optimize the known-length copy_string_contents()
262 # as much as possible.
263 for func0, funcstart, for_size in unroll_func_for_size:
264 if size == for_size:
265 if jit.isconstant(start) and start == 0:
266 func0(ll_builder, ll_str)
267 else:
268 funcstart(ll_builder, ll_str, start)
269 return True
270 return False # use the fall-back path
271
272 # ------------------------------------------------------------
273 # builder.append_multiple_char()
274
275 @always_inline
276 def ll_append_multiple_char(ll_builder, char, times):
277 if jit.we_are_jitted():
278 if ll_jit_try_append_multiple_char(ll_builder, char, times):
279 return
280 _ll_append_multiple_char(ll_builder, char, times)
281
282 @jit.dont_look_inside
283 def _ll_append_multiple_char(ll_builder, char, times):
284 part1 = ll_builder.current_end - ll_builder.current_pos
285 if times > part1:
286 times -= part1
287 buf = ll_builder.current_buf
288 for i in xrange(ll_builder.current_pos, ll_builder.current_end):
289 buf.chars[i] = char
290 ll_grow_by(ll_builder, times)
291 #
292 buf = ll_builder.current_buf
293 pos = ll_builder.current_pos
294 end = pos + times
295 ll_builder.current_pos = end
296 for i in xrange(pos, end):
297 buf.chars[i] = char
298
299 @jit.unroll_safe
300 def ll_jit_try_append_multiple_char(ll_builder, char, size):
301 if jit.isconstant(size):
302 if size == 0:
303 return True
304 # a special case: if the builder's pos and end are still contants
305 # (typically if the builder is still virtual), and if 'size' fits,
306 # then we don't need any reallocation and can just set the
307 # characters in the buffer, in a way that won't force anything.
308 if (jit.isconstant(ll_builder.current_pos) and
309 jit.isconstant(ll_builder.current_end) and
310 size <= (ll_builder.current_end - ll_builder.current_pos) and
311 size <= 16):
312 pos = ll_builder.current_pos
313 buf = ll_builder.current_buf
314 stop = pos + size
315 ll_builder.current_pos = stop
316 while pos < stop:
317 buf.chars[pos] = char
318 pos += 1
319 return True
320 if size == 1:
321 ll_append_char(ll_builder, char)
322 return True
323 return False # use the fall-back path
324
325 # ------------------------------------------------------------
326 # builder.append_charpsize()
327
328 @jit.dont_look_inside
329 def ll_append_charpsize(ll_builder, charp, size):
330 part1 = ll_builder.current_end - ll_builder.current_pos
331 if size > part1:
332 # First, the part that still fits
333 ll_builder.copy_raw_to_string(charp, ll_builder.current_buf,
334 ll_builder.current_pos, part1)
335 charp = rffi.ptradd(charp, part1)
336 size -= part1
337 ll_grow_by(ll_builder, size)
338 #
339 pos = ll_builder.current_pos
340 ll_builder.current_pos = pos + size
341 ll_builder.copy_raw_to_string(charp, ll_builder.current_buf, pos, size)
342
343 # ------------------------------------------------------------
344 # builder.getlength()
345
346 @always_inline
347 def ll_getlength(ll_builder):
348 num_chars_missing_from_last_piece = (
349 ll_builder.current_end - ll_builder.current_pos)
350 return ll_builder.total_size - num_chars_missing_from_last_piece
351
352 # ------------------------------------------------------------
353 # builder.build()
354
355 @jit.look_inside_iff(lambda ll_builder: jit.isvirtual(ll_builder))
356 def ll_build(ll_builder):
357 # NB. usually the JIT doesn't look inside this function; it does
358 # so only in the simplest example where it could virtualize everything
359 if ll_builder.extra_pieces:
360 ll_fold_pieces(ll_builder)
361 elif ll_builder.current_pos != ll_builder.total_size:
362 ll_shrink_final(ll_builder)
363 return ll_builder.current_buf
364
365 def ll_shrink_final(ll_builder):
366 final_size = ll_builder.current_pos
367 ll_assert(final_size <= ll_builder.total_size,
368 "final_size > ll_builder.total_size?")
369 buf = rgc.ll_shrink_array(ll_builder.current_buf, final_size)
370 ll_builder.current_buf = buf
371 ll_builder.current_end = final_size
372 ll_builder.total_size = final_size
373
374 def ll_fold_pieces(ll_builder):
375 final_size = BaseStringBuilderRepr.ll_getlength(ll_builder)
376 ll_assert(final_size >= 0, "negative final_size")
377 extra = ll_builder.extra_pieces
378 ll_builder.extra_pieces = lltype.nullptr(lltype.typeOf(extra).TO)
379 #
380 # A fast-path if the builder contains exactly one big piece:
381 # discard the allocated current_buf and put the big piece there
382 if ll_builder.current_pos == 0 and not extra.prev_piece:
383 piece = extra.buf
384 ll_assert(final_size == len(piece.chars),
385 "bogus final_size in fold_pieces")
386 ll_builder.total_size = final_size
387 ll_builder.current_buf = piece
388 ll_builder.current_pos = final_size
389 ll_builder.current_end = final_size
390 return
391 #
392 result = ll_builder.mallocfn(final_size)
393 piece = ll_builder.current_buf
394 piece_lgt = ll_builder.current_pos
395 ll_assert(ll_builder.current_end == len(piece.chars),
396 "bogus last piece_lgt")
397 ll_builder.total_size = final_size
398 ll_builder.current_buf = result
399 ll_builder.current_pos = final_size
400 ll_builder.current_end = final_size
401
402 dst = final_size
403 while True:
404 dst -= piece_lgt
405 ll_assert(dst >= 0, "rbuilder build: overflow")
406 ll_builder.copy_string_contents(piece, result, 0, dst, piece_lgt)
407 if not extra:
408 break
409 piece = extra.buf
410 piece_lgt = len(piece.chars)
411 extra = extra.prev_piece
412 ll_assert(dst == 0, "rbuilder build: underflow")
413
414 # ------------------------------------------------------------
415 # bool(builder)
416
417 def ll_bool(ll_builder):
418 return ll_builder != nullptr(lltype.typeOf(ll_builder).TO)
419
420 # ------------------------------------------------------------
421
422 class BaseStringBuilderRepr(AbstractStringBuilderRepr):
423 def empty(self):
424 return nullptr(self.lowleveltype.TO)
425
426 ll_append = staticmethod(ll_append)
427 ll_append_char = staticmethod(ll_append_char)
428 ll_append_slice = staticmethod(ll_append_slice)
429 ll_append_multiple_char = staticmethod(ll_append_multiple_char)
430 ll_append_charpsize = staticmethod(ll_append_charpsize)
431 ll_getlength = staticmethod(ll_getlength)
432 ll_build = staticmethod(ll_build)
433 ll_bool = staticmethod(ll_bool)
434
435 class StringBuilderRepr(BaseStringBuilderRepr):
436 lowleveltype = lltype.Ptr(STRINGBUILDER)
437 basetp = STR
438 convert_to_ll = staticmethod(llstr)
439 string_repr = string_repr
440 char_repr = char_repr
441 raw_ptr_repr = PtrRepr(
442 lltype.Ptr(lltype.Array(lltype.Char, hints={'nolength': True}))
443 )
444
445 @staticmethod
446 def ll_new(init_size):
447 # Clamp 'init_size' to be a value between 0 and 1280.
448 # Negative values are mapped to 1280.
449 init_size = intmask(min(r_uint(init_size), r_uint(1280)))
450 ll_builder = lltype.malloc(STRINGBUILDER)
451 ll_builder.current_buf = ll_builder.mallocfn(init_size)
452 ll_builder.current_pos = 0
453 ll_builder.current_end = init_size
454 ll_builder.total_size = init_size
455 return ll_builder
456
457
458 class UnicodeBuilderRepr(BaseStringBuilderRepr):
459 lowleveltype = lltype.Ptr(UNICODEBUILDER)
460 basetp = UNICODE
461 convert_to_ll = staticmethod(llunicode)
462 string_repr = unicode_repr
463 char_repr = unichar_repr
464 raw_ptr_repr = PtrRepr(
465 lltype.Ptr(lltype.Array(lltype.UniChar, hints={'nolength': True}))
466 )
467
468 @staticmethod
469 def ll_new(init_size):
470 # Clamp 'init_size' to be a value between 0 and 1280.
471 # Negative values are mapped to 1280.
472 init_size = intmask(min(r_uint(init_size), r_uint(1280)))
473 ll_builder = lltype.malloc(UNICODEBUILDER)
474 ll_builder.current_buf = ll_builder.mallocfn(init_size)
475 ll_builder.current_pos = 0
476 ll_builder.current_end = init_size
477 ll_builder.total_size = init_size
478 return ll_builder
479
480
481 unicodebuilder_repr = UnicodeBuilderRepr()
482 stringbuilder_repr = StringBuilderRepr()