diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 50839342..3c1080bc 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -2268,6 +2268,7 @@ func (vm *VM) bootstrap() { {vm.cHash, "to_hash"}, {vm.cString, "to_str"}, {vm.cInteger, "to_int"}, + {vm.cRegexp, "to_regexp"}, } { cls, meth := tc.cls, tc.meth cls.smethods["try_convert"] = &Method{name: "try_convert", owner: cls, diff --git a/internal/vm/io.go b/internal/vm/io.go index b57a388b..d964a6fb 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -120,6 +120,11 @@ func (vm *VM) registerIO() { if fc, ok := vm.consts["File"].(*RClass).consts["Constants"].(*RClass); ok { cIO.includes = append(cIO.includes, fc) } + // IO.try_convert(obj): obj if it is an IO, else its #to_io conversion, else nil. + cIO.smethods["try_convert"] = &Method{name: "try_convert", owner: cIO, + native: func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + return vm.tryConvert(args[0], cIO, "to_io") + }} defIOWrite(cIO) defStringIORead(cIO) // IO carries the read protocol too ($stdin, File streams) defIOReadExtra(cIO) diff --git a/internal/vm/try_convert_internal_test.go b/internal/vm/try_convert_internal_test.go index 22161e4a..d7043d20 100644 --- a/internal/vm/try_convert_internal_test.go +++ b/internal/vm/try_convert_internal_test.go @@ -40,6 +40,15 @@ begin; Array.try_convert(Bad.new); rescue TypeError => e; p e.message; end`, {`class BadI; def to_int; "s"; end; end begin; Integer.try_convert(BadI.new); rescue TypeError => e; p e.message; end`, `"can't convert BadI into Integer (BadI#to_int gives String)"`}, + // Regexp.try_convert (via #to_regexp) and IO.try_convert (via #to_io). + {`p Regexp.try_convert(/x/)`, `/x/`}, + {`p Regexp.try_convert("x")`, `nil`}, + {`class RC; def to_regexp; /custom/; end; end; p Regexp.try_convert(RC.new)`, `/custom/`}, + {`p IO.try_convert($stdout).equal?($stdout)`, `true`}, + {`p IO.try_convert("x")`, `nil`}, + {`class Bad2; def to_regexp; 42; end; end +begin; Regexp.try_convert(Bad2.new); rescue TypeError => e; p e.message; end`, + `"can't convert Bad2 into Regexp (Bad2#to_regexp gives Integer)"`}, } for _, c := range cases { if got := eval(t, c.src); got != c.want+"\n" { diff --git a/scripts/conformance/rubyspec/FLOOR b/scripts/conformance/rubyspec/FLOOR index da34743d..1575884a 100644 --- a/scripts/conformance/rubyspec/FLOOR +++ b/scripts/conformance/rubyspec/FLOOR @@ -1 +1 @@ -15870 +15880