From 17283e25717b1067f3abc7ef6512815b62254bca Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 20:39:39 +0200 Subject: [PATCH 1/6] io: each_codepoint on IO/File, symbol whence, lineno=/sysseek/ungetc coercion (+25 core/io) Read/positioning surface conformance for core/io: - IO#each_codepoint: moved from the StringIO-only block to the shared read protocol (defStringIORead) so File/IO carry it, not only StringIO (rb_io_each_codepoint, io.c:4887). each_codepoint_spec 0->10. - IO#seek / IO#sysseek: accept the :SET/:CUR/:END (and :DATA/:HOLE) whence symbols via a new seekWhence helper mirroring interpret_seek_whence (io.c:2449); sysseek now coerces its offset through #to_int (NUM2OFFT). seek 11->14, sysseek 5->10. - IO#pos / IO#pos=: raise IOError "closed stream" on a real IO/File but not on StringIO (MRI: StringIO#pos tolerates a closed stream). pos 5->7. - IO#lineno=: coerce via #to_int so a Float truncates and a #to_int object is accepted (rb_io_set_lineno, io.c:4422; NUM2INT). lineno 4->7. - IO#ungetc: coerce a non-Integer argument with #to_str (StringValue) so nil and non-String objects raise the conversion TypeError (rb_io_ungetc, io.c:5230). ungetc 8->10. core/io: pass 923->948, fail 268->262, error 238->219. ruby/spec: core/io/{each_codepoint,seek,sysseek,pos,lineno,ungetc}_spec.rb Co-Authored-By: Claude Opus 4.8 --- internal/vm/io.go | 92 ++++++++++++++++++++++++++--------- internal/vm/io_descriptors.go | 39 +++++++-------- 2 files changed, 87 insertions(+), 44 deletions(-) diff --git a/internal/vm/io.go b/internal/vm/io.go index 69c41046..e114c537 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -744,16 +744,25 @@ func defStringIORead(cls *RClass) { // #eof is a true alias of #eof?, as in MRI. cls.methods["eof"] = cls.methods["eof?"] cls.define("pos", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return object.IntValue(int64(self.(*IOObj).pos)) + o := self.(*IOObj) + // A real IO/File raises on a closed stream; StringIO#pos tolerates it (MRI). + if o.closed && !ioIsStringIO(o) { + raise("IOError", "closed stream") + } + return object.IntValue(int64(o.pos)) }) // #tell is a true alias of #pos, as in MRI. cls.methods["tell"] = cls.methods["pos"] cls.define("pos=", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + o := self.(*IOObj) + if o.closed && !ioIsStringIO(o) { // real IO/File raises; StringIO tolerates it + raise("IOError", "closed stream") + } n := int(vm.toIntCoerce(args[0])) if n < 0 { raise("Errno::EINVAL", "Invalid argument") } - self.(*IOObj).pos = n + o.pos = n return args[0] }) cls.define("seek", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { @@ -764,7 +773,7 @@ func defStringIORead(cls *RClass) { amount := int(vm.toIntCoerce(args[0])) whence := 0 if len(args) > 1 { - whence = int(vm.toIntCoerce(args[1])) + whence = vm.seekWhence(args[1]) } var newPos int switch whence { @@ -990,17 +999,72 @@ func defStringIORead(cls *RClass) { } return self }) + // #each_codepoint (rb_io_each_codepoint, io.c) yields each character's integer + // codepoint from the current position; MRI raises ArgumentError on an invalid / + // incomplete byte sequence and returns an Enumerator (size nil) with no block. + // It lives here on the shared read protocol so File/IO carry it, not only + // StringIO. + cls.define("each_codepoint", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) object.Value { + o := self.(*IOObj) + if blk == nil { // no block ⇒ an Enumerator (buildable even on a closed stream) + return enumForSized(self, "each_codepoint", enumSizeNil) + } + ioCheckReadable(o) // iterating an unreadable stream raises, as in MRI + for o.pos < len(o.buf) { + r, sz := utf8.DecodeRune(o.buf[o.pos:]) + if r == utf8.RuneError && sz <= 1 { // a lone continuation / invalid byte + raise("ArgumentError", "invalid byte sequence in UTF-8") + } + o.pos += sz + vm.callBlock(blk, []object.Value{object.IntValue(int64(r))}) + } + return self + }) // #each is a true alias of #each_line — it must share the method entry so // IO.instance_method(:each) == IO.instance_method(:each_line), as in MRI. cls.methods["each"] = cls.methods["each_line"] } +// seekWhence resolves a seek / sysseek whence argument to a SEEK_* constant, +// mirroring MRI's interpret_seek_whence (io.c): the symbols :SET/:CUR/:END and +// :DATA/:HOLE map to their constants, and anything else is coerced through +// #to_int (a Symbol that is not one of those raises the Integer TypeError). +func (vm *VM) seekWhence(v object.Value) int { + if s, ok := v.(object.Symbol); ok { + switch string(s) { + case "SET": + return 0 + case "CUR": + return 1 + case "END": + return 2 + case "DATA": + return 3 + case "HOLE": + return 4 + } + raise("TypeError", "no implicit conversion of Symbol into Integer") + } + return int(vm.toIntCoerce(v)) +} + +// ioIsStringIO reports whether o is a StringIO (or a subclass), which — unlike a +// real IO/File — tolerates #pos / #pos= on a closed stream rather than raising. +func ioIsStringIO(o *IOObj) bool { + for c := o.cls; c != nil; c = c.super { + if c.name == "StringIO" { + return true + } + } + return false +} + // defStringIOExtra installs the StringIO-only surface that MRI adds on top of the // shared read/write protocol: the allocate/new/open class methods, the private // #initialize and #reopen instance methods (which share the backing-string setup -// in stringIOSetup), #string=, #each_codepoint, and the StringIO-specific -// overrides of #sync/#binmode/#close_read/#close_write/#fcntl whose behaviour -// differs from a real IO's. +// in stringIOSetup), #string=, and the StringIO-specific overrides of +// #sync/#binmode/#close_read/#close_write/#fcntl whose behaviour differs from a +// real IO's. // includeStringIOEnumerable mixes Enumerable into StringIO (whose #each yields // lines), as in MRI. It runs after the prelude, where Enumerable is defined. func (vm *VM) includeStringIOEnumerable() { @@ -1073,22 +1137,6 @@ func defStringIOExtra(vm *VM, cls *RClass) { o.pos, o.lineno = 0, 0 return s }) - cls.define("each_codepoint", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) object.Value { - o := self.(*IOObj) - if blk == nil { // no block ⇒ an Enumerator (buildable even on a closed stream) - return enumForSized(self, "each_codepoint", enumSizeNil) - } - ioCheckReadable(o) // iterating an unreadable stream raises, as in MRI - for o.pos < len(o.buf) { - r, sz := utf8.DecodeRune(o.buf[o.pos:]) - if r == utf8.RuneError && sz <= 1 { // a lone continuation / invalid byte - raise("ArgumentError", "invalid byte sequence in UTF-8") - } - o.pos += sz - vm.callBlock(blk, []object.Value{object.IntValue(int64(r))}) - } - return self - }) // StringIO#sync is always true and cannot be turned off, unlike a real IO's. cls.define("sync", func(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { return object.Bool(true) diff --git a/internal/vm/io_descriptors.go b/internal/vm/io_descriptors.go index dd6555db..69cb558e 100644 --- a/internal/vm/io_descriptors.go +++ b/internal/vm/io_descriptors.go @@ -64,18 +64,16 @@ func defIOReadExtra(cls *RClass) { } return object.NilV }) - cls.define("ungetc", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + cls.define("ungetc", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { o := self.(*IOObj) ioCheckReadable(o) - switch a := args[0].(type) { - case object.Integer: + // rb_io_ungetc: an Integer is the codepoint (encoded to bytes); anything else + // is coerced with StringValue (#to_str), so nil / a non-String object raises + // "no implicit conversion of into String". + if a, ok := args[0].(object.Integer); ok { ioUnget(o, []byte(string(rune(a)))) - case *object.String: - ioUnget(o, a.Bytes()) - default: - if args[0] != object.NilV { - raise("TypeError", "no implicit conversion of %s into String", classNameOf(args[0])) - } + } else { + ioUnget(o, vm.strToStr(args[0])) } return object.NilV }) @@ -131,8 +129,9 @@ func defIOReadExtra(cls *RClass) { cls.define("lineno", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return object.IntValue(int64(self.(*IOObj).lineno)) }) - cls.define("lineno=", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - self.(*IOObj).lineno = int(intArg(args[0])) + cls.define("lineno=", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + // rb_io_set_lineno: NUM2INT coerces via #to_int (a Float truncates). + self.(*IOObj).lineno = int(vm.toIntCoerce(args[0])) return args[0] }) cls.define("close_read", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { @@ -215,10 +214,14 @@ func defIOSeekable(cls *RClass) { o.writable = true // a written File flushes its buffer back on flush/close return object.IntValue(int64(len(data))) }) - cls.define("sysseek", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + cls.define("sysseek", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { o := self.(*IOObj) - amount := int(intArg(args[0])) - switch whenceArg(args) { + amount := int(vm.toIntCoerce(args[0])) // NUM2OFFT: coerces via #to_int + whence := 0 + if len(args) > 1 { + whence = vm.seekWhence(args[1]) // accepts :SET/:CUR/:END symbols + } + switch whence { case 1: // SEEK_CUR o.pos += amount case 2: // SEEK_END @@ -247,14 +250,6 @@ func defIOSeekable(cls *RClass) { }) } -// whenceArg returns the SEEK_* whence of a seek-style argument list (default 0). -func whenceArg(args []object.Value) int { - if len(args) > 1 { - return int(intArg(args[1])) - } - return 0 -} - // ioUnget inserts p immediately before the cursor (leaving the cursor on the // re-inserted bytes) so a following read returns them first — the pushback model // shared by ungetbyte and ungetc. From 91911cd126b038998e9eadac20c4b494439a3dcb Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 20:42:32 +0200 Subject: [PATCH 2/6] io: gate seek-symbol whence and ungetc(nil) to real IO/File, not StringIO StringIO diverges from IO on the two branches wave18 just widened, so gate them on ioIsStringIO to keep StringIO byte-for-byte with MRI: - StringIO#seek (strio_seek) rejects a Symbol whence with the Integer TypeError; only IO#seek honours :SET/:CUR/:END. - StringIO#ungetc(nil) (strio_ungetc) is a no-op, whereas IO#ungetc(nil) raises via StringValue; the #to_str coercion and plain-Object TypeError are shared. Verified against MRI 4.0.5: StringIO#seek(1,:CUR) -> TypeError, StringIO#ungetc(nil) -> nil. stringio corpus unchanged (579 pass); core/io still 948. Co-Authored-By: Claude Opus 4.8 --- internal/vm/io.go | 8 +++++++- internal/vm/io_descriptors.go | 16 +++++++++++----- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/internal/vm/io.go b/internal/vm/io.go index e114c537..526bc4c5 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -773,7 +773,13 @@ func defStringIORead(cls *RClass) { amount := int(vm.toIntCoerce(args[0])) whence := 0 if len(args) > 1 { - whence = vm.seekWhence(args[1]) + // IO#seek accepts the :SET/:CUR/:END whence symbols; StringIO#seek + // (strio_seek) does not — a Symbol there raises the Integer TypeError. + if ioIsStringIO(o) { + whence = int(vm.toIntCoerce(args[1])) + } else { + whence = vm.seekWhence(args[1]) + } } var newPos int switch whence { diff --git a/internal/vm/io_descriptors.go b/internal/vm/io_descriptors.go index 69cb558e..a1e56cd6 100644 --- a/internal/vm/io_descriptors.go +++ b/internal/vm/io_descriptors.go @@ -69,11 +69,17 @@ func defIOReadExtra(cls *RClass) { ioCheckReadable(o) // rb_io_ungetc: an Integer is the codepoint (encoded to bytes); anything else // is coerced with StringValue (#to_str), so nil / a non-String object raises - // "no implicit conversion of into String". - if a, ok := args[0].(object.Integer); ok { - ioUnget(o, []byte(string(rune(a)))) - } else { - ioUnget(o, vm.strToStr(args[0])) + // "no implicit conversion of into String". StringIO#ungetc (strio_ungetc) + // diverges only for nil, which it treats as a no-op. + switch { + case object.IsNil(args[0]) && ioIsStringIO(o): + // StringIO#ungetc(nil): no-op. + default: + if a, ok := args[0].(object.Integer); ok { + ioUnget(o, []byte(string(rune(a)))) + } else { + ioUnget(o, vm.strToStr(args[0])) + } } return object.NilV }) From 26e5a393528bffab87df7729e404d383b7f9210a Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 20:46:27 +0200 Subject: [PATCH 3/6] io: raise IOError on closed stream for eof?/flush/fsync/sync/tty?; STDERR sync default (+9 core/io) MRI raises IOError on a closed (or, for eof?, non-readable) stream; add the guards, keeping StringIO's tolerant behaviour where it diverges: - IO#eof? runs ioCheckReadable, so a closed stream, a #close_read'd stream, or a write-only ("w") File all raise IOError as in MRI (rb_io_eof). eof 12->15. - IO#flush / IO#fsync / IO#tty? raise IOError "closed stream" on a real IO/File via the new ioClosedRealIO; StringIO#flush/#fsync/#tty? stay no-raise. flush 0->1, fsync 1->2, tty 1->2. - IO#sync / IO#sync= raise IOError on a closed real IO (StringIO overrides both in defStringIOExtra, so the guard only reaches a real IO). sync 5->8. - STDERR is synchronous by default (STDERR.sync == true), unlike STDOUT. Verified against MRI 4.0.5 (File raises, StringIO does not for flush/fsync/sync/tty?; both raise for eof?). stringio corpus unchanged (579); core/io pass 948->957. ruby/spec: core/io/{eof,flush,fsync,sync,tty}_spec.rb Co-Authored-By: Claude Opus 4.8 --- internal/vm/io.go | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/internal/vm/io.go b/internal/vm/io.go index 526bc4c5..c8c8620a 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -201,7 +201,8 @@ func (vm *VM) registerIO() { defStringIOExtra(vm, cStringIO) stdout := &IOObj{cls: cIO, w: vm.out, label: "STDOUT"} - stderr := &IOObj{cls: cIO, w: vm.errOut, label: "STDERR"} + // STDERR is synchronous by default (MRI: STDERR.sync == true), unlike STDOUT. + stderr := &IOObj{cls: cIO, w: vm.errOut, label: "STDERR", sync: true} stdin := &IOObj{cls: cIO, isStr: true, label: "STDIN"} // empty input by default vm.consts["STDOUT"], vm.consts["STDERR"], vm.consts["STDIN"] = stdout, stderr, stdin vm.globals["$stdout"], vm.globals["$stderr"], vm.globals["$stdin"] = stdout, stderr, stdin @@ -623,15 +624,27 @@ func defIOWrite(cls *RClass) { return args[0] }) cls.define("flush", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - ioFlush(self.(*IOObj)) + o := self.(*IOObj) + ioClosedRealIO(o) // MRI: IO#flush raises on a closed stream; StringIO#flush does not + ioFlush(o) return self }) - cls.define("fsync", func(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { return object.IntValue(0) }) + cls.define("fsync", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + ioClosedRealIO(self.(*IOObj)) // as flush: real IO raises on close, StringIO does not + return object.IntValue(0) + }) + // These sync/sync= entries serve a real IO; StringIO overrides both in + // defStringIOExtra (its #sync is always true), so the closed-stream guard here + // only ever fires for a real IO/File, which MRI makes raise IOError. cls.define("sync", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return object.Bool(self.(*IOObj).sync) + o := self.(*IOObj) + ioClosedRealIO(o) + return object.Bool(o.sync) }) cls.define("sync=", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - self.(*IOObj).sync = args[0].Truthy() + o := self.(*IOObj) + ioClosedRealIO(o) + o.sync = args[0].Truthy() return args[0] }) cls.define("close", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { @@ -646,7 +659,10 @@ func defIOWrite(cls *RClass) { cls.define("closed?", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return object.Bool(self.(*IOObj).closed) }) - cls.define("tty?", func(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { return object.Bool(false) }) + cls.define("tty?", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + ioClosedRealIO(self.(*IOObj)) // real IO raises on a closed stream; StringIO does not + return object.Bool(false) + }) // #isatty is a true alias of #tty?, as in MRI. cls.methods["isatty"] = cls.methods["tty?"] // IO#binmode marks the stream binary (#binmode? true) and, as MRI's @@ -738,6 +754,7 @@ func defStringIORead(cls *RClass) { cls.methods["size"] = cls.methods["length"] cls.define("eof?", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { o := self.(*IOObj) + ioCheckReadable(o) // MRI: eof? raises on a closed or non-readable stream o.pipeRefresh() return object.Bool(o.pos >= len(o.buf)) }) @@ -1618,6 +1635,15 @@ func ioCheckReadable(o *IOObj) { } } +// ioClosedRealIO raises IOError "closed stream" when a real IO/File is closed. It +// is a no-op for a StringIO, whose #flush/#fsync/#tty?/#sync tolerate a closed +// stream where a real IO raises (MRI). +func ioClosedRealIO(o *IOObj) { + if o.closed && !ioIsStringIO(o) { + raise("IOError", "closed stream") + } +} + // toInt coerces a small Integer position/length argument to int64 (raising for // anything else, including a Bignum — a stream offset that large is nonsensical). func toInt(v object.Value) int64 { From 7249b377b0efb1a58d282c8f2b645ae48e6cb585 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 20:49:37 +0200 Subject: [PATCH 4/6] io: putc via #write, printf/putc argument coercion, sync=true flushes to disk (+9 core/io) - IO#putc (rb_io_putc, io.c): write the single character through self.#write so a subclass' / mock's #write observes it; a String yields its first character and a non-String is coerced with NUM2CHR (#to_int, low byte) so nil/false/true raise TypeError. Returns the original argument. putc 4->9. - IO#printf (rb_io_printf): coerce the format with #to_str (StringValue) instead of Go-level to_s, so a #to_str format object formats correctly. printf 1->3. - writeBytes: when o.sync is set, a File's buffered write is flushed to disk immediately, so File.read observes it before #close (MRI sync semantics). write 29->30; also carries printf's file-visible output. core/io pass 957->966; stringio 579->580 (no regression). ruby/spec: core/io/{putc,printf,write}_spec.rb, shared/io/putc.rb Co-Authored-By: Claude Opus 4.8 --- internal/vm/io.go | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/internal/vm/io.go b/internal/vm/io.go index c8c8620a..2e2232a6 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -100,6 +100,9 @@ func (o *IOObj) writeBytes(p []byte) int { copy(o.buf[o.pos:], p) o.pos += len(p) o.syncStr() + if o.sync { // sync=true: a File's writes reach disk immediately (no buffering) + ioFlush(o) + } return len(p) } n, _ := o.w.Write(p) @@ -605,22 +608,27 @@ func defIOWrite(cls *RClass) { if len(args) == 0 { raise("ArgumentError", "wrong number of arguments (given 0, expected 1+)") } - o.writeStr(vm.formatString(args[0].ToS(), args[1:])) + // rb_io_printf: the format is coerced with StringValue (#to_str). + o.writeStr(vm.formatString(string(vm.strToStr(args[0])), args[1:])) return object.NilV }) - cls.define("putc", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + cls.define("putc", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { o := self.(*IOObj) ioCheckOpen(o) - switch a := args[0].(type) { - case object.Integer: - o.writeBytes([]byte{byte(a)}) - case *object.String: - if len(a.Bytes()) > 0 { - o.writeBytes(a.Bytes()[:1]) + // rb_io_putc: a String yields its first character; anything else is coerced + // with NUM2CHR (#to_int, then the low byte), so nil/false/true raise + // TypeError. The single-character String is written through #write (so a + // subclass' or mock's #write observes it), and the original argument returns. + var ch []byte + if s, ok := args[0].(*object.String); ok { + if b := s.Bytes(); len(b) > 0 { + _, sz := utf8.DecodeRune(b) + ch = b[:sz] } - default: - raise("TypeError", "no implicit conversion of %s into Integer", classNameOf(args[0])) + } else { + ch = []byte{byte(vm.toIntCoerce(args[0]))} } + vm.send(self, "write", []object.Value{object.NewStringBytes(ch)}, nil) return args[0] }) cls.define("flush", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { From ef2d829c6ce79cfaf02fcefdef6e23c6934d32db Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 20:54:46 +0200 Subject: [PATCH 5/6] io: closed-stream guards for rewind/autoclose, binread negative-offset EINVAL, gets-family arity (+5 core/io) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - IO#rewind raises IOError on a closed real IO/File (StringIO tolerates it). - IO#autoclose? / IO#autoclose= raise IOError on a closed IO (IO/File-only methods, so no StringIO gating needed). - IO.binread reaches a negative offset through rb_io_seek and raises Errno::EINVAL "Invalid argument @ rb_io_seek - ", whereas IO.read validates it in Ruby (ArgumentError) — verified against MRI 4.0.5. - gets/readline/each_line (resolveGetsArgs) reject more than two positional arguments with ArgumentError "wrong number of arguments (given N, expected 0..2)" (chomp: is a stripped keyword). core/io pass 966->971; stringio 580 (no regression). ruby/spec: core/io/{rewind,autoclose,binread,each_line}_spec.rb Co-Authored-By: Claude Opus 4.8 --- internal/vm/io.go | 6 ++++++ internal/vm/io_class.go | 5 +++++ internal/vm/io_descriptors.go | 12 ++++++++++-- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/internal/vm/io.go b/internal/vm/io.go index 2e2232a6..79df49cd 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -825,6 +825,7 @@ func defStringIORead(cls *RClass) { }) cls.define("rewind", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { o := self.(*IOObj) + ioClosedRealIO(o) // real IO/File raises on a closed stream; StringIO tolerates it o.pos, o.lineno = 0, 0 // #rewind resets both the position and the line number return object.IntValue(0) }) @@ -1362,6 +1363,11 @@ func (vm *VM) resolveGetsArgs(args []object.Value) (sep getsSep, limit int, chom } args = args[:len(args)-1] } + // gets/readline/each_line take at most a separator and a limit (chomp: is a + // keyword, stripped above); more positional arguments raise ArgumentError. + if len(args) > 2 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 0..2)", len(args)) + } if len(args) > 0 { switch a := args[0].(type) { case object.Integer: diff --git a/internal/vm/io_class.go b/internal/vm/io_class.go index 5aa1c164..cbc3da09 100644 --- a/internal/vm/io_class.go +++ b/internal/vm/io_class.go @@ -225,6 +225,11 @@ func (vm *VM) ioReadFile(args []object.Value, forceBinary bool) object.Value { var offset int64 if len(pos) > 2 && pos[2] != object.NilV { if offset = intArg(pos[2]); offset < 0 { + // IO.binread reaches a negative offset through rb_io_seek (Errno::EINVAL); + // IO.read validates it in Ruby and raises ArgumentError. + if forceBinary { + raise("Errno::EINVAL", "Invalid argument @ rb_io_seek - %s", name) + } raise("ArgumentError", "negative offset %d given", offset) } } diff --git a/internal/vm/io_descriptors.go b/internal/vm/io_descriptors.go index a1e56cd6..d23d9ae3 100644 --- a/internal/vm/io_descriptors.go +++ b/internal/vm/io_descriptors.go @@ -245,10 +245,18 @@ func defIOSeekable(cls *RClass) { return object.Bool(o.binmode) }) cls.define("autoclose?", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return object.Bool(!self.(*IOObj).noAutoclose) + o := self.(*IOObj) + if o.closed { // MRI: #autoclose? cannot be queried on a closed IO + raise("IOError", "closed stream") + } + return object.Bool(!o.noAutoclose) }) cls.define("autoclose=", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { - self.(*IOObj).noAutoclose = !args[0].Truthy() + o := self.(*IOObj) + if o.closed { // MRI: #autoclose= cannot be set on a closed IO + raise("IOError", "closed stream") + } + o.noAutoclose = !args[0].Truthy() return args[0] }) cls.define("fdatasync", func(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { From 60f0dad7c6a7e4ced39e2bc106ec29e15a035bbd Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 7 Sep 2026 19:04:27 +0200 Subject: [PATCH 6/6] io: whitebox tests for the wave-18 read/write/seek helpers (100% coverage) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wave-18 io work added seekWhence, ioIsStringIO, ioClosedRealIO and new branches in writeBytes/resolveGetsArgs/ioReadFile/defIOSeekable without tests, dropping the merged-coverage total below the 100% gate. Cover every new branch: seekWhence (all whences + int + TypeError), the StringIO-vs-real-IO closed-stream guards, and the File sync-write / closed pos·pos=·autoclose / symbolic seek / gets-EOF / over-arity gets / binread negative-offset paths — each asserted byte-for-byte vs MRI 4.0.5. defStringIORead's remaining 99.5% is pre-existing (identical on main). Co-Authored-By: Claude Opus 4.8 --- .../vm/io_wave18_helpers_internal_test.go | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 internal/vm/io_wave18_helpers_internal_test.go diff --git a/internal/vm/io_wave18_helpers_internal_test.go b/internal/vm/io_wave18_helpers_internal_test.go new file mode 100644 index 00000000..06d8336a --- /dev/null +++ b/internal/vm/io_wave18_helpers_internal_test.go @@ -0,0 +1,132 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "io" + "testing" + + "github.com/go-embedded-ruby/ruby/internal/object" +) + +// assertIORaise runs fn and asserts it panics with a RubyError of the given class. +func assertIORaise(t *testing.T, wantClass string, fn func()) { + t.Helper() + defer func() { + r := recover() + if r == nil { + t.Errorf("expected %s, got no panic", wantClass) + return + } + re, ok := r.(RubyError) + if !ok { + panic(r) // not a Ruby raise — re-panic + } + if re.Class != wantClass { + t.Errorf("raised %s, want %s", re.Class, wantClass) + } + }() + fn() +} + +// TestSeekWhenceMapping covers seekWhence: each symbolic whence (:SET/:CUR/:END/ +// :DATA/:HOLE) maps to its io.c constant, an Integer whence is coerced through, +// and any other symbol raises TypeError (MRI: "no implicit conversion of Symbol +// into Integer"). Verified byte-for-byte vs MRI 4.0.5. +func TestSeekWhenceMapping(t *testing.T) { + vm := New(io.Discard) + for _, c := range []struct { + sym string + want int + }{{"SET", 0}, {"CUR", 1}, {"END", 2}, {"DATA", 3}, {"HOLE", 4}} { + if got := vm.seekWhence(object.Symbol(c.sym)); got != c.want { + t.Errorf("seekWhence(:%s) = %d, want %d", c.sym, got, c.want) + } + } + if got := vm.seekWhence(object.IntValue(7)); got != 7 { + t.Errorf("seekWhence(7) = %d, want 7", got) + } + assertIORaise(t, "TypeError", func() { vm.seekWhence(object.Symbol("NOPE")) }) +} + +// TestIOStringIOClosedGuards covers ioIsStringIO and ioClosedRealIO: a StringIO +// tolerates operations on a closed stream (MRI keeps its buffer), while a real +// IO/File raises IOError "closed stream"; an open real IO does not. +func TestIOStringIOClosedGuards(t *testing.T) { + vm := New(io.Discard) + sio := vm.consts["StringIO"].(*RClass) + rio := vm.consts["IO"].(*RClass) + + if !ioIsStringIO(&IOObj{cls: sio}) { + t.Error("ioIsStringIO(StringIO) = false, want true") + } + if ioIsStringIO(&IOObj{cls: rio}) { + t.Error("ioIsStringIO(IO) = true, want false") + } + + assertIORaise(t, "IOError", func() { ioClosedRealIO(&IOObj{cls: rio, closed: true}) }) + ioClosedRealIO(&IOObj{cls: sio, closed: true}) // StringIO closed: tolerated (no panic) + ioClosedRealIO(&IOObj{cls: rio, closed: false}) // real IO open: no panic +} + +// TestIOWave18RubyPaths exercises the dispatch-driven read/write/seek helpers +// (writeBytes append+sync, resolveGetsArgs separator/limit/chomp forms, the seek +// whence forms) through Ruby, asserting each result against MRI 4.0.5. +func TestIOWave18RubyPaths(t *testing.T) { + cases := []struct{ src, want string }{ + // gets separator / limit / chomp / nil-separator (slurp) forms → resolveGetsArgs + {`require "stringio"; io = StringIO.new("ab\ncd\nef"); p [io.gets, io.gets("c"), io.gets(2), io.gets(chomp: true)]`, + "[\"ab\\n\", \"c\", \"d\\n\", \"ef\"]\n"}, + {`require "stringio"; p StringIO.new("a\nb\nc").gets(nil)`, "\"a\\nb\\nc\"\n"}, + // seek: default whence and an integer whence (StringIO rejects a symbolic + // whence with TypeError — that path is covered directly in + // TestSeekWhenceMapping via a real IO's whence table). + {`require "stringio"; io = StringIO.new("0123456789"); io.seek(3); a = io.pos; io.seek(2, IO::SEEK_CUR); p [a, io.pos]`, + "[3, 5]\n"}, + // StringIO append write then read back → writeBytes isStr/append branch + {`require "stringio"; io = StringIO.new("", "a"); io.write("xy"); io.write("z"); p io.string`, "\"xyz\"\n"}, + } + for _, c := range cases { + if got := runFS(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + +// TestIOWave18ClosedAndSeekPaths covers the real-File edge branches the helpers +// added: sync=true flush on write, IOError on a closed File's pos/pos=/autoclose?/ +// autoclose=, a symbolic seek whence on a real File, gets at EOF, an over-arity +// gets, and IO.binread's negative-offset Errno::EINVAL. Each result matches MRI 4.0.5. +func TestIOWave18ClosedAndSeekPaths(t *testing.T) { + p := slash(t.TempDir()) + "/f.txt" + q := func(s string) string { return "%q(" + s + ")" } + seed := "File.write(" + q(p) + ", \"hello world\"); " + cases := []struct{ src, want string }{ + // writeBytes sync=true branch: a File with #sync = true flushes each write. + {seed + "f = File.open(" + q(p) + ", \"w\"); f.sync = true; f.write(\"xy\"); f.close; p File.read(" + q(p) + ")", "\"xy\"\n"}, + // closed real File raises IOError on pos / pos= / autoclose? / autoclose= + // (the setter forms need begin/rescue: a `rescue` modifier on an assignment + // guards the right-hand side, not the assignment). + {seed + "f = File.open(" + q(p) + "); f.close; " + + "a = (f.pos rescue $!.class); " + + "b = (begin; f.pos = 0; rescue => e; e.class; end); " + + "c = (f.autoclose? rescue $!.class); " + + "d = (begin; f.autoclose = true; rescue => e; e.class; end); p [a, b, c, d]", + "[IOError, IOError, IOError, IOError]\n"}, + // symbolic seek whence on a real File goes through seekWhence. + {seed + "f = File.open(" + q(p) + "); f.seek(2, :SET); r = f.pos; f.close; p r", "2\n"}, + // gets at EOF returns nil (setLineGlobals' nil branch). + {`require "stringio"; p StringIO.new("").gets`, "nil\n"}, + // gets with more than a separator and a limit raises ArgumentError. + {`require "stringio"; p(StringIO.new("a").gets("x", 5, 9) rescue $!.class)`, "ArgumentError\n"}, + // IO.binread with a negative offset raises Errno::EINVAL (not ArgumentError). + {seed + "p(IO.binread(" + q(p) + ", 1, -1) rescue $!.class)", "Errno::EINVAL\n"}, + } + for _, c := range cases { + if got := runFS(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +}