Repository navigation
Conversation
This was referenced Oct 29, 2026
This was referenced Oct 29, 2026
Merged
sholden
force-pushed
the
feature/scoped-clr-extensions
branch
from
October 29, 2026 16:08
0901891 to
1f7acf0
Compare
Refinements: only refined calls pay, and the JIT and OSR keep working
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]>
…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]>
Src/Samples/Linq/101samples.rb stopped parsing when Ruby stopped accepting a trailing comma in a nested block parameter, |(c,), p|, and nothing ran it after that. Past the parse error it raised a NameError at FirstOrDefault, which names Fixnum, gone since Ruby 3.2. - |(c,), p| is |(c, _), p|. - Fixnum is Integer, which is System::Int32 in IronRuby. - Min: Projection called sum, copied from Sum: Projection, and printed the total length of the words instead of the shortest. It calls min now, through method(:min).of(Object, Integer) as Min: Grouped does. A Func<Object, int> fits both Min(Func<TSource, int>) and Min<TSource, TResult>(Func<TSource, TResult>), and IronRuby can't choose between them where C# picks the first. - Repeat printed its 7s without a newline, so the next heading ran on. - OfType was commented out as an IronRuby bug. It works now. The file still calls using_clr_extensions. Its output is the reference for moving it to `using'. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The samples were the last code outside the tests that called using_clr_extensions, so they printed its deprecation warning. They say `using System::Linq' now. Inside the scope calls resolve as they did under using_clr_extensions, so every call keeps its name, and the output is the same apart from the warning. to_seq, which turns the samples' arrays into the IEnumerable<T> LINQ extends, was a method added to Object for the whole program. It is a refinement of Object now, active below the `using' like the LINQ methods. Nothing in the file calls it before that point. A probe at each of the 119 call sites with a LINQ method's name saw all of them run: 112 reach a System.Linq.Enumerable method, and the other 7 are Array#join on what to_a returned. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Nothing ran Src/Samples/Linq/101samples.rb, so nobody noticed when it stopped parsing. build-and-test now runs it on each OS and target framework, after the socket check, and diffs its stdout and stderr against Src/Samples/Linq/101samples.expected, which holds this branch's output on Linux and net10.0. A wrong answer, an exception or a warning fails the step. Tried locally by putting using_clr_extensions back, which adds its deprecation warning; by changing count(pred) to where(pred); by raising in the middle; and by dropping `using LinqSampleHelpers', which makes to_seq undefined. The sample takes about 1.6 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The samples passed every LINQ delegate as lambda { ... }. A block goes to a
method's trailing delegate parameter, so a call whose last argument was a
lambda now takes a block:
numbers.where { |n| n < 5 }, group_by(->(p) { p.category }) { |c, g| ... },
aggregate(start_balance) { |balance, next_withdrawal| ... }. A lambda that
isn't the last argument, such as a key selector before a result selector,
and the make_pair and identity helpers are -> lambdas now.
Two indexed samples keep a lambda. On .NET 9 and later OfType returns one
of LINQ's private iterator classes, whose own public Where(Func<T, bool>)
and Select(Func<T, R>) IronRuby binds to. A block with two parameters fits
those too, because a proc takes any number of arguments, so
digits.where { |digit, index| ... } got nil for index and
numbers.select { |num, index| ... } was ambiguous. A lambda's arity rules
them out. The indexed select_many, take_while and skip_while have no such
methods to compete with and take blocks. Each of the two has a comment.
The output is unchanged, so 101samples.expected is too. A probe at each of
the 119 call sites with a LINQ method's name still sees all of them reach
the same methods as before.
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
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.
using_clr_extensions System::Linqturns LINQ's extension methods on for every call in the runtime. A gem that calls it changes whatlist.selectmeans in every other file. C# scopes extension methods to the files that sayusing System.Linq;, and Ruby already has a lexically scoped way to add methods to a class, refinements. Sousingnow also takes a CLR namespace and brings its extension methods into the rest of the file, class body or eval string, the same places a refinement would be active.using System::Linq::Enumerablebrings in one static class's extension methods, as C#'susing staticdoes.Inside that scope, a call resolves the way it did under
using_clr_extensions. Moving code from one form to the other means changing only theusingline.Resolution matches
using_clr_extensionsusing_clr_extensionsputs a type's extension methods in its own CLR method group. That includes the extension methods of the interfaces the type implements. The scoped form puts them in the same places, only for calls in the scope:They go only where the old form puts them: in the CLR method group of a class backed by a CLR type. That group has the class's own extension methods and those of its interfaces. So:
A Ruby object like an Array, Hash or String gets no LINQ. Its ancestors don't include
IEnumerable[T], which is also why the old form never gave it any. To use LINQ on one, convert it first, for example with ato_seqrefinement like the one in101samples.rb.A first version of this PR put extension methods after every Ruby method, closer to C#'s rule. That made
list.selectmean Ruby'sselectunderusingbut LINQ'sSelectunder the old form, and every sample that moved over had to rename its calls. So the scoped form now resolves exactly like the old one.A Ruby class that includes
IEnumerable[Object]gets no LINQ, as under the old form.To check that, I ran 30 calls on each of 20 kinds of object:
select,where,first,count,min,take,reverse,group_by,zip,to_a,respond_to?,method,sendand others.List[Object],List[Integer],Integer[],HashSet,Dictionaryand anOfTypeiterator;select, and a Ruby class that includesIEnumerable[Object];Results, compared with master before this stack (14d53a5):
using System::Linq, every line matches master'susing_clr_extensions.usings it inside one module, every line outside that module matches master with no activation.using_clr_extensionsand no activation print what they print on master.How it works
It's built on the refinement machinery from Largo#49. A CLR namespace in a scope's
usinglist becomes part of that scope'sRefinementActivation. Methods defined there record it, call sites guard on it, andsend,public_send,method,respond_to?and irb see it. The namespace's extension methods are filed with the types they extend, under their CLR and Ruby names, including methods from assemblies loaded after theusing. Those names join the index of refined (module, name) pairs from Largo#49, so only calls of those names on those types take the guard. Each class caches the merged method group per class version, name and activation.using_clr_extensionsis deprecatedIt keeps working as before. The first call in a process warns:
It's an ordinary warning, not one in Ruby's
:deprecatedcategory, which is hidden by default. It shows unless$VERBOSEis nil.The LINQ samples
Src/Samples/Linq/101samples.rb, IronRuby's port of Microsoft's 101 LINQ Samples, shows the new form. It was the last code outside the tests that calledusing_clr_extensions, and it hadn't parsed in a long time. Its last four commits, reviewed as #5 and merged here:|(c,), p|is|(c, _), p|,FixnumisInteger, and three samples that ran but were wrong are fixed: "Min: Projection" calledsum, "Repeat" lacked a newline, and "OfType" had been commented out.using_clr_extensions System::Linqwithusing System::Linq, and make theto_seqhelper a refinement instead of a method added toObject. Every LINQ call keeps its name, and the output is the same apart from the warning.->for the lambdas that remain. "Where: Indexed" and "Select: Indexed" keep a lambda because of the private-iterator bug under "Not covered".Src/Samples/Linq/101samples.expected. A wrong answer, an exception or a warning fails the step.Numbers
Release build, net10.0, on Linux.
usingsSystem::Linqand makes no hot LINQ call runs as fast as one without theusing.where/countloop of 200,000 iterations takes 1.11–1.14 s throughusing_clr_extensionsand 1.24–1.27 s throughusing, about 12% more. The difference is the lexical guard, plus the precompiled and shared rules that a guarded call gives up.Tests
ClrScopedExtensions1–5cover:Enumerableand merged into CLR method groups, against the Widget, Square and Box fixtures;using static;usingof its namespace;IEnumerable[Object];selectdefined on, then removed from,List[Integer].using_clr_extensionstests now go through aLegacyExtensionsTestOutputhelper, which expects the one warning.spec/languagepasses with 2935 examples and 0 failures. The refinement-related core specs listed in Refinements: only refined calls pay, and the JIT and OSR keep working Largo/ironruby#49 pass with 205 examples and 0 failures. The refinement and JIT matrices still match CRuby.using System::Linqon one line and LINQ calls on the next;respond_to?,methodandsend;using, which doesn't see the extensions;using;101samples.rband the 30-call comparison above.Not covered
[Extension]attribute. Static extension members don't either.$LOAD_PATHavoids it.seq.Take(2).Skip(5)is nil where C# gives an empty sequence,Enumerable.range(1, 3).Take(0)never ends, and a two-parameter block given towhereon anOfTyperesult gets nil for the index.RubyClass.IsVisibleaccepts any public method, whatever its declaring type. The fix isn't small, because the public properties of C# anonymous types belong to internal classes too.Follow-up PRs on top of this one:
Stack
using_clr_extensions.perf/refinements, is that PR's branch, rebased onto Largo's master.using System::Linq: CLR extension methods scoped like C#'s using directive #3, this PRThe fork's #1 and #2 are closed in favour of those.
🤖 Generated with Claude Code