-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathIOModule.cpp
More file actions
3511 lines (3063 loc) · 110 KB
/
Copy pathIOModule.cpp
File metadata and controls
3511 lines (3063 loc) · 110 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "IOChecks.hpp"
#include "Modules.hpp"
#include "runtime/MemoryError.hpp"
#include "runtime/NotImplementedError.hpp"
#include "runtime/OSError.hpp"
#include "runtime/PyArgParser.hpp"
#include "runtime/PyBool.hpp"
#include "runtime/PyBytes.hpp"
#include "runtime/PyDict.hpp"
#include "runtime/PyFunction.hpp"
#include "runtime/PyInteger.hpp"
#include "runtime/PyList.hpp"
#include "runtime/PyMemoryView.hpp"
#include "runtime/PyNone.hpp"
#include "runtime/PyObject.hpp"
#include "runtime/PyString.hpp"
#include "runtime/PyTuple.hpp"
#include "runtime/PyType.hpp"
#include "runtime/StopIteration.hpp"
#include "runtime/Value.hpp"
#include "runtime/ValueError.hpp"
#include "runtime/types/api.hpp"
#include "runtime/types/builtin.hpp"
#include "utilities.hpp"
#include "vm/VM.hpp"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <optional>
#include <unistd.h>
#include <variant>
#if defined(__GLIBCXX__) || defined(__GLIBCPP__)
#include <ext/stdio_filebuf.h>
#endif
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
namespace py {
namespace {
PyType *s_io_base = nullptr;
PyType *s_io_raw_iobase = nullptr;
PyType *s_io_buffered_io_base = nullptr;
PyType *s_io_buffered_reader = nullptr;
PyType *s_io_buffered_writer = nullptr;
PyType *s_io_buffered_rwpair = nullptr;
PyType *s_io_buffered_random = nullptr;
PyType *s_io_textiobase = nullptr;
PyType *s_io_incremental_newline_decoder = nullptr;
PyType *s_io_bytesio = nullptr;
PyType *s_io_fileio = nullptr;
PyType *s_io_stringio = nullptr;
PyType *s_io_textiowrapper = nullptr;
PyType *s_blocking_io_error = nullptr;
PyType *s_unsupported_operation_type = nullptr;
}// namespace
static constexpr size_t s_default_buffer_size = 8192;
Exception *unsupported_operation(PyTuple *args, PyDict *kwargs)
{
ASSERT(s_unsupported_operation_type);
auto *obj = s_unsupported_operation_type->call(args, kwargs).unwrap();
ASSERT(obj->type()->issubclass(Exception::class_type()));
return static_cast<Exception *>(obj);
}
class IOBase : public PyBaseObject
{
friend class ::Heap;
private:
IOBase() : IOBase(s_io_base->type()) {}
protected:
IOBase(const PyType *type) : PyBaseObject(type->underlying_type()) {}
private:
PyResult<bool> is_closed() const
{
auto result = lookup_attribute(PyString::create("__IOBase_closed").unwrap());
if (std::get<0>(result).is_err()) return Err(std::get<0>(result).unwrap_err());
return Ok(std::get<1>(result) == LookupAttrResult::FOUND);
}
PyResult<std::monostate> check_closed() const
{
auto closed = lookup_attribute(PyString::create("closed").unwrap());
if (std::get<0>(closed).is_err()) return Err(std::get<0>(closed).unwrap_err());
if (std::get<1>(closed) == LookupAttrResult::FOUND) {
return truthy(std::get<0>(closed).unwrap(), VirtualMachine::the().interpreter())
.and_then([](bool closed) -> PyResult<std::monostate> {
if (!closed) return Ok(std::monostate{});
return Err(value_error("I/O operation on closed file."));
});
} else {
return Ok(std::monostate{});
}
}
public:
static constexpr std::string_view __doc__ =
"The abstract base class for all I/O classes, acting on streams of\n"
"bytes. There is no public constructor.\n"
"\n"
"This class provides dummy implementations for many methods that\n"
"derived classes can override selectively; the default implementations\n"
"represent a file that cannot be read, written or seeked.\n"
"\n"
"Even though IOBase does not declare read, readinto, or write because\n"
"their signatures will vary, implementations and clients should\n"
"consider those methods part of the interface. Also, implementations\n"
"may raise UnsupportedOperation when operations they do not support are\n"
"called.\n"
"\n"
"The basic type used for binary data read from or written to a file is\n"
"bytes. Other bytes-like objects are accepted as method arguments too.\n"
"In some cases (such as readinto), a writable object is required. Text\n"
"I/O classes work with str data.\n"
"\n"
"Note that calling any method (except additional calls to close(),\n"
"which are ignored) on a closed stream should raise a ValueError.\n"
"\n"
"IOBase (and its subclasses) support the iterator protocol, meaning\n"
"that an IOBase object can be iterated over yielding the lines in a\n"
"stream.\n"
"\n"
"IOBase also supports the :keyword:`with` statement. In this example,\n"
"fp is closed after the suite of the with statement is complete:\n"
"\n"
"with open('spam.txt', 'r') as fp:\n"
" fp.write('Spam and eggs!')\n";
static PyResult<IOBase *> create(const PyType *type)
{
auto &heap = VirtualMachine::the().heap();
auto *result = heap.allocate<IOBase>(type);
if (!result) { return Err(memory_error(sizeof(IOBase))); }
return Ok(result);
}
static PyResult<PyObject *> __new__(const PyType *type, PyTuple *, PyDict *)
{
return IOBase::create(type);
}
PyResult<PyObject *> __iter__() const
{
if (auto closed = check_closed(); closed.is_err()) return Err(closed.unwrap_err());
return Ok(const_cast<IOBase *>(this));
}
PyResult<PyObject *> __next__()
{
return get_method(PyString::create("readline").unwrap()).and_then([](PyObject *readline) {
return readline->call(PyTuple::create().unwrap(), PyDict::create().unwrap())
.and_then([](PyObject *line) -> PyResult<PyObject *> {
auto m = line->as_mapping();
if (auto size = m.unwrap().len(); size.is_err()) {
return Err(size.unwrap_err());
} else {
if (size.unwrap() == 0) {
// since we don't handle the situation where __next__ returns
// Ok(nullptr), we make an extra allocation here for StopIteration,
// and have the same semantics as cpython
return Err(stop_iteration());
} else {
return Ok(line);
}
}
});
});
}
PyResult<PyObject *> close() const
{
auto closed = is_closed();
if (closed.is_err()) return Err(closed.unwrap_err());
if (closed.unwrap()) return Ok(py_none());
auto flushed =
get_method(PyString::create("flush").unwrap()).and_then([](PyObject *method) {
return method->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
if (flushed.is_err()) return flushed;
return Ok(py_none());
}
PyResult<PyObject *> fileno() const
{
return Err(unsupported_operation(PyTuple::create(String{ "fileno" }).unwrap(), nullptr));
}
PyResult<PyObject *> flush() const
{
auto closed = is_closed();
if (closed.is_err()) return Err(closed.unwrap_err());
if (closed.unwrap()) { return Err(value_error("I/O operation on closed file.")); }
return Ok(py_none());
}
PyResult<PyObject *> isatty() const
{
return check_closed().and_then([](auto) { return Ok(py_false()); });
}
PyResult<PyObject *> readline(int64_t limit) const
{
auto peek = lookup_attribute(PyString::create("peek").unwrap());
if (std::get<0>(peek).is_err()) return std::get<0>(peek);
const bool peakable = std::get<1>(peek) == LookupAttrResult::FOUND;
std::vector<std::byte> buffer;
while (limit < 0 || static_cast<int64_t>(buffer.size()) < limit) {
int64_t nreadahead = 1;
if (peakable) {
auto readahead = std::get<0>(peek).unwrap()->call(
PyTuple::create(Number{ 1 }).unwrap(), PyDict::create().unwrap());
if (readahead.is_err()) return readahead;
if (!as<PyBytes>(readahead.unwrap())) {
// FIXME: should be a OSError
return Err(value_error("peek() should have returned a bytes object, not '{}'",
readahead.unwrap()->type()->name()));
}
auto readahead_bytes = as<PyBytes>(readahead.unwrap());
if (!readahead_bytes->value().b.empty()) {
const auto &bytes = readahead_bytes->value().b;
const auto upper = limit == -1
? bytes.size()
: std::min(static_cast<int64_t>(bytes.size()), limit);
auto it = std::find(bytes.begin(), bytes.begin() + upper, std::byte{ '\n' });
nreadahead = std::distance(bytes.begin(), it);
}
}
auto b = get_method(PyString::create("read").unwrap())
.and_then([nreadahead](PyObject *read) {
return read->call(PyTuple::create(Number{ nreadahead }).unwrap(),
PyDict::create().unwrap());
});
if (b.is_err()) return b;
if (!as<PyBytes>(b.unwrap())) {
// FIXME: should be a OSError
return Err(value_error("read() should have returned a bytes object, not '{}'",
b.unwrap()->type()->name()));
}
auto *new_bytes = as<PyBytes>(b.unwrap());
if (new_bytes->value().b.size() == 0) { break; }
buffer.insert(buffer.end(), new_bytes->value().b.begin(), new_bytes->value().b.end());
if (static_cast<char>(buffer.back()) == '\n') { break; }
}
return PyBytes::create(Bytes{ std::move(buffer) });
}
PyResult<PyObject *> readlines(int64_t hint) const
{
auto result_ = PyList::create();
if (result_.is_err()) return result_;
auto *result = result_.unwrap();
auto it_ = iter();
if (it_.is_err()) return it_;
auto *it = it_.unwrap();
size_t length = 0;
while (true) {
auto line = it->next();
if (line.is_err()) {
if (line.unwrap_err()->type() == stop_iteration()->type()) {
break;
} else {
return line;
}
}
result->elements().push_back(line.unwrap());
if (hint > 0) {
if (auto m = result->as_mapping(); m.is_ok()) {
if (auto size = m.unwrap().len(); size.is_err()) {
return Err(size.unwrap_err());
} else {
length += size.unwrap();
if (static_cast<int64_t>(length) > hint) { break; }
}
} else {
return Err(m.unwrap_err());
}
}
}
return Ok(result);
}
PyResult<PyObject *> seek() const
{
// FIXME
return Err(unsupported_operation(PyTuple::create(String{ "seek" }).unwrap(), nullptr));
}
PyResult<PyObject *> seekable() const { return Ok(py_false()); }
PyResult<PyObject *> tell() const
{
return get_method(PyString::create("seek").unwrap()).and_then([](auto *seek) {
return seek->call(
PyTuple::create(Number{ 0 }, Number{ 1 }).unwrap(), PyDict::create().unwrap());
});
}
PyResult<PyObject *> truncate() const
{
return Err(unsupported_operation(PyTuple::create(String{ "truncate" }).unwrap(), nullptr));
}
PyResult<PyObject *> writable() const { return Ok(py_false()); }
PyResult<PyObject *> writelines(PyObject *lines) const
{
if (auto closed = check_closed(); closed.is_err()) return Err(closed.unwrap_err());
auto iter_ = lines->iter();
if (iter_.is_err()) return iter_;
auto *iter = iter_.unwrap();
while (true) {
auto line = iter->next();
if (line.is_err()) {
if (line.unwrap_err()->type() == stop_iteration()->type()) {
break;
} else {
return line;
}
}
auto write = get_method(PyString::create("write").unwrap());
if (write.is_err()) return write;
auto res = write.unwrap()->call(
PyTuple::create(line.unwrap()).unwrap(), PyDict::create().unwrap());
if (res.is_err()) return res;
}
return Ok(py_none());
}
PyResult<PyObject *> check_seekable_() { return check_seekable(this); }
PyResult<PyObject *> check_readable_() { return check_readable(this); }
PyResult<PyObject *> check_writable_() { return check_writable(this); }
PyObject *dict() const { return m_attributes; }
PyType *static_type() const override { return s_io_base; }
PyResult<PyObject *> __enter__(PyTuple *, PyDict *)
{
return check_closed()
.and_then([this](auto) -> PyResult<PyObject *> { return Ok(this); })
.or_else([](auto *err) -> PyResult<PyObject *> { return Err(err); });
}
PyResult<PyObject *> __exit__(PyTuple *, PyDict *)
{
return get_method(PyString::create("close").unwrap()).and_then([](PyObject *close) {
return close->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
}
static PyType *register_type(PyModule *module)
{
if (!s_io_base) {
s_io_base =
klass<IOBase>(module, "_IOBase")
.def("close", &IOBase::close)
.property_readonly("closed",
[](IOBase *self) {
auto closed = self->is_closed();
if (closed.is_err()) { TODO(); }
return Ok(closed.unwrap() ? py_true() : py_false());
})
.property_readonly("__dict__", [](IOBase *self) { return Ok(self->dict()); })
.def("fileno", &IOBase::fileno)
.def("flush", &IOBase::flush)
.def("isatty", &IOBase::isatty)
.def("readline",
[](IOBase *self, PyTuple *args, PyDict *kwargs) -> PyResult<PyObject *> {
ASSERT(!kwargs || kwargs->map().empty());
ASSERT(args);
if (args->elements().empty()) {
return self->readline(-1);
} else if (args->elements().size() > 1) {
return Err(value_error(
"BaseIO.readline expected at most one argument (got {})",
args->elements().size()));
} else {
return PyObject::from(args->elements()[0])
.and_then([self](auto *limit) -> PyResult<PyObject *> {
if (!as<PyInteger>(limit)) { return Err(type_error("")); }
return self->readline(as<PyInteger>(limit)->as_i64());
});
}
})
.def("readlines",
[](IOBase *self, PyTuple *args, PyDict *kwargs) -> PyResult<PyObject *> {
ASSERT(!kwargs || kwargs->map().empty());
ASSERT(args);
if (args->elements().empty()) {
return self->readline(-1);
} else if (args->elements().size() > 1) {
return Err(value_error(
"BaseIO.readlines expected at most one argument (got {})",
args->elements().size()));
} else {
return PyObject::from(args->elements()[0])
.and_then([self](auto *hint) -> PyResult<PyObject *> {
if (!as<PyInteger>(hint)) { return Err(type_error("")); }
return self->readlines(as<PyInteger>(hint)->as_i64());
});
}
})
.def("seek", &IOBase::seek)
.def("seekable", &IOBase::seekable)
.def("tell", &IOBase::tell)
.def("truncate", &IOBase::truncate)
.def("writable", &IOBase::writable)
.def("writelines",
[](IOBase *self, PyTuple *args, PyDict *kwargs) -> PyResult<PyObject *> {
ASSERT(!kwargs || kwargs->map().empty());
ASSERT(args);
if (args->elements().empty()) {
return Err(
value_error("BaseIO.readlines expected one argument (got 0)"));
} else if (args->elements().size() > 1) {
return Err(value_error(
"BaseIO.readlines expected at most one argument (got {})",
args->elements().size()));
} else {
return PyObject::from(args->elements()[0])
.and_then([self](auto *lines) -> PyResult<PyObject *> {
return self->writelines(lines);
});
}
})
.def("_checkSeekable", &IOBase::check_seekable_)
.def("_checkReadable", &IOBase::check_readable_)
.def("_checkWritable", &IOBase::check_writable_)
.def("__enter__", &IOBase::__enter__)
.def("__exit__", &IOBase::__exit__)
.finalize();
}
module->add_symbol(PyString::create("_IOBase").unwrap(), s_io_base);
return s_io_base;
}
protected:
static PyResult<PyObject *> check_seekable(PyObject *self)
{
return self->get_method(PyString::create("seekable").unwrap())
.and_then([](auto *seekable) { return seekable->call(nullptr, nullptr); })
.and_then([](auto *result) -> PyResult<PyObject *> {
if (result != py_true()) {
return Err(unsupported_operation(
PyTuple::create(String{ "File or stream is not seekable." }).unwrap(),
nullptr));
}
return Ok(py_true());
});
}
static PyResult<PyObject *> check_readable(PyObject *self)
{
return self->get_method(PyString::create("readable").unwrap())
.and_then([](auto *readable) { return readable->call(nullptr, nullptr); })
.and_then([](auto *result) -> PyResult<PyObject *> {
if (result != py_true()) {
return Err(unsupported_operation(
PyTuple::create(String{ "File or stream is not readable." }).unwrap(),
nullptr));
}
return Ok(py_true());
});
}
static PyResult<PyObject *> check_writable(PyObject *self)
{
return self->get_method(PyString::create("writable").unwrap())
.and_then([](auto *writable) { return writable->call(nullptr, nullptr); })
.and_then([](auto *result) -> PyResult<PyObject *> {
if (result != py_true()) {
return Err(unsupported_operation(
PyTuple::create(String{ "File or stream is not writable." }).unwrap(),
nullptr));
}
return Ok(py_true());
});
}
};
class RawIOBase : public IOBase
{
friend class ::Heap;
private:
RawIOBase() : RawIOBase(s_io_raw_iobase->type()) {}
protected:
RawIOBase(const PyType *type) : IOBase(type) {}
public:
static constexpr std::string_view __doc__ = "Base class for raw binary I/O.";
static PyResult<RawIOBase *> create(const PyType *type)
{
auto &heap = VirtualMachine::the().heap();
auto *result = heap.allocate<RawIOBase>(type);
if (!result) { return Err(memory_error(sizeof(RawIOBase))); }
return Ok(result);
}
static PyResult<PyObject *> __new__(const PyType *type, PyTuple *, PyDict *)
{
return RawIOBase::create(type);
}
PyType *static_type() const override { return s_io_raw_iobase; }
PyResult<PyObject *> read(int64_t n)
{
if (n < 0) {
return get_method(PyString::create("readall").unwrap()).and_then([](PyObject *readall) {
return readall->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
}
auto bytes_ = PyBytes::create();
if (bytes_.is_err()) return bytes_;
auto *bytes = bytes_.unwrap();
return get_method(PyString::create("readinto").unwrap())
.and_then([bytes](PyObject *readinto) {
return readinto->call(PyTuple::create(bytes).unwrap(), PyDict::create().unwrap());
})
.and_then([](PyObject *res) -> PyResult<int64_t> {
if (!as<PyInteger>(res)) {
return Err(type_error(
"expected readinto to return an int, got '{}'", res->type()->name()));
}
return Ok(as<PyInteger>(res)->as_i64());
})
.and_then([bytes](const int64_t &n) {
const auto &b = bytes->value().b;
std::vector<std::byte> result{ b.begin(), b.begin() + n };
return PyBytes::create(Bytes{ std::move(result) });
});
}
PyResult<PyObject *> readinto(PyObject *) const
{
return Err(not_implemented_error("_RawIOBase.readinto"));
}
PyResult<PyObject *> write(PyObject *) const
{
return Err(not_implemented_error("_RawIOBase.write"));
}
static PyType *register_type(PyModule *module)
{
if (!s_io_raw_iobase) {
s_io_raw_iobase =
klass<RawIOBase>(module, "_RawIOBase", s_io_base)
.def("read",
[](RawIOBase *self, PyTuple *args, PyDict *kwargs) -> PyResult<PyObject *> {
ASSERT(!kwargs || kwargs->map().empty());
int64_t n = -1;
if (args && args->elements().size() > 1) {
return Err(value_error(
"_RawIOBase.read expected at most one argument (got {})",
args->elements().size()));
} else if (args && args->elements().size() == 1) {
auto arg0 = PyObject::from(args->elements()[0]);
if (arg0.is_err()) return arg0;
if (!as<PyInteger>(arg0.unwrap()) && arg0.unwrap() != py_none()) {
return Err(
type_error("argument should be integer or None, not '{}'",
arg0.unwrap()->type()->name()));
}
if (arg0.unwrap() != py_none()) {
n = as<PyInteger>(arg0.unwrap())->as_i64();
}
}
return self->read(n);
})
// .def("readall", &RawIOBase::readall)
.def("readinto", &RawIOBase::readinto)
.def("write", &RawIOBase::write)
.finalize();
}
module->add_symbol(PyString::create("_RawIOBase").unwrap(), s_io_raw_iobase);
return s_io_raw_iobase;
}
};
class BufferedIOBase : public IOBase
{
friend class ::Heap;
BufferedIOBase() : BufferedIOBase(s_io_buffered_io_base) {}
protected:
BufferedIOBase(PyType *type) : IOBase(type) {}
public:
static constexpr std::string_view __doc__ =
"Base class for buffered IO objects.\n"
"\n"
"The main difference with RawIOBase is that the read() method\n"
"supports omitting the size argument, and does not have a default\n"
"implementation that defers to readinto().\n"
"\n"
"In addition, read(), readinto() and write() may raise\n"
"BlockingIOError if the underlying raw stream is in non-blocking\n"
"mode and not ready; unlike their raw counterparts, they will never\n"
"return None.\n"
"\n"
"A typical implementation should not inherit from a RawIOBase\n"
"implementation, but wrap one.\n";
static PyResult<BufferedIOBase *> create(const PyType *type)
{
auto &heap = VirtualMachine::the().heap();
auto *result = heap.allocate<BufferedIOBase>(const_cast<PyType *>(type));
if (!result) { return Err(memory_error(sizeof(BufferedIOBase))); }
return Ok(result);
}
static PyResult<PyObject *> __new__(const PyType *type, PyTuple *, PyDict *)
{
return BufferedIOBase::create(type);
}
PyResult<PyObject *> detach() const
{
return Err(unsupported_operation(PyTuple::create(String{ "detach" }).unwrap(), nullptr));
}
PyResult<PyObject *> read(PyTuple *, PyDict *) const
{
return Err(unsupported_operation(PyTuple::create(String{ "read" }).unwrap(), nullptr));
}
PyResult<PyObject *> read1(PyTuple *, PyDict *) const
{
return Err(unsupported_operation(PyTuple::create(String{ "read1" }).unwrap(), nullptr));
}
PyResult<PyObject *> readinto_generic(PyBuffer &buffer, bool readinto1) const
{
const auto method_name = readinto1 ? "read1" : "read";
auto data =
get_method(PyString::create(method_name).unwrap()).and_then([&buffer](PyObject *read) {
return read->call(
PyTuple::create(Number{ buffer.len }).unwrap(), PyDict::create().unwrap());
});
if (data.is_err()) return data;
if (!as<PyBytes>(data.unwrap())) { return Err(type_error("read() should return bytes")); }
auto data_bytes = as<PyBytes>(data.unwrap())->value().b;
const auto len = data_bytes.size();
if (static_cast<int64_t>(len) > buffer.len) {
return Err(
value_error("read() returned too much data: "
"{} bytes requested, {} returned",
buffer.len,
len));
}
std::copy_n(data_bytes.begin(),
data_bytes.size(),
static_cast<std::byte *>(buffer.buf->get_buffer()));
return PyInteger::create(static_cast<int64_t>(len));
}
PyResult<PyObject *> readinto(PyBuffer &buffer) const
{
return readinto_generic(buffer, false);
}
PyResult<PyObject *> readinto1(PyBuffer &buffer) const
{
return readinto_generic(buffer, true);
}
PyResult<PyObject *> write(PyTuple *, PyDict *) const
{
return Err(unsupported_operation(PyTuple::create(String{ "write" }).unwrap(), nullptr));
}
PyType *static_type() const override { return s_io_buffered_io_base; }
static PyType *register_type(PyModule *module)
{
if (!s_io_buffered_io_base) {
s_io_buffered_io_base =
klass<BufferedIOBase>(module, "_BufferedIOBase", s_io_base)
.def("detach", &BufferedIOBase::detach)
.def("read", &BufferedIOBase::read)
.def("read1", &BufferedIOBase::read1)
.def("readinto",
[](BufferedIOBase *self,
PyTuple *args,
PyDict *kwargs) -> py::PyResult<py::PyObject *> {
ASSERT(!kwargs || kwargs->map().empty());
if (!args || args->elements().size() != 1) {
return Err(
type_error("_BufferedIOBase.readinto() takes exactly "
"one argument ({} given)",
args->elements().size()));
}
auto arg = PyObject::from(args->elements()[0]);
if (arg.is_err()) return arg;
PyBuffer buffer;
int flags = 1;
return arg.unwrap()
->get_buffer(buffer, flags)
.or_else([arg](auto) -> PyResult<std::monostate> {
return Err(type_error(
"readinto() argument must be read-write bytes-like "
"object, not {}",
arg.unwrap()->type()->name()));
})
.and_then(
[&buffer, arg, self](auto) -> py::PyResult<py::PyObject *> {
if (buffer.is_ccontiguous()) {
return self->readinto(buffer);
} else {
return Err(type_error(
"readinto() argument must be a contiguous "
"buffer, not {}",
arg.unwrap()->type()->name()));
}
});
})
.def("readinto1",
[](BufferedIOBase *self,
PyTuple *args,
PyDict *kwargs) -> py::PyResult<py::PyObject *> {
ASSERT(!kwargs || kwargs->map().empty());
if (!args || args->elements().size() != 1) {
return Err(
type_error("_BufferedIOBase.readinto1() takes exactly "
"one argument ({} given)",
args->elements().size()));
}
auto arg = PyObject::from(args->elements()[0]);
if (arg.is_err()) return arg;
PyBuffer buffer;
int flags = 1;
return arg.unwrap()
->get_buffer(buffer, flags)
.or_else([arg](auto) -> PyResult<std::monostate> {
return Err(type_error(
"readinto1() argument must be read-write bytes-like "
"object, not {}",
arg.unwrap()->type()->name()));
})
.and_then(
[&buffer, arg, self](auto) -> py::PyResult<py::PyObject *> {
if (buffer.is_ccontiguous()) {
return self->readinto(buffer);
} else {
return Err(type_error(
"readinto() argument must be a contiguous "
"buffer, not {}",
arg.unwrap()->type()->name()));
}
});
})
.def("write", &BufferedIOBase::write)
.finalize();
}
module->add_symbol(PyString::create("_BufferedIOBase").unwrap(), s_io_buffered_io_base);
return s_io_buffered_io_base;
}
};
template<typename T>
// requires(std::is_base_of_v<PyObject, T>)
struct Buffered : IOChecks<Buffered<T>>
{
PyObject *raw{ nullptr };
bool ok{ false };
bool detached{ false };
bool readable_{ false };
bool writable_{ false };
bool finalizing{ false };
bool fast_closed_checks{ false };
std::unique_ptr<std::streambuf> buffer;
bool valid_readbuffer() const { return readable_ && buffer && buffer->in_avail() != -1; }
int64_t readahead() const { return valid_readbuffer() ? buffer->in_avail() : 0; }
bool is_initialized() const { return ok && raw; }
bool is_detached() const { return detached; }
PyResult<std::monostate> check_closed(std::string_view err_msg) const
{
if (is_closed() && readahead() == 0) { return Err(value_error(std::string{ err_msg })); }
return Ok(std::monostate{});
}
PyResult<PyObject *> detach()
{
return static_cast<T *>(this)
->get_method(PyString::create("flush").unwrap())
.and_then([](PyObject *flush) {
return flush->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
})
.and_then([this](PyObject *) {
auto *raw = this->raw;
this->raw = nullptr;
this->detached = true;
this->ok = false;
return Ok(raw);
});
}
PyResult<PyObject *> simple_flush() const
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
return raw->get_method(PyString::create("flush").unwrap()).and_then([](PyObject *flush) {
return flush->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
}
PyResult<PyObject *> flush_and_rewind();
PyResult<bool> closed() const
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
return raw->get_attribute(PyString::create("closed").unwrap())
.and_then([](PyObject *closed) {
return truthy(closed, VirtualMachine::the().interpreter());
});
}
PyResult<PyObject *> close()
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
// FIXME add lock
auto r = closed();
if (r.is_err()) return Err(r.unwrap_err());
if (r.unwrap()) return Ok(py_none());
if (finalizing) { TODO(); }
auto res =
static_cast<T *>(this)
->get_method(PyString::create("flush").unwrap())
.and_then([](PyObject *flush) -> PyResult<PyObject *> {
return flush->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
res = raw->get_method(PyString::create("close").unwrap())
.and_then([](PyObject *close) -> PyResult<PyObject *> {
return close->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
if (buffer) { buffer = nullptr; }
return res;
}
PyResult<PyObject *> seekable() const
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
return static_cast<const T *>(this)
->raw->get_method(PyString::create("seekable").unwrap())
.and_then([](PyObject *seekable) -> PyResult<PyObject *> {
return seekable->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
}
PyResult<PyObject *> writable() const
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
return static_cast<const T *>(this)
->raw->get_method(PyString::create("writable").unwrap())
.and_then([](PyObject *writable) -> PyResult<PyObject *> {
return writable->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
}
PyResult<PyObject *> readable() const
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
return static_cast<const T *>(this)
->get_method(PyString::create("readable").unwrap())
.and_then([](PyObject *readable) -> PyResult<PyObject *> {
return readable->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
}
PyResult<PyObject *> fileno() const
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
return static_cast<const T *>(this)
->raw->get_method(PyString::create("fileno").unwrap())
.and_then([](PyObject *fileno) -> PyResult<PyObject *> {
return fileno->call(PyTuple::create().unwrap(), PyDict::create().unwrap());
});
}
PyResult<PyObject *> isatty() const
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
return static_cast<const T *>(this)
->raw->get_method(PyString::create("isatty").unwrap())
.and_then([](PyObject *isatty) -> PyResult<PyObject *> {
return isatty->call(nullptr, nullptr);
});
}
PyResult<PyObject *> _dealloc_warn(PyObject *source) const
{
if (this->ok && this->raw) {
// Best-effort warning fired from a deallocation path; any
// exception raised by the user's _dealloc_warn override has
// nowhere useful to land, so deliberately discard.
(void)this->raw->get_method(PyString::create("_dealloc_warn").unwrap())
.and_then([source](PyObject *_dealloc_warn) {
return _dealloc_warn->call(
PyTuple::create(source).unwrap(), PyDict::create().unwrap());
});
}
return Ok(py_none());
}
bool is_closed() const
{
if (!buffer) return false;
if (this->fast_closed_checks) {
TODO();
} else {
return closed().or_else([](auto) { return Ok(false); }).unwrap();
}
}
PyResult<PyObject *> read(int64_t n)
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
if (n < -1) { return Err(value_error("read length must be non-negative or -1")); }
if (is_closed()) { return Err(value_error("read of closed file")); }
if (n == -1) {
return static_cast<T *>(this)->readall();
} else {
auto res = static_cast<T *>(this)->readfast(n);
if (res.is_ok() && res.unwrap() != py_none()) { return res; }
return static_cast<T *>(this)->readgeneric(n);
}
}
PyResult<PyObject *> read1(int64_t n)
{
if (auto err = this->check_initialized(); err.is_err()) return Err(err.unwrap_err());
if (n < 0) {
// TODO: determine actual buffer size
n = 4096;
}
if (is_closed()) { return Err(value_error("read of closed file")); }
if (n == 0) { return PyBytes::create(); }
const auto have = readahead();
if (have > 0) { return static_cast<T *>(this)->readfast(std::min<int64_t>(n, have)); }
Bytes b;
b.b.resize(n);