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
125 changes: 117 additions & 8 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down Expand Up @@ -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",
}
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -6834,26 +6881,88 @@ 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.
//
// 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 {
// 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 v.Inspect()
}

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)
}
}

Expand Down
149 changes: 149 additions & 0 deletions internal/vm/kernel_io_output_wave22_internal_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
6 changes: 4 additions & 2 deletions internal/vm/stdlib_puppet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,11 @@ K = DelegateClass(Array); p K.new([9, 8]).first`, "9\n"},
{"p_user_inspect", `class Z; def inspect; "<Z>"; end; end; p Z.new`, "<Z>\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`, "#<Z>\n"},
{"p_nonstring_inspect", `class Z; def inspect; 5; end; end; p Z.new`, "#<Z>\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"},
Expand Down