Debian Codegraph @

rpython/rlib/rmarshal.py

raw symbols SCIP
1 """A way to serialize data in the same format as the 'marshal' module
2 but accessible to RPython programs.
3 """
4
5 from rpython.annotator import model as annmodel
6 from rpython.annotator.signature import annotation
7 from rpython.annotator.listdef import ListDef, TooLateForChange
8 from rpython.tool.pairtype import pair, pairtype
9 from rpython.rlib.rarithmetic import r_longlong, intmask, LONG_BIT, ovfcheck
10 from rpython.rlib.rfloat import formatd, rstring_to_float
11 from rpython.rlib.unroll import unrolling_iterable
12 from rpython.rlib.rstring import assert_str0
13
14 class CannotMarshal(Exception):
15 pass
16
17 class CannotUnmarshall(Exception):
18 pass
19
20 def get_marshaller(type):
21 """Return a marshaller function.
22 The marshaller takes two arguments: a buffer and an object of
23 type 'type'. The buffer is list of characters that gets extended
24 with new data when the marshaller is called.
25 """
26 s_obj = annotation(type, None)
27 try:
28 # look for a marshaller in the 'dumpers' list
29 return find_dumper(s_obj)
30 except CannotMarshal:
31 # ask the annotation to produce an appropriate dumper
32 pair(_tag, s_obj).install_marshaller()
33 return find_dumper(s_obj)
34 get_marshaller._annspecialcase_ = 'specialize:memo'
35
36 def get_loader(type):
37 s_obj = annotation(type, None)
38 try:
39 # look for a marshaller in the 'loaders' list
40 return find_loader(s_obj)
41 except CannotUnmarshall:
42 # ask the annotation to produce an appropriate loader
43 pair(_tag, s_obj).install_unmarshaller()
44 return find_loader(s_obj)
45
46 def get_unmarshaller(type):
47 """Return an unmarshaller function.
48 The unmarshaller takes a string as argument, and return an object
49 of type 'type'. It raises ValueError if the marshalled data is
50 invalid or contains an object of a different type.
51 """
52 loaditem = get_loader(type)
53 # wrap the loaditem into a more convenient interface
54 try:
55 return _unmarshaller_cache[loaditem]
56 except KeyError:
57 def unmarshaller(buf):
58 loader = Loader(buf)
59 result = loaditem(loader)
60 loader.check_finished()
61 return result
62 _unmarshaller_cache[loaditem] = unmarshaller
63 return unmarshaller
64 get_unmarshaller._annspecialcase_ = 'specialize:memo'
65 _unmarshaller_cache = {}
66
67 # ____________________________________________________________
68 #
69 # Dumpers and loaders
70
71 TYPE_NONE = 'N'
72 TYPE_FALSE = 'F'
73 TYPE_TRUE = 'T'
74 TYPE_INT = 'i'
75 TYPE_INT64 = 'I'
76 TYPE_FLOAT = 'f'
77 TYPE_STRING = 's'
78 TYPE_TUPLE = '('
79 TYPE_LIST = '['
80 TYPE_DICT = '{'
81
82 dumpers = []
83 loaders = []
84 s_list_of_chars = annmodel.SomeList(ListDef(None, annmodel.SomeChar(),
85 mutated=True, resized=True))
86
87 def add_dumper(s_obj, dumper):
88 dumpers.append((s_obj, dumper))
89 dumper.s_obj = s_obj
90 dumper._annenforceargs_ = [s_list_of_chars, s_obj]
91
92 def add_loader(s_obj, loader):
93 # 's_obj' should be the **least general annotation** that we're
94 # interested in, somehow
95 loaders.append((s_obj, loader))
96
97 def get_dumper_annotation(dumper):
98 return dumper.s_obj
99
100 def find_dumper(s_obj):
101 # select a suitable dumper - the condition is that the dumper must
102 # accept an input that is at least as general as the requested s_obj
103 for s_cond, dumper in dumpers:
104 if weakly_contains(s_cond, s_obj):
105 return dumper
106 raise CannotMarshal(s_obj)
107
108 def find_loader(s_obj):
109 # select a suitable loader - note that we need more loaders than
110 # dumpers in general, because the condition is that the loader should
111 # return something that is contained within the requested s_obj
112 for s_cond, loader in loaders[::-1]:
113 if s_obj.contains(s_cond):
114 return loader
115 if s_obj == annmodel.s_None:
116 return load_none
117 raise CannotUnmarshall(s_obj)
118
119 def w_long(buf, x):
120 buf.append(chr(x & 0xff))
121 x >>= 8
122 buf.append(chr(x & 0xff))
123 x >>= 8
124 buf.append(chr(x & 0xff))
125 x >>= 8
126 buf.append(chr(x & 0xff))
127 w_long._annenforceargs_ = [None, int]
128
129 def dump_none(buf, x):
130 buf.append(TYPE_NONE)
131 add_dumper(annmodel.s_None, dump_none)
132
133 def load_none(loader):
134 if readchr(loader) != TYPE_NONE:
135 raise ValueError("expected a None")
136 return None
137 #add_loader(annmodel.s_None, load_none) -- cannot install it as a regular
138 # loader, because it will also match any annotation that can be None
139
140 def dump_bool(buf, x):
141 if x:
142 buf.append(TYPE_TRUE)
143 else:
144 buf.append(TYPE_FALSE)
145 add_dumper(annmodel.s_Bool, dump_bool)
146
147 def load_bool(loader):
148 t = readchr(loader)
149 if t == TYPE_TRUE:
150 return True
151 elif t == TYPE_FALSE:
152 return False
153 else:
154 raise ValueError("expected a bool")
155 add_loader(annmodel.s_Bool, load_bool)
156
157 def dump_int(buf, x):
158 # only use TYPE_INT on 32-bit platforms
159 if LONG_BIT > 32:
160 dump_longlong(buf, r_longlong(x))
161 else:
162 buf.append(TYPE_INT)
163 w_long(buf, x)
164 add_dumper(annmodel.SomeInteger(), dump_int)
165
166 def load_int_nonneg(loader):
167 x = load_int(loader)
168 if x < 0:
169 raise ValueError("expected a non-negative int")
170 return x
171 add_loader(annmodel.SomeInteger(nonneg=True), load_int_nonneg)
172
173 def load_int(loader):
174 r = readchr(loader)
175 if LONG_BIT > 32 and r == TYPE_INT64:
176 x = readlong(loader) & 0xFFFFFFFF
177 x |= readlong(loader) << 32
178 return x
179 if r == TYPE_INT:
180 return readlong(loader)
181 raise ValueError("expected an int")
182 add_loader(annmodel.SomeInteger(), load_int)
183
184 def dump_longlong(buf, x):
185 buf.append(TYPE_INT64)
186 w_long(buf, intmask(x))
187 w_long(buf, intmask(x>>32))
188 add_dumper(annotation(r_longlong), dump_longlong)
189
190 r_32bits_mask = r_longlong(0xFFFFFFFF)
191
192 def load_longlong_nonneg(loader):
193 x = load_longlong(loader)
194 if x < 0:
195 raise ValueError("expected a non-negative longlong")
196 return x
197 add_loader(annmodel.SomeInteger(knowntype=r_longlong, nonneg=True),
198 load_longlong_nonneg)
199
200 def load_longlong(loader):
201 if readchr(loader) != TYPE_INT64:
202 raise ValueError("expected a longlong")
203 x = r_longlong(readlong(loader)) & r_32bits_mask
204 x |= (r_longlong(readlong(loader)) << 32)
205 return x
206 add_loader(annotation(r_longlong), load_longlong)
207
208 def dump_float(buf, x):
209 buf.append(TYPE_FLOAT)
210 s = formatd(x, 'g', 17)
211 buf.append(chr(len(s)))
212 buf += s
213 add_dumper(annmodel.SomeFloat(), dump_float)
214
215 def load_float(loader):
216 if readchr(loader) != TYPE_FLOAT:
217 raise ValueError("expected a float")
218 length = ord(readchr(loader))
219 s = readstr(loader, length)
220 return rstring_to_float(s)
221 add_loader(annmodel.SomeFloat(), load_float)
222
223 def dump_string_or_none(buf, x):
224 if x is None:
225 dump_none(buf, x)
226 else:
227 buf.append(TYPE_STRING)
228 w_long(buf, len(x))
229 buf += x
230 add_dumper(annmodel.SomeString(can_be_None=True), dump_string_or_none)
231
232 def load_single_char(loader):
233 if readchr(loader) != TYPE_STRING or readlong(loader) != 1:
234 raise ValueError("expected a character")
235 return readchr(loader)
236 add_loader(annmodel.SomeChar(), load_single_char)
237
238 def load_string_nonul(loader):
239 if readchr(loader) != TYPE_STRING:
240 raise ValueError("expected a string")
241 length = readlong(loader)
242 return assert_str0(readstr(loader, length))
243 add_loader(annmodel.SomeString(can_be_None=False, no_nul=True),
244 load_string_nonul)
245
246 def load_string(loader):
247 if readchr(loader) != TYPE_STRING:
248 raise ValueError("expected a string")
249 length = readlong(loader)
250 return readstr(loader, length)
251 add_loader(annmodel.SomeString(can_be_None=False, no_nul=False),
252 load_string)
253
254 def load_string_or_none_nonul(loader):
255 t = readchr(loader)
256 if t == TYPE_STRING:
257 length = readlong(loader)
258 return assert_str0(readstr(loader, length))
259 elif t == TYPE_NONE:
260 return None
261 else:
262 raise ValueError("expected a string or None")
263 add_loader(annmodel.SomeString(can_be_None=True, no_nul=True),
264 load_string_or_none_nonul)
265
266 def load_string_or_none(loader):
267 t = readchr(loader)
268 if t == TYPE_STRING:
269 length = readlong(loader)
270 return readstr(loader, length)
271 elif t == TYPE_NONE:
272 return None
273 else:
274 raise ValueError("expected a string or None")
275 add_loader(annmodel.SomeString(can_be_None=True, no_nul=False),
276 load_string_or_none)
277
278 # ____________________________________________________________
279 #
280 # Loader support class
281
282 class Loader(object):
283
284 def __init__(self, buf):
285 self.buf = buf
286 self.pos = 0
287
288 def check_finished(self):
289 if self.pos != len(self.buf):
290 raise ValueError("not all data consumed")
291
292 def need_more_data(self):
293 raise ValueError("not enough data") # can be overridden
294
295 # the rest are not method on the Loader class, because it causes troubles
296 # in rpython.translator.rsandbox if new methods are discovered after some
297 # sandboxed-enabled graphs are produced
298 def readstr(loader, count):
299 if count < 0:
300 raise ValueError("negative count")
301 pos = loader.pos
302 try:
303 end = ovfcheck(pos + count)
304 except OverflowError:
305 raise ValueError("cannot decode count: value too big")
306 while end > len(loader.buf):
307 loader.need_more_data()
308 loader.pos = end
309 return loader.buf[pos:end]
310 readstr._annenforceargs_ = [None, int]
311
312 def readchr(loader):
313 pos = loader.pos
314 while pos >= len(loader.buf):
315 loader.need_more_data()
316 loader.pos = pos + 1
317 return loader.buf[pos]
318
319 def peekchr(loader):
320 pos = loader.pos
321 while pos >= len(loader.buf):
322 loader.need_more_data()
323 return loader.buf[pos]
324
325 def readlong(loader):
326 a = ord(readchr(loader))
327 b = ord(readchr(loader))
328 c = ord(readchr(loader))
329 d = ord(readchr(loader))
330 if d >= 0x80:
331 d -= 0x100
332 return a | (b<<8) | (c<<16) | (d<<24)
333
334 # ____________________________________________________________
335 #
336 # Annotations => dumpers and loaders
337
338 class MTag(object):
339 """Tag for pairtype(), for the purpose of making the get_marshaller()
340 and get_unmarshaller() methods of SomeObject only locally visible."""
341 _tag = MTag()
342
343 def weakly_contains(s_bigger, s_smaller):
344 # a special version of s_bigger.contains(s_smaller). Warning, to
345 # support ListDefs properly, this works by trying to produce a side-effect
346 # on s_bigger. It relies on the fact that s_bigger was created with
347 # an expression like 'annotation([s_item])' which returns a ListDef with
348 # no bookkeeper, on which side-effects are not allowed.
349 saved = annmodel.TLS.allow_int_to_float
350 try:
351 annmodel.TLS.allow_int_to_float = False
352 s_union = annmodel.unionof(s_bigger, s_smaller)
353 return s_bigger.contains(s_union)
354 except (annmodel.UnionError, TooLateForChange):
355 return False
356 finally:
357 annmodel.TLS.allow_int_to_float = saved
358
359
360 class __extend__(pairtype(MTag, annmodel.SomeObject)):
361
362 def install_marshaller((tag, s_obj)):
363 if not hasattr(s_obj, '_get_rmarshall_support_'):
364 raise CannotMarshal(s_obj)
365 # special support for custom annotation like SomeStatResult:
366 # the annotation tells us how to turn an object into something
367 # else that can be marshalled
368 def dump_with_custom_reduce(buf, x):
369 reduced_obj = fn_reduce(x)
370 reduceddumper(buf, reduced_obj)
371 s_reduced_obj, fn_reduce, fn_recreate = s_obj._get_rmarshall_support_()
372 reduceddumper = get_marshaller(s_reduced_obj)
373 add_dumper(s_obj, dump_with_custom_reduce)
374
375 def install_unmarshaller((tag, s_obj)):
376 if not hasattr(s_obj, '_get_rmarshall_support_'):
377 raise CannotUnmarshall(s_obj)
378 # special support for custom annotation like SomeStatResult
379 def load_with_custom_recreate(loader):
380 reduced_obj = reducedloader(loader)
381 return fn_recreate(reduced_obj)
382 s_reduced_obj, fn_reduce, fn_recreate = s_obj._get_rmarshall_support_()
383 reducedloader = get_loader(s_reduced_obj)
384 add_loader(s_obj, load_with_custom_recreate)
385
386
387 class __extend__(pairtype(MTag, annmodel.SomeList)):
388
389 def install_marshaller((tag, s_list)):
390 def dump_list_or_none(buf, x):
391 if x is None:
392 dump_none(buf, x)
393 else:
394 buf.append(TYPE_LIST)
395 w_long(buf, len(x))
396 for item in x:
397 itemdumper(buf, item)
398
399 itemdumper = get_marshaller(s_list.listdef.listitem.s_value)
400 if s_list.listdef.listitem.dont_change_any_more:
401 s_general_list = s_list
402 else:
403 s_item = get_dumper_annotation(itemdumper)
404 s_general_list = annotation([s_item])
405 add_dumper(s_general_list, dump_list_or_none)
406
407 def install_unmarshaller((tag, s_list)):
408 def load_list_or_none(loader):
409 t = readchr(loader)
410 if t == TYPE_LIST:
411 length = readlong(loader)
412 result = []
413 for i in range(length):
414 result.append(itemloader(loader))
415 return result
416 elif t == TYPE_NONE:
417 return None
418 else:
419 raise ValueError("expected a list or None")
420
421 itemloader = get_loader(s_list.listdef.listitem.s_value)
422 add_loader(s_list, load_list_or_none)
423
424
425 class __extend__(pairtype(MTag, annmodel.SomeDict)):
426
427 def install_marshaller((tag, s_dict)):
428 def dump_dict_or_none(buf, x):
429 if x is None:
430 dump_none(buf, x)
431 else:
432 buf.append(TYPE_DICT)
433 for key, value in x.items():
434 keydumper(buf, key)
435 valuedumper(buf, value)
436 buf.append('0') # end of dict
437
438 keydumper = get_marshaller(s_dict.dictdef.dictkey.s_value)
439 valuedumper = get_marshaller(s_dict.dictdef.dictvalue.s_value)
440 if (s_dict.dictdef.dictkey.dont_change_any_more or
441 s_dict.dictdef.dictvalue.dont_change_any_more):
442 s_general_dict = s_dict
443 else:
444 s_key = get_dumper_annotation(keydumper)
445 s_value = get_dumper_annotation(valuedumper)
446 s_general_dict = annotation({s_key: s_value})
447 add_dumper(s_general_dict, dump_dict_or_none)
448
449 def install_unmarshaller((tag, s_dict)):
450 def load_dict_or_none(loader):
451 t = readchr(loader)
452 if t == TYPE_DICT:
453 result = {}
454 while peekchr(loader) != '0':
455 key = keyloader(loader)
456 value = valueloader(loader)
457 result[key] = value
458 readchr(loader) # consume the final '0'
459 return result
460 elif t == TYPE_NONE:
461 return None
462 else:
463 raise ValueError("expected a dict or None")
464
465 keyloader = get_loader(s_dict.dictdef.dictkey.s_value)
466 valueloader = get_loader(s_dict.dictdef.dictvalue.s_value)
467 add_loader(s_dict, load_dict_or_none)
468
469
470 class __extend__(pairtype(MTag, annmodel.SomeTuple)):
471
472 def install_marshaller((tag, s_tuple)):
473 def dump_tuple(buf, x):
474 buf.append(TYPE_TUPLE)
475 w_long(buf, len(x))
476 for i, itemdumper in unroll_item_dumpers:
477 itemdumper(buf, x[i])
478
479 itemdumpers = [get_marshaller(s_item) for s_item in s_tuple.items]
480 unroll_item_dumpers = unrolling_iterable(enumerate(itemdumpers))
481 dumper_annotations = [get_dumper_annotation(itemdumper)
482 for itemdumper in itemdumpers]
483 s_general_tuple = annmodel.SomeTuple(dumper_annotations)
484 add_dumper(s_general_tuple, dump_tuple)
485
486 def install_unmarshaller((tag, s_tuple)):
487 def load_tuple(loader):
488 if readchr(loader) != TYPE_TUPLE:
489 raise ValueError("expected a tuple")
490 if readlong(loader) != expected_length:
491 raise ValueError("wrong tuple length")
492 result = ()
493 for i, itemloader in unroll_item_loaders:
494 result += (itemloader(loader),)
495 return result
496
497 itemloaders = [get_loader(s_item) for s_item in s_tuple.items]
498 expected_length = len(itemloaders)
499 unroll_item_loaders = unrolling_iterable(enumerate(itemloaders))
500 add_loader(s_tuple, load_tuple)