Debian Codegraph @

pypy/module/_io/interp_iobase.py

raw symbols SCIP
1 from errno import EINTR
2 from pypy.interpreter.baseobjspace import W_Root
3 from pypy.interpreter.error import OperationError, oefmt
4 from pypy.interpreter.typedef import (
5 TypeDef, GetSetProperty, generic_new_descr, descr_get_dict, descr_set_dict,
6 make_weakref_descr, unwrap_spec)
7 from pypy.interpreter.gateway import interp2app
8 from rpython.rlib.rstring import StringBuilder
9 from rpython.rlib import rweakref, rweaklist
10
11
12 DEFAULT_BUFFER_SIZE = 8192
13
14 def convert_size(space, w_size):
15 if space.is_none(w_size) or w_size is None:
16 return -1
17 else:
18 return space.int_w(w_size)
19
20 def trap_eintr(space, error):
21 # Return True if an EnvironmentError with errno == EINTR is set
22 if not error.match(space, space.w_EnvironmentError):
23 return False
24 try:
25 w_value = error.get_w_value(space)
26 w_errno = space.getattr(w_value, space.newtext("errno"))
27 return space.eq_w(w_errno, space.newint(EINTR))
28 except OperationError:
29 return False
30
31 def unsupported(space, message):
32 w_exc = space.getattr(space.getbuiltinmodule('_io'),
33 space.newtext('UnsupportedOperation'))
34 return OperationError(w_exc, space.newtext(message))
35
36 # May be called with any object
37 def check_readable_w(space, w_obj):
38 if not space.is_true(space.call_method(w_obj, 'readable')):
39 raise unsupported(space, "File or stream is not readable")
40
41 # May be called with any object
42 def check_writable_w(space, w_obj):
43 if not space.is_true(space.call_method(w_obj, 'writable')):
44 raise unsupported(space, "File or stream is not writable")
45
46 # May be called with any object
47 def check_seekable_w(space, w_obj):
48 if not space.is_true(space.call_method(w_obj, 'seekable')):
49 raise unsupported(space, "File or stream is not seekable")
50
51 class W_IOBase(W_Root):
52 cffi_fileobj = None # pypy/module/_cffi_backend
53
54 def __init__(self, space, add_to_autoflusher=True):
55 # XXX: IOBase thinks it has to maintain its own internal state in
56 # `__IOBase_closed` and call flush() by itself, but it is redundant
57 # with whatever behaviour a non-trivial derived class will implement.
58 self.space = space
59 self.w_dict = None
60 self.__IOBase_closed = False
61 if add_to_autoflusher:
62 get_autoflusher(space).add(self)
63 if self.needs_finalizer():
64 self.register_finalizer(space)
65
66 def getdict(self, space):
67 if self.w_dict is None:
68 self.w_dict = space.newdict(instance=True)
69 return self.w_dict
70
71 def getdictvalue(self, space, attr):
72 if self.w_dict is None:
73 return None
74 return space.finditem_str(self.w_dict, attr)
75
76 def _closed(self, space):
77 # This gets the derived attribute, which is *not* __IOBase_closed
78 # in most cases!
79 w_closed = space.findattr(self, space.newtext('closed'))
80 if w_closed is not None and space.is_true(w_closed):
81 return True
82 return False
83
84 def _finalize_(self):
85 # Note: there is only this empty _finalize_() method here, but
86 # we still need register_finalizer() so that descr_del() is
87 # called. IMPORTANT: this is not the recommended way to have a
88 # finalizer! It makes the finalizer appear as __del__() from
89 # app-level, and the user can call __del__() explicitly, or
90 # override it, with or without calling the parent's __del__().
91 # This matches 'tp_finalize' in CPython >= 3.4. So far (3.5),
92 # this is the only built-in class with a 'tp_finalize' slot that
93 # can be subclassed.
94 pass
95
96 def descr_del(self):
97 space = self.space
98 w_closed = space.findattr(self, space.newtext('closed'))
99 try:
100 # If `closed` doesn't exist or can't be evaluated as bool, then
101 # the object is probably in an unusable state, so ignore.
102 if w_closed is not None and not space.is_true(w_closed):
103 try:
104 self._dealloc_warn_w(space, self)
105 finally:
106 space.call_method(self, "close")
107 except OperationError:
108 # Silencing I/O errors is bad, but printing spurious tracebacks is
109 # equally as bad, and potentially more frequent (because of
110 # shutdown issues).
111 pass
112
113 def _CLOSED(self):
114 # Use this macro whenever you want to check the internal `closed`
115 # status of the IOBase object rather than the virtual `closed`
116 # attribute as returned by whatever subclass.
117 return self.__IOBase_closed
118
119 def _unsupportedoperation(self, space, message):
120 raise unsupported(space, message)
121
122 def _check_closed(self, space, message=None):
123 if message is None:
124 message = "I/O operation on closed file"
125 if self._closed(space):
126 raise OperationError(
127 space.w_ValueError, space.newtext(message))
128
129 def check_closed_w(self, space):
130 self._check_closed(space)
131
132 def closed_get_w(self, space):
133 return space.newbool(self.__IOBase_closed)
134
135 def close_w(self, space):
136 if self._CLOSED():
137 return
138
139 cffifo = self.cffi_fileobj
140 self.cffi_fileobj = None
141 if cffifo is not None:
142 cffifo.close()
143
144 try:
145 space.call_method(self, "flush")
146 finally:
147 self.__IOBase_closed = True
148
149 self.maybe_unregister_rpython_finalizer_io(space)
150
151 def maybe_unregister_rpython_finalizer_io(self, space):
152 from rpython.rlib import rgc
153 if self.user_overridden_class:
154 return
155 rgc.may_ignore_finalizer(self)
156
157 def needs_finalizer(self):
158 # can return False if we know that the precise close() method
159 # of this class will have no effect
160 return True
161
162 def _dealloc_warn_w(self, space, w_source):
163 """Called when the io is implicitly closed via the deconstructor"""
164 pass
165
166 def flush_w(self, space):
167 if self._CLOSED():
168 raise oefmt(space.w_ValueError, "I/O operation on closed file")
169
170 def seek_w(self, space, w_offset, w_whence=None):
171 self._unsupportedoperation(space, "seek")
172
173 def tell_w(self, space):
174 return space.call_method(self, "seek", space.newint(0), space.newint(1))
175
176 def truncate_w(self, space, w_size=None):
177 self._unsupportedoperation(space, "truncate")
178
179 def fileno_w(self, space):
180 self._unsupportedoperation(space, "fileno")
181
182 def enter_w(self, space):
183 self._check_closed(space)
184 return self
185
186 def exit_w(self, space, __args__):
187 space.call_method(self, "close")
188
189 def iter_w(self, space):
190 self._check_closed(space)
191 return self
192
193 def next_w(self, space):
194 w_line = space.call_method(self, "readline")
195 if space.len_w(w_line) == 0:
196 raise OperationError(space.w_StopIteration, space.w_None)
197 return w_line
198
199 def isatty_w(self, space):
200 self._check_closed(space)
201 return space.w_False
202
203 def readable_w(self, space):
204 return space.w_False
205
206 def writable_w(self, space):
207 return space.w_False
208
209 def seekable_w(self, space):
210 return space.w_False
211
212 def getstate_w(self, space):
213 raise oefmt(space.w_TypeError, "cannot serialize '%T' object", self)
214
215 # ______________________________________________________________
216
217 def readline_w(self, space, w_limit=None):
218 # For backwards compatibility, a (slowish) readline().
219 limit = convert_size(space, w_limit)
220
221 has_peek = space.findattr(self, space.newtext("peek"))
222
223 builder = StringBuilder()
224 size = 0
225
226 while limit < 0 or size < limit:
227 nreadahead = 1
228
229 if has_peek:
230 try:
231 w_readahead = space.call_method(self, "peek", space.newint(1))
232 except OperationError as e:
233 if trap_eintr(space, e):
234 continue
235 raise
236 if not space.isinstance_w(w_readahead, space.w_bytes):
237 raise oefmt(space.w_IOError,
238 "peek() should have returned a bytes object, "
239 "not '%T'", w_readahead)
240 length = space.len_w(w_readahead)
241 if length > 0:
242 n = 0
243 buf = space.bytes_w(w_readahead)
244 if limit >= 0:
245 while True:
246 if n >= length or n >= limit:
247 break
248 n += 1
249 if buf[n-1] == '\n':
250 break
251 else:
252 while True:
253 if n >= length:
254 break
255 n += 1
256 if buf[n-1] == '\n':
257 break
258 nreadahead = n
259
260 try:
261 w_read = space.call_method(self, "read", space.newint(nreadahead))
262 except OperationError as e:
263 if trap_eintr(space, e):
264 continue
265 raise
266 if not space.isinstance_w(w_read, space.w_bytes):
267 raise oefmt(space.w_IOError,
268 "peek() should have returned a bytes object, not "
269 "'%T'", w_read)
270 read = space.bytes_w(w_read)
271 if not read:
272 break
273
274 size += len(read)
275 builder.append(read)
276
277 if read[-1] == '\n':
278 break
279
280 return space.newbytes(builder.build())
281
282 def readlines_w(self, space, w_hint=None):
283 hint = convert_size(space, w_hint)
284 if hint <= 0:
285 return space.newlist(space.unpackiterable(self))
286
287 length = 0
288 lines_w = []
289 w_iterator = space.iter(self)
290 while 1:
291 try:
292 w_line = space.next(w_iterator)
293 except OperationError as e:
294 if not e.match(space, space.w_StopIteration):
295 raise
296 break
297 lines_w.append(w_line)
298 length += space.len_w(w_line)
299 if length > hint:
300 break
301 return space.newlist(lines_w)
302
303 def writelines_w(self, space, w_lines):
304 self._check_closed(space)
305
306 w_iterator = space.iter(w_lines)
307
308 while True:
309 try:
310 w_line = space.next(w_iterator)
311 except OperationError as e:
312 if not e.match(space, space.w_StopIteration):
313 raise
314 break # done
315 while True:
316 try:
317 space.call_method(self, "write", w_line)
318 except OperationError as e:
319 if trap_eintr(space, e):
320 continue
321 raise
322 else:
323 break
324
325 @staticmethod
326 def output_slice(space, rwbuffer, target_pos, data):
327 if target_pos + len(data) > rwbuffer.getlength():
328 raise oefmt(space.w_RuntimeError,
329 "target buffer has shrunk during operation")
330 rwbuffer.setslice(target_pos, data)
331
332
333 W_IOBase.typedef = TypeDef(
334 '_io._IOBase',
335 __new__ = generic_new_descr(W_IOBase),
336 __enter__ = interp2app(W_IOBase.enter_w),
337 __exit__ = interp2app(W_IOBase.exit_w),
338 __iter__ = interp2app(W_IOBase.iter_w),
339 __next__ = interp2app(W_IOBase.next_w),
340 close = interp2app(W_IOBase.close_w),
341 flush = interp2app(W_IOBase.flush_w),
342 seek = interp2app(W_IOBase.seek_w),
343 tell = interp2app(W_IOBase.tell_w),
344 truncate = interp2app(W_IOBase.truncate_w),
345 fileno = interp2app(W_IOBase.fileno_w),
346 isatty = interp2app(W_IOBase.isatty_w),
347 readable = interp2app(W_IOBase.readable_w),
348 writable = interp2app(W_IOBase.writable_w),
349 seekable = interp2app(W_IOBase.seekable_w),
350
351 _checkReadable = interp2app(check_readable_w),
352 _checkWritable = interp2app(check_writable_w),
353 _checkSeekable = interp2app(check_seekable_w),
354 _checkClosed = interp2app(W_IOBase.check_closed_w),
355 closed = GetSetProperty(W_IOBase.closed_get_w,
356 doc="True if the file is closed"),
357 __dict__ = GetSetProperty(descr_get_dict, descr_set_dict, cls=W_IOBase),
358 __weakref__ = make_weakref_descr(W_IOBase),
359 __del__ = interp2app(W_IOBase.descr_del),
360 __confirm_applevel_del__ = True,
361
362 readline = interp2app(W_IOBase.readline_w),
363 readlines = interp2app(W_IOBase.readlines_w),
364 writelines = interp2app(W_IOBase.writelines_w),
365 )
366
367 class W_RawIOBase(W_IOBase):
368 pass
369
370
371 # ________________________________________________________________
372 # Abstract read methods, based on readinto()
373
374 # note that the self needs to be W_IOBase here, even though the methods are on
375 # _RawIOBase. The reason is the applevel_subclasses_base below, which ensures
376 # that subclasses of _io._RawIOBase are instances of (a subclass of) W_IOBase.
377 # This is not a problem, because W_RawIOBase does not actually have any
378 # content the methods and don't expect much from "self". see also comment in
379 # descr_new_rawiobase below
380
381 @unwrap_spec(self=W_IOBase)
382 def rawiobase_read_w(self, space, w_size=None):
383 size = convert_size(space, w_size)
384 if size < 0:
385 return space.call_method(self, "readall")
386
387 w_buffer = space.call_function(space.w_bytearray, w_size)
388 w_length = space.call_method(self, "readinto", w_buffer)
389 if space.is_w(w_length, space.w_None):
390 return w_length
391 space.delslice(w_buffer, w_length, space.len(w_buffer))
392 return space.call_function(space.w_bytes, w_buffer)
393
394 @unwrap_spec(self=W_IOBase)
395 def rawiobase_readall_w(self, space):
396 builder = StringBuilder()
397 while True:
398 try:
399 w_data = space.call_method(self, "read",
400 space.newint(DEFAULT_BUFFER_SIZE))
401 except OperationError as e:
402 if trap_eintr(space, e):
403 continue
404 raise
405 if space.is_w(w_data, space.w_None):
406 if not builder.getlength():
407 return w_data
408 break
409
410 if not space.isinstance_w(w_data, space.w_bytes):
411 raise oefmt(space.w_TypeError, "read() should return bytes")
412 data = space.bytes_w(w_data)
413 if not data:
414 break
415 builder.append(data)
416 return space.newbytes(builder.build())
417
418 def descr_new_rawiobase(space, w_subtype, __args__):
419 instance = space.allocate_instance(W_RawIOBase, w_subtype)
420 # NB: for subclasses of _io._RawIOBase, the instance is not actually an
421 # instance of W_RawIOBase! this does not matter for the methods at all, of
422 # course, since W_RawIOBase does not have any extra fields over W_IOBase.
423 W_IOBase.__init__(instance, space)
424 return instance
425
426 assert W_RawIOBase.__init__.im_func is W_IOBase.__init__.im_func
427
428 W_RawIOBase.typedef = TypeDef(
429 '_io._RawIOBase', W_IOBase.typedef,
430 __doc__ = "Base class for raw binary I/O.",
431 __rpython_level_class__ = W_RawIOBase,
432 __new__ = interp2app(descr_new_rawiobase),
433 read = interp2app(rawiobase_read_w),
434 readall = interp2app(rawiobase_readall_w),
435 )
436 W_RawIOBase.typedef.applevel_subclasses_base = W_IOBase
437
438
439 # ------------------------------------------------------------
440 # functions to make sure that all streams are flushed on exit
441 # ------------------------------------------------------------
442
443
444 class AutoFlusher(rweaklist.RWeakListMixin):
445 def __init__(self, space):
446 self.initialize()
447
448 def add(self, w_iobase):
449 if rweakref.has_weakref_support():
450 self.add_handle(w_iobase)
451 #else:
452 # no support for weakrefs, so ignore and we
453 # will not get autoflushing
454
455 def flush_all(self, space):
456 while True:
457 handles = self.get_all_handles()
458 self.initialize() # reset the state here
459 progress = False
460 for wr in handles:
461 w_iobase = wr()
462 if w_iobase is None:
463 continue
464 progress = True
465 try:
466 space.call_method(w_iobase, 'flush')
467 except OperationError:
468 # Silencing all errors is bad, but getting randomly
469 # interrupted here is equally as bad, and potentially
470 # more frequent (because of shutdown issues).
471 pass
472 if not progress:
473 break
474
475 def get_autoflusher(space):
476 return space.fromcache(AutoFlusher)