Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions internal/vm/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,22 +138,27 @@ func (vm *VM) registerIO() {
// real file descriptors, so this is an identity, not an OS fd. StringIO has no
// #fileno, so it is defined only here on IO. A closed stream raises IOError.
vm.nextFd = 2 // synthetic descriptors for non-standard streams start at 3
vm.fdTable = map[int]*IOObj{}
fileno := func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
o := self.(*IOObj)
if o.closed {
raise("IOError", "closed stream")
}
switch o.label {
case "STDIN":
vm.fdTable[0] = o
return object.IntValue(0)
case "STDOUT":
vm.fdTable[1] = o
return object.IntValue(1)
case "STDERR":
vm.fdTable[2] = o
return object.IntValue(2)
}
if o.fd == 0 {
vm.nextFd++
o.fd = vm.nextFd
vm.fdTable[o.fd] = o
}
return object.IntValue(int64(o.fd))
}
Expand Down
64 changes: 64 additions & 0 deletions internal/vm/io_class.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,34 @@ func (vm *VM) registerIOClassMethods(cIO, cFile *RClass) {
cIO.smethods[name] = m
cFile.smethods[name] = m
}
// IO.new(fd, mode = "r", **opts) / IO.for_fd wrap an existing descriptor. rbgo
// has no real fds, so the descriptor is looked up in the synthetic fd table
// (populated by #fileno); an unknown one raises Errno::EBADF. The result is a
// fresh IO carrying the mode's read/write intent and encoding.
forFd := func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
pos, opts := splitIOOpts(args)
if len(pos) < 1 || len(pos) > 2 {
raise("ArgumentError", "wrong number of arguments (given %d, expected 1..2)", len(pos))
}
fd := int(vm.repeatLong(pos[0]))
if _, ok := vm.fdTable[fd]; !ok {
raise("Errno::EBADF", "Bad file descriptor - fd %d", fd)
}
mode := ""
if len(pos) >= 2 && !object.IsNil(pos[1]) {
mode = strArg(pos[1])
}
if opts != nil {
if m, ok := opts.Get(object.Symbol("mode")); ok && !object.IsNil(m) {
mode = strArg(m)
}
}
res := &IOObj{cls: cIO, isStr: true, writable: strings.ContainsAny(mode, "wa+")}
vm.applyIOMode(res, mode, opts)
return res
}
cIO.smethods["for_fd"] = &Method{name: "for_fd", owner: cIO, native: forFd}
cIO.smethods["new"] = &Method{name: "new", owner: cIO, native: forFd}
def("read", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
return vm.ioReadFile(args, false)
})
Expand Down Expand Up @@ -364,6 +392,42 @@ func encOpt(opts *object.Hash) (object.Value, bool) {
return nil, false
}

// applyIOMode sets the external/internal encoding of a stream from a mode string
// ("w:ext[:int]") and/or the :external_encoding / :internal_encoding / :encoding
// options, canonicalising each name.
func (vm *VM) applyIOMode(o *IOObj, mode string, opts *object.Hash) {
if i := strings.IndexByte(mode, ':'); i >= 0 {
enc := mode[i+1:]
if j := strings.IndexByte(enc, ':'); j >= 0 {
o.extEnc = vm.lookupEncodingName(enc[:j]).name
o.intEnc = vm.lookupEncodingName(enc[j+1:]).name
} else if enc != "" {
o.extEnc = vm.lookupEncodingName(enc).name
}
}
if opts == nil {
return
}
if v, ok := opts.Get(object.Symbol("external_encoding")); ok && !object.IsNil(v) {
o.extEnc = vm.encodingArg(v).name
}
if v, ok := opts.Get(object.Symbol("internal_encoding")); ok && !object.IsNil(v) {
o.intEnc = vm.encodingArg(v).name
}
if v, ok := opts.Get(object.Symbol("encoding")); ok && !object.IsNil(v) {
// A String :encoding may be a combined "external:internal"; an Encoding is a
// single external encoding.
if s, isStr := v.(*object.String); isStr {
if j := strings.IndexByte(s.Str(), ':'); j >= 0 {
o.extEnc = vm.lookupEncodingName(s.Str()[:j]).name
o.intEnc = vm.lookupEncodingName(s.Str()[j+1:]).name
return
}
}
o.extEnc = vm.encodingArg(v).name
}
}

// ioOptEncoding returns the canonical encoding name selected by the :encoding /
// :external_encoding option, or "" when none is given.
func (vm *VM) ioOptEncoding(opts *object.Hash) string {
Expand Down
33 changes: 33 additions & 0 deletions internal/vm/io_class_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package vm

import (
"fmt"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -228,3 +229,35 @@ func TestIOCopyStream(t *testing.T) {
}
}
}

// TestIOForFd covers IO.new / IO.for_fd wrapping a synthetic descriptor: an IO
// instance is created for a live fd, #to_int coerces the argument, the mode's
// read/write intent and encoding (from the mode string or options) are applied,
// an unknown fd raises Errno::EBADF, and the arity is 1..2. Files are created
// under Dir.mktmpdir for portability. Asserted against MRI Ruby 4.0.6.
func TestIOForFd(t *testing.T) {
fd := `require "tmpdir"
Dir.mktmpdir do |d|
fd = File.open(File.join(d, "f"), "w").fileno
` + "%s\nend"
wrap := func(body string) string { return fmt.Sprintf(fd, body) }
cases := []struct{ src, want string }{
{wrap(`p IO.new(fd, "w").instance_of?(IO)`), "true\n"},
{wrap(`p IO.for_fd(fd, "w").instance_of?(IO)`), "true\n"},
{wrap(`p IO.for_fd(fd, "w").write("foo")`), "3\n"},
{wrap(`io = IO.new(fd, "w:utf-8:ISO-8859-1"); p [io.external_encoding.to_s, io.internal_encoding.to_s]`), "[\"UTF-8\", \"ISO-8859-1\"]\n"},
{wrap(`io = IO.new(fd, "w", external_encoding: "utf-8", internal_encoding: "ibm866"); p [io.external_encoding.to_s, io.internal_encoding.to_s]`), "[\"UTF-8\", \"IBM866\"]\n"},
{wrap(`io = IO.new(fd, mode: "w:utf-8"); p io.external_encoding.to_s`), "\"UTF-8\"\n"},
{wrap(`io = IO.new(fd, "w", encoding: "utf-8"); p io.external_encoding.to_s`), "\"UTF-8\"\n"},
{wrap(`io = IO.new(fd, "w", encoding: "utf-8:ibm866"); p [io.external_encoding.to_s, io.internal_encoding.to_s]`), "[\"UTF-8\", \"IBM866\"]\n"},
{wrap(`obj = Object.new; d2 = fd; obj.define_singleton_method(:to_int) { d2 }; p IO.new(obj, "w").instance_of?(IO)`), "true\n"},
{wrap(`begin; IO.new(-999, "r"); rescue Errno::EBADF => e; p e.class; end`), "Errno::EBADF\n"},
{wrap(`begin; IO.new; rescue ArgumentError => e; p e.class; end`), "ArgumentError\n"},
{wrap(`begin; IO.new(fd, "r", "x"); rescue ArgumentError => e; p e.class; end`), "ArgumentError\n"},
}
for _, c := range cases {
if got := eval(t, c.src); got != c.want {
t.Errorf("src=%q got=%q want=%q", c.src, got, c.want)
}
}
}
1 change: 1 addition & 0 deletions internal/vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ type VM struct {
cIOBuffer *RClass
cARGF *RClass
nextFd int
fdTable map[int]*IOObj
cYielder *RClass
cWeakMap *RClass
cWeakKeyMap *RClass
Expand Down
2 changes: 1 addition & 1 deletion scripts/conformance/rubyspec/FLOOR
Original file line number Diff line number Diff line change
@@ -1 +1 @@
16180
16240