diff --git a/internal/vm/io.go b/internal/vm/io.go index 77ff3a5f..63edaee9 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -138,6 +138,7 @@ 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 { @@ -145,15 +146,19 @@ func (vm *VM) registerIO() { } 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)) } diff --git a/internal/vm/io_class.go b/internal/vm/io_class.go index 5107830a..be3c9606 100644 --- a/internal/vm/io_class.go +++ b/internal/vm/io_class.go @@ -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) }) @@ -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 { diff --git a/internal/vm/io_class_internal_test.go b/internal/vm/io_class_internal_test.go index 25175cd1..1df23be0 100644 --- a/internal/vm/io_class_internal_test.go +++ b/internal/vm/io_class_internal_test.go @@ -5,6 +5,7 @@ package vm import ( + "fmt" "os" "path/filepath" "testing" @@ -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) + } + } +} diff --git a/internal/vm/vm.go b/internal/vm/vm.go index a7573e3e..414e9094 100644 --- a/internal/vm/vm.go +++ b/internal/vm/vm.go @@ -388,6 +388,7 @@ type VM struct { cIOBuffer *RClass cARGF *RClass nextFd int + fdTable map[int]*IOObj cYielder *RClass cWeakMap *RClass cWeakKeyMap *RClass diff --git a/scripts/conformance/rubyspec/FLOOR b/scripts/conformance/rubyspec/FLOOR index f827ae6d..a7b654a4 100644 --- a/scripts/conformance/rubyspec/FLOOR +++ b/scripts/conformance/rubyspec/FLOOR @@ -1 +1 @@ -16180 +16240