From e3410992b2ac172e970e1b3e578d4e510fde6bb1 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sat, 29 Aug 2026 21:56:32 +0200 Subject: [PATCH] Add the __ENCODING__ keyword __ENCODING__ evaluates to the source file's encoding. rbgo scripts are UTF-8, so the compiler rewrites the bare keyword to Encoding::UTF_8 (an intrinsic beside binding), making it work at the top level, in a method body and as a sub-expression. Verified against ruby 4.0.6. Whole-package coverage stays at 100%; the ruby/spec floor rises 16260 -> 16270 (language/magic_comment +9, language/encoding +1). Co-Authored-By: Claude Opus 4.8 --- internal/compiler/compiler.go | 6 ++++++ internal/vm/encoding_test.go | 17 +++++++++++++++++ scripts/conformance/rubyspec/FLOOR | 2 +- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/internal/compiler/compiler.go b/internal/compiler/compiler.go index 611e0f02..07ee8a60 100644 --- a/internal/compiler/compiler.go +++ b/internal/compiler/compiler.go @@ -839,6 +839,12 @@ func (c *Compiler) compileCall(v *ast.Call) { b.emit(bytecode.OpBinding, 0, 0) return } + // __ENCODING__ is the source encoding keyword; rbgo scripts are UTF-8, so it is + // Encoding::UTF_8. + if v.Recv == nil && v.Block == nil && v.Name == "__ENCODING__" && len(v.Args) == 0 { + c.compileNode(&ast.ScopedConst{Recv: &ast.ConstRef{Name: "Encoding"}, Name: "UTF_8"}) + return + } // A bare eval(str) with no explicit binding evaluates against the caller's // binding, so it can see (and assign) the caller's local variables — exactly // like eval(str, binding). Rewrite it to that two-argument form using the diff --git a/internal/vm/encoding_test.go b/internal/vm/encoding_test.go index 4ae4606e..c3ce4a13 100644 --- a/internal/vm/encoding_test.go +++ b/internal/vm/encoding_test.go @@ -167,3 +167,20 @@ func TestEncodingCompatible(t *testing.T) { } } } + +// TestEncodingKeyword covers the __ENCODING__ keyword, which evaluates to the +// source encoding (Encoding::UTF_8 for rbgo's UTF-8 scripts) at the top level, in +// a method body and as a sub-expression. Asserted against MRI Ruby 4.0.6. +func TestEncodingKeyword(t *testing.T) { + cases := []struct{ src, want string }{ + {`p __ENCODING__`, "#\n"}, + {`p __ENCODING__ == Encoding::UTF_8`, "true\n"}, + {`p [1, __ENCODING__.name]`, "[1, \"UTF-8\"]\n"}, + {`def m; __ENCODING__; end; p m.name`, "\"UTF-8\"\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/scripts/conformance/rubyspec/FLOOR b/scripts/conformance/rubyspec/FLOOR index 29938696..54829da3 100644 --- a/scripts/conformance/rubyspec/FLOOR +++ b/scripts/conformance/rubyspec/FLOOR @@ -1 +1 @@ -16260 +16270