Source

pypy / pypy / module / _io / interp_iobase.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
from pypy.interpreter.baseobjspace import Wrappable
from pypy.interpreter.typedef import (
    TypeDef, GetSetProperty, generic_new_descr, descr_get_dict, descr_set_dict,
    make_weakref_descr)
from pypy.interpreter.gateway import interp2app
from pypy.interpreter.error import OperationError, operationerrfmt
from rpython.rlib.rstring import StringBuilder
from rpython.rlib import rweakref


DEFAULT_BUFFER_SIZE = 8192

def convert_size(space, w_size):
    if space.is_none(w_size):
        return -1
    else:
        return space.int_w(w_size)

def unsupported(space, message):
    w_exc = space.getattr(space.getbuiltinmodule('_io'),
                          space.wrap('UnsupportedOperation'))
    return OperationError(w_exc, space.wrap(message))

# May be called with any object
def check_readable_w(space, w_obj):
    if not space.is_true(space.call_method(w_obj, 'readable')):
        raise unsupported(space, "File or stream is not readable")

# May be called with any object
def check_writable_w(space, w_obj):
    if not space.is_true(space.call_method(w_obj, 'writable')):
        raise unsupported(space, "File or stream is not writable")

# May be called with any object
def check_seekable_w(space, w_obj):
    if not space.is_true(space.call_method(w_obj, 'seekable')):
        raise unsupported(space, "File or stream is not seekable")

class W_IOBase(Wrappable):
    cffi_fileobj = None    # pypy/module/_cffi_backend

    def __init__(self, space):
        # XXX: IOBase thinks it has to maintain its own internal state in
        # `__IOBase_closed` and call flush() by itself, but it is redundant
        # with whatever behaviour a non-trivial derived class will implement.
        self.space = space
        self.w_dict = space.newdict()
        self.__IOBase_closed = False
        self.streamholder = None # needed by AutoFlusher
        get_autoflushher(space).add(self)

    def getdict(self, space):
        return self.w_dict

    def _closed(self, space):
        # This gets the derived attribute, which is *not* __IOBase_closed
        # in most cases!
        w_closed = space.findattr(self, space.wrap('closed'))
        if w_closed is not None and space.is_true(w_closed):
            return True
        return False

    def __del__(self):
        self.clear_all_weakrefs()
        self.enqueue_for_destruction(self.space, W_IOBase.destructor,
                                     'internal __del__ of ')

    def destructor(self):
        assert isinstance(self, W_IOBase)
        space = self.space
        w_closed = space.findattr(self, space.wrap('closed'))
        try:
            # If `closed` doesn't exist or can't be evaluated as bool, then
            # the object is probably in an unusable state, so ignore.
            if w_closed is not None and not space.is_true(w_closed):
                try:
                    self._dealloc_warn_w(space, space.wrap(self))
                finally:
                    space.call_method(self, "close")
        except OperationError:
            # Silencing I/O errors is bad, but printing spurious tracebacks is
            # equally as bad, and potentially more frequent (because of
            # shutdown issues).
            pass

    def _CLOSED(self):
        # Use this macro whenever you want to check the internal `closed`
        # status of the IOBase object rather than the virtual `closed`
        # attribute as returned by whatever subclass.
        return self.__IOBase_closed

    def _unsupportedoperation(self, space, message):
        raise unsupported(space, message)

    def _check_closed(self, space, message=None):
        if message is None:
            message = "I/O operation on closed file"
        if self._closed(space):
            raise OperationError(
                space.w_ValueError, space.wrap(message))

    def check_closed_w(self, space):
        self._check_closed(space)

    def closed_get_w(self, space):
        return space.newbool(self.__IOBase_closed)

    def close_w(self, space):
        if self._CLOSED():
            return

        cffifo = self.cffi_fileobj
        self.cffi_fileobj = None
        if cffifo is not None:
            cffifo.close()

        try:
            space.call_method(self, "flush")
        finally:
            self.__IOBase_closed = True
            get_autoflushher(space).remove(self)

    def _dealloc_warn_w(self, space, w_source):
        """Called when the io is implicitly closed via the deconstructor"""
        pass

    def flush_w(self, space):
        if self._CLOSED():
            raise OperationError(
                space.w_ValueError,
                space.wrap("I/O operation on closed file"))

    def seek_w(self, space):
        self._unsupportedoperation(space, "seek")

    def tell_w(self, space):
        return space.call_method(self, "seek", space.wrap(0), space.wrap(1))

    def truncate_w(self, space):
        self._unsupportedoperation(space, "truncate")

    def fileno_w(self, space):
        self._unsupportedoperation(space, "fileno")

    def enter_w(self, space):
        self._check_closed(space)
        return space.wrap(self)

    def exit_w(self, space, __args__):
        space.call_method(self, "close")

    def iter_w(self, space):
        self._check_closed(space)
        return space.wrap(self)

    def next_w(self, space):
        w_line = space.call_method(self, "readline")
        if space.len_w(w_line) == 0:
            raise OperationError(space.w_StopIteration, space.w_None)
        return w_line

    def isatty_w(self, space):
        self._check_closed(space)
        return space.w_False

    def readable_w(self, space):
        return space.w_False

    def writable_w(self, space):
        return space.w_False

    def seekable_w(self, space):
        return space.w_False

    def getstate_w(self, space):
        raise operationerrfmt(space.w_TypeError,
                              "cannot serialize '%s' object",
                              space.type(self).getname(space))

    # ______________________________________________________________

    def readline_w(self, space, w_limit=None):
        # For backwards compatibility, a (slowish) readline().
        limit = convert_size(space, w_limit)

        old_size = -1

        has_peek = space.findattr(self, space.wrap("peek"))

        builder = StringBuilder()
        size = 0

        while limit < 0 or size < limit:
            nreadahead = 1

            if has_peek:
                w_readahead = space.call_method(self, "peek", space.wrap(1))
                if not space.isinstance_w(w_readahead, space.w_str):
                    raise operationerrfmt(
                        space.w_IOError,
                        "peek() should have returned a bytes object, "
                        "not '%s'", space.type(w_readahead).getname(space))
                length = space.len_w(w_readahead)
                if length > 0:
                    n = 0
                    buf = space.bytes_w(w_readahead)
                    if limit >= 0:
                        while True:
                            if n >= length or n >= limit:
                                break
                            n += 1
                            if buf[n-1] == '\n':
                                break
                    else:
                        while True:
                            if n >= length:
                                break
                            n += 1
                            if buf[n-1] == '\n':
                                break
                    nreadahead = n

            w_read = space.call_method(self, "read", space.wrap(nreadahead))
            if not space.isinstance_w(w_read, space.w_str):
                raise operationerrfmt(
                    space.w_IOError,
                    "peek() should have returned a bytes object, "
                    "not '%s'", space.type(w_read).getname(space))
            read = space.bytes_w(w_read)
            if not read:
                break

            size += len(read)
            builder.append(read)

            if read[-1] == '\n':
                break

        return space.wrapbytes(builder.build())

    def readlines_w(self, space, w_hint=None):
        hint = convert_size(space, w_hint)

        if hint <= 0:
            return space.newlist(space.unpackiterable(self))

        lines_w = []
        length = 0
        while True:
            w_line = space.call_method(self, "readline")
            line_length = space.len_w(w_line)
            if line_length == 0: # done
                break

            lines_w.append(w_line)

            length += line_length
            if length > hint:
                break

        return space.newlist(lines_w)

    def writelines_w(self, space, w_lines):
        self._check_closed(space)

        w_iterator = space.iter(w_lines)

        while True:
            try:
                w_line = space.next(w_iterator)
            except OperationError, e:
                if not e.match(space, space.w_StopIteration):
                    raise
                break  # done
            space.call_method(self, "write", w_line)

W_IOBase.typedef = TypeDef(
    '_IOBase',
    __module__ = "_io",
    __new__ = generic_new_descr(W_IOBase),
    __enter__ = interp2app(W_IOBase.enter_w),
    __exit__ = interp2app(W_IOBase.exit_w),
    __iter__ = interp2app(W_IOBase.iter_w),
    __next__ = interp2app(W_IOBase.next_w),
    close = interp2app(W_IOBase.close_w),
    flush = interp2app(W_IOBase.flush_w),
    seek = interp2app(W_IOBase.seek_w),
    tell = interp2app(W_IOBase.tell_w),
    truncate = interp2app(W_IOBase.truncate_w),
    fileno = interp2app(W_IOBase.fileno_w),
    isatty = interp2app(W_IOBase.isatty_w),
    readable = interp2app(W_IOBase.readable_w),
    writable = interp2app(W_IOBase.writable_w),
    seekable = interp2app(W_IOBase.seekable_w),
    _checkReadable = interp2app(check_readable_w),
    _checkWritable = interp2app(check_writable_w),
    _checkSeekable = interp2app(check_seekable_w),
    closed = GetSetProperty(W_IOBase.closed_get_w,
                            doc="True if the file is closed"),
    _checkClosed = interp2app(W_IOBase.check_closed_w),
    __dict__ = GetSetProperty(descr_get_dict, descr_set_dict, cls=W_IOBase),
    __weakref__ = make_weakref_descr(W_IOBase),

    readline = interp2app(W_IOBase.readline_w),
    readlines = interp2app(W_IOBase.readlines_w),
    writelines = interp2app(W_IOBase.writelines_w),
)

class W_RawIOBase(W_IOBase):
    # ________________________________________________________________
    # Abstract read methods, based on readinto()

    def read_w(self, space, w_size=None):
        size = convert_size(space, w_size)
        if size < 0:
            return space.call_method(self, "readall")

        w_buffer = space.call_function(space.w_bytearray, w_size)
        w_length = space.call_method(self, "readinto", w_buffer)
        if space.is_w(w_length, space.w_None):
            return w_length
        space.delslice(w_buffer, w_length, space.len(w_buffer))
        return space.call_function(space.w_bytes, w_buffer)

    def readall_w(self, space):
        builder = StringBuilder()
        while True:
            w_data = space.call_method(self, "read",
                                       space.wrap(DEFAULT_BUFFER_SIZE))
            if space.is_w(w_data, space.w_None):
                if not builder.getlength():
                    return w_data
                break

            if not space.isinstance_w(w_data, space.w_bytes):
                raise OperationError(space.w_TypeError, space.wrap(
                    "read() should return bytes"))
            data = space.bytes_w(w_data)
            if not data:
                break
            builder.append(data)
        return space.wrapbytes(builder.build())

W_RawIOBase.typedef = TypeDef(
    '_RawIOBase', W_IOBase.typedef,
    __module__ = "_io",
    __new__ = generic_new_descr(W_RawIOBase),

    read = interp2app(W_RawIOBase.read_w),
    readall = interp2app(W_RawIOBase.readall_w),
)


# ------------------------------------------------------------
# functions to make sure that all streams are flushed on exit
# ------------------------------------------------------------

class StreamHolder(object):

    def __init__(self, w_iobase):
        self.w_iobase_ref = rweakref.ref(w_iobase)
        w_iobase.autoflusher = self

    def autoflush(self, space):
        w_iobase = self.w_iobase_ref()
        if w_iobase is not None:
            try:
                space.call_method(w_iobase, 'flush')
            except OperationError, e:
                # Silencing all errors is bad, but getting randomly
                # interrupted here is equally as bad, and potentially
                # more frequent (because of shutdown issues).
                pass 


class AutoFlusher(object):
    
    def __init__(self, space):
        self.streams = {}

    def add(self, w_iobase):
        assert w_iobase.streamholder is None
        if rweakref.has_weakref_support():
            holder = StreamHolder(w_iobase)
            w_iobase.streamholder = holder
            self.streams[holder] = None
        #else:
        #   no support for weakrefs, so ignore and we
        #   will not get autoflushing

    def remove(self, w_iobase):
        holder = w_iobase.streamholder
        if holder is not None:
            del self.streams[holder]

    def flush_all(self, space):
        while self.streams:
            for streamholder in self.streams.keys():
                try:
                    del self.streams[streamholder]
                except KeyError:
                    pass    # key was removed in the meantime
                else:
                    streamholder.autoflush(space)


def get_autoflushher(space):
    return space.fromcache(AutoFlusher)