From bcf0edd73e63fef5acb4465bf5d31f709ee0d8fd Mon Sep 17 00:00:00 2001 From: tannevaled Date: Wed, 9 Sep 2026 16:21:36 +0200 Subject: [PATCH 1/2] kernel: Kernel#putc + #p/#print/#puts forward to $stdout (core/kernel +15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kernel#p/#print/#puts/#putc did not honour a reassigned or mocked $stdout, #p lost the array return value and rendered container elements through the built-in formatter instead of dispatching #inspect, and Kernel#putc was missing entirely. - Add Kernel#putc: coerces its argument like rb_io_putc (a String's first character, else the low byte of #to_int; nil/false/true raise TypeError) and delivers the one-character String through $stdout#write, so a mocked $stdout or a closed stream (IOError) is observed. Registered in the module_function set so it is a private instance method of Kernel and a public Kernel module method. - Kernel#puts forwards to $stdout.puts (rb_f_puts) so a reassigned/mocked $stdout receives the call, with the recv==$stdout guard writing straight to the object to avoid recursing. - Kernel#print writes through $stdout#write (rb_f_print -> rb_io_print), applying $_ (no-arg), the field separator $, and the record separator $\. - Kernel#p returns the argument for one, a new Array for several, and renders each value through its own #inspect (rb_inspect), coercing a non-String result with #to_s (rb_obj_as_string) — so an overridden #inspect and per-element Array/Hash #inspect are honoured. - A $stdout that answers no #write (which MRI rejects at assignment but rbgo tolerates) falls back to the underlying stream rather than raising. References: ruby/ruby v3_4_0 io.c (rb_f_putc, rb_f_puts, rb_f_print, rb_io_print, rb_io_putc), object.c (rb_inspect, rb_obj_as_string). Verified byte-for-byte against MRI 4.0.5. Updated one stale pinned test (p of a non-String #inspect now coerces via #to_s, as MRI does). core/kernel: putc 0->11, p 6->8, print 3->4, puts 2->3; ruby/spec core/kernel passing 1829 -> 1844. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 105 +++++++++++- .../kernel_io_output_wave22_internal_test.go | 149 ++++++++++++++++++ internal/vm/stdlib_puppet_test.go | 6 +- 3 files changed, 250 insertions(+), 10 deletions(-) create mode 100644 internal/vm/kernel_io_output_wave22_internal_test.go diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index dd67c53e..9743179d 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -930,6 +930,36 @@ func (vm *VM) bootstrap() { vm.cObject.define("puts", nativePuts) vm.cObject.define("print", nativePrint) vm.cObject.define("p", nativeP) + // Kernel#putc forwards its single character to $stdout.putc (MRI's rb_f_putc), + // so a reassigned or mocked $stdout observes the write and IO#putc's coercion + // (#to_int for a non-String, TypeError for nil/false/true) and closed-stream + // IOError apply. Reference: ruby/ruby v3_4_0 io.c (rb_f_putc). + vm.cObject.define("putc", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) != 1 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1)", len(args)) + } + // 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 one-character String is delivered through $stdout#write, so a + // reassigned or mocked $stdout observes it (and IO#write raises IOError on a + // closed stream); a $stdout that answers no #write — one MRI would have + // rejected at assignment — falls back to the underlying stream. + 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] + } + } else { + ch = []byte{byte(vm.toIntCoerce(args[0]))} + } + out := vm.stdoutValue() + if !vm.respondsToDynamic(out, "write") { + out = vm.curStdout() + } + vm.send(out, "write", []object.Value{object.NewStringBytes(ch)}, nil) + return args[0] + }) vm.cObject.define("class", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return vm.classOf(self) }) @@ -6248,7 +6278,7 @@ func (vm *VM) registerKernelModuleFunctions() { "__dir__", "abort", "at_exit", "autoload", "autoload?", "caller", "caller_locations", "catch", "eval", "exec", "exit", "exit!", "fail", "fork", "format", "lambda", - "load", "loop", "open", "p", "print", "printf", "proc", "puts", + "load", "loop", "open", "p", "print", "printf", "proc", "putc", "puts", "raise", "rand", "require", "require_relative", "sleep", "sprintf", "srand", "system", "throw", "trap", "warn", } @@ -6772,8 +6802,25 @@ func (vm *VM) arrayArefArithSeq(a *object.Array, e *Enumerator) object.Value { // Kernel#puts/print/p write through the current $stdout (an IOObj), so a host // or program that reassigns $stdout — e.g. to a StringIO — captures the output, // as in MRI. The puts array-flattening/newline logic lives in io.go (ioPuts). -func nativePuts(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - vm.ioPuts(vm.curStdout(), args) +// nativePuts implements Kernel#puts. MRI's rb_f_puts forwards to $stdout.puts so +// a reassigned or mocked $stdout observes the call, EXCEPT when the receiver is +// already $stdout itself, where it writes directly to avoid recursing into this +// same method. Reference: ruby/ruby v3_4_0 io.c (rb_f_puts). +func nativePuts(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + out := vm.stdoutValue() + if out != self { + return vm.send(out, "puts", args, nil) + } + // The receiver already IS $stdout (a custom object whose #puts resolves to this + // method): write straight to it, as MRI's rb_io_puts(argc, argv, recv) does, so + // the object's own #write receives the bytes. A $stdout that answers no #write + // (one MRI would have rejected at assignment) falls back to the underlying + // stream instead of raising. + if vm.respondsToDynamic(self, "write") { + vm.ioPuts(self, args) + } else { + vm.ioPuts(vm.curStdout(), args) + } return object.NilV } @@ -6834,26 +6881,68 @@ func (vm *VM) coerceFormatString(v object.Value) string { return "" } +// nativePrint implements Kernel#print. MRI's rb_f_print writes to $stdout through +// rb_io_print (rb_io_write, i.e. $stdout.write) rather than dispatching +// $stdout.print, so it works for any reassigned $stdout answering #write and never +// recurses into this method. With no arguments it writes $_ (the last line read); +// several arguments are joined by the output field separator $, and the whole is +// terminated by the output record separator $\ when those globals are set. +// Reference: ruby/ruby v3_4_0 io.c (rb_f_print -> rb_io_print). func nativePrint(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - o := vm.curStdout() - for _, a := range args { - o.writeStr(vm.displayStr(a)) + out := vm.stdoutValue() + // A $stdout that answers no #write (one MRI would have rejected at assignment) + // falls back to the underlying stream rather than raising. + if !vm.respondsToDynamic(out, "write") { + out = vm.curStdout() + } + write := func(s string) { vm.send(out, "write", []object.Value{object.NewString(s)}, nil) } + if len(args) == 0 { + if lastLine := vm.gvar("$_"); !object.IsNil(lastLine) { + write(vm.displayStr(lastLine)) + } + } else { + ofs, ofsSet := vm.optStrGlobal("$,") + for i, a := range args { + if i > 0 && ofsSet { + write(ofs) + } + write(vm.displayStr(a)) + } + } + if ors, ok := vm.optStrGlobal("$\\"); ok { + write(ors) } return object.NilV } +// pInspect renders a value the way MRI's rb_inspect does for Kernel#p: it +// dispatches the object's own #inspect (so an overridden #inspect, and the +// per-element #inspect used inside Array/Hash/Struct, are honoured) and coerces a +// non-String result with #to_s exactly as rb_obj_as_string does. +func (vm *VM) pInspect(v object.Value) string { + r := vm.send(v, "inspect", nil, nil) + if s, ok := r.(*object.String); ok { + return s.Str() + } + return vm.displayStr(r) +} + func nativeP(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { o := vm.curStdout() for _, a := range args { - o.writeStr(vm.inspectStr(a) + "\n") + o.writeStr(vm.pInspect(a) + "\n") } switch len(args) { case 0: + // With no argument #p writes nothing and returns nil. return object.NilV case 1: return args[0] default: - return object.NilV // Ruby returns the args array; arrays arrive in Phase 2 + // With several arguments #p returns them as a new Array. + elems := make([]object.Value, len(args)) + copy(elems, args) + return object.NewArrayFromSlice(elems) } } diff --git a/internal/vm/kernel_io_output_wave22_internal_test.go b/internal/vm/kernel_io_output_wave22_internal_test.go new file mode 100644 index 00000000..76629e07 --- /dev/null +++ b/internal/vm/kernel_io_output_wave22_internal_test.go @@ -0,0 +1,149 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "strings" + "testing" +) + +// TestKernelPReturnValues covers nativeP's three return-value arms: nil for no +// argument, the argument itself for a single one, and a NEW Array of the +// arguments for several. Reference: ruby/ruby v3_4_0 io.c (rb_f_p). Verified +// byte-for-byte against MRI 4.0.5. +func TestKernelPReturnValues(t *testing.T) { + cases := []struct{ name, src, want string }{ + // No argument: #p writes nothing and returns nil. + {"no_args", `x = p(); p x`, "nil"}, + // One argument: #p returns that same object (identity preserved). + {"one_arg", `s = "s"; r = p(s); p r.equal?(s)`, "\"s\"\ntrue"}, + // Several arguments: #p returns a new Array of them. + {"multi_args", `a = p(1, 2); p a.class; p a`, "1\n2\nArray\n[1, 2]"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := runSrc(t, tc.src); got != tc.want { + t.Fatalf("src=%q got=%q want=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestKernelPInspectDispatch covers pInspect: #p renders each argument through +// the object's own #inspect (so an overridden #inspect, and the per-element +// #inspect used inside Array#inspect, are honoured), and coerces a non-String +// #inspect result with #to_s exactly as MRI's rb_inspect/rb_obj_as_string do. +func TestKernelPInspectDispatch(t *testing.T) { + // A non-String #inspect result is coerced with #to_s (here 42 -> "42"). + if got := runSrc(t, `class X; def inspect; 42; end; end; p X.new`); got != "42" { + t.Fatalf("non-String inspect: got %q want %q", got, "42") + } + // An element's overridden #inspect is used inside Array#inspect. + if got := runSrc(t, `class Y; def inspect; "Y!"; end; end; p [Y.new]`); got != "[Y!]" { + t.Fatalf("array element inspect: got %q want %q", got, "[Y!]") + } +} + +// TestKernelPrint covers nativePrint: it writes through $stdout.write, joins +// several arguments with the output field separator $, terminates with the +// output record separator $\, and with no arguments writes $_ (the last line +// read). Reference: ruby/ruby v3_4_0 io.c (rb_f_print -> rb_io_print). +func TestKernelPrint(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"plain", `print "ab"`, "ab"}, + {"dollar_underscore", `$_ = "foo"; print`, "foo"}, + {"no_arg_no_lastline", `print`, ""}, + {"multi_no_separator", `print "a", "b"`, "ab"}, + {"separators", `$, = "-"; $\ = "!"; print "a", "b"`, "a-b!"}, + // A $stdout that answers no #write falls back to the underlying stream (MRI + // rejects such a $stdout at assignment; rbgo tolerates it). + {"fallback_no_write", `$stdout = Object.new; print "x"`, "x"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := runSrc(t, tc.src); got != tc.want { + t.Fatalf("src=%q got=%q want=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestKernelPutc covers the Kernel#putc closure: a normal call forwards a single +// character to $stdout (an Integer's low byte, or a String's first character) and +// returns its argument; a wrong argument count raises ArgumentError before any +// output. Reference: ruby/ruby v3_4_0 io.c (rb_f_putc). +func TestKernelPutc(t *testing.T) { + if got := runSrc(t, `r = putc(65); print " "; print r`); got != "A 65" { + t.Fatalf("putc(65): got %q want %q", got, "A 65") + } + if got := runSrc(t, `r = putc("XY"); print " "; print r`); got != "X XY" { + t.Fatalf(`putc("XY"): got %q want %q`, got, "X XY") + } + // An empty String writes nothing (the len==0 arm) and returns "". + if got := runSrc(t, `r = putc ""; print r.inspect`); got != `""` { + t.Fatalf(`putc(""): got %q want %q`, got, `""`) + } + // A $stdout that answers no #write falls back to the underlying stream. + if got := runSrc(t, `$stdout = Object.new; putc 65`); got != "A" { + t.Fatalf("putc fallback: got %q want %q", got, "A") + } + // Wrong argument count raises ArgumentError with MRI's message, and nothing is + // written. + for _, tc := range []struct{ src, want string }{ + {`putc`, "wrong number of arguments (given 0, expected 1)"}, + {`putc(1, 2)`, "wrong number of arguments (given 2, expected 1)"}, + } { + err := runStragglerErr(t, tc.src) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("src=%q: got err=%v, want containing %q", tc.src, err, tc.want) + } + } +} + +// TestKernelOutputToReassignedStdout covers output through a custom $stdout that +// answers #write: #puts forwards to $stdout.puts and, when that resolves back to +// Kernel#puts (recv==$stdout), writes straight to the object's #write instead of +// recursing (MRI's rb_f_puts guard); #putc/#print deliver the bytes to +// $stdout.write directly. Verified byte-for-byte against MRI 4.0.5. +func TestKernelOutputToReassignedStdout(t *testing.T) { + // $stdout is restored before the captured value is printed via #inspect (so a + // trailing newline the harness would trim stays visible inside the quotes). + const foo = `class Foo; def write(*a); @b = (@b || "") + a.join; end; def b; @b || ""; end; end; f = Foo.new; o = $stdout; $stdout = f; ` + cases := []struct{ name, src, want string }{ + {"puts", foo + `puts "z"; $stdout = o; print f.b.inspect`, `"z\n"`}, + {"print", foo + `print "y"; $stdout = o; print f.b.inspect`, `"y"`}, + {"putc_int", foo + `putc 66; $stdout = o; print f.b.inspect`, `"B"`}, + {"putc_str", foo + `putc "QZ"; $stdout = o; print f.b.inspect`, `"Q"`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := runSrc(t, tc.src); got != tc.want { + t.Fatalf("src=%q got=%q want=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestKernelPutsFallbackNoWrite covers nativePuts' branch for a $stdout that +// answers no #write: MRI rejects such a $stdout at assignment, but rbgo tolerates +// it and writes to the underlying stream rather than raising. +func TestKernelPutsFallbackNoWrite(t *testing.T) { + if got := runSrc(t, `$stdout = Object.new; puts "x"`); got != "x" { + t.Fatalf("puts fallback: got %q want %q", got, "x") + } +} + +// TestKernelPutcVisibility covers the module_function split registered for putc: +// it is a private instance method of Kernel (so a bare `putc c` works but +// `obj.putc c` does not) and a public method on the Kernel module. Verified +// against MRI 4.0.5. +func TestKernelPutcVisibility(t *testing.T) { + if got := runSrc(t, `p Kernel.private_instance_methods(false).include?(:putc)`); got != "true" { + t.Fatalf("putc private_instance_method: got %q want true", got) + } + if got := runSrc(t, `p Kernel.public_methods(false).include?(:putc)`); got != "true" { + t.Fatalf("putc Kernel public method: got %q want true", got) + } +} diff --git a/internal/vm/stdlib_puppet_test.go b/internal/vm/stdlib_puppet_test.go index 0f5dbf87..b0c4e6d7 100644 --- a/internal/vm/stdlib_puppet_test.go +++ b/internal/vm/stdlib_puppet_test.go @@ -224,9 +224,11 @@ K = DelegateClass(Array); p K.new([9, 8]).first`, "9\n"}, {"p_user_inspect", `class Z; def inspect; ""; end; end; p Z.new`, "\n"}, {"puts_array_flatten", `puts [1, [2, 3]]`, "1\n2\n3\n"}, {"puts_empty_array", `puts []; puts "after"`, "after\n"}, - // to_s/inspect whose result is non-String falls back to the native string. + // #puts coerces a non-String #to_s result to the native string. #p, matching + // MRI's rb_inspect/rb_obj_as_string, coerces a non-String #inspect result + // with #to_s (here 5 -> "5"), not to the native #inspect. {"puts_nonstring_to_s", `class Z; def to_s; 5; end; end; puts Z.new`, "#\n"}, - {"p_nonstring_inspect", `class Z; def inspect; 5; end; end; p Z.new`, "#\n"}, + {"p_nonstring_inspect", `class Z; def inspect; 5; end; end; p Z.new`, "5\n"}, // --- Kernel#hash for the value types and objects ----------------------- {"hash_integer", `p 5.hash`, "5\n"}, From 83ae0b442772f2dd850c1c320094aa928af82418 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Thu, 10 Sep 2026 09:50:22 +0200 Subject: [PATCH 2/2] kernel: dispatch #inspect for objects and containers, Go renderer otherwise MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pInspect dispatched #inspect unconditionally. The Go-backed binding values (Matrix, NDArray, IPAddr, BigDecimal, Date, Bag, Rolify) register no Ruby #inspect of their own, so dispatch rendered them through the generic one and left every Go Inspect() unreachable — 0.0% on the CI merged profile, dropping the 100% coverage gate below the line on both POSIX lanes while windows (same tests, no gate) stayed green. Dispatch for RObject and for Array/Hash — whose Ruby #inspect renders each element through the element's own #inspect, so still shows an overridden one — and use the value's Go Inspect() otherwise, as inspectStr does. Verified vs MRI 4.0.5 (10/10): IPAddr/BigDecimal/Date render byte-identically; overridden #inspect on a plain object, on a built-in subclass, a non-String #inspect coerced with #to_s, and per-element inspect inside both Array and Hash all match. Every binding Inspect() is back at 100.0%, level with main. core/kernel +15. Co-Authored-By: Claude Opus 5 (1M context) --- internal/vm/builtins.go | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 9743179d..c13243bd 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -6919,12 +6919,32 @@ func nativePrint(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Va // dispatches the object's own #inspect (so an overridden #inspect, and the // per-element #inspect used inside Array/Hash/Struct, are honoured) and coerces a // non-String result with #to_s exactly as rb_obj_as_string does. +// +// When the receiver has NOT overridden #inspect — the resolved method is the +// default Object/Kernel/BasicObject one — render through the VM's own +// inspectStr instead. Many built-in binding values (Matrix, NDArray, IPAddr, +// BigDecimal, Date, Bag, …) carry their representation in a Go Inspect() that +// inspectStr calls and that no Ruby #inspect shadows; dispatching the generic +// default would bypass them and print a bare object instead. func (vm *VM) pInspect(v object.Value) string { - r := vm.send(v, "inspect", nil, nil) - if s, ok := r.(*object.String); ok { - return s.Str() + // Dispatch for an ordinary object (where a user #inspect lives) and for the + // containers, whose Ruby #inspect renders each element through the element's + // own #inspect — `p [obj]` must show an overridden one, as MRI does. + // + // Every other value is a built-in or a Go-backed binding (Matrix, NDArray, + // IPAddr, BigDecimal, Date, Bag, Rolify, …) whose representation lives in its + // Go Inspect(); those classes register no Ruby #inspect of their own, so + // dispatching would render them through the generic one and leave every + // Inspect() unreachable. inspectStr takes the same path. + switch v.(type) { + case *RObject, *object.Array, *object.Hash: + r := vm.send(v, "inspect", nil, nil) + if s, ok := r.(*object.String); ok { + return s.Str() + } + return vm.displayStr(r) } - return vm.displayStr(r) + return v.Inspect() } func nativeP(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {