Skip to content

CLR interop for modern Ruby: keywords, blocks and delegates, pattern matching, on-demand BCL loading - #26

Merged
Largo merged 33 commits into
masterfrom
feature/clr-interop-modern
Oct 27, 2026
Merged

Largo merged 33 commits into
masterfrom
feature/clr-interop-modern

Conversation

@Largo

@Largo Largo commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

Calling .NET from Ruby, checked end to end against the classic IronRuby interop surface and brought up to what Ruby 4 code naturally writes.

The classic interop still works. CLR namespaces as modules, require/load_assembly, name mangling, generics (List[String], method(:m).of(String)), out/ref parameters, indexers, enums and flags, events (add/remove/block), clr_member/clr_ctor/clr_new/overload, interface implementation via include, overriding virtuals, properties and events from Ruby subclasses, opening CLR classes, hosting through ScriptEngine/ScriptScope/Operations (plus C# dynamic), extension libraries built with ClassInitGenerator, ADO.NET, and Test::Unit/minitest/RSpec/Cucumber against CLR types. What was broken is fixed here:

  • System::Console.WriteLine "hi" failed with uninitialized constant System::Console: the BCL is split into many assemblies on .NET 8. Platform assemblies now load on demand when a constant misses in a CLR namespace (System::Console, System::Linq, System::Text::Json, System::Net::Http, ...), using the trusted platform assembly list.
  • Overriding one overload of a virtual (def sleep; super(14); end) broke C# callers of the other overloads. Now a virtual call the Ruby override can't take goes to the CLR implementation of that overload.
  • Several CLR names that #methods listed (jr_connect, update_transfer_data, create_qr_code) weren't callable. Now they are.
  • include System::IComparable failed because the name is also IComparable<T>. A type group now stands for its non-generic member wherever a module is expected. Static calls on it also work: Task.Run, Tuple.Create.
  • ir -r csv didn't see bundled gems; it now goes through RubyGems' require as MRI does. ir -X:ExceptionDetail could not start, because caller included CLR frames and require_relative resolved against a .cs file.

Binder: modern Ruby calls into CLR methods

  • Keyword arguments bind by name to parameters (greet("Bob", greeting: "Hi"), first_name: for firstName). This includes splatted **opts. On constructors they also set properties and fields, like a C# object initializer: Widget.new(title: "t", width: 3), Point.new(x: 1, y: 2) for structs. Keywords that bind to nothing are passed on as a positional Hash only where a Hash fits; otherwise MRI's unknown keyword error is raised.
  • A block goes to the trailing delegate parameter: list.ForEach { }, list.Sort { |a, b| b <=> a }, Task.Run { 6 * 7 }, LINQ list.where { it > 1 }.
    • Before, the block was silently ignored (Sort with a block sorted ascending).
    • break inside the block ends the CLR call with its value.
    • A block with fewer parameters than the delegate passes ignores the extra arguments, as Ruby blocks do.
    • If overloads differ, the one matching the block's arity wins; between Action and Func, the one that keeps the block's value wins.
    • A block that fits several overloads equally is now an error that suggests passing the delegate explicitly, instead of being dropped.
  • Method objects convert to delegates, like Procs already did.
  • Out/ref results are a Ruby Array. So ok, n = Int32.TryParse("42") works, TryParse results can be pattern-matched, and a C# Deconstruct(out ...) serves as #deconstruct.
  • Ruby Arrays and Hashes pass for typed collections, converted item by item: int[], IEnumerable<T>, IList<T>, List<T>, Dictionary<K,V>. Before, an Array could not be passed for an int[] at all.
  • Ruby ranges and negative indexes pass for System.Range/System.Index, with Ruby's meaning (1..-2, -1 is ^1).
  • Generic inference with blocks: a block no longer forces a delegate's input type parameter to Object. That was what broke Where<T>(IEnumerable<T>, Func<T,bool>) on a List<int>. This is a new DLR patch, Build/dlr-patches/0005-TypeInferer-invokable-delegate-parameters.patch. It applies cleanly after 0001–0004 on a fresh upstream checkout.
  • Method#parameters names a CLR method's parameters, which keywords bind to.

Library: Ruby protocols on CLR objects

  • Delegates are callable like lambdas: call, .(), [], to_proc (so map(&func)), arity, parameters, curry, >>, <<.
  • Tuples and key-value pairs destructure: to_ary/deconstruct on every ValueTuple/Tuple; dict.each { |k, v| } now yields key and value.
  • Hash patterns match CLR objects' public members: case point in {x: 1, y:}, by Ruby or CLR name. Plain Ruby objects and builtins are unchanged.
  • IComparable<T> types are Comparable: <, between?, clamp, max.
  • Tasks and async streams:
    • Task#value waits and unwraps a single inner exception.
    • IAsyncEnumerable<T> is Enumerable.
  • C# 8 default interface methods can be called from Ruby, and they run for Ruby classes that implement the interface.

Also fixed on the way:

  • in {} / **nil now pass nil to deconstruct_keys, as MRI does.
  • load_assembly invalidates cached defined? misses.
  • using_clr_extensions sees extension methods of assemblies reached through facades, and of closed generic interfaces: LINQ sum/max/average on List<int>.

The README gains a short "Calling .NET" section; every line in it was run against a build.

Testing

  • IronRuby.Tests: 0 failures (master: 0), rebuilt from clean bin/obj.
    • Three new test files: ClrBinderTests.cs, ClrProtocolTests.cs, ClrRuntimeInteropTests.cs.
    • Three existing expectations were updated: Method#inspect now shows parameter names (2), and CLR classes list the pattern-matching mixin in ancestors (1).
  • spec/language: 2934 examples, 0 failures, 0 errors (same as master).
  • spec/core: directory by directory, identical to master in every directory: 23,136 examples, 0 failures, 20 errors (the known ObjectSpace.each_object and friends). Expectation counts only differ in timing-dependent thread specs.
  • spec/library: 6,398 examples, 0 failures, 0 errors (same as master).
  • CI: green on Linux and Windows for net8.0 and net10.0, including the Windows Forms Notepad sample.
  • The original IronRuby interop suite (Tests/Interop/net, run with a Fixnum = Integer shim):
    • No regressions against master; small gains in ruby, typegroup and class.
    • One expectation flips: the old suite asserts both that include IInterfaceGroup raises and that it includes the non-generic member. This branch does the latter.

Known gaps (unchanged)

  • A Ruby subclass whose initialize calls super(args) into a CLR constructor still fails. A class with no default constructor needs new instead. Fixing it means deferring construction until super, as JRuby does.
  • A Ruby String passed for an object parameter arrives as MutableString; to_clr_string converts it. Some APIs reject it, e.g. ADO.NET AddWithValue.
  • Windows Forms is covered by the Notepad sample in Windows CI. WPF was not exercised here.

🤖 Generated with Claude Code

Largo and others added 28 commits October 26, 2026 23:52
Calls into CLR methods now accept what Ruby 3/4 code naturally passes:

- Keyword arguments bind to parameters by name, in any order, using either
  the CLR name or IronRuby's snake_case form of it (greet("Bob", greeting:
  "Hi"), first_name: for firstName). On a constructor, keywords that no
  parameter takes set writable properties and fields of the new object, like
  a C# object initializer: Widget.new(title: "t", width: 3). When nothing
  binds by name the keywords fall back to a positional Hash, which is what
  Ruby does for a method without keyword parameters.
- A block passed to a CLR method goes to its trailing delegate parameter:
  list.ForEach { |x| }, list.Sort { |a, b| b <=> a }, list.FindAll { }.
  Before, the block was silently dropped (Sort with a block sorted
  ascending). A block that fits no delegate parameter is still unused.
- A Method object converts to a delegate whose parameter count it accepts,
  like a Proc does: Funcs.Apply(method(:twice), 5).
- Out and ref parameters come back as a Ruby Array instead of a CLR
  object[], so the result destructures and pattern matches; a C#
  Deconstruct(out ...) method (records, KeyValuePair) now serves as
  #deconstruct for array patterns.

Rules that depend on the keywords test the exact keyword set, and rules
that pass or skip the block test that a block is there and its arity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On .NET Core the class library is split into many assemblies that the
runtime only loads when referenced, so the most basic interop example,
System::Console.WriteLine, raised NameError until the script ran
load_assembly 'System.Console'; the same for System::Linq, the
System.Collections generics, Regex, Process, HttpClient, Json, Xml...

A constant lookup that misses in a CLR namespace module now tries the
platform assemblies that could define the member - A.B.Name, A.B, A for
a miss in A.B, then the netstandard facade - and looks again. Only
names on the trusted platform assembly list are considered, each
namespace member and each assembly is tried once, and the top level
(Object) is never involved. Startup is unchanged: nothing misses in a
CLR namespace while the runtime boots.

Loading an assembly now also moves the constant version: a defined?
site that cached a miss kept answering nil after load_assembly added
the member.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A delegate returned from C# only answered #invoke, so it could not be
passed as a block (&func), composed with a Proc, or used where Ruby
expects a callable (Proc#>> checks respond_to?(:call)). DelegateOps
extends System.Delegate with what Method/Proc offer: call, (), [], ===,
yield, to_proc, arity, parameters, lambda?, curry, >> and <<.

Every call goes through a dynamic site for Invoke, so arguments get the
same conversions a direct #invoke gives them. #to_proc is a lambda whose
recorded signature is Invoke's, so its arity, parameters and argument
count checks match the delegate's; curry, >> and << reuse ProcOps on that
lambda, as CRuby's Method#curry/>>/<< do on Method#to_proc. Out
parameters are left out of the signature since callers do not pass them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A constant that names both a type and generic types of the same name
(System::Threading::Tasks::Task, System::Tuple, System::Nullable, ...)
is a TypeGroup, so Task.Run, Tuple.Create or Nullable.GetUnderlyingType
raised NoMethodError for TypeGroup. TypeGroup already forwarded new,
clr_new, clr_ctor and superclass by hand.

TypeGroup now has method_missing and respond_to_missing?: a call the
group does not define itself goes to the non-generic type when that type
has a public method of the name (arguments and block passed on through a
send site); anything else raises the usual NoMethodError. The group's
own methods (Enumerable, name, ...) still win. `Task::Factory` style
constant access is not covered: the runtime rejects `::` on a non-module
before any method is consulted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A C# 8 default interface method has a body of its own, but interface
modules exposed no members at all - abstract ones are metadata, an
object exposes its implementation through its class - so the body was
unreachable: C# calling IGreeter.Greet() on a Ruby object that includes
IGreeter got NoMethodError 'Greet', and so did Ruby calling greet on it
or on a C# object whose class relies on the default.

An interface module now resolves the public default methods (and
default property accessors) of its interface and of the interfaces it
extends. The group is an attached CLR member, so a virtual call from
the generated override forwards to the base dispatch, a non-virtual
call of the default body - valid IL on .NET 8 for a type implementing
the interface, checked with an emitted type. Calls from Ruby go through
the interface, where an override or explicit implementation still wins,
and super from a Ruby override reaches the default body.

Method listing no longer skips CLR modules: methods and instance_methods
missed what respond_to? and calls found there - the default methods and
the Ruby methods libraries define on interface modules (ArrayList#each).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A C# method returning (int Min, int Max) could not be taken apart with
`min, max = ...`, a block given a dictionary's pairs got the pair and nil
for |k, v|, and neither worked with array or hash patterns.

ITuple (every ValueTuple and Tuple) gets to_a/to_ary, deconstruct,
size/length and [] (Array#[] index semantics). KeyValuePair<,> - a generic
type definition module, which the runtime mixes into each instantiation -
and DictionaryEntry get to_a/to_ary and deconstruct_keys ({key:, value:},
also answering the CLR names Key/Value); DictionaryEntry also gets
deconstruct. KeyValuePair's own CLR Deconstruct is found before anything
a mixin defines, so array patterns on pairs use it.

#deconstruct/#deconstruct_keys hand CLR strings to the pattern as Ruby
strings, since String === only matches those; to_a/to_ary keep the values
as the CLR returned them, like every other CLR collection conversion.
deconstruct_keys follows Struct's contract: nil asks for every key, an
Array for those keys (Symbols or Strings), anything else is a TypeError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ions

Follow-up to the keyword and block binding:

- Keywords also bind by name when they arrive splatted (f(**opts),
  f(*args, **opts)), and a site that sees different keyword sets binds each.
- Keywords that bind to nothing raise MRI's "unknown keyword: :zz". They
  fall back to a positional Hash only for a parameter that takes a Hash as
  it is (Hash, IDictionary, Object), not one the conversion protocols would
  try to turn it into an Integer.
- Value types with no declared constructor take keywords too:
  Point.new(x: 1, y: 2). new is now a generic default(T) factory whose
  return type lets the binder set members, replacing the stub that was
  swapped for Expression.New after resolution.
- A delegate made from a Proc calls it the way Proc#call does, with its own
  flow-control frame, so break in a block passed to a CLR method ends that
  call with the break value (list.ForEach { |x| break if ... }).
- A block or proc converts to a delegate of any arity - it ignores extra
  arguments, as Ruby blocks do - while overload resolution prefers the
  delegate that matches its arity, and between Action and Func the one that
  keeps the block's value. Lambdas still need a matching arity.
- A Ruby Array passed for T[], IEnumerable<T>, IList<T>, IReadOnlyList<T>,
  List<T> etc. and a Hash passed for Dictionary<K, V>/IDictionary<K, V> are
  copied into one, each item converted as an argument would be (TypeError or
  RangeError for an item that does not fit). Before, an Array could not be
  passed to an int[] parameter at all ("no implicit conversion of Array into
  Array").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Overloads of a CLR virtual method usually call each other - Sleep()
calls Sleep(8), which calls Sleep(8, "bed") - and a Ruby method that
overrides the name takes every overload's place. A Ruby
`def sleep; super(14); end` therefore broke the chain: Sleep(int)'s
virtual call of Sleep(int, string) arrived at the Ruby method with two
arguments and raised ArgumentError.

A virtual call whose argument count the Ruby method cannot accept now
goes to the CLR implementation of that overload, as if the Ruby method
overrode only the overloads it can take. Only the virtual-call path
changes: calls from Ruby keep Ruby semantics (the Ruby method replaced
the name), a method with a rest parameter still receives everything,
an ArgumentError raised inside a matching override propagates, and an
abstract overload, having nothing to fall back to, still gets the
ArgumentError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nDetail

- `ir -r csv` failed with "cannot load such file -- csv" although csv is
  installed as a bundled gem: the -r libraries were loaded by the loader
  directly, past the Kernel#require RubyGems installs. MRI calls #require
  on main for each -r, so they now go through main's #require once the
  prelude has loaded RubyGems (and through the builtin loader without it).
- `ir -X:ExceptionDetail` could not start: the switch also added CLR frames
  to Kernel#caller, and require_relative, which takes the directory of the
  first caller frame, resolved rubygems/defaults against a .cs file of the
  runtime. The switch is about exception backtraces; caller and
  caller_locations now report Ruby frames in every mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A hash pattern hands #deconstruct_keys the keys it names, or nil when it
needs every key. The prism lowering passed nil only for a named **rest;
MRI (prism_compile.c) also passes nil for **nil, which has to see the
keys the pattern does not name, and for `in {}`, which matches only an
object with no keys at all. With the key list instead, Struct and Data
returned {} for `in {}`, so `Struct.new(:a).new(1) in {}` matched where
MRI says false.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`case point; in {X: 1, Y: y}` against a C# record, class or struct failed
with "does not respond to #deconstruct_keys". Pattern matching asks
respond_to?(:deconstruct_keys), so the CLR object has to have one - but
only CLR objects: a plain Ruby object must keep not responding, and the
built-in classes keep their own.

A library module, IronRuby::Clr::PatternMatching, defines
deconstruct_keys over the public readable instance properties and fields
(indexers, static and non-public members left out; a member hidden by
`new' counts once). A key is the CLR name or the Ruby name that member
calls already use (first_name for FirstName, via RubyUtils mangling);
nil asks for every member under its Ruby name. The contract is
Struct#deconstruct_keys's: missing keys are absent, a non-Array argument
is a TypeError. Values that are CLR strings are handed over as Ruby
strings so that `name: String => n` matches.

The runtime mixes the module into every concrete CLR class it creates
for a type no library defines, the way it mixes FlagEnumeration into
flag enums (a stub type marks it). That set is exactly the "plain CLR
types": Ruby classes, built-ins and library extension classes are not
created there. Being an ordinary mixin, it comes after the class's own
CLR members and after interface/generic-definition modules
(KeyValuePair's deconstruct_keys wins), and a Ruby definition in the
class or in an included module overrides it. Abstract classes are left
out: they have no instances, and System::Char, a library class deriving
from ValueType, would otherwise inherit it. ClrGenerics1 lists the first
three ancestors of a generic class, which now include the module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
For a CLR method that is not overloaded, #parameters now describes its
real parameter list, with the names keywords bind to in IronRuby's
snake_case form: Options.method(:Greet).parameters is
[[:req, :name], [:opt, :greeting], [:opt, :times]] instead of the
[[:req], [:rest]] approximation derived from the arity. Out parameters are
results, not arguments, and are left out. Overloaded methods and Ruby
library methods (which MRI describes without names too) are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The non-generic IComparable has long been mixed with Comparable and
given <=>, but a C# type implementing only IComparable<T> had a <=> that
returned nil and no <, between?, clamp; [a, b].max failed.

IComparable<> - the generic type definition module, which the runtime
mixes into every IComparable<X> and so into every implementing type -
now includes Comparable and defines <=>. The argument picks the
CompareTo: the T it is exactly, else one it is an instance of (so a
subclass compares through its base's IComparable<Base>); a Ruby string
goes to IComparable<string> as a CLR string. The calls go through a
delegate cached per T rather than reflection.

<=> answers nil for what cannot be compared, as Ruby's contract says:
nil, an argument no CompareTo takes, and - for the non-generic
IComparable - whatever CompareTo rejects with ArgumentException, which
IComparable documents as its "not my type" answer. It used to raise.

The class-init generator named the initializer of an extension by the
Ruby name, which drops generic arguments, so IComparable and
IComparable<T> produced two LoadSystem__IComparable_Instance methods. A
generic definition's id now carries its arity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A generic type definition extension has the Ruby name of its
non-generic namesake (System::IComparable for IComparable<T>), and
Array.Sort is not stable, so the two registrations swapped places
depending on what else the library defined. The id breaks the tie.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Task#value is Thread#value for a task: it waits and returns the result,
nil for a task without one. A faulted task raises the exception it
failed with instead of the AggregateException around it (unless there
are several), a cancelled one its TaskCanceledException. Result and Wait
are unchanged. The result is read through a delegate cached per task
type, found by walking up to Task<T>, so the internal subclasses an async
method returns (AsyncStateMachineBox<...>) work; a Task<VoidTaskResult>
- what `async Task' methods and Task.CompletedTask really are - has no
result and gives nil.

IAsyncEnumerable<> (a generic type definition module, mixed into every
implementation) includes Enumerable and defines #each, which drains the
stream synchronously - waiting on each MoveNextAsync through AsTask, as
an incomplete ValueTask may not be read directly - and disposes the
enumerator however the iteration ends, break included. Without a block
it returns an Enumerator. to_a, first(n), map etc. come from Enumerable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Mangling is not one-to-one: JrConnect and JRConnect both mangle to
jr_connect, which unmangles to JRConnect; updateTransferData mangles to
update_transfer_data, which unmangles to UpdateTransferData; CreateQrCode
to create_qr_code, which unmangles to CreateQRCode. #methods listed these
members under their mangled names, but calling those names raised
NoMethodError - so did System::Text::Encoding.ut_f8 and Uri.uri_scheme_ws.

A name that finds no member through unmangling is now looked up among
the members of the type whose names mangle to it (a member the name
unmangles to still wins). TryMangleName and TryUnmangleName keep their
rules - IPAddress <-> ip_address, SHA unmangled, SH <-> sh, the
two-letter words - so IronRuby::Clr::Name.mangle/unmangle are unchanged.
Default interface methods match the same way.

Two listing fixes go with it: a class no longer lists the operators of
its type (they are invoked on instances, where they are listed), and a
name is listed once, for the member a call reaches - List#Count rather
than also Enumerable#count behind it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Delegate and Task became library classes (DelegateOps, TaskOps), and a
library class extending a CLR type does not get that type's interfaces
mixed in - only classes the runtime creates do. So delegates stopped
being System::ICloneable/ISerializable and tasks System::IAsyncResult/
IDisposable, and since a subclass only mixes in the interfaces it adds,
so did every Func and every Task<T>.

Both now [Includes] their interfaces. The library initializer could only
include modules a library had defined; a CLR interface it is asked for
is now looked up (or created) the way the runtime does for any CLR type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Follows from #parameters naming the parameters of a CLR method that is not
overloaded: List#f3 inspects as f3(t) and C#middle as middle(a), where they
showed an anonymous (_) before. MRI shows names too wherever it knows them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…expected

System::IComparable names both IComparable and IComparable<T>, so the
constant is a type group, and `include System::IComparable` - the way a Ruby
class implements a CLR interface - failed with "no implicit conversion of
Microsoft::Scripting::Actions::TypeGroup into Module". So did
obj.is_a?(System::IComparable) and every other call that takes a module.

A type group now converts to the module or class of its non-generic member
wherever a module or class is expected, as TypeGroup#new already builds the
non-generic member. A group with only generic members (System::Func) raises
a TypeError that points to Func[...]/Func.of(...).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…interface methods, overload overrides, CLR name lookup

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	Src/IronRuby.Tests/RubyTests.cs
…rguments

Generic type inference let a Ruby block passed for a delegate parameter
decide the type parameters of that delegate's own parameters. For
Where<T>(IEnumerable<T>, Func<T, bool>) the block's guess, Object, widened T
past the int the List<int> receiver gives, and binding then failed to
convert the List<int> to IEnumerable<object>. So list.where { |x| x > 1 }
and list.Where(->(x) { ... }) after using_clr_extensions System::Linq, and
any generic C# method shaped like it, could not be called with a block.

A block takes whatever its delegate passes it, so it says nothing about
those types: Build/dlr-patches/0005 makes such an input abstain in the DLR's
TypeInferer and lets the other arguments decide. Its guess is still used
when nothing else mentions the type parameter (Apply<T>(Func<T, T>)), and
type parameters in the delegate's return type are inferred as before.
The patch applies cleanly on a fresh upstream checkout after 0001-0004.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es, tuples, patterns, IComparable<T>, Task, type groups)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	Src/IronRuby.Tests/RubyTests.cs
After using_clr_extensions System::Linq, List[Integer]#sum raised "wrong
number of arguments (given 0, expected 1)": the method group held only
the generic selector overloads Sum<T>(IEnumerable<T>, Func<T, int>) and
the like. The non-generic Sum(this IEnumerable<int>) - and Max, Min,
Average without a selector - are activated on the IEnumerable[Integer]
module, which the class mixes in, but the class only took an interface
module's extension when ExtensionMethodInfo.IsExtensionOf accepted the
class's type, and for an extended type without type parameters that
means the very same type.

An extension of an instantiated interface now applies to every type
implementing it, so its overloads join the generic ones in one group:
l.sum, l.Sum, l.max, l.average work, and a selector passed as a Func
still reaches the generic overloads. Ruby's own Enumerable#sum stays
shadowed only after the opt-in using_clr_extensions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…locks

Found by running the combined branches together:

- using_clr_extensions System::Linq found no extension methods once the
  System.Linq types had become known through a facade's type forwarders
  (netstandard, System.Xml): the assembly that defines them is loaded by
  the forwarding but never reported as loaded, so it was never scanned.
  Activating a namespace now also scans the assemblies its types really
  live in (and the empty, global namespace is handled).
- The on-demand loading of platform assemblies fell back to the
  netstandard facade for any namespace - including one included into
  Object (include Modern), where every top-level constant lookup lands.
  The fallback is now only for System and Microsoft namespaces.
- A block also goes to a trailing delegate parameter in a splatted call,
  which is how a type group forwards Task.Run { ... } to Task.
- Of delegates that all return a value, a block prefers the one returning
  Object: Task.Run { 6 * 7 } is Run(Func<TResult>), not
  Run(Func<Task<TResult>>), which a block returning 42 cannot satisfy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…faces

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	Src/IronRuby.Tests/RubyTests.cs
When a block fit more than one delegate overload equally - LINQ's
Sum(Func<T, int>), Sum(Func<T, long>), Sum(Func<T, double>) ... - the call
fell back to an overload without a delegate and silently ignored the block:
list.sum { |x| x * 2 } returned the plain sum. It now raises the ambiguity,
naming the overloads and pointing to passing the delegate itself
(list.sum(System::Func[Integer, Integer].new { |x| x * 2 })).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
C# 8's Index and Range are how .NET APIs take a slice. A Ruby Range of
Integers now passes for a System.Range with Ruby's meaning - inclusive end
unless excluded, nil for a beginless or endless side, negative endpoints
counting from the end: 1..3 is 1..4, 1...-1 is 1..^1, -3..-1 is ^3..^0 -
so a C# s[range] gives what Ruby's s[range] gives. A negative Integer
passes for a System.Index counted from the end (-1 is ^1), where Index's
own implicit conversion threw "Non-negative number required". A Range
with non-Integer endpoints is a TypeError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A section on CLR interop: what has always worked, and what .NET APIs take
now - blocks for delegates, keywords by name, delegates as callables,
pattern matching on records and tuples, LINQ with blocks, Task#value,
ranges for System.Range - each line of it checked against a build.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 57 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f232f75e-6572-4914-b535-109b433c8692
Commits

Reviewing files that changed from the base of the PR and between 471260a and c122a4d.

Files ignored due to path filters: 2
  • Src/Libraries/Initializers.Generated.cs is excluded by !**/*.generated.*
  • Src/Ruby/Compiler/ReflectionCache.Generated.cs is excluded by !**/*.generated.*
Files selected for processing: 35
  • Build/dlr-patches/0005-TypeInferer-invokable-delegate-parameters.patch
  • Build/dlr-patches/README.md
  • README.md
  • Src/ClassInitGenerator/Libraries/LibraryDef.cs
  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/ClrBinderTests.cs
  • Src/IronRuby.Tests/Runtime/ClrProtocolTests.cs
  • Src/IronRuby.Tests/Runtime/ClrRuntimeInteropTests.cs
  • Src/IronRuby.Tests/Runtime/ClrSubclassingTests.cs
  • Src/IronRuby.Tests/Runtime/ClrTests.cs
  • Src/Libraries/Builtins/ModuleOps.cs
  • Src/Libraries/Extensions/ClrPatternMatchingOps.cs
  • Src/Libraries/Extensions/DelegateOps.cs
  • Src/Libraries/Extensions/IComparableOps.cs
  • Src/Libraries/Extensions/TaskOps.cs
  • Src/Libraries/Extensions/TupleOps.cs
  • Src/Libraries/Extensions/TypeGroupOps.cs
  • Src/Prism/PrismAstBridge.cs
  • Src/Ruby/Builtins/LibraryInitializer.cs
  • Src/Ruby/Builtins/Proc.Meta.cs
  • Src/Ruby/Builtins/RubyClass.cs
  • Src/Ruby/Builtins/RubyMethod.Meta.cs
  • Src/Ruby/Builtins/RubyModule.cs
  • Src/Ruby/Builtins/Stubs.cs
  • Src/Ruby/Runtime/Calls/RubyCallAction.cs
  • Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs
  • Src/Ruby/Runtime/Calls/RubyMethodGroupInfo.cs
  • Src/Ruby/Runtime/Calls/RubyOverloadResolver.cs
  • Src/Ruby/Runtime/Calls/SuperCallAction.cs
  • Src/Ruby/Runtime/Conversions/Converter.cs
  • Src/Ruby/Runtime/RubyContext.cs
  • Src/Ruby/Runtime/RubyOps.cs
  • Src/Ruby/Runtime/RubyScope.cs
  • Src/Ruby/Runtime/RubyStackTraceBuilder.cs
  • Src/Ruby/Runtime/RubyUtils.cs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

… Object

Three things that did not work when calling .NET from Ruby:

- A Ruby class derived from a CLR class could not pass arguments to the
  base class's constructor: super in initialize reached Object#initialize
  ("wrong number of arguments (given 1, expected 0)"), and a base class
  without a parameterless constructor could not be allocated at all
  ("define Doctor#new singleton method instead of Doctor#initialize").
  super in initialize now runs the matching CLR base constructor on the new
  instance, as base(...) does in a C# constructor - with keywords, splats,
  protected constructors of abstract classes, through several Ruby levels.
  A base class with a parameterless constructor is still constructed with
  it on allocation (so an initialize without super works as before; super()
  then does nothing more). Without one, new allocates the instance
  unconstructed - its Ruby class set, so virtual calls from the base
  constructor reach Ruby overrides - and raises if initialize never calls
  super, which C# would not have compiled.
- CLR const and static readonly fields are constants of their class:
  System::Math::PI, String::Empty, an enum's values, as Java's static final
  fields are in JRuby. Properties and other static members stay methods -
  a constant is cached where it is used, which DateTime.Now must not be -
  and naming one as a constant (Task::Factory) says how to call it
  (Task.Factory). Builtin classes such as Integer keep MRI's constants.
  `::` on a type group (System::Nullable::GetUnderlyingType) qualifies as
  its non-generic member, as a type group does where a module is expected.
- A Ruby String passed for a CLR method's Object parameter arrives as a
  System.String instead of a MutableString, which CLR code that looks at
  what it gets did not understand: ADO.NET's AddWithValue raised "No
  mapping exists from object type MutableString", System.Text.Json
  serialized its internals. JRuby passes a java.lang.String likewise. Ruby
  library methods are unaffected. A string stored through an Object
  parameter (ArrayList#Add) comes back as a System::String, which compares,
  hashes and matches in case/when like the Ruby string it was and answers
  Ruby String methods; only String === and #inspect's quotes tell them
  apart.

ClrConstructor3 expected the old allocation error; it now gets the new one,
after the module's initialize has run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Largo and others added 2 commits October 27, 2026 14:14
A Ruby subclass of Proc (or Array, Hash, String) whose initialize calls
super reached the new CLR-constructor path, because those builtins are CLR
types too, and Proc's constructors do not take a block's arguments:
spec/core/proc/new_spec "called on a subclass of Proc" raised ArgumentError.
super into a CLR constructor, and allocating unconstructed, are now only for
plain CLR classes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Largo added 2 commits October 27, 2026 19:08
CLR interop gaps: super into CLR constructors, CLR constants, strings for Object parameters
# Conflicts:
#	Build/dlr-patches/README.md
@Largo
Largo merged commit 91518b1 into master Oct 27, 2026
7 checks passed
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.

1 participant