Skip to content

Share refinements with methods defined in a refine block - #10217

Open
evaniainbrooks wants to merge 1 commit into
jruby:masterfrom
evaniainbrooks:10207-refined-instance-eval-string
Open

evaniainbrooks wants to merge 1 commit into
jruby:masterfrom
evaniainbrooks:10207-refined-instance-eval-string

Conversation

@evaniainbrooks

@evaniainbrooks evaniainbrooks commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #10207.

A method defined in a refine block got a copy of the refinements that existed when it was defined. Refinements added later in the same module were missing, so refining an existing method (like String#upcase) fell back to the original method. Smaller repro:

module Refs
  refine(BasicObject) { def direct = 'x'.upcase }
  refine(String) { def upcase = 'refined' }
end
using Refs
Object.new.direct  # CRuby: "refined", JRuby: "X"

In the issue, the JIT hid the bug: the compiled refined instance_eval does not push a scope, so the eval used the scope of evaluate, which has all refinements.

CRuby shares the refinements with the new cref and marks both as shared (vm.c, vm_cref_new0). A later using copies them first (eval.c, rb_using_refinement). JRuby already checked SHARED_MODULE in usingRefinement but never set it. Now captureParentRefinements shares the map and sets the flag, and the copy happens in getRefinementsForWrite(), so import_methods copies too.

Testing:

  • Added an example to spec/ruby/core/module/refine_spec.rb. It fails without the fix and passes with it in interpreter, JIT and -X-C mode, and on CRuby 4.0.1 and 3.4.8.
  • spec/ruby/core/{module,basicobject,kernel,refinement,main}, spec/ruby/language and spec/compiler pass in interpreter and JIT mode.
  • test/mri/ruby/test_refinement.rb: only test_import_methods fails, and it fails without this change too.

A method or block copied its parent's refinements when it was defined.
A method defined in a refine block then missed refinements added later
in the same module, so a refined existing method such as String#upcase
fell back to the original. CRuby shares the refinements with the new
cref and copies them only when a later using changes them (vm_cref_new0
and rb_using_refinement). Do the same, using the existing SHARED_MODULE
flag, which was checked but never set.

Fixes jruby#10207
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refinements ignored in instance_eval(string) when instance_eval is refined, until JIT warm-up

1 participant