Repository navigation
Conversation
…nsions
A CLR method group is stored in the method table under the name it was looked
up by: w.describe stores Widget's Describe overloads under "describe". When
using_clr_extensions activated more Describe overloads, the groups were
invalidated under the extension's CLR name, "Describe", so the group under
"describe" survived and kept serving the old overloads. A call that resolved
describe before the activation made describe("x") a TypeError (no conversion
of String into Integer) afterwards, and method(:describe) returned the same
stale group. This affected extensions on a class, on an interface, and on a
generic definition (List[Integer]#count before System::Linq lost
Enumerable.Count's overloads).
The invalidation now covers the mangled name as well as the CLR name.
ClrExtensionMethods6-8 cover a class, its CLR and Ruby subclasses and
method(:describe); an interface and a generic type definition; and
List#count with System::Linq.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Defining any refinement used to switch off, for the whole program, every fast
path call dispatch has: precompiled dispatchers, rules shared across receiver
classes, the respond_to?/send intrinsics, direct keyword calls, OSR loops and
the method JIT (permanently, and process-wide). Every method compiled after it
also allocated a scope side object on each call to record its definition-time
refinements. A program that merely loaded a refinement ran ~45% slower.
What a refinement can affect is now tracked the way CRuby's REFINED method
entries do it: per refined module and method name. A call is refinement
sensitive only if some refinement of the receiver's class or one of its
ancestors has a method of that name; only those calls take the lexical guard,
and every other call is bound, dispatched and JIT-compiled as if nothing were
refined.
- RubyContext keeps { refined module -> names } (plus a lock-free set of all
names). A method coming or going in a refinement registers its name and
re-versions the classes below the refined module, so calls bound without the
guard re-bind. This also fixes calls that kept their old target when a method
was added to, redefined in or removed from an active refinement outside its
refine block.
- Precompiled dispatchers, shared rules, respond_to?(:sym) folding and the JIT's
direct keyword calls step aside only for sensitive (class, name) pairs.
- The method JIT resolves the operators and self-call a body binds under the
refinements active where the body was defined, the way its call sites would,
instead of standing down. OSR loops do the same with their scope's
refinements, with an entry guard on them. JitRuntime's global kill switch is
gone.
- A method defined where nothing is `using'd is compiled with no refinement
record at all (a later def of the same body where one is active recompiles
it, as before), and the record, where there is one, is a field of the method
scope rather than a per-call allocation.
- RefinementActivation instances are interned by contents, so a `using' in one
file no longer fails the guards of refined calls in every other file.
- "#{x}" and &x only take the refinement-aware path when some refinement has
#to_s / #to_proc / the symbol's method.
A program that defines refinements without hot refined calls now runs at the
speed of one that defines none (2.1s against 3.0-3.2s before on the long run of
a fib + allocation benchmark); a hot refined call costs ~10-20% over a plain one
for the guard.
Refinements1-6 cover late arrivals in a refinement, refined operators after a
method turned hot, per-name and per-class sensitivity (module and CLR class
refinements), respond_to?, conversions, and a def re-run under a using.
Util/refinement-binding-matrix.rb diffs the bound paths against CRuby with the
JIT and OSR on and off; Util/jit-matrix.rb section 9 now checks what the JIT
compiles once a refinement exists.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A method body records the refinements active at its `def' only once something
has been refined. A method defined before that, but first called (compiled)
after, got an empty record that meant "follow the declaring scope", so a
`using' that came later in the scope it was written in reached into it:
def before(s) = (s.r rescue :plain)
module R; refine(String) { def r = :refined }; end
before('x') # :plain
using R
before('x') # :refined - CRuby: :plain
A def that runs with nothing refined now marks its body, and a compilation for
its module with nothing recorded sees no refinements. A copy compiled for a
refinement (Refinement#import_methods) still follows the scope it was given.
Refinements7 and section 9 of Util/refinement-binding-matrix.rb cover it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ective
using_clr_extensions activates a namespace's extension methods for every call
in the runtime: a gem calling it changes what `list.select' means in every
other file. C# scopes them to the files that say `using System.Linq;', and
Ruby has the same notion for refinements, so `using' now accepts a CLR
namespace and brings its extension methods into the rest of the file, class
body or eval string, exactly where a refinement would be active:
using System::Linq
list.where { it > 1 }.order_by { -it }.to_a
`using System::Linq::Enumerable' brings in one static class's extension
methods, as C#'s `using static' does.
Extension methods come last, as in C#, rather than at the extended type's
place in the ancestors: a call that finds a Ruby method calls it
(list.select is Enumerable#select), one that finds a CLR method group gets them
as more overloads (list.count(pred) next to List#Count; an exact tie still goes
to the instance method), and one that finds nothing gets them alone
(list.where). The CLR-cased name (list.Select) still reaches them.
Built on the refinement machinery: a CLR namespace in a scope's `using' list is
part of its RefinementActivation, so methods defined there record it, call
sites guard on it, and send/public_send/method/respond_to? and irb see it. The
namespace's extension methods are filed with the types they extend (including
those of assemblies loaded later) under their CLR and Ruby names, and those
names join the per-(module, name) index stage one introduced - only calls of
those names on those types take the lexical guard. The group a call sees is
cached per class version, name and activation.
A program that `using's System::Linq pays nothing where it makes no LINQ call;
a hot LINQ call costs ~12% more than through using_clr_extensions, for the
guard. using_clr_extensions keeps working as before and now warns, once per
process, that it is deprecated.
ClrScopedExtensions1-4 cover the lexical scope, extension methods coming last
(Ruby method, merged CLR group, extension alone; Widget/Square/Box fixtures),
`using static', and a call bound before the first `using' of the namespace.
The tests of using_clr_extensions expect its one warning.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… only lexically
The scoped form put extension methods last, behind every Ruby method, so
`using System::Linq' turned list.select from LINQ's Select (what
using_clr_extensions gives) into Enumerable#select, and code moving from one
form to the other had to rename its calls to their CLR names. The scoped form is
meant to be using_clr_extensions confined to a file, class body or eval string,
so it now resolves the same way.
An extension method sits where a refinement of the type it extends would, and a
class's place also has those of the interfaces it implements, as
using_clr_extensions puts both in the class's own CLR method group:
using System::Linq
list.select { it * 2 }.to_a # LINQ's Select, ahead of Enumerable#select
dictionary.select { ... } # LINQ's too, ahead of the IDictionary one
[3, 1].select { it > 1 } # Array#select: Array's ancestors have no IEnumerable[T]
[3, 1].Select { ... } # NoMethodError, as before
A CLR method group anywhere still gets them as more overloads, the instance member
winning an exact tie (list.count(pred), list.reverse). A Ruby method defined
ahead of them wins, and a site bound to them re-binds when one is defined or
removed. A singleton class sees them, as respond_to? and method did under
using_clr_extensions.
Across 13 receivers (List, Integer[], HashSet, Dictionary, an OfType iterator,
a List with a singleton class, Array, Hash, Range, String, Object, ...) and 30
calls, the two forms now print the same, except that a Ruby class including
IEnumerable[Object] gets LINQ through `using' and doesn't through
using_clr_extensions. 101samples.rb prints the same under both with only its
using line changed.
ClrScopedExtensions2 expects LINQ's select; ClrScopedExtensions5 covers Array,
Dictionary, a singleton, Enumerable#where behind LINQ's on a List and ahead of
nothing on an Array, and a Ruby select defined and removed on List[Integer].
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sions has them using_clr_extensions adds extension methods to the CLR method groups of classes backed by a CLR type, its own and those of its interfaces, and nowhere else. The scoped form also looked at interface modules themselves, so a Ruby class that includes IEnumerable[Object] got LINQ through `using' and nothing through using_clr_extensions. Now only a CLR class's place counts, when deciding whether extensions shadow a Ruby method and when gathering them into a group. Against master (14d53a5), over 20 receivers - CLR collections, a List with a singleton class, Ruby subclasses of List with and without their own select, class objects, Array, Hash, Range, String, Struct, Set, Enumerator - and 30 calls each: `using System::Linq' prints what master's using_clr_extensions does, and a program that `using's it in one module prints, outside that module, what master prints with no activation. using_clr_extensions and no activation print what they print on master. ClrScopedExtensions5 also checks the Ruby class including IEnumerable[Object]. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rule of a call a refinement could change tests, on every call, that the caller's scope has the refinements the call was bound under. The scope answered by recursion. A block scope asked its parent, which asked its own, and every step checked again that something had been refined, read the context's refinement version and looked for the memo that only scopes with rare state keep. For a call in a block in a method that was two calls and some twenty dependent loads. The rule now calls RubyScope.GetLexicalRefinements. It leaves out the "anything refined?" test, since a rule with the guard is only built once something has been refined, and that stays true. It walks the chain in a loop. A scope without rare state has no `using' of its own and no memo, so a block steps to its parent unless its Proc has a refine block's override, and a method answers from its definition record. The first scope with rare state answers from its memo, read in place, or takes the general step as before, which recurses from there. GetActiveRefinements is the same walk behind the "anything refined?" test, so every caller gets the answer it got before. A refined call in a block in a method, 20 million calls on one core in Release, took 0.75 s before and 0.66 s after, against 0.56 s for the same call to an ordinary method. Made directly in the method it went from 0.68 s to 0.63 s. Five million calls in a block at the top level went from 0.27 s to 0.25 s, against 0.22 s, and in a class body from 0.32 s to 0.29 s, against 0.25 s. There are no new tests, since every answer is the same. Refinements1-7, the refinement and binding matrices and the refinement specs cover the walk. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… scopes A method sees the refinements recorded where its `def' ran, and nothing can `using' anything inside a method. So the scope of a method has exactly the refinements its record holds. So does the scope of a block written directly in one, unless a refine block is running the block, because Module#refine puts an override on the Proc for as long as it runs. The rule of a refined call made from such a scope now tests that instead of walking. From a method scope it tests that the scope's record holds the refinements the call was bound under. From a block scope it tests that the block's parent is a method scope whose record holds them, and that no refine block is running. The test is chosen for the kind of scope the call was bound from, and the rule is shared like any other. The scope of another method with the same refinements passes it, and any other scope fails it and is bound with the walk. - RubyUtils.EvaluateRefinementBlock counts the refine blocks running, in RubyOps.RefineBlocksRunning, around setting and restoring the override. While none is running no Proc has an override, so the walk also steps over a block scope without reading its Proc. - RubyMethodBody.SetDefinitionRefinements bumps the refinement version when a `def' runs again under other refinements and compiled code may already use its record, so that a scope that memoized the old answer agrees with the rules that read the record. That changes one case. A call still running when its own `def' ran again under other refinements kept the old ones if its scope had evaluated a string, and saw the new ones otherwise. It now sees the new ones either way. CRuby keeps the old ones, but IronRuby only reaches this case because a block run before and after a top-level `using' sees it the second time, and CRuby's block doesn't. I first gave each method body binders of its own, whose rules tested the record without a type test. That was no faster, and a file of 2000 methods calling LINQ's names took twice as long to warm up, because bodies no longer shared rules. The same 20 million refined calls on one core went from 0.66 s to 0.62 s in a block in a method and from 0.63 s to 0.60 s directly in it, against 0.56 to 0.58 s for an ordinary call. #2's benchmark of a hot refined call, run five times as long, went from 1.96 s to 1.87 s, against 1.80 s. Refinements8 covers a `def' run again under other refinements, with calls bound against the old record in the method and in a block, and a call still running, with and without an eval. In Refinements9, Module#refine runs a block in a method, and one inside it, after their calls were bound against the method's record. It fails if the rule or the walk ignores the count. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A call a refinement could change never got a precompiled dispatcher, because a dispatcher tested nothing but the receiver's class version. Where the rule reads a method's record, a dispatcher can read it too. That is a call made from the scope of a method, or of a block written directly in one. The dispatcher tests that the scope is a method scope whose record holds the refinements the call was resolved under, or a block scope whose parent's record holds them while no refine block runs. RubyCallAction.BindPrecompiled resolves such a call under the caller's refinements and asks the RubyMethodInfo for a refined dispatcher. These are variants of the WithScope and WithScopeAndBlock dispatchers, generated from the same templates for arities 0 to 5. Like the others, a refined dispatcher is pointed at the compiled body when the light compiler compiles it, and a rule never is. Any other refined call gets a rule as before, and the dispatchers of unrefined calls are unchanged. #2's benchmark of a hot refined call, run five times as long on one core, took 1.87 s with the rule and 1.81 s with the dispatcher, against 1.80 s for the same call to an ordinary method. Refinements10 makes refined calls on a Ruby object with no arguments, with two and with a block, in a method and in a block in it. Then it runs the `def' again under other refinements and has Module#refine run the block. It fails if the dispatcher ignores the record or the refine block count. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… record The calls of extension methods that a `using' of a CLR namespace brings in are refinement-sensitive calls like any other. So a call made in a method, or in a block in one, now tests the method's refinement record. Where it resolves to a Ruby method on a Ruby object, it gets a refined precompiled dispatcher. ClrScopedExtensions6 checks that such calls bind again when the same `def' runs after a `using System::Linq', and that a method defined after it reaches the extension methods, in the method and in a block. ClrScopedExtensions7 checks the dispatchers against the lookup `using' now does, on an instance of a Ruby subclass of List[Object]. LINQ's skip and where win over Enumerable's, which sit behind List[Object]'s place. The subclass's or a singleton class's own win when they are defined ahead of it, and LINQ's win again when those are removed. An Array keeps Enumerable's. The test fails if the dispatcher resolves the call without the caller's refinements. This is a commit of its own because it needs the CLR namespaces of `using', and the three commits below it do not. Co-Authored-By: Claude Opus 5.5 <[email protected]>
sholden
force-pushed
the
perf/refinement-guard
branch
from
October 29, 2026 15:53
fb6d7b3 to
03de8fe
Compare
sholden
force-pushed
the
feature/scoped-clr-extensions
branch
from
October 29, 2026 16:08
0901891 to
1f7acf0
Compare
sholden
force-pushed
the
feature/scoped-clr-extensions
branch
from
October 29, 2026 17:48
1f7acf0 to
e77892f
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Since #2, a call pays for refinements only where a refinement could change it, and there its rule tests that the caller's scope has the refinements the call was bound under. That test was most of what a hot refined call still cost. The scope answered it by recursion, checking again at every step that anything had been refined, and a refined call could never use a precompiled dispatcher. On #2's benchmark the refined call took 13–17% longer than the same call to an ordinary method.
With this PR a refined call made in a method, or in a block written directly in one, takes 0–2% longer on that benchmark, which is within its noise. Top-level code and class bodies can change their refinements partway through with
using, so their calls still ask the scope. They now do it through a loop that costs 40–65% of what the recursion did.It's stacked on #3, rebased onto df7f389, where
usinga CLR namespace resolves calls the wayusing_clr_extensionsdoes. The first three commits only touch #2's machinery and could move below #3.Where a method's record is enough
A method sees the refinements recorded where its
defran, and nothing canusinganything inside a method.Module#usingrefuses anywhere a method scope encloses the call, andmain.usingrefuses anywhere a method or a class body does. So the scope of a method has exactly the refinements its record holds. So does the scope of a block written directly in a method, except whileModule#refineruns that block and puts an override on its Proc.I looked for ways one compiled body could run under more than one record, and found two.
defthat runs again updates its body's record in place. The refinements can only differ in IronRuby, where a block run before and after a top-levelusingsees it the second time. CRuby's block keeps the refinements it was created with. Every check reads the record's current value, so calls bound against the old one bind again.Module#refineruns a block with an override.EvaluateRefinementBlocknow counts the refine blocks running, and no check that reads a record for a block passes while one is.The rest don't.
define_method,instance_evalandclass_evalwith a block run it with its defining scope as parent, so a block written in a method still has the method's record.Refinement#import_methodscompiles the copy with an empty record that follows the scope it was written in, so its calls walk. Aclass << selfin a method, anevalstring and a block nested in another block aren't one of the two shapes, so their calls walk too.JRuby gives a refined call site its static scope when it compiles it. The method's record is the closest thing IronRuby has, and I first handed it to the call sites the same way, with binders of each method body's own. That cost warm-up time, as described below, so the rules read the record through the scope argument instead. The record can change, so the rule can't drop the test, but it reads one field.
CRuby keeps the method a refined call found in the call site's cache. The refined dispatchers of commit 3 do the same, with the record check. The stale answers noted at the end suggest CRuby's cache doesn't check where the call is made from.
What changed
RubyScope.GetLexicalRefinementswalks the chain without recursion and leaves out the "anything refined?" test, because a rule with the guard only exists once something has been refined. A scope without rare state steps to its parent, a method scope answers from its record, and the first scope with rare state answers from its memo.GetActiveRefinementsis the same walk behind that test, so every caller gets the answer it got before.RubyMethodBodypoints the body's dispatchers at the compiled code, but it can't do that for rules. That was the last 4%.using System::Linq: CLR extension methods scoped like C#'s using directive #3's scoped extension methods under the new checks. This is the only commit that needsusing System::Linq: CLR extension methods scoped like C#'s using directive #3.Under #3's new lookup
None of my code decides on its own that a call can't see an extension method. A refined dispatcher is made from what
ResolveMethodNoLockreturns under the caller's refinements, the same lookup a rule uses, so it gets df7f389's places for free. It binds only a Ruby method that wins. A call that reaches an extension method group gets a rule, as before. The dispatcher tests the receiver's class version and the caller's refinements, as a rule does, so it binds again whenever a rule would, including when a method is defined or removed ahead of the extensions. Singleton classes need nothing special either. A singleton class has its own version, and the lookup from it reaches its class's extension place further up.ClrScopedExtensions7checks this on an instance of a Ruby subclass ofList[Object], the kind of Ruby object that has a place among its ancestors. LINQ'sskipandwherebeatEnumerable's, the subclass's or a singleton class's own take over when defined and hand the call back when removed, and anArraykeepsEnumerable's. It fails if the dispatcher resolves the call without the caller's refinements.The LINQ benchmark
Under df7f389,
l.where { ... }.countreaches LINQ'sCountthrough both forms, so the 9% gap betweenusing System::Linqandusing_clr_extensionsI reported before is gone. The two are now within 3% of each other, and this PR doesn't move either one. The guard was never a measurable part of a 6 µs iteration. These calls are on CLR objects, so they get rules rather than dispatchers.What I tried and dropped
My first version gave each method body binders of its own, whose rules tested the record without a type test. It was no faster than reading the record through the scope, and bodies stopped sharing rules. A file of 2,000 methods calling
first,countandselectunderusing System::Linq, each called once, took 2.1–2.2 s instead of 1.0 s.Numbers
Release build, net10.0, on Linux, on a Ryzen 7 5800H that other jobs were using at the same time. I alternated runs with a Release build of #3. "Pinned" runs were held to one physical core with
taskset -c 12,13, which kept the spread down.#2's benchmark, 3 million refined calls, 9 runs each, against df7f389:
I measured the tables below against #3's previous head, afadb4b, before the rebase. The rebase didn't change the first three commits, and df7f389's lookup only runs where a CLR namespace is in scope, which none of these benchmarks has.
The same benchmark, run five times as long and pinned, 5 runs at each commit:
A refined call with a trivial body, 20 million calls, pinned, medians of 5 runs:
Five million refined calls in a block, pinned, medians of 7 runs. These still walk.
#3's LINQ benchmark, 200,000 iterations, 7 runs each, against df7f389:
using System::Linqusing_clr_extensionsWarm-up of a file of 2,000 methods, each called once, under
using System::Linq, pinned, against df7f389: 1.05–1.08 s before, 1.02–1.07 s after.Util/bench, all 63 benchmarks, best of 3, against afadb4b. I ranUtil/bench/run.sh 3one benchmark at a time, alternating between the two builds. The geometric mean of the ratios is 1.003. Eight benchmarks moved past 5%. Rerun twice at best of 5, seven came back within 5%, at 0.96–1.02.strscan_tokensstayed at +11% because it runs in two modes, about 0.52 s and 0.60 s, in both builds. Ten single runs of each gave a best of 0.516 s before and 0.526 s after. No benchmark in the suite defines a refinement or uses a CLR namespace, so none of them reaches the code this PR or df7f389 changes. An earlier full run, before commit 3, came out at 0.997.Tests
All of these ran on the branch as it is now, on df7f389, unless they say otherwise.
Refinements8,Refinements9andRefinements10inSrc/IronRuby.Tests/Runtime/RefinementTests.cscover adefrun again under other refinements, with calls bound against the old record and a call still running, with and without an eval. They coverModule#refinerunning blocks whose calls were bound against a method's record, and refined dispatchers with no arguments, with two and with a block. I removed each check in turn and the test covering it failed: the version bump, the refine block count in the rule, the walk and the dispatcher, and the record in the dispatcher.ClrScopedExtensions6makes scoped extension calls in a method and in a block in it, and runs thedefagain after ausing System::Linq. NewClrScopedExtensions7is described above.using System::Linq: CLR extension methods scoped like C#'s using directive #3's ownClrScopedExtensions5also binds a call in a method through the record test, and passes.spec/languageon both frameworks.spec/languagepasses with 2935 examples and 0 failures, in Debug and in Release.Util/refinement-binding-matrix.rbprints the same as CRuby 4.0 against the Debug and Release builds, with the JIT and OSR on and off.Util/jit-matrix.rbmatches CRuby in Debug and Release too.Util/refinement-matrix.rbprints exactly what df7f389's build prints, in Debug and in Release. It differs from CRuby only in object addresses and in the 9 lines that quote a method name with a backtick, which Error messages quote names 'like this', as Ruby 3.4 and 4.0 do #9 fixes.send,public_send,method,respond_to?,&:sym, string interpolation,instance_evalwith a block and a string,eval,binding.eval, lambdas,define_method,module_function, singleton methods,class << selfin a method,import_methods, refine blocks, and LINQ calls on Ruby and CLR receivers. They print the same as df7f389's build, except for the case above, with the JIT and OSR on and off.perf/refinementswithout conflicts. There IronRuby.Tests passed, the binding and JIT matrices matched CRuby with the JIT and OSR on and off in Debug and Release, the refinement matrix printed the same asperf/refinementsalone, and the refinement core specs passed with 205 examples and 0 failures. The rebase left those three commits unchanged.Found, not fixed
All of these predate this PR.
refine(String, &pr). CRuby 4.0 raisesArgumentError: can't pass a Proc as a block to Module#refine.usinginside a block at the top level stays active for the rest of the file in CRuby, and only for the rest of the block in IronRuby.usingsees it when it's called later in IronRuby. In CRuby it keeps the refinements it was created with. That is the only way adefcan run again under different refinements.Module#refinestarts running a block whose calls ran before, so it misses the refinements the refine block activates.Refinements9andRefinements10note where CRuby prints something else because of it.IEnumerable[Object]still takes the refinement test, though df7f389 gives that class no extension place. It costs the test and nothing else, which this PR makes about 1 ns.-ER, which asks a Debug build to print the rules it binds, is parsed as-Ewith the encoding nameR, so IronRuby fails to start.Stack
using_clr_extensionsusing System::Linq: CLR extension methods scoped like C#'s using directive #3 scopes CLR extension methods withusing, resolved asusing_clr_extensionsresolves themusing System::Linq: CLR extension methods scoped like C#'s using directive #3. The fourth testsusing System::Linq: CLR extension methods scoped like C#'s using directive #3.🤖 Generated with Claude Code