From f4bef07d9e8af9f0ddcfb198821c06a6abdcd9ed Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:25:30 +0000 Subject: [PATCH 001/439] Let class variables, defined? of a constant and {expr}::C into light frames The census of master had three constructs that kept methods out of light frames although they only look things up lexically: a class variable (90 methods of Src/StdLib + AWFY), `defined?` of a constant (89) and a constant qualified by an expression, `self.class::FOO` (80). Their helpers - RubyOps.GetClassVariable, TryGetClassVariable, IsDefinedClassVariable, SetClassVariable, IsDefined{Unqualified,Qualified, Global}Constant, GetExpressionQualifiedConstant and IsDefinedExpressionQualifiedConstant - read only the runtime, the global scope and the lexical chain from the scope. RubyScope.GetInnerMostModule and TryResolveConstantNoLock walk Module up the parents; a method scope's Module is null and it is no instance_eval scope, so the walk from it is the walk from its parent, the declaring scope, which the light frame already hands the plain constant reads (and which the scope made on demand has as its parent). A block scope has no module either, so a light block's `scope ?? parent` stands in the same way. IsScopeFree now lets in, under IR_LIGHT_LEXICAL (on unless =0): @@x, defined?(@@x), @@x = v and its op-assigns (operator ones under IR_LIGHT_CALLS, as for @x), and defined? or a read of a constant whose innermost qualifier is a constant or a scope-free expression; ScopeOperandIndex hands the five helpers not yet listed the declaring scope. `x::A = v` stays out. With the switch off, IR_LIGHT_FRAMES=why names it. Census (Src/StdLib + AWFY, 28,376 methods): light frames 26,019 -> 26,293 (91.7% -> 92.7%), 274 moved up, none down; JIT verdicts unchanged. ab.rb -r 4 against the switch off (no perf counters here, so time): @@cv 118 -> 81 ns, defined?(C) 80 -> 40, self.class::C 71 -> 42; a plain constant read 36.0 -> 35.7. Util/lexical-light-matrix.rb prints CRuby 4.0's output on the unchanged build, and on this one by default, with IR_LIGHT_LEXICAL=0, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. jit-matrix, jit-calls-matrix, block-given-matrix and light-rest-matrix agree with the baseline and CRuby. Method_LightFrameLexical1 is new; it and 45 named class-variable, constant and light-frame tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 44 +++ .../Ast/Definitions/MethodDefinition.cs | 58 ++++ Util/bench/prelude-cost.rb | 18 + Util/lexical-light-matrix.rb | 316 ++++++++++++++++++ 5 files changed, 437 insertions(+) create mode 100644 Util/lexical-light-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fe0f92281..8694154d2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1137,6 +1137,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGuard1, Method_LightFrameBlockGiven1, Method_LightFrameRest1, + Method_LightFrameLexical1, Method_ParkedScope1, Method_ParkedScopeLeak1, Method_LightFrameBlockPass1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 19e10dfbc..9064b38c5 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7709,6 +7709,50 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters "); } + /// + /// IR_LIGHT_LEXICAL: class variables, defined? of a constant and {expr}::C in a light frame are looked up from the + /// declaring scope, which is where a method scope's lexical chain starts (Util/lexical-light-matrix.rb). + /// + public void Method_LightFrameLexical1() { + TestOutput(@" +require 'ruby4' +class A + @@x = 1 + C = 2 + def r; @@x; end + def w(v); @@x = v; end + def oa; @@y ||= 3; end + def d; [defined?(@@x), defined?(@@no), defined?(C), defined?(Nope), defined?(A::C), defined?(self.class::C)]; end + def q(m); m::C; end + def s; self.class::C; end + class << self; def sr; @@x; end; end +end +class B < A; C = 4; def br; @@x; end; end +def top; @@x; end +a = A.new +p a.r, a.w(5), a.r, B.new.br, A.sr, a.oa, a.d, B.new.d +p 40.times.map { |i| [A, B][i % 2].new.s }.uniq, a.q(B) +begin; a.q(1); rescue TypeError => e; p e.message; end +begin; top; rescue RuntimeError => e; p e.message; end +A.class_eval { def e; @@x; end } +begin; a.e; rescue RuntimeError => e; p e.message; end +", @" +1 +5 +5 +5 +5 +3 +[""class variable"", nil, ""constant"", nil, ""constant"", ""constant""] +[""class variable"", nil, ""constant"", nil, ""constant"", ""constant""] +[2, 4] +4 +""1 is not a class/module"" +""class variable access from toplevel"" +""class variable access from toplevel"" +"); + } + /// /// BigDecimal against CRuby 4.0's bigdecimal 4.0.1: a Rational operand of a comparison is expanded as /// for arithmetic (== used to recurse through Rational#== until the stack overflowed), #power and #** diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 3b5b47761..af02e278b 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -583,6 +583,13 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// internal static readonly bool LightRescueEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_RESCUE") != "0"; + /// + /// IR_LIGHT_LEXICAL=0 keeps every method with a class variable (`@@x', `@@x = v', `defined?(@@x)'), a `defined?' of a + /// constant (`defined?(A)', `defined?(A::B)', `defined?(x::A)') or a constant qualified by an expression + /// (`self.class::A') out of light frames (see IsScopeFree and LightFrameRewriter.ScopeOperandIndex). + /// + internal static readonly bool LightLexicalEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_LEXICAL") != "0"; + // The built-in methods that store the caller's $~ when given a Regexp, and so take the caller's scope: a light frame // that calls one makes its scope on the call (RubyOps.LightScopeRequired) and calls again, which costs more than the // scope made at entry (gap 16 of Util/perf/LEDGER.md). A name only says which method is likely, not which is called, @@ -1050,6 +1057,36 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong if (isDefined != null && isDefined.Expression is InstanceVariable) { return true; } + // `@@x', `@@x = v', `defined?(@@x)', `defined?(A)', `defined?(A::B)', `defined?(x::A)', `x::A' (IR_LIGHT_LEXICAL): + // their helpers (RubyOps.GetClassVariable, IsDefinedClassVariable, IsDefinedUnqualifiedConstant, + // GetExpressionQualifiedConstant...) read the runtime, the global scope and the lexical chain from the scope. A method + // scope has no module (Module is null) and is no instance_eval scope, so the walks of RubyScope.GetInnerMostModule + // and TryResolveConstantNoLock pass over it to its parent, the declaring scope, which the rewriter hands them + // (LightFrameRewriter.ScopeOperandIndex). `defined?(x::A)' evaluates x in a try that answers nil for any exception. + if (LightLexicalEnabled) { + if (node is ClassVariable || isDefined != null && isDefined.Expression is ClassVariable) { + return true; + } + var lexicalConstant = (isDefined != null) ? isDefined.Expression as ConstantVariable : node as ConstantVariable; + if (lexicalConstant != null) { + return IsScopeFreeQualifier(lexicalConstant, blockLiterals, why); + } + var lexicalAssignment = node as SimpleAssignmentExpression; + if (lexicalAssignment != null && lexicalAssignment.Left is ClassVariable) { + // `@@x += 1' is a call of + between a read and a write + return IsScopeFree(lexicalAssignment.Right, blockLiterals, why) && + (lexicalAssignment.Operation == null || LightCallsEnabled || Refuse(why, "operator assignment (IR_LIGHT_CALLS=0)")); + } + } else if (why != null) { + var lexicalAssignment = node as SimpleAssignmentExpression; + var lexical = (isDefined != null) ? isDefined.Expression : + (lexicalAssignment != null && lexicalAssignment.Left is ClassVariable) ? lexicalAssignment.Left : node; + if (lexical is ClassVariable || lexical is ConstantVariable && (isDefined != null || !IsCachedConstant((ConstantVariable)lexical))) { + return Refuse(why, (isDefined != null ? "IsDefinedExpression of " : lexical != node ? "assignment to " : "") + + lexical.GetType().Name + (isDefined == null && lexical is ConstantVariable ? " with an expression qualifier" : "") + + " (IR_LIGHT_LEXICAL=0)"); + } + } var constant = node as ConstantVariable; if (constant != null) { return IsCachedConstant(constant) || Refuse(why, "ConstantVariable with an expression qualifier"); @@ -1383,6 +1420,15 @@ private static bool IsCachedConstant(ConstantVariable/*!*/ constant) { return qualifier == null || (qualifier is ConstantVariable && IsCachedConstant((ConstantVariable)qualifier)); } + // IR_LIGHT_LEXICAL: A, ::A, A::B::C, or {expr}::A::B whose expr is scope-free (see IsScopeFree) + private static bool IsScopeFreeQualifier(ConstantVariable/*!*/ constant, bool blockLiterals, StrongBox why) { + var qualifier = constant.Qualifier; + while (qualifier is ConstantVariable) { + qualifier = ((ConstantVariable)qualifier).Qualifier; + } + return qualifier == null || IsScopeFree(qualifier, blockLiterals, why); + } + private static bool AreScopeFree(Statements statements, bool blockLiterals, StrongBox why) { if (statements != null) { foreach (var statement in statements) { @@ -1564,6 +1610,18 @@ private static int ScopeOperandIndex(MethodInfo/*!*/ method) { if (method == Methods.SetInstanceVariable) { return 2; } + // class variables and constants qualified by an expression: the runtime, the global scope and the lexical chain + // (see IsScopeFree, IR_LIGHT_LEXICAL) + if (LightLexicalEnabled) { + if (method == Methods.GetClassVariable || method == Methods.TryGetClassVariable || + method == Methods.IsDefinedClassVariable) { + return 0; + } + if (method == Methods.SetClassVariable || method == Methods.GetExpressionQualifiedConstant || + method == Methods.IsDefinedExpressionQualifiedConstant) { + return 1; + } + } if (LightHashEnabled && (method == Methods.MakeHash || method == Methods.MakeSymbolHash1 || method == Methods.MakeSymbolHash2 || method == Methods.MakeSymbolHash3)) { return 0; diff --git a/Util/bench/prelude-cost.rb b/Util/bench/prelude-cost.rb index 7ef869e50..51c537bcc 100644 --- a/Util/bench/prelude-cost.rb +++ b/Util/bench/prelude-cost.rb @@ -305,6 +305,17 @@ def n_optnil0; @a.n_optnil; end def n_none; @a.n_none; end end +# lexical lookups: a constant read (x_const, a light frame before IR_LIGHT_LEXICAL) against a class variable, +# a `defined?' of a constant and a constant qualified by an expression (each kept a scope before it) +class Lx + C = 1 + @@cv = 1 + def x_const; C; end + def x_cv; @@cv; end + def x_defc; defined?(C) ? 1 : 0; end + def x_qual; self.class::C; end +end + def cpu File.read("/proc/thread-self/schedstat").to_i / 1e9 rescue SystemCallError @@ -451,3 +462,10 @@ def t(name, n) t("n_splat0", N) { |n| i = 0; s = 0; while i < n; s += h.n_splat0; i += 1; end; s } t("n_opt0", N) { |n| i = 0; s = 0; while i < n; s += h.n_opt0; i += 1; end; s } t("n_optnil0", N) { |n| i = 0; s = 0; while i < n; s += h.n_optnil0; i += 1; end; s } + +# lexical lookups +lx = Lx.new +t("x_const", N) { |n| i = 0; s = 0; while i < n; s += lx.x_const; i += 1; end; s } +t("x_cv", N) { |n| i = 0; s = 0; while i < n; s += lx.x_cv; i += 1; end; s } +t("x_defc", N) { |n| i = 0; s = 0; while i < n; s += lx.x_defc; i += 1; end; s } +t("x_qual", N) { |n| i = 0; s = 0; while i < n; s += lx.x_qual; i += 1; end; s } diff --git a/Util/lexical-light-matrix.rb b/Util/lexical-light-matrix.rb new file mode 100644 index 000000000..1c8b03e19 --- /dev/null +++ b/Util/lexical-light-matrix.rb @@ -0,0 +1,316 @@ +# Differential matrix for the lexical lookups of a method that runs without a scope (a light frame, +# MethodDefinition.TransformLightFrame): class variables (`@@x', `@@x = v', `@@x ||= v', `defined?(@@x)'), +# `defined?' of a constant (`defined?(Foo)', `defined?(A::B)', `defined?(::A)', `defined?(expr::A)') and a +# constant qualified by an expression (`self.class::FOO', `obj::X'). Their helpers read the runtime and +# the lexical chain from the scope, and a method scope has no module of its own, so its chain starts at +# the declaring scope: with IR_LIGHT_LEXICAL on, the light frame hands them that scope. Run it under CRuby +# and under ./ir.sh with the shortcut on and off, and diff: +# +# ruby Util/lexical-light-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/lexical-light-matrix.rb > /tmp/on.txt 2>&1 +# IR_LIGHT_LEXICAL=0 ./ir.sh Util/lexical-light-matrix.rb > /tmp/off.txt 2>&1 +# IR_LIGHT_FRAMES=0 ./ir.sh Util/lexical-light-matrix.rb > /tmp/noframes.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt && diff /tmp/mri.txt /tmp/noframes.txt +# +# Every probe runs N times and reports each distinct answer once, in the order they first appear, so the +# interpreted body, the compiled one and a site whose rule or cache is already bound all meet the case: +# where the method is written (a class body, `class << self', module_eval with a String and with a +# block, a refinement, the top level, a module function), a class variable an ancestor overtakes, and +# constants and class variables defined, changed and removed after the site is bound. +# +# IR_LIGHT_FRAMES=why ./ir.sh Util/lexical-light-matrix.rb 2>&1 >/dev/null | grep -a '^\[light\]' +# +# says which of the methods below are light frames. + +N = 3000 + +def t(label) + print label.ljust(58), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def err + yield +rescue Exception => e + "#{e.class}: #{e.message[0, 70]}" +end + +# ---------------------------------------------------------------- 1. class variables in a class body + +class CvBase + @@x = 1 + @@counter = 0 + def read; @@x; end + def write(v); @@x = v; end + def or_assign; @@lazy ||= :made; end + def op_assign; @@counter += 1; end + def defined_x; defined?(@@x); end + def defined_missing; defined?(@@nope); end + def read_missing; @@nope; end + def read_in_block; [1, 2].map { |i| @@x + i }; end + def read_twice; [@@x, @@x]; end + def self.class_read; @@x; end + class << self + def singleton_read; @@x; end + def singleton_defined; defined?(@@x); end + end +end + +class CvSub < CvBase + def sub_read; @@x; end + def sub_write(v); @@x = v; end +end + +o = CvBase.new +s = CvSub.new +t('read') { o.read } +t('write then read') { |i| o.write(i % 3); o.read } +o.write(1) +t('||=') { o.or_assign } +t('+= (3000 times)') { |i| o.op_assign; i == N - 1 ? CvBase.class_variable_get(:@@counter) : nil } +t('defined?(@@x)') { o.defined_x } +t('defined?(@@nope)') { o.defined_missing } +t('read missing') { err { o.read_missing } } +t('read in a block') { o.read_in_block } +t('read twice') { o.read_twice } +t('def self.m') { CvBase.class_read } +t('class << self') { CvBase.singleton_read } +t('class << self, defined?') { CvBase.singleton_defined } +t('subclass reads the base\'s') { s.sub_read } +t('subclass writes the base\'s') { |i| s.sub_write(i % 2 + 10); [o.read, CvSub.class_variables.sort] } +o.write(1) + +# defined, changed and removed after the site is bound +class CvLate + def late; @@late; end + def late_defined; defined?(@@late); end +end +cl = CvLate.new +# (Not removed after it was read: CRuby 4.0.10 then reads a dangling inline cache and crashes.) +t('defined later, changed') do |i| + CvLate.class_variable_set(:@@late, :here) if i == 1000 + CvLate.class_variable_set(:@@late, :again) if i == 2000 + [err { cl.late }, cl.late_defined] +end + +# a class variable an ancestor takes over (MRI: "is overtaken by") +class CvOverBase; end +class CvOver < CvOverBase + @@ov = :sub + def ov; @@ov; end + def ov_defined; defined?(@@ov); end +end +co = CvOver.new +t('overtaken by an ancestor later') do |i| + CvOverBase.class_variable_set(:@@ov, :base) if i == 1500 + err { co.ov } +end +# Not probed, because the unchanged build differs from CRuby 4.0 there already: `defined?(@@ov)' once an +# ancestor has overtaken @@ov (CRuby: "class variable"; IronRuby raises the RuntimeError), and `@@r' in a +# method of a `refine' block (CRuby: the module around the refine; IronRuby: the refinement). + +# a module's class variable through an including class +module CvMod + @@m = :mod + def m_read; @@m; end + def m_write(v); @@m = v; end + module_function def m_function; @@m; end +end +class CvIncl; include CvMod; end +t('module method via an includer') { CvIncl.new.m_read } +t('module function') { [CvMod.m_function, CvMod.send(:m_function)] } +t('module method via bind_call') { CvMod.instance_method(:m_read).bind_call(Object.new) } +t('module method writes') { |i| CvIncl.new.m_write(i % 2); CvMod.class_variable_get(:@@m) } + +# ---------------------------------------------------------------- 2. where the method is written + +class CvEval; @@e = :eval_class; end +CvEval.module_eval "def eval_string; @@e; end" +CvEval.module_eval { def eval_block; @@e; end } +CvEval.class_eval "class << self; def eval_singleton; @@e; end; end" +CvEval.send(:define_method, :dm) { @@e } rescue nil +ce = CvEval.new +t('module_eval with a String') { err { ce.eval_string } } +t('module_eval with a block') { err { ce.eval_block } } +t('class << self in a String') { err { CvEval.eval_singleton } } +t('define_method with a block') { err { ce.dm } } + +def toplevel_cv; @@top; end +def toplevel_cv_defined; defined?(@@top); end +t('toplevel def') { err { toplevel_cv } } +t('toplevel def, defined?') { err { toplevel_cv_defined } } + +obj = Object.new +obj.instance_eval "def ie_cv; defined?(@@x); end" +t('instance_eval String def') { err { obj.ie_cv } } + + +class CvDeep + @@d = :outer + class Inner + def inner_read; @@d; end + end + module Mixin + def mixin_read; defined?(@@d); end + end +end +t('nested class does not see the outer\'s') { err { CvDeep::Inner.new.inner_read } } +t('nested module, defined?') { err { Object.new.extend(CvDeep::Mixin).mixin_read } } + +# ---------------------------------------------------------------- 3. defined? of a constant + +class DcBase; INHERITED = 1; end + +module DcOuter + LEX = 1 + PRIV = 2 + private_constant :PRIV + module Deep; D = 1; end + class Probe < DcBase + def lexical; defined?(LEX); end + def private_lexical; defined?(PRIV); end + def private_qualified; defined?(DcOuter::PRIV); end + def missing; defined?(NoSuchThing); end + def global; defined?(::String); end + def global_missing; defined?(::NoSuchThing); end + def qualified; defined?(DcOuter::Deep::D); end + def qualified_missing; defined?(DcOuter::Nope::D); end + def inherited_c; defined?(INHERITED); end + def late; defined?(DcLate); end + def late_qualified; defined?(DcOuter::Late2); end + def class_expr; defined?(self.class::OWN); end + def obj_expr(x); defined?(x::D); end + def expr_chain(x); defined?(x::Deep::D); end + def raising_expr; defined?(boom::D); end + def boom; raise "boom"; end + def in_condition; defined?(LEX) ? :yes : :no; end + def unless_guard; return :none unless defined?(DcLate); :some; end + class << self + def s_lexical; defined?(LEX); end + end + end +end +class DcSub < DcOuter::Probe; OWN = 3; end + +pr = DcOuter::Probe.new +t('defined?(LEX)') { pr.lexical } +t('defined?(PRIV) lexically') { pr.private_lexical } +t('defined?(Mod::PRIV)') { pr.private_qualified } +t('defined?(NoSuchThing)') { pr.missing } +t('defined?(::String)') { pr.global } +t('defined?(::NoSuchThing)') { pr.global_missing } +t('defined?(A::B::C)') { pr.qualified } +t('defined?(A::Nope::C)') { pr.qualified_missing } +t('defined?(inherited)') { pr.inherited_c } +t('defined?(self.class::OWN)') { |i| i.even? ? pr.class_expr : DcSub.new.class_expr } +t('defined?(x::D)') { |i| pr.obj_expr([DcOuter::Deep, DcOuter, 1, nil][i % 4]) } +t('defined?(x::Deep::D)') { |i| pr.expr_chain([DcOuter, DcOuter::Deep, 1][i % 3]) } +t('defined?(raising::D)') { err { pr.raising_expr } } +t('defined? as a condition') { pr.in_condition } +t('class << self, defined?(LEX)') { DcOuter::Probe.s_lexical } +t('defined later, removed') do |i| + Object.const_set(:DcLate, 1) if i == 1000 + Object.send(:remove_const, :DcLate) if i == 2000 + DcOuter.const_set(:Late2, 1) if i == 1200 + DcOuter.send(:remove_const, :Late2) if i == 2200 + [pr.late, pr.late_qualified, pr.unless_guard] +end +class DcMissing + def self.const_missing(n); :"missing_#{n}"; end + def probe; defined?(Whatever); end +end +t('const_missing is not called') { DcMissing.new.probe } + +DcOuter.module_eval "def self.dc_string; defined?(LEX); end" +DcOuter.module_eval { def self.dc_block; defined?(LEX); end } +t('module_eval String, defined?(LEX)') { DcOuter.dc_string } +t('module_eval block, defined?(LEX)') { DcOuter.dc_block } +def toplevel_defined_c; defined?(LEX); end +t('toplevel def, defined?(LEX)') { toplevel_defined_c } + +# ---------------------------------------------------------------- 4. {expr}::C + +class EqBase + FOO = :base + def own_foo; self.class::FOO; end + def via(x); x::FOO; end + def chain(x); x::Inner::V; end + def missing(x); x::NOPE; end +end +class EqSub < EqBase; FOO = :sub; end +class EqOther < EqBase; end +module EqHolder + FOO = :holder + module Inner; V = :v; end + SECRET = 1 + private_constant :SECRET + def self.const_missing(n); :"cm_#{n}"; end +end +class EqProbe + def secret(x); x::SECRET; end +end + +t('self.class::FOO') { |i| [EqBase, EqSub, EqOther][i % 3].new.own_foo } +t('x::FOO, many modules') { |i| EqBase.new.via([EqBase, EqSub, EqHolder, EqOther][i % 4]) } +t('x::FOO, not a module') { |i| err { EqBase.new.via([1, nil, "s"][i % 3]) } } +t('x::Inner::V') { |i| err { EqBase.new.chain([EqHolder, EqBase][i % 2]) } } +t('x::NOPE, const_missing') { |i| err { EqBase.new.missing([EqHolder, EqBase][i % 2]) } } +t('x::SECRET, private') { err { EqProbe.new.secret(EqHolder) } } +t('changed after bound') do |i| + if i == 1000 + EqSub.send(:remove_const, :FOO) + elsif i == 2000 + EqSub.const_set(:FOO, :again) + end + EqSub.new.own_foo +end + +# ---------------------------------------------------------------- 5. what the frame still does afterwards + +class After + @@a = 1 + A = 2 + def then_binding; x = @@a; [x, binding.local_variable_get(:x)]; end + def then_locals; x = self.class::A; [x, local_variables]; end + def then_raise; raise ArgumentError, "a=#{@@a} #{defined?(A)}"; end + def then_caller; [@@a, caller(0, 1)[0][/in .*/]]; end + def then_method; [defined?(A), __method__]; end + def recursive(n); n == 0 ? [@@a, self.class::A] : recursive(n - 1); end +end +af = After.new +t('then binding') { af.then_binding } +t('then local_variables') { af.then_locals } +t('then raise') { err { af.then_raise } } +t('then caller') { af.then_caller } +t('then __method__') { af.then_method } +t('recursion') { af.recursive(5) } + +calls = [] +tp = TracePoint.new(:call) { |tp| calls << tp.method_id if tp.defined_class == CvBase } +t('TracePoint :call') do |i| + tp.enable if i == 1000 + r = [o.read, o.defined_x] + tp.disable if i == 2000 + r +end +puts "traced #{calls.size} calls of #{calls.uniq.sort.inspect}" + +# ---------------------------------------------------------------- 6. a refinement (last: every method defined after +# `using' keeps its scope, so nothing above may follow it) + +module CvRefine + refine String do + def cv_refined_defined; defined?(@@nowhere); end + end +end +using CvRefine +t('refinement body, defined? of a missing one') { "s".cv_refined_defined } From 44256650be46e2eb74970f9a5892fe7a7dbc4bf9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:25:30 +0000 Subject: [PATCH 002/439] Ledger: perf/lexical landed (census only, not gated) Gap 9 names IR_LIGHT_LEXICAL and its matrix; the Landed entry has the census, the ab.rb numbers, the modes the matrix was run in, and three things found on the way: defined?(@@x) raises once an ancestor overtook @@x, @@x in a refine block resolves to the refinement (both differ from CRuby on master too), and CRuby 4.0.10 crashes reading a class variable removed after its inline cache was warmed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..45be2decf 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -795,9 +795,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has nor a multiple assignment (`a, b = b, a`; `IR_LIGHT_MASGN=0`, see Landed, perf/masgn); nor a regex literal whose method leaves `$~` alone (`s.match?(/x/)`, `/a#{x}/`; `IR_LIGHT_REGEX=0`, see Landed, perf/lightre: one passed to `gsub`, `=~`, `split`, `when` and the like stays out); + nor a class variable, a `defined?` of a constant or a constant qualified by an expression + (`@@x`, `defined?(A::B)`, `self.class::C`; `IR_LIGHT_LEXICAL=0`, see Landed, perf/lexical); Util/block-given-matrix.rb, Util/light-rest-matrix.rb, Util/block-pass-matrix.rb, Util/splat-pass-matrix.rb, Util/interpolation-matrix.rb, Util/hash-literal-matrix.rb, - Util/masgn-matrix.rb and Util/regex-light-matrix.rb are their matrices. + Util/masgn-matrix.rb, Util/regex-light-matrix.rb and Util/lexical-light-matrix.rb are their + matrices. What the census names next (2026-11-19 after perf/hashlit, 28,335 methods, 6,542 of them not light). By its first table: keyword parameters 1,257 (37 of them the prelude's, none AWFY's), `rescue`/`ensure` 478, 185 candidates that still need their @@ -1384,6 +1387,46 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lexical (2026-11-26) - class variables, `defined?` of a constant and `{expr}::C` in + light frames (`IR_LIGHT_LEXICAL`, gap 9).** The census of master f81fc19 had three lines of + "not a light frame: the construct" that are lexical lookups: ClassVariable 90 methods, + `IsDefinedExpression of ConstantVariable` 89, `ConstantVariable with an expression qualifier` + 80. Their helpers (`RubyOps.GetClassVariable`, `TryGetClassVariable`, `IsDefinedClassVariable`, + `SetClassVariable`; `IsDefinedUnqualifiedConstant`, `IsDefinedQualifiedConstant`, + `IsDefinedGlobalConstant`, which `ScopeOperandIndex` already listed; `GetExpressionQualifiedConstant`, + `IsDefinedExpressionQualifiedConstant`) read the runtime, the global scope and the lexical chain + from the scope: `RubyScope.GetInnerMostModule` and `TryResolveConstantNoLock` walk `Module` up + the parents, and a method scope's `Module` is null and it is no instance_eval scope, so the walk + from it is the walk from its parent - the declaring scope the rewriter hands them (the scope + made on demand has the same parent). A block scope has no module either, so a light block's + `scope ?? parent` stands in the same way. `IsScopeFree` lets in, under the switch, `@@x`, + `defined?(@@x)`, `@@x = v` and its op-assigns (operator ones need `IR_LIGHT_CALLS` as for `@x`), + and `defined?`/a read of any constant whose innermost qualifier is a constant or a scope-free + expression; `ScopeOperandIndex` hands the five helpers not yet listed the declaring scope; with + the switch off `IR_LIGHT_FRAMES=why` names it. `x::A = v` stays out. Census (Src/StdLib + AWFY, + 28,376 methods): light frames 26,019 -> 26,293 (91.7% -> 92.7%), 274 methods moved up, none + down; JIT compiles / maybe / never unchanged (3,296 / 2,921 / 22,159). The prelude's + `SystemCallError.__coerce_errno__` is among them, no AWFY method (AWFY has none of the three). + `ab.rb -r 4` on new shapes of `prelude-cost.rb` against the switch off (no perf counters in + the container, so time, not `-i`; the machine was shared by four other experiments): `x_cv` + (`@@cv`) 118.2 -> 80.9 ns (0.68), `x_defc` (`defined?(C) ? 1 : 0`) 80.4 -> 40.0 (0.50), + `x_qual` (`self.class::C`) 70.6 -> 41.8 (0.59); `x_const` (a plain constant, light before) + 36.0 -> 35.7 (0.99 overlap). `Util/lexical-light-matrix.rb` (class bodies, `class << self`, + module_eval with a String and with a block, define_method, the top level, instance_eval, a + module function, bind_call, a nested class, an ancestor overtaking a class variable later, + constants and class variables defined and changed after the site is bound, private constants, + const_missing, a raising qualifier of `defined?`, binding, caller, TracePoint) prints CRuby + 4.0's output on the unchanged build and on the change by default, with `IR_LIGHT_LEXICAL=0`, + `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and R2R; jit-matrix, + jit-calls-matrix, block-given-matrix and light-rest-matrix agree with the baseline and CRuby; + census `-c` on a Richards trace 0 differ; IronRuby.Tests `Method_LightFrameLexical1` (new) + and 45 named class-variable, constant and light-frame tests pass. Found on the way, not + fixed (they differ on master too, so the matrix leaves them out): `defined?(@@x)` raises the + "overtaken" RuntimeError where CRuby answers "class variable"; `@@x` in a method of a `refine` + block resolves to the refinement, CRuby to the module around it. And CRuby 4.0.10 crashes + reading a class variable removed after its inline cache was warmed (a dangling cache), so the + matrix does not remove one. - census only, not gated + - **perf/first-bind (2026-11-26) - what a first bind costs, split; light-scope sites call library methods through a dispatcher for their first calls (gap 26).** The split (master 4bae83f3, R2R host with the startup library; `IR_BIND_TRACE`, `IR_PHASE_TIMES`, perf with jitdump classing From 59fb958a05cdcd8b691d6f25efac9a718a4f2158 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:42:46 +0000 Subject: [PATCH 003/439] JIT: leave out a statement guarded by a constant whose value makes it dead `trace(x) if TRACING` with TRACING false kept Richards' Scheduler#schedule, and any method with the `debug(x) if DEBUG` idiom, out of the method JIT: the screen refused the call in the dead arm, and the compiler bailed at it. The constant is already folded (JitCompiler.ResolveConstant) and looked up again at each entry when the constant version moves (gap 29). Now, for `if C ... [else ...] end` and `unless C ... [else ...] end` without an elsif, whose condition is a foldable constant, the compiler emits only the arm the constant's value leaves alive (TryEmitConstantGuarded), and the screen walks only that arm: JitStub.Wrap looks the constant up in the declaring scope as the compiler will. The census and the precompiled library, which have no values, take a guard of one arm for a switch that is off. A method body's loop runs on past the entry, so a body with a loop that left an arm out is made one that may deopt: its safe point then deopts when the constant is reassigned (MethodLoopSafePointSlow); an impure one is declined, as any loop in a body that can deopt with an effect. One that binds a callee with a loop is declined. Outlined loops hand themselves back on a reassignment already (RubyContext.ConstantReassigned). IR_JIT_DEADCONST=0 turns it off. Census (Src/StdLib + AWFY): 2 methods never -> maybe (schedule, RSS tag_end), none down; census -c on a Richards trace 0 differ, declined after the pre-screen 6 -> 6. schedule is called once per iteration and its `while` is still refused by the loop tier at `call: is_task_holding_or_waiting/0`, so Richards does not move. Util/bench/deadconst-shapes.rb, ab.rb -r 4 new/base: m_dead 0.84, m_dead2 0.85, mloop_dead 0.25, loop_dead 0.08, controls ~1.0 (overlap). Util/deadconst-matrix.rb (new, 22 rows, including another thread reassigning the constant while compiled loops run) prints CRuby's output on the unchanged build and on this one with the JIT on, off, without JIT calls and with the switch off; jit, jit-calls, block-loop, osr-array, jit-const and inline matrices unchanged in all four modes. Census only, not gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5NtGd2eCVJ7fCeWbG --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 100 +++++++++- Src/Ruby/Runtime/Jit/JitRuntime.cs | 7 + Src/Ruby/Runtime/Jit/JitStub.cs | 18 +- Util/bench/deadconst-shapes.rb | 88 +++++++++ Util/deadconst-matrix.rb | 278 ++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 65 ++++++- 6 files changed, 551 insertions(+), 5 deletions(-) create mode 100644 Util/bench/deadconst-shapes.rb create mode 100644 Util/deadconst-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 6b8ce93ec..2c4516498 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -622,6 +622,16 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ return null; } + // An arm left out under a constant is left out for as long as the entry finds the constant unchanged. A + // loop runs on past the entry: one of the body's own has to deopt at its safe point when the constant is + // reassigned (MethodLoopSafePointSlow, which a body that may not deopt goes on from with what it was + // compiled with), so the body is one that can, which only a pure body may be (below). A callee's loop + // deopts by the callee's own rule, which is not this body's, so a body that calls one stays generic. + if (c._droppedArm) { + if (c._calleeLoop) { return Declined("a statement left out under a constant, and a callee with a loop"); } + if (c._hasLoop) { c._canDeopt = true; } + } + // Writes held back that the body cannot keep (JitCompiler.Sink.cs): compile it storing them where they are. if (c._sunk != null && c._sinkObstacle != null) { // an Integer variable written in both representations: another round holding it as a long @@ -1551,6 +1561,8 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { // arms together, so _deoptAfterEffect sees each path as it runs, not one arm's write as // coming before the other arm's deopt. private MSA.Expression/*!*/ EmitIf(IfExpression/*!*/ node, out JT type) { + MSA.Expression guarded; + if (TryEmitConstantGuarded(node, out guarded, out type)) { return guarded; } var clauses = node.ElseIfClauses; int n = (clauses != null) ? clauses.Count : 0; bool hasElse = n > 0 && clauses[n - 1].Condition == null; @@ -1587,6 +1599,8 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { } private MSA.Expression/*!*/ EmitUnless(UnlessExpression/*!*/ node, out JT type) { + MSA.Expression guarded; + if (TryEmitConstantGuarded(node, out guarded, out type)) { return guarded; } var test = Ast.Not(EmitCondition(node.Condition)); bool pureAfterTest = _pure; JT thenType; @@ -1609,6 +1623,64 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return Join(test, thenExpr, thenType, elseExpr, elseType, out type); } + /// + /// `x if C', `x unless C', `if C then x else y end' (IR_JIT_DEADCONST): the arm the constant's value makes dead + /// is not emitted at all, and neither is the test. The constant is folded as any other read of it is + /// (ResolveConstant), so the entry finds out that it changed (JitStub.RevalidateConstants) and the arm runs + /// again from the next call; an outlined loop hands itself back at its next safe point when it is reassigned + /// (RubyContext.ConstantReassigned), and a method body with a loop is made to deopt there (TryCompile: + /// _droppedArm). False when the node is not such a guard, or the value is one a non-main Ractor may not + /// read, which EmitConstant checks where it is read. + /// + private bool TryEmitConstantGuarded(RExpr/*!*/ node, out MSA.Expression result, out JT type) { + result = null; + type = JT.None; + ConstantVariable guard; + Statements whenTrue, whenFalse; + if (!JitRuntime.DeadConstants || !ConstantGuard(node, out guard, out whenTrue, out whenFalse)) { return false; } + object value = ResolveConstant(guard); + if (!RactorIsolation.IsTriviallyShareable(value)) { return false; } + _droppedArm = true; + var live = RubyOps.IsTrue(value) ? whenTrue : whenFalse; + if (live == null || live.Count == 0) { + type = JT.Obj; + result = Ast.Constant(null, typeof(object)); + } else { + result = EmitRegion(live, out type); + } + return true; + } + + // An arm was left out under a constant (TryEmitConstantGuarded). + private bool _droppedArm; + + /// + /// `if C ... [else ...] end' or `unless C ... [else ...] end', without an elsif, whose condition is a constant the + /// compiler folds (`C', `::C', `A::B'): is what runs when the constant is truthy and + /// what runs when it is not (either may be null: nothing). The screen (JitScreen) + /// and the compiler ask it of the same nodes. + /// + internal static bool ConstantGuard(RExpr/*!*/ node, out ConstantVariable guard, out Statements whenTrue, out Statements whenFalse) { + guard = null; + whenTrue = whenFalse = null; + var ifExpr = node as IfExpression; + if (ifExpr != null) { + var clauses = ifExpr.ElseIfClauses; + if (clauses != null && clauses.Count > 0 && (clauses.Count != 1 || clauses[0].Condition != null)) { return false; } + guard = ifExpr.Condition as ConstantVariable; + whenTrue = ifExpr.Body; + whenFalse = (clauses != null && clauses.Count == 1) ? clauses[0].Statements : null; + } else { + var unless = node as UnlessExpression; + if (unless == null) { return false; } + if (unless.ElseClause != null && unless.ElseClause.Condition != null) { return false; } + guard = unless.Condition as ConstantVariable; + whenTrue = (unless.ElseClause != null) ? unless.ElseClause.Statements : null; + whenFalse = unless.Statements; + } + return guard != null && JitScreen.IsFoldableConstant(guard); + } + /// /// `while c; body; end' / `until c; body; end'. A `break' jumps to the exit and a `next' to the test /// (EmitBreak); a `redo' makes Emit bail. The value is nil, or what a `break v' stored in the loop's result. @@ -3077,6 +3149,9 @@ private JitScreen(MethodDeclaration/*!*/ ast, JitKeywords keywords) { // when screening a callee, which may call nothing itself. private Func _isLeafCallee; + // What a constant guarding a statement is now (CanEverCompile's constantTruth); null: not known. + private Func _constantTruth; + /// /// False when no assignment of parameter types could ever make TryCompile succeed for /// this body. names the node kind that decided it. @@ -3089,11 +3164,15 @@ internal static bool CanEverCompile(MethodDeclaration/*!*/ ast, out string rejec /// /// : the locals the body reads other than as the value of an /// instance variable or element assignment, or assigns. + /// : what a constant guarding a statement is now (JitCompiler.ConstantGuard): true + /// or false, or null if it could not be folded; null when the values are not known (the census, the precompiled + /// library), in which case a guard of one arm is taken for a switch that is off. /// internal static bool CanEverCompile(MethodDeclaration/*!*/ ast, JitKeywords keywords, Func isLeafCallee, - out string rejectedBy, out HashSet otherUses) { + out string rejectedBy, out HashSet otherUses, Func constantTruth = null) { var s = new JitScreen(ast, keywords); s._isLeafCallee = isLeafCallee; + s._constantTruth = constantTruth; otherUses = s._otherUses; s._all = CollectAll; CollectAll = null; @@ -3288,6 +3367,20 @@ private bool Walk(RExpr/*!*/ node) { return WalkCondition(cond.Condition) && Walk(cond.TrueExpression) && Walk(cond.FalseExpression); } + // `x if C', `x unless C', `if C then x else y end' (JitCompiler.TryEmitConstantGuarded): only the arm the + // constant's value leaves alive is emitted. Not knowing the value, a guard of one arm is a switch that is + // off (`trace(x) if TRACING'), as it is where the census meets it; a guard of two arms has both walked. + ConstantVariable guard; + Statements whenTrue, whenFalse; + if (JitRuntime.DeadConstants && JitCompiler.ConstantGuard(node, out guard, out whenTrue, out whenFalse)) { + if (_constantTruth != null) { + bool? truth = _constantTruth(guard); + if (truth.HasValue) { return WalkStatements(truth.Value ? whenTrue : whenFalse); } + } else if (whenTrue == null || whenFalse == null) { + return true; + } + } + var ifExpr = node as IfExpression; if (ifExpr != null) { var clauses = ifExpr.ElseIfClauses; @@ -3461,6 +3554,11 @@ private bool WalkAssignment(SimpleAssignmentExpression/*!*/ assign) { // order puts before what is walked after it. private bool _effectWalked; + /// A constant JitCompiler.ResolveConstant may fold (WalkConstant). + internal static bool IsFoldableConstant(ConstantVariable/*!*/ node) { + return WalkConstant(node); + } + /// Mirrors JitCompiler.ResolveConstant: `C', `::C', and `A::B' qualified by constants. private static bool WalkConstant(ConstantVariable/*!*/ node) { for (RExpr q = node.Qualifier; q != null; q = ((ConstantVariable)q).Qualifier) { diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 08bbc6657..ff2b4cc60 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -39,6 +39,13 @@ public static partial class JitRuntime { /// IR_JIT_VERBOSE=1 traces what gets specialized and what is rejected. internal static readonly bool Verbose = Environment.GetEnvironmentVariable("IR_JIT_VERBOSE") == "1"; + /// + /// IR_JIT_DEADCONST (on unless =0): a statement guarded by a constant whose value makes it dead when the body is + /// compiled - `trace(x) if TRACING' with TRACING false - is left out of the typed body and of a loop's copy, under + /// the constant's revalidation (JitCompiler.TryEmitConstantGuarded), and the screen does not refuse the body for it. + /// + internal static readonly bool DeadConstants = Environment.GetEnvironmentVariable("IR_JIT_DEADCONST") != "0"; + /// /// Statistics, printed by -X:JITStats. /// diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index c83d7a13a..41ed4c822 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -1659,9 +1659,10 @@ internal static string ParameterShape(MethodDeclaration/*!*/ ast) { // The static part of Wrap's decision; rejectedBy is set when the screen (not the parameter list) refused the body. // isLeafCallee: the census's answer in place of the declaring module's (CensusScreen). + // constantTruth: what a constant guarding a statement is now (JitScreen.CanEverCompile); null where it is not known. private static bool Screen(MethodDeclaration/*!*/ ast, RubyContext/*!*/ context, RubyModule declaringModule, out JitKeywords keywords, out bool[] hasDefault, out object[] defaults, out bool perCount, out bool[] storedOnly, out int arity, out string rejectedBy, - Func isLeafCallee = null) { + Func isLeafCallee = null, Func constantTruth = null) { keywords = null; hasDefault = null; defaults = null; @@ -1723,7 +1724,7 @@ private static bool Screen(MethodDeclaration/*!*/ ast, RubyContext/*!*/ context, (isLeafCallee != null) ? isLeafCallee : (declaringModule != null) ? (name, onSelf) => IsLeafMethod(declaringModule, name, onSelf) || (onSelf && context.RubyOptions.JitCalls && IsCallableMethod(declaringModule, name, 0)) - : (Func)((name, onSelf) => true), out rejectedBy, out otherUses)) { + : (Func)((name, onSelf) => true), out rejectedBy, out otherUses, constantTruth)) { return false; } @@ -1898,7 +1899,18 @@ private JitCode Named(JitCode code, long epoch, int version, int constantVersion bool perCount; int arity; string rejectedBy; - if (!Screen(ast, context, declaringModule, out keywords, out hasDefault, out defaults, out perCount, out storedOnly, out arity, out rejectedBy)) { + // A constant guarding a statement is looked up where the compiler will fold it (JitCompiler.TryEmitConstantGuarded): + // a guard that leaves the statement dead now does not keep the method out. One that cannot be folded is + // walked as any condition; without the scope none can be. + Func constantTruth = guard => { + object value; + RubyModule owner; + if (declaringScope == null || JitFoldedConstant.Resolve(context, declaringScope, guard, out value, out owner) != null || + !RactorIsolation.IsTriviallyShareable(value)) { return null; } + return RubyOps.IsTrue(value); + }; + if (!Screen(ast, context, declaringModule, out keywords, out hasDefault, out defaults, out perCount, out storedOnly, out arity, out rejectedBy, + null, constantTruth)) { if (rejectedBy != null) { JitRuntime.RecordScreenRejection(rejectedBy); if (JitRuntime.Verbose) { diff --git a/Util/bench/deadconst-shapes.rb b/Util/bench/deadconst-shapes.rb new file mode 100644 index 000000000..e62fd69eb --- /dev/null +++ b/Util/bench/deadconst-shapes.rb @@ -0,0 +1,88 @@ +# Shapes for a statement guarded by a constant that is false (`trace(x) if TRACING', Richards' Scheduler#schedule; +# IR_JIT_DEADCONST, JitCompiler.TryEmitConstantGuarded), in the format Util/perf/ab.rb reads: ` ns +# ` per shape, shape names as arguments, N from the environment, INSTR=1 (ab.rb -i) for instructions per +# call. Each guarded shape has a control that is the same code without the guard: on a build that leaves the dead +# statement out the two should count the same. +# +# ruby Util/perf/ab.rb -i Util/bench/deadconst-shapes.rb \ +# "base=env IR_CONFIG=Release ./ir.sh" "new=env IR_CONFIG=Release ../wt-deadconst/ir.sh" +$stdout.sync = true + +TRACING = false +DEBUG_LEVEL = nil +module Conf; VERBOSE = false; end + +class Stepper + attr_reader :traced + def initialize; @traced = 0; @k = 3; end + def trace(x); @traced += 1; x; end + + # a hot method: a call on self guarded by a false constant, then the work + def step_dead(x) + trace(x) if TRACING + x + @k + end + + # the same with `unless', a nil constant and a qualified one + def step_dead2(x) + trace(x) if DEBUG_LEVEL + trace(x) if Conf::VERBOSE + x + @k + end + + # control: the work alone + def step_plain(x) + x + @k + end + + # a loop inside a method called hot, with the guard in the loop + def sum_dead(n) + i = 0 + s = 0 + while i < n + trace(i) if TRACING + s += i + i += 1 + end + s + end + + # control + def sum_plain(n) + i = 0 + s = 0 + while i < n + s += i + i += 1 + end + s + end +end + +def trace(x); x; end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end + +o = Stepper.new +N = (ENV["N"] || 1_000_000).to_i +t("m_dead", N) { |n| i = 0; s = 0; while i < n; s += o.step_dead(i); i += 1; end; s + o.traced } +t("m_dead2", N) { |n| i = 0; s = 0; while i < n; s += o.step_dead2(i); i += 1; end; s + o.traced } +t("m_plain", N) { |n| i = 0; s = 0; while i < n; s += o.step_plain(i); i += 1; end; s + o.traced } +# a method with a short loop, called hot: the method JIT's (per call: 8 iterations) +t("mloop_dead", N / 4) { |n| i = 0; s = 0; while i < n; s += o.sum_dead(8); i += 1; end; s + o.traced } +t("mloop_plain", N / 4) { |n| i = 0; s = 0; while i < n; s += o.sum_plain(8); i += 1; end; s + o.traced } +# a long loop run once: the loop tier's (OSR); its sum stays an Integer the loop's copy keeps as an int +t("loop_dead", N * 4) { |n| i = 0; s = 0; while i < n; trace(i) if TRACING; s += i & 7; i += 1; end; s } +t("loop_plain", N * 4) { |n| i = 0; s = 0; while i < n; s += i & 7; i += 1; end; s } diff --git a/Util/deadconst-matrix.rb b/Util/deadconst-matrix.rb new file mode 100644 index 000000000..7ea2ebc49 --- /dev/null +++ b/Util/deadconst-matrix.rb @@ -0,0 +1,278 @@ +# Differential matrix for a statement guarded by a constant (`trace(x) if TRACING', `log(x) unless QUIET'): the +# method JIT and the loop tiers fold the constant (JitCompiler.ResolveConstant), and with IR_JIT_DEADCONST (on unless +# =0) leave out the arm the constant's value makes dead, under the constant's revalidation (JitStub. +# RevalidateConstants at a method's entry, JitLoopGuard at a loop's safe point). Each row warms a method of its own +# past the JIT's thresholds with the guard dead, changes the constant - reassigned, removed, set to nil or 0, shadowed +# by a nearer one - and calls again; the threaded rows change it while a compiled loop runs, which must see it at its +# next iteration as CRuby's next read does. Run under CRuby and under ./ir.sh - with the JIT on, off, without +# JIT calls and with the switch off - and diff: +# +# ruby Util/deadconst-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/deadconst-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/deadconst-matrix.rb > /tmp/nojit.txt +# ./ir.sh -X:NoJITCalls Util/deadconst-matrix.rb > /tmp/nocalls.txt +# IR_JIT_DEADCONST=0 ./ir.sh Util/deadconst-matrix.rb > /tmp/off.txt +# for f in jit nojit nocalls off; do diff /tmp/mri.txt /tmp/$f.txt; done +# +# What the JIT did goes to stderr: IR_JIT_VERBOSE=1 IR_OSR_VERBOSE=1 ./ir.sh Util/deadconst-matrix.rb 2>&1 >/dev/null + +$stdout.sync = true + +WARM = 3000 + +# Reassigns a constant without CRuby's "already initialized constant" warning: the warning is given only when +# $VERBOSE is not nil. +def reassign(mod, name, value) + verbose, $VERBOSE = $VERBOSE, nil + mod.const_set(name, value) +ensure + $VERBOSE = verbose +end + +class Probe + attr_reader :notes + def initialize; @notes = []; end + def note(x); @notes << x; x; end +end + +def answer + yield +rescue NameError => e + [e.class, e.message] +end + +# warm with the guard dead, change, call, warm again, call again; print each call's answer and the notes taken +def around(label, o, change) + v = nil + WARM.times { |i| v = answer { yield o, i } } + out = [v, o.notes.size] + change.call + out << answer { yield o, 1 } << o.notes.size + WARM.times { |i| v = answer { yield o, i } } + out << v << o.notes.size + puts "#{label}: #{out.inspect}" +end + +# ---------------------------------------------------------------- 1. method bodies, between calls + +DF1 = false +class P1 < Probe; def m(x); note(x) if DF1; x + 1; end; end +around("1. if FALSE, reassigned true", P1.new, -> { reassign(Object, :DF1, true) }) { |o, i| o.m(i) } + +DF2 = false +class P2 < Probe; def m(x); note(x) if DF2; end; end +around("2. if FALSE as the value", P2.new, -> { reassign(Object, :DF2, true) }) { |o, i| o.m(i) } + +DT3 = true +class P3 < Probe; def m(x); note(x) unless DT3; x * 2; end; end +around("3. unless TRUE, reassigned false", P3.new, -> { reassign(Object, :DT3, false) }) { |o, i| o.m(i) } + +DF4 = false +class P4 < Probe + def m(x) + if DF4 + note(x) + :on + else + x + 2 + end + end +end +around("4. if/else, reassigned true", P4.new, -> { reassign(Object, :DF4, true) }) { |o, i| o.m(i) } + +DT5 = true +class P5 < Probe + def m(x) + if DT5 + x - 1 + else + note(x) + end + end +end +around("5. if TRUE with a dead else, reassigned false", P5.new, -> { reassign(Object, :DT5, false) }) { |o, i| o.m(i) } + +module Cfg6; DEBUG = false; end +class P6 < Probe; def m(x); note(x) if Cfg6::DEBUG; x + 6; end; end +around("6. qualified, reassigned true", P6.new, -> { reassign(Cfg6, :DEBUG, true) }) { |o, i| o.m(i) } + +NIL7 = nil +class P7 < Probe; def m(x); note(x) if NIL7; x + 7; end; end +around("7. nil, set to 0 (truthy)", P7.new, -> { reassign(Object, :NIL7, 0) }) { |o, i| o.m(i) } + +DF8 = false +class P8 < Probe; def m(x); note(x) if DF8; x + 8; end; end +around("8. removed", P8.new, -> { Object.send(:remove_const, :DF8) }) { |o, i| o.m(i) } + +DF9 = false +class P9 < Probe; def m(x); note(x) if DF9; x + 9; end; end +around("9. shadowed by a nearer constant", P9.new, -> { P9.const_set(:DF9, true) }) { |o, i| o.m(i) } + +DF10 = false +class P10Base < Probe; end +class P10 < P10Base; def m(x); note(x) if DF10; x + 10; end; end +around("10. shadowed through a superclass", P10.new, -> { P10Base.const_set(:DF10, :yes) }) { |o, i| o.m(i) } + +DF11 = false +class P11 < Probe; def m(x); note(x) if DF11; x + 11; end; end +around("11. set to an equal false again", P11.new, -> { reassign(Object, :DF11, false) }) { |o, i| o.m(i) } + +DF12 = false +class P12 < Probe; def m(x); y = (note(x) if DF12); y.inspect; end; end +around("12. the value assigned", P12.new, -> { reassign(Object, :DF12, 12) }) { |o, i| o.m(i) } + +DF13 = false +class P13 < Probe + def m(x); helper(x) + 1; end + def helper(x); note(x) if DF13; x; end +end +around("13. in a callee", P13.new, -> { reassign(Object, :DF13, true) }) { |o, i| o.m(i) } + +DF14 = false +class P14 < Probe + def m(n) + i = 0 + s = 0 + while i < n + note(i) if DF14 + s += i + i += 1 + end + s + end +end +around("14. in a method's while", P14.new, -> { reassign(Object, :DF14, true) }) { |o, i| o.m(i % 7) } + +DF15 = false +class P15 < Probe + def m(n) + s = 0 + n.times { |i| note(i) if DF15; s += i } + s + end +end +around("15. in a times block", P15.new, -> { reassign(Object, :DF15, true) }) { |o, i| o.m(i % 7) } + +DT16 = true +class P16 < Probe; def m(x); note(x) if DT16; x + 16; end; end +around("16. if TRUE (live), reassigned false", P16.new, -> { reassign(Object, :DT16, false) }) { |o, i| o.m(i) } + +# ---------------------------------------------------------------- 2. while a compiled loop runs + +# Another thread reassigns the constant while the loop spins; the loop must see it at an iteration after that, as +# CRuby's next read does. The bound is reached only by a loop that never sees it. LIMIT_I is an Integer the typed +# bodies, warmed with small ones, take as an int (a larger one goes to the generic body and the loop tier). +LIMIT = 3_000_000_000 +LIMIT_I = 2_000_000_000 + +DF20 = false +class P20 < Probe + def spin(n) + i = 0 + while i < n + return :seen if DF20 + i += 1 + end + :limit + end +end +o20 = P20.new +w20 = nil +WARM.times { w20 = o20.spin(5) } +t20 = Thread.new { sleep 0.1; reassign(Object, :DF20, true) } +r20 = o20.spin(LIMIT_I) +t20.join +puts "20. a method's while, reassigned by another thread: #{[w20, r20].inspect}" + +DF21 = false +i21 = 0 +t21 = Thread.new { sleep 0.1; reassign(Object, :DF21, true) } +r21 = :limit +while i21 < LIMIT + if DF21 + r21 = :seen + break + end + i21 += 1 +end +t21.join +puts "21. a top-level while, reassigned by another thread: #{r21.inspect}" + +DF22 = false +class P22 < Probe + def spin(n) + i = 0 + s = 0 + while i < n + note(i) if DF22 + break unless @notes.empty? + s += 1 + i += 1 + end + @notes.empty? ? :limit : :seen + end +end +o22 = P22.new +w22 = nil +WARM.times { w22 = o22.spin(5) } +t22 = Thread.new { sleep 0.1; reassign(Object, :DF22, true) } +r22 = o22.spin(LIMIT_I) +t22.join +puts "22. a dropped call in a method's while, reassigned by another thread: #{[w22, r22].inspect}" + +DF23 = false +class P23 < Probe + def spin(n) + s = 0 + n.times do |i| + break if DF23 + s += 1 + end + s < n ? :seen : :limit + end +end +o23 = P23.new +w23 = nil +WARM.times { w23 = o23.spin(5) } +t23 = Thread.new { sleep 0.1; reassign(Object, :DF23, true) } +r23 = o23.spin(LIMIT_I) +t23.join +puts "23. a times block, reassigned by another thread: #{[w23, r23].inspect}" + +DF24 = false +class P24 < Probe + def m(x); note(x) if DF24; x; end +end +o24 = P24.new +WARM.times { |i| o24.m(i) } +t24 = Thread.new { sleep 0.05; reassign(Object, :DF24, true) } +k24 = 0 +k24 += 1 while o24.notes.empty? && (o24.m(k24) || true) && k24 < 200_000_000 +t24.join +puts "24. a method called in a loop, reassigned by another thread: #{o24.notes.empty? ? :limit : :seen}" + +# A loop that has nothing else that may deopt (a Float counter does not overflow): the safe point must still see the +# reassignment, which a body that may not deopt goes on past (JitRuntime.MethodLoopSafePointSlow). The guarded +# statement is a call, which keeps the method from the typed body where nothing is left out under a constant. (With +# `return :seen if DF25' the unchanged build compiles it and answers :limit, as with the switch off: a folded +# constant in such a loop, Util/perf/LEDGER.md gap 29.) +DF25 = false +class P25 < Probe + def spin(n) + x = 0.0 + while x < n + return note(:seen) if DF25 + x += 1.0 + end + :limit + end +end +o25 = P25.new +w25 = nil +WARM.times { w25 = o25.spin(5.0) } +t25 = Thread.new { sleep 0.1; reassign(Object, :DF25, true) } +r25 = o25.spin(2.0e9) +t25.join +puts "25. a method's while that cannot deopt otherwise, reassigned by another thread: #{[w25, r25].inspect}" + +puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..c8a5f4fb2 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -604,7 +604,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (`trace(...) if TRACING`) dropped under the constant's version, for Richards' `schedule` (7.5% self, the largest generic body of the benchmark); behind it the loop tier still refuses `schedule`'s `while` for its calls on another receiver, so find - out first what compiles once the screen lets it through. And two that the rounds + out first what compiles once the screen lets it through. Done in perf/deadconst (see Landed): the + screen lets `schedule` through and nothing compiles - it is called once per iteration, so it is the loop + tier's, which still stops at `[osr] emitter: call: is_task_holding_or_waiting/0`; the next step for it + is calls on another receiver in an outlined loop. And two that the rounds above keep running into: held-back writes that reach through a bound callee (a caller whose only effects are its callee's writes to the same self: `read_required_char` -> `read_char` -> `read`, `set_nesting_level` -> `set_is_root`), and attribute writes @@ -1259,6 +1262,15 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the name cannot tell a constant that shadows the folded one from any other of that name. The next attempt keys on where the constant was found (the modules of the folded lookup's path), and is measured on a loop beside a thread that defines the same name elsewhere. + Another, found in round perf/deadconst (2026-11-26) and open on master: a typed method body + whose `while` folds a constant and has nothing else that may deopt goes on with the old value + after another thread reassigns it (`x = 0.0; while x < n; return :seen if DF; x += 1.0; end; + :limit`, warmed with DF false, then DF reassigned 0.1 s into `spin(2.0e9)`: CRuby `:seen`, + IronRuby `:limit`). Its safe point sees the move, but `MethodLoopSafePointSlow` deopts only a body + that may deopt (`JitLoopGuard.MayDeopt`), and this one has no deopt of its own (an Int counter's + overflow check gives most loops one). perf/deadconst makes such a body deopt where it left an arm + out; for a folded value in general the same (`_canDeopt` for a pure body with a loop that folded a + constant) is untried, and an impure body would have to be declined for it. 30. **`Binding#local_variable_get`, `_set`, `_defined?` and `local_variables` are an `eval` of source text each** (the prelude, `class Binding`): 436 us for a set against 0.1 on CRuby. `ERB#result_with_hash` sets one per key (237 times CRuby), irb sets `_` @@ -1384,6 +1396,57 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/deadconst (/perf-step, 2026-11-26, master f81fc19) - a statement guarded by a constant whose + value makes it dead is left out of the typed body and of a loop's copy (gap 1)** - census only, not gated. + `trace(x) if TRACING`, `log(x) unless QUIET`, `if C then a else b end` without an elsif, where C is a + constant the compiler folds (`C`, `::C`, `A::B`): `JitCompiler.TryEmitConstantGuarded` resolves it as + any folded read (`ResolveConstant`, so the entry's revalidation, gap 29, covers it) and emits only the + arm its value leaves alive, without the test. The screen asks the same question of the same nodes + (`JitCompiler.ConstantGuard`): `JitStub.Wrap` hands it the constant's value now, looked up in the + declaring scope as the compiler will (`JitFoldedConstant.Resolve`), and it walks only the live arm; the + census and the precompiled library, which have no values, take a guard of one arm for a switch that is + off. A loop runs on past the entry, so a method body with a loop (its own or an iterator's block) that + left something out is made one that may deopt (`_canDeopt`): its safe point then deopts when the constant + is reassigned (`MethodLoopSafePointSlow`), which only a pure body may (otherwise it is declined, as any + loop in a body that can deopt and has an effect); a body that binds a callee with a loop is declined. + An outlined loop needs nothing: a reassignment moves the code epoch (`RubyContext.ConstantReassigned`) + and its safe point hands it back. Switch: `IR_JIT_DEADCONST=0`. + Census (Src/StdLib + AWFY, 28,376 methods): never 22,159 -> 22,157, maybe 2,921 -> 2,923; 2 methods + moved up, none down - `Scheduler#schedule` (never at `MethodCall trace (self)` -> maybe at "constant + without a scope: NO_TASK", the census's usual stop) and RSS `ListenerMixin#tag_end` (`p ... if DEBUG`). + The census cannot see a constant's value, so it was judged by a run and by shapes. Richards traced + (3 x 10): the screen no longer rejects `schedule`, and nothing else changed - `schedule` is called once + per iteration and never reaches the method JIT's threshold, and its `while` is still refused by the + loop tier at its first call on another receiver: `[osr] emitter: call: is_task_holding_or_waiting/0`, + `richards.rb:260: not specializable` (behind it `@current_task.link` and `.run_task`; `trace` was never + the loop tier's first obstacle). `declined ... (passed the pre-screen)` 6 -> 6; `census -c`: 49 agree, + 0 differ, 16 specialized all compiles/maybe, 6 declined all maybe. No AWFY benchmark is expected to move. + `Util/bench/deadconst-shapes.rb` (new), `ab.rb -r 4` by time (this container has no instruction + counter: `-i` printed nothing), CRuby / base / new ns: `m_dead` (a call on self under a false + constant, then `x + @k`) 27.3 / 61.2 / 51.3 = 0.84; `m_dead2` (a nil and a qualified guard) 35.5 / 59.6 + / 50.4 = 0.85; `mloop_dead` (the guard in a method's `while`, 8 iterations a call) 223.6 / 240.0 / 60.3 = + 0.25; `loop_dead` (in a long loop, the loop tier's) 17.9 / 34.8 / 2.8 = 0.08; their controls without + the guard `m_plain` 1.02, `mloop_plain` 0.99, `loop_plain` 1.03, all overlap; each guarded shape is now + at its control. + Checked: `Util/deadconst-matrix.rb` (new, 22 rows): between calls the guard reassigned true or false, + `unless`, if/else both ways, qualified, nil set to 0, removed (NameError), shadowed lexically and through + a superclass, set to an equal false again, the `if`'s value assigned, in a bound callee, in a method's + `while`, in a `times` block, a live guard turned off; and another thread reassigning it while a compiled + loop runs: a method's `while` (Int and Float counters), a top-level `while` (OSR), a `times` block, a + method called in a loop. CRuby's output on the unchanged build, and on the new one with the JIT on, + `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and the switch off. With the loop rule taken out, the Float row + answers `:limit` (it is the row that tests it: an Int counter's overflow makes the body one that may + deopt anyway). jit, jit-calls, block-loop, osr-array, jit-const matrices and inline-matrix (one case per + process) print the same on base and new in all four modes, CRuby's but for inline-matrix's + `tree_int_key`, which differs on every IronRuby build (documented in the matrix). IronRuby.Tests Jit* + (16) pass. + For the gate: a method that folded a constant in a `while` and has nothing else that may deopt keeps the + constant's old value after another thread reassigns it, on master too (gap 29); this change fixes it + only where an arm is left out. The screen's lookup runs at each `def`'s first call, under the class + hierarchy lock, once per guard. Look hardest at the loop rule (`TryCompile`, `_droppedArm`) and at a + dropped arm after a call of a bound callee that runs generic code which reassigns the constant - the + same question every folded constant already raises, not timed or probed beyond row 13. + - **perf/first-bind (2026-11-26) - what a first bind costs, split; light-scope sites call library methods through a dispatcher for their first calls (gap 26).** The split (master 4bae83f3, R2R host with the startup library; `IR_BIND_TRACE`, `IR_PHASE_TIMES`, perf with jitdump classing From ede9d1c76af9da148cfff22c473d431c88540cb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:43:06 +0000 Subject: [PATCH 004/439] Util: a differential matrix and timing shapes for searching a String Util/string-search-matrix.rb prints #index, #rindex, #byteindex, #byterindex, #include?, #start_with?, #end_with?, Regexp#match?, #=~, #match and String#match? with what each leaves in $~, over ASCII, UTF-8, astral, BINARY, broken UTF-8, US-ASCII, EUC-JP and UTF-16LE receivers in each content kind (literal, built, sliced, force_encoded, indexed, subclass), needles of one and three characters, empty, broken, of another encoding, #to_str and Regexp, and offsets in and out of range. On master it differs from CRuby 4.0 in two places: a BINARY ASCII needle on a non-ASCII UTF-8 receiver (wrong offsets), and a Regexp search from an offset outside the string, which CRuby answers with nil before it checks the encodings. Util/bench/strsearch-shapes.rb has 120 shapes for ledger gap 21: the same searches on 10 KB receivers, found early, late or not at all, plus a short anchored match and three controls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Util/bench/strsearch-shapes.rb | 316 +++++++++++++++++++++++++++++++++ Util/string-search-matrix.rb | 126 +++++++++++++ 2 files changed, 442 insertions(+) create mode 100644 Util/bench/strsearch-shapes.rb create mode 100644 Util/string-search-matrix.rb diff --git a/Util/bench/strsearch-shapes.rb b/Util/bench/strsearch-shapes.rb new file mode 100644 index 000000000..2940fca1e --- /dev/null +++ b/Util/bench/strsearch-shapes.rb @@ -0,0 +1,316 @@ +# Searching a String (ledger gap 21): index, rindex, include?, start_with? and byteindex with a +# one- and a three-character needle, and Regexp#match?, =~ and #match, on 10 KB receivers that are +# ASCII (a), UTF-8 with non-ASCII characters (u) and BINARY with high bytes (b), the needle found +# early (e, byte 5), late (l, 30 bytes from the end) or not at all (n). ns per call of a method +# on H, the caller a `while` loop; the sum of the results is the checksum. +# +# ruby Util/perf/ab.rb -i Util/bench/strsearch-shapes.rb "base=env IR_CONFIG=Release ./ir.sh" \ +# "new=env IR_CONFIG=Release ../wt-strsearch/ir.sh" -- idx1_a_n idx1_u_n mp_u_n +# ruby Util/bench/strsearch-shapes.rb --list +# +# The methods were generated once from a table and are written out, one per shape (a method made by +# define_method costs more than what is measured). Controls: size, eq, short_idx. +$stdout.sync = true + +FILL_A = "abcdefghij" * 1000 +FILL_U = "abcdéfghîj" * 910 # 11 bytes, 10 characters +FILL_B = ("abcd\xE9fghij" * 1000).b +def place(fill, at, s) = (f = fill.dup; f[at, s.size] = s; f) +def lateat(fill) = fill.size - 30 +R = {} +%i[a u b].each do |k| + fill = { a: FILL_A, u: FILL_U, b: FILL_B }[k] + q = k == :b ? 'q"z'.b : 'q"z' + R[[k, :e]] = place(fill, 5, q) + R[[k, :l]] = place(fill, lateat(fill), q) + R[[k, :n]] = fill.dup +end +Q1 = '"' +Q3 = 'q"z' +Q1B = '"'.b +Q3B = 'q"z'.b +RE = /[<>"]/ +RE3 = /q"z/ +RE_INT = /\A[+-]?\d+/ +SHORT = "12345 rest" + +class H + def initialize + @ae = R[[:a, :e]] + @al = R[[:a, :l]] + @an = R[[:a, :n]] + @ue = R[[:u, :e]] + @ul = R[[:u, :l]] + @un = R[[:u, :n]] + @be = R[[:b, :e]] + @bl = R[[:b, :l]] + @bn = R[[:b, :n]] + @short = SHORT.dup + @other = FILL_A.dup + end + def idx1_a_e = (@ae.index(Q1) || -1) + def idx3_a_e = (@ae.index(Q3) || -1) + def inc1_a_e = (@ae.include?(Q1) ? 1 : 0) + def inc3_a_e = (@ae.include?(Q3) ? 1 : 0) + def bidx1_a_e = (@ae.byteindex(Q1) || -1) + def ridx1_a_e = (@ae.rindex(Q1) || -1) + def ridx3_a_e = (@ae.rindex(Q3) || -1) + def mp_a_e = (RE.match?(@ae) ? 1 : 0) + def tilde_a_e = (RE =~ @ae || -1) + def match_a_e = ((m = RE.match(@ae)) ? m.begin(0) : -1) + def mp3_a_e = (RE3.match?(@ae) ? 1 : 0) + def idxre_a_e = (@ae.index(RE) || -1) + def idx1_a_l = (@al.index(Q1) || -1) + def idx3_a_l = (@al.index(Q3) || -1) + def inc1_a_l = (@al.include?(Q1) ? 1 : 0) + def inc3_a_l = (@al.include?(Q3) ? 1 : 0) + def bidx1_a_l = (@al.byteindex(Q1) || -1) + def ridx1_a_l = (@al.rindex(Q1) || -1) + def ridx3_a_l = (@al.rindex(Q3) || -1) + def mp_a_l = (RE.match?(@al) ? 1 : 0) + def tilde_a_l = (RE =~ @al || -1) + def match_a_l = ((m = RE.match(@al)) ? m.begin(0) : -1) + def mp3_a_l = (RE3.match?(@al) ? 1 : 0) + def idxre_a_l = (@al.index(RE) || -1) + def idx1_a_n = (@an.index(Q1) || -1) + def idx3_a_n = (@an.index(Q3) || -1) + def inc1_a_n = (@an.include?(Q1) ? 1 : 0) + def inc3_a_n = (@an.include?(Q3) ? 1 : 0) + def bidx1_a_n = (@an.byteindex(Q1) || -1) + def ridx1_a_n = (@an.rindex(Q1) || -1) + def ridx3_a_n = (@an.rindex(Q3) || -1) + def mp_a_n = (RE.match?(@an) ? 1 : 0) + def tilde_a_n = (RE =~ @an || -1) + def match_a_n = ((m = RE.match(@an)) ? m.begin(0) : -1) + def mp3_a_n = (RE3.match?(@an) ? 1 : 0) + def idxre_a_n = (@an.index(RE) || -1) + def sw1_a = (@ae.start_with?(Q1) ? 1 : 0) + def sw3_a = (@ae.start_with?("abcde") ? 1 : 0) + def idx1_u_e = (@ue.index(Q1) || -1) + def idx3_u_e = (@ue.index(Q3) || -1) + def inc1_u_e = (@ue.include?(Q1) ? 1 : 0) + def inc3_u_e = (@ue.include?(Q3) ? 1 : 0) + def bidx1_u_e = (@ue.byteindex(Q1) || -1) + def ridx1_u_e = (@ue.rindex(Q1) || -1) + def ridx3_u_e = (@ue.rindex(Q3) || -1) + def mp_u_e = (RE.match?(@ue) ? 1 : 0) + def tilde_u_e = (RE =~ @ue || -1) + def match_u_e = ((m = RE.match(@ue)) ? m.begin(0) : -1) + def mp3_u_e = (RE3.match?(@ue) ? 1 : 0) + def idxre_u_e = (@ue.index(RE) || -1) + def idx1_u_l = (@ul.index(Q1) || -1) + def idx3_u_l = (@ul.index(Q3) || -1) + def inc1_u_l = (@ul.include?(Q1) ? 1 : 0) + def inc3_u_l = (@ul.include?(Q3) ? 1 : 0) + def bidx1_u_l = (@ul.byteindex(Q1) || -1) + def ridx1_u_l = (@ul.rindex(Q1) || -1) + def ridx3_u_l = (@ul.rindex(Q3) || -1) + def mp_u_l = (RE.match?(@ul) ? 1 : 0) + def tilde_u_l = (RE =~ @ul || -1) + def match_u_l = ((m = RE.match(@ul)) ? m.begin(0) : -1) + def mp3_u_l = (RE3.match?(@ul) ? 1 : 0) + def idxre_u_l = (@ul.index(RE) || -1) + def idx1_u_n = (@un.index(Q1) || -1) + def idx3_u_n = (@un.index(Q3) || -1) + def inc1_u_n = (@un.include?(Q1) ? 1 : 0) + def inc3_u_n = (@un.include?(Q3) ? 1 : 0) + def bidx1_u_n = (@un.byteindex(Q1) || -1) + def ridx1_u_n = (@un.rindex(Q1) || -1) + def ridx3_u_n = (@un.rindex(Q3) || -1) + def mp_u_n = (RE.match?(@un) ? 1 : 0) + def tilde_u_n = (RE =~ @un || -1) + def match_u_n = ((m = RE.match(@un)) ? m.begin(0) : -1) + def mp3_u_n = (RE3.match?(@un) ? 1 : 0) + def idxre_u_n = (@un.index(RE) || -1) + def sw1_u = (@ue.start_with?(Q1) ? 1 : 0) + def sw3_u = (@ue.start_with?("abcde") ? 1 : 0) + def idx1_b_e = (@be.index(Q1B) || -1) + def idx3_b_e = (@be.index(Q3B) || -1) + def inc1_b_e = (@be.include?(Q1B) ? 1 : 0) + def inc3_b_e = (@be.include?(Q3B) ? 1 : 0) + def bidx1_b_e = (@be.byteindex(Q1B) || -1) + def ridx1_b_e = (@be.rindex(Q1B) || -1) + def ridx3_b_e = (@be.rindex(Q3B) || -1) + def mp_b_e = (RE.match?(@be) ? 1 : 0) + def tilde_b_e = (RE =~ @be || -1) + def match_b_e = ((m = RE.match(@be)) ? m.begin(0) : -1) + def mp3_b_e = (RE3.match?(@be) ? 1 : 0) + def idxre_b_e = (@be.index(RE) || -1) + def idx1_b_l = (@bl.index(Q1B) || -1) + def idx3_b_l = (@bl.index(Q3B) || -1) + def inc1_b_l = (@bl.include?(Q1B) ? 1 : 0) + def inc3_b_l = (@bl.include?(Q3B) ? 1 : 0) + def bidx1_b_l = (@bl.byteindex(Q1B) || -1) + def ridx1_b_l = (@bl.rindex(Q1B) || -1) + def ridx3_b_l = (@bl.rindex(Q3B) || -1) + def mp_b_l = (RE.match?(@bl) ? 1 : 0) + def tilde_b_l = (RE =~ @bl || -1) + def match_b_l = ((m = RE.match(@bl)) ? m.begin(0) : -1) + def mp3_b_l = (RE3.match?(@bl) ? 1 : 0) + def idxre_b_l = (@bl.index(RE) || -1) + def idx1_b_n = (@bn.index(Q1B) || -1) + def idx3_b_n = (@bn.index(Q3B) || -1) + def inc1_b_n = (@bn.include?(Q1B) ? 1 : 0) + def inc3_b_n = (@bn.include?(Q3B) ? 1 : 0) + def bidx1_b_n = (@bn.byteindex(Q1B) || -1) + def ridx1_b_n = (@bn.rindex(Q1B) || -1) + def ridx3_b_n = (@bn.rindex(Q3B) || -1) + def mp_b_n = (RE.match?(@bn) ? 1 : 0) + def tilde_b_n = (RE =~ @bn || -1) + def match_b_n = ((m = RE.match(@bn)) ? m.begin(0) : -1) + def mp3_b_n = (RE3.match?(@bn) ? 1 : 0) + def idxre_b_n = (@bn.index(RE) || -1) + def sw1_b = (@be.start_with?(Q1B) ? 1 : 0) + def sw3_b = (@be.start_with?("abcde") ? 1 : 0) + def int_match = ((m = RE_INT.match(@short)) ? m.end(0) : -1) + def int_mp = (RE_INT.match?(@short) ? 1 : 0) + def int_tilde = (RE_INT =~ @short || -1) + def short_idx = (@short.index(" ") || -1) + def size = @other.size + def eq = (@other == @short ? 1 : 0) +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +h = H.new +# a shape over a whole 10 KB receiver takes a microsecond or more; one that stops early or is +# short, about a hundred nanoseconds +LONG = (ENV["N"] || 100_000).to_i +SHORTN = LONG * 10 +# CRuby takes 9 to 60 us for a character class over the whole of a 10 KB String, IronRuby under one: +# the count is the long one so that IronRuby's sections are long enough to time. +REGEX = LONG + +t("idx1_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx1_a_e; i += 1; end; s } +t("idx3_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx3_a_e; i += 1; end; s } +t("inc1_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.inc1_a_e; i += 1; end; s } +t("inc3_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.inc3_a_e; i += 1; end; s } +t("bidx1_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.bidx1_a_e; i += 1; end; s } +t("ridx1_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.ridx1_a_e; i += 1; end; s } +t("ridx3_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.ridx3_a_e; i += 1; end; s } +t("mp_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.mp_a_e; i += 1; end; s } +t("tilde_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.tilde_a_e; i += 1; end; s } +t("match_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.match_a_e; i += 1; end; s } +t("mp3_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.mp3_a_e; i += 1; end; s } +t("idxre_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idxre_a_e; i += 1; end; s } +t("idx1_a_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx1_a_l; i += 1; end; s } +t("idx3_a_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx3_a_l; i += 1; end; s } +t("inc1_a_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc1_a_l; i += 1; end; s } +t("inc3_a_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc3_a_l; i += 1; end; s } +t("bidx1_a_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.bidx1_a_l; i += 1; end; s } +t("ridx1_a_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx1_a_l; i += 1; end; s } +t("ridx3_a_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx3_a_l; i += 1; end; s } +t("mp_a_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp_a_l; i += 1; end; s } +t("tilde_a_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.tilde_a_l; i += 1; end; s } +t("match_a_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.match_a_l; i += 1; end; s } +t("mp3_a_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp3_a_l; i += 1; end; s } +t("idxre_a_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.idxre_a_l; i += 1; end; s } +t("idx1_a_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx1_a_n; i += 1; end; s } +t("idx3_a_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx3_a_n; i += 1; end; s } +t("inc1_a_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc1_a_n; i += 1; end; s } +t("inc3_a_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc3_a_n; i += 1; end; s } +t("bidx1_a_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.bidx1_a_n; i += 1; end; s } +t("ridx1_a_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx1_a_n; i += 1; end; s } +t("ridx3_a_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx3_a_n; i += 1; end; s } +t("mp_a_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp_a_n; i += 1; end; s } +t("tilde_a_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.tilde_a_n; i += 1; end; s } +t("match_a_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.match_a_n; i += 1; end; s } +t("mp3_a_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp3_a_n; i += 1; end; s } +t("idxre_a_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.idxre_a_n; i += 1; end; s } +t("sw1_a", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.sw1_a; i += 1; end; s } +t("sw3_a", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.sw3_a; i += 1; end; s } +t("idx1_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx1_u_e; i += 1; end; s } +t("idx3_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx3_u_e; i += 1; end; s } +t("inc1_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.inc1_u_e; i += 1; end; s } +t("inc3_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.inc3_u_e; i += 1; end; s } +t("bidx1_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.bidx1_u_e; i += 1; end; s } +t("ridx1_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.ridx1_u_e; i += 1; end; s } +t("ridx3_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.ridx3_u_e; i += 1; end; s } +t("mp_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.mp_u_e; i += 1; end; s } +t("tilde_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.tilde_u_e; i += 1; end; s } +t("match_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.match_u_e; i += 1; end; s } +t("mp3_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.mp3_u_e; i += 1; end; s } +t("idxre_u_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idxre_u_e; i += 1; end; s } +t("idx1_u_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx1_u_l; i += 1; end; s } +t("idx3_u_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx3_u_l; i += 1; end; s } +t("inc1_u_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc1_u_l; i += 1; end; s } +t("inc3_u_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc3_u_l; i += 1; end; s } +t("bidx1_u_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.bidx1_u_l; i += 1; end; s } +t("ridx1_u_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx1_u_l; i += 1; end; s } +t("ridx3_u_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx3_u_l; i += 1; end; s } +t("mp_u_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp_u_l; i += 1; end; s } +t("tilde_u_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.tilde_u_l; i += 1; end; s } +t("match_u_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.match_u_l; i += 1; end; s } +t("mp3_u_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp3_u_l; i += 1; end; s } +t("idxre_u_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.idxre_u_l; i += 1; end; s } +t("idx1_u_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx1_u_n; i += 1; end; s } +t("idx3_u_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx3_u_n; i += 1; end; s } +t("inc1_u_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc1_u_n; i += 1; end; s } +t("inc3_u_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc3_u_n; i += 1; end; s } +t("bidx1_u_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.bidx1_u_n; i += 1; end; s } +t("ridx1_u_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx1_u_n; i += 1; end; s } +t("ridx3_u_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx3_u_n; i += 1; end; s } +t("mp_u_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp_u_n; i += 1; end; s } +t("tilde_u_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.tilde_u_n; i += 1; end; s } +t("match_u_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.match_u_n; i += 1; end; s } +t("mp3_u_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp3_u_n; i += 1; end; s } +t("idxre_u_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.idxre_u_n; i += 1; end; s } +t("sw1_u", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.sw1_u; i += 1; end; s } +t("sw3_u", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.sw3_u; i += 1; end; s } +t("idx1_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx1_b_e; i += 1; end; s } +t("idx3_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx3_b_e; i += 1; end; s } +t("inc1_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.inc1_b_e; i += 1; end; s } +t("inc3_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.inc3_b_e; i += 1; end; s } +t("bidx1_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.bidx1_b_e; i += 1; end; s } +t("ridx1_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.ridx1_b_e; i += 1; end; s } +t("ridx3_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.ridx3_b_e; i += 1; end; s } +t("mp_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.mp_b_e; i += 1; end; s } +t("tilde_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.tilde_b_e; i += 1; end; s } +t("match_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.match_b_e; i += 1; end; s } +t("mp3_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.mp3_b_e; i += 1; end; s } +t("idxre_b_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idxre_b_e; i += 1; end; s } +t("idx1_b_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx1_b_l; i += 1; end; s } +t("idx3_b_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx3_b_l; i += 1; end; s } +t("inc1_b_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc1_b_l; i += 1; end; s } +t("inc3_b_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc3_b_l; i += 1; end; s } +t("bidx1_b_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.bidx1_b_l; i += 1; end; s } +t("ridx1_b_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx1_b_l; i += 1; end; s } +t("ridx3_b_l", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx3_b_l; i += 1; end; s } +t("mp_b_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp_b_l; i += 1; end; s } +t("tilde_b_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.tilde_b_l; i += 1; end; s } +t("match_b_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.match_b_l; i += 1; end; s } +t("mp3_b_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp3_b_l; i += 1; end; s } +t("idxre_b_l", REGEX) { |n| i = 0; s = 0; while i < n; s += h.idxre_b_l; i += 1; end; s } +t("idx1_b_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx1_b_n; i += 1; end; s } +t("idx3_b_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.idx3_b_n; i += 1; end; s } +t("inc1_b_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc1_b_n; i += 1; end; s } +t("inc3_b_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.inc3_b_n; i += 1; end; s } +t("bidx1_b_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.bidx1_b_n; i += 1; end; s } +t("ridx1_b_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx1_b_n; i += 1; end; s } +t("ridx3_b_n", LONG) { |n| i = 0; s = 0; while i < n; s += h.ridx3_b_n; i += 1; end; s } +t("mp_b_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp_b_n; i += 1; end; s } +t("tilde_b_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.tilde_b_n; i += 1; end; s } +t("match_b_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.match_b_n; i += 1; end; s } +t("mp3_b_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.mp3_b_n; i += 1; end; s } +t("idxre_b_n", REGEX) { |n| i = 0; s = 0; while i < n; s += h.idxre_b_n; i += 1; end; s } +t("sw1_b", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.sw1_b; i += 1; end; s } +t("sw3_b", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.sw3_b; i += 1; end; s } +t("int_match", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.int_match; i += 1; end; s } +t("int_mp", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.int_mp; i += 1; end; s } +t("int_tilde", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.int_tilde; i += 1; end; s } +t("short_idx", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.short_idx; i += 1; end; s } +t("size", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.size; i += 1; end; s } +t("eq", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.eq; i += 1; end; s } diff --git a/Util/string-search-matrix.rb b/Util/string-search-matrix.rb new file mode 100644 index 000000000..59fbc532c --- /dev/null +++ b/Util/string-search-matrix.rb @@ -0,0 +1,126 @@ +# Differential matrix for searching a String: #index, #rindex, #byteindex, #byterindex, +# #include?, #start_with?, #end_with? with a String or a Regexp needle, and Regexp#match?, #=~, +# #match and String#match?, #=~, #match, with what each leaves in $~. +# +# ruby Util/string-search-matrix.rb > /tmp/strsearch.mri +# ./ir.sh Util/string-search-matrix.rb > /tmp/strsearch.ir +# diff -u /tmp/strsearch.mri /tmp/strsearch.ir +# +# The receivers are ASCII, UTF-8 with two- and three-byte characters, UTF-8 with a character above +# U+FFFF (a surrogate pair in IronRuby's UTF-16), BINARY with high bytes, broken UTF-8, US-ASCII, +# EUC-JP and UTF-16LE, each in the content kinds a String can be in here (a literal, one built by +# <<, one sliced, one force_encoded, one that has been indexed by character already), and a +# subclass. The needles are one and three characters, empty, broken, of another encoding, an +# object with #to_str, and a Regexp; the offsets are positive, negative, past the end and at it. +# A row prints the answer and $~ (its begin, or nil, or "kept" when the call must leave it alone), +# or the exception's class and message. + +def show(v) + case v + when MatchData then "#" + else v.inspect + end +end + +# $~ belongs to the frame of the code that matched, so each block sets it to a sentinel match +# itself and hands back the answer, $~ before and $~ after. +SENTINEL = /sentinel/ +def try(label) + v, before, after = yield + m = after.equal?(before) ? "kept" : (after ? after.begin(0).inspect : "nil") + puts "#{label}\t#{show(v)}\t$~=#{m}" +rescue Exception => e + puts "#{label}\t#{e.class}: #{e.message}" +end + +class SubStr < String; end +class ToStr; def initialize(s) = @s = s; def to_str = @s; end + +def kinds(base) + out = {} + out[:lit] = base.dup + b = String.new(encoding: base.encoding); base.each_char { |c| b << c }; out[:built] = b + out[:slice] = ("_".encode(base.encoding) + base)[1..] + out[:forced] = base.b.force_encoding(base.encoding) + ix = base.dup; ix[0] if ix.size > 0; ix.size; out[:indexed] = ix + out[:sub] = SubStr.new(base) + out +end + +RECEIVERS = { + ascii: 'ab"cd ab"cd q"z end', + utf8: 'éa"日cd é"b q"z fin', + astral: "😀a\"𝒳c q\"z 😀\"", + binary: "ab\"\xE9\xFFcd \xE9\"q\"z".b, + broken: "ab\"\xE9cd q\"z \xFF\"".dup.force_encoding("UTF-8"), + usascii: 'ab"cd q"z'.dup.force_encoding("US-ASCII"), + eucjp: "a\"\xA4\xA2\"q\"z".dup.force_encoding("EUC-JP"), + utf16: 'a"b q"z'.encode("UTF-16LE"), + empty: "", +} + +NEEDLES = { + q1: '"', q3: 'q"z', none: '#', empty: "", + nonascii: "é", astral: "😀", bin1: '"'.b, binhi: "\xE9".b, + broken: "\xE9".dup.force_encoding("UTF-8"), eucjp: "\xA4\xA2".dup.force_encoding("EUC-JP"), + utf16: '"'.encode("UTF-16LE"), tostr: ToStr.new('"'), sub: SubStr.new('q"z'), +} +OFFSETS = [nil, 0, 1, 3, -1, -3, 100, -100] + +RECEIVERS.each do |rname, base| + kinds(base).each do |kname, s| + puts "== #{rname}/#{kname} #{s.encoding} valid=#{s.valid_encoding?} size=#{s.size} bytesize=#{s.bytesize}" + NEEDLES.each do |nname, n| + OFFSETS.each do |off| + a = off.nil? ? "" : ", #{off}" + try("index(#{nname}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.index(n) : s.index(n, off)), b, $~] } + try("rindex(#{nname}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.rindex(n) : s.rindex(n, off)), b, $~] } + try("byteindex(#{nname}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.byteindex(n) : s.byteindex(n, off)), b, $~] } + try("byterindex(#{nname}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.byterindex(n) : s.byterindex(n, off)), b, $~] } + end + try("include?(#{nname})") { "sentinel" =~ SENTINEL; b = $~; [(s.include?(n)), b, $~] } + try("start_with?(#{nname})") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?(n)), b, $~] } + try("end_with?(#{nname})") { "sentinel" =~ SENTINEL; b = $~; [(s.end_with?(n)), b, $~] } + end + [/"/, /q"z/, /[<>"]/, /\A[+-]?\d+/, /\Aa/, /z/, /é/, /😀/, /./, /\b/, /(?")/].each do |re| + OFFSETS.each do |off| + a = off.nil? ? "" : ", #{off}" + try("#{re.inspect}.match?(s#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? re.match?(s) : re.match?(s, off)), b, $~] } + try("#{re.inspect}.match(s#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? re.match(s) : re.match(s, off)), b, $~] } + try("s.match?(#{re.inspect}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.match?(re) : s.match?(re, off)), b, $~] } + try("s.index(#{re.inspect}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.index(re) : s.index(re, off)), b, $~] } + try("s.rindex(#{re.inspect}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.rindex(re) : s.rindex(re, off)), b, $~] } + try("s.byteindex(#{re.inspect}#{a})") { "sentinel" =~ SENTINEL; b = $~; [(off.nil? ? s.byteindex(re) : s.byteindex(re, off)), b, $~] } + end + try("#{re.inspect} =~ s") { "sentinel" =~ SENTINEL; b = $~; [(re =~ s), b, $~] } + try("s =~ #{re.inspect}") { "sentinel" =~ SENTINEL; b = $~; [(s =~ re), b, $~] } + try("s.match(#{re.inspect})") { "sentinel" =~ SENTINEL; b = $~; [(s.match(re)), b, $~] } + try("s.start_with?(#{re.inspect})") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?(re)), b, $~] } + try("#{re.inspect} === s") { "sentinel" =~ SENTINEL; b = $~; [(re === s), b, $~] } + end + try("s.match?('q\"z')") { "sentinel" =~ SENTINEL; b = $~; [(s.match?('q"z')), b, $~] } + try("s.match('q\"z')") { "sentinel" =~ SENTINEL; b = $~; [(s.match('q"z')), b, $~] } + end +end + +puts "== odd operands" +try("/a/.match?(nil)") { "sentinel" =~ SENTINEL; b = $~; [(/a/.match?(nil)), b, $~] } +try("/a/ =~ nil") { "sentinel" =~ SENTINEL; b = $~; [(/a/ =~ nil), b, $~] } +try("/a/.match(nil)") { "sentinel" =~ SENTINEL; b = $~; [(/a/.match(nil)), b, $~] } +try("/a/.match?(:bab)") { "sentinel" =~ SENTINEL; b = $~; [(/a/.match?(:bab)), b, $~] } +try("/a/ =~ :bab") { "sentinel" =~ SENTINEL; b = $~; [(/a/ =~ :bab), b, $~] } +try("/a/.match?(1)") { "sentinel" =~ SENTINEL; b = $~; [(/a/.match?(1)), b, $~] } +try("/a/.match?(ToStr)") { "sentinel" =~ SENTINEL; b = $~; [(/a/.match?(ToStr.new("xa"))), b, $~] } +try("'ab'.index(1)") { "sentinel" =~ SENTINEL; b = $~; [("ab".index(1)), b, $~] } +try("'ab'.index(nil)") { "sentinel" =~ SENTINEL; b = $~; [("ab".index(nil)), b, $~] } +try("'ab'.index('a', 'x')") { "sentinel" =~ SENTINEL; b = $~; [("ab".index("a", "x")), b, $~] } +try("'ab'.index('b', 1.9)") { "sentinel" =~ SENTINEL; b = $~; [("ab".index("b", 1.9)), b, $~] } +try("'ab'.include?(nil)") { "sentinel" =~ SENTINEL; b = $~; [("ab".include?(nil)), b, $~] } +try("'ab'.include?(ToStr)") { "sentinel" =~ SENTINEL; b = $~; [("ab".include?(ToStr.new("b"))), b, $~] } +try("/\\xff/n.match?(utf8)") { "sentinel" =~ SENTINEL; b = $~; [(Regexp.new("\xff".b).match?("é")), b, $~] } +try("/é/.match?(binary)") { "sentinel" =~ SENTINEL; b = $~; [(/é/.match?("\xC3\xA9".b)), b, $~] } +try("/é/.match?(eucjp)") { "sentinel" =~ SENTINEL; b = $~; [(/é/.match?("\xA4\xA2".dup.force_encoding("EUC-JP"))), b, $~] } +s = "abc\"def" +try("index after <<") { "sentinel" =~ SENTINEL; b = $~; [(s << "\"x"; s.index('"', 4)), b, $~] } +try("index after setbyte") { "sentinel" =~ SENTINEL; b = $~; [(t = +"abc"; t.setbyte(1, 0x22); t.index('"')), b, $~] } +try("frozen literal index") { "sentinel" =~ SENTINEL; b = $~; [('x"y'.freeze.index('"')), b, $~] } From ba4a151cf3ab313eb5b62c320a9a119e8536f277 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:43:06 +0000 Subject: [PATCH 005/439] byteindex/byterindex with a String needle in C#, Regexp#match? without a MatchData MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit String#byteindex and #byterindex forwarded every call to a Ruby helper (ruby4.rb's __ir_byte_search__) that built a table of the byte offset of every character with each_char, on every call: 1.1 ms for one call on a 10 KB UTF-8 String with non-ASCII characters, where CRuby takes 76-160 ns; 610-760 ns on 10 KB of ASCII against CRuby's 64-120. The usual call - a String needle, an Integer offset or none - is now done in C#: a receiver whose characters are its bytes (ASCII, BINARY, a single-byte encoding) needs no conversion, and a valid UTF-8 one counts the UTF-8 bytes of its UTF-16 characters (vectorized for the answer, a scalar walk for an offset other than 0). The answers are the helper's, the IndexError for an offset inside a character included; every other call (a Regexp, which sets $~, a #to_str needle, a Bignum offset, other encodings, a broken string) still goes to the helper. Regexp#match? made a Match and a MatchData for a successful match only to answer true. It now asks Regex.IsMatch, but for a subject with a surrogate pair, which needs the Match to skip one that starts between the halves. IR_FAST_SEARCH=0 turns both off, for timing one build both ways. Also fixes #index, #rindex, #include? (and the byte searches built on them) with a needle held as bytes, such as a BINARY "\"".b, on a receiver held as characters that are not its bytes: the receiver's IndexOf(byte[]) means bytes, so it switched the receiver to bytes and answered a byte offset where a character offset was meant ("é\"".index("\"".b) was 2, CRuby says 1). The needle's characters are searched for instead. Util/string-search-matrix.rb's 246 rows of it now print CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/Builtins/MutableStringOps.cs | 113 ++++++++++++++++++ Src/Libraries/Builtins/RubyRegexOps.cs | 8 +- .../Builtins/MutableString.BinaryContent.cs | 15 ++- Src/Ruby/Builtins/RubyRegex.cs | 23 ++++ 4 files changed, 156 insertions(+), 3 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 5dbf80244..45fa6f2fe 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -4463,15 +4463,128 @@ private static object CallMatchingHelper(CallSiteStorage + /// IR_FAST_SEARCH=0 turns off the shortcuts searching takes (#byteindex and #byterindex with a + /// String needle done here rather than in ruby4.rb, Regexp#match? without a MatchData), so + /// that one build can be timed with and without them. + /// + internal static readonly bool FastSearchEnabled = Environment.GetEnvironmentVariable("IR_FAST_SEARCH") != "0"; + + // __ir_byte_search__ (ruby4.rb) for the usual call, a String needle and an Integer offset or + // none, done here. The helper builds a table of the byte offset of every character on every + // call, which is a millisecond for 10 KB of UTF-8 (MRI: 150 ns); a receiver whose characters + // are its bytes needs no table, and a valid UTF-8 one can count the bytes of its characters, + // which .NET does vectorized. The answers are the helper's, the IndexError for an offset + // inside a character included. False for any other call (a Regexp, a #to_str needle, an + // offset that is not a Fixnum, another encoding, a broken string), which the helper makes. + private static bool TryByteSearch(MutableString/*!*/ self, object[]/*!*/ args, bool reverse, out object result) { + result = null; + if (!FastSearchEnabled || args.Length < 1 || args.Length > 2) { + return false; + } + MutableString needle = args[0] as MutableString; + if (needle == null || (args.Length == 2 && !(args[1] is int))) { + return false; + } + + ReadOnlySpan chars = default(ReadOnlySpan); + bool singleByte = self.DetectSingleByteCharacters(); + if (!singleByte) { + if (self.Encoding != RubyEncoding.UTF8 || self.ContainsInvalidCharacters()) { + return false; + } + self.PrepareForCharacterRead(); + ReadOnlySpan bytes; + if (!self.GetCharacterData(out chars, out bytes)) { + return false; + } + } + + int size = singleByte ? GetCharacterLength(self) : Encoding.UTF8.GetByteCount(chars); + int offset = (args.Length == 2) ? (int)args[1] : (reverse ? size : 0); + if (offset < 0) { + offset += size; + if (offset < 0) { + return true; + } + } + if (offset > size) { + // #byteindex gives up past the end, #byterindex clamps to it + if (!reverse) { + return true; + } + offset = size; + } + + int charOffset; + if (singleByte) { + charOffset = offset; + } else { + int clrOffset = Utf8OffsetToClrIndex(chars, offset); + if (clrOffset < 0) { + throw RubyExceptions.CreateIndexError("offset {0} does not land on character boundary", offset); + } + charOffset = self.ToCharacterIndex(clrOffset); + } + + object found = reverse ? LastIndexOf(self, needle, charOffset) : Index(self, needle, charOffset); + if (found == null || singleByte) { + result = found; + return true; + } + int foundClr = self.ToClrIndex((int)found); + if (foundClr > chars.Length) { + // the string changed under the search (another thread): the helper is the one to ask + return false; + } + result = ScriptingRuntimeHelpers.Int32ToObject(Encoding.UTF8.GetByteCount(chars.Slice(0, foundClr))); + return true; + } + + /// + /// The CLR index of the character that starts bytes into the + /// UTF-8 form of (valid UTF-16), or -1 when that offset is inside a + /// character or past the end. + /// + private static int Utf8OffsetToClrIndex(ReadOnlySpan chars, int byteOffset) { + int bytes = 0; + int i = 0; + while (bytes < byteOffset && i < chars.Length) { + char c = chars[i]; + if (c < 0x80) { + bytes += 1; + i += 1; + } else if (c < 0x800) { + bytes += 2; + i += 1; + } else if (Char.IsHighSurrogate(c) && i + 1 < chars.Length && Char.IsLowSurrogate(chars[i + 1])) { + bytes += 4; + i += 2; + } else { + bytes += 3; + i += 1; + } + } + return (bytes == byteOffset) ? i : -1; + } + [RubyMethod("byteindex")] public static object ByteIndex(CallSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, MutableString/*!*/ self, params object[]/*!*/ args) { + object result; + if (TryByteSearch(self, args, false, out result)) { + return result; + } return CallMatchingHelper(storage, scope, self, "__ir_byteindex__", args.Length > 0 ? args[0] : null, new RubyArray(args)); } [RubyMethod("byterindex")] public static object ByteLastIndex(CallSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, MutableString/*!*/ self, params object[]/*!*/ args) { + object result; + if (TryByteSearch(self, args, true, out result)) { + return result; + } return CallMatchingHelper(storage, scope, self, "__ir_byterindex__", args.Length > 0 ? args[0] : null, new RubyArray(args)); } diff --git a/Src/Libraries/Builtins/RubyRegexOps.cs b/Src/Libraries/Builtins/RubyRegexOps.cs index 4098953ff..cf5fa6185 100644 --- a/Src/Libraries/Builtins/RubyRegexOps.cs +++ b/Src/Libraries/Builtins/RubyRegexOps.cs @@ -545,7 +545,13 @@ public static bool IsMatch(RubyRegex/*!*/ self, [DefaultProtocol]MutableString s if (!self.IsInitialized) { throw RubyExceptions.CreateTypeError("uninitialized Regexp"); } - return str != null && self.MatchFromCharacter(str, start, false) != null; + if (str == null) { + return false; + } + // IR_FAST_SEARCH=0: the MatchData is made and thrown away, as it used to be. + return MutableStringOps.FastSearchEnabled + ? self.IsMatchFromCharacter(str, start) + : self.MatchFromCharacter(str, start, false) != null; } [RubyMethod("match?")] diff --git a/Src/Ruby/Builtins/MutableString.BinaryContent.cs b/Src/Ruby/Builtins/MutableString.BinaryContent.cs index 67fd9ac89..3698ee015 100644 --- a/Src/Ruby/Builtins/MutableString.BinaryContent.cs +++ b/Src/Ruby/Builtins/MutableString.BinaryContent.cs @@ -660,7 +660,14 @@ public override int IndexIn(Content/*!*/ str, int start, int count) { // The buffer is a capacity, not a length: searching for the whole of it would look // for the unused tail as well, and a needle built by growing one - String#pack, say - // would never be found. - return str.IndexOf(ExactData(), start, count); + if (str is BinaryContent) { + return str.IndexOf(ExactData(), start, count); + } + // A receiver held as characters is searched for the needle's characters. Its + // IndexOf(byte[]) means bytes: on a receiver whose characters are not its bytes (é) + // it switched the receiver to bytes and answered a byte offset where a CLR index was + // asked for - "é\"".index("\"".b) was 2. + return str.IndexOf(DataToString(), start, count); } /// @@ -703,7 +710,11 @@ public override int LastIndexOf(byte[]/*!*/ bytes, int start, int count) { } public override int LastIndexIn(Content/*!*/ str, int start, int count) { - return str.LastIndexOf(ExactData(), start, count); + // as IndexIn + if (str is BinaryContent) { + return str.LastIndexOf(ExactData(), start, count); + } + return str.LastIndexOf(DataToString(), start, count); } #endregion diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 14d275b16..003308390 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -1517,6 +1517,29 @@ public MatchData MatchFromCharacter(MutableString/*!*/ input, int start, bool fr return Match(input, start, freezeInput); } + /// + /// Whether would find a match, for + /// Regexp#match?: the same checks and the same search, but the engine is only asked whether + /// there is one (Regex.IsMatch), so neither a Match with its groups nor a MatchData nor a + /// frozen copy of the input is made. A subject with a surrogate pair needs the Match to tell + /// a match between the two halves of a pair from one Ruby has, and takes the long way. + /// + public bool IsMatchFromCharacter(MutableString/*!*/ input, int start) { + if (!ToSearchStart(input, ref start, false)) { + return false; + } + string str; + bool astral; + Regex regex = Transform(input, out str, out astral, true); + if (start < 0) { + start += str.Length; + } + if (start < 0 || start > str.Length) { + return false; + } + return astral ? MatchOutsidePairs(regex, str, start).Success : regex.IsMatch(str, start); + } + /// /// The last match starting at or before Ruby character index . /// From c9a4e7c04627013cb1cd8ed37f644d79ffedb4ea Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:46:45 +0000 Subject: [PATCH 006/439] A Regexp search from an offset outside the string answers nil before checking encodings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CRuby's rb_str_index_m, rb_str_rindex_m, rb_reg_match_p and reg_match_pos look at the offset first: "\xE9".b.index(/é/, 100), /é/.match?(bin, 100), utf16.rindex(/a/, -100) and broken_utf8.index(/"/, 100) answer nil (or false), and #index and #rindex clear $~. IronRuby checked the offset only for a subject with a surrogate pair, after the regex had been made for the subject - which raises Encoding::CompatibilityError for an incompatible one - and String#index(Regexp) refused a broken receiver before the offset. RubyRegex.ToSearchStart now checks the range for every subject, and String#index(Regexp) checks it before the receiver's encoding. Util/string-search-matrix.rb's last 852 differing rows now print CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/Builtins/MutableStringOps.cs | 11 ++++++++++- Src/Ruby/Builtins/RubyRegex.cs | 21 +++++++++++++++------ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 45fa6f2fe..96dfd3200 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -4377,7 +4377,16 @@ public static object Index(RubyScope/*!*/ scope, MutableString/*!*/ self, [NotNull]RubyRegex/*!*/ regex, [DefaultProtocol, Optional]int start) { // A Regexp has to interpret characters, so unlike #index with a String this one does - // refuse a receiver whose bytes are not valid in its encoding, the way MRI does. + // refuse a receiver whose bytes are not valid in its encoding, the way MRI does - but + // only once the offset is inside the string: rb_str_index_m answers nil (and clears $~) + // for one outside it first. + if (start != 0) { + int length = GetCharacterLength(self); + if (start < 0 ? start + length < 0 : start > length) { + scope.GetInnerMostClosureScope().CurrentMatch = null; + return null; + } + } RequireValidEncoding(self); MatchData match = regex.MatchFromCharacter(self, start, true); diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 003308390..b7c3ac165 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -1462,18 +1462,29 @@ public static RegexOptions ToClrOptions(RubyRegexOptions options) { /// Ruby's pos argument - Regexp#match(str, pos), String#index(re, pos), #match? - is a /// character index, negative from the end, while Match and LastMatch take the index /// space the regex runs in: the CLR chars of the string. Answers false when the - /// position is outside the string. + /// position is outside the string - before the regex is made for the input, which checks + /// its encoding: MRI answers nil (false) for /é/.match?(binary, 100) and does not raise. /// private bool ToSearchStart(MutableString/*!*/ input, ref int start, bool clamp) { - if (start == 0 || input.KnowsCharIndexIsClrIndex) { + if (start == 0) { return true; } + if (input.KnowsCharIndexIsClrIndex) { + return ToSearchStart(input.GetCharCount(), ref start, clamp); + } input.PrepareForCharacterRead(); if (!input.HasSurrogatePairs()) { - return true; + return ToSearchStart(input.GetCharCount(), ref start, clamp); + } + + if (!ToSearchStart(input.GetCharacterCount(), ref start, clamp)) { + return false; } + start = input.ToClrIndex(start); + return true; + } - int length = input.GetCharacterCount(); + private static bool ToSearchStart(int length, ref int start, bool clamp) { if (start < 0) { start += length; if (start < 0) { @@ -1486,8 +1497,6 @@ private bool ToSearchStart(MutableString/*!*/ input, ref int start, bool clamp) } start = length; } - - start = input.ToClrIndex(start); return true; } From ff223b03a9c66d47b3ee5a6a1bc0439b9edaa614 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:52:12 +0000 Subject: [PATCH 007/439] Light frames read and write global variables through the declaring scope A global variable kept a method out of light frames: IsScopeFree had no case for one, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` alone made 258 methods of the standard library allocate a scope on every call, Kernel#puts among them. Only `$~` and `$_` (and what is derived from `$~`) live in the frame; every other global is the runtime's. Now a light frame reads and writes any global but those two names through the declaring scope (RubyOps.ReadLightGlobalVariable, GetLightGlobalVariable, SetLightGlobalVariable, in LightFrameRewriter.VisitGlobalVariableCall), and `defined?($x)` hands IsDefinedGlobalVariable the declaring scope. A name that turns out to denote `$~` or `$_` (an alias, English.rb's `$LAST_MATCH_INFO`) answers LightScopeRequired having done nothing, and the frame makes its scope and does it again with the cached helper; so does an assignment while a trace_var handler is registered, one in a non-main Ractor and one that creates the global. The decision and the access use the same variable object, so an alias made by another thread in between cannot make a frame read its declaring scope's match. A name that already denotes `$~` or `$_` when the body is compiled keeps the scope, and so does a global in a body of more than 24 calls (the masgn limit: String#__ir_split_lines__ light was 2.3 times the IL and `lines` 1.10 times slower). The frame keeps its stack check, since `$FILENAME`, `$stdout =` and trace_var handlers run Ruby code. IR_LIGHT_GLOBALS=0 turns it off. Census (Src/StdLib + AWFY, 28,376 methods): light frames 91.7% -> 92.6%, 238 methods moved up, none down, JIT unchanged; census -c agrees with traced runs. Timed against the switch off: defined?($g) 0.66, a `$/` default 0.68, $stdout 0.71-0.88, `x + $g` 0.56-0.90, puts 0.88; controls overlap. Util/global-light-matrix.rb (new) prints CRuby 4.0's output as built, with the switch off, IR_LIGHT_FRAMES=0, IR_PARKED_SCOPES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and on the R2R host; 14 related matrices pass in those modes; Method_LightFrameGlobal1 (new) and the global-variable tests pass. Census only: not yet gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 65 ++++ Src/Ruby/Compiler/Ast/BlockDefinition.cs | 4 +- .../Ast/Definitions/MethodDefinition.cs | 133 ++++++- Src/Ruby/Runtime/Globals/GlobalVariable.cs | 7 + .../Runtime/Globals/GlobalVariableInfo.cs | 4 + .../Globals/ReadOnlyGlobalVariableInfo.cs | 4 + .../Globals/SpecialGlobalVariableInfo.cs | 18 + Src/Ruby/Runtime/RubyContext.cs | 14 + Src/Ruby/Runtime/RubyOps.cs | 70 ++++ Util/bench/global-shapes.rb | 97 +++++ Util/global-light-matrix.rb | 340 ++++++++++++++++++ 12 files changed, 753 insertions(+), 4 deletions(-) create mode 100644 Util/bench/global-shapes.rb create mode 100644 Util/global-light-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fe0f92281..c1e7ee034 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1137,6 +1137,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGuard1, Method_LightFrameBlockGiven1, Method_LightFrameRest1, + Method_LightFrameGlobal1, Method_ParkedScope1, Method_ParkedScopeLeak1, Method_LightFrameBlockPass1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 19e10dfbc..63e3ee672 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7709,6 +7709,71 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters "); } + /// + /// A method that reads or writes a global is a light frame too (MethodDefinition.IsLightGlobal): every global but $~ and + /// $_ is the runtime's, and the frame reads and writes it through the declaring scope. A name that comes to denote $~ or $_ + /// after the method was compiled (an alias) makes the scope on demand at the read or the write, and so does any + /// assignment while a trace_var handler is registered. Util/global-light-matrix.rb has the full matrix. Expected output + /// is CRuby 4.0's. + /// + public void Method_LightFrameGlobal1() { + TestOutput(@" +require 'ruby4' +$g = 1 +$m = nil +$l = nil +def r; $g; end +def w(v); $g = v; end +def op; $g += 1; end +def orr(v); $h ||= v; end +def out; $stdout.equal?(STDOUT); end +def dflt(sep = $/); sep; end +def defd; [defined?($g), defined?($never_set_anywhere)]; end +def ro; $! = 1; end +def bad_out; $stdout = 5; end +def seen; v = $g; [v, binding.local_variable_get(:v)]; end +def no_match; $m; end +def late_line(v); $l = v; $_; end +p r, w(2), r, op, orr(5), orr(6), out, dflt, defd +begin; ro; rescue NameError => e; p e.message; end +begin; bad_out; rescue TypeError => e; p e.message; end +p seen, no_match, late_line(3) +alias $m $~ +alias $l $_ +'top' =~ /top/ +p no_match, $~[0], late_line('x'), $_ +log = [] +trace_var(:$g) { |v| log << v } +w(7); op +untrace_var(:$g) +p log, 40.times.map { |i| w(i); r }.sum +def deep(n); $depth = n; deep(n + 1); end +begin; deep(0); rescue SystemStackError; p :stack; end +", @" +1 +2 +2 +3 +5 +5 +true +""\n"" +[""global-variable"", nil] +""$! is a read-only variable"" +""$stdout must have write method, Integer given"" +[3, 3] +nil +nil +nil +""top"" +""x"" +nil +[7, 8] +780 +:stack +"); + } + /// /// BigDecimal against CRuby 4.0's bigdecimal 4.0.1: a Rational operand of a comparison is expanded as /// for arithmetic (== used to recurse through Rational#== until the stack overflowed), #power and #** diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index dbcf43ec3..03c3b812a 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -233,7 +233,9 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St // the block's own scope answers - `Module.new { using R; o.respond_to?(:m) }', whose respond_to? reads only the // runtime and the refinements from the scope it is given ([DeclaringScope]). var callScope = Ast.Coalesce(AstUtils.Convert(scopeVariable, typeof(RubyScope)), parent); - var rewriter = new MethodDefinition.LightFrameRewriter(scopeVariable, lazy, null, callScope, inLoop, false); + var rewriter = new MethodDefinition.LightFrameRewriter(scopeVariable, lazy, null, callScope, inLoop, false) { + Context = gen.Context + }; var lazyParamInit = rewriter.Visit(paramInit); var lazyStatements = rewriter.Visit(statements); if (!rewriter.NeedsScope) { diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 3b5b47761..02ead26f3 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -553,6 +553,13 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { internal static readonly bool LightRegexEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_REGEX") != "0"; private static readonly bool LightRegexAll = Environment.GetEnvironmentVariable("IR_LIGHT_REGEX") == "all"; + /// + /// IR_LIGHT_GLOBALS=0 keeps every method that reads or writes a global variable out of light frames. Otherwise `$x', + /// `$x = v' and `defined?($x)' are scope-free for every name but `$~' and `$_', which are the frame's own (see + /// IsLightGlobal and LightFrameRewriter.VisitGlobalVariableCall). + /// + internal static readonly bool LightGlobalsEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_GLOBALS") != "0"; + /// /// IR_LIGHT_BREAK=0 keeps every method with a `break', `next' or `redo' in a `while'/`until' loop of its body out of /// light frames (see IsScopeFree). @@ -723,7 +730,7 @@ private bool IsLightFrameCandidate() { if (body == null || HasHandling(body) && !LightRescueEnabled) { return false; } - if (IsLargeWithMultipleAssignment() || HasScopeReadingSuper()) { + if (IsLargeWithMultipleAssignment() || IsLargeWithGlobal() || HasScopeReadingSuper()) { return false; } return IsBodyScopeFree(false) || LightBlocksEnabled && IsBodyScopeFree(true); @@ -759,6 +766,18 @@ private bool IsLargeWithMultipleAssignment() { return counter.HasMultipleAssignment && counter.Calls > MaxMultipleAssignmentCalls; } + // A body that reads or writes a global and makes more than MaxMultipleAssignmentCalls calls keeps its scope, for the + // reason above: such bodies were all kept out of light frames until globals were let in, and the one measured lost as + // one - the prelude's String#__ir_split_lines__ (`$/' and some forty calls), whose light lambda was 17,890 bytes of IL + // against 7,652 with its scope, made `"a\nb\n".lines' 1.10 times slower (six alternating rounds, spread 4-6%). + private bool IsLargeWithGlobal() { + if (!LightGlobalsEnabled) { + return false; + } + var counter = WalkCalls(); + return counter.HasGlobal && counter.Calls > MaxMultipleAssignmentCalls; + } + // The names of the library methods of Kernel, BasicObject, Module, Enumerable, String, Symbol and Regexp that read their // caller's scope (binding, block_given?, respond_to?'s visibility, $~...). A `super' in a method of one of these names // most likely reaches one, and a light frame would then make its scope on every call, after the light site has @@ -809,6 +828,9 @@ private sealed class CallCounter : Walker { internal int Calls; internal bool HasMultipleAssignment; internal bool HasSuperCall; + internal bool HasGlobal; + + public override bool Enter(GlobalVariable/*!*/ node) { HasGlobal = true; return true; } // the walker visits only the left side of a multiple assignment: the calls of the right side count too public override bool Enter(ParallelAssignmentExpression/*!*/ node) { @@ -898,6 +920,9 @@ private string WhyNotLightFrameCandidate() { if (IsLargeWithMultipleAssignment()) { return "multiple assignment in a body of more than " + MaxMultipleAssignmentCalls + " calls"; } + if (IsLargeWithGlobal()) { + return "global variable in a body of more than " + MaxMultipleAssignmentCalls + " calls"; + } if (HasScopeReadingSuper()) { return "super in " + _name + " (the library method reads its caller's scope)"; } @@ -1050,6 +1075,16 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong if (isDefined != null && isDefined.Expression is InstanceVariable) { return true; } + // `$stdout', `$VERBOSE', `defined?($x)': the runtime's, read through the declaring scope (IsLightGlobal); + // RubyOps.IsDefinedGlobalVariable reads only the runtime from its scope, for any name + var global = node as GlobalVariable; + if (global != null) { + return IsLightGlobal(global) || why != null && Refuse(why, LightGlobalsEnabled ? + "GlobalVariable " + global.FullName + " (the frame's own)" : "GlobalVariable (IR_LIGHT_GLOBALS=0)"); + } + if (isDefined != null && isDefined.Expression is GlobalVariable && LightGlobalsEnabled) { + return true; + } var constant = node as ConstantVariable; if (constant != null) { return IsCachedConstant(constant) || Refuse(why, "ConstantVariable with an expression qualifier"); @@ -1060,7 +1095,8 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong if (!IsScopeFree(assignment.Right, blockLiterals, why)) { return false; } - if (assignment.Left is LocalVariable || assignment.Left is InstanceVariable) { + if (assignment.Left is LocalVariable || assignment.Left is InstanceVariable || + assignment.Left is GlobalVariable && IsLightGlobal((GlobalVariable)assignment.Left)) { return assignment.Operation == null || LightCallsEnabled || Refuse(why, "operator assignment (IR_LIGHT_CALLS=0)"); } // `o.x = v', `a[i] = v' (and their op-assigns): calls of x= and []= @@ -1354,6 +1390,10 @@ private static bool IsScopeFreeTarget(LeftValue/*!*/ target, bool blockLiterals, if (target is LocalVariable || target is InstanceVariable || target is Placeholder) { return true; } + var global = target as GlobalVariable; + if (global != null && IsLightGlobal(global)) { + return true; + } var compound = target as CompoundLeftValue; if (compound != null) { foreach (var nested in compound.LeftValues) { @@ -1377,6 +1417,17 @@ private static bool IsScopeFreeTarget(LeftValue/*!*/ target, bool blockLiterals, return why != null && Refuse(why, "multiple assignment to " + target.GetType().Name); } + /// + /// A global a light frame reads and writes without its scope: any but `$~' (the match) and `$_' (the last line read), which + /// live in the frame (RubyScope.GetInnerMostClosureScope), so that a method naming them keeps its scope as it would make it for + /// them anyway. Every other global is the runtime's (SpecialGlobalVariableInfo, GlobalVariableInfo). A name can still turn out + /// to denote one of the two - an alias, English.rb's `$LAST_MATCH_INFO' - which the frame finds out when it reads or writes it, + /// and then makes its scope (LightFrameRewriter.VisitGlobalVariableCall). + /// + private static bool IsLightGlobal(GlobalVariable/*!*/ global) { + return LightGlobalsEnabled && global.Name != "~" && global.Name != "_"; + } + // A, ::A, A::B::C - the reads ConstantVariable.MakeCachedRead makes - not {expr}::A private static bool IsCachedConstant(ConstantVariable/*!*/ constant) { var qualifier = constant.Qualifier; @@ -1458,7 +1509,8 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ BlockParameter = LightBlockGivenEnabled ? blockParameter : null, SuperModule = LightSuperEnabled ? ConstantValue(declaringModule) as RubyModule : null, SuperName = _name, - Handling = LightRescueEnabled + Handling = LightRescueEnabled, + Context = gen.Context }; var rewritten = rewriter.Visit(statements); if (LightFramesVerbose) { @@ -1533,6 +1585,10 @@ internal sealed class LightFrameRewriter : MSA.ExpressionVisitor { // scope they need (see VisitHandlingCall). Not a block's frame, whose body has none (MethodDefinition.IsScopeFree). internal bool Handling; + // The runtime the body is compiled in, if known: a global whose name already denotes a variable of the frame's when the + // body is compiled - English.rb's `$LAST_MATCH_INFO', required before - keeps the scope (see VisitGlobalVariableCall). + internal RubyContext Context; + // The OSR sites handed the declaring scope (see VisitMethodCall): marked as in a light frame once the body is one. internal readonly List/*!*/ OsrSites = new List(); @@ -1564,6 +1620,9 @@ private static int ScopeOperandIndex(MethodInfo/*!*/ method) { if (method == Methods.SetInstanceVariable) { return 2; } + if (LightGlobalsEnabled && method == Methods.IsDefinedGlobalVariable) { + return 0; + } if (LightHashEnabled && (method == Methods.MakeHash || method == Methods.MakeSymbolHash1 || method == Methods.MakeSymbolHash2 || method == Methods.MakeSymbolHash3)) { return 0; @@ -1684,6 +1743,68 @@ private MSA.Expression VisitHandlingCall(MSA.MethodCallExpression/*!*/ node) { return Ast.Call(node.Method, arguments); } + private static readonly MethodInfo/*!*/ _ReadLightGlobalVariable = typeof(RubyOps).GetMethod("ReadLightGlobalVariable"); + private static readonly MethodInfo/*!*/ _GetLightGlobalVariable = typeof(RubyOps).GetMethod("GetLightGlobalVariable"); + private static readonly MethodInfo/*!*/ _SetLightGlobalVariable = typeof(RubyOps).GetMethod("SetLightGlobalVariable"); + private static readonly FieldInfo/*!*/ _LightScopeRequired = typeof(RubyOps).GetField("LightScopeRequired"); + + /// + /// `$x', `$x ||= v', `$x = v' (RubyOps.ReadCachedGlobalVariable, GetCachedGlobalVariable, SetCachedGlobalVariable) in a light + /// frame: read and written by RubyOps.ReadLightGlobalVariable and its siblings, through the declaring scope, which has the + /// runtime. They do nothing and answer LightScopeRequired when the name denotes a variable of the frame's - `$~' or `$_' + /// under another name (an alias) - or when the scope may be read for something else (a trace_var handler, a Ractor's + /// isolation); the frame then makes its scope and does it again with the helper the body was compiled with, as a call + /// does whose rule reads the scope. The value assigned is evaluated once, before either. The frame keeps its stack check + /// (MakesCalls): some variables run Ruby code when they are read or assigned (ARGF.filename for $FILENAME, #respond_to? + /// for $stdout, the trace_var handlers), which may call the method again, as a constant read may call const_missing. + /// Null for any other call. + /// + private MSA.Expression VisitGlobalVariableCall(MSA.MethodCallExpression/*!*/ node) { + MethodInfo light; + int scopeIndex; + if (node.Method == Methods.ReadCachedGlobalVariable) { + light = _ReadLightGlobalVariable; + scopeIndex = 0; + } else if (node.Method == Methods.GetCachedGlobalVariable) { + light = _GetLightGlobalVariable; + scopeIndex = 0; + } else if (node.Method == Methods.SetCachedGlobalVariable) { + light = _SetLightGlobalVariable; + scopeIndex = 1; + } else { + return null; + } + if (node.Object != null || node.Arguments.Count != scopeIndex + 2 || !IsScope(node.Arguments[scopeIndex]) || + !(node.Arguments[scopeIndex + 1] is MSA.ConstantExpression)) { + return null; + } + // A name that denotes `$~' or `$_' now, an alias made before the method's first call, would make the scope on demand + // at every read or write: the frame makes it at its entry instead, as it did before. + var globalSite = ((MSA.ConstantExpression)node.Arguments[scopeIndex + 1]).Value as GlobalVariableSite; + IronRuby.Runtime.GlobalVariable current; + if (globalSite == null || Context != null && Context.TryGetGlobalVariable(globalSite.Name, out current) && current.ReadsScope) { + NeedsScope = true; + return node; + } + MakesCalls = true; + var site = node.Arguments[scopeIndex + 1]; + var declaringScope = AstUtils.Convert(_declaringScope, typeof(RubyScope)); + var lazyScope = AstUtils.Convert(_lazyScope, typeof(RubyScope)); + var result = Ast.Variable(typeof(object), "#global"); + if (scopeIndex == 0) { + return Ast.Block(new[] { result }, + Ast.Assign(result, Ast.Call(light, declaringScope, site)), + Ast.Condition(Ast.ReferenceEqual(result, Ast.Field(null, _LightScopeRequired)), Ast.Call(node.Method, lazyScope, site), result) + ); + } + var value = Ast.Variable(typeof(object), "#global-value"); + return Ast.Block(new[] { value, result }, + Ast.Assign(value, AstUtils.Convert(Visit(node.Arguments[0]), typeof(object))), + Ast.Assign(result, Ast.Call(light, value, declaringScope, site)), + Ast.Condition(Ast.ReferenceEqual(result, Ast.Field(null, _LightScopeRequired)), Ast.Call(node.Method, value, lazyScope, site), result) + ); + } + protected override MSA.Expression/*!*/ VisitMethodCall(MSA.MethodCallExpression/*!*/ node) { if (Handling) { var handling = VisitHandlingCall(node); @@ -1691,6 +1812,12 @@ private MSA.Expression VisitHandlingCall(MSA.MethodCallExpression/*!*/ node) { return handling; } } + if (LightGlobalsEnabled) { + var global = VisitGlobalVariableCall(node); + if (global != null) { + return global; + } + } // (a block's body, BlockDefinition.TransformLightCalls, has no flow-control frame of its own: _rfc is null) if (_rfc != null && node.Method == Methods.MethodYield && node.Arguments.Count == 3 && node.Arguments[0] == _scope) { // the raw scope variable, which is null unless a hook made the scope diff --git a/Src/Ruby/Runtime/Globals/GlobalVariable.cs b/Src/Ruby/Runtime/Globals/GlobalVariable.cs index 50b0875ca..9375bccf3 100644 --- a/Src/Ruby/Runtime/Globals/GlobalVariable.cs +++ b/Src/Ruby/Runtime/Globals/GlobalVariable.cs @@ -34,6 +34,13 @@ protected GlobalVariable() { /// public virtual bool IsDefined { get { return true; } } + /// + /// Whether reading or assigning the variable may use the scope it is given for more than its runtime, which a light frame + /// cannot give it: the frame hands the declaring scope (RubyOps.ReadLightGlobalVariable). A variable of a kind this assembly + /// does not know, a host's or a library's, is taken to. + /// + internal virtual bool ReadsScope { get { return true; } } + public abstract object GetValue(RubyContext/*!*/ context, RubyScope scope); public abstract void SetValue(RubyContext/*!*/ context, RubyScope scope, string/*!*/ name, object value); diff --git a/Src/Ruby/Runtime/Globals/GlobalVariableInfo.cs b/Src/Ruby/Runtime/Globals/GlobalVariableInfo.cs index 928b562c1..aea13605d 100644 --- a/Src/Ruby/Runtime/Globals/GlobalVariableInfo.cs +++ b/Src/Ruby/Runtime/Globals/GlobalVariableInfo.cs @@ -34,6 +34,10 @@ public override bool IsDefined { get { return _isDefined; } } + internal override bool ReadsScope { + get { return false; } + } + public override object GetValue(RubyContext/*!*/ context, RubyScope scope) { return _value; } diff --git a/Src/Ruby/Runtime/Globals/ReadOnlyGlobalVariableInfo.cs b/Src/Ruby/Runtime/Globals/ReadOnlyGlobalVariableInfo.cs index 3c7d8289a..bfeef1beb 100644 --- a/Src/Ruby/Runtime/Globals/ReadOnlyGlobalVariableInfo.cs +++ b/Src/Ruby/Runtime/Globals/ReadOnlyGlobalVariableInfo.cs @@ -22,6 +22,10 @@ public ReadOnlyGlobalVariableInfo(object value) { _value = value; } + internal override bool ReadsScope { + get { return false; } + } + public override object GetValue(RubyContext/*!*/ context, RubyScope scope) { return _value; } diff --git a/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs b/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs index 54e008160..80976a02c 100644 --- a/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs +++ b/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs @@ -25,6 +25,24 @@ internal SpecialGlobalVariableInfo(GlobalVariableId id) { _id = id; } + // $~ and the variables made from it, and $_: the innermost method's or eval's (RubyScope.GetInnerMostClosureScope), not the + // runtime's. Each of the rest reads the runtime only. + internal override bool ReadsScope { + get { + switch (_id) { + case GlobalVariableId.MatchData: + case GlobalVariableId.MatchLastGroup: + case GlobalVariableId.PreMatch: + case GlobalVariableId.PostMatch: + case GlobalVariableId.EntireMatch: + case GlobalVariableId.LastInputLine: + return true; + default: + return false; + } + } + } + /// /// $< is ARGF, which the standard library defines in Ruby - later than the context is /// built, so the constant is read when the variable is asked for rather than cached at diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 45a135cd9..eae8f814f 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3403,6 +3403,20 @@ internal object GetGlobalVariableValue(GlobalVariable/*!*/ variable, RubyScope s } } + /// + /// What SetGlobalVariable does for its name, to a variable a GlobalVariableSite found, minus the lookup: a light frame + /// decides from the variable that the scope it gives is enough (RubyOps.SetLightGlobalVariable), and a lookup made again + /// could find another one, aliased since. + /// + internal void SetGlobalVariableValue(GlobalVariable/*!*/ variable, RubyScope scope, string/*!*/ name, object value) { + lock (GlobalVariablesLock) { + variable.SetValue(this, scope, name, value); + } + if (_anyGlobalVariableTraced) { + FireGlobalVariableTraces(scope, name, value); + } + } + /// /// Runs the Kernel#trace_var handlers of a global that has just been assigned outside /// SetGlobalVariable (which runs them itself). diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index b02bda1b0..0df3ee308 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -3101,6 +3101,76 @@ public static object SetCachedGlobalVariable(object value, RubyScope/*!*/ scope, return value; } + /// + /// ReadCachedGlobalVariable in a light frame (MethodDefinition.LightFrameRewriter.VisitGlobalVariableCall), given the + /// declaring scope, which has the frame's runtime and nothing else of the frame's. LightScopeRequired, having read nothing, + /// when the variable would read more of its scope than the runtime - `$~' or `$_' under another name, an alias such as + /// English.rb's `$LAST_MATCH_INFO' - or a non-main Ractor's isolation may: the frame then makes its scope and calls + /// ReadCachedGlobalVariable with it. What is read is the variable the decision was made for, not one looked up again, + /// which another thread may have aliased in between. + /// + public static object ReadLightGlobalVariable(RubyScope/*!*/ declaringScope, GlobalVariableSite/*!*/ site) { + var context = declaringScope.RubyContext; + if (context.RactorsStarted && !site.IsCoreLibrary && RactorIsolation.IsNonMain(context)) { + return LightScopeRequired; + } + var variable = site.GetVariable(context); + var plain = variable as GlobalVariableInfo; + if (plain != null) { + return plain.Value; + } + if (variable != null) { + return variable.ReadsScope ? LightScopeRequired : context.GetGlobalVariableValue(variable, declaringScope); + } + if (context.Verbose is bool && (bool)context.Verbose) { + context.ReportWarning(String.Format("global variable '${0}' not initialized", site.Name), true); + } + return null; + } + + /// GetCachedGlobalVariable in a light frame: see ReadLightGlobalVariable. + public static object GetLightGlobalVariable(RubyScope/*!*/ declaringScope, GlobalVariableSite/*!*/ site) { + var context = declaringScope.RubyContext; + if (context.RactorsStarted && !site.IsCoreLibrary && RactorIsolation.IsNonMain(context)) { + return LightScopeRequired; + } + var variable = site.GetVariable(context); + var plain = variable as GlobalVariableInfo; + if (plain != null) { + return plain.Value; + } + if (variable != null) { + return variable.ReadsScope ? LightScopeRequired : context.GetGlobalVariableValue(variable, declaringScope); + } + return null; + } + + /// + /// SetCachedGlobalVariable in a light frame: see ReadLightGlobalVariable. LightScopeRequired, having assigned nothing, also + /// while any trace_var handler is registered (a String handler is evaluated in a scope), and for a name that denotes no + /// variable yet, which SetGlobalVariable creates by its name. An ordinary global is assigned in place, any other variable + /// that reads no more than the runtime through the general path, minus the lookup by name. + /// + public static object SetLightGlobalVariable(object value, RubyScope/*!*/ declaringScope, GlobalVariableSite/*!*/ site) { + var context = declaringScope.RubyContext; + if (context.AnyGlobalVariableTraced || context.RactorsStarted && !site.IsCoreLibrary && RactorIsolation.IsNonMain(context)) { + return LightScopeRequired; + } + var variable = site.GetVariable(context); + var plain = variable as GlobalVariableInfo; + if (plain != null) { + plain.Assign(value); + // a handler registered since the test above: it is evaluated in a scope of its own (KernelOps.TraceVariable) + context.GlobalVariableAssigned(declaringScope, site.Name, value); + return value; + } + if (variable == null || variable.ReadsScope) { + return LightScopeRequired; + } + context.SetGlobalVariableValue(variable, declaringScope, site.Name, value); + return value; + } + [Emitted] public static bool IsDefinedGlobalVariable(RubyScope/*!*/ scope, string/*!*/ name) { GlobalVariable variable; diff --git a/Util/bench/global-shapes.rb b/Util/bench/global-shapes.rb new file mode 100644 index 000000000..0a2e19ce6 --- /dev/null +++ b/Util/bench/global-shapes.rb @@ -0,0 +1,97 @@ +# What a method that reads or writes a global variable costs, light frame or not (MethodDefinition.IsLightGlobal, +# IR_LIGHT_GLOBALS): ns per call of the method, the caller a `while' loop. The switch is the third arm: +# +# ruby Util/perf/ab.rb -i Util/bench/global-shapes.rb "off=env IR_LIGHT_GLOBALS=0 IR_CONFIG=Release ./ir.sh" \ +# "on=env IR_CONFIG=Release ./ir.sh" +# +# read, write, opasgn, stdout, verbose, plus, dflt and defd are light with the switch on; puts and lines are the prelude's +# Kernel#puts (it reads $stdout) and String#lines (its helper reads $/); alias reads English.rb's kind of alias of $~, which +# makes the frame's scope on demand on every call (the price of the fallback); ivar and tilde are the same in both arms +# (a light frame without a global; a method that names $~). +$stdout.sync = true + +$g = 1 +$gw = 0 +alias $g_last_match $~ + +class H + def read = $g + def write(v) = $gw = v + def opasgn = $gw += 1 + def stdout = $stdout.equal?(STDOUT) ? 1 : 0 + def verbose = $VERBOSE ? 1 : 2 + def plus(x) = x + $g + def dflt(sep = $/) = sep.size + def defd = defined?($g) ? 1 : 0 + def alias_read = $g_last_match ? 1 : 0 + + def ivar = @x ? 1 : 2 + def tilde; $~ ? 1 : 0; end +end + +class NullOut + def write(*a) = a.size +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the seven sections as the +# time is. See Util/perf/instructions.rb. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-12s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +h = H.new +N = (ENV['N'] || 500_000).to_i +s = "a\nb\n" + +t("read", N) { |n| i = 0; c = 0; while i < n; c += h.read; i += 1; end; c } +t("write", N) { |n| i = 0; c = 0; while i < n; c += h.write(1); i += 1; end; c } +t("opasgn", N) { |n| $gw = 0; i = 0; while i < n; h.opasgn; i += 1; end; $gw } +t("stdout", N) { |n| i = 0; c = 0; while i < n; c += h.stdout; i += 1; end; c } +t("verbose", N) { |n| i = 0; c = 0; while i < n; c += h.verbose; i += 1; end; c } +t("plus", N) { |n| i = 0; c = 0; while i < n; c += h.plus(i & 3); i += 1; end; c } +t("dflt", N) { |n| i = 0; c = 0; while i < n; c += h.dflt; i += 1; end; c } +t("defd", N) { |n| i = 0; c = 0; while i < n; c += h.defd; i += 1; end; c } +t("alias", N) { |n| i = 0; c = 0; while i < n; c += h.alias_read; i += 1; end; c } +t("puts", N / 5) do |n| + old = $stdout + $stdout = NullOut.new + begin + i = 0 + while i < n + puts i + i += 1 + end + ensure + $stdout = old + end + n +end +t("lines", N / 5) { |n| i = 0; c = 0; while i < n; c += s.lines.size; i += 1; end; c } +t("ivar", N) { |n| i = 0; c = 0; while i < n; c += h.ivar; i += 1; end; c } +t("tilde", N) { |n| i = 0; c = 0; while i < n; c += h.tilde; i += 1; end; c } diff --git a/Util/global-light-matrix.rb b/Util/global-light-matrix.rb new file mode 100644 index 000000000..130445541 --- /dev/null +++ b/Util/global-light-matrix.rb @@ -0,0 +1,340 @@ +# Differential matrix for global variables in a method that runs without a scope (a light frame, +# MethodDefinition.TransformLightFrame). An ordinary global, and every special one but the regex +# match and the last input line, is the runtime's: `$x', `$x = v', `$x ||= v' and `defined?($x)' are +# read and written through the declaring scope there (LightFrameRewriter.VisitGlobalVariableCall). +# A name that turns out to denote `$~' or `$_' - an alias, English.rb's `$LAST_MATCH_INFO' - makes +# the frame's scope on demand and is read again with it, and so is any global while a trace_var +# handler is registered. Run it under CRuby and under ./ir.sh with the shortcut on and off, and diff: +# +# ruby Util/global-light-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/global-light-matrix.rb > /tmp/on.txt 2>&1 +# IR_LIGHT_GLOBALS=0 ./ir.sh Util/global-light-matrix.rb > /tmp/off.txt 2>&1 +# IR_LIGHT_FRAMES=0 ./ir.sh Util/global-light-matrix.rb > /tmp/noframes.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt && diff /tmp/mri.txt /tmp/noframes.txt +# +# Every probe runs N times and reports each distinct answer once, in the order they first appear, so +# the interpreted body, the compiled one and a site whose rule is already bound all meet the case. +# +# IR_LIGHT_FRAMES=why ./ir.sh Util/global-light-matrix.rb 2>&1 >/dev/null | grep -a '^\[light\]' +# +# says which of the methods below are light frames. + +N = 3000 + +def t(label) + print label.ljust(58), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 60]}" + end +end + +# ---------------------------------------------------------------- 1. reads of the runtime's globals + +$g_plain = 10 +def r_plain; $g_plain; end +def r_plain_plus(x); $g_plain + x; end +def r_stdout; $stdout.equal?(STDOUT); end +def r_stderr; $stderr.equal?(STDERR); end +def r_verbose; $VERBOSE; end +def r_debug; $DEBUG; end +def r_rs; $/; end +def r_fs; $;; end +def r_ofs; $,; end +def r_program; $0 == $PROGRAM_NAME; end +def r_load_path; [$LOAD_PATH.equal?($:), $LOAD_PATH.class]; end +def r_loaded; $LOADED_FEATURES.equal?($"); end +def r_pid; $$ == Process.pid; end +def r_bang; $!; end +def r_at; $@; end +def r_status; $?.class; end +def r_lineno; $.; end +def r_undefined; $g_never_assigned_anywhere; end +def r_two; [$g_plain, $VERBOSE]; end +def r_in_while; i = 0; s = 0; while i < 3; s += $g_plain; i += 1; end; s; end +def r_in_if(x); x > 0 ? $g_plain : -$g_plain; end +def r_minus_w; $-w; end +def r_star; $*.equal?(ARGV); end + +t('a plain global') { r_plain } +t('a plain global in an expression') { |i| r_plain_plus(i % 2) } +t('$stdout') { r_stdout } +t('$stderr') { r_stderr } +t('$VERBOSE') { r_verbose } +t('$DEBUG') { r_debug } +t('$/') { r_rs } +t('$;') { r_fs } +t('$,') { r_ofs } +t('$0 == $PROGRAM_NAME') { r_program } +t('$LOAD_PATH') { r_load_path } +t('$LOADED_FEATURES') { r_loaded } +t('$$') { r_pid } +t('$! outside a rescue') { r_bang } +t('$@ outside a rescue') { r_at } +t('$?') { system('true'); r_status } +t('$.') { r_lineno.class } +t('a global never assigned') { r_undefined } +t('two globals') { r_two } +t('in a while') { r_in_while } +t('in a conditional') { |i| r_in_if(i % 2 == 0 ? 1 : -1) } +t('$-w') { r_minus_w } +t('$* is ARGV') { r_star } + +# ---------------------------------------------------------------- 2. writes + +def w_plain(v); $g_w = v; end +def w_plain_read(v); $g_w = v; $g_w + 1; end +def w_op(x); $g_op += x; end +def w_or(v); $g_or ||= v; end +def w_and(v); $g_and &&= v; end +def w_two(a, b); $g_a = a; $g_b = b; [$g_a, $g_b]; end +def w_swap; $g_a, $g_b = $g_b, $g_a; [$g_a, $g_b]; end +def w_value(v); ($g_val = v).to_s; end +def w_stdout(o); $stdout = o; end +def w_verbose(v); $VERBOSE = v; end +def w_readonly_bang; $! = 1; end +def w_readonly_load_path; $LOAD_PATH = []; end +def w_lineno(v); $. = v; $.; end +def w_stdout_bad; $stdout = 5; end +def w_new_global(i); $g_new_global = i; end + +t('assign a plain global') { |i| w_plain(i % 3); $g_w } +t('assign and read back') { |i| w_plain_read(i % 3) } +$g_op = 0 +t('op-assign') { |i| w_op(1); $g_op % 7 } +t('||= unset, then set') { |i| $g_or = nil if i % 2 == 0; w_or(i % 3) } +t('&&= set, then nil') { |i| $g_and = (i % 2 == 0) ? 1 : nil; w_and(:x) } +t('two writes, two reads') { |i| w_two(i % 2, :b) } +$g_a = 1; $g_b = 2 +t('parallel assignment of two globals') { w_swap } +t('the value of an assignment') { |i| w_value(i % 2) } +t('$stdout to another writer and back') do |i| + out = Object.new + def out.write(*a) = a.sum(&:size) + w_stdout(out) + r = $stdout.equal?(out) + w_stdout(STDOUT) + [r, $stdout.equal?(STDOUT)] +end +t('$VERBOSE to nil and back') { |i| old = $VERBOSE; w_verbose(nil); r = $VERBOSE; w_verbose(old); [r, $VERBOSE == old] } +t('$! is read-only') { w_readonly_bang } +t('$LOAD_PATH is read-only') { w_readonly_load_path } +t('$. is an Integer') { |i| w_lineno(i % 2) } +t('$stdout to something without write') { w_stdout_bad } +t('a global made by the method') { |i| w_new_global(i % 2); $g_new_global } + +# ---------------------------------------------------------------- 3. the frame's own: $~, $_ and their aliases + +alias $g_match $~ +alias $g_line $_ + +def m_tilde; 'ab' =~ /b/; $~ && $~[0]; end +def m_alias_after_match; 'xy' =~ /y/; $g_match && $g_match[0]; end +def m_alias_no_match; $g_match; end +def m_alias_set_line(v); $g_line = v; $_; end +def m_line_alias_read; $_ = 'own'; $g_line; end +def m_alias_line_unset; $g_line; end +def m_alias_print(v); $g_line = v; print; end +def m_alias_then_call; $g_line = 'L'; [1].map { $_ }; end +def m_alias_both_ways; 'q' =~ /q/; a = $g_match[0]; $g_match = nil; [a, $~]; end + +'top' =~ /top/ +$_ = 'top line' +t('$~ after a match of the method') { m_tilde } +t('alias of $~ after a match of the method') { m_alias_after_match } +t('alias of $~, no match of its own') { m_alias_no_match } +t('the caller still has its own $~') { m_alias_no_match; $~[0] } +t('alias of $_ assigned, $_ read') { |i| m_alias_set_line(i % 2 == 0 ? 'a' : 'b') } +t('$_ assigned, alias read') { m_line_alias_read } +t('alias of $_, nothing assigned in the method') { m_alias_line_unset } +t('the caller keeps its $_') { m_alias_set_line('callee'); $_ } +$stdout.sync = true +t('print with no argument prints the alias-assigned $_') { |i| m_alias_print(i % 1000 == 0 ? "printed\n" : ''); :ok } +t('a block reads the $_ the alias assigned') { m_alias_then_call } +t('alias of $~ read and assigned') { m_alias_both_ways } + +# the same with the Regexp in a constant, which keeps the method a light frame: the match is stored through the scope the +# call makes on demand, and the alias then reads that scope +RE_Y = /y/ +RE_Q = /q/ +RE_B = /b/ +RE_T = /t/ +def m_light_alias_after_match; 'xy' =~ RE_Y; $g_match && $g_match[0]; end +def m_light_alias_match_method; RE_Y.match('zy'); $g_match.pre_match; end +def m_light_alias_both_ways; 'q' =~ RE_Q; a = $g_match[0]; $g_match = nil; [a, $g_match]; end +def m_light_alias_no_match_after_call; [1].size; $g_match; end +def m_light_threads; 'tt' =~ RE_T; [Thread.new { $g_match }.value, $g_match[0]]; end +def m_light_block_alias; 'bb' =~ RE_B; [1].map { $g_match[0] }; end +def m_light_line_alias_write_then_print(v); $g_line = v; print; $g_line; end + +t('light: alias of $~ after =~ with a constant') { m_light_alias_after_match } +t('light: alias of $~ after Regexp#match') { m_light_alias_match_method } +t('light: alias of $~ read and assigned') { m_light_alias_both_ways } +t('light: alias of $~ after an unrelated call') { m_light_alias_no_match_after_call } +t('light: the caller\'s $~ after those') { $~[0] } +t('light: another thread, then the method\'s own') { m_light_threads } +t('light: a block reads the alias of the method\'s $~') { m_light_block_alias } +t('light: alias of $_ written, print, read') { |i| m_light_line_alias_write_then_print(i % 1000 == 0 ? "p\n" : '') } +t('light: the caller\'s $_ after that') { $_ } + +# The same once more, with the methods compiled before the names became aliases: a name that already denotes $~ or $_ +# when a method is first called keeps that method's scope (LightFrameRewriter.VisitGlobalVariableCall), so these are the +# ones that find out at the read or the write and make the scope then. +def l_after_match; 'xy' =~ RE_Y; $g_late_match && $g_late_match[0]; end +def l_match_method; RE_Y.match('zy'); $g_late_match.is_a?(MatchData) ? $g_late_match.pre_match : $g_late_match; end +def l_both_ways; 'q' =~ RE_Q; a = $g_late_match && $g_late_match[0]; $g_late_match = nil; [a, $g_late_match]; end +def l_no_match_after_call; [1].size; $g_late_match; end +def l_threads; 'tt' =~ RE_T; [Thread.new { $g_late_match }.value, $g_late_match && $g_late_match[0]]; end +def l_block; 'bb' =~ RE_B; [1].map { $g_late_match && $g_late_match[0] }; end +def l_line_write_then_print(v); $g_late_line = v; print; $g_late_line; end +def l_line_read; $g_late_line; end +$g_late_match = :plain +$g_late_line = '' +before = [l_after_match, l_match_method, l_both_ways, l_no_match_after_call, l_threads, l_block, l_line_write_then_print(''), l_line_read] +p before +alias $g_late_match $~ +alias $g_late_line $_ +t('late: alias of $~ after =~ with a constant') { l_after_match } +t('late: alias of $~ after Regexp#match') { l_match_method } +t('late: alias of $~ read and assigned') { l_both_ways } +t('late: alias of $~ after an unrelated call') { l_no_match_after_call } +t('late: the caller\'s $~ after those') { $~[0] } +t('late: another thread, then the method\'s own') { l_threads } +t('late: a block reads the alias of the method\'s $~') { l_block } +t('late: alias of $_ written, print, read') { |i| l_line_write_then_print(i % 1000 == 0 ? "lp\n" : '') } +t('late: alias of $_ read, nothing assigned') { l_line_read } +t('late: the caller\'s $_ after that') { $_ } + +def m_half; $g_half; end +$g_half = :plain +t('a global aliased to $~ half way') do |i| + eval('alias $g_half $~') if i == N / 2 + 'zz' =~ /z/ + r = m_half + r.is_a?(MatchData) ? :match_of_the_method_or_nil : r +end +eval('alias $g_half $g_plain') +t('and aliased to a plain global after') { m_half } + +def m_threads; 'tt' =~ /t/; Thread.new { $g_match }.value; end +t('another thread has no $~ of the method') { m_threads } + +# ---------------------------------------------------------------- 4. trace_var + +$g_traced_log = [] +def tr_assign(v); $g_traced = v; end +def tr_read; $g_traced; end +trace_var(:$g_traced) { |v| $g_traced_log << v if $g_traced_log.size < 5 } +t('assigning a traced global fires the handler') { |i| tr_assign(i % 4); tr_read } +p $g_traced_log +untrace_var(:$g_traced) +t('and not after untrace_var') { |i| tr_assign(:untraced); $g_traced_log.size } + +$g_cmd_log = [] +trace_var(:$g_traced2, '$g_cmd_log << $g_traced2 if $g_cmd_log.size < 3') +def tr_assign2(v); $g_traced2 = v; end +t('a String handler') { |i| tr_assign2(i % 3); $g_cmd_log.size } +p $g_cmd_log +untrace_var(:$g_traced2) + +def tr_recursive(v); $g_rec = v; end +trace_var(:$g_rec) { |v| tr_recursive(v * 2) if v < 100 } +t('a handler that assigns the variable it traces') { |i| tr_recursive(1); $g_rec } +untrace_var(:$g_rec) + +# ---------------------------------------------------------------- 5. defined? + +def d_plain; defined?($g_plain); end +def d_never; defined?($g_defined_never); end +def d_stdout; defined?($stdout); end +def d_tilde_alias; defined?($g_match); end +t('defined?($g) of a set global') { d_plain } +t('defined?($g) of a global never set') { d_never } +t('defined?($stdout)') { d_stdout } +t('defined? of an alias of $~') { d_tilde_alias } + +# ---------------------------------------------------------------- 6. other ways in, and what the frame still does + +class GHost + def ivar_and_global; @x = $g_plain; [@x, $VERBOSE]; end + def self.singleton; $g_plain * 2; end + define_method(:defined_by_block) { $g_plain + 1 } +end +module GFun + module_function + def fun; $g_plain - 1; end +end + +def o_binding; v = $g_plain; b = binding; b.local_variable_get(:v); end +def o_locals; v = $g_plain; local_variables; end +def o_eval; v = $g_plain; eval('v + $g_plain'); end +def o_block; [1, 2].map { |x| x + $g_plain }; end +def o_proc; pr = proc { $g_plain }; pr; end +def o_raise; raise ArgumentError, "g=#{$g_plain}"; end +def o_rescue; begin; raise 'x'; rescue; $!.message; end; end +def o_rescue_at; begin; raise 'y'; rescue; $@.class; end; end +def o_caller; $g_plain; caller(0, 1)[0][/'.*'/]; end +def o_method_name; $g_plain; __method__; end +def o_deep(n); $g_depth = n; o_deep(n + 1); end +def o_puts(v); $stdout.write("#{v}\n"); end + +t('in a method of a class') { GHost.new.ivar_and_global } +t('a singleton method') { GHost.singleton } +t('define_method') { GHost.new.defined_by_block } +t('module_function') { GFun.fun } +t('send') { send(:r_plain) } +t('__send__') { __send__(:r_plain) } +t('public_send of a public method') { GHost.new.public_send(:ivar_and_global) } +t('Method#call') { method(:r_plain).call } +t('bind_call') { Object.instance_method(:r_plain).bind_call(self) } +t('binding after a read') { o_binding } +t('local_variables after a read') { o_locals } +t('eval after a read') { o_eval } +t('a block reading a global') { o_block } +t('a proc called after the method returned') { o_proc.call } +t('raise with a global in the message') { begin; o_raise; rescue => e; e.message; end } +t('$! in a rescue of the method') { o_rescue } +t('$@ in a rescue of the method') { o_rescue_at } +t('caller') { o_caller } +t('__method__') { o_method_name } +t('a million deep') { |i| i == 0 ? (begin; o_deep(0); rescue SystemStackError; :stack_error; end) : :skipped } +t('$stdout.write and Kernel#puts to a writer') do |i| + buf = [] + out = Object.new + out.define_singleton_method(:write) { |*a| buf.concat(a); a.sum(&:size) } + old = $stdout + $stdout = out + begin + o_puts(i % 2) + puts 'via Kernel#puts' + ensure + $stdout = old + end + buf +end + +# ---------------------------------------------------------------- 7. a light block + +def lb_each; s = 0; [1, 2, 3].each { |x| s += x * $g_plain }; s; end +def lb_write; [1, 2].each { |x| $g_lb = x }; $g_lb; end +def lb_alias; 'bb' =~ /b/; [1].map { $g_match[0] }; end +t('a block reading a global') { lb_each } +t('a block writing a global') { lb_write } +t('a block reading the alias of the method\'s $~') { lb_alias } + +# ---------------------------------------------------------------- 8. tracing + +def tp_target; $g_plain; end +calls = [] +tp = TracePoint.new(:call) { |x| calls << x.method_id if x.method_id == :tp_target && calls.size < 2 } +tp.enable +t('a TracePoint for :call') { tp_target } +tp.disable +p calls +t('after the TracePoint is disabled') { tp_target } From 04875d7775e4288f951c149ab55414fa1e740135 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:52:38 +0000 Subject: [PATCH 008/439] Ledger: globals in light frames (perf/lglobal), census only Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..f57aae65c 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -824,6 +824,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has whose call does not); `defined?(@x)` is refused. A method with both a literal block and a passed one still makes its scope for the passed one's call (LightScopeCall leaves calls with a block to BlockLiterals). + Global variables went in in round thirty-seven (perf/lglobal, `IR_LIGHT_GLOBALS`, + `Util/global-light-matrix.rb`, see Landed): every name but `$~` and `$_`; a global in a body + of more than 24 calls still keeps its scope (the masgn limit, measured again on + `String#__ir_split_lines__`). 10. **`!=` outside the method JIT is two dispatches**: `BasicObject#!=` calls `==` through a site shared by every `!=` in the runtime, so that site is polymorphic. 2.9% @@ -1384,6 +1388,57 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - + census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, + `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, + on every call of `puts`). Only `$~` and `$_` (and what is derived from `$~`) live in the frame + (RubyScope.GetInnerMostClosureScope); every other global is the runtime's (SpecialGlobalVariableInfo, + GlobalVariableInfo). So a light frame now reads and writes any global but those two names through + the declaring scope: `RubyOps.ReadLightGlobalVariable`, `GetLightGlobalVariable` and + `SetLightGlobalVariable` take the place of the cached helpers (LightFrameRewriter.VisitGlobalVariableCall), + and `defined?($x)` hands `IsDefinedGlobalVariable` the declaring scope. A name can still denote `$~` or + `$_` - an alias, English.rb's `$LAST_MATCH_INFO` - so the helpers decide from the variable the site + finds (`GlobalVariable.ReadsScope`, true for a kind this assembly does not know) and answer + `LightScopeRequired`, having done nothing, when it would read the frame; the frame then makes its + scope and does it again with the cached helper, the value assigned evaluated once. The same while a + trace_var handler is registered, for a non-main Ractor, and for an assignment that creates the + global. What is read or assigned is the variable the decision was made for + (`RubyContext.SetGlobalVariableValue`), not one looked up again, which another thread may have + aliased in between. A name that already denotes `$~` or `$_` when the body is compiled keeps the + scope (the rewriter is given the runtime): reading English's alias light made the scope at every + read, 1.43x. The frame keeps its stack check: `$FILENAME` asks ARGF.filename, `$stdout = o` asks + `o.respond_to?(:write)`, and a trace_var handler runs Ruby, any of which may call the method again. + A global in a body of more than 24 calls keeps its scope (the masgn limit): `String#__ir_split_lines__` + (`$/` and some forty calls) was 17,890 bytes of IL light against 7,652 with its scope, and + `"a\nb\n".lines` 1.10x slower in six alternating rounds alone; 25 methods are held back by it. + `IR_LIGHT_GLOBALS=0` turns it off. + Light frames 91.7% -> 92.6% (26,019 -> 26,257), light blocks unchanged, JIT unchanged (Src/StdLib + + AWFY, 28,376 methods; 238 methods moved up, none down). Of the prelude: Kernel#puts, + Exception.to_tty?, Process.last_status, Process::Status.wait, GC::Profiler.report, + Enumerator::Generator#initialize; none of AWFY's. `census.rb -c` on traces of + `Util/bench/app-shapes.rb` (920 methods called) and of the matrix (175): light frames 0 differ; + declined 29 and specialized 115 on both trees. + Timed (`ab.rb -r 6`, `Util/bench/global-shapes.rb`, pinned, load 0.5-1.8; this container has no + perf counters, so no `-i`), ns a call, off -> on: `defined?($g)` 91.7 -> 60.4 (0.66), `def m(sep = + $/)` 94.1 -> 63.9 (0.68), `$stdout.equal?(STDOUT)` 95.6 -> 72.0-83.9 (0.71-0.88), `$VERBOSE` 79.9 -> + 72.0 (0.84-0.90), `x + $g` 80.0 -> 47.9-71.9 (0.56-0.90), `puts` to a null writer alone 358.7 -> + 316.4 (0.88, overlap); `$g` alone and `$g = v` are compiled by the method JIT either way (overlap); + controls (an ivar, a method that names `$~`) overlap. `lines` and the alias read looked 1.3-1.5x + slower late in the sequential script and are the same alone (0.97, 1.00) and as a pair (the same + minimum on both trees): a state of the process, as round eight describes. + Checked: `Util/global-light-matrix.rb` (new: reads and writes of plain and special globals, + read-only ones, `$stdout` to a writer and to something without #write, `||=`, `&&=`, op-assign, + parallel assignment; `$~`, `$_` and aliases of them made before and after the methods were compiled, + in a block, in another thread, with print; trace_var with a block, a String and a handler that + assigns its own variable; defined?; send, bind_call, define_method, binding, eval, raise, `$!` in a + rescue, caller, a million deep, TracePoint) prints CRuby's output on the baseline and on the + candidate as built, `IR_LIGHT_GLOBALS=0`, `IR_LIGHT_FRAMES=0`, `IR_PARKED_SCOPES=0`, `-X:NoJIT + -X:NoOSR`, `-X:NoJITCalls` and the R2R host. gate-matrices.rb on 14 matrices (global-light, + block-given, block-scope-reuse, jit, keyword-light, light-rest, loop-light, masgn, hot-shapes, + regex-light, rescue-light, shared-rule-light, splat-pass, super-light) in those seven modes: PASS, + 90 same, 8 baseline (hot-shapes in every mode and regex-light under R2R, as on master). + `Method_LightFrameGlobal1` (new) and 27 named global tests pass. + - **perf/first-bind (2026-11-26) - what a first bind costs, split; light-scope sites call library methods through a dispatcher for their first calls (gap 26).** The split (master 4bae83f3, R2R host with the startup library; `IR_BIND_TRACE`, `IR_PHASE_TIMES`, perf with jitdump classing From ba4da2f1f1a577e9cc6c33705a3bfb0799341ab9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:03:05 +0000 Subject: [PATCH 009/439] Census: walk into a begin/rescue/ensure the screen has refused In its collect-all mode (JitScreen.CollectAll, set only by the census) the screen noted a Body with rescue, else or ensure clauses and returned without walking the protected part, the clauses' class lists and statements, or the else and ensure statements. Every call inside was uncounted, so "JIT never, one thing only: Body 461" listed methods full of calls (lstat, udpsock.bind, path2class) as if taking the clauses alone would let them through. The census's screen now walks them after the refusal. The real screen still stops at the first refusal and never reaches the new code. Every verdict is unchanged (census.rb -d against master: 0 methods changed; -c on a Json trace: 59 agree, 0 differ); Body alone is 30 methods, not 461. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 6b8ce93ec..39b24408d 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -3159,15 +3159,34 @@ private bool No(object/*!*/ node) { /// Mirrors JitCompiler.EmitBody. private bool WalkBody(Body/*!*/ body) { if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { - return No(body); + return No(body) && WalkClausesForCensus(body, 0); } return WalkStatements(body.Statements); } + /// + /// The census's screen (CollectAll) goes on into a body it has refused for its clauses: what the protected part, the + /// rescue clauses (their class lists too), else and ensure hold would be refused as well, and a refusal of the body + /// alone must mean that taking the clauses lets the method through. The real screen stops at No and never gets here. + /// + private bool WalkClausesForCensus(Body/*!*/ body, int prologueLength) { + if (_all == null) { return false; } + for (int i = prologueLength; i < body.Statements.Count; i++) { Walk(body.Statements[i]); } + if (body.RescueClauses != null) { + foreach (var clause in body.RescueClauses) { + foreach (var type in clause.Types) { Walk(type); } + WalkStatements(clause.Statements); + } + } + WalkStatements(body.ElseStatements); + WalkStatements(body.EnsureStatements); + return true; + } + /// Mirrors JitCompiler.EmitBody of a method with keywords: the prologue is not emitted. private bool WalkMethodBody(Body/*!*/ body, int prologueLength) { if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { - return No(body); + return No(body) && WalkClausesForCensus(body, prologueLength); } for (int i = prologueLength; i < body.Statements.Count; i++) { if (!Walk(body.Statements[i])) { return false; } From 7b73450d8f933646c96799cf0ba452f25c7853fe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:03:06 +0000 Subject: [PATCH 010/439] Ledger: a typed rescue/ensure in the method JIT, rejected; rescue matrix Gap 22's JIT half. With the census fixed, Body is the only refusal in 30 methods, all cold I/O and protocol wrappers whose protected part is a call. A handler as a deopt to the generic body re-runs the method from the top, so it is sound only for a protected part with no call (an exception out of a call may follow anything the callee did): one method of 28,376. Not implemented; the ledger says what a handler emitted in the typed body needs. Util/jit-rescue-matrix.rb: 33 hot probes of rescue, ensure, else, retry, the modifier, $!, cause, throw and Timeout through a handler, effects before a raise. It prints CRuby 4.0's output on master with the JIT on, with -X:NoJIT -X:NoOSR, -X:NoJITCalls and IR_LIGHT_FRAMES=0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/jit-rescue-matrix.rb | 302 ++++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 44 ++++++ 2 files changed, 346 insertions(+) create mode 100644 Util/jit-rescue-matrix.rb diff --git a/Util/jit-rescue-matrix.rb b/Util/jit-rescue-matrix.rb new file mode 100644 index 000000000..c81839634 --- /dev/null +++ b/Util/jit-rescue-matrix.rb @@ -0,0 +1,302 @@ +# Differential matrix for `begin`/`rescue`/`else`/`ensure` in methods the method JIT could +# take (-X:JIT, Src/Ruby/Runtime/Jit/; gap 22 in Util/perf/LEDGER.md). Run under CRuby and +# under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-rescue-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-rescue-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-rescue-matrix.rb > /tmp/nojit.txt +# IR_LIGHT_FRAMES=0 ./ir.sh Util/jit-rescue-matrix.rb > /tmp/nolight.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt && diff /tmp/mri.txt /tmp/nolight.txt +# +# Every method is called past the JIT's thresholds with the types it would be specialized +# for and raises on some of those calls, so that a typed body which takes the handler is +# entered both ways. The traps are the ones a deopt to the generic body falls into: an +# effect before the raise must happen once (the generic body runs from the top), the +# class list of a rescue is evaluated after the inner ensure clauses have run, `$!` is +# set in the handler and restored after it, `retry` re-runs the protected part only, an +# `ensure` runs once whether the body returns, raises, throws or is timed out. + +def t(label) + print label.ljust(56), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + acc = 0 + while i < n + v = yield i + acc += v if v.is_a?(Integer) + i += 1 + end + acc +end + +class P + def initialize; @n = 0; @e = 0; @log = []; end + attr_reader :n, :e, :log + + # 1. a pure protected part, never raising + def pure(x) + begin + x + 1 + rescue StandardError + 0 + end + end + + # 2. a pure protected part that raises on some calls (ZeroDivisionError) + def div(x) + begin + 100 / x + rescue ZeroDivisionError + -1 + end + end + + # 3. an effect before the raise: the write must happen once per call + def eff(x) + @n += 1 + begin + @n += 1 + 100 / x + rescue ZeroDivisionError + @n += 10 + -1 + end + end + + # 4. retry: the protected part runs again, what came before it does not + def ret(x) + @n += 1 + tries = 0 + begin + tries += 1 + 100 / (x - tries + 2) + rescue ZeroDivisionError + retry if tries < 3 + -tries + end + end + + def klasses + @log << :klasses + ZeroDivisionError + end + + # 5. a rescue class list that is a method call: evaluated only when something is raised + def klist(x) + begin + 100 / x + rescue klasses + -1 + end + end + + # 6. ensure, with a return in the body + def ens_ret(x) + begin + return x * 2 if x.odd? + x + ensure + @e += 1 + end + end + + # 7. a return in the ensure clause swallows the exception + def ens_swallow(x) + begin + 100 / x + ensure + return -7 if x == 0 + end + end + + # 8. $! in the handler and after it + def bang(x) + begin + 100 / x + rescue ZeroDivisionError + $!.class.name.size + end + end + + def callee(x) + @log << x if x % 50 == 0 + raise ArgumentError, "big" if x > 250 + x + end + + # 9. an exception from a callee that made an effect before raising + def from_callee(x) + begin + callee(x) + 1 + rescue ArgumentError + -1 + end + end + + # 10. a rescue modifier + def modifier(x) + (100 / x) rescue -2 + end + + # 11. else and ensure together + def full(x) + begin + v = 100 / x + rescue ZeroDivisionError + v = -1 + else + @n += 1 + ensure + @e += 1 + end + v + end + + # 12. the inner ensure runs before the outer rescue's class list is evaluated + def order(x) + begin + begin + 100 / x + ensure + @log << :inner_ensure + end + rescue klasses + @log << :rescued + -1 + end + end + + # 13. a raise in the protected part (a deopt in a typed body), with an ensure + def raise_ens(x) + begin + raise ArgumentError, "x=#{x}" if x > 250 + x + 1 + ensure + @e += 1 + end + end + + # 14. a raise in the handler: its cause is the rescued exception + def reraise(x) + begin + 100 / x + rescue ZeroDivisionError + raise ArgumentError, "wrapped" + end + end + + def thrower(x) + throw :out, x if x > 250 + x + end + + # 15. throw through an ensure + def thr(x) + begin + thrower(x) + ensure + @e += 1 + end + end + + # 16. a rescue that does not match lets the exception through, after the ensure + def nomatch(x) + begin + 100 / x + rescue ArgumentError + -1 + ensure + @e += 1 + end + end + + # 17. a rescue with no class takes StandardError only + def bare(x) + begin + x > 250 ? Integer("zz") : x + rescue + -3 + end + end + + # 18. an ensure writing self: frozen self + def ens_frozen(x) + begin + x + 1 + ensure + @e = x + end + end + + # 19. a float body + def fdiv(x) + begin + Integer === x ? 1.0 / x : x + rescue TypeError + -1.0 + end + end +end + +o = P.new +t("1. pure") { warm { |i| o.pure(i) } } +t("1. pure, a Float") { o.pure(1.5) } +t("1. pure, a String") { o.pure("a") } +t("2. div, 0 every 7th") { warm { |i| o.div(i % 7) } } +t("2. div after warm, 0") { o.div(0) } +t("3. eff") { o = P.new; [warm { |i| o.eff(i % 5) }, o.n] } +t("4. retry") { o = P.new; [warm { |i| o.ret(i % 4) }, o.n] } +t("5. class list a call") { o = P.new; [warm { |i| o.klist(i % 9) }, o.log.size] } +t("5. class list, wrong") { o.klist(nil) } +t("6. ensure, return") { o = P.new; [warm { |i| o.ens_ret(i) }, o.e] } +t("7. ensure swallows") { warm { |i| o.ens_swallow(i % 3) } } +t("8. $! in the handler") { [warm { |i| o.bang(i % 3) }, $!] } +t("8. $! restored") { begin; raise "outer"; rescue; o.bang(0); $!.message; end } +t("9. from a callee") { o = P.new; [warm { |i| o.from_callee(i) }, o.log] } +t("10. modifier") { warm { |i| o.modifier(i % 4) } } +t("11. else and ensure") { o = P.new; [warm { |i| o.full(i % 6) }, o.n, o.e] } +t("12. order") { o = P.new; warm { |i| o.order(i % 2 + 1) }; o.order(0); o.log.last(3) } +t("13. raise and ensure") { o = P.new; r = warm(250) { |i| o.raise_ens(i) }; [r, o.e] } +t("13. raises") { o.raise_ens(300) } +t("13. ensure ran") { o.e } +t("14. cause") { warm(100) { |i| o.reraise(i + 1) }; begin; o.reraise(0); rescue => e; [e.class, e.cause.class]; end } +t("15. throw through") { o = P.new; [catch(:out) { warm { |i| o.thr(i) } }, o.e] } +t("16. no match") { o = P.new; warm(100) { |i| o.nomatch(i + 1) }; o.nomatch(0) } +t("16. ensure ran") { o.e } +t("17. bare rescue") { warm { |i| o.bare(i) } } +t("17. NoMethodError") { begin; o.bare(nil); rescue NoMethodError => e; e.class; end } +t("18. ensure, frozen") { o = P.new; warm { |i| o.ens_frozen(i) }; o.freeze; begin; o.ens_frozen(5); rescue FrozenError => e; e.class; end } +t("18. value kept") { o.e } +t("19. float") { warm { |i| o.fdiv(i + 1) }; [o.fdiv(4), o.fdiv(0.5)] } + +# 20. Timeout through a hot method with a rescue: Timeout's exception is not a StandardError +require 'timeout' +o = P.new +t("20. Timeout through rescue") do + Timeout.timeout(0.2) { loop { o.pure(1); o.div(1); sleep 0.001 } } +end +t("20. still works") { o.div(0) } + +# 21. a method redefined after it turned hot +class P + remove_method :pure + def pure(x) + begin + x - 1 + rescue StandardError + 0 + end + end +end +t("21. redefined") { o.pure(10) } +t("22. $! at the end") { $!.inspect } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..02cc0924b 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1068,6 +1068,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has find what the method does around the handler (the scope, the saving of `$!`, the frame) and let a body whose handler is not entered run as light as one without. And **a raise that is rescued costs 6.3 us against 0.64**: a .NET exception per use. + The method JIT (round of 2026-11-26, see Rejected, perf/jitbody): `Body` alone refuses 30 + methods, not the 461 the census used to say, all cold wrappers whose rescued part is a + call; a handler as a deopt can take only a call-free protected part (1 method). Left: a + handler emitted in the typed body, worth it only once a run shows hot methods needing it. 23. **A method made by `define_method` is called at 2.3 times CRuby's time** (64 against 28 ns; a `def` of the same body 31; YJIT 2-5 ns): the method JIT takes no block as a method body. Rails-style code defines most of its small methods this way. @@ -4174,6 +4178,46 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitbody (2026-11-26) - a `begin`/`rescue`/`ensure` in the method JIT's typed body** + (gap 22; `JIT never, one thing only: Body 461`). Not attempted past the census, which + answered it: the 461 were an error of the census. In its collect-all mode the screen + (`JitScreen.WalkBody`) noted the refused `Body` and returned without walking what was in + it, so every call inside a `begin` went uncounted; walked (the change kept, census only, + every verdict the same: `-d` 0 methods changed, `-c` on Json 59/59 agree), `Body` is + refused in 736 methods and alone in **30**, not 461 (Src/StdLib + AWFY, 28,376 methods). + - The forms, over the 753 `never` methods with a `Body` among their refusals (a prism script + over the census's `-l -a` list, not kept): `rescue` 639 + (with a class list 579, bare 71, `=> e` 186, several clauses 52), `ensure` 125, a + `begin` inside the method 381, at the method's level 377, `retry` 20, `else` 14, the + modifier 7. Of the 30 alone: `rescue` 21 (class list 20, bare 1, `=> e` 2), `ensure` 7; + no `retry`, `else` or modifier. A bare `begin ... end` is no refusal at all (the screen + and `JitCompiler.Emit` take a `Body` without clauses). + - Why not the cheapest sound form, the handler as a deopt to the generic body (as round + nineteen's `raise`): a deopt re-runs the method from the top, so it is sound only if + nothing observable happened before the exception, and an exception out of a call may + come after anything the callee did. So the protected part must have no call at all, and + the 30 are all I/O and protocol wrappers whose protected part is a call (`lstat`, + `getsockname`, `path`, `@http.finish`, `count || default`, `offsets.fetch`). One method + has a call-free protected part: `Net::IMAP::SASL::PlainAuthenticator#process`, an + `ensure` around a `return` of a string. Ceiling of that form: 1 method of 28,376. + And `Util/bench/rescue-shapes.rb` calls `is_a?` in every shape (refused by the screen on + purpose, to measure the frames), so no change here moves it; nothing was timed. + - What a next attempt needs: the handler in the typed body itself - a .NET try/catch whose + filter is the generic body's (`RescuePassMayTest`, `CanRescue*`, the class list + evaluated after inner ensures, `$!` set and restored, `retry` a jump), an `ensure` as a + finally that does not run for a deopt passing through, and a deopt inside the handler or + the ensure declined as after an effect. It wins at most the 30 (all `maybe` behind + calls), and they are cold. Not worth it until a run (`census.rb -u` on app-shapes) + shows hot methods that have nothing else refused. + - `Util/jit-rescue-matrix.rb` (new): 33 probes, hot past the thresholds and raising on + some calls - an effect before the raise, `retry`, a class list that is a method call, + inner ensure before the outer class list, `ensure` with `return` in the body and in the + clause, `$!` in the handler and restored, a callee's effect then raise, the modifier, + else+ensure, a deopting `raise` with ensure, `cause`, `throw` through an ensure, a + rescue that does not match, a frozen self written in ensure, Timeout through a rescue, + redefinition. It prints CRuby's output on master with the JIT on, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` and `IR_LIGHT_FRAMES=0`. + - **perf/evalc da03f675 and its second pass (round thirty-one, 2026-11-22) - a cache of the compiled code of eval'd strings** (gap 31). Merged, then taken out (f133bcfa) after an independent review; the second pass that fixed the review's points was rejected too. From 0cfab5ca75dcff62db8ee9adeb83641543ce72c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:10:21 +0000 Subject: [PATCH 011/439] Add Util/struct-matrix.rb and Util/bench/struct-shapes.rb The matrix probes creating Struct objects and classes against CRuby 4.0: keyword_init true, false and nil, missing, unknown and String keywords, too many arguments, subclasses that override initialize and call super, a redefined new or initialize, a refinement, a struct class made in a thread, and what a new class answers; each line cold, a second time and warm (200 calls). On master it differs from CRuby in six lines: String keys are unknown keywords, a subclass of a keyword_init: true struct is not keyword_init (keyword_init? nil, positional arguments taken), and a new struct class's singleton_methods lack :inspect. The shapes time keyword and positional Struct#new, a keyword initializer, Hash#dup, Struct.new class creation with and without a first new and getter, and controls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Util/bench/struct-shapes.rb | 86 ++++++++++++++++ Util/struct-matrix.rb | 197 ++++++++++++++++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 Util/bench/struct-shapes.rb create mode 100644 Util/struct-matrix.rb diff --git a/Util/bench/struct-shapes.rb b/Util/bench/struct-shapes.rb new file mode 100644 index 000000000..002f814e3 --- /dev/null +++ b/Util/bench/struct-shapes.rb @@ -0,0 +1,86 @@ +# What creating a Struct object and a Struct class costs (LEDGER gaps 24 and 19): ns per operation, the caller a +# `while' loop. The switch is the other arm: +# +# ruby Util/perf/ab.rb -r 6 Util/bench/struct-shapes.rb "off=env IR_FAST_STRUCT=0 IR_CONFIG=Release ./ir.sh" \ +# "on=env IR_CONFIG=Release ./ir.sh" +# +# kw_new is Struct.new(..., keyword_init: true)'s new with keywords; kwnil_new the same keywords to a struct made +# without keyword_init: (nil: it takes both); kw_hash a keyword_init struct given one Hash argument; pos_new a +# positional new; sub_kw a subclass of a keyword_init struct whose initialize calls super with keywords. kwinit is +# a class whose initialize takes two required keywords, hash_dup a Hash#dup of three keys. new_class makes a Struct +# class (Struct.new(:a)); new_class_use makes one and calls its new and its getter once (a first call on a new +# class); both run N/40 times. getter, setter, obj_new and plain are controls. +$stdout.sync = true + +KW = Struct.new(:a, :b, keyword_init: true) +KN = Struct.new(:a, :b) +P = Struct.new(:a, :b) +class SubKW < KW + def initialize(a:, b: 2) + super(a: a, b: b) + end +end +class Product + attr_reader :sku, :name + def initialize(sku:, name:) + @sku = sku + @name = name + end +end +class Obj + attr_reader :a + def initialize(a, b) + @a = a + @b = b + end +end +def plain(a) = a + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-14s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +N = (ENV['N'] || 200_000).to_i +NC = [N / 40, 20].max +H3 = { a: 1, b: 2, c: 3 } +PT = P.new(1, 2) + +t("kw_new", N) { |n| i = 0; c = 0; while i < n; c += KW.new(a: i, b: 2).a; i += 1; end; c } +t("kwnil_new", N) { |n| i = 0; c = 0; while i < n; c += KN.new(a: i, b: 2).a; i += 1; end; c } +t("kw_hash", N) { |n| i = 0; c = 0; h = { a: 1, b: 2 }; while i < n; c += KW.new(h).b + i; i += 1; end; c } +t("sub_kw", N) { |n| i = 0; c = 0; while i < n; c += SubKW.new(a: i).b; i += 1; end; c } +t("pos_new", N) { |n| i = 0; c = 0; while i < n; c += P.new(i, 2).a; i += 1; end; c } +t("kwinit", N) { |n| i = 0; c = 0; while i < n; c += Product.new(sku: i, name: "x").sku; i += 1; end; c } +t("hash_dup", N) { |n| i = 0; c = 0; while i < n; c += H3.dup.size + i; i += 1; end; c } +t("new_class", NC) { |n| i = 0; c = 0; while i < n; c += Struct.new(:a).members.size; i += 1; end; c } +t("new_class_use", NC) { |n| i = 0; c = 0; while i < n; k = Struct.new(:a, :b); c += k.new(i, 1).a; i += 1; end; c } +t("getter", N) { |n| i = 0; c = 0; while i < n; c += PT.a + i; i += 1; end; c } +t("setter", N) { |n| i = 0; c = 0; s = P.new(0, 0); while i < n; s.b = i; c += s.b; i += 1; end; c } +t("obj_new", N) { |n| i = 0; c = 0; while i < n; c += Obj.new(i, 2).a; i += 1; end; c } +t("plain", N) { |n| i = 0; c = 0; while i < n; c += plain(i); i += 1; end; c } diff --git a/Util/struct-matrix.rb b/Util/struct-matrix.rb new file mode 100644 index 000000000..3c02e02c9 --- /dev/null +++ b/Util/struct-matrix.rb @@ -0,0 +1,197 @@ +# Expression matrix for creating Struct objects and Struct classes (LEDGER gaps 24 and 19, +# perf/struct): keyword_init true, false and nil, missing and unknown keywords, too many +# arguments, subclasses whose initialize calls super, redefined new and initialize, a +# refinement, a Struct made in a thread, and what a new class answers. +# +# ruby Util/struct-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/struct-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +# +# Every line is " => " or " !! : ". Object +# ids are taken out of inspect. Each expression runs twice and then in a loop of 200, so a +# path that only a warm call site takes is probed too; a line says so when the warm answer +# differs from the first. + +KT = Struct.new(:a, :b, keyword_init: true) +KF = Struct.new(:a, :b, keyword_init: false) +KN = Struct.new(:a, :b) +K1 = Struct.new(:a, keyword_init: 1) +KE = Struct.new(keyword_init: true) +class SubKT < KT; end +class SubKN < KN; end +class InitKT < KT + def initialize(a:, b: 20) + super(a: a * 10, b: b) + end +end +class InitPos < KN + def initialize(*args, **kw) + super + self.b ||= :default + end +end +class InitHashKT < KT + def initialize(h) + super(h) + end +end +class NewKT < KT + def self.new(*args, **kw) + o = super + o.a = [:via_new, o.a] + o + end +end +class InitLate < KT; end +class InitLate + def initialize(**kw) + super(**kw.transform_values { |v| v.to_s }) + end +end +class FrozenKT < KT + def initialize(**kw) + super + freeze + end +end +module RefineKT + refine KT do + def a = :refined + end +end +module UsingRefine + using RefineKT + def self.read = KT.new(a: 1).a +end +KTH = Thread.new { Struct.new(:x, :y, keyword_init: true) }.value +KNH = Thread.new { Struct.new(:x, :y) }.value +HD = Hash.new(:dflt).merge(a: 1) + +EXPRESSIONS = <<~'RUBY'.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + # --- keyword_init: true + KT.new(a: 1, b: 2).to_a + KT.new(a: 1).to_a + KT.new(b: 2).to_a + KT.new.to_a + KT.new(**{}).to_a + KT.new({a: 1, b: 2}).to_a + KT.new({a: 1}).to_a + KT.new({"a" => 1}) + KT.new(c: 1) + KT.new(a: 1, c: 1, d: 2) + KT.new("a" => 1) + KT.new(1) + KT.new(1, 2) + KT.new(1, a: 2) + KT.new({a: 1}, {b: 2}) + KT.new(**HD).to_a + KT.new(b: 2, a: 1).to_h + KT.new(a: 1, b: 2) == KT.new(b: 2, a: 1) + KT.new(a: 1, b: 2).inspect + KT.new(a: [1], b: {c: 1}).to_h + KT.keyword_init? + KT.members + KT.inspect.sub(/0x\h+/, "XX") + KT.new(a: 1).frozen? + KT.new(a: 1).freeze.frozen? + (s = KT.new(a: 1).freeze; s.a = 2) + (s = KT.new(a: 1); s.send(:initialize, b: 3); s.to_a) + (s = KT.new(a: 1).freeze; s.send(:initialize, b: 3)) + (h = {a: 1}; s = KT.new(**h); h[:a] = 9; s.a) + (k = {a: {x: 1}}; s = KT.new(**k); s.a.equal?(k[:a])) + KE.new.to_a + KE.new(a: 1) + K1.new(a: 1, b: 2).to_a + K1.keyword_init? + K1.new(1) + # --- keyword_init: false + KF.new(a: 1, b: 2).to_a + KF.new(1, 2).to_a + KF.new(1, b: 2).to_a + KF.new(1, 2, 3) + KF.keyword_init? + # --- keyword_init: nil (the default): both + KN.new(a: 1, b: 2).to_a + KN.new(a: 1).to_a + KN.new(c: 3) + KN.new(1, 2).to_a + KN.new(1).to_a + KN.new(1, b: 2).to_a + KN.new({a: 1, b: 2}).to_a + KN.new(1, 2, 3) + KN.new("a" => 1).to_a + KN.new(**{}).to_a + KN.keyword_init? + KN.new(a: 1, b: 2).inspect + # --- subclasses + SubKT.new(a: 1, b: 2).to_a + SubKT.new(c: 1) + SubKT.new(1, 2) + SubKT.keyword_init? + SubKN.new(a: 1, b: 2).to_a + SubKN.new(1, 2).to_a + SubKN.keyword_init? + InitKT.new(a: 1).to_a + InitKT.new(a: 1, b: 2).to_a + InitKT.new(b: 1) + InitPos.new(1).to_a + InitPos.new(a: 1).to_a + InitPos.new(1, 2).to_a + InitHashKT.new({a: 1, b: 2}).to_a + InitHashKT.new(a: 5).to_a + NewKT.new(a: 1, b: 2).to_a + InitLate.new(a: 1, b: 2).to_a + FrozenKT.new(a: 1).frozen? + FrozenKT.new(a: 1).to_a + UsingRefine.read + KT.new(a: 1).a + KTH.new(x: 1, y: 2).to_a + KTH.new(z: 1) + KNH.new(x: 1).to_a + KNH.new(1, 2).to_a + Thread.new { KT.new(a: 1, b: 2).to_a }.value + # --- making a class + Struct.new(:a).new(1).a + Struct.new(:a).members + (Struct.send(:remove_const, :Abc) if Struct.const_defined?(:Abc, false); Struct.new("Abc", :a).name) + Struct.new(:a, :a) + Struct.new(:a=) + Struct.new(:a, keyword_init: true, x: 1) + Struct.new(:a, foo: 1, bar: 2) + Struct.new(:a) { def x = a * 2 }.new(3).x + Struct.new(:a, :b).new(1, 2, 3) + Struct.new(:a).new(1).frozen? + Struct.new(:a).singleton_methods.sort + Struct.new(:a, keyword_init: true).singleton_methods.sort + Struct.new(:a).instance_methods(false).sort + Struct.new(:a, :b, keyword_init: true).inspect.sub(/0x\h+/, "XX") + (c = Struct.new(:a); c.new(1) == c.new(1)) + (c = Struct.new(:a); c[5].a) + (c = Struct.new(:a); d = Class.new(c); d.new(1).a) + (c = Struct.new(:a); def c.new(*) = :mine; c.new(1)) + (c = Struct.new(:a); c.define_method(:initialize) { |*a| super(*a.map { _1 * 2 }) }; c.new(4).a) + (c = Struct.new(:a, keyword_init: true); c.define_method(:initialize) { |**k| super(**k.transform_values { _1 + 1 }) }; c.new(a: 4).a) + (c = Struct.new(:a); c.class_eval { def a = 42 }; c.new(1).a) + (c = Struct.new(:a); s = c.new(1); c.class_eval { undef_method :a }; s.a) + (c = Struct.new(:a); c.new(1).respond_to?(:a=)) + Struct.new(:a).new(1).hash == Struct.new(:a).new(1).hash +RUBY + +def clean(v) = v.inspect.gsub(/0x\h+/, "XX") +def run(source) + "=> #{clean(eval(source))}" +rescue Exception => e + "!! #{e.class}: #{e.message.gsub(/0x\h+/, "XX")}" +end + +EXPRESSIONS.each do |source| + first = run(source) + second = run(source) + warm = nil + 200.times { warm = run(source) } + line = "#{source} #{first}" + line += " [second: #{second}]" if second != first + line += " [warm: #{warm}]" if warm != first + puts line +end +puts "done" From 0c0ad7cfc42ce4ad82c3d314d8998f119172b458 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:10:21 +0000 Subject: [PATCH 012/439] Store Struct keyword arguments in Struct#initialize itself Struct.new(..., keyword_init: true).new(a: 1, b: 2) was 3.2 times CRuby's time (gap 24): RubyStructOps.Initialize stored only one positional value per member and sent every other call, keywords included, through a call site to __struct_initialize_slow__ in ruby4.rb, which copied the Hash, asked the class for members and keyword_init?, took the difference of the keys and splatted the values into __struct_initialize__. Initialize now stores keywords whose keys all name members (a Symbol or a String, as MRI's struct_hash_set_i through rb_struct_pos) when the class's keyword_init is true or nil, and a single Hash argument when it is true, and clears every member for no arguments; anything else (an unknown key, keywords beside positional values) still goes to the slow path, now told the class's keyword_init. That is read as MRI's struct_ivar_get does, from the nearest struct class above that has one, so a subclass of a keyword_init: true struct is keyword_init too (keyword_init? true, positional arguments rejected) as in CRuby, where it answered nil before; and String keys are members in the slow path too, as in CRuby, where they were unknown keywords. IR_FAST_STRUCT=0 sends the keyword calls to the slow path as before. Util/struct-matrix.rb prints CRuby's output in both modes but for a new struct class's singleton_methods (no :inspect, as before). Util/bench/struct-shapes.rb, four alternating rounds (CRuby / before / after, ns): kw_new 299 / 1018 / 200, kwnil_new 301 / 1019 / 198, kw_hash 203 / 1058 / 139, sub_kw 360 / 1178 / 397; pos_new, getter, obj_new and plain overlap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Libraries/Builtins/StructOps.cs | 82 ++++++++++++++++++++++++----- Src/Ruby/Builtins/RubyStruct.cs | 24 ++++++--- Src/StdLib/ironruby/ruby4.rb | 34 +++++++----- 3 files changed, 108 insertions(+), 32 deletions(-) diff --git a/Src/Libraries/Builtins/StructOps.cs b/Src/Libraries/Builtins/StructOps.cs index 5663d6533..b48d8f050 100644 --- a/Src/Libraries/Builtins/StructOps.cs +++ b/Src/Libraries/Builtins/StructOps.cs @@ -89,9 +89,10 @@ private static object Create(BlockParam block, RubyClass/*!*/ self, string class return result; } - // Struct#initialize. The overwhelmingly common call - one positional value per member, the + // Struct#initialize. The overwhelmingly common calls - one positional value per member, the // last of them not a Hash that could be keywords, on a class not built with keyword_init: - // true - stores the values right here, which is what keeps Point.new(1, 2) cheap. Every + // true; or keywords that all name members, to a class whose keyword_init is not false - + // store the values right here, which is what keeps Point.new(1, 2) cheap. Every // other call goes to Struct#__struct_initialize_slow__ in ruby4.rb with the positional // arguments as one array and the keywords, if any, as a Hash - as a // `def initialize(*args, **kwargs)' would have received them. The keywords arrive here as @@ -99,7 +100,7 @@ private static object Create(BlockParam block, RubyClass/*!*/ self, string class // stays a positional argument (MRI's rb_struct_initialize_m tells them apart the same way). [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] [ReceivesKeywords] - public static object Initialize(CallSiteStorage>/*!*/ slowPath, + public static object Initialize(CallSiteStorage>/*!*/ slowPath, RubyStruct/*!*/ self, params object[]/*!*/ items) { // MRI's rb_struct_modify comes first: re-initializing a frozen struct is a FrozenError @@ -109,22 +110,38 @@ public static object Initialize(CallSiteStorage 0) { - var hash = items[positional - 1] as Hash; - if (hash != null && hash.IsKeywordArguments) { - // a plain copy: the flag would make it the slow path's keywords again - keywords = new Hash(hash); - positional--; + Hash keywordHash = positional > 0 ? items[positional - 1] as Hash : null; + bool hasKeywords = keywordHash != null && keywordHash.IsKeywordArguments; + + if (FastStruct) { + // MRI's rb_struct_initialize_m: no arguments clears every member, whatever keyword_init says. + if (positional == 0) { + self.SetValues(new object[count]); + return null; + } + // Keywords alone, to a struct whose keyword_init is true or nil; or one Hash argument to a + // keyword_init: true struct, which takes it as the keywords. Every key that names a member is + // stored here and the rest cleared; a key that names none goes to the slow path for its error. + if (positional == 1 && keywordHash != null && (hasKeywords ? !(keywordInit is bool && !(bool)keywordInit) : RubyOps.IsTrue(keywordInit)) + && TryInitializeFromKeywords(self, keywordHash)) { + return null; } } + Hash keywords = null; + if (hasKeywords) { + // a plain copy: the flag would make it the slow path's keywords again + keywords = new Hash(keywordHash); + positional--; + } + // Without the prelude (the test harness runs the libraries alone) there is no slow path: // store what was given, as the C# `def initialize(*args)' did. if (!self.ImmediateClass.ResolveMethod("__struct_initialize_slow__", VisibilityContext.AllVisible).Found) { @@ -135,8 +152,47 @@ public static object Initialize(CallSiteStorage + /// IR_FAST_STRUCT=0 sends every Struct#initialize but a positional one per member to the slow path in ruby4.rb, + /// as before keyword arguments were stored here. + /// + internal static readonly bool FastStruct = Environment.GetEnvironmentVariable("IR_FAST_STRUCT") != "0"; + + // struct_hash_set_i: a Symbol or String key names a member (rb_struct_pos); false, storing nothing, when a key + // names none, for the slow path to raise "unknown keywords" with all of them. + private static bool TryInitializeFromKeywords(RubyStruct/*!*/ self, Hash/*!*/ keywords) { + var values = new object[self.ItemCount]; + foreach (var entry in keywords) { + string name; + var symbol = entry.Key as RubySymbol; + if (symbol != null) { + name = symbol.ToString(); + } else { + var str = entry.Key as MutableString; + if (str == null) { + return false; + } + name = str.ConvertToString(); + } + int index; + if (!self.TryGetIndex(name, out index)) { + return false; + } + values[index] = entry.Value; + } + self.SetValues(values); + return true; + } + + // Struct.new's classes' #keyword_init? (ruby4.rb): MRI's struct_ivar_get, which a subclass answers with the + // keyword_init: of the struct class above it. + [RubyMethod("__keyword_init__", RubyMethodAttributes.PrivateSingleton)] + public static object GetKeywordInit(RubyClass/*!*/ self) { + return RubyStruct.GetKeywordInit(self); } // The plain store, for __struct_initialize_slow__. diff --git a/Src/Ruby/Builtins/RubyStruct.cs b/Src/Ruby/Builtins/RubyStruct.cs index 67d586853..d796c5a56 100644 --- a/Src/Ruby/Builtins/RubyStruct.cs +++ b/Src/Ruby/Builtins/RubyStruct.cs @@ -338,16 +338,26 @@ public int ItemCount { } /// - /// Whether the struct's class was built by Struct.new(..., keyword_init: true): ruby4.rb's - /// Struct.new keeps the option in the class's @__keyword_init__, which is what the class's - /// #keyword_init? answers. A subclass has none of its own. + /// The keyword_init: option of Struct.new, as MRI's struct_ivar_get finds it: ruby4.rb's Struct.new keeps it in the + /// class's @__keyword_init__ (true, false or nil), and a subclass has the one of the nearest class above it that + /// has one. Nil when none has. /// - public bool IsKeywordInit { - get { - var data = ImmediateClass.GetNonSingletonClass().TryGetInstanceData(); + public object KeywordInit { + get { return GetKeywordInit(ImmediateClass.GetNonSingletonClass()); } + } + + private static readonly string/*!*/ _KeywordInitVariable = IronRuby.Runtime.RubyUtils.GetCoreStateInstanceVariableName("@__keyword_init__"); + + public static object GetKeywordInit(RubyClass/*!*/ cls) { + string name = _KeywordInitVariable; + for (RubyClass c = cls; c != null && c.StructInfo != null; c = c.SuperClass) { + var data = c.TryGetInstanceData(); object value; - return data != null && data.TryGetInstanceVariable(IronRuby.Runtime.RubyUtils.GetCoreStateInstanceVariableName("@__keyword_init__"), out value) && RubyOps.IsTrue(value); + if (data != null && data.TryGetInstanceVariable(name, out value)) { + return value; + } } + return null; } } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 329b23a18..6a300c47d 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -12430,7 +12430,8 @@ def new(*args, **options, &block) ::Kernel.instance_method(:__ir_set_hidden_ivar__).bind_call(klass, :@__keyword_init__, keyword_init) define_singleton = ::Kernel.instance_method(:define_singleton_method) # only classes created by Struct.new answer #keyword_init?, not every Struct subclass - define_singleton.bind_call(klass, :keyword_init?) { @__keyword_init__ } + # a subclass answers its superclass's (MRI's struct_ivar_get) + define_singleton.bind_call(klass, :keyword_init?) { __keyword_init__ } if keyword_init # MRI: #(keyword_init: true) define_singleton.bind_call(klass, :inspect) { "#{super()}(keyword_init: true)" } @@ -12441,16 +12442,15 @@ def new(*args, **options, &block) end class Struct - # Struct#initialize is RubyStructOps.Initialize: it stores one positional value per member - # itself and hands every other call here, the positional arguments in one array and the - # keywords, if any, in a Hash - as a `def initialize(*args, **kwargs)' would have received - # them. __struct_initialize__ is the plain store. - def __struct_initialize_slow__(args, kwargs) + # Struct#initialize is RubyStructOps.Initialize: it stores one positional value per member, + # and keywords that all name members, itself and hands every other call here, the positional + # arguments in one array and the keywords, if any, in a Hash - as a `def initialize(*args, + # **kwargs)' would have received them - with the class's keyword_init (true, false or nil, a + # subclass's that of the struct class above it). __struct_initialize__ is the plain store. + def __struct_initialize_slow__(args, kwargs, keyword_init = nil) kwargs ||= {} # self.class.members, not members: a struct may have a member called "members" - klass = self.class - names = klass.members - keyword_init = klass.respond_to?(:keyword_init?) ? klass.keyword_init? : nil + names = self.class.members # The overwhelmingly common call: one positional value per member. if kwargs.empty? && !keyword_init && args.size == names.size @@ -12474,12 +12474,22 @@ def __struct_initialize_slow__(args, kwargs) unless args.empty? raise ArgumentError, "wrong number of arguments (given #{args.size + (kwargs.empty? ? 0 : 1)}, expected 0)" end - unknown = kwargs.keys - names - unless unknown.empty? + # struct_hash_set_i: a Symbol or a String names a member (rb_struct_pos) + values = ::Array.new(names.size) + unknown = nil + kwargs.each_pair do |key, value| + index = (key.is_a?(::Symbol) || key.is_a?(::String)) ? names.index(key.to_sym) : nil + if index + values[index] = value + else + (unknown ||= []) << key + end + end + if unknown # MRI's wording is plural whatever the count raise ArgumentError, "unknown keywords: #{unknown.join(', ')}" end - __struct_initialize__(*names.map { |name| kwargs[name] }) + __struct_initialize__(*values) else # pad with nil so that a partial re-initialize clears the remaining members values = args.dup From 95d5891232463476abfa265e81c7ac8d1672a244 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:11:42 +0000 Subject: [PATCH 013/439] byteindex on UTF-8: count the bytes of the whole string only for an offset from the end The first cut counted the UTF-8 size of the receiver on every call, so a #byteindex from offset 0 on 10 KB of UTF-8 text cost 1.3 us when the needle was at byte 5 (CRuby 75 ns). The walk to a positive offset now says by itself whether the offset is past the end, and the size is counted only for a negative offset. bidx1_u_e 1302.6 -> 146.2 ns (Util/bench/strsearch-shapes.rb, four alternating rounds); the matrix and byteindex_spec/byterindex_spec are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/Builtins/MutableStringOps.cs | 60 ++++++++++++++-------- 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 96dfd3200..e72793c5f 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -4509,29 +4509,47 @@ private static bool TryByteSearch(MutableString/*!*/ self, object[]/*!*/ args, b } } - int size = singleByte ? GetCharacterLength(self) : Encoding.UTF8.GetByteCount(chars); - int offset = (args.Length == 2) ? (int)args[1] : (reverse ? size : 0); - if (offset < 0) { - offset += size; + int charOffset; + if (singleByte) { + int size = GetCharacterLength(self); + int offset = (args.Length == 2) ? (int)args[1] : (reverse ? size : 0); if (offset < 0) { - return true; + offset += size; + if (offset < 0) { + return true; + } } - } - if (offset > size) { - // #byteindex gives up past the end, #byterindex clamps to it - if (!reverse) { - return true; + if (offset > size) { + // #byteindex gives up past the end, #byterindex clamps to it + if (!reverse) { + return true; + } + offset = size; } - offset = size; - } - - int charOffset; - if (singleByte) { charOffset = offset; } else { - int clrOffset = Utf8OffsetToClrIndex(chars, offset); - if (clrOffset < 0) { - throw RubyExceptions.CreateIndexError("offset {0} does not land on character boundary", offset); + // The UTF-8 size of the whole string is counted only for an offset from the end: + // the walk to a positive offset finds out by itself whether it is past the end. + int clrOffset; + if (args.Length < 2) { + clrOffset = reverse ? chars.Length : 0; + } else { + int offset = (int)args[1]; + if (offset < 0) { + offset += Encoding.UTF8.GetByteCount(chars); + if (offset < 0) { + return true; + } + } + clrOffset = Utf8OffsetToClrIndex(chars, offset); + if (clrOffset == -2) { + if (!reverse) { + return true; + } + clrOffset = chars.Length; + } else if (clrOffset < 0) { + throw RubyExceptions.CreateIndexError("offset {0} does not land on character boundary", offset); + } } charOffset = self.ToCharacterIndex(clrOffset); } @@ -4552,8 +4570,8 @@ private static bool TryByteSearch(MutableString/*!*/ self, object[]/*!*/ args, b /// /// The CLR index of the character that starts bytes into the - /// UTF-8 form of (valid UTF-16), or -1 when that offset is inside a - /// character or past the end. + /// UTF-8 form of (valid UTF-16): -1 when that offset is inside a + /// character, -2 when it is past the end. /// private static int Utf8OffsetToClrIndex(ReadOnlySpan chars, int byteOffset) { int bytes = 0; @@ -4574,7 +4592,7 @@ private static int Utf8OffsetToClrIndex(ReadOnlySpan chars, int byteOffset i += 1; } } - return (bytes == byteOffset) ? i : -1; + return (bytes == byteOffset) ? i : (bytes < byteOffset) ? -2 : -1; } [RubyMethod("byteindex")] From cae001fca646eacc81ac8edde681823858be99d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:12:46 +0000 Subject: [PATCH 014/439] LEDGER: perf/strsearch landed (not gated); gap 21 rewritten with what is still open Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Util/perf/LEDGER.md | 56 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 3 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..6a2ad6148 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1056,10 +1056,22 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has String `match?` takes 0.47 us), although `match?` has less to do; a short anchored match is 1.3 to 1.5 times CRuby (`/\A[+-]?\d+/.match("12345 rest")` 663 against 452 ns). One run beside two builds, so factors only; shapes and a reading of the three - entry points are in `Util/bench/daloze-lessons.md`, section 6. Reading the code did - not explain the first two; the experiment starts with finding out (a one-character - needle straight to a span search, `match?` without a Match object). Outside AWFY; + entry points are in `Util/bench/daloze-lessons.md`, section 6. Outside AWFY; it is what JSON escaping, `strscan` and log parsing spend. + Round of perf/strsearch (2026-11-26, see Landed): `Util/bench/strsearch-shapes.rb` (120 + shapes) did not reproduce the regexp half - over 10 KB IronRuby is 25 to 160 times + *faster* than CRuby (`mp_u_n` 366 ns against 59 us, .NET's vectorized `IndexOfAny`), + and `match?` and `=~` cost the same there; what was slow was `match?` that finds + something (it built a MatchData), `#byteindex` (a Ruby helper; 1.1 ms on 10 KB of UTF-8) + and a BINARY needle (wrong answers); all three are dealt with. **Still open:** `s.index('"')` not + found in 10 KB is 198 ns against 109 (profile: 59% in `PackedSpanHelpers.IndexOf`, + the search over 20 KB of UTF-16; the rest is the call) - only a receiver held as bytes + would close it; `#start_with?` 134 / 212 ns against 55 / 90 (its caller makes a + `RubyMethodScope`, since the method takes the scope for a Regexp prefix's `$~`: gap 16 + / a scope-free overload); `#byteindex` on UTF-8 found late is 1.3 us against 117 ns + (the UTF-8 length of the prefix, `Encoding.UTF8.GetByteCount`, 1.1 us over 10 KB of + mixed text), and from a positive offset other than 0 it walks the characters to it, so a + strscan-style loop of byte offsets over UTF-8 text is quadratic where CRuby's is not. 22. **A `begin`/`rescue` or `ensure` in a method costs about 80 ns per call when nothing is raised**: `def r(x) begin; x + 1; rescue StandardError; 0; end end` 106 ns against CRuby's 24, the same with `ensure` 112 against 27 (`Util/bench/zjit-post-shapes.rb`, @@ -1384,6 +1396,44 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/strsearch (2026-11-26) - `#byteindex`/`#byterindex` with a String needle in C#, + `Regexp#match?` without a MatchData, and two searches that answered wrong (gap 21)** - not + gated. Commits ba4a151, c9a4e7c, 95d5891 on `claude/perf-strsearch`; switch + `IR_FAST_SEARCH=0` (both speed-ups; the fixes are not switched). The census does not see a + library method's speed (0 methods moved, 28,376); judged by time, since this container has + no instruction counter: `Util/perf/ab.rb -r 4 Util/bench/strsearch-shapes.rb`, CRuby / master + f81fc19 / the candidate with the switch off / on, alternating rounds, ns: + + bidx1_a_e 65.3 / 590.4 / 587.6 / 130.8 0.22 mp_a_e 98.2 / 166.0 / 157.5 / 104.0 0.66 + bidx1_a_l 115.7 / 759.6 / 786.9 / 279.2 0.35 mp_u_e 127.6 / 156.0 / 162.2 / 107.9 0.67 + bidx1_a_n 117.6 / 754.9 / 755.9 / 231.0 0.31 mp3_b_e 91.9 / 171.1 / 175.1 / 116.0 0.66 + bidx1_b_n 119.3 / 663.4 / 638.1 / 199.2 0.31 int_mp 119.9 / 164.4 / 165.6 / 108.0 0.65 + controls, all overlap: idx1_a_n 199.3 -> 198.2, idx1_u_l 196.5 -> 200.0, tilde_a_e 247.8 -> + 248.0, int_tilde 248.0 -> 255.3, mp_u_l 396.7 -> 348.0, size 51.5 -> 47.4, eq 74.7 -> 67.6 + + On 10 KB of UTF-8 with non-ASCII characters `#byteindex` was 1,118,000 / 1,130,000 / + 1,146,000 ns (found at byte 5 / 30 bytes from the end / not found; master, N=1000) and is + 146 / 1,316 / 239 (CRuby 75 / 117 / 120). What it was: `#byteindex` and `#byterindex` sent + every call to ruby4.rb's `__ir_byte_search__`, which builds a table of every character's + byte offset with `each_char` on every call. Now a String needle with a Fixnum offset (or + none) is done in C#: a receiver whose characters are its bytes needs no conversion, a valid + UTF-8 one walks its UTF-16 characters to the offset and counts the UTF-8 length of the + prefix the answer ends; a Regexp, a `#to_str` needle, a Bignum offset, other multibyte + encodings and broken strings still go to the helper. `Regexp#match?` asks `Regex.IsMatch` + (but for a subject with a surrogate pair, which needs the Match to drop one that starts + between the halves). Fixed on the way, both in the new `Util/string-search-matrix.rb` + (56,234 rows, which now print CRuby 4.0's output, switch on and off; master differs in + 1,098): a needle held as bytes (`'"'.b`) on a receiver held as characters that are not + its bytes switched the receiver to bytes and answered byte offsets (`"é\"".index('"'.b)` + was 2); and a Regexp search from an offset outside the string raised the encoding's + CompatibilityError (or, for `#index`, the broken receiver's ArgumentError) where CRuby + answers nil first. Checked: the matrix; `astral-string`, `string-methods`, + `regexp-binary-ctype`, `stdre`, `regex-light` and `regexp-escaped-byte` matrices print what + master prints; spec/core/string index, rindex, byteindex, byterindex, match, start_with, + include, partition, rpartition, slice, element_reference, element_set, split, sub, gsub, + scan, end_with, spec/core/regexp/match_spec.rb, spec/library/stringscanner and + stringio/gets_spec.rb: 0 failures; 62 named MutableString/Regex IronRuby.Tests pass. + - **perf/first-bind (2026-11-26) - what a first bind costs, split; light-scope sites call library methods through a dispatcher for their first calls (gap 26).** The split (master 4bae83f3, R2R host with the startup library; `IR_BIND_TRACE`, `IR_PHASE_TIMES`, perf with jitdump classing From 948ad0a0d5bf6fb15bba336d605cadd8e24bbc0a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:20:04 +0000 Subject: [PATCH 015/439] Make a new anonymous Struct class without moving the global method version Struct.new moved RubyModule.GlobalMethodVersion, the one guard of every typed body and running compiled loop (gap 19, measured: a loop calling a specialized method while it made a Struct class every 10,000 iterations counted 8 JIT invalidations for 30 classes, and a method so invalidated eight times settles on its generic body for good; Class.new counts none). AddClassMembers added new and [] to the class's singleton class, which override Class#new, and the prelude then defined keyword_init? and inspect, which overrides Module#inspect: each override of a method some site had resolved runs MethodsUpdated. No site, rule or compiled body can depend on a resolution through a class no code has seen. When the class is anonymous and its superclass's inherited hook is the default (so no Ruby code ran while it was made and no constant names it), its methods are now put in the tables without PrepareMethodUpdate (RubyModule.SetMethodOfUnseenModuleNoEventNoLock), all of them first and then their method_added / singleton_method_added events. A named struct, or one whose superclass has an inherited hook, adds them as before. keyword_init? and inspect are now made in C# with the others, as MRI's setup_struct makes them, for every struct class: the prelude's define_singleton_method blocks are gone. So a class made without keyword_init: lists :inspect in singleton_methods, as in CRuby (it did not), and its keyword_init? still answers through struct_ivar_get's walk. IR_FAST_STRUCT=0 adds the methods the old way. Util/struct-matrix.rb now prints CRuby's output, with the switch on and off; the loop above counts 0 invalidations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Libraries/Builtins/StructOps.cs | 15 +----- Src/Ruby/Builtins/RubyModule.cs | 17 ++++++- Src/Ruby/Builtins/RubyStruct.cs | 73 ++++++++++++++++++++++++----- Src/StdLib/ironruby/ruby4.rb | 15 ++---- 4 files changed, 80 insertions(+), 40 deletions(-) diff --git a/Src/Libraries/Builtins/StructOps.cs b/Src/Libraries/Builtins/StructOps.cs index b48d8f050..57a977fda 100644 --- a/Src/Libraries/Builtins/StructOps.cs +++ b/Src/Libraries/Builtins/StructOps.cs @@ -120,7 +120,7 @@ public static object Initialize(CallSiteStorage 0 ? items[positional - 1] as Hash : null; bool hasKeywords = keywordHash != null && keywordHash.IsKeywordArguments; - if (FastStruct) { + if (RubyStruct.FastStruct) { // MRI's rb_struct_initialize_m: no arguments clears every member, whatever keyword_init says. if (positional == 0) { self.SetValues(new object[count]); @@ -156,12 +156,6 @@ public static object Initialize(CallSiteStorage - /// IR_FAST_STRUCT=0 sends every Struct#initialize but a positional one per member to the slow path in ruby4.rb, - /// as before keyword arguments were stored here. - /// - internal static readonly bool FastStruct = Environment.GetEnvironmentVariable("IR_FAST_STRUCT") != "0"; - // struct_hash_set_i: a Symbol or String key names a member (rb_struct_pos); false, storing nothing, when a key // names none, for the slow path to raise "unknown keywords" with all of them. private static bool TryInitializeFromKeywords(RubyStruct/*!*/ self, Hash/*!*/ keywords) { @@ -188,13 +182,6 @@ private static bool TryInitializeFromKeywords(RubyStruct/*!*/ self, Hash/*!*/ ke return true; } - // Struct.new's classes' #keyword_init? (ruby4.rb): MRI's struct_ivar_get, which a subclass answers with the - // keyword_init: of the struct class above it. - [RubyMethod("__keyword_init__", RubyMethodAttributes.PrivateSingleton)] - public static object GetKeywordInit(RubyClass/*!*/ self) { - return RubyStruct.GetKeywordInit(self); - } - // The plain store, for __struct_initialize_slow__. [RubyMethod("__struct_initialize__", RubyMethodAttributes.PrivateInstance)] public static void Reinitialize(RubyStruct/*!*/ self, params object[]/*!*/ items) { diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 98a665651..bfa4f284b 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -2454,8 +2454,19 @@ public void SetMethodNoEventNoLock(RubyContext/*!*/ callerContext, string/*!*/ n SetMethodNoMutateNoEventNoLock(callerContext, name, method); } + /// + /// Adds a method, without its event, to a module no code can have seen yet - one just made, whose making ran no Ruby + /// code (RubyStruct.DefineStruct): no call site, rule or compiled body can depend on a resolution through it, so the + /// override and missing-method checks of PrepareMethodUpdate, which move the global method version that every typed + /// body and running loop guards on, have nothing to invalidate. + /// + internal void SetMethodOfUnseenModuleNoEventNoLock(string/*!*/ name, RubyMemberInfo/*!*/ method) { + Mutate(); + SetMethodNoMutateNoEventNoLock(Context, name, method, true, false); + } + internal void SetMethodNoMutateNoEventNoLock(RubyContext/*!*/ callerContext, string/*!*/ name, RubyMemberInfo/*!*/ method, - bool newEntry = true) { + bool newEntry = true, bool prepareUpdate = true) { Context.RequiresClassHierarchyLock(); Assert.NotNull(name, method); @@ -2468,7 +2479,9 @@ internal void SetMethodNoMutateNoEventNoLock(RubyContext/*!*/ callerContext, str WarnIfRedefiningCoreMethodNoLock(name, method); } - PrepareMethodUpdate(name, method); + if (prepareUpdate) { + PrepareMethodUpdate(name, method); + } InitializeMethodsNoLock(); _methods[name] = method; diff --git a/Src/Ruby/Builtins/RubyStruct.cs b/Src/Ruby/Builtins/RubyStruct.cs index d796c5a56..7eda9dcf9 100644 --- a/Src/Ruby/Builtins/RubyStruct.cs +++ b/Src/Ruby/Builtins/RubyStruct.cs @@ -119,43 +119,90 @@ private RubyStruct(RubyClass/*!*/ rubyClass, object[]/*!*/ data) return new RubyStruct(rubyClass, true); } + /// + /// IR_FAST_STRUCT=0 sends every Struct#initialize but a positional one per member to the slow path in ruby4.rb, and + /// adds a new struct class's methods the way any method is added, moving the global method version. + /// + public static readonly bool FastStruct = Environment.GetEnvironmentVariable("IR_FAST_STRUCT") != "0"; + // triggers "inherited" event, adds constant to the owner public static RubyClass/*!*/ DefineStruct(RubyClass/*!*/ owner, string className, string/*!*/[]/*!*/ attributeNames) { Assert.NotNullItems(attributeNames); - - // MRI: "inherited" event is triggered by DefineClass before the members are defined and the body is evaluated. - // Any exception thrown by the event will cancel struct initialization. - RubyClass result = owner.Context.DefineClass(owner, className, owner, new Info(attributeNames)); - AddClassMembers(result, attributeNames); + // An anonymous class whose superclass's inherited hook is the default has been seen by no code when its + // members are added: no Ruby code ran while it was made and no constant names it. + var context = owner.Context; + bool unseen = FastStruct && className == null && context.IsDefaultHook(owner, RubyClass.Hook.Inherited); + // MRI: "inherited" event is triggered by DefineClass before the members are defined and the body is evaluated. + // Any exception thrown by the event will cancel struct initialization. + RubyClass result = context.DefineClass(owner, className, owner, new Info(attributeNames)); + AddClassMembers(result, attributeNames, unseen && context.IsDefaultHook(owner, RubyClass.Hook.Inherited)); return result; } // add methods to the generated class - private static void AddClassMembers(RubyClass/*!*/ cls, string[]/*!*/ structMembers) { + private static void AddClassMembers(RubyClass/*!*/ cls, string[]/*!*/ structMembers, bool unseen) { var newInstance = new RuleGenerator(RuleGenerators.InstanceConstructor); var context = cls.Context; - var singletonClass = cls.GetOrCreateSingletonClass(); - singletonClass.AddMethod(context, "[]", new RubyCustomMethodInfo(newInstance, RubyMemberFlags.Public, singletonClass)); - singletonClass.AddMethod(context, "new", new RubyCustomMethodInfo(newInstance, RubyMemberFlags.Public, singletonClass)); + // setup_struct's singleton methods: new, [], members, inspect, keyword_init? + var methods = new List>>(5 + 2 * structMembers.Length); + Action add = (module, name, method) => + methods.Add(new KeyValuePair>(module, new KeyValuePair(name, method))); - singletonClass.AddMethod(context, "members", new RubyLibraryMethodInfo( + add(singletonClass, "new", new RubyCustomMethodInfo(newInstance, RubyMemberFlags.Public, singletonClass)); + add(singletonClass, "[]", new RubyCustomMethodInfo(newInstance, RubyMemberFlags.Public, singletonClass)); + add(singletonClass, "members", new RubyLibraryMethodInfo( new[] { LibraryOverload.Create(new Func(GetMembers), false, 0, 0) }, RubyMemberFlags.Public, singletonClass )); + add(singletonClass, "inspect", new RubyLibraryMethodInfo( + new[] { LibraryOverload.Create(new Func(Inspect), false, 0, 0) }, + RubyMemberFlags.Public, + singletonClass + )); + add(singletonClass, "keyword_init?", new RubyLibraryMethodInfo( + new[] { LibraryOverload.Create(new Func(GetKeywordInit), false, 0, 0) }, + RubyMemberFlags.Public, + singletonClass + )); for (int i = 0; i < structMembers.Length; i++) { string getter = structMembers[i]; - // any symbol is a legal member name; the accessors are defined for all of them, // even when the resulting name is not writable as a literal method call - cls.AddMethod(context, getter, new RubyCustomMethodInfo(CreateGetter(i), RubyMemberFlags.Public, cls, 0, i)); - cls.AddMethod(context, getter + '=', new RubyCustomMethodInfo(CreateSetter(i), RubyMemberFlags.Public, cls, 1, i)); + add(cls, getter, new RubyCustomMethodInfo(CreateGetter(i), RubyMemberFlags.Public, cls, 0, i)); + add(cls, getter + '=', new RubyCustomMethodInfo(CreateSetter(i), RubyMemberFlags.Public, cls, 1, i)); + } + + if (unseen) { + // all of them first, then their events, which may run Ruby code (singleton_method_added, method_added) + using (context.ClassHierarchyLocker()) { + foreach (var entry in methods) { + entry.Key.SetMethodOfUnseenModuleNoEventNoLock(entry.Value.Key, entry.Value.Value); + } + } + foreach (var entry in methods) { + entry.Key.MethodAdded(entry.Value.Key); + } + } else { + foreach (var entry in methods) { + entry.Key.AddMethod(context, entry.Value.Key, entry.Value.Value); + } + } + } + + // The struct class's #inspect (MRI's rb_struct_s_inspect): its name, and "(keyword_init: true)" after it for a + // class made with that option. + public static MutableString/*!*/ Inspect(RubyClass/*!*/ self) { + var result = self.GetDisplayName(self.Context, false); + if (RubyOps.IsTrue(GetKeywordInit(self))) { + result = result.Append("(keyword_init: true)"); } + return result; } // Derived struct: [RubyMethod("members", RubyMethodAttributes.PublicSingleton)] diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 6a300c47d..7c17bedfe 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -12424,18 +12424,11 @@ def new(*args, **options, &block) end klass = args.empty? ? __struct_new__(nil) : __struct_new__(*args) - # klass is a new receiver: a call like klass.define_singleton_method would bind a rule - # of its own, every time (hundreds of microseconds). The methods called through - # bind_call share one rule - and are the built-ins, as in MRI's struct.c. + # klass is a new receiver: a call like klass.instance_variable_set would bind a rule of its + # own, every time (hundreds of microseconds). The methods called through bind_call share + # one rule. The class's keyword_init? and inspect (MRI's setup_struct) are RubyStruct's and + # read the option from here. ::Kernel.instance_method(:__ir_set_hidden_ivar__).bind_call(klass, :@__keyword_init__, keyword_init) - define_singleton = ::Kernel.instance_method(:define_singleton_method) - # only classes created by Struct.new answer #keyword_init?, not every Struct subclass - # a subclass answers its superclass's (MRI's struct_ivar_get) - define_singleton.bind_call(klass, :keyword_init?) { __keyword_init__ } - if keyword_init - # MRI: #(keyword_init: true) - define_singleton.bind_call(klass, :inspect) { "#{super()}(keyword_init: true)" } - end ::Module.instance_method(:module_eval).bind_call(klass, &block) if block klass end From c6cdba2dc41ae39668a8c1831e165c57d567bca2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:22:29 +0000 Subject: [PATCH 016/439] Add a differential matrix and timing shapes for define_method bodies in the method JIT Util/dmeth-jit-matrix.rb calls methods made by define_method thousands of times each, past the method JIT's thresholds: the bodies a typed body can be made of (arguments, ivars, calls, constants, loops, return, overflow, recursion, optional arguments), and what a block body must keep that a def does not - captured locals shared with the defining scope, yield and block_given? of the defining method's block, implicit super raising, __method__ under an alias, binding, instance_exec of the same Proc, define_method with a Method/UnboundMethod/lambda, redefinition and remove_method while hot, overrides, a module in two classes, refinements, constants in Class.new. It prints CRuby 4.0's output on master with the JIT on, -X:NoJIT -X:NoOSR and -X:NoJITCalls. Util/bench/dmeth-shapes.rb times define_method methods of no, one and two arguments, an ivar read and a call on self against a def of each, for Util/perf/ab.rb. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Util/bench/dmeth-shapes.rb | 40 ++++++ Util/dmeth-jit-matrix.rb | 242 +++++++++++++++++++++++++++++++++++++ 2 files changed, 282 insertions(+) create mode 100644 Util/bench/dmeth-shapes.rb create mode 100644 Util/dmeth-jit-matrix.rb diff --git a/Util/bench/dmeth-shapes.rb b/Util/bench/dmeth-shapes.rb new file mode 100644 index 000000000..d65eaacce --- /dev/null +++ b/Util/bench/dmeth-shapes.rb @@ -0,0 +1,40 @@ +# Calls of methods made by define_method (gap 23 of Util/perf/LEDGER.md), against a `def' of the same +# body: no, one and two arguments, an instance variable read, a call to another method of self, and a +# body over a captured local (which the method JIT declines). ` ns ' per line, +# for Util/perf/ab.rb; `ruby dmeth-shapes.rb NAME...' runs only the shapes named; N scales the counts. +SCALE = (ENV["N"] || "1").to_f +def t(name, n = 2_000_000) + return unless ARGV.empty? || ARGV.include?(name) + n = (n * SCALE).to_i + best = 1e9; r = nil + 5.times { t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC); r = yield n; d = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0; best = d if d < best } + printf "%-14s %8.1f ns %s\n", name, best * 1e9 / n, r +end +class B + def initialize = (@a = 3) + def helper(x) = x * 2 + define_method(:bm0) { 1 } + define_method(:bm1) { |x| x + 1 } + define_method(:bm2) { |x, y| x + y } + define_method(:bmivar) { @a } + define_method(:bmcall) { |x| helper(x) + 1 } + captured = 1 + define_method(:bmcapt) { |x| x + captured } + def dm0 = 1 + def dm1(x) = x + 1 + def dm2(x, y) = x + y + def dmivar = @a + def dmcall(x) = helper(x) + 1 +end +o = B.new +t("bm0") { |n| i = 0; c = 0; while i < n; c += o.bm0; i += 1; end; c } +t("dm0") { |n| i = 0; c = 0; while i < n; c += o.dm0; i += 1; end; c } +t("bm1") { |n| i = 0; c = 0; while i < n; c = o.bm1(c); i += 1; end; c } +t("dm1") { |n| i = 0; c = 0; while i < n; c = o.dm1(c); i += 1; end; c } +t("bm2") { |n| i = 0; c = 0; while i < n; c += o.bm2(i, 1); i += 1; end; c } +t("dm2") { |n| i = 0; c = 0; while i < n; c += o.dm2(i, 1); i += 1; end; c } +t("bmivar") { |n| i = 0; c = 0; while i < n; c += o.bmivar; i += 1; end; c } +t("dmivar") { |n| i = 0; c = 0; while i < n; c += o.dmivar; i += 1; end; c } +t("bmcall") { |n| i = 0; c = 0; while i < n; c += o.bmcall(i); i += 1; end; c } +t("dmcall") { |n| i = 0; c = 0; while i < n; c += o.dmcall(i); i += 1; end; c } +t("bmcapt") { |n| i = 0; c = 0; while i < n; c = o.bmcapt(c); i += 1; end; c } diff --git a/Util/dmeth-jit-matrix.rb b/Util/dmeth-jit-matrix.rb new file mode 100644 index 000000000..a5f122003 --- /dev/null +++ b/Util/dmeth-jit-matrix.rb @@ -0,0 +1,242 @@ +# Differential matrix for the method JIT taking the body of a method made by define_method (a block body, +# RubyLambdaMethodInfo; IR_JIT_DMETH). Every probe calls its method thousands of times, past the JIT's +# thresholds, so that a typed body is made where one can be and the rows see what it computes, what it +# declines, and what happens when its guards fail (redefinition, remove_method, another receiver class, +# overflow). Util/dmeth-matrix.rb covers the call itself (arity errors, flow control, binding, threads). +# Run under CRuby and under ./ir.sh - with the JIT on, off, without direct calls and with the switch off: +# +# ruby Util/dmeth-jit-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/dmeth-jit-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/dmeth-jit-matrix.rb > /tmp/nojit.txt +# ./ir.sh -X:NoJITCalls Util/dmeth-jit-matrix.rb > /tmp/nocalls.txt +# IR_JIT_DMETH=0 ./ir.sh Util/dmeth-jit-matrix.rb > /tmp/off.txt +# +# All must end with the row `end' and be identical. JIT decisions go to stderr (IR_JIT_VERBOSE=1). + +$stdout.sync = true +FILE = File.basename(__FILE__) +N = 4000 + +def err + yield + :no_error +rescue Exception => e + [e.class, e.message] +end + +def row(name, value) + puts "#{name}: #{value.inspect}" +end + +# the values of every 997th call and of the last +def hot(n = N) + r = [] + v = nil + n.times { |i| v = yield(i); r << v if i % 997 == 0 } + r << v +end + +K = 7 + +class P + def initialize(a) = (@a = a; @f = 1.5) + attr_reader :a + def helper(x) = x * 2 + define_method(:zero) { 42 } + define_method(:one) { |x| x + 1 } + define_method(:two) { |x, y| x * y + 1 } + define_method(:three) { |x, y, z| x - y + z } + define_method(:ivar) { @a } + define_method(:ivar_plus) { |x| @a + x } + define_method(:flt) { |x| @f * x } + define_method(:call_other) { |x| helper(x) + 1 } + define_method(:attr) { |x| a + x } + define_method(:const) { |x| K + x } + define_method(:selfie) { self } + define_method(:store) { |x| @b = x; @b + 1 } + define_method(:cond) { |x| x > 10 ? x - 10 : x + 10 } + define_method(:loop_) { |n| s = 0; i = 0; while i < n; s += i; i += 1; end; s } + define_method(:ret) { |x| return x * 2 if x.odd?; x } + define_method(:big) { |x| x * 4611686018427387904 } + define_method(:div) { |x, y| x / y } + define_method(:fib) { |n| n < 2 ? n : fib(n - 1) + fib(n - 2) } + define_method(:opt) { |x, y = 5| x + y } + define_method(:raiser) { |x| raise ArgumentError, "r#{x}" if x == N - 1; x } +end + +p1 = P.new(3) +row "1. zero/one/two/three", [hot { p1.zero }, hot { |i| p1.one(i) }, hot { |i| p1.two(i, 3) }, hot { |i| p1.three(i, 2, 1) }] +row "2. ivars", [hot { p1.ivar }, hot { |i| p1.ivar_plus(i) }, hot { |i| p1.flt(i) }] +row "3. calls", [hot { |i| p1.call_other(i) }, hot { |i| p1.attr(i) }, hot { |i| p1.const(i) }, hot { p1.selfie.equal?(p1) }] +row "4. store, cond, loop", [hot { |i| p1.store(i) }, p1.instance_variable_get(:@b), hot { |i| p1.cond(i % 20) }, hot { |i| p1.loop_(i % 30) }] +row "5. return", [hot { |i| p1.ret(i) }, (0..9).map { |i| p1.ret(i) }] +row "6. overflow, division", [hot { |i| p1.big(i) }, hot { |i| p1.div(i, 3) }, err { p1.div(1, 0) }, hot { |i| p1.div(i + 0.5, 2) }] +row "7. recursion", [hot(200) { |i| p1.fib(i % 15) }, p1.fib(20)] +row "8. optional", [hot { |i| p1.opt(i) }, hot { |i| p1.opt(i, 1) }] +row "9. raise", [err { hot { |i| p1.raiser(i) } }] +begin + p1.raiser(N - 1) +rescue ArgumentError => e + row "9a. backtrace", [e.backtrace_locations[0].label, e.backtrace_locations[0].lineno == P.instance_method(:raiser).source_location[1]] +end +row "10. mixed argument types", [hot { |i| p1.one(i.odd? ? i : i.to_f) }, hot { |i| p1.one(i.odd? ? i : 2**70) }, err { p1.one("s") }] +row "10a. arity errors hot", [err { p1.one }, err { p1.two(1) }, err { p1.zero(1) }, err { p1.opt }, err { p1.opt(1, 2, 3) }] + +# Captured locals of the defining scope: shared, and writes are seen outside. +class Q + base = 10 + define_method(:read_captured) { |x| x + base } + define_method(:set_base) { |v| base = v } + total = 0 + define_method(:acc) { |x| total += x } + define_method(:total) { total } +end +q = Q.new +r1 = hot { |i| q.read_captured(i) } +q.set_base(100) +row "11. captured locals", [r1, hot { |i| q.read_captured(i) }, hot { |i| q.acc(1) }, q.total] + +# yield and block_given? see the defining method's block, not the call's. +class Y + def self.make(name) + define_method(name) { |x| block_given? ? yield + x : -x } + end + make(:with_block) { 1000 } + make(:without_block) +end +y = Y.new +row "12. yield/block_given? of the defining scope", [hot { |i| y.with_block(i) }, hot { |i| y.without_block(i) }, hot { |i| y.with_block(i) { 5 } }] + +class YBase + def m(x) = [:base, x] + def n(x) = x * 10 +end +class YSub < YBase + define_method(:m) { |x| super } + define_method(:n) { |x| super(x) + 1 } +end +ys = YSub.new +row "13. implicit super raises", [err { ys.m(1) }, hot { err { ys.m(1) } }] +row "13a. explicit super", [hot { |i| ys.n(i) }] + +# __method__ under an alias, binding, instance_exec of the same Proc. +class R + define_method(:who) { __method__ } + alias_method :who2, :who + define_method(:bnd) { |x| _y = x + 1; binding } + PR = proc { |x| x + @v } + define_method(:viapr, &PR) + def initialize = (@v = 9) +end +rr = R.new +row "14. __method__", [hot { rr.who }, hot { rr.who2 }] +row "15. binding", [hot { |i| b = rr.bnd(i); [b.local_variable_get(:x), b.local_variable_get(:_y), b.receiver.equal?(rr)] }] +row "16. instance_exec of the same Proc", [hot { |i| rr.viapr(i) }, hot { |i| rr.instance_exec(i, &R::PR) }, hot { |i| Struct.new(:v).new(3).instance_exec(i) { |z| z } }] + +# define_method with a Method, an UnboundMethod, a lambda. +class M + def plain(x) = x + 100 + define_method(:from_unbound, instance_method(:plain)) + define_method(:from_bound, M.new.method(:plain)) + define_method(:from_lambda, ->(x) { x + 200 }) + define_method(:from_lambda_ret, ->(x) { return x + 300 if x > 0; 0 }) +end +mm = M.new +row "17. Method/UnboundMethod/lambda", [hot { |i| mm.from_unbound(i) }, hot { |i| mm.from_bound(i) }, hot { |i| mm.from_lambda(i) }, hot { |i| mm.from_lambda_ret(i) }, + err { mm.from_lambda }] + +# Redefinition and remove_method while the body is hot; an override in a subclass; a module in two classes. +class H + define_method(:h) { |x| x + 1 } +end +hh = H.new +r1 = hot { |i| hh.h(i) } +H.define_method(:h) { |x| x + 2 } +r2 = hot { |i| hh.h(i) } +class H; def h(x) = x + 3; end +r3 = hot { |i| hh.h(i) } +H.define_method(:h) { |x| x + 4 } +r4 = hot { |i| hh.h(i) } +H.send(:remove_method, :h) +row "18. redefinition and remove_method", [r1, r2, r3, r4, err { hh.h(1) }] + +class HS < P + define_method(:one) { |x| x + 1000 } +end +hs = HS.new(1) +row "19. subclass override", [hot { |i| p1.one(i) }, hot { |i| hs.one(i) }, hot { |i| (i.odd? ? p1 : hs).one(i) }] + +module Mx + define_method(:mx) { |x| @a + x } +end +class A1; include Mx; def initialize = (@a = 1); end +class A2; include Mx; def initialize = (@a = 2.5); end +a1, a2 = A1.new, A2.new +row "20. module in two classes", [hot { |i| a1.mx(i) }, hot { |i| a2.mx(i) }, hot { |i| (i.odd? ? a1 : a2).mx(i) }] + +o = Object.new +o.define_singleton_method(:sm) { |x| x * 2 } +o.instance_variable_set(:@a, 4) +row "21. singleton", [hot { |i| o.sm(i) }] +class << o + define_method(:sm2) { |x| @a * x } +end +row "21a. singleton class body", [hot { |i| o.sm2(i) }] + +row "22. send and method", [hot { |i| p1.send(:one, i) }, hot { |i| p1.method(:two).call(i, 2) }, P.instance_method(:two).arity, P.instance_method(:opt).arity] + +ths = 4.times.map { |t| Thread.new { x = 0; 20_000.times { |i| x += p1.two(i, t) + p1.ivar_plus(t) }; x } } +row "23. threads", ths.map(&:value) + +# frozen receiver: a store raises +pf = P.new(1) +hot { |i| pf.store(i) } +pf.freeze +row "24. store into a frozen receiver", [err { pf.store(1) }.first] + +# refinements visible where the block was written +module Ref + refine Integer do + def +(o) = 99 + end +end +class Rf + using Ref + define_method(:radd) { |x| x + 1 } +end +row "25. refinements", [hot { |i| Rf.new.radd(i) }] + +# Where the block was written: in a method, in Class.new, in a class_eval string; one Proc under two names. +class W + def self.make(name) = define_method(name) { |x| x * 3 } + make(:w3) + make(:w3b) + class_eval "define_method(:ev) { |x| x + 5 }" + PR2 = proc { |x| x + @k.to_i } + define_method(:n1, &PR2) + define_method(:n2, &PR2) + define_method(:defl) { |x, y = (x * 2)| x + y } + define_method(:orassign) { |x| @memo ||= x; @memo + x } + define_method(:keephash) { |h| h } + define_method(:priv) { |x| x - 1 } + private :priv + def callpriv(x) = priv(x) + def takes(x, **kw) = [x, kw] +end +ww = W.new +cn = Class.new { define_method(:cn) { |x| x << 1 } }.new +row "26. written in a method, Class.new, class_eval", [hot { |i| ww.w3(i) }, hot { |i| ww.w3b(i) }, hot { |i| cn.cn(i) }, hot { |i| ww.ev(i) }] +row "27. one Proc, two names", [hot { |i| ww.n1(i) }, hot { |i| ww.n2(i) }] +row "28. default, ||=", [hot { |i| ww.defl(i) }, hot { |i| ww.defl(i, 1) }, hot { |i| ww.orassign(i) }] +row "29. a keyword hash kept", [hot { |i| ww.takes(ww.keephash(a: i)) }] +row "30. private", [hot { |i| ww.callpriv(i) }, err { ww.priv(1) }] + +# Constants resolve where the block was written: in Class.new's block that is outside the new class. +kc = Class.new { const_set(:K, 99); define_method(:kk) { |x| K + x } }.new +module KM + K = 500 + KC = Class.new { define_method(:kk) { |x| K + x } } +end +row "31. constants in Class.new", [hot { |i| kc.kk(i) }, hot { |i| KM::KC.new.kk(i) }] + +puts 'end' From 8bd9781c5529f84f659b36ae51e2b1b2f2310b74 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:22:29 +0000 Subject: [PATCH 017/439] Let the method JIT take the body of a method made by define_method A method made by define_method was called at about twice a def's time (gap 23 of the ledger: 51 ns against 26 for `{ |x| x + 1 }`, CRuby 24): the method JIT works on a def's syntax tree and never took a block as a method body. JitBlockMethod takes a block as the def it would be when nothing in it tells the two apart. BlockDefinition keeps its tree on the dispatcher (BlockDispatcher.JitAst) when the JIT is on and the block uses none of the enclosing scope's locals, has a def's parameters and was not compiled for eval or tracing. At the first call a rule is built for, a screen of its own refuses what in a block means the defining scope's thing - yield and block_given? (the defining method's block), super (implicit super must raise), class variables, __method__, binding, proc/lambda, nested blocks and block-pass, regular expressions and globals - and a MethodDefinition over the block's statements goes to JitStub.Wrap as a def's does, with the Proc's scope for constants and the refinements active there. The stub's generic body is the call Proc.BuildCall's rule made, in C#. RubyLambdaMethodInfo's rule calls the stub for plain arguments (no block, splat or assignment value), passing an omitted optional as the default sentinel and unmarking a trailing keyword hash as the block's dispatcher does. A self-call of the same define_method method binds as a def's (JitStub.SelfCallResolvesHere). IR_JIT_DMETH=0 turns it off. Checked: Util/dmeth-jit-matrix.rb, Util/dmeth-matrix.rb, jit-matrix, jit-calls-matrix and block-given-matrix print CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls and the switch off; inline-matrix (one case per process) prints what master prints. The 69 IronRuby.Tests that use define_method and the 20 named for the JIT pass. ab.rb -r 6, ns a call, off -> new: bm0 51.2 -> 27.3, bm1 51.3 -> 26.5, bm2 60.3 -> 37.5, bmivar 47.3 -> 30.6, bmcall 74.2 -> 39.1; defs level. Not gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/Ruby/Compiler/Ast/BlockDefinition.cs | 35 +++ Src/Ruby/Runtime/Calls/BlockDispatcher.cs | 6 + .../Runtime/Calls/RubyLambdaMethodInfo.cs | 60 +++++ Src/Ruby/Runtime/Jit/JitBlockMethod.cs | 238 ++++++++++++++++++ Src/Ruby/Runtime/Jit/JitStub.cs | 7 +- Util/perf/LEDGER.md | 53 ++++ 6 files changed, 398 insertions(+), 1 deletion(-) create mode 100644 Src/Ruby/Runtime/Jit/JitBlockMethod.cs diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index dbcf43ec3..e55f00b12 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -86,6 +86,35 @@ private bool HasPostParameters { get { return PostParameterCount > 0; } } + /// + /// Parameters a method's typed body takes as a def's (JitStub.ParameterShape): plain mandatory locals, then + /// optional ones, no rest, post, block or keyword parameter. + /// + private bool IsJitMethodShape() { + if (HasFormalParametersInArray || ParameterCount > IronRuby.Runtime.Jit.JitStub.MaxArity) { + return false; + } + var signature = _parameters.Signature; + if (signature != null && (signature.TakesKeywords || signature.RefusesKeywords)) { + return false; + } + foreach (var parameter in _parameters.Mandatory) { + if (!(parameter is LocalVariable)) { + return false; + } + } + foreach (var optional in _parameters.Optional) { + if (!(optional.Left is LocalVariable)) { + return false; + } + } + return true; + } + + public LexicalScope/*!*/ DefinedScope { + get { return _definedScope; } + } + private bool HasUnsplatParameter { get { return _parameters.Unsplat != null; @@ -383,6 +412,12 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St blockDispatcher.LoopInfo = BlockLoopInfo.TryCreate(this, gen.Context, _definedScope.Depth, gen.SourcePath + ":" + Location.Start.Line); } + if (outerVariables == null && !hasNestedReturn && !gen.TraceEnabled && !gen.CompilerOptions.IsEval && + IronRuby.Runtime.Jit.JitBlockMethod.Enabled && gen.Context.RubyOptions.Jit && IsJitMethodShape()) { + // -X:JIT: a block over none of the enclosing scope's locals may become the body of a method + // (define_method), which the method JIT can take as it takes a def's (JitBlockMethod) + blockDispatcher.JitAst = this; + } var dispatcher = Ast.Constant(blockDispatcher, typeof(BlockDispatcher)); string encodedName = RubyStackTraceBuilder.EncodeMethodName(BlockFrameLabel(gen), gen.SourcePath, Location, gen.DebugMode); diff --git a/Src/Ruby/Runtime/Calls/BlockDispatcher.cs b/Src/Ruby/Runtime/Calls/BlockDispatcher.cs index 18e326743..9c16a041e 100644 --- a/Src/Ruby/Runtime/Calls/BlockDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/BlockDispatcher.cs @@ -166,6 +166,12 @@ public abstract class BlockDispatcher { /// internal IronRuby.Runtime.Osr.BlockLoopInfo LoopInfo; + /// + /// -X:JIT: the block literal, when the method JIT may take it as the body of a method made by define_method + /// (JitBlockMethod); null otherwise. + /// + internal IronRuby.Compiler.Ast.BlockDefinition JitAst; + public bool Ruby2Keywords { get { return _ruby2Keywords; } set { _ruby2Keywords = value; } diff --git a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs index d140e3412..40976773c 100644 --- a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs @@ -110,6 +110,31 @@ public Proc/*!*/ Lambda { get { return _lambda; } } + // -X:JIT: what the method JIT made of the block (JitBlockMethod), at the first call a rule was built for; + // NoJit when it took nothing. Each copy (alias, visibility) has its own, as each def copy shares its body's. + private sealed class JitHolder { + internal Delegate Trampoline; + internal IronRuby.Compiler.Ast.MethodDefinition Ast; + } + private static readonly JitHolder NoJit = new JitHolder(); + private JitHolder _jit; + + private JitHolder/*!*/ GetJit() { + var jit = Volatile.Read(ref _jit); + if (jit == null) { + IronRuby.Compiler.Ast.MethodDefinition ast = null; + var trampoline = IronRuby.Runtime.Jit.JitBlockMethod.Enabled ? IronRuby.Runtime.Jit.JitBlockMethod.TryWrap(this, out ast) : null; + jit = (trampoline != null) ? new JitHolder { Trampoline = trampoline, Ast = ast } : NoJit; + jit = Interlocked.CompareExchange(ref _jit, jit, null) ?? jit; + } + return jit; + } + + /// The def the method JIT took the block as, once a call made it (JitStub.SelfCallResolvesHere). + internal IronRuby.Compiler.Ast.MethodDefinition JitAst { + get { var jit = Volatile.Read(ref _jit); return jit != null ? jit.Ast : null; } + } + internal int Id { get { return _id; } } @@ -179,6 +204,37 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA } } + // -X:JIT: plain arguments, as many as the block takes, go to the stub of the method JIT, whose generic body is + // the call below (JitBlockMethod). An omitted optional argument is passed as the default sentinel, as to a def's. + if (!args.Signature.HasBlock && !args.Signature.HasSplattedArgument && !args.Signature.HasRhsArgument) { + var jit = GetJit(); + if (jit.Trampoline != null) { + var simple = args.GetSimpleArgumentExpressions(); + int jitArity = jit.Ast.Parameters.Mandatory.Length + jit.Ast.Parameters.Optional.Length; + if (simple.Count <= jitArity) { + var jitArgs = new Ast[2 + jitArity]; + jitArgs[0] = AstUtils.Box(args.TargetExpression); + jitArgs[1] = IronRuby.Compiler.Ast.AstFactory.NullOfProc; + int k = 0; + foreach (var arg in simple) { + jitArgs[2 + k] = AstUtils.Box(arg); + k++; + } + // the block declares no keywords: a hash passed as keywords is a positional argument it may keep (as + // BlockDispatcher.Positional unmarks it) + if (k > 0) { + jitArgs[1 + k] = Methods.ClearKeywordArguments.OpCall(jitArgs[1 + k]); + } + for (; k < jitArity; k++) { + jitArgs[2 + k] = Ast.Field(null, typeof(RubyOps).GetField("DefaultArgument")); + } + metaBuilder.Result = IronRuby.Runtime.Jit.JitStub.CallCurrent(jit.Trampoline, jitArgs); + AddRactorCheck(metaBuilder, args); + return; + } + } + } + if (args.Signature.HasBlock) { // The call is the flow-control frame of a literal block given to it, as a def method's is (its // RubyMethodScope): a break from the block, wherever the body passes it on to, ends this call. @@ -192,6 +248,10 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA args ); + AddRactorCheck(metaBuilder, args); + } + + private void AddRactorCheck(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args) { // once there are Ractors, a block that is not shareable runs only in the Ractor that defined the method metaBuilder.AddInitialization(Ast.IfThen( Ast.Property(AstUtils.Constant(args.RubyContext), typeof(RubyContext).GetProperty("RactorsStarted")), diff --git a/Src/Ruby/Runtime/Jit/JitBlockMethod.cs b/Src/Ruby/Runtime/Jit/JitBlockMethod.cs new file mode 100644 index 000000000..ea4f3edb4 --- /dev/null +++ b/Src/Ruby/Runtime/Jit/JitBlockMethod.cs @@ -0,0 +1,238 @@ +/* **************************************************************************** + * + * -X:JIT for the body of a method made by define_method. + * + * The method JIT works on a def's syntax tree (MethodDefinition): JitStub wraps the generic body, profiles + * it, and asks JitCompiler for a typed body. A method made by define_method runs a block instead + * (RubyLambdaMethodInfo), which it never took: such a call cost twice a def's (gap 23 of Util/perf/LEDGER.md). + * + * A block can be taken as a def when nothing in it tells the two apart: + * - it reads and writes none of the enclosing scopes' locals (BlockDispatcher.OuterVariableNames is null, + * so BlockDefinition kept its tree: BlockDispatcher.JitAst), and was not compiled for eval or tracing; + * - its parameters are a def's (plain mandatory, then optional; BlockDefinition.IsJitMethodShape); + * - its body has nothing whose meaning is the defining scope's rather than the method's: no yield and no + * block_given? (the defining method's block), no super (implicit super raises; explicit super names the + * method's owner), no class variable (the block's lexical class), no __method__, binding and the like, no + * block, lambda or block-pass, no regular expression or global variable (the frame's $~ and $_). + * The rest is the same: self is the receiver, `return' returns from the method, constants resolve in the + * scope the block was written in (the Proc's LocalScope, as a def's in its declaring scope), and the calls + * see the refinements active there. The JIT's own screen (JitStub.Screen) then decides as for a def. + * + * The generic body the stub falls back to - while profiling, on a guard that fails, on a deopt - is the + * call the rule makes without the JIT (Proc.BuildCall), written in C#. The rule calls the stub for a call + * with plain arguments, no block, splat or assignment value (RubyLambdaMethodInfo.BuildCallNoFlow). + * IR_JIT_DMETH=0 turns it off. + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using IronRuby.Builtins; +using IronRuby.Compiler.Ast; +using IronRuby.Runtime.Calls; + +namespace IronRuby.Runtime.Jit { + using MethodDeclaration = IronRuby.Compiler.Ast.MethodDefinition; + + internal sealed class JitBlockMethod { + internal static readonly bool Enabled = Environment.GetEnvironmentVariable("IR_JIT_DMETH") != "0"; + + private readonly Proc/*!*/ _lambda; + + private JitBlockMethod(Proc/*!*/ lambda) { + _lambda = lambda; + } + + /// + /// The JIT's trampoline for the method, or null when its block is not one the JIT may take (see above). + /// is the def the block is taken as, which the stub specializes. + /// + internal static Delegate TryWrap(RubyLambdaMethodInfo/*!*/ method, out MethodDeclaration ast) { + ast = null; + var lambda = method.Lambda; + var block = lambda.Dispatcher.JitAst; + var context = method.DeclaringModule.Context; + if (block == null || !context.RubyOptions.Jit) { return null; } + + string rejectedBy = BlockScreen.Rejects(block); + if (rejectedBy != null) { + if (JitRuntime.Verbose) { + Console.Error.WriteLine("[jit] define_method {0}/{1} not taken: {2}", method.DeclaringModule.Name ?? "main", method.DefinitionName, rejectedBy); + } + return null; + } + + var location = block.Location; + var def = new MethodDeclaration(block.DefinedScope, null, method.DefinitionName, block.Parameters, + new Body(block.Body, null, null, null, location), location) { + // the body neither yields nor passes a block on (BlockScreen): the call's block is nothing to it + UsesBlock = false + }; + + // The refinements the block's calls see are those active where it was written. + var scope = lambda.LocalScope; + StrongBox refinements = null; + if (context.HasRefinements) { + var active = scope.GetActiveRefinements(); + if (!active.IsEmpty) { + refinements = new StrongBox(active); + } + } + + var generic = new JitBlockMethod(lambda).MakeGeneric(def.Parameters.Mandatory.Length + def.Parameters.Optional.Length); + if (generic == null) { return null; } + var result = JitStub.Wrap(generic, def, context, method.DeclaringModule, scope, refinements); + if (result == generic) { return null; } + ast = def; + return result; + } + + private Delegate MakeGeneric(int arity) { + switch (arity) { + case 0: return new Func(Call0); + case 1: return new Func(Call1); + case 2: return new Func(Call2); + case 3: return new Func(Call3); + case 4: return new Func(Call4); + case 5: return new Func(Call5); + case 6: return new Func(Call6); + default: return null; + } + } + + // What the rule of Proc.BuildCall does: a BlockParam for the call, the yield, and a return from a block + // nested in the body caught at this call. An omitted optional argument arrives as RubyOps.DefaultArgument, + // which is what the dispatcher would hand the body for it. + + private object Call0(object self, Proc block) { + var bfc = RubyOps.CreateBfcForProcCall(_lambda); + try { + return RubyOps.MethodProcCall(bfc, RubyOps.Yield0(block, self, bfc)); + } catch (Exception e) when (RubyOps.IsLambdaUnwinderTarget(bfc, e)) { + return RubyOps.GetLambdaUnwinderReturnValue(e); + } finally { + RubyOps.LeaveProcCall(bfc); + } + } + + private object Call1(object self, Proc block, object a0) { + var bfc = RubyOps.CreateBfcForProcCall(_lambda); + try { + return RubyOps.MethodProcCall(bfc, RubyOps.Yield1(a0, block, self, bfc)); + } catch (Exception e) when (RubyOps.IsLambdaUnwinderTarget(bfc, e)) { + return RubyOps.GetLambdaUnwinderReturnValue(e); + } finally { + RubyOps.LeaveProcCall(bfc); + } + } + + private object Call2(object self, Proc block, object a0, object a1) { + var bfc = RubyOps.CreateBfcForProcCall(_lambda); + try { + return RubyOps.MethodProcCall(bfc, RubyOps.Yield2(a0, a1, block, self, bfc)); + } catch (Exception e) when (RubyOps.IsLambdaUnwinderTarget(bfc, e)) { + return RubyOps.GetLambdaUnwinderReturnValue(e); + } finally { + RubyOps.LeaveProcCall(bfc); + } + } + + private object Call3(object self, Proc block, object a0, object a1, object a2) { + var bfc = RubyOps.CreateBfcForProcCall(_lambda); + try { + return RubyOps.MethodProcCall(bfc, RubyOps.Yield3(a0, a1, a2, block, self, bfc)); + } catch (Exception e) when (RubyOps.IsLambdaUnwinderTarget(bfc, e)) { + return RubyOps.GetLambdaUnwinderReturnValue(e); + } finally { + RubyOps.LeaveProcCall(bfc); + } + } + + private object Call4(object self, Proc block, object a0, object a1, object a2, object a3) { + var bfc = RubyOps.CreateBfcForProcCall(_lambda); + try { + return RubyOps.MethodProcCall(bfc, RubyOps.Yield4(a0, a1, a2, a3, block, self, bfc)); + } catch (Exception e) when (RubyOps.IsLambdaUnwinderTarget(bfc, e)) { + return RubyOps.GetLambdaUnwinderReturnValue(e); + } finally { + RubyOps.LeaveProcCall(bfc); + } + } + + private object Call5(object self, Proc block, object a0, object a1, object a2, object a3, object a4) { + return CallN(self, block, new[] { a0, a1, a2, a3, a4 }); + } + + private object Call6(object self, Proc block, object a0, object a1, object a2, object a3, object a4, object a5) { + return CallN(self, block, new[] { a0, a1, a2, a3, a4, a5 }); + } + + private object CallN(object self, Proc block, object[]/*!*/ args) { + var bfc = RubyOps.CreateBfcForProcCall(_lambda); + try { + return RubyOps.MethodProcCall(bfc, RubyOps.YieldN(args, block, self, bfc)); + } catch (Exception e) when (RubyOps.IsLambdaUnwinderTarget(bfc, e)) { + return RubyOps.GetLambdaUnwinderReturnValue(e); + } finally { + RubyOps.LeaveProcCall(bfc); + } + } + + /// What in a block body means something else in a def's (see the header). + private sealed class BlockScreen : Walker { + // Calls on self that answer for the frame they are made in, which is the block's. + private static readonly HashSet FrameCalls = new HashSet { + "block_given?", "iterator?", "__method__", "__callee__", "__dir__", "binding", "local_variables", + "proc", "lambda", "eval", "caller", "caller_locations", "define_method", "instance_eval", "instance_exec", + "class_eval", "module_eval", "class_exec", "module_exec", "using", "require_relative", "autoload", + }; + + private string _rejectedBy; + + internal static string Rejects(BlockDefinition/*!*/ block) { + var screen = new BlockScreen(); + try { + foreach (var statement in block.Body) { + screen.Walk(statement); + if (screen._rejectedBy != null) { break; } + } + foreach (var optional in block.Parameters.Optional) { + if (screen._rejectedBy != null) { break; } + screen.Walk(optional.Right); + } + } catch (Exception) { + screen._rejectedBy = "screen-error"; + } + return screen._rejectedBy; + } + + private bool No(string/*!*/ what) { + if (_rejectedBy == null) { _rejectedBy = what; } + return false; + } + + public override bool Enter(YieldCall/*!*/ node) { return No("yield"); } + public override bool Enter(SuperCall/*!*/ node) { return No("super"); } + public override bool Enter(ClassVariable/*!*/ node) { return No("class variable"); } + public override bool Enter(IronRuby.Compiler.Ast.GlobalVariable/*!*/ node) { return No("global variable"); } + public override bool Enter(RegexMatchReference/*!*/ node) { return No("match reference"); } + public override bool Enter(RegularExpression/*!*/ node) { return No("regular expression"); } + public override bool Enter(RegularExpressionCondition/*!*/ node) { return No("regular expression"); } + public override bool Enter(BlockDefinition/*!*/ node) { return No("block"); } + public override bool Enter(LambdaDefinition/*!*/ node) { return No("lambda"); } + public override bool Enter(BlockReference/*!*/ node) { return No("block-pass"); } + public override bool Enter(MethodDefinition/*!*/ node) { return No("def"); } + public override bool Enter(ClassDefinition/*!*/ node) { return No("class"); } + public override bool Enter(ModuleDefinition/*!*/ node) { return No("module"); } + public override bool Enter(SingletonDefinition/*!*/ node) { return No("class << self"); } + + public override bool Enter(MethodCall/*!*/ node) { + if ((node.Target == null || node.Target is SelfReference) && FrameCalls.Contains(node.MethodName)) { + return No(node.MethodName); + } + return true; + } + } + } +} diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index c83d7a13a..bfe37c97e 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -1182,7 +1182,12 @@ private bool SelfCallResolvesHere(RubyClass/*!*/ cls, RefinementActivation/*!*/ var resolved = cls.ResolveMethod(_ast.Name, VisibilityContext.AllVisible, refinements); if (!resolved.Found) { return false; } var info = resolved.Info as RubyMethodInfo; - return info != null && ReferenceEquals(info.GetSyntaxTree(), _ast); + if (info == null) { + // a method made by define_method calling itself: the def its block was taken as (JitBlockMethod) + var lambda = resolved.Info as RubyLambdaMethodInfo; + return lambda != null && ReferenceEquals(lambda.JitAst, _ast); + } + return ReferenceEquals(info.GetSyntaxTree(), _ast); } // ---- entry lambda ------------------------------------------------------------------ diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..ace194eac 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1074,6 +1074,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Tried in round thirty-one (see Rejected, perf/dmeth): without the method JIT the call is only about 1.15 times a `def`'s, and a pooled BlockParam and a direct rule bought 1.16-1.2; what is left is the JIT taking a block body (a `JitStub` over a `BlockDefinition`). + Round of 2026-11-26 (see Landed, perf/dmethjit, not gated): taken; `bm1` 51 -> 26.5 ns against + CRuby's 24. Left: bodies over captured locals, `block_given?`/`yield` or `super`, and calls with a + block or a splat, which still take the rule. 24. **Struct with `keyword_init: true`: creating an object is 3.2 times CRuby** (1162 against 369 ns; positional creation is level at 142 against 131). And `h.each_pair { |k, v| }` / `each_with_index` are 1.6 to 1.9 times CRuby (gap 13 with @@ -1384,6 +1387,56 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/dmethjit (2026-11-26) - the method JIT takes the body of a method made by `define_method` + (gap 23)** - not gated. `JitBlockMethod` (Runtime/Jit) takes a block as the `def` it would be + when nothing in it tells the two apart: BlockDefinition keeps its tree on the dispatcher + (`BlockDispatcher.JitAst`) when the block reads and writes none of the enclosing scope's locals, + has a def's parameters (plain mandatory, then optional; no rest, post, block or keyword one) and + was not compiled for eval or tracing; at the first call a rule is built for, its own screen refuses + what means the defining scope's thing in a block (yield, `block_given?`, `super`, class variables, + `__method__`, `binding`, `proc`/`lambda`, nested blocks and block-pass, regular expressions and + globals); then a synthetic `MethodDefinition` over the block's statements goes to `JitStub.Wrap` as a + def's would, with the Proc's `LocalScope` for its constants and the refinements active there. The + stub's generic body is the call the rule made (`Proc.BuildCall`) written in C#; the rule of + `RubyLambdaMethodInfo` calls the stub for plain arguments (no block, splat or assignment value), + passing omitted optionals as the default sentinel and unmarking a trailing keyword hash. + `JitStub.SelfCallResolvesHere` takes a self-call of the same define_method method (recursion). + Switch: `IR_JIT_DMETH=0`. + - The census counts only `def`s and moves by nothing (28,376 methods, 0 changed). Judged instead + by a traced run and a timed one. `Util/bench/dmeth-shapes.rb` under IR_JIT_VERBOSE=1: every + `bm*` shape specialized but `bmcapt` (a captured local: not taken). Traces of + `Util/bench/app-shapes.rb` and AWFY Richards, DeltaBlue, Json, CD: the same specialized (113, 78) + and declined-after-the-pre-screen (29, 19) counts as the baseline - none of their methods is an + eligible define_method body (delegate's and forwardable's take `*args, &block`). + - Timing (`ab.rb -r 6`, ns a call; CRuby / master / switch off / new, new over off): `bm0` 22.1 / + 50.0 / 51.2 / 27.3 (0.53), `bm1` 24.2 / 51.4 / 51.3 / 26.5 (0.52), `bm2` 30.2 / 60.0 / 60.3 / + 37.5 (0.62), `bmivar` 21.6 / 48.1 / 47.3 / 30.6 (0.65), `bmcall` 41.4 / 69.9 / 74.2 / 39.1 + (0.53); the `def` controls and `bmcapt` level (0.90-1.01, overlap). An omitted optional argument + (`{ |x, y = 2| }` called with one) 93.9 -> 38.5. A body wrapped and then declined (a `return`, a + `nil.to_i`) costs what it did (0.99, 1.04 overlap). + - Slower: a body whose typed version keeps deopting (`{ |x| x + 1 }` called with an Integer and a + Float in turn) 98.2 -> 107.7 (1.10, alone, -r 8) - the stub's retire-and-retry cycle, which a + `def` of the same body pays as well (1.12 against -X:NoJIT). + - Matrices, CRuby against master against new: `Util/dmeth-jit-matrix.rb` (new: 31 rows - every + shape the JIT takes, captured locals read and written, the defining method's block, implicit and + explicit super, `__method__` under an alias, binding, instance_exec of the same Proc, define_method + with a Method/UnboundMethod/lambda, redefinition and remove_method while hot, a subclass override, a + module in two classes with different ivar types, refinements, Class.new constants, a kept keyword + hash), `Util/dmeth-matrix.rb`, `jit-matrix`, `jit-calls-matrix`, `block-given-matrix` with the JIT + on, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and the switch off: all identical to CRuby. + `Util/perf/inline-matrix.rb` (one case per process, the same modes): new identical to master; + both differ from CRuby in `tree_int_key` ("Object must be of type Int32." where CRuby says + "undefined method 'compare_to' for an instance of Integer"), as on master. IronRuby.Tests: the 69 + registered tests that use define_method and the 20 named for the JIT pass. + - Found on master, not fixed: two define_method methods made from the same Proc are `==` as + UnboundMethods in CRuby and not in IronRuby (`W.instance_method(:n1) == W.instance_method(:n2)`). + - For the gate: the rule now calls a JIT stub for every eligible define_method method, so a + wrong typed body shows in any code that defines methods this way; the block's tree is kept on + its dispatcher for the life of the Proc when the JIT is on (one reference per eligible literal, + as `LoopInfo` already does); the generic body re-implements Proc.BuildCall's rule in C# + (`JitBlockMethod.Call0..CallN`): a difference in break/return/LambdaUnwinder handling would show + there first. + - **perf/first-bind (2026-11-26) - what a first bind costs, split; light-scope sites call library methods through a dispatcher for their first calls (gap 26).** The split (master 4bae83f3, R2R host with the startup library; `IR_BIND_TRACE`, `IR_PHASE_TIMES`, perf with jitdump classing From c4a89fc8aa29e25d1e2b7819655b11a2ca66d5a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:23:59 +0000 Subject: [PATCH 018/439] Call a Struct member's reader through a precompiled dispatcher A struct class's readers are RubyCustomMethodInfos whose rule generators are closures made per member of each class (RubyStruct.CreateGetter), so no rule is shared between two classes and the first call of a getter on each new struct class built and interpreted a rule of its own (gap 19: 32-577 us under IR_BIND_TRACE=1). RubyCustomMethodInfo.GetDispatcher now gives a member's reader, called with nothing at a site with a scope, a RubyStructReaderDispatcher: the receiver is a RubyStruct of the class version the call resolved for, and the member at its index is read as the rule reads it; anything else is handed on as every dispatcher hands a miss on. A light site takes it too: it reads no scope, and BindPrecompiled resolves a light site's call as public and unrefined and leaves a refinement-sensitive name to the rule, as for an attribute reader. Writers keep their rules. IR_FAST_STRUCT=0 leaves readers to their rules. IR_BIND_TRACE=1: the first `a' on each new struct class is `pre', 4-9 us. Util/struct-matrix.rb prints CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Ruby/Runtime/Calls/MethodDispatcher.cs | 24 +++++++++++++++++++ Src/Ruby/Runtime/Calls/RubyCallAction.cs | 3 ++- .../Runtime/Calls/RubyCustomMethodInfo.cs | 22 +++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/Calls/MethodDispatcher.cs b/Src/Ruby/Runtime/Calls/MethodDispatcher.cs index 69df6209f..91fc7c72d 100644 --- a/Src/Ruby/Runtime/Calls/MethodDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/MethodDispatcher.cs @@ -414,4 +414,28 @@ public object Invoke(CallSite/*!*/ callSite, TScope/*!*/ scope, object s } } } + + /// A Struct member's reader (RubyCustomMethodInfo.GetDispatcher): the member at its index, for a receiver of the class the call resolved for. + public sealed class RubyStructReaderDispatcher : MemberDispatcher { + private readonly int _index; + + internal RubyStructReaderDispatcher(int index, int version) { + _index = index; + Version = version; + } + + public override object/*!*/ CreateDelegate(bool isUntyped) { + return isUntyped ? + (object)new Func(Invoke) : + (object)new Func(Invoke); + } + + public object Invoke(CallSite/*!*/ callSite, TScope/*!*/ scope, object self) { + var s = self as RubyStruct; + if (s != null && s.ImmediateClass.Version.Method == Version) { + return RubyStruct.GetValue(s, _index); + } + return Miss>(callSite)(callSite, scope, self); + } + } } diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 84ecc49d5..dc8cb4682 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -263,7 +263,8 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ null; } - dispatcher = (!light || rubyMethod != null || method.Info is RubyAttributeAccessorInfo) ? + dispatcher = (!light || rubyMethod != null || method.Info is RubyAttributeAccessorInfo || + method.Info is RubyCustomMethodInfo customReader && customReader.IsStructReader) ? method.Info.GetDispatcher(delegateType, Signature, target, version) : null; // a Ruby method of a builtin class (much of the core library is written in Ruby), called on nil, true, false or a CLR object: diff --git a/Src/Ruby/Runtime/Calls/RubyCustomMethodInfo.cs b/Src/Ruby/Runtime/Calls/RubyCustomMethodInfo.cs index 9b3324488..2a806d8fa 100644 --- a/Src/Ruby/Runtime/Calls/RubyCustomMethodInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyCustomMethodInfo.cs @@ -121,5 +121,27 @@ public override int GetArity() { public override RubyMemberInfo TrySelectOverload(Type/*!*/[]/*!*/ parameterTypes) { return this; } + + /// A Struct member's reader. + internal bool IsStructReader { get { return _structMember >= 0 && _arity == 0; } } + + /// + /// A Struct member's reader called with nothing: a dispatcher that reads the member, as the rule does (RubyStruct's + /// CreateGetter). The rule's generator is a closure made per member of each struct class, so no rule is shared between + /// two classes, and without this the first call of a getter on each new class built and interpreted one (gap 19). + /// + internal override MemberDispatcher GetDispatcher(Type/*!*/ delegateType, RubyCallSignature signature, object target, int version) { + if (!IsStructReader || !RubyStruct.FastStruct || !(target is RubyStruct) || + signature.ArgumentCount != 0 || signature.HasRhsArgument || signature.HasBlock || signature.HasSplattedArgument || + !signature.HasScope) { + return null; + } + // the site's (scope, receiver) as RubyObjectAttributeReaderDispatcherWithScope takes them, typed or untyped + if (delegateType != typeof(Func) && + delegateType != typeof(Func)) { + return null; + } + return new RubyStructReaderDispatcher(_structMember, version); + } } } From e25ce0f00e30c75bd66b5bd3630c9e7c7042a05e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:25:21 +0000 Subject: [PATCH 019/439] Defer the stack walk of the StopIteration that ends a cursor's iteration An Enumerator#next over a built-in source (Array, Hash, Range, Integer#times...) already runs on a cursor with no fiber, at 67-94 ns against CRuby's 226-234. What each such iteration still paid was its end: a StopIteration thrown from C# took the catch-site walk of the whole CLR stack as soon as a frame rescued it, 22-24 us against CRuby's 0.8, where an exception Kernel#raise makes defers the walk until something exposes it (RubyExceptionData.TryDeferCatchSite). The cursor's StopIteration is now marked unkept, unless a TracePoint is enabled. The first one, which the cursor keeps as the cause of the ones raised after it, takes the walk when it is handed out as a cause (ExposeCatchSite). Kernel#loop rescued StopIteration with `=> stop`, which exposed it; it now reads the result of $! without exposing it (Enumerator.__rescued_stop_result__), and calls #result as before when that is not the prelude's own. IR_FAST_NEXT=0 turns both off. Util/bench/extiter-shapes.rb (ab.rb -r 6, new/off): a 4-element Array drained with begin/rescue 0.20 (1265 ns per next, CRuby 1395), with loop 0.25, `next` after the end 0.16, a Hash of 100 0.57, 1000-element Array/Range and peek 0.77-0.79; the fiber-backed controls overlap. Util/extiter-matrix.rb (131 probes, including causes' backtraces after the frame that dropped the first end has returned) prints CRuby's output on the baseline, the change and the change switched off; enum-next, enum, jit, raise, hash-order and other matrices agree with the baseline; spec/core/enumerator, kernel/loop, exception, enumerable and language/rescue pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Src/Libraries/Builtins/Enumerator.cs | 47 ++- Src/Ruby/Runtime/RubyContext.cs | 5 +- Src/Ruby/Runtime/RubyExceptionData.cs | 10 + Src/StdLib/ironruby/ruby4.rb | 6 +- Util/bench/extiter-shapes.rb | 66 ++++ Util/extiter-matrix.rb | 472 ++++++++++++++++++++++++++ Util/perf/LEDGER.md | 49 ++- 7 files changed, 648 insertions(+), 7 deletions(-) create mode 100644 Util/bench/extiter-shapes.rb create mode 100644 Util/extiter-matrix.rb diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index 80fde7a4b..28d6e0806 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -579,6 +579,7 @@ private sealed class PreludeMethods { internal RubyMemberInfo StructEach; internal RubyMemberInfo EachSlice; internal RubyMemberInfo EachCons; + internal RubyMemberInfo StopIterationResult; } private static readonly object _preludeMethodsKey = new object(); @@ -604,6 +605,8 @@ public static object RegisterCursorMethod(RubyContext/*!*/ context, object self, methods.EachSlice = method.Info; } else if (name == "each_cons") { methods.EachCons = method.Info; + } else if (name == "result") { + methods.StopIterationResult = method.Info; } } return null; @@ -904,7 +907,29 @@ private static object CursorStep(CallSiteStorage + /// The StopIteration a cursor throws is one nothing can have kept, as one Kernel#raise makes (RaisedUnkept): it is made + /// here, of the built-in class, with no Ruby code run, and thrown at once. So the frame that rescues it may leave the walk + /// of the stack below it - most of what a raise costs here, and an iteration ends with one - until the exception is + /// exposed, and a `loop { e.next }` or a `rescue StopIteration` that drops it never takes the walk. The first one the cursor + /// does keep, to be the cause of the ones after it, and takes the walk when it hands it out as one (CursorStep). Not while a + /// TracePoint is enabled, which may see it go by and keep it. + /// + private static bool ThrowsUnkept() { + return _fastNext && TracePoint.ActiveEvents == 0; } private static StopIteration/*!*/ CreateStopIteration(RubyContext/*!*/ context, object result, StopIteration cause) { @@ -993,6 +1018,26 @@ public static object Feed(RubyContext/*!*/ context, Enumerator/*!*/ self, object return null; } + /// + /// Kernel#loop's `rescue StopIteration => stop; stop.result`, without the `=> stop`: that hands the exception to Ruby code, + /// which takes the walk of the stack for its backtrace (RubyExceptionData.TryDeferCatchSite), and the walk is most of what + /// ending a `loop { e.next }` costs. The result is read here from the exception being rescued ($!), which nothing sees; + /// unless #result is not the prelude's own (redefined, or a subclass's or a singleton's), which is then called with the + /// exception, exposed first as `=> stop` would have. + /// + [RubyMethod("__rescued_stop_result__", RubyMethodAttributes.PublicSingleton)] + public static object GetRescuedStopResult(CallSiteStorage>/*!*/ resultStorage, RubyClass/*!*/ self) { + RubyContext context = resultStorage.Context; + Exception stop = context.CurrentExceptionNoExpose; + object result; + if (_fastNext && stop is StopIteration && + IsPreludeMethod(context, stop, "result", GetPreludeMethods(context).StopIterationResult)) { + return context.TryGetInstanceVariable(stop, RubyUtils.GetCoreStateInstanceVariableName("@__result__"), out result) ? result : null; + } + var site = resultStorage.GetCallSite("result", 0); + return site.Target(site, context.CurrentException); + } + /// /// For the fiber: takes the fed value, if any, as the suspended yield returns. /// diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 45a135cd9..f128e69d3 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3568,9 +3568,10 @@ public Exception CurrentException { /// /// $! for code that only keeps it to restore it later, or to throw it on out of the frame that caught it, which completes - /// its backtrace itself. + /// its backtrace itself - or that reads it without handing it to anything that could keep it (Kernel#loop takes the + /// result of the StopIteration it rescued, Enumerator.__rescued_stop_result__). /// - internal Exception CurrentExceptionNoExpose { + public Exception CurrentExceptionNoExpose { get { return _currentException; } } diff --git a/Src/Ruby/Runtime/RubyExceptionData.cs b/Src/Ruby/Runtime/RubyExceptionData.cs index 5ff0cafc8..d4da51a28 100644 --- a/Src/Ruby/Runtime/RubyExceptionData.cs +++ b/Src/Ruby/Runtime/RubyExceptionData.cs @@ -516,6 +516,16 @@ internal static void ResolveCatchSite(Exception exception) { } } + /// + /// for a library that keeps an exception it threw as one nothing had kept + /// () and hands it to Ruby code later: an Enumerator's external iteration keeps the StopIteration + /// of its end, to be the cause of the ones it raises after it. The walk is taken from where this is called, which has the + /// catching frame's callers below it for as long as that frame lives. + /// + public static void ExposeCatchSite(Exception exception) { + ResolveCatchSite(exception); + } + internal static bool IsCatchSitePending(Exception/*!*/ exception) { var data = TryGetInstance(exception); return data != null && data._pendingCatchSite != null; diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 329b23a18..cefe3c96d 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -6849,6 +6849,7 @@ def __set_result__(value) def result @__result__ end + ::Enumerator.__iter_cursor_method__(self, :result) end module Kernel @@ -6873,8 +6874,9 @@ def loop return to_enum(:loop) { ::Float::INFINITY } unless block_given? begin yield while true - rescue ::StopIteration => stop - stop.result + rescue ::StopIteration + # stop.result, without the `=> stop` that would take the walk of the stack for a backtrace nobody reads + ::Enumerator.__rescued_stop_result__ end end end diff --git a/Util/bench/extiter-shapes.rb b/Util/bench/extiter-shapes.rb new file mode 100644 index 000000000..0f3c52bc7 --- /dev/null +++ b/Util/bench/extiter-shapes.rb @@ -0,0 +1,66 @@ +# External iteration (Enumerator#next, #peek) over sources whose #each needs no fiber, and controls +# that keep theirs (LEDGER gap 35). Each shape makes an enumerator and takes ITEMS values from it with +# #next, so a row is the cost of one #next (the enumerator's making spread over the items). +$stdout.sync = true +# Process CPU, not the thread's: a fiber is another thread here, and its work is the point. +def cpu = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times do + t0 = cpu; sum = yield n; d = cpu - t0 + best = d if d < best + end + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +N = (ENV["N"] || 1000).to_i +def n(c) = [c * N / 1000, 1].max + +SMALL = [1, 2, 3, 4] +LARGE = (1..1000).to_a +HSH = (1..100).to_h { |i| [i, i * 2] } + +# all of e's values with #next: the loop ends on StopIteration, as loop { } does +def drain(e) + s = 0 + begin + while true + v = e.next + s += v.is_a?(Array) ? v[0] + v[1].to_i : v + end + rescue StopIteration + end + s +end + +def peeks(e) + s = 0 + begin + while true + s += e.peek + e.next + end + rescue StopIteration + end + s +end + +# per #next: the count is in items +t("ary_small", n(200_000)) { |n| s = 0; (n / 4).times { s += drain(SMALL.each) }; s } +t("ary_large", n(200_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.each) }; s } +t("range", n(200_000)) { |n| s = 0; (n / 1000).times { s += drain((1..1000).each) }; s } +t("hash", n(100_000)) { |n| s = 0; (n / 100).times { s += drain(HSH.each) }; s } +t("loop_small", n(200_000)) { |n| s = 0; (n / 4).times { e = SMALL.each; loop { s += e.next } }; s } +t("rescue_end", n(20_000)) { |n| s = 0; e = SMALL.each; n.times { begin; e.next; rescue StopIteration; s += 1; end }; s } +# a control: Array#zip takes an enumerator's items with #each (MRI's take_items), not with #next +t("zip_short", n(20_000)) { |n| s = 0; (n / 8).times { SMALL.zip(SMALL.each, [1, 2].each) { |a, b, c| s += a + b + c.to_i } }; s } +t("peek", n(100_000)) { |n| s = 0; (n / 1000).times { s += peeks(LARGE.each) }; s } +t("map_next", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.map) }; s } +t("ewi_next", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.each.with_index) }; s } +t("select_next", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.select) }; s } +t("lazy_next", n(5_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.lazy.map { |x| x + 1 }) }; s } +t("produce", n(20_000)) { |n| s = 0; (n / 1000).times { e = Enumerator.produce(1) { |x| x + 1 }; 1000.times { s += e.next } }; s } +t("zip_enum", n(20_000)) { |n| s = 0; (n / 1000).times { LARGE.zip(LARGE.each) { |a, b| s += a + b } }; s } +# controls: these keep their fiber (a generator; map, select, with_index, lazy and produce above too) +t("generator", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(Enumerator.new { |y| LARGE.each { |x| y << x } }) }; s } diff --git a/Util/extiter-matrix.rb b/Util/extiter-matrix.rb new file mode 100644 index 000000000..6731ff513 --- /dev/null +++ b/Util/extiter-matrix.rb @@ -0,0 +1,472 @@ +# External iteration (Enumerator#next, #peek, #rewind, #feed...) over the sources a cursor walks +# without a fiber (Enumerator.cs) and over the ones that keep their fiber, and the StopIteration that +# ends it: its result, its cause, its backtrace. Prints one line per probe; CRuby 4.0, the unchanged +# build and the candidate must print the same (LEDGER gap 35, perf/extiter). +# +# ruby Util/extiter-matrix.rb > a; ./ir.sh Util/extiter-matrix.rb > b; diff a b +$stdout.sync = true + +def probe(name) + r = begin + yield + rescue Exception => e + "#{e.class}: #{e.message}" + end + puts "#{name}: #{r.inspect}" +end + +# a backtrace without the path of this file +def bt(e) = (e.backtrace || []).map { |l| l.sub(/\A.*extiter-matrix\.rb:/, "") }.first(4) + +def drain(e) + out = [] + loop { out << e.next } + out +end + +def stop_of(e) + loop { e.next } + begin + e.next + rescue StopIteration => s + s + end +end + +# --- what each source yields, and what #each answers -------------------------------------- +probe("ary") { drain([1, 2, 3].each) } +probe("ary_empty") { drain([].each) } +probe("range") { drain((1..4).each) } +probe("range_excl") { drain((1...4).each) } +probe("range_endless"){ e = (1..).each; [e.next, e.next, e.next] } +probe("hash") { drain({ a: 1, b: 2 }.each) } +probe("hash_pair") { drain({ a: 1, b: 2 }.each_pair) } +probe("hash_keys") { drain({ a: 1, b: 2 }.each_key) } +probe("hash_values") { drain({ a: 1, b: 2 }.each_value) } +probe("times") { drain(3.times) } +probe("upto") { drain(1.upto(3)) } +probe("downto") { drain(3.downto(1)) } +probe("each_index") { drain(%w[a b c].each_index) } +probe("reverse_each") { drain([1, 2, 3].reverse_each) } +probe("ewi") { drain([:a, :b].each_with_index) } +probe("each_slice") { drain([1, 2, 3, 4, 5].each_slice(2)) } +probe("each_cons") { drain([1, 2, 3, 4].each_cons(2)) } +probe("bytes") { drain("ab".each_byte) } +probe("chars") { drain("ab".each_char) } +probe("struct") { S1 = Struct.new(:a, :b) unless defined?(S1); drain(S1.new(1, 2).each) } +probe("with_index") { drain([:a, :b].each.with_index(1)) } +probe("map") { drain([1, 2].map) } +probe("select") { drain([1, 2].select) } +probe("lazy") { drain([1, 2, 3].lazy.map { |x| x * 2 }) } +probe("generator") { drain(Enumerator.new { |y| y << 1; y.yield 2, 3; y << 4; :gen_done }) } +probe("produce") { e = Enumerator.produce(1) { |x| x * 2 }; [e.next, e.next, e.next, e.next] } +probe("produce_stop") { e = Enumerator.produce(1) { |x| x < 3 ? x + 1 : raise(StopIteration) }; drain(e) } +probe("chain") { drain([1].each + [2, 3]) } + +# --- StopIteration#result: what #each answered --------------------------------------------- +a = [1, 2] +probe("result_ary") { stop_of(a.each).result.equal?(a) } +probe("result_hash") { h = { x: 1 }; stop_of(h.each).result.equal?(h) } +probe("result_range") { stop_of((1..2).each).result } +probe("result_times") { stop_of(2.times).result } +probe("result_gen") { stop_of(Enumerator.new { |y| y << 1; :gen_result }).result } +probe("result_map") { stop_of([1, 2].map).result } +probe("result_slice") { stop_of([1, 2, 3].each_slice(2)).result } +probe("loop_value") { e = [1, 2].each; loop { e.next } } +probe("loop_gen") { e = Enumerator.new { |y| y << 1; 42 }; loop { e.next } } +probe("loop_nested") { e = [1].each; f = [2, 3].each; r = loop { e.next; loop { f.next } }; r } +probe("loop_other_stop") { loop { raise StopIteration, "mine" } } +probe("stop_message") { e = [].each; begin; e.next; rescue StopIteration => s; [s.class, s.message, s.result]; end } + +# --- the end, raised again: a new StopIteration each time whose cause is the first --------- +probe("stop_again") do + e = [1].each + e.next + s1 = (e.next rescue $!) + s2 = (e.next rescue $!) + s3 = (e.next rescue $!) + [s1.equal?(s2), s2.cause.equal?(s1), s3.cause.equal?(s1), s1.cause, s2.result, s3.message] +end +probe("stop_again_dropped") do + e = [1].each + e.next + begin; e.next; rescue StopIteration; end + s2 = (e.next rescue $!) + [s2.cause.class, s2.cause.result, s2.cause.message] +end +probe("stop_again_peek") do + e = [1].each + e.next + s1 = (e.peek rescue $!) + s2 = (e.next rescue $!) + [s2.cause.equal?(s1), s2.result] +end +probe("stop_gen_again") do + e = Enumerator.new { |y| y << 1; :r } + e.next + s1 = (e.next rescue $!) + s2 = (e.next rescue $!) + [s2.cause.equal?(s1), s2.result, s1.result] +end + +# --- backtraces of the end ---------------------------------------------------------------- +def bt_direct + e = [1].each + e.next + begin + e.next + rescue StopIteration => s + bt(s) + end +end +probe("bt_direct") { bt_direct } + +def bt_inner(e) = e.next +def bt_nested + e = [].each + begin + bt_inner(e) + rescue StopIteration => s + bt(s) + end +end +probe("bt_nested") { bt_nested } + +def bt_global + e = (1..1).each + e.next + begin + e.next + rescue StopIteration + bt($!) + end +end +probe("bt_global") { bt_global } + +# the first end rescued without a look, the cause read later in the same frame +def bt_cause_same + e = [1].each + e.next + begin; e.next; rescue StopIteration; end + s2 = (e.next rescue $!) + [bt(s2.cause), bt(s2)] +end +probe("bt_cause_same") { bt_cause_same } + +# the first end rescued and dropped in a frame that has returned, the cause read later +def bt_first_end(e) + begin; e.next; rescue StopIteration; end + nil +end +def bt_cause_later + e = [1].each + e.next + bt_first_end(e) + s2 = (e.next rescue $!) + [bt(s2.cause), bt(s2)] +end +probe("bt_cause_later") { bt_cause_later } + +def bt_loop_kept + e = [1].each + loop { e.next } + s2 = (e.next rescue $!) + [bt(s2.cause).size > 0, s2.cause.class, bt(s2)] +end +probe("bt_loop_kept") { bt_loop_kept } + +def bt_full_message + e = [].each + begin + e.next + rescue StopIteration => s + s.full_message(highlight: false).lines.first.sub(/\A.*extiter-matrix\.rb:/, "") + end +end +probe("bt_full_message") { bt_full_message } + +probe("bt_locations") do + e = [].each + begin + e.next + rescue StopIteration => s + s.backtrace_locations.first(2).map { |l| [l.lineno, l.label] } + end +end + +# a StopIteration kept by a rescue, the frame left, then read +def keep_stop + e = [].each + begin + e.next + rescue StopIteration => s + $kept = s + end + nil +end +probe("bt_kept_late") { keep_stop; bt($kept) } + +def raise_again + e = [].each + begin + e.next + rescue StopIteration + raise + end +end +probe("bt_reraise") { begin; raise_again; rescue StopIteration => s; bt(s); end } + +def ensure_pass + e = [].each + begin + e.next + ensure + $ens = 1 + end +end +probe("bt_through_ensure") { begin; ensure_pass; rescue StopIteration => s; [bt(s), $ens]; end } + +probe("stop_cause_of_new") do + e = [].each + begin + begin + e.next + rescue StopIteration + raise ArgumentError, "x" + end + rescue ArgumentError => a + [a.cause.class, bt(a.cause)] + end +end + +# --- peek, next_values, peek_values --------------------------------------------------------- +probe("peek") { e = [1, 2].each; [e.peek, e.peek, e.next, e.peek, e.next, (e.peek rescue $!.class)] } +probe("peek_mutate") { e = [[1]].each; v = e.peek; v << 2; [e.next] } +probe("next_values") { e = [1, nil, [2]].each; [e.next_values, e.next_values, e.next_values] } +probe("peek_values") { e = [1].each; v = e.peek_values; v << 9; [e.peek_values, e.next_values] } +probe("nv_hash") { e = { a: 1 }.each; [e.peek_values, e.next_values] } +probe("nv_ewi") { e = [:a].each_with_index; [e.peek_values, e.next_values] } +probe("nv_generator") { e = Enumerator.new { |y| y.yield; y.yield 1; y.yield 1, 2; y.yield nil }; [e.next_values, e.next_values, e.next_values, e.next_values] } +probe("next_gen_multi") { e = Enumerator.new { |y| y.yield; y.yield 1, 2 }; [e.next, e.next] } + +# --- rewind, feed, size ------------------------------------------------------------------- +probe("rewind") { e = [1, 2].each; a = e.next; e.rewind; [a, e.next, e.next] } +probe("rewind_done") { e = [1].each; e.next; (e.next rescue nil); e.rewind; [e.next] } +probe("rewind_gen") { e = Enumerator.new { |y| y << 1; y << 2 }; e.next; e.rewind; [e.next, e.next] } +probe("rewind_obj") do + o = Object.new + def o.each; yield 1; yield 2; end + def o.rewind; $rewound = true; end + $rewound = false + e = o.to_enum + e.next + e.rewind + [$rewound, e.next] +end +probe("feed_map") { e = [1, 2].map; e.next; e.feed :a; e.next; e.feed :b; stop_of(e).result } +probe("feed_select") { e = [1, 2, 3].select; e.next; e.feed true; e.next; e.next; e.feed 1; stop_of(e).result } +probe("feed_each") { e = [1, 2].each; e.next; e.feed :x; e.next; stop_of(e).result } +probe("feed_twice") { e = [1].each; e.feed 1; (e.feed 2 rescue "#{$!.class}: #{$!.message}") } +probe("feed_gen") { got = []; e = Enumerator.new { |y| got << y.yield(1); got << y.yield(2) }; e.next; e.feed :f; e.next; (e.next rescue nil); got } +probe("size") { [[1, 2].each.size, (1..4).each.size, 3.times.size, {a: 1}.each.size, Enumerator.new { }.size, [1].each_slice(2).size] } +probe("size_after_next") { e = [1, 2, 3].each; e.next; e.size } + +# --- an Array changed during the iteration: Array#each reads the length at each step ------ +probe("append") do + a = [1, 2] + e = a.each + out = [e.next] + a << 3 + out << e.next << e.next + out << (e.next rescue :stop) +end +probe("append_after_end") { a = [1]; e = a.each; e.next; (e.next rescue nil); a << 2; (e.next rescue :stop) } +probe("shrink") { a = [1, 2, 3]; e = a.each; x = e.next; a.clear; [x, (e.next rescue :stop)] } +probe("replace") { a = [1, 2, 3]; e = a.each; x = e.next; a[1] = :z; [x, e.next] } +probe("unshift") { a = [1, 2]; e = a.each; x = e.next; a.unshift(0); [x, e.next, e.next] } +probe("hash_add") do + h = { a: 1 } + e = h.each + e.next + begin + h[:b] = 2 + :added + rescue => x + x.class + end +end +probe("hash_delete") { h = { a: 1, b: 2, c: 3 }; e = h.each; x = e.next; h.delete(:b); [x, e.next, (e.next rescue :stop)] } + +# --- a redefined or prepended #each, before and after the enumerator is made --------------- +class RedefA < Array +end +probe("subclass_each") do + c = Class.new(Array) { def each; yield :sub; self; end } + drain(c.new([1, 2]).each) +end +probe("singleton_each") do + a = [1, 2] + def a.each; yield :single; self; end + drain(a.each) +end +probe("redefined_before_next") do + a = RedefA.new([1, 2]) + e = a.each + RedefA.class_eval { def each; yield :late; self; end } + r = drain(e) + RedefA.class_eval { remove_method :each } + r +end +probe("redefined_during") do + a = RedefA.new([1, 2, 3]) + e = a.each + x = e.next + RedefA.class_eval { def each; yield :late; self; end } + r = [x, e.next, e.next] + RedefA.class_eval { remove_method :each } + r +end +module PrependEach + def each + return to_enum(:each) unless block_given? + super { |x| yield x * 10 } + end +end +class PrepA < Array; end +probe("prepended_before") do + PrepA.prepend(PrependEach) + drain(PrepA.new([1, 2]).each) +end +class PrepB < Array; end +probe("prepended_after_make") do + e = PrepB.new([1, 2]).each + PrepB.prepend(PrependEach) + drain(e) +end +probe("hash_redef") { h = { a: 1 }; def h.each; yield :h; self; end; drain(h.each) } +probe("range_redef") { r = (1..2); def r.each; yield :r; self; end; drain(r.each) } +probe("to_enum_each") { a = [1, 2]; drain(a.to_enum) } +probe("enum_for_args") { drain([1, 2, 3].enum_for(:each_slice, 2)) } + +# --- each_slice / map and friends on an enumerator --------------------------------------------- +probe("each_slice_next") { e = [1, 2, 3].each_slice(2); [e.next, e.next, (e.next rescue :stop)] } +probe("map_next") { e = [1, 2].map; [e.next, e.next, (e.next rescue :stop)] } +probe("map_with_index") { drain([5, 6].map.with_index) } +probe("each_with_object") { drain([1, 2].each_with_object([])) } +probe("ewi_on_hash") { drain({ a: 1 }.each_with_index) } +probe("lazy_select") { e = (1..Float::INFINITY).lazy.select(&:even?).map { |x| x * 3 }; [e.next, e.next, e.peek] } +probe("lazy_take") { drain((1..).lazy.map { |x| x + 1 }.take(3)) } +probe("lazy_size") { [(1..3).lazy.map { |x| x }.size, (1..3).lazy.select { true }.size] } +probe("yielder_proc") { drain(Enumerator.new { |y| [1, 2].each(&y) }) } +probe("yielder_chain"){ drain(Enumerator.new { |y| y << 1 << 2 }) } + +# --- exceptions inside the source --------------------------------------------------------------- +probe("gen_raises") do + e = Enumerator.new { |y| y << 1; raise ArgumentError, "boom" } + [e.next, (e.next rescue "#{$!.class}: #{$!.message}"), e.next] +end + +# --- copies, frozen, inspect ------------------------------------------------------------------ +probe("dup_fresh") { e = [1, 2].each; d = e.dup; [d.next, e.next] } +probe("dup_started") { e = [1, 2].each; e.next; (e.dup rescue "#{$!.class}: #{$!.message}") } +probe("dup_done") { e = [1].each; e.next; (e.next rescue nil); d = e.dup; [d.next] } +probe("frozen") { e = [1].each.freeze; (e.next rescue $!.class) } +probe("inspect_started") { e = [1, 2].each; e.next; e.inspect } + +# --- threads: a cursor belongs to the thread that started it ---------------------------------- +probe("thread_fresh") { e = [1, 2].each; Thread.new { e.next }.value } +probe("thread_started") do + e = [1, 2, 3].each + e.next + Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value +end +probe("thread_peeked") do + e = [1, 2, 3].each + e.peek + Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value +end +probe("thread_done") do + e = [1].each + e.next + (e.next rescue nil) + Thread.new { begin; e.next; rescue => x; [x.class, x.cause.class]; end }.value +end +probe("thread_gen") do + e = Enumerator.new { |y| y << 1; y << 2 } + e.next + Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value +end +probe("thread_after") { e = [1, 2].each; Thread.new { e.next }.join; (e.next rescue "#{$!.class}: #{$!.message}") } +probe("thread_each_own") do + e = [1, 2, 3].each + 4.times.map { Thread.new { f = e.dup; [f.next, f.next] }.value }.uniq +end + +# --- an abandoned enumerator ------------------------------------------------------------------ +probe("abandoned") do + 50.times { e = [1, 2, 3].each; e.next } + 50.times { e = Enumerator.new { |y| y << 1; y << 2 }; e.next } + GC.start + :ok +end + +# --- zip and friends that take values with #next ----------------------------------------------- +probe("zip_enum") { [1, 2, 3].zip([4, 5].each) } +probe("zip_gen") { [1, 2].zip(Enumerator.new { |y| y << :a }) } +probe("zip_block") { r = []; [1, 2].zip((3..4).each) { |x| r << x }; r } + +# --- Kernel#loop reads the result of the StopIteration it rescues ------------------------------- +class MyStop < StopIteration + def result = [:mine, super] +end +probe("loop_sub_result") { loop { raise MyStop } } +probe("loop_sub_kept") do + $seen = nil + c = Class.new(StopIteration) { def result; $seen = self; :c; end } + r = loop { raise c, "kept" } + [r, $seen.class == c, $seen.message, bt($seen).size > 0] +end +probe("loop_singleton_result") do + s = StopIteration.new("s") + def s.result = :single + loop { raise s } +end +probe("loop_redefined_result") do + StopIteration.class_eval { alias_method :__matrix_result__, :result; remove_method :result; def result = [:redef, __matrix_result__] } + e = [1].each + r = loop { e.next } + StopIteration.class_eval { remove_method :result; alias_method :result, :__matrix_result__; remove_method :__matrix_result__ } + r +end +probe("loop_after_restore") { e = [1].each; loop { e.next } } +probe("loop_dollar_bang") { e = [].each; loop { e.next }; $!.inspect } +probe("loop_inner_rescue") { e = [].each; loop { begin; e.next; rescue StopIteration => s; break [s.class, s.result.size]; end } } +probe("loop_ensure") { x = []; e = [1].each; r = loop { begin; e.next; ensure; x << $!.class; end }; [r, x] } +probe("loop_tracepoint") do + seen = [] + tp = TracePoint.new(:raise) { |t| seen << t.raised_exception } + e = [1].each + r = tp.enable { loop { e.next } } + s = seen.last + [r, seen.size <= 1, s.nil? || bt(s).size > 0] +end +probe("loop_kept_cause_later") do + e = [1].each + loop { e.next } + s = (e.next rescue $!) + [s.cause.result, bt(s.cause).first.sub(/\A\d+:/, "")] +end + +# the first end dropped three frames down, its frames gone, the cause read from a block elsewhere +def deep_drop(e) + begin; e.next; rescue StopIteration; end + nil +end +def deep_d3(e) = deep_drop(e) +def deep_d2(e) = deep_d3(e) +def deep_d1(e) = deep_d2(e) +def deep_later(e) + [1].each { s = (e.next rescue $!); return [bt(s.cause), bt(s)] } +end +probe("bt_cause_deep") { e = [1].each; e.next; deep_d1(e); deep_later(e) } +probe("bt_cause_deep_hot") { r = nil; 100.times { e = [1].each; e.next; deep_d1(e); r = deep_later(e) }; r } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..ba452f5cc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1359,8 +1359,23 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has that moves it back onto the main thread looks slower (`csv_parse` 1.37 and 0.94 of its time in the round-35 gate, while process CPU fell to 0.18-0.37). `invoice-parts.rb` and `csv-shapes.rb` use `CLOCK_PROCESS_CPUTIME_ID`, which counts the JIT's background threads - too. Untried: switching fibers without a thread (a continuation of the method JIT's own, - or a stackless form for the enumerators the prelude makes). + too. + The stackless form this entry listed as untried was already there (2026-11-26, perf/extiter + found it): `Enumerator.cs`'s ExternalCursor walks Array#each / each_index / reverse_each / + each_with_index, Hash#each / each_pair / each_key / each_value, Integer#times / upto / + downto, an Integer Range, String#each_byte / each_char, Struct#each and each_slice / + each_cons over those, while the method is the unredefined one, with no fiber; a `next` there + is 67-94 ns against CRuby's 226-234 (`Util/bench/extiter-shapes.rb`). Its end was the cost + left - a StopIteration thrown from C# took the catch-site walk, 22 us against CRuby's 0.8 - + and perf/extiter (Landed) defers that walk. Still on a fiber, 5-10 us of process CPU per + `next` against 0.22-0.36: `map` / `select` / `each_with_object` enumerators (no cursor for + them yet: a cursor could keep the fed values for StopIteration#result), `with_index`, + `Enumerator::Lazy`, `Enumerator.produce` (generators of the prelude, which run Ruby code + between two values: a cursor would call blocks under its lock) and `Enumerator.new`. A raw + fiber round trip is 2.3 us of wall clock and 4.7-6 us of CPU (two threads spinning), so the + prelude's machinery around it is not where the time is. Untried: cursors for `map` and + `select` over an Array; a cursor over a cursor for `with_index`; switching fibers without a + thread (a continuation of the method JIT's own). 36. **Left from round thirty-five**, each smaller than one gap of its own: `...` passed on is still a splat of an Array and a block argument (`def m(...) = n(...)` allocates the rest per call; the frame is light now); `URI::Generic#query=` and `merge` still run the @@ -1384,6 +1399,36 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/extiter (2026-11-26) - the StopIteration that ends a cursor's external iteration defers + its stack walk, and `loop` reads its result without exposing it (gap 35)** - not gated. A + `next` over a built-in source (Array, Hash, Range, Integer#times...) runs on a cursor with no + fiber already, at 67-94 ns against CRuby's 226-234; what each such iteration still paid was + its end: a StopIteration thrown from C# took the catch-site walk of the whole CLR stack (22-24 us, + CRuby 0.8), where one Kernel#raise makes defers it until the exception is exposed + (RubyExceptionData.TryDeferCatchSite, RaisedUnkept). Now the cursor's StopIteration is marked + unkept (`RubyExceptionData.MarkUnkept`) unless a TracePoint is enabled; the first one, which the + cursor keeps as the cause of those after it, takes the walk when it is handed out as a cause + (`RubyExceptionData.ExposeCatchSite`, public now). And Kernel#loop rescues StopIteration + without `=> stop`, which exposed it, reading the result through `Enumerator.__rescued_stop_result__` + (`$!` read with `RubyContext.CurrentExceptionNoExpose`, public now), unless #result is not + the prelude's (registered with `__iter_cursor_method__`), when it calls it as before. Switch: + `IR_FAST_NEXT=0`. `ruby Util/perf/ab.rb -r 6 Util/bench/extiter-shapes.rb` (new), ns per + `next`, CRuby / base f81fc19 / off / new, new/off: 4-element Array drained with + `begin/rescue` 1395 / 6275 / 6243 / 1265 (0.20), the same with `loop { e.next }` 1414 / 7028 + / 7052 / 1730 (0.25), `next` again after the end 766 / 23764 / 23893 / 3882 (0.16), Hash of + 100 271.9 against 474.8 (0.57), Array and Range of 1000 and `peek` 0.77-0.79; the controls, + which keep their fiber (map, select, with_index, lazy, produce, Enumerator.new; 5-11 us against + 0.22-0.36) and zip, overlap (spreads up to 120% on the fiber rows). `Util/extiter-matrix.rb` + (new, 131 probes: every cursor source, results, causes and their backtraces with the first end + dropped in a frame that has returned, `loop` with a subclass's, a singleton's and a redefined + #result, TracePoint, threads, mutation during the iteration, redefinition before and after the + enumerator is made) prints CRuby's output on base, new and new with the switch off; + enum-next-, enum-, enumerable2-, block-loop-, loop-light-, full-message-, raise-, jit-raise-, + hash-order- and jit-matrix the same on base and new. spec/core/enumerator + + kernel/loop_spec (443 examples) and spec/core/exception + enumerable + language/rescue_spec + (846) pass on both; 72 named IronRuby.Tests (Enumerator_*, Loop*, Backtrace*, Exception*, + Raise*, Rescue*) pass. + - **perf/first-bind (2026-11-26) - what a first bind costs, split; light-scope sites call library methods through a dispatcher for their first calls (gap 26).** The split (master 4bae83f3, R2R host with the startup library; `IR_BIND_TRACE`, `IR_PHASE_TIMES`, perf with jitdump classing From 37eae8155d928b77b21abc8e2dcc8a255372c47a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:38:27 +0000 Subject: [PATCH 020/439] Construct a Struct class's first instances without a rule Class#new of a struct class built a rule per class - allocate a RubyStruct, call initialize through a site of its own - since LibraryDispatcher.TryCreateConstruction took only classes whose instances are plain Ruby objects (gap 19: about 80-160 us under IR_BIND_TRACE=1 for the first `new' on each new struct class). RubyClass.TryGetObjectConstruction now takes, for TryCreateConstruction only, a class made by Struct.new or a subclass of one: allocate the RubyStruct as the rule does, then call a Ruby initialize as for a plain class, or Struct#initialize through a site of the construction's own with the arguments of new and no block, as the rule calls a library initializer (implicit self, so a private one too). The method JIT's constructions still take plain classes only. IR_FAST_STRUCT=0 leaves struct classes to their rules. Util/struct-matrix.rb gains rows for a private initialize, method_missing, an undefined initialize, a subclass's Ruby initialize, six members, a block given to new and a refined initialize (which every IronRuby build sees, CRuby not: known, as on master). IR_BIND_TRACE=1: the first `new' on each new struct class is `pre', 10-25 us; new_class_use of struct-shapes.rb, six alternating rounds: 70.4 us with IR_FAST_STRUCT=0, 47.2 with it on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Ruby/Builtins/RubyClass.cs | 64 ++++++++++++++++++++- Src/Ruby/Runtime/Calls/LibraryDispatcher.cs | 2 +- Util/struct-matrix.rb | 17 ++++++ 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index 6e7f9b5ba..d1c000d1b 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -1756,10 +1756,17 @@ public object TryAllocatePlainInstance() { /// no block, in the cases it is the allocation of a RubyObject and maybe a call of a Ruby initializer of that arity and /// nothing else; null otherwise. /// - internal ObjectConstruction TryGetObjectConstruction(int count) { + internal ObjectConstruction TryGetObjectConstruction(int count, bool structs = false) { Func allocator; + bool isStruct = false; if (!TryGetPlainAllocation(out allocator)) { - return null; + // A class made by Struct.new, or a subclass of one (structs: for LibraryDispatcher.TryCreateConstruction): the rule + // allocates a RubyStruct (GetAllocatorNewExpression) and calls initialize, Struct's or a Ruby one, as for a plain class. + if (!structs || !IsPlainStruct()) { + return null; + } + allocator = _structAllocator; + isStruct = true; } int version; @@ -1773,6 +1780,15 @@ internal ObjectConstruction TryGetObjectConstruction(int count) { return null; } + // Struct#initialize, a library method that takes the scope from no one: called as the rule calls it, through a site of + // its own (BuildOverriddenInitializerCall) + if (isStruct) { + if (initializer is RubyLibraryMethodInfo) { + var structInitializer = (initializer.DeclaringModule == Context.GetClass(typeof(RubyStruct))) ? CreateInitializeCall(count) : null; + return (structInitializer != null) ? new ObjectConstruction(this, allocator, version, structInitializer, count) : null; + } + } + // Object#initialize and BasicObject#initialize: no arguments - construct (a RubyObject constructor, the same allocation) if (initializer is RubyLibraryMethodInfo) { return (count == 0 && (initializer.DeclaringModule.IsObjectClass || initializer.DeclaringModule.IsBasicObjectClass)) ? @@ -1805,6 +1821,50 @@ internal ObjectConstruction TryGetObjectConstruction(int count) { return (body.GetType() == MemberDispatcher.GetRubyMethodDelegateType(count)) ? new ObjectConstruction(this, allocator, version, body, count) : null; } + private static readonly Func/*!*/ _structAllocator = (cls) => RubyStruct.Create(cls); + + // Class#new makes an instance of this class as a RubyStruct, and does nothing else before initialize (GetAllocatorNewExpression). + private bool IsPlainStruct() { + return RubyStruct.FastStruct && _structInfo != null && !IsSingletonClass && !_isUninitializedAllocation && _isRubyClass && + CAllocator == null && !IsException() && GetUnderlyingSystemType() == typeof(RubyStruct); + } + + // The rule's call of a library initialize (BuildOverriddenInitializerCall): a dynamic call of the instance's initialize, + // private methods included, with the arguments of new and no block, as a Ruby initializer's body is called (ObjectConstruction). + private Delegate CreateInitializeCall(int count) { + var action = RubyCallAction.Make(Context, Symbols.Initialize, new RubyCallSignature(count, RubyCallFlags.HasImplicitSelf)); + switch (count) { + case 0: { + var site = CallSite>.Create(action); + return new Func((self, block) => site.Target(site, self)); + } + case 1: { + var site = CallSite>.Create(action); + return new Func((self, block, a0) => site.Target(site, self, a0)); + } + case 2: { + var site = CallSite>.Create(action); + return new Func((self, block, a0, a1) => site.Target(site, self, a0, a1)); + } + case 3: { + var site = CallSite>.Create(action); + return new Func((self, block, a0, a1, a2) => site.Target(site, self, a0, a1, a2)); + } + case 4: { + var site = CallSite>.Create(action); + return new Func((self, block, a0, a1, a2, a3) => + site.Target(site, self, a0, a1, a2, a3)); + } + case 5: { + var site = CallSite>.Create(action); + return new Func((self, block, a0, a1, a2, a3, a4) => + site.Target(site, self, a0, a1, a2, a3, a4)); + } + default: + return null; + } + } + public void BuildObjectConstructionNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args, string/*!*/ methodName) { if (IsSingletonClass) { metaBuilder.SetError(Methods.MakeVirtualClassInstantiatedError.OpCall()); diff --git a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs index 5a11e77fa..e1d4d252e 100644 --- a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs @@ -1323,7 +1323,7 @@ internal static object TryCreateConstruction(RubyCallAction/*!*/ binder, Type/*! return null; } - var construction = cls.TryGetObjectConstruction(count); + var construction = cls.TryGetObjectConstruction(count, true); if (construction == null) { return null; } diff --git a/Util/struct-matrix.rb b/Util/struct-matrix.rb index 3c02e02c9..1582d823e 100644 --- a/Util/struct-matrix.rb +++ b/Util/struct-matrix.rb @@ -11,6 +11,9 @@ # ids are taken out of inspect. Each expression runs twice and then in a loop of 200, so a # path that only a warm call site takes is probed too; a line says so when the warm answer # differs from the first. +# +# Known: `UsingRefine.make` prints [:refined, :init] on every IronRuby build (a refinement of +# initialize is seen by Class#new); CRuby's new calls the unrefined initialize. KT = Struct.new(:a, :b, keyword_init: true) KF = Struct.new(:a, :b, keyword_init: false) @@ -59,9 +62,16 @@ module RefineKT def a = :refined end end +module RefineInit + refine KN do + def initialize(*) = super(:refined, :init) + end +end module UsingRefine using RefineKT + using RefineInit def self.read = KT.new(a: 1).a + def self.make = KN.new(1, 2).to_a end KTH = Thread.new { Struct.new(:x, :y, keyword_init: true) }.value KNH = Thread.new { Struct.new(:x, :y) }.value @@ -144,6 +154,13 @@ def self.read = KT.new(a: 1).a FrozenKT.new(a: 1).frozen? FrozenKT.new(a: 1).to_a UsingRefine.read + UsingRefine.make + (c = Struct.new(:a); c.class_eval { private def initialize(*) = super(:priv) }; c.new(1).a) + (c = Struct.new(:a); c.class_eval { def method_missing(n, *a) = n }; c.new(1).a) + (c = Struct.new(:a, :b); c.class_eval { undef_method :initialize }; c.new(1, 2)) + (c = Struct.new(:a); d = Class.new(c) { def initialize(x) = super(x * 3) }; d.new(2).a) + (c = Struct.new(:a, :b, :c, :d, :e, :f); c.new(1, 2, 3, 4, 5, 6).to_a) + (c = Struct.new(:a, :b); c.new(1) { :blk }.to_a) KT.new(a: 1).a KTH.new(x: 1, y: 2).to_a KTH.new(z: 1) From eaf1df17a97dc145f65ed8beea34b087590eec3b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:38:44 +0000 Subject: [PATCH 021/439] Remember a light site's LightScopeRequired answer (IR_LIGHT_REMEMBER) A light frame's call whose light site answers RubyOps.LightScopeRequired makes the scope late and calls again through the ordinary site, on every call (gap 16). Each light site gets a box, a constant of the body like a regex literal's cache, which the scope-making arm sets to the marker; the light path becomes `memory ?? light(...)`, so a site that once needed the scope goes straight to it. A stale read costs an ask or a scope, never a wrong answer. The AOT compiler re-creates a set box empty. Measured with callgrind (no perf counter in this container) it saves nothing: the light site is 7 of the 232 instructions a light gsub pays over a scoped one, and the extra node costs 37 an iteration in interpreted code. Reverted in the next commit; see Util/perf/LEDGER.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 34 +++++++++++++++++-- Util/aot/IronRuby.Aot/AotCompiler.cs | 3 +- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 3b5b47761..3f4dc75f7 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -553,6 +553,13 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { internal static readonly bool LightRegexEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_REGEX") != "0"; private static readonly bool LightRegexAll = Environment.GetEnvironmentVariable("IR_LIGHT_REGEX") == "all"; + /// + /// IR_LIGHT_REMEMBER=0 has a light frame's call ask its light site every time (see LightFrameRewriter.MakeLightCall): + /// otherwise a site whose rule has once answered RubyOps.LightScopeRequired goes straight to the scope and the + /// ordinary site from then on. + /// + internal static readonly bool LightRememberEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_REMEMBER") != "0"; + /// /// IR_LIGHT_BREAK=0 keeps every method with a `break', `next' or `redo' in a `while'/`until' loop of its body out of /// light frames (see IsScopeFree). @@ -1967,13 +1974,36 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres var result = Ast.Variable(typeof(object), "#r"); temps[0] = result; MakesCalls = true; - body.Add(Ast.Assign(result, AstUtils.LightDynamic(lightAction, typeof(object), lightArgs))); + MSA.Expression lightCall = AstUtils.LightDynamic(lightAction, typeof(object), lightArgs); + MSA.Expression memory = null; + if (LightRememberEnabled) { + // A site whose rule has answered RubyOps.LightScopeRequired once remembers it (gap 16): from then on the frame + // makes its scope and calls through the ordinary site without asking the light one, whose answer would most + // likely be the same - `s.gsub(/b/, "x")', whose callee stores the caller's $~, would otherwise pay for the light + // call on every call as well as for the scope. The memory is a box of the site, shared by every invocation, + // every thread and every runtime that runs this body; it is only ever set, and only to the marker. A stale read + // costs no more than the ask it skips or makes, and the ordinary site with the scope is what the light one + // stands in for, so a receiver whose method would not have needed the scope gets the right answer too, only a + // scope it did not need. The light path pays one node for it (`memory ?? light'), which matters while the body + // is interpreted; the store is on the path that makes the scope anyway (in a block's frame also for its + // `block_given?', which that frame answers through the scope every time). + memory = Ast.Field(AstUtils.Constant(new StrongBox(null)), "Value"); + lightCall = Ast.Coalesce(memory, lightCall); + } + body.Add(Ast.Assign(result, lightCall)); MSA.Expression needsScope = Ast.ReferenceEqual(result, AstUtils.Constant(RubyOps.LightScopeRequired)); + MSA.Expression fullCall = AstUtils.LightDynamic(action, typeof(object), fullArgs); + if (memory != null) { + fullCall = Ast.Block( + Ast.IfThen(Ast.ReferenceEqual(memory, AstUtils.Constant(null)), Ast.Assign(memory, AstUtils.Constant(RubyOps.LightScopeRequired))), + fullCall + ); + } if (blockGiven && BlockParameter == null) { // a block's frame has the method's block only through its scope: the call, as for any rule that reads it needsScope = Ast.OrElse(needsScope, Ast.ReferenceEqual(result, AstUtils.Constant(RubyOps.LightBlockGiven))); } - MSA.Expression value = Ast.Condition(needsScope, AstUtils.LightDynamic(action, typeof(object), fullArgs), result); + MSA.Expression value = Ast.Condition(needsScope, fullCall, result); if (blockGiven && BlockParameter != null) { // `block_given?' that is Kernel's (DispatchIntrinsics.TryBuildBlockGiven): whether the frame was given a // block, which is what Kernel#block_given? reads from the scope this frame would have to make for it - diff --git a/Util/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index b3afb7173..e36b4ea45 100644 --- a/Util/aot/IronRuby.Aot/AotCompiler.cs +++ b/Util/aot/IronRuby.Aot/AotCompiler.cs @@ -1046,7 +1046,8 @@ private Expression Serialize(object value, out string hint) { Expression.Constant(range.Begin), Expression.Constant(range.End), Expression.Constant(range.ExcludeEnd)); case IStrongBox box when value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(StrongBox<>): - if (box.Value != null) throw new NotSupportedException("StrongBox holding " + box.Value.GetType()); + // a light site's memory that has been set (LightFrameRewriter.MakeLightCall) starts empty again: it is only a hint + if (box.Value != null && box.Value != RubyOps.LightScopeRequired) throw new NotSupportedException("StrongBox holding " + box.Value.GetType()); hint = "cache"; return Expression.New(value.GetType()); From 25cfca60a3c6aa939ca94ab9e5fd3cefc00ec182 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:38:56 +0000 Subject: [PATCH 022/439] Revert "Remember a light site's LightScopeRequired answer (IR_LIGHT_REMEMBER)" Rejected by perf/lsite's measurements: the regex shapes still lose 1.7-2.9% against a scope made at entry with it, inject(:+), zip and inject with a block count 1-4% more with it than without, and every light site, controls included, pays for the extra node while interpreted. Util/perf/LEDGER.md (Rejected, perf/lsite) has the numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 34 ++----------------- Util/aot/IronRuby.Aot/AotCompiler.cs | 3 +- 2 files changed, 3 insertions(+), 34 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 3f4dc75f7..3b5b47761 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -553,13 +553,6 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { internal static readonly bool LightRegexEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_REGEX") != "0"; private static readonly bool LightRegexAll = Environment.GetEnvironmentVariable("IR_LIGHT_REGEX") == "all"; - /// - /// IR_LIGHT_REMEMBER=0 has a light frame's call ask its light site every time (see LightFrameRewriter.MakeLightCall): - /// otherwise a site whose rule has once answered RubyOps.LightScopeRequired goes straight to the scope and the - /// ordinary site from then on. - /// - internal static readonly bool LightRememberEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_REMEMBER") != "0"; - /// /// IR_LIGHT_BREAK=0 keeps every method with a `break', `next' or `redo' in a `while'/`until' loop of its body out of /// light frames (see IsScopeFree). @@ -1974,36 +1967,13 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres var result = Ast.Variable(typeof(object), "#r"); temps[0] = result; MakesCalls = true; - MSA.Expression lightCall = AstUtils.LightDynamic(lightAction, typeof(object), lightArgs); - MSA.Expression memory = null; - if (LightRememberEnabled) { - // A site whose rule has answered RubyOps.LightScopeRequired once remembers it (gap 16): from then on the frame - // makes its scope and calls through the ordinary site without asking the light one, whose answer would most - // likely be the same - `s.gsub(/b/, "x")', whose callee stores the caller's $~, would otherwise pay for the light - // call on every call as well as for the scope. The memory is a box of the site, shared by every invocation, - // every thread and every runtime that runs this body; it is only ever set, and only to the marker. A stale read - // costs no more than the ask it skips or makes, and the ordinary site with the scope is what the light one - // stands in for, so a receiver whose method would not have needed the scope gets the right answer too, only a - // scope it did not need. The light path pays one node for it (`memory ?? light'), which matters while the body - // is interpreted; the store is on the path that makes the scope anyway (in a block's frame also for its - // `block_given?', which that frame answers through the scope every time). - memory = Ast.Field(AstUtils.Constant(new StrongBox(null)), "Value"); - lightCall = Ast.Coalesce(memory, lightCall); - } - body.Add(Ast.Assign(result, lightCall)); + body.Add(Ast.Assign(result, AstUtils.LightDynamic(lightAction, typeof(object), lightArgs))); MSA.Expression needsScope = Ast.ReferenceEqual(result, AstUtils.Constant(RubyOps.LightScopeRequired)); - MSA.Expression fullCall = AstUtils.LightDynamic(action, typeof(object), fullArgs); - if (memory != null) { - fullCall = Ast.Block( - Ast.IfThen(Ast.ReferenceEqual(memory, AstUtils.Constant(null)), Ast.Assign(memory, AstUtils.Constant(RubyOps.LightScopeRequired))), - fullCall - ); - } if (blockGiven && BlockParameter == null) { // a block's frame has the method's block only through its scope: the call, as for any rule that reads it needsScope = Ast.OrElse(needsScope, Ast.ReferenceEqual(result, AstUtils.Constant(RubyOps.LightBlockGiven))); } - MSA.Expression value = Ast.Condition(needsScope, fullCall, result); + MSA.Expression value = Ast.Condition(needsScope, AstUtils.LightDynamic(action, typeof(object), fullArgs), result); if (blockGiven && BlockParameter != null) { // `block_given?' that is Kernel's (DispatchIntrinsics.TryBuildBlockGiven): whether the frame was given a // block, which is what Kernel#block_given? reads from the scope this frame would have to make for it - diff --git a/Util/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index e36b4ea45..b3afb7173 100644 --- a/Util/aot/IronRuby.Aot/AotCompiler.cs +++ b/Util/aot/IronRuby.Aot/AotCompiler.cs @@ -1046,8 +1046,7 @@ private Expression Serialize(object value, out string hint) { Expression.Constant(range.Begin), Expression.Constant(range.End), Expression.Constant(range.ExcludeEnd)); case IStrongBox box when value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(StrongBox<>): - // a light site's memory that has been set (LightFrameRewriter.MakeLightCall) starts empty again: it is only a hint - if (box.Value != null && box.Value != RubyOps.LightScopeRequired) throw new NotSupportedException("StrongBox holding " + box.Value.GetType()); + if (box.Value != null) throw new NotSupportedException("StrongBox holding " + box.Value.GetType()); hint = "cache"; return Expression.New(value.GetType()); From cd9cc85e5ce3662cfeb3a49a5d23285b388b1fdc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:38:56 +0000 Subject: [PATCH 023/439] Count instructions under callgrind where perf_event_open is refused Util/perf/ab.rb -i reads the CPU's instruction counter (Util/perf/instructions.rb), which most containers and VMs do not allow, and timing there spreads 5-15% on shapes of 50-500 ns. count.sh runs a tree's ir.sh under callgrind with only the shape files' timed sections instrumented (client requests through Fiddle, a stand-in Instructions loaded with -r), counting the main thread, with tiered compilation off and a non-concurrent GC: sections agree to 0.01%, and so do processes of one arm. It is a drop-in command for ab.rb -i. Its counts are not the counter's and depend on the shapes run before in the process, so arms are compared with each other on the same shape list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/perf/callgrind/cgctl.c | 4 ++++ Util/perf/callgrind/count.sh | 31 +++++++++++++++++++++++++ Util/perf/callgrind/instructions.rb | 36 +++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 Util/perf/callgrind/cgctl.c create mode 100755 Util/perf/callgrind/count.sh create mode 100644 Util/perf/callgrind/instructions.rb diff --git a/Util/perf/callgrind/cgctl.c b/Util/perf/callgrind/cgctl.c new file mode 100644 index 000000000..010b207d6 --- /dev/null +++ b/Util/perf/callgrind/cgctl.c @@ -0,0 +1,4 @@ +/* Instruments only what lies between cg_start() and cg_stop() (Util/perf/callgrind/count.sh). */ +#include +void cg_start(void) { CALLGRIND_START_INSTRUMENTATION; CALLGRIND_ZERO_STATS; } +void cg_stop(void) { CALLGRIND_DUMP_STATS; CALLGRIND_STOP_INSTRUMENTATION; } diff --git a/Util/perf/callgrind/count.sh b/Util/perf/callgrind/count.sh new file mode 100755 index 000000000..ca9485914 --- /dev/null +++ b/Util/perf/callgrind/count.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Instructions per call where the CPU's counter cannot be opened (Util/perf/instructions.rb needs perf_event_open, +# which most containers and VMs refuse): runs TREE/ir.sh under callgrind, instrumenting only the shape files' timed +# sections, and counting only the main thread. A drop-in for ab.rb -i's commands: +# +# ruby Util/perf/ab.rb -i -r 1 -n 20000 Util/bench/regex-shapes.rb \ +# "off=env IR_LIGHT_X=0 Util/perf/callgrind/count.sh ." "on=Util/perf/callgrind/count.sh ." -- gsub size +# +# What it measures is not what instructions.rb measures: .NET's tiered compilation is off (DOTNET_TieredCompilation=0: +# fully optimized code from the first call, no PGO), because under valgrind tier-up depends on how slowly everything +# runs; the GC is not concurrent, so that a collection is counted on the thread that caused it. Counts are steady to +# 0.01% from section to section and from process to process, but they are larger than instructions.rb's and differ +# from them shape by shape. Compare arms of this tool with each other only. +# +# Mind the shape file's driver: its `while` loop is a block run by the DLR interpreter, where one more expression node +# in a light frame's call costs about 30 instructions an iteration - which a change to every light site pays in the +# driver too (perf/lsite: +37 on every shape, the controls included). A control shape that moves says so. +# +# A process takes 2-3 minutes (start-up runs under valgrind, uninstrumented); N=20000 is plenty. Needs valgrind and +# its headers (valgrind/callgrind.h) and a C compiler. +TREE=$(cd "$1" && pwd); shift +HERE=$(cd "$(dirname "$0")" && pwd) +LIBDIR="${TMPDIR:-/tmp}/ir-callgrind" +mkdir -p "$LIBDIR" +[ "$LIBDIR/libcgctl.so" -nt "$HERE/cgctl.c" ] || cc -O2 -shared -fPIC -o "$LIBDIR/libcgctl.so" "$HERE/cgctl.c" || exit 1 +D=$(mktemp -d "$LIBDIR/out.XXXXXX") +trap 'rm -rf "$D"' EXIT +export DOTNET_TieredCompilation=0 DOTNET_gcConcurrent=0 DOTNET_EnableWriteXorExecute=0 +export CG_LIB="$LIBDIR/libcgctl.so" CG_DIR="$D" CG_REAL="$TREE/Util/perf/instructions.rb" +valgrind -q --log-file="$D/valgrind.log" --tool=callgrind --trace-children=yes --instr-atstart=no --separate-threads=yes \ + --callgrind-out-file="$D/cg.%p" "$TREE/ir.sh" -r "$HERE/instructions.rb" "$@" diff --git a/Util/perf/callgrind/instructions.rb b/Util/perf/callgrind/instructions.rb new file mode 100644 index 000000000..8c2fc104b --- /dev/null +++ b/Util/perf/callgrind/instructions.rb @@ -0,0 +1,36 @@ +# Util/perf/instructions.rb's Instructions, for a run under Util/perf/callgrind/count.sh: the first read of a section +# starts callgrind's instrumentation, the second dumps it and answers the main thread's count. Loaded first (-r), it +# takes the place of the real one, which the shape files then require in vain: the tree's, and the one beside the +# shape file being run (a shape file of another tree). +$LOADED_FEATURES << File.expand_path(ENV["CG_REAL"]) if ENV["CG_REAL"] +$LOADED_FEATURES << File.expand_path("../perf/instructions.rb", File.dirname(File.expand_path($0))) +require 'fiddle' +module Instructions + def self.open + lib = Fiddle.dlopen(ENV['CG_LIB']) + @start = Fiddle::Function.new(lib['cg_start'], [], Fiddle::TYPE_VOID) + @stop = Fiddle::Function.new(lib['cg_stop'], [], Fiddle::TYPE_VOID) + @dir = ENV['CG_DIR'] + @on = false + self + rescue StandardError, LoadError + nil + end + + def self.read + if @on + @stop.call + @on = false + # --separate-threads=yes: the main thread's file of this dump is cg.PID.N-01 + files = Dir[File.join(@dir, "cg.#{Process.pid}.*-*")] + main = files.find { |f| f.end_with?('-01') } + count = main && File.foreach(main).grep(/^(totals|summary):/).first&.split&.at(1)&.to_i + files.each { |f| File.delete(f) } + count + else + @on = true + @start.call + 0 + end + end +end From 6bf4d821591777233fe90eb5eebfc19b77b43ceb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:38:56 +0000 Subject: [PATCH 024/439] perf/lsite: record the remembered light site as rejected, keep its matrix Gap 16's untried idea, a light site that remembers it needed the scope, does not stop the shapes it was for from losing: profiled with callgrind, a light gsub pays 232 instructions a call more than a scoped one, of which the light site's rule is 7; the rest is the late scope's arm in the body and the light frame's exit. The ledger has the numbers and names what is left to try (enter through the scoped body after the first late scope). Util/light-remember-matrix.rb probes a site that needed the scope and then not, the reverse, redefinition half way, method_missing, protected and private methods, super, block_given? in a block, binding, two threads and a refinement; it prints CRuby 4.0's output on the baseline and the candidate in six modes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/light-remember-matrix.rb | 172 ++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 63 ++++++++++++- 2 files changed, 230 insertions(+), 5 deletions(-) create mode 100644 Util/light-remember-matrix.rb diff --git a/Util/light-remember-matrix.rb b/Util/light-remember-matrix.rb new file mode 100644 index 000000000..c7b4f5cbb --- /dev/null +++ b/Util/light-remember-matrix.rb @@ -0,0 +1,172 @@ +# Differential matrix for a light frame's call whose light site answers RubyOps.LightScopeRequired (the frame then makes +# its scope and calls again through the ordinary site; LightFrameRewriter.MakeLightCall) - and for a site that would +# remember that answer and skip the light site from then on (IR_LIGHT_REMEMBER, tried in perf/lsite and rejected; see +# Util/perf/LEDGER.md gap 16). Run it under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/light-remember-matrix.rb > mri.txt +# ./ir.sh Util/light-remember-matrix.rb > on.txt +# IR_LIGHT_REGEX=all ./ir.sh Util/light-remember-matrix.rb > all.txt +# IR_LIGHT_FRAMES=0 ./ir.sh Util/light-remember-matrix.rb > off.txt +# diff mri.txt on.txt && diff mri.txt all.txt && diff mri.txt off.txt +# +# The probes: a site that needed the scope once and then gets a receiver whose method does not, and the reverse; +# the callee redefined half way and put back; a refinement; method_missing; a protected method; super into a method +# that reads the caller's scope; block_given? in a block's frame; binding; and two threads sharing one site. Each +# reports the call's value and the caller's $~ after it, which no callee may change. +# +# IR_LIGHT_FRAMES=why ./ir.sh Util/light-remember-matrix.rb 2>&1 >/dev/null | grep -a '^\[light\]' +# +# says which of the methods below are light frames. + +N = 3000 + +def t(label) + print label.ljust(56), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +# the caller's own match data after the call, which the call must leave alone +def kept + "keep" =~ /(ke)ep/ + r = yield + [r, $~ && $~[0], $1] +end + +# A receiver whose #sub, #gsub, #split, #=~ and #prot need no caller's scope. +class Plain + def sub(*a) = [:plain_sub, a.size] + def gsub(*a) = [:plain_gsub, a.size] + def split(*a) = [:plain_split, a.size] + def =~(o) = :plain_match + def prot = :plain_prot +end + +# ---------------------------------------------------------------- 1. one site, receivers that need the scope and not + +# String#sub/gsub/split/=~ store the caller's $~ (the light site answers LightScopeRequired); Plain's do not. +def l_sub(o) = o.sub("a", "x") +def l_gsub(o, r) = o.gsub(r, "x") +def l_split(o, r) = o.split(r) +def l_eqt(o, r) = o =~ r +def l_pass(o) = o.size + +t("sub: String first, then Plain") { |i| kept { l_sub(i < N / 2 ? "abc" : Plain.new) } } +t("sub: Plain first, then String") { |i| kept { l_sub(i < N / 2 ? Plain.new : "abc") } } +t("sub: alternating") { |i| kept { l_sub(i.even? ? "abc" : Plain.new) } } +t("gsub with a Regexp: String, then Plain, then String") { |i| kept { l_gsub(i % 1000 < 500 ? "aba" : Plain.new, /a/) } } +t("gsub with a String pattern: alternating") { |i| kept { l_gsub(i.odd? ? "aba" : Plain.new, "a") } } +t("split: String, then Plain") { |i| kept { l_split(i < 10 ? "a,b" : Plain.new, /,/) } } +t("=~: Plain, then String, then nil") { |i| kept { l_eqt(i < 1000 ? Plain.new : (i < 2000 ? "xxa" : nil), /a/) } } +t("a site that never needs the scope") { |i| kept { l_pass(i.even? ? "abc" : [1, 2]) } } + +# ---------------------------------------------------------------- 2. the callee redefined half way, and put back + +class String + alias_method :__lr_orig_tr, :tr +end +def l_tr(s) = s.tr("a", "b") +t("String#tr, redefined at 1000 and put back at 2000") do |i| + if i == 1000 + String.class_eval { remove_method :tr; def tr(*) = :redefined_tr } + elsif i == 2000 + String.class_eval { remove_method :tr; alias_method :tr, :__lr_orig_tr } + end + kept { l_tr("aaa") } +end + +def l_sub2(s) = s.sub(/a/, "z") +t("String#sub replaced by a Ruby method at 1000, back at 2000") do |i| + if i == 1000 + String.class_eval { alias_method :__lr_orig_sub, :sub; remove_method :sub; def sub(*a) = [:ruby_sub, a.size] } + elsif i == 2000 + String.class_eval { remove_method :sub; alias_method :sub, :__lr_orig_sub } + end + kept { l_sub2("bab") } +end + +# ---------------------------------------------------------------- 3. method_missing, protected, private + +class Ghost + def method_missing(name, *a) = name == :sub ? [:ghost, a.size] : super + def respond_to_missing?(name, p = false) = name == :sub || super +end +t("sub: method_missing, then String, then method_missing") { |i| kept { l_sub(i % 1500 < 700 ? Ghost.new : "abc") } } + +class Prot + def call_prot(o) = o.prot + protected def prot = :protected_prot +end +t("protected method of the same class, then a public one") { |i| Prot.new.call_prot(i < N / 2 ? Prot.new : Plain.new) } +t("protected method, alternating with a public one") { |i| Prot.new.call_prot(i.even? ? Plain.new : Prot.new) } + +class Priv + def call_priv(o) = o.secret + private def secret = :secret +end +t("private method with an explicit receiver, then public") do |i| + begin + Priv.new.call_priv(i < 10 ? Priv.new : Plain.new.tap { |p| def p.secret = :public_secret }) + rescue NoMethodError => e + e.class + end +end + +# ---------------------------------------------------------------- 4. super into a method that reads the caller's scope + +class SubString < String + def sub(*a) = super + def gsub(*a, &b) = super +end +t("super into String#sub: then a plain receiver") { |i| kept { l_sub(i < N / 2 ? SubString.new("abc") : Plain.new) } } +t("super into String#gsub with a block") { |i| kept { SubString.new("aba").gsub(/a/) { |m| [m, $&].inspect } } } + +# ---------------------------------------------------------------- 5. block_given?, binding, eval from the same site + +def l_bg_block(&b) = [1].map { |_| block_given? }.first +t("block_given? in a block of the method") { |i| i.even? ? l_bg_block : l_bg_block { } } + +def l_bnd(o, x) = o.respond_to?(:sub) ? [o.sub("a", "q"), binding.local_variable_get(:x)] : x +t("sub then binding in the same frame") { |i| kept { l_bnd(i.even? ? "abc" : Plain.new, i % 3) } } + +# ---------------------------------------------------------------- 6. two threads on one site + +def l_thread_sub(o) = o.sub(/b/, "B") +# each thread in a method of its own, whose $~ is its own +def l_thread_worker(k) + bad = 0 + 2000.times do |j| + "mine" =~ /(mi)ne/ + o = (j + k).even? ? "abc" : Plain.new + r = l_thread_sub(o) + bad += 1 unless r == (o.is_a?(String) ? "aBc" : [:plain_sub, 2]) && $1 == "mi" + end + bad +end +t("two threads, one site, mixed receivers") do |i| + next nil unless i % 300 == 0 + 2.times.map { |k| Thread.new { l_thread_worker(k) } }.map(&:value) +end + +# ---------------------------------------------------------------- 7. a refinement (in force for the rest of the file) + +module RefineSub + refine Plain do + def sub(*a) = :refined_plain_sub + end +end + +def l_sub_unrefined(o) = o.sub("a", "w") +using RefineSub +def l_sub_refined(o) = o.sub("a", "w") +t("refined Plain#sub, then String") { |i| kept { l_sub_refined(i < N / 2 ? Plain.new : "abc") } } +t("String, then refined Plain#sub") { |i| kept { l_sub_refined(i < N / 2 ? "abc" : Plain.new) } } +t("method defined before using: Plain, String") { |i| kept { l_sub_unrefined(i.even? ? Plain.new : "abc") } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..eff09a1d0 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -971,11 +971,14 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has which costs about 150-200 instructions more than a scope made at entry. `inject` with a block, in the same method, lost its scope (658 -> 498 B, 3% fewer instructions). A C#-only shape the change cannot reach (`minmax`) read 4.6% more in that table, so 5% is - about the floor for one shape there. Untried: a site that has answered - `LightScopeRequired` remembers it, and the frame makes its scope before that call the - next time without asking; or the prelude gives such a method's rare path a method of its - own, so that the common path stays without a splat or a scope-reading callee - (`/perf-core`). + about the floor for one shape there. Tried and rejected (perf/lsite, see Rejected): a + site that has answered `LightScopeRequired` remembers it and skips the light site from + then on - the light site is +7 of the +232 instructions a light `gsub` pays; the rest is + the late scope's arm in the body and the light frame's exit. Untried: a light method + that has made its scope late once enters through its scoped body from then on (a + per-method memory, compiled twice); or the prelude gives such a method's rare path a + method of its own, so that the common path stays without a splat or a scope-reading + callee (`/perf-core`). The second: `w_splat` is 366 ns against 188 for the bare call (CRuby 194 and 71), and still about 185 B a call more than the block-passing wrapper: the rest Array the caller's rule builds and its unpacking into the callee. Untried: a rule for a splat @@ -4174,6 +4177,56 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/lsite (/perf-step, 2026-11-26) - a light site that remembers it needed the scope** + (gap 16; switch `IR_LIGHT_REMEMBER`). In `LightFrameRewriter.MakeLightCall`, each site + got a box (`StrongBox`, a constant of the body like a regex literal's cache, set + only to `RubyOps.LightScopeRequired`): `#r = memory ?? light(...)`, and the arm that makes + the scope stores the marker when the box is empty. A stale read costs an ask or a scope, + never a wrong answer, since the ordinary site with the scope is what the light one stands + in for. The AOT compiler had to learn to re-create a set box empty. First version + (`memory == null ? (r = light(), r == marker ? memory = r : r) : marker`) cost more. + - **How it was measured.** No `ab.rb -i` here: the container refuses + `perf_event_open`, and timing (`ab.rb -r 10`) spread 5-15% on 50-500 ns shapes. New: + `Util/perf/callgrind/count.sh`, callgrind instrumenting only the shape files' sections, + main thread only, tiered compilation off: steady to 0.01% section to section and process + to process (two processes of one arm: 8,996.6 / 8,993.3), but larger than the counter's + numbers and dependent on which shapes ran before in the process, so arms are compared + with the same shape list. N=20,000. + - **Regex shapes** (instructions a call; on = scope at entry, all = `IR_LIGHT_REGEX=all`; + remember off -> on): `gsub` on 12,719 -> 12,751, all 12,954 -> 12,971 (all/on 1.017); + `split` all 11,115 -> 11,240 (1.029 against on); `case when /z/` 8,908 -> 8,870 (1.029); + `=~ /d/` 6,014 -> 6,018 (1.028). Controls: `size` 1,538 -> 1,575, `tilde` (a scoped + method) 6,321 -> 6,357, `match?` 4,968 -> 5,038: +37 on every shape, the cost of the + one node in the shape file's own driver loop, a light block run by the DLR + interpreter (the first version: +118). + - **inject(:+) and zip** (core-small.rb; `IR_LIGHT_FRAMES=0` / remember off / on): + `inject_sym` 9,268 / 9,132 / 9,345, `zip` 13,168 / 13,133 / 13,256, `inject` with a block + 10,418 / 10,276 / 10,643, `minmax` (control) 4,793 / 4,503 / 4,594. In this measure the + light frames already did not lose against scoped ones, and remembering made all four + worse (1.009-1.036): the prelude's light frames run interpreted at first and pay the + node on every light call. + - **Why it cannot work: the light site is not the cost.** callgrind with the CLR's perf + map, one `gsub` section, light (all) against scoped (on), +232 instructions a call: the + method's own compiled body +165 (the late scope's arm: `MaterializeLocals`, + `CreateMethodScopeLazy`'s arguments, the test), `CreateMethodScopeLazy` +35 against + `CreateMethodScope` 57 less, `LeaveLightMethodFrameSlow` +23, `LeaveLightMethodFrame` + +17, `TakePendingCallee(Slow)` +30, `EnterLightMethod` +12; the light site's rule (the + dynamic `CallSite.Target`) +7. Skipping the site saves those 7 and adds the node. + - Kept: `Util/light-remember-matrix.rb` (a site that needed the scope once and then gets a + receiver whose method does not, and the reverse, alternating; String#tr and String#sub + redefined at 1,000 calls and put back at 2,000; method_missing; a protected method of the + same class then a public one; a private method with an explicit receiver; super into + String#sub and String#gsub with a block; block_given? in a block of the method; binding + after a scope-needing call; two threads on one site with their own `$~`; a refinement + in force, and a method defined before `using`). It, regex-light, block-given and + light-rest print CRuby 4.0's output on the baseline and on the candidate, each as built, + with `IR_LIGHT_REMEMBER=0`, `IR_LIGHT_FRAMES=0`, `IR_LIGHT_REGEX=all`, `-X:NoJIT + -X:NoOSR` and `-X:NoJITCalls`; hot-shapes prints the baseline's in every mode (its + known `Encoding::CompatibilityError` for CRuby's FrozenError). Not run: `IR_CONFIG=R2R`. + - Learned: what a light frame that makes its scope late pays is the frame, not the + question - to stop losing, such a method has to enter scoped next time (gap 16's + "Untried"), not ask less. + - **perf/evalc da03f675 and its second pass (round thirty-one, 2026-11-22) - a cache of the compiled code of eval'd strings** (gap 31). Merged, then taken out (f133bcfa) after an independent review; the second pass that fixed the review's points was rejected too. From 16ec59956cffcc9c13cc51ba3a54b6f8697cb370 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:55:12 +0000 Subject: [PATCH 025/439] LEDGER: perf/struct landed (not gated); gaps 24 and 19 brought up to date Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Util/perf/LEDGER.md | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8088ae413..3451a4cca 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1037,6 +1037,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has method version (reading the code: `new` and `[]` added to the struct class's singleton class override `Class#new`, which invalidates sites on override), so it throws away every running loop's copy and every typed body's entry. + perf/struct (see Landed, not gated) measured it - 8 JIT invalidations for 30 `Struct.new`s + beside a hot loop - and fixed it for anonymous classes (0); a reader and the first `new` on a + new struct class take dispatchers instead of rules (4-9 and 10-25 us under IR_BIND_TRACE). + `Struct.new(:a, :b)` plus a first new and getter 79.5 -> 51 us (CRuby 5.7); `Struct.new` alone + 26-27 -> 20-21 us a class (CRuby: 4.1-4.4). Left: the class itself (`Struct.new` in C# is about + three quarters of it, `Class.new(Struct)` 4 us), writers' rules, and a site past the + dispatchers' budget building a `new` rule per class. 20. **Array and Hash are not safe under concurrent mutation** - a correctness gap, listed here because the fix has a speed price and the papers say how to keep it at zero for code that does not share. Eight threads appending to one Array raise "Source array @@ -1082,6 +1089,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the invoice shapes are at CRuby's time. Left: initializers taking keywords (`Product.new(sku: ...)`) at about 2x CRuby, `Hash#dup`, and Struct `keyword_init` as above. And `Data.singleton_methods` lists `:allocate`, which CRuby's does not (as on the baseline). + perf/struct (see Landed, not gated): Struct keyword creation is stored in C#, `kw_new` 1017 -> + 198 ns against CRuby's 299 (`kw_hash` 147 against 196, `sub_kw` 379 against 356). Left from this + gap: keyword initializers (`kwinit` 236 against 132) and `Hash#dup`. 25. **Havlak: 1.4 times CRuby, 25 times TruffleRuby, and no single place** (round sixteen's breakdown; its author's numbers, taken beside two other experiments at load 2-14, so ratios). CRuby runs a copy with som.rb's `Set` renamed to `SomSet`: 2.85-3.3 @@ -1384,6 +1394,55 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/struct (2026-11-26, 0cfab5c..37eae81, not gated) - Struct keyword arguments stored in + C#; a new struct class made without moving the global method version, its readers and its first + constructions without rules (gaps 24 and 19).** Four commits, one switch (`IR_FAST_STRUCT=0`). + (1) `Struct#initialize` (RubyStructOps.Initialize) stores keywords whose keys all name members + (Symbol or String, MRI's struct_hash_set_i) when keyword_init is true or nil, a single Hash for + keyword_init: true, and clears every member for no arguments; it sent all of them through a site + to `__struct_initialize_slow__` in ruby4.rb before (copy the Hash, `members`, `keyword_init?`, + `keys - names`, a splat). keyword_init is read as MRI's struct_ivar_get does, so a subclass of a + keyword_init: true struct is keyword_init too, and String keys name members: both were wrong on + master. (2) Measured first, as the gap asked: a loop calling a specialized method while it made a + Struct class every 10,000 iterations counted 8 JIT invalidations for 30 classes (Class.new none), + and eight settle the method on its generic body for good; `new` and `[]` on the singleton class + override Class#new, and the prelude's `inspect` overrides Module#inspect. An anonymous class whose + superclass has the default inherited hook has been seen by no code, so its methods go into the + tables without PrepareMethodUpdate (`RubyModule.SetMethodOfUnseenModuleNoEventNoLock`), events + after; `keyword_init?` and `inspect` are made in C# with the others, as MRI's setup_struct does + (so `singleton_methods` lists `:inspect`, as in CRuby). Now 0 invalidations. (3) A member reader + at a site with a scope (light ones too) gets a `RubyStructReaderDispatcher`: the rule generators + are closures per member per class, so no rule was ever shared (IR_BIND_TRACE: 32-577 us -> 4-9 us). + (4) `LibraryDispatcher.TryCreateConstruction` takes struct classes (`TryGetObjectConstruction(count, + structs: true)`; the method JIT's constructions still take plain classes only): allocate the + RubyStruct, call a Ruby initialize as for a plain class or Struct#initialize through a site of the + construction's own, as the rule does (IR_BIND_TRACE: the first `new` 80-160 us -> 10-25 us). + `Util/bench/struct-shapes.rb`, six alternating rounds, CRuby / master / new, ns: `kw_new` 299 / + 1017 / 198, `kwnil_new` 305 / 1019 / 189, `kw_hash` 196 / 1051 / 147, `sub_kw` 356 / 1149 / 379, + `pos_new` 120 / 180 / 115, `new_class_use` (Struct.new plus a first new and getter) 5,678 / 79,510 + / 50,976; `kwinit`, `getter`, `setter`, `obj_new`, `plain` and `hash_dup` overlap (the machine was + loaded: `getter` read 39 ns in one run and 79-93 in another; `hash_dup`, `setter` and `obj_new` + each looked slower once and overlapped run alone, 8-10 rounds). `new_class` is GC-bound and its + least-of-seven swings (spreads 44-143%); in one process, rounds of 1,000 `Struct.new(:a, :b)`, + three alternating runs: 26-27 us a class on master, 20-21 here, CRuby 4.1-4.4. + `Util/struct-matrix.rb` (new, 110 rows, each cold, again and warm) prints CRuby's output but for + `UsingRefine.make`, a refined `initialize` that Class#new sees on every IronRuby build (master + too); master differs in eight more rows. Matrices through gate-matrices.rb, as built, `-X:NoJIT + -X:NoOSR`, `-X:NoJITCalls`, `IR_LIGHT_FRAMES=0`, `IR_PARKED_SCOPES=0`, R2R and `IR_FAST_STRUCT=0`: + struct, hash-struct, hash-order, keyword-light, jit, jit-calls `same` or `baseline -16`, + hot-shapes `baseline`: PASS. spec/core/struct: 170 examples, 1 error (the known deconstruct_keys + one) on master, on this and with the switch off. IronRuby.Tests, the 37 named Struct, Keyword and + Construct tests and ClrRubyImpliedInterfaces3: PASSED. Recursion through a struct's initialize + and keyword initialize: SystemStackError with and without the JIT. Census: 0 methods changed (it + sees none of this). For the gate: the unseen-class path (a hook of `inherited` defined in another + thread between the two checks, ObjectSpace finding the class before its members exist), the + construction's initialize site made without the caller's scope (as the rule's library-initialize + call, which keeps the caller's flags, may not be), and that `keyword_init?` reads the hidden + variable through superclasses for any Struct subclass. Left: writers keep per-class rules; a site + past the dispatchers' budget builds a `new` rule per class (about 250 classes into a loop); + `Struct.new` itself is 5 times CRuby; `kwinit` (`def initialize(sku:, name:)`) 1.8x and + `Hash#dup` are untouched. + - **perf/first-bind (2026-11-26) - what a first bind costs, split; light-scope sites call library methods through a dispatcher for their first calls (gap 26).** The split (master 4bae83f3, R2R host with the startup library; `IR_BIND_TRACE`, `IR_PHASE_TIMES`, perf with jitdump classing From 1efd7e633878f74fab07e1fc92a627fb0237a20c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:55:47 +0000 Subject: [PATCH 026/439] Take next on map, select and reject enumerators with a cursor, not a fiber An enumerator of #map, #collect, #select, #filter, #find_all or #reject ran its external iteration on a fiber, a thread here: 5-10 us of process CPU per #next against CRuby's 0.22-0.26. The element such a method yields is the one its receiver's #each yields, which the cursors of Array#each, Range#each, Hash#each and Struct#each already produce without running Ruby code; what the method adds is what it does with its block's answers, and under #next the block's answer is the value fed with #feed, or nil. So an enumerator of Array's own methods, or of Enumerable's over a receiver whose #each a cursor walks, now gets a cursor that steps the source and keeps each answer as the suspended yield returns (ExternalCursor.Resume): the answers for #map, the elements answered true for #select (Array's re-read after the block, as MRI's rb_ary_elt does) and false for #reject (Array's as yielded). StopIteration#result is what it collected (ExternalCursor.Result). The methods involved must be the built-in ones, as for the other cursors; IR_FAST_NEXT=0 leaves them to the fiber. Util/bench/extiter-shapes.rb (ab.rb -r 6, ns per next): [1000].map 9944 -> 92 (CRuby 245), select 5123 -> 77, (1..1000).map 9478 -> 102, a Hash's find_all 7727 -> 369; the fiber-backed controls level when run alone. 50 new probes in Util/extiter-matrix.rb (178 in all: each method over each source, fed and not, peek, next_values, loop, rewind, mutation, redefinition, threads) print CRuby's output with the change, without it and switched off; enum-next, block-loop, hash-order, raise, full-message, enum and jit matrices agree with the baseline. spec/core/enumerator, kernel/loop and the array and enumerable map/select/ reject specs pass in all three modes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Src/Libraries/Builtins/Enumerator.cs | 141 ++++++++++++++++++++++++++- Util/bench/extiter-shapes.rb | 4 +- Util/extiter-matrix.rb | 64 ++++++++++++ Util/perf/LEDGER.md | 47 +++++++-- 4 files changed, 244 insertions(+), 12 deletions(-) diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index 28d6e0806..ae2130776 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -292,6 +292,108 @@ internal virtual bool Multiple { /// The method has returned: what it does on its way out. internal virtual void Finish() { } + + /// + /// The yield of the last step has returned, with the value fed to it (Enumerator#feed) or nil: what the method's + /// block would have answered. + /// + internal virtual void Resume(object fed) { + } + + /// What the method answers (StopIteration#result), once it has returned. + internal virtual object Result { + get { return Receiver; } + } + } + + // What a collecting method does with what its block answers, the block being the suspended yield of #next: #map + // keeps the answers, #select (#filter, #find_all) the elements it answered true for, #reject the others. + private const int CollectMap = 0, CollectSelect = 1, CollectReject = 2; + + // Array#map, #collect, #select, #filter and #reject (IListOps): the length is read at each step, as Array#each's + // is; #select keeps the element as it is once the block has run (MRI's rb_ary_elt), #reject the one it yielded. + private sealed class ArrayCollectCursor : ExternalCursor { + private readonly RubyArray/*!*/ _array; + private readonly int _kind; + private readonly RubyArray/*!*/ _result = new RubyArray(); + private int _index; + private object _current; + + internal ArrayCollectCursor(RubyArray/*!*/ array, int kind) : base(array) { + _array = array; + _kind = kind; + } + + internal override bool MoveNext(out object value) { + int index = _index; + if (index < _array.Count) { + _index = index + 1; + value = _current = _array[index]; + return true; + } + value = _current = null; + return false; + } + + internal override void Resume(object fed) { + if (_kind == CollectMap) { + _result.Add(fed); + } else if (_kind == CollectSelect) { + if (Protocols.IsTrue(fed)) { + int index = _index - 1; + _result.Add(index < _array.Count ? _array[index] : null); + } + } else if (!Protocols.IsTrue(fed)) { + _result.Add(_current); + } + } + + internal override object Result { + get { return _result; } + } + } + + // Enumerable#map, #collect, #select, #filter, #find_all and #reject over a cursor of the receiver's #each (a Range, + // a Hash's #map and #find_all, a Struct): the element kept is the one yielded, packed before the block runs (FilterImpl). + private sealed class EnumerableCollectCursor : ExternalCursor { + private readonly ExternalCursor/*!*/ _inner; + private readonly int _kind; + private readonly RubyArray/*!*/ _result = new RubyArray(); + private object _current; + + internal EnumerableCollectCursor(object receiver, ExternalCursor/*!*/ inner, int kind) : base(receiver) { + _inner = inner; + _kind = kind; + } + + internal override bool Multiple { + get { return _inner.Multiple; } + } + + internal override bool MoveNext(out object value) { + if (_inner.MoveNext(out value)) { + _current = value; + return true; + } + _current = null; + return false; + } + + internal override void Resume(object fed) { + if (_kind == CollectMap) { + _result.Add(fed); + } else if (Protocols.IsTrue(fed) == (_kind == CollectSelect)) { + _result.Add(_current); + } + } + + internal override void Finish() { + _inner.Finish(); + } + + internal override object Result { + get { return _result; } + } } // Enumerable#each_slice and #each_cons (EachSlice) over a cursor of the receiver's #each: a new @@ -671,6 +773,18 @@ private static ExternalCursor TryCreateCursor(RubyContext/*!*/ context, Enumerat case "each": return TryCreateEachCursor(context, target); + case "map": + case "collect": + return TryCreateCollectCursor(context, target, name, CollectMap); + + case "select": + case "filter": + case "find_all": + return TryCreateCollectCursor(context, target, name, CollectSelect); + + case "reject": + return TryCreateCollectCursor(context, target, name, CollectReject); + case "each_pair": return (hash = target as Hash) != null && IsBuiltinMethod(context, target, name, typeof(IDictionaryOps), "Each", "EachPair") ? new HashCursor(hash, HashCursor.Pairs) : null; @@ -716,6 +830,28 @@ private static ExternalCursor TryCreateCursor(RubyContext/*!*/ context, Enumerat return null; } + // A collecting method (#map, #select...) that is Array's own over an Array, or Enumerable's over a receiver whose #each + // a cursor can do. IR_FAST_NEXT=0 leaves them to the fiber. + private static ExternalCursor TryCreateCollectCursor(RubyContext/*!*/ context, object target, string/*!*/ name, int kind) { + if (!_fastNext) { + return null; + } + // the C# methods of the name: the blockless one that made the enumerator, and the one with a block it stands for + string impl = (kind == CollectMap) ? (name == "collect" ? "Collect" : "Map") : + (kind == CollectReject) ? "Reject" : (name == "filter" ? "Filter" : name == "find_all" ? "FindAll" : "Select"); + RubyArray array = target as RubyArray; + if (array != null && name != "find_all") { + return IsBuiltinMethod(context, target, name, typeof(IListOps), + kind == CollectMap ? "GetMapEnumerator" : kind == CollectSelect ? "GetSelectEnumerator" : "Reject", impl) ? + new ArrayCollectCursor(array, kind) : null; + } + if (!IsBuiltinMethod(context, target, name, typeof(Enumerable), kind == CollectMap ? "GetMapEnumerator" : impl, impl)) { + return null; + } + ExternalCursor inner = TryCreateEachCursor(context, target); + return inner != null ? new EnumerableCollectCursor(target, inner, kind) : null; + } + // The receiver's own #each, when it is a built-in one a cursor can do. private static ExternalCursor TryCreateEachCursor(RubyContext/*!*/ context, object target) { RubyArray array; @@ -872,6 +1008,7 @@ private static object CursorStep(CallSiteStorage x; "#{x.class}: #{x.message}"; end }.value } +probe("coll_frozen_feed") { e = [1].map; e.next; e.freeze; (e.feed(1) rescue $!.class) } +probe("coll_inspect") { e = [1, 2].select; e.next; e.inspect } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..cdd2a561a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1418,15 +1418,17 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has each_cons over those, while the method is the unredefined one, with no fiber; a `next` there is 67-94 ns against CRuby's 226-234 (`Util/bench/extiter-shapes.rb`). Its end was the cost left - a StopIteration thrown from C# took the catch-site walk, 22 us against CRuby's 0.8 - - and perf/extiter (Landed) defers that walk. Still on a fiber, 5-10 us of process CPU per - `next` against 0.22-0.36: `map` / `select` / `each_with_object` enumerators (no cursor for - them yet: a cursor could keep the fed values for StopIteration#result), `with_index`, - `Enumerator::Lazy`, `Enumerator.produce` (generators of the prelude, which run Ruby code - between two values: a cursor would call blocks under its lock) and `Enumerator.new`. A raw - fiber round trip is 2.3 us of wall clock and 4.7-6 us of CPU (two threads spinning), so the - prelude's machinery around it is not where the time is. Untried: cursors for `map` and - `select` over an Array; a cursor over a cursor for `with_index`; switching fibers without a - thread (a continuation of the method JIT's own). + and perf/extiter (Landed) defers that walk; perf/extiter2 (Landed) gives `map`, `collect`, + `select`, `filter`, `find_all` and `reject` cursors of their own. Still on a fiber, 5-10 us of + process CPU per `next` against 0.22-0.36: `with_index` / `each_with_index` / `with_object` on + an enumerator, `each_with_object`, `filter_map` and `flat_map` (the prelude's), Hash#select and + #reject (Hash's own, whose result is a Hash), `Enumerator::Lazy`, `Enumerator.produce` + (generators of the prelude, which run Ruby code between two values: a cursor would call blocks + under its lock) and `Enumerator.new`. A raw fiber round trip is 2.3 us of wall clock and 4.7-6 + us of CPU (two threads spinning), so the prelude's machinery around it is not where the time + is. Untried: a cursor over a cursor for `with_index` (the prelude would have to mark the + generator it makes with its source and offset); switching fibers without a thread (a + continuation of the method JIT's own). 36. **Left from round thirty-five**, each smaller than one gap of its own: `...` passed on is still a splat of an Array and a block argument (`def m(...) = n(...)` allocates the rest per call; the frame is light now); `URI::Generic#query=` and `merge` still run the @@ -1450,6 +1452,33 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/extiter2 (2026-11-26) - `map`, `collect`, `select`, `filter`, `find_all` and `reject` + enumerators take `next` on a cursor, with no fiber (gap 35)** - not gated. Base: the merged + branch at 2f8c31c, which has perf/extiter. An enumerator of Array's own #map / #collect / + #select / #filter / #reject, or of Enumerable's #map / #collect / #select / #filter / + #find_all / #reject over a receiver whose #each a cursor walks (Range, Hash#map and + #find_all, Struct, Integer#times' enumerator), runs on a cursor once the methods involved + are checked to be the built-in ones (`IsBuiltinMethod`, as for the other cursors): the + element comes from the source's cursor, and what the suspended block would have answered - + the value fed with #feed, or nil - is kept for StopIteration#result (`ExternalCursor.Resume`, + `Result`): the answers for #map, the elements answered true for #select (Array's re-read + after the block, MRI's rb_ary_elt), false for #reject (Array's as yielded). No Ruby code runs + in the cursor. `IR_FAST_NEXT=0` leaves them to the fiber (and undoes perf/extiter too). + `Util/bench/extiter-shapes.rb`, `ab.rb -r 6`, ns per `next`, CRuby / base / off / new: + `[1000].map` 245 / 9412 / 9944 / 92 (0.01 of off), `select` 226 / 5024 / 5123 / 77, + `(1..1000).map` 259 / 5174 / 9478 / 102, a Hash's `find_all` 365 / 7427 / 7727 / 369 (0.05); + the cursor shapes of perf/extiter level with base. The fiber controls read 1.1-2.3 times off + in that run, after shapes that no longer start a fiber; alone (`-- ewi_next lazy_next + produce generator`, six rounds) 0.95-1.02, all overlapping. `Util/extiter-matrix.rb` (178 + probes now: each method over each source, with and without #feed, fed before the first + `next` and after the last, `peek`, `next_values`, `loop`, `rewind`, mutation during the + iteration, a subclass, a singleton's and a redefined method and #each, threads) prints + CRuby's output on base, new and off; enum-next-, block-loop-, hash-order-, raise-, + full-message-, enum- and jit-matrix are the same on base, new and off. spec/core/enumerator, + kernel/loop_spec and the array and enumerable map / collect / select / filter / find_all / + reject specs (540 examples) pass in all three; 95 named IronRuby.Tests (Enumerator*, + Enumerable*, Array*, Loop*, Fiber*, Backtrace*, Exception*, Raise*, Rescue*) pass. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 329982e6d3c8ed8411396c419b6f4ca6c4ff940b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:04:49 +0000 Subject: [PATCH 027/439] defined?(@@x) and class_variable_defined? answer true for an overtaken class variable Once an ancestor had a class variable of the same name as a class's own, `defined?(@@x)' in the class and Module#class_variable_defined? raised "class variable @@x of C is overtaken by B": both went through RubyModule.TryResolveClassVariable, the lookup of a read, which raises that error. CRuby answers "class variable" and true: rb_cvar_defined walks the ancestors without the check, and only a read (rb_cvar_get) raises. RubyModule.IsClassVariableDefined is that walk; RubyOps.IsDefinedClassVariable and ModuleOps.IsClassVariableDefined use it. A read and class_variable_get still raise. ClassVariables_DefinedOvertaken1 has CRuby 4.0's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 31 +++++++++++++++++++++++++ Src/Libraries/Builtins/ModuleOps.cs | 3 +-- Src/Ruby/Builtins/RubyModule.cs | 17 ++++++++++++++ Src/Ruby/Runtime/RubyOps.cs | 3 +-- 5 files changed, 51 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 834bc86db..aabb376c0 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -847,6 +847,7 @@ public Tests(Driver/*!*/ driver) { Exception_RescueRefinedCaseEquality1, ClassVariables1, + ClassVariables_DefinedOvertaken1, UnqualifiedConstants2, AliasMethodLookup1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 7128d1114..896541bc0 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -846,6 +846,37 @@ puts @@a "); } + /// + /// defined?(@@x) and Module#class_variable_defined? answer true for a class variable an ancestor has overtaken, + /// as MRI's rb_cvar_defined does; reading it still raises. + /// + public void ClassVariables_DefinedOvertaken1() { + TestOutput(@" +class OB; end +class OS < OB + @@ov = :sub + def d = defined?(@@ov) + def r = @@ov +end +p OS.new.d, OS.class_variable_defined?(:@@ov) +OB.class_variable_set(:@@ov, :base) +p OS.new.d, OS.class_variable_defined?(:@@ov), OB.class_variable_defined?(:@@ov) +begin; OS.new.r; rescue RuntimeError => e; p e.message; end +begin; OS.class_variable_get(:@@ov); rescue RuntimeError => e; p e.message; end +p OS.class_variable_defined?(:@@none), defined?(OS) +", @" +""class variable"" +true +""class variable"" +true +true +""class variable @@ov of OS is overtaken by OB"" +""class variable @@ov of OS is overtaken by OB"" +false +""constant"" +"); + } + public void Scenario_RubyThreads1() { AssertOutput(delegate() { CompilerTest(@" diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 18e33562d..3a508655b 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -1229,8 +1229,7 @@ public static bool IsClassVariableDefined(RubyModule/*!*/ self, [DefaultProtocol if (self.Context.RactorsStarted) { RactorIsolation.CheckClassVariable(self, variableName); } - object value; - if (self.TryResolveClassVariable(variableName, out value) == null) { + if (!self.IsClassVariableDefined(variableName)) { RubyUtils.CheckClassVariableName(variableName); return false; } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index bfa4f284b..05b7c1eb4 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -3817,6 +3817,23 @@ public RubyModule TryResolveClassVariable(string/*!*/ name, out object value) { return target; } + /// + /// Whether the module or an ancestor has the class variable: MRI's rb_cvar_defined, which `defined?(@@x)' and + /// Module#class_variable_defined? answer by, walks the ancestors without the "overtaken" check of a read + /// (TryResolveClassVariable). + /// + public bool IsClassVariableDefined(string/*!*/ name) { + Assert.NotNull(name); + bool found = false; + using (Context.ClassHierarchyLocker()) { + ForEachAncestor(delegate(RubyModule/*!*/ module) { + object value; + return found = module.TryGetClassVariable(name, out value); + }); + } + return found; + } + public bool EnumerateClassVariables(Func/*!*/ action) { var table = _classVariables; if (table != null) { diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 0df3ee308..44b3d1f7f 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -5978,8 +5978,7 @@ public static bool IsDefinedClassVariable(RubyScope/*!*/ scope, string/*!*/ name if (owner.Context.RactorsStarted) { RactorIsolation.CheckClassVariable(owner, name); } - object value; - return owner.TryResolveClassVariable(name, out value) != null; + return owner.IsClassVariableDefined(name); } [Emitted] From f654dcdaaccdd61b67c7d35c5e4876a41136b4b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:04:49 +0000 Subject: [PATCH 028/439] A method defined in a refine block reads the class variables of the module around it `@@x' in a method defined in a `refine' block read and wrote the class variables of the refinement, an anonymous module ("uninitialized class variable @@x in "), where CRuby uses the module the `refine' is written in. Such a method's declaring scope is a RubyModuleScope of the refinement (RubyOps.DefinitionScope), made so that the refinements are active in it, and the class-variable walk (RubyScope.GetInnerMostModule) stopped at it. CRuby's vm_get_cvar_base passes over a cref pushed by an eval, which the refine block's is, as it passes over a singleton class's; the walk now passes over a refinement too. Constant lookup still sees the refinement, as in CRuby. ClassVariables_Refinement1 has CRuby 4.0's output; Util/lexical-light-matrix.rb probes `@@x' and `defined?(@@x)' in a refinement and `defined?' of an overtaken class variable again, and prints CRuby's output in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 30 +++++++++++++++++++++++++ Src/Ruby/Runtime/RubyScope.cs | 5 ++++- Util/lexical-light-matrix.rb | 9 ++++---- 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index aabb376c0..787172386 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -848,6 +848,7 @@ public Tests(Driver/*!*/ driver) { ClassVariables1, ClassVariables_DefinedOvertaken1, + ClassVariables_Refinement1, UnqualifiedConstants2, AliasMethodLookup1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 896541bc0..27077eb09 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -877,6 +877,36 @@ class OS < OB "); } + /// + /// A method defined in a `refine' block reads and writes the class variables of the module around the `refine', + /// as MRI's vm_get_cvar_base, which passes over the refinement's cref, does. + /// + public void ClassVariables_Refinement1() { + TestOutput(@" +module RM + @@r = :outer + refine String do + p @@r + def cv_r = @@r + def cv_d = defined?(@@r) + def cv_w(v) = (@@r = v) + def cv_missing = defined?(@@nowhere) + end +end +using RM +p ""s"".cv_r, ""s"".cv_d, ""s"".cv_missing +""s"".cv_w(:written) +p RM.class_variable_get(:@@r), ""s"".cv_r +", @" +:outer +:outer +""class variable"" +nil +:written +:written +"); + } + public void Scenario_RubyThreads1() { AssertOutput(delegate() { CompilerTest(@" diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 9c64af656..a8602ff6c 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -902,7 +902,10 @@ internal RubyModule GetInnerMostModuleForClassVariableAccess() { RubyScope scope = this; do { RubyModule result = scope.Module; - if (result != null && (!skipSingletons || !(result.IsSingletonClass || IsInstanceEval(scope)))) { + // MRI's vm_get_cvar_base passes over a singleton class's cref and one pushed by an eval - an instance_eval'd + // String, and the refinement a method defined in a `refine' block has as its cref (RubyOps.DefinitionScope), + // whose @@x is the module's around the `refine' + if (result != null && (!skipSingletons || !(result.IsSingletonClass || result.IsRefinement || IsInstanceEval(scope)))) { return result; } scope = scope.Parent; diff --git a/Util/lexical-light-matrix.rb b/Util/lexical-light-matrix.rb index 1c8b03e19..c91150bf6 100644 --- a/Util/lexical-light-matrix.rb +++ b/Util/lexical-light-matrix.rb @@ -112,11 +112,8 @@ def ov_defined; defined?(@@ov); end co = CvOver.new t('overtaken by an ancestor later') do |i| CvOverBase.class_variable_set(:@@ov, :base) if i == 1500 - err { co.ov } + [err { co.ov }, co.ov_defined, CvOver.class_variable_defined?(:@@ov)] end -# Not probed, because the unchanged build differs from CRuby 4.0 there already: `defined?(@@ov)' once an -# ancestor has overtaken @@ov (CRuby: "class variable"; IronRuby raises the RuntimeError), and `@@r' in a -# method of a `refine' block (CRuby: the module around the refine; IronRuby: the refinement). # a module's class variable through an including class module CvMod @@ -308,9 +305,13 @@ def recursive(n); n == 0 ? [@@a, self.class::A] : recursive(n - 1); end # `using' keeps its scope, so nothing above may follow it) module CvRefine + @@r = :refinement_module refine String do def cv_refined_defined; defined?(@@nowhere); end + def cv_refined; err { @@r }; end + def cv_refined_d; defined?(@@r); end end end using CvRefine t('refinement body, defined? of a missing one') { "s".cv_refined_defined } +t('refinement body') { ["s".cv_refined, "s".cv_refined_d] } From c35cf3ed28de951c94031e75a046a724f46f8884 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:05:03 +0000 Subject: [PATCH 029/439] Let keywords beside a rest or post parameter, and `**h' passed on, into light frames The census of 2f8c31c kept 101 methods out of light frames for "keyword parameters with a rest or post parameter", 24 of them the prelude's (String#each_line, String#lines, IO#initialize, File#initialize, Data#initialize, Kernel#open, IO.readlines...). perf/lkw left the line out: such a signature is lowered to one splat, `def m(*?args?)', and a prologue that binds the positionals out of it by hand (PrismAstBridge.LowerGeneralParameters), with SplatParameterRead nodes IsScopeFree did not take. Each SplatParameterRead is one runtime call on the hidden local: CheckSplatArity, ShiftSplatArgument, ShiftOptionalSplatArgument, ShiftRestSplatArguments and the auto-splat pair take no scope, and PopKeywordArguments reads only the runtime's equality comparer, for the empty hash of a call without keywords. The rest Array is bound by the method's RubyMethodInfo whatever the frame, so a light frame consumes the same call-owned Array a scope frame does. IR_LIGHT_KEYWORD_REST (on unless =0) lets the lowering in: IsScopeFree takes SplatParameterRead (its local and an optional's default), and ScopeOperandIndex hands PopKeywordArguments the declaring scope. A signature whose positionals a parameterless `super' cannot read back by name (an anonymous rest with posts, a destructured parameter) keeps its copy of the splat and its scope. That alone moved 58 methods; 30 more then passed the filter and failed in the rewriter, because they pass `**opts' on: KeywordArgumentSplat compiles to SplatKeywordHash, SplatKeywordHashIfHash, KeywordSplatArgument or (a parameterless super with **rest) PassOnKeywordRest, which read only the runtime's equality comparer too. IR_LIGHT_KEYWORD_SPLAT (on unless =0) hands them the declaring scope; that also lets in the methods without a rest that pass a hash on (`def f(**o) = g(**o)', `g(x, **h)'). Census (Src/StdLib + AWFY, 28,376 methods): light frames 26,535 -> 26,693 (93.5% -> 94.1%), 158 moved up, none down; JIT verdicts unchanged; "body needs its scope after the rewrite" 104 -> 34. Each switch alone: +58 and +70. Instructions per call (Util/perf/callgrind/count.sh, both switches off -> on, new shapes in prelude-cost.rb): a rest and a keyword 5,720 -> 5,325 (0.93), passing **opts on 12,272 -> 11,359 (0.93), String#each_line(chomp: true) 17,670 -> 17,436 (0.99); a keyword without a rest and a constant read 1.00. Util/keyword-rest-light-matrix.rb (new) prints CRuby 4.0's output on the unchanged build, and on this one by default, with either switch off, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. The keyword, lexical, jit, jit-calls, block-given, light-rest, splat-pass and hash-literal matrices agree with the baseline and CRuby. Method_LightFrameKeywordRest1 is new; 102 named tests (class variables, refinements, keywords, super, splats, constants, light frames) pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 44 ++++ .../Ast/Definitions/MethodDefinition.cs | 46 +++- Util/bench/prelude-cost.rb | 17 ++ Util/keyword-rest-light-matrix.rb | 200 ++++++++++++++++++ 5 files changed, 302 insertions(+), 6 deletions(-) create mode 100644 Util/keyword-rest-light-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 787172386..e11c273f5 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1139,6 +1139,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGuard1, Method_LightFrameBlockGiven1, Method_LightFrameRest1, + Method_LightFrameKeywordRest1, Method_LightFrameGlobal1, Method_LightFrameLexical1, Method_ParkedScope1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 27077eb09..1c5e91aeb 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7770,6 +7770,50 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters "); } + /// + /// IR_LIGHT_KEYWORD_REST and IR_LIGHT_KEYWORD_SPLAT: keywords beside a rest or post parameter, bound out of one splat + /// (PrismAstBridge.LowerGeneralParameters), and a hash passed on as keywords, in a light frame + /// (Util/keyword-rest-light-matrix.rb). + /// + public void Method_LightFrameKeywordRest1() { + TestOutput(@" +def rk(*a, k: 1); [a, k]; end +def post(x, *r, z, k: 0); [x, r, z, k]; end +def opt(x, y = x + 1, *r, k: y); [x, y, r, k]; end +def inner(*a, **o); o[:seen] = true unless o.empty?; [a, o]; end +def pass(*a, **o); inner(*a, **o); end +class B; def m(a, **o) = [:b, a, o]; end +class S < B; def m(a, **o); [:s, super]; end; end +arr = [1, 2, 3] +h = {k: 5} +p rk, rk(1, k: 2), rk({k: 3}), post(1, 2), post(*arr, k: 4), arr, opt(1), opt(1, 5, 6, k: 7) +p pass(1, **h), h, pass(**nil), pass(1, **{}), S.new.m(1, j: 2), S.new.m(1) +p 40.times.map { |i| rk(*[i] * (i % 3), k: i % 2).flatten.size }.uniq +begin; post(1); rescue ArgumentError => e; p e.message; end +begin; rk(j: 1); rescue ArgumentError => e; p e.message; end +begin; pass(1, **1); rescue TypeError => e; p e.message; end +", @" +[[], 1] +[[1], 2] +[[{k: 3}], 1] +[1, [], 2, 0] +[1, [2], 3, 4] +[1, 2, 3] +[1, 2, [], 2] +[1, 5, [6], 7] +[[1], {k: 5, seen: true}] +{k: 5} +[[], {}] +[[1], {}] +[:s, [:b, 1, {j: 2}]] +[:s, [:b, 1, {}]] +[1, 2, 3] +""wrong number of arguments (given 1, expected 2+)"" +""unknown keyword: :j"" +""no implicit conversion of Integer into Hash"" +"); + } + /// /// A method that reads or writes a global is a light frame too (MethodDefinition.IsLightGlobal): every global but $~ and /// $_ is the runtime's, and the frame reads and writes it through the declaring scope. A name that comes to denote $~ or $_ diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index c31a62eec..a50e32e33 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -597,6 +597,18 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// internal static readonly bool LightLexicalEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_LEXICAL") != "0"; + /// + /// IR_LIGHT_KEYWORD_REST=0 keeps every method with keyword parameters beside a rest or post parameter + /// (`def warn(*msgs, uplevel: nil)', `def m(a, *r, z, k: 1)') out of light frames (see KeywordsWithSplatLowering). + /// + internal static readonly bool LightKeywordRestEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_KEYWORD_REST") != "0"; + + /// + /// IR_LIGHT_KEYWORD_SPLAT=0 makes a light-frame candidate that passes a hash on as keywords (`inner(*args, **opts)', + /// a parameterless `super' with a `**rest') make its scope, as before (see LightFrameRewriter.ScopeOperandIndex). + /// + internal static readonly bool LightKeywordSplatEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_KEYWORD_SPLAT") != "0"; + // The built-in methods that store the caller's $~ when given a Regexp, and so take the caller's scope: a light frame // that calls one makes its scope on the call (RubyOps.LightScopeRequired) and calls again, which costs more than the // scope made at entry (gap 16 of Util/perf/LEDGER.md). A name only says which method is likely, not which is called, @@ -712,8 +724,10 @@ private MSA.Expression/*!*/ StackCheck { /// call's keyword hash, and a prologue at the head of the body that checks it and binds each keyword to its local, the /// defaults evaluated there in order (PrismAstBridge.LowerKeywords): locals, calls and runtime helpers that take no /// scope, so the body is scope-free if its statements are. The hash a call that passes no keywords gets is the - /// runtime's (LightFrameRewriter.ScopeOperandIndex). Not taken: keywords beside a rest or post parameter, which the - /// general lowering binds out of one splat by hand (KeywordsWithSplatLowering). + /// runtime's (LightFrameRewriter.ScopeOperandIndex). Keywords beside a rest or post parameter too (IR_LIGHT_KEYWORD_REST): + /// the general lowering binds them out of one splat by hand (KeywordsWithSplatLowering), with helpers that take no + /// scope but PopKeywordArguments, which reads the runtime's (ScopeOperandIndex). Not taken: such a signature whose + /// positionals a parameterless `super' cannot read back by name, which keeps a copy of the splat (SuperSplat). /// A body with rescue, else or ensure clauses, in the method's body or in a `begin', or with a rescue modifier or a /// `retry', is one if its statements and clauses are (AreClausesScopeFree): $! is the runtime's, so the path that raises /// nothing saves and restores it without a scope, and the path that catches an exception makes the scope on demand where @@ -725,7 +739,7 @@ private bool IsLightFrameCandidate() { _parameters.LeadingMandatoryCount != _parameters.Mandatory.Length) { return false; } - if (HasKeywordParameters && (!LightKeywordsEnabled || KeywordsWithSplatLowering)) { + if (HasKeywordParameters && (!LightKeywordsEnabled || KeywordsWithSplatLowering && !LightKeywordRestEnabled)) { return false; } foreach (var parameter in _parameters.Mandatory) { @@ -906,8 +920,8 @@ private string WhyNotLightFrameCandidate() { if (HasKeywordParameters && !LightKeywordsEnabled) { return "keyword parameters (IR_LIGHT_KEYWORDS=0)"; } - if (HasKeywordParameters && KeywordsWithSplatLowering) { - return "keyword parameters with a rest or post parameter"; + if (HasKeywordParameters && KeywordsWithSplatLowering && !LightKeywordRestEnabled) { + return "keyword parameters with a rest or post parameter (IR_LIGHT_KEYWORD_REST=0)"; } var body = Body; if (body == null || HasHandling(body) && !LightRescueEnabled) { @@ -968,7 +982,7 @@ private bool HasKeywordParameters { } // Keywords beside a rest or post parameter: the general lowering takes every argument in one splat and binds the - // positionals out of it by hand (PrismAstBridge.LowerGeneralParameters), with helpers IsScopeFree does not take. + // positionals out of it by hand (PrismAstBridge.LowerGeneralParameters), with SplatParameterRead (see IsScopeFree). private bool KeywordsWithSplatLowering { get { return _parameters.Unsplat != null || _parameters.LeadingMandatoryCount != _parameters.Mandatory.Length; } } @@ -1167,6 +1181,15 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong return IsScopeFree(keywordRead.Keywords, blockLiterals, why) && (keywordRead.DefaultValue == null || IsScopeFree(keywordRead.DefaultValue, blockLiterals, why)); } + // the general lowering's reads of the one splat (PrismAstBridge.LowerGeneralParameters, IR_LIGHT_KEYWORD_REST): one + // runtime call each on the hidden local, which takes no scope but PopKeywordArguments, which reads the runtime's + // equality comparer for the empty hash of a call without keywords (LightFrameRewriter.ScopeOperandIndex); an optional + // parameter's default is evaluated in place when the splat has no argument left for it + var splatRead = node as SplatParameterRead; + if (splatRead != null && LightKeywordRestEnabled) { + return IsScopeFree(splatRead.Arguments, blockLiterals, why) && + (splatRead.DefaultValue == null || IsScopeFree(splatRead.DefaultValue, blockLiterals, why)); + } var keywordTest = node as KeywordArgumentsTest; if (keywordTest != null) { return IsScopeFree(keywordTest.Value, blockLiterals, why); @@ -1692,6 +1715,17 @@ private static int ScopeOperandIndex(MethodInfo/*!*/ method) { } // the default of the hidden keyword parameter, the call passed no keywords: the runtime's shared empty hash, or a // new one for a `**rest' to take over + // the keyword hash taken off the end of the general lowering's splat, or an empty one (IR_LIGHT_KEYWORD_REST) + if (LightKeywordRestEnabled && method == Methods.PopKeywordArguments) { + return 0; + } + // `f(**h)' (KeywordArgumentSplat): the copy of h the call passes, made with the runtime's equality comparer, in a + // one-or-zero element array for a splatted call, or the call's own keyword hash passed on by a parameterless + // `super' (IR_LIGHT_KEYWORD_SPLAT) + if (LightKeywordSplatEnabled && (method == Methods.SplatKeywordHash || method == Methods.SplatKeywordHashIfHash || + method == Methods.KeywordSplatArgument || method == Methods.PassOnKeywordRest)) { + return 0; + } if (LightKeywordsEnabled && (method == Methods.GetOmittedKeywordArguments || method == Methods.MakeOmittedKeywordArguments)) { return 0; } diff --git a/Util/bench/prelude-cost.rb b/Util/bench/prelude-cost.rb index 51c537bcc..04b282a73 100644 --- a/Util/bench/prelude-cost.rb +++ b/Util/bench/prelude-cost.rb @@ -316,6 +316,15 @@ def x_defc; defined?(C) ? 1 : 0; end def x_qual; self.class::C; end end +# keywords beside a rest (IR_LIGHT_KEYWORD_REST) and a hash passed on as keywords (IR_LIGHT_KEYWORD_SPLAT): kr_kw, the +# same keyword without the rest, was a light frame before; the others kept a scope +class Kr + def kw(a, k: 1) = a + k + def rest(*a, k: 1) = a.size + k + def inner(*a, **o) = a.size + o.size + def pass(*a, **o) = inner(*a, **o) +end + def cpu File.read("/proc/thread-self/schedstat").to_i / 1e9 rescue SystemCallError @@ -469,3 +478,11 @@ def t(name, n) t("x_cv", N) { |n| i = 0; s = 0; while i < n; s += lx.x_cv; i += 1; end; s } t("x_defc", N) { |n| i = 0; s = 0; while i < n; s += lx.x_defc; i += 1; end; s } t("x_qual", N) { |n| i = 0; s = 0; while i < n; s += lx.x_qual; i += 1; end; s } + +# keywords beside a rest, and passed on +kr = Kr.new +kl = "ab" +t("kr_kw", N) { |n| i = 0; s = 0; while i < n; s += kr.kw(i, k: 2); i += 1; end; s } +t("kr_rest", N) { |n| i = 0; s = 0; while i < n; s += kr.rest(i, k: 2); i += 1; end; s } +t("kr_pass", N) { |n| i = 0; s = 0; while i < n; s += kr.pass(i, k: 2); i += 1; end; s } +t("kr_lines", N) { |n| i = 0; s = 0; while i < n; kl.each_line(chomp: true) { |l| s += l.size }; i += 1; end; s } diff --git a/Util/keyword-rest-light-matrix.rb b/Util/keyword-rest-light-matrix.rb new file mode 100644 index 000000000..f3f5eec1b --- /dev/null +++ b/Util/keyword-rest-light-matrix.rb @@ -0,0 +1,200 @@ +# Differential matrix for methods with keyword parameters beside a rest or post parameter that run without a scope (a +# light frame, MethodDefinition.IsLightFrameCandidate, IR_LIGHT_KEYWORD_REST). Run it under CRuby and under ./ir.sh with +# the shape on and off, and diff: +# +# ruby Util/keyword-rest-light-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/keyword-rest-light-matrix.rb > /tmp/on.txt 2>&1 +# IR_LIGHT_KEYWORD_REST=0 ./ir.sh Util/keyword-rest-light-matrix.rb > /tmp/off.txt 2>&1 +# IR_LIGHT_FRAMES=0 ./ir.sh Util/keyword-rest-light-matrix.rb > /tmp/noframes.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt && diff /tmp/mri.txt /tmp/noframes.txt +# +# Such a signature is lowered to one splat, `def m(*?args?)', and a prologue that takes the keyword hash off its end +# and binds the positionals out of it by hand (PrismAstBridge.LowerGeneralParameters): RubyOps.PopKeywordArguments, +# CheckSplatArity, ShiftSplatArgument, ShiftOptionalSplatArgument, ShiftRestSplatArguments. The probes cover the +# signatures (a rest, required and optional positionals before it, a post parameter, **rest, **nil, an anonymous +# rest), the binding (nothing, too few, a positional Hash, keywords, unknown ones, a splat, the caller's Array left +# alone), the defaults (an earlier parameter, a call), what reads the frame (binding, local_variables, block_given?, +# yield, zsuper, raise and its backtrace, caller), the other ways in (send, public_send, Method#call, to_proc), the +# method changing under a bound site, recursion, TracePoint, and prelude methods of this shape (String#each_line, +# String#lines, Data#initialize, Array#sample, Kernel#warn), and a call that passes `**h' on (IR_LIGHT_KEYWORD_SPLAT, +# RubyOps.KeywordSplatArgument and PassOnKeywordRest: nil, an empty Hash, to_hash, the caller's Hash not aliased). +# +# IR_LIGHT_FRAMES=why ./ir.sh Util/keyword-rest-light-matrix.rb 2>&1 >/dev/null | grep -a '^\[light\]' +# +# says which of the methods below are light frames. + +N = 3000 + +def t(label) + print label.ljust(52), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def err + yield +rescue Exception => e + "#{e.class}: #{e.message[0, 80]}" +end + +# ---------------------------------------------------------------- 1. signatures and binding + +def rest_kw(*a, k: 1); [a, k]; end +def req_rest_kw(x, *r, k:); [x, r, k]; end +def opt_rest_kw(x, y = 2, *r, k: 1); [x, y, r, k]; end +def post_kw(x, *r, z, k: 0); [x, r, z, k]; end +def all_kw(a, b = 5, *c, d, e: 2, **o); [a, b, c, d, e, o]; end +def rest_kwrest(*a, **o); [a, o]; end +def rest_nokw(x, *r, **nil); [x, r]; end +def anon_rest(*, k: 1); k; end +def post_only(x, *, z, k: 0); [x, z, k]; end + +t('rest_kw()') { rest_kw } +t('rest_kw(1, 2)') { rest_kw(1, 2) } +t('rest_kw(1, k: 3)') { rest_kw(1, k: 3) } +t('rest_kw({k: 3}) positional Hash') { rest_kw({k: 3}) } +t('rest_kw(**{})') { rest_kw(**{}) } +t('rest_kw(j: 1) unknown') { err { rest_kw(j: 1) } } +t('req_rest_kw missing keyword') { err { req_rest_kw(1) } } +t('req_rest_kw too few') { err { req_rest_kw(k: 1) } } +t('req_rest_kw(1, 2, 3, k: 4)') { req_rest_kw(1, 2, 3, k: 4) } +t('opt_rest_kw 1 / 2 / 3 positionals') { |i| opt_rest_kw(*[1, 2, 3][0, i % 3 + 1]) } +t('opt_rest_kw with k') { |i| opt_rest_kw(*[1, 2, 3][0, i % 3 + 1], k: i % 2) } +t('post_kw(1, 2)') { post_kw(1, 2) } +t('post_kw(1, 2, 3, 4, k: 5)') { post_kw(1, 2, 3, 4, k: 5) } +t('post_kw too few') { err { post_kw(1) } } +t('all_kw') { |i| err { all_kw(*(1..(i % 5)).to_a, e: 7, z: 8) } } +t('rest_kwrest') { |i| rest_kwrest(*[1, 2][0, i % 3], **(i.even? ? {a: 1} : {})) } +t('rest_kwrest string key') { rest_kwrest(1, **{"s" => 2}) } +t('rest_nokw') { rest_nokw(1, 2) } +t('rest_nokw with keywords') { err { rest_nokw(1, k: 2) } } +t('rest_nokw with a positional Hash') { rest_nokw(1, {k: 2}) } +t('anon_rest') { |i| anon_rest(1, 2, k: i % 2) } +t('post_only') { post_only(1, 2, 3, k: 4) } +arr = [1, 2, 3] +t('splat leaves the caller\'s Array') { |i| [req_rest_kw(*arr, k: i % 2), post_kw(*arr), arr] } +h = {k: 9} +t('double splat leaves the caller\'s Hash') { [rest_kw(1, **h), rest_kwrest(**h), h] } +t('nil and false') { [rest_kw(nil, k: nil), post_kw(nil, false)] } + +# ---------------------------------------------------------------- 2. defaults + +def counter; @c = (@c || 0) + 1; end +def default_reads(x, y = x * 2, *r, k: y + 1); [x, y, r, k]; end +def default_calls(x, *r, k: counter); k.is_a?(Integer); end +t('defaults read earlier parameters') { |i| default_reads(*[1, 2][0, i % 2 + 1]) } +t('default calls a method') { default_calls(1) } + +# ---------------------------------------------------------------- 3. what the frame still does + +def f_binding(x, *r, k: 1); binding.local_variable_get(:r) + [binding.local_variable_get(:k)]; end +def f_locals(x, *r, z, k: 1); local_variables.sort; end +def f_block(*a, k: 1); block_given? ? yield(a, k) : :none; end +def f_raise(*a, k: 1); raise ArgumentError, "k=" + k.to_s; end +def f_caller(*a, k: 1); caller(0, 1)[0][/in .*/]; end +def f_recurse(n, *r, k: 0); n == 0 ? k : f_recurse(n - 1, *r, k: k + 1); end +def f_in_block(*a, k: 1); a.map { |v| v + k }; end +t('binding') { f_binding(1, 2, 3, k: 4) } +t('local_variables') { f_locals(1, 2) } +t('block_given? and yield') { |i| i.even? ? f_block(1, k: 2) : f_block(1, k: 2) { |a, k| [a, k] } } +t('raise') { err { f_raise(1) } } +t('raise backtrace label') { begin; f_raise; rescue => e; e.backtrace[0][/in .*/]; end } +t('caller') { f_caller } +t('recursion') { f_recurse(20, 1, 2) } +t('a block reads the parameters') { f_in_block(1, 2, k: 10) } + +class ZBase + def m(*a, k: 0); [:base, a, k]; end + def p2(x, *r, z, k: 0); [:base, x, r, z, k]; end +end +class ZSub < ZBase + def m(*a, k: 0); [:sub, super]; end + def p2(x, *r, z, k: 0); r = [:changed]; [:sub, super]; end + def explicit(*a, k: 0); [:explicit, method(:m).super_method.call(*a, k: k)]; end +end +t('zsuper with a rest and keywords') { |i| ZSub.new.m(*[1, 2][0, i % 3], k: i % 2) } +t('zsuper after reassigning the rest') { ZSub.new.p2(1, 2, 3, k: 4) } +t('super_method') { ZSub.new.explicit(1, k: 2) } + +# ---------------------------------------------------------------- 4. other ways in + +t('send') { send(:req_rest_kw, 1, 2, k: 3) } +PS = Object.new +def PS.g(*a, k: 1) = [a, k] +t('public_send') { PS.public_send(:g, 1, k: 2) } +t('Method#call') { method(:opt_rest_kw).call(1, k: 5) } +t('to_proc') { [[1, 2]].map(&method(:post_kw)) } +t('arity and parameters') { [method(:rest_kw).arity, method(:req_rest_kw).arity, method(:post_kw).parameters] } + +class Redef + def r(*a, k: 1); [:first, a, k]; end +end +rd = Redef.new +t('redefined after the site is bound') do |i| + Redef.class_eval { remove_method :r; def r(*a, k: 1); [:second, a, k]; end } if i == 1500 + rd.r(i % 2, k: 0) +end + +calls = [] +tp = TracePoint.new(:call) { |tp| calls << tp.method_id if tp.method_id == :rest_kw } +t('TracePoint :call') do |i| + tp.enable if i == 1000 + r = rest_kw(1, k: 2) + tp.disable if i == 2000 + r +end +puts "traced #{calls.size} calls" + +# ---------------------------------------------------------------- 5. passing `**h' on (IR_LIGHT_KEYWORD_SPLAT) + +def kw_inner(*a, **o); o[:mutated] = true unless o.empty?; [a, o]; end +def pass_opts(*args, **opts); kw_inner(*args, **opts); end +def pass_only(**opts); kw_inner(**opts); end +def pass_any(x, h); kw_inner(x, **h); end +class ToHash; def to_hash = {th: 1}; end +class PassBase; def pk(a, **rest) = [:base, a, rest]; end +class PassSub < PassBase + def pk(a, **rest); [:sub, super]; end + def pk2(a, **rest); rest[:extra] = 1; [:sub2, method(:pk).super_method.call(a, **rest)]; end +end +held = {k: 1} +t('**opts passed on') { |i| pass_opts(*[1, 2][0, i % 3], **(i.even? ? {k: i % 2} : {})) } +t('**opts alone') { |i| pass_only(**(i.even? ? {} : {a: 1})) } +t('the callee does not alias the hash') { [pass_any(1, held), held] } +t('**nil') { pass_any(1, nil) } +t('**{}') { pass_any(1, {}) } +t('**obj with to_hash') { pass_any(1, ToHash.new) } +t('**obj without to_hash') { |i| err { pass_any(1, [1, :x, Object][i % 3]) } } +t('**string keys') { pass_any(1, {"s" => 1}) } +t('zsuper passes **rest on') { |i| PassSub.new.pk(1, **(i.even? ? {} : {k: 2})) } +t('**rest changed, then passed on') { PassSub.new.pk2(1, k: 2) } + +# ---------------------------------------------------------------- 6. prelude methods of this shape + +D = Data.define(:x, :y) +t('String#each_line(chomp:)') { "a\nb\n".each_line(chomp: true).to_a } +t('String#lines') { |i| "a\nb\n".lines(chomp: i.even?) } +t('String#each_line(sep, chomp:)') { "a,b,".each_line(",", chomp: true).to_a } +t('Data#initialize') { |i| i.even? ? D.new(1, 2) : D.new(x: 1, y: 2) } +t('Data#initialize missing') { err { D.new(1) } } +t('Array#sample(random:)') { [1, 2, 3].sample(3, random: Random.new(1)).sort } +SEEN = [] +WARN_TO = Object.new +def WARN_TO.write(*s); SEEN.concat(s); s.sum(&:size); end +t('Kernel#warn') do + saved, $stderr = $stderr, WARN_TO + warn "w1", "w2" + warn "w3", category: :experimental + $stderr = saved + out = SEEN.join + SEEN.clear + out +end From 2e9521f0180e774a57a3e7669957c5df060032ce Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:05:08 +0000 Subject: [PATCH 030/439] JIT: a method body's loop sees a folded constant reassigned at its safe point A typed method body whose `while` folded a constant, and had nothing else that may deopt (a Float counter; an Int one's overflow check is a deopt), went on with the old value after another thread reassigned the constant, until the call returned. CRuby's next read sees the new value. The reassignment moves the code epoch and the loop's safe point saw it, but MethodLoopSafePointSlow deopts only a body that may deopt. ResolveConstant now notes a constant folded in or after a loop of the method body's own, and TryCompile makes such a body one that may deopt (replacing perf/deadconst's rule for a left-out arm, which it covers); one with an effect is declined, as any loop body that can deopt with an effect is. A constant folded after a call of a bound callee with a loop declines the body. Before deopting, the safe point looks the body's folded constants up again (JitLoopGuard.ConstantsStillHold, the entry's revalidation for a running loop), so a reassignment of another constant lets the loop go on. Checked: Util/deadconst-matrix.rb rows 26-29 (a folded step and a folded bound reassigned by another thread: :limit before, CRuby's :seen now; the same with an effect; another constant reassigned during the loop) print CRuby's output with the JIT on, off, without JIT calls and with IR_JIT_DEADCONST=0; jit, jit-calls, jit-const, block-loop, osr-array and dmeth-jit matrices unchanged in all modes; all fourteen AWFY benchmarks make the same JIT and OSR decisions; census unchanged; Jit*/Loop* IronRuby.Tests pass. Instructions a call (callgrind): ordinary loops 1.000-1.004, the Float loop that folds a constant 1.048 (its entry's deopt handler, once a call). The ledger also records what the loop tier lacks for Richards' Scheduler#schedule: a class profile for receivers in loops, attribute reads on a local a long `while` writes, and a general call followed by a store that cannot deopt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5NtGd2eCVJ7fCeWbG --- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 6 ++ Src/Ruby/Runtime/Jit/JitCompiler.cs | 29 ++++---- Src/Ruby/Runtime/Jit/JitRuntime.cs | 28 +++++++ Src/Ruby/Runtime/Jit/JitStub.cs | 1 + Util/bench/deadconst-shapes.rb | 26 +++++++ Util/deadconst-matrix.rb | 81 +++++++++++++++++++++ Util/perf/LEDGER.md | 65 ++++++++++++++++- 7 files changed, 221 insertions(+), 15 deletions(-) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 74fb7bf24..814ca49e6 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -173,6 +173,12 @@ private object ResolveConstant(ConstantVariable/*!*/ node) { _resolvedConstantOwner = owner; (_foldedConstants ?? (_foldedConstants = new List())).Add(new JitFoldedConstant(scope, node, value, owner)); _usesConstants = true; + // a method body's loop runs on past the entry's revalidation (TryCompile); an outlined loop's copy hands + // itself back on any reassignment + if (_loop == null) { + if (_hasLoop) { _foldedInLoop = true; } + if (_calleeLoop) { _foldedAfterCalleeLoop = true; } + } return value; } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index c1cca3ad4..9c509cbfc 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -622,15 +622,16 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ return null; } - // An arm left out under a constant is left out for as long as the entry finds the constant unchanged. A - // loop runs on past the entry: one of the body's own has to deopt at its safe point when the constant is - // reassigned (MethodLoopSafePointSlow, which a body that may not deopt goes on from with what it was - // compiled with), so the body is one that can, which only a pure body may be (below). A callee's loop - // deopts by the callee's own rule, which is not this body's, so a body that calls one stays generic. - if (c._droppedArm) { - if (c._calleeLoop) { return Declined("a statement left out under a constant, and a callee with a loop"); } - if (c._hasLoop) { c._canDeopt = true; } - } + // A folded constant - a value, or an arm left out under one - holds for as long as the entry finds it + // unchanged. A loop runs on past the entry, and CRuby's next read sees a reassignment another thread + // made meanwhile: a constant folded in a loop of the body's own, or after one, is looked up again at the + // loop's safe point when the code epoch moves (MethodLoopSafePointSlow), and if it changed the body + // deopts there. So the body is one that may deopt, which only a pure body may be (below: one with an + // effect is declined, as a loop that can deopt in a body with an effect always is). A callee's loop + // looks only at the callee's constants, so a body that folds one after calling such a callee stays + // generic. (Gap 29: such a body that had nothing else to deopt for went on with the old value.) + if (c._foldedAfterCalleeLoop) { return Declined("a constant folded after a call of a callee with a loop"); } + if (c._foldedInLoop) { c._canDeopt = true; } // Writes held back that the body cannot keep (JitCompiler.Sink.cs): compile it storing them where they are. if (c._sunk != null && c._sinkObstacle != null) { @@ -1628,8 +1629,7 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { /// is not emitted at all, and neither is the test. The constant is folded as any other read of it is /// (ResolveConstant), so the entry finds out that it changed (JitStub.RevalidateConstants) and the arm runs /// again from the next call; an outlined loop hands itself back at its next safe point when it is reassigned - /// (RubyContext.ConstantReassigned), and a method body with a loop is made to deopt there (TryCompile: - /// _droppedArm). False when the node is not such a guard, or the value is one a non-main Ractor may not + /// (RubyContext.ConstantReassigned), and a method body's loop deopts there (TryCompile: _foldedInLoop). False when the node is not such a guard, or the value is one a non-main Ractor may not /// read, which EmitConstant checks where it is read. /// private bool TryEmitConstantGuarded(RExpr/*!*/ node, out MSA.Expression result, out JT type) { @@ -1640,7 +1640,6 @@ private bool TryEmitConstantGuarded(RExpr/*!*/ node, out MSA.Expression result, if (!JitRuntime.DeadConstants || !ConstantGuard(node, out guard, out whenTrue, out whenFalse)) { return false; } object value = ResolveConstant(guard); if (!RactorIsolation.IsTriviallyShareable(value)) { return false; } - _droppedArm = true; var live = RubyOps.IsTrue(value) ? whenTrue : whenFalse; if (live == null || live.Count == 0) { type = JT.Obj; @@ -1651,8 +1650,10 @@ private bool TryEmitConstantGuarded(RExpr/*!*/ node, out MSA.Expression result, return true; } - // An arm was left out under a constant (TryEmitConstantGuarded). - private bool _droppedArm; + // A constant was folded in or after a loop of the body's own (ResolveConstant), or after a call of a callee with + // one: what TryCompile makes the body deopt for, or declines. + private bool _foldedInLoop; + private bool _foldedAfterCalleeLoop; /// /// `if C ... [else ...] end' or `unless C ... [else ...] end', without an elsif, whose condition is a constant the diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index ff2b4cc60..b34ece775 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -353,6 +353,12 @@ public static long MethodLoopSafePointSlow(JitLoopGuard/*!*/ guard, StrongBox + /// The method version is the one the code was compiled under, and each constant it folded resolves as it did + /// (JitFoldedConstant.StillHolds): what moved the constant version was nothing the code folded, and the version + /// read before the lookups is recorded as current. As JitStub.RevalidateConstants: a change between the read + /// and the store has moved the version past the one stored, so the next safe point looks again. + /// + internal bool ConstantsStillHold() { + var context = ConstantsOf; + var folded = Folded; + if (context == null || folded == null || RubyModule.GlobalMethodVersion != Version) { return false; } + int version = System.Threading.Volatile.Read(ref context.ConstantAccessVersion); + foreach (var constant in folded) { + if (!constant.StillHolds(context)) { return false; } + } + if (context.IsAutoloadInProgress) { return false; } + System.Threading.Volatile.Write(ref ConstantVersion, version); + return true; + } + /// A method table or a constant the code was built on has changed since. internal bool Stale { get { diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 0cd57e185..9f8a4172c 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -1878,6 +1878,7 @@ internal static bool IsLeafMethodOfSomeClass(RubyContext/*!*/ context, string/*! /// private JitCode Named(JitCode code, long epoch, int version, int constantVersion) { if (code != null) { + code.LoopGuard.Folded = code.FoldedConstants; code.LoopGuard.Set(epoch, version, code.UsesConstants ? _context : null, constantVersion); } if (code != null && _frameName != null) { diff --git a/Util/bench/deadconst-shapes.rb b/Util/bench/deadconst-shapes.rb index e62fd69eb..2b082051e 100644 --- a/Util/bench/deadconst-shapes.rb +++ b/Util/bench/deadconst-shapes.rb @@ -11,6 +11,7 @@ TRACING = false DEBUG_LEVEL = nil module Conf; VERBOSE = false; end +FSTEP = 0.5 class Stepper attr_reader :traced @@ -47,6 +48,29 @@ def sum_dead(n) s end + # a Float loop folding a constant: nothing else in it may deopt, so it is the kind of body that is now made one that + # may (at its loop's safe point, when a constant is reassigned: gap 29) + def fsum_const(n) + x = 0.0 + i = 0.0 + while i < n + x += FSTEP + i += 1.0 + end + x + end + + # control: the step a parameter + def fsum_plain(n, step) + x = 0.0 + i = 0.0 + while i < n + x += step + i += 1.0 + end + x + end + # control def sum_plain(n) i = 0 @@ -83,6 +107,8 @@ def t(name, n) # a method with a short loop, called hot: the method JIT's (per call: 8 iterations) t("mloop_dead", N / 4) { |n| i = 0; s = 0; while i < n; s += o.sum_dead(8); i += 1; end; s + o.traced } t("mloop_plain", N / 4) { |n| i = 0; s = 0; while i < n; s += o.sum_plain(8); i += 1; end; s + o.traced } +t("mfloop_const", N / 4) { |n| i = 0; s = 0.0; while i < n; s += o.fsum_const(8.0); i += 1; end; s } +t("mfloop_plain", N / 4) { |n| i = 0; s = 0.0; while i < n; s += o.fsum_plain(8.0, 0.5); i += 1; end; s } # a long loop run once: the loop tier's (OSR); its sum stays an Integer the loop's copy keeps as an int t("loop_dead", N * 4) { |n| i = 0; s = 0; while i < n; trace(i) if TRACING; s += i & 7; i += 1; end; s } t("loop_plain", N * 4) { |n| i = 0; s = 0; while i < n; s += i & 7; i += 1; end; s } diff --git a/Util/deadconst-matrix.rb b/Util/deadconst-matrix.rb index 7ea2ebc49..e66fe0319 100644 --- a/Util/deadconst-matrix.rb +++ b/Util/deadconst-matrix.rb @@ -275,4 +275,85 @@ def spin(n) t25.join puts "25. a method's while that cannot deopt otherwise, reassigned by another thread: #{[w25, r25].inspect}" +# ---------------------------------------------------------------- 3. a folded value in a running loop (gap 29) + +# Not a guard: the constant is a value the loop computes with. A method's typed body folds it, and its loop's safe +# point sees the reassignment move the code epoch; a body with nothing else that may deopt went on with the old +# value until it returned (CRuby's next read answers the new one). +STEP26 = 1.0 +class P26 < Probe + def spin(n) + x = 0.0 + while x < n + x += STEP26 + end + x > n ? :seen : :limit + end +end +o26 = P26.new +w26 = nil +WARM.times { w26 = o26.spin(5.0) } +t26 = Thread.new { sleep 0.1; reassign(Object, :STEP26, 1.0e12) } +r26 = o26.spin(2.0e9) +t26.join +puts "26. a folded step in a method's while, reassigned by another thread: #{[w26, r26].inspect}" + +LIM27 = 2.0e9 +class P27 < Probe + def spin(k) + x = 0.0 + while x < LIM27 + x += k + end + x < 2.0e9 ? :seen : :limit + end +end +o27 = P27.new +w27 = nil +WARM.times { w27 = o27.spin(1.0e9) } +t27 = Thread.new { sleep 0.1; reassign(Object, :LIM27, 0.0) } +r27 = o27.spin(1.0) +t27.join +puts "27. a folded bound of a method's while, reassigned by another thread: #{[w27, r27].inspect}" + +# The same with an effect in the loop (a Float instance variable written): a body that cannot be restarted. +STEP28 = 1.0 +class P28 < Probe + def spin(n) + @acc = 0.0 + x = 0.0 + while x < n + @acc += 0.5 + x += STEP28 + end + x > n ? :seen : :limit + end +end +o28 = P28.new +w28 = nil +WARM.times { w28 = o28.spin(5.0) } +t28 = Thread.new { sleep 0.1; reassign(Object, :STEP28, 1.0e12) } +r28 = o28.spin(2.0e9) +t28.join +puts "28. a folded step in a while with an effect, reassigned by another thread: #{[w28, r28].inspect}" + +# Another constant reassigned again and again while the loop runs: the answer is the folded one's. +STEP29 = 1.0 +OTHER29 = 0 +class P29 < Probe + def spin(n) + x = 0.0 + while x < n + x += STEP29 + end + x + end +end +o29 = P29.new +WARM.times { o29.spin(5.0) } +t29 = Thread.new { 200.times { |k29| reassign(Object, :OTHER29, k29) } } +r29 = o29.spin(2.0e7) +t29.join +puts "29. another constant reassigned while a folded loop runs: #{r29.inspect}" + puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..185a6f592 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -607,7 +607,24 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has out first what compiles once the screen lets it through. Done in perf/deadconst (see Landed): the screen lets `schedule` through and nothing compiles - it is called once per iteration, so it is the loop tier's, which still stops at `[osr] emitter: call: is_task_holding_or_waiting/0`; the next step for it - is calls on another receiver in an outlined loop. And two that the rounds + is calls on another receiver in an outlined loop. What that takes, found in perf/deadconst2 by taking + the obstacles off a copy of `schedule` one at a time (`IR_OSR_VERBOSE=1`): first the predicate + `is_task_holding_or_waiting` (`@task_holding || (!@packet_pending && @task_waiting)`, a pure method the + method JIT would inline, but the loop tier's inliner has no profile of the receiver's class); with + the loop's receiver in a local `t` it still says `call: is_task_holding_or_waiting/0`, and with the + predicate written out on attribute readers `call: th_p/0` - an attribute read on a local the `while` + writes is refused there on purpose (round eight: CD's `Node#successor` walks a few links per entry and + paid the copy's entry each time; only a core iterator's loop takes it). Behind those, `run_task`, which + no outlined loop can call: it needs a general call made with the loop's scope (visibility and + refinements as the source's, gap 1's round seven), and since an outlined loop deopts to the top of the + iteration from its snapshot, nothing after the call in the iteration may deopt - `@current_task = t` + is an instance variable write on self, which deopts for a frozen self. So three pieces: a class + profile for receivers in loops (the live value at entry is one, as `_peekLocal` uses), attribute reads + on a written local in a `while` that is entered once and runs long (the OSR counter knows it, the + entry does not), and a general call from a loop with a store after it that cannot deopt. The prize is + the loop's own dispatch (one predicate call, three attribute reads, two instance variable writes an + iteration), not `run_task`, which stays a call: at most `schedule`'s 7.5% self time, likely half. + Not attempted. And two that the rounds above keep running into: held-back writes that reach through a bound callee (a caller whose only effects are its callee's writes to the same self: `read_required_char` -> `read_char` -> `read`, `set_nesting_level` -> `set_is_root`), and attribute writes @@ -1310,6 +1327,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has overflow check gives most loops one). perf/deadconst makes such a body deopt where it left an arm out; for a folded value in general the same (`_canDeopt` for a pure body with a loop that folded a constant) is untried, and an impure body would have to be declined for it. + Done in perf/deadconst2 (see Landed): such a body deopts at its loop's safe point when a constant + it folded was reassigned, and looks its constants up again there (going on) when it was another. + What is left of this gap's running-loop faults: a nearer constant appearing (rminor's case above), + and a method body with an effect that only a method redefinition makes stale, which goes on with + the old method until it returns (`MethodLoopSafePointSlow`'s impure branch). 30. **`Binding#local_variable_get`, `_set`, `_defined?` and `local_variables` are an `eval` of source text each** (the prelude, `class Binding`): 436 us for a set against 0.1 on CRuby. `ERB#result_with_hash` sets one per key (237 times CRuby), irb sets `_` @@ -1450,6 +1472,47 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/deadconst2 (/perf-step, 2026-11-26, on claude/happy-gauss-95wm2j 2f8c31c) - a typed method body + whose loop folded a constant sees it reassigned at the loop's next safe point (gap 29)** - not gated. + The fault perf/deadconst found: a method body's `while` that folded a constant, with nothing else that + may deopt (a Float counter: an Int one's overflow check is a deopt), went on with the old value after + another thread reassigned the constant, until the call returned; CRuby's next read sees the new one. + The reassignment did move the code epoch (`RubyContext.ConstantReassigned`) and the safe point saw it, + but `MethodLoopSafePointSlow` deopts only a body that may (`JitLoopGuard.MayDeopt`). Now + `ResolveConstant` notes a constant folded in or after a loop of the method body's own, and `TryCompile` + makes such a body one that may deopt (the rule perf/deadconst had for a left-out arm, which this + replaces); one with an effect is declined, as a loop body that can deopt with an effect always is. One + that folds a constant after calling a bound callee with a loop is declined (the callee's safe point + looks at its own constants only). And the safe point, before deopting, looks the body's folded + constants up again (`JitLoopGuard.ConstantsStillHold`, the entry's `RevalidateConstants` for a running + loop: the method version unchanged, each constant the same object in the same module, the version read + before the lookups stored after): a reassignment of another constant lets the loop go on, where before + a body that could deopt deopted for any reassignment anywhere. rminor's trouble (a name cannot tell + which new constant concerns a fold) does not arise: a reassignment moves the epoch already, and what + is compared is the folded constants' own lookups. + Census (Src/StdLib + AWFY): 0 methods changed, as it must (it compiles no constant). All fourteen AWFY + benchmarks traced (3 x 1, `IR_JIT_VERBOSE` and `IR_OSR_VERBOSE`): the same methods specialized and + declined and the same loops specialized and refused on both builds. Richards `census -c` 0 differ. + Instructions a call (`Util/perf/callgrind/count.sh`, `ab.rb -i -n 20000`, base / new, + `Util/bench/deadconst-shapes.rb`): `mfloop_const` (a method's 8-iteration Float loop adding a constant, + the kind this makes deopt-capable) 1575.0 / 1650.8 = 1.048 - the entry's deopt handler and entry count, + once a call, not per iteration; its control `mfloop_plain` (the step a parameter) 1.002; `mloop_plain` + (an Int loop) 1.004, `mloop_dead` 1.000, `m_dead` 1.000, `m_plain` 1.000, `loop_dead` and `loop_plain` + (OSR) 1.001. Ordinary loops count the same. + Checked: `Util/deadconst-matrix.rb` gains rows 26-29 - a folded step and a folded bound of a method's + Float `while` reassigned by another thread (both `:limit` on the unchanged build, CRuby's `:seen` now; + the safe point deopts), the same with an instance variable written in the loop (declined on both + builds), and another constant reassigned 200 times while a folded loop runs (the right sum; no deopt in + the trace). The matrix prints CRuby's output on the new build with the JIT on, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` and `IR_JIT_DEADCONST=0`; jit, jit-calls, jit-const, block-loop, osr-array and dmeth-jit + matrices print CRuby's on both builds in all four modes, inline-matrix the baseline's (its documented + `tree_int_key`). IronRuby.Tests Jit* and Loop* (21) pass. + For the gate: a pure body with a loop that folds a constant now has a deopt-capable entry (+76 + instructions a call on the Float shape); a caller that binds such a body treats it as one that can + deopt (`code.Deopts`), which could decline a caller with an effect before the call - none of the + fourteen benchmarks has one. Look at the order in `ConstantsStillHold` and at `Folded` being set + before `LoopGuard.Set` publishes the epoch. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 3cabf5734b9d6f36f2efb9c926988b56f14ebf10 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:05:35 +0000 Subject: [PATCH 031/439] Ledger: perf/lexical2 landed (census only, not gated) Gap 9 names IR_LIGHT_KEYWORD_REST, IR_LIGHT_KEYWORD_SPLAT and their matrix; the Landed entry has why this census line was chosen, the census with each switch alone and both, the instruction counts (0.93 on the shapes, below perf-frame's 15% bar: the splat lowering, not the scope, is what such a call costs, and is the next idea), the modes checked, and the two class-variable fixes. perf/lexical's entry points at them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 64 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..6c0885d2a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -800,10 +800,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has see Landed, perf/lightre: one passed to `gsub`, `=~`, `split`, `when` and the like stays out); nor a class variable, a `defined?` of a constant or a constant qualified by an expression (`@@x`, `defined?(A::B)`, `self.class::C`; `IR_LIGHT_LEXICAL=0`, see Landed, perf/lexical); + nor keywords beside a rest or post parameter (`def warn(*msgs, uplevel: nil)`; + `IR_LIGHT_KEYWORD_REST=0`) nor a hash passed on as keywords (`g(*a, **o)`; + `IR_LIGHT_KEYWORD_SPLAT=0`, both see Landed, perf/lexical2); Util/block-given-matrix.rb, Util/light-rest-matrix.rb, Util/block-pass-matrix.rb, Util/splat-pass-matrix.rb, Util/interpolation-matrix.rb, Util/hash-literal-matrix.rb, - Util/masgn-matrix.rb, Util/regex-light-matrix.rb and Util/lexical-light-matrix.rb are their - matrices. + Util/masgn-matrix.rb, Util/regex-light-matrix.rb, Util/lexical-light-matrix.rb and + Util/keyword-rest-light-matrix.rb are their matrices. What the census names next (2026-11-19 after perf/hashlit, 28,335 methods, 6,542 of them not light). By its first table: keyword parameters 1,257 (37 of them the prelude's, none AWFY's), `rescue`/`ensure` 478, 185 candidates that still need their @@ -1450,6 +1453,61 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lexical2 (/perf-step, 2026-11-26, on 2f8c31c) - keywords beside a rest or post + parameter, and a hash passed on as keywords, in light frames (`IR_LIGHT_KEYWORD_REST`, + `IR_LIGHT_KEYWORD_SPLAT`, gap 9)** - census only, not gated. Chosen over the other "not a + light frame" lines of the census of 2f8c31c because it is the one the prelude has: 24 of its + 101 methods (`String#each_line`, `String#lines`, `IO#initialize`, `File#initialize`, + `Data#initialize`, `Kernel#open`, `IO.readlines`, `Enumerator.produce`), against 2 of the 71 + LambdaDefinition methods (whose Proc makes the scope anyway) and 4 `defined?` of anything else; + "body needs its scope after the rewrite" (104) is many causes. perf/lkw had left the line out + without an attempt ("the general lowering binds the positionals out of one splat with helpers + `IsScopeFree` does not take"). + - The lowering is `def m(*?args?)` and a prologue of `SplatParameterRead`s + (PrismAstBridge.LowerGeneralParameters): one runtime call each on the hidden local, none + taking the scope but `PopKeywordArguments`, which reads the runtime's equality comparer for + the empty hash of a call without keywords. The rest Array is bound by the RubyMethodInfo in + either frame, so the prologue empties the same call-owned Array (the matrix checks that the + caller's splatted Array and double-splatted Hash are left alone). A signature a + parameterless `super` cannot rebuild by name (an anonymous rest with posts) keeps its copy + of the splat (`SuperSplat`) and its scope. + - That alone: +58. 30 more then passed the filter and failed in the rewriter because they pass + `**opts` on - the shape perf/lkw also named ("a body that passes `**opts` on (52)") and that + every light-frame candidate had: `KeywordArgumentSplat`'s helpers (`SplatKeywordHash`, + `SplatKeywordHashIfHash`, `KeywordSplatArgument`, `PassOnKeywordRest`) read only the + runtime's equality comparer. `IR_LIGHT_KEYWORD_SPLAT` alone +70; both +158. `a: 1, **h` + (KeywordSplatMerge, 19 methods) is still refused by `IsScopeFree`. + - Census (Src/StdLib + AWFY, 28,376 methods): light frames 26,535 -> 26,693 (93.5% -> 94.1%), + 158 moved up, none down; JIT compiles / maybe / never unchanged (3,296 / 2,923 / 22,157); + "body needs its scope after the rewrite" 104 -> 34. No AWFY method moved. `-c` on a + Richards trace 0 differ. + - Instructions a call (`Util/perf/callgrind/count.sh` through `ab.rb -i -r 1 -n 20000`, both + switches off -> on, new shapes in `prelude-cost.rb`): `kr_rest` (`def rest(*a, k: 1)`) + 5,720 -> 5,325 (0.93), `kr_pass` (`pass(*a, **o) = inner(*a, **o)`) 12,272 -> 11,359 + (0.93), `kr_lines` (`"ab".each_line(chomp: true) { }`) 17,670 -> 17,436 (0.99); the + controls `kr_kw` (`def kw(a, k: 1)`, light before) and `x_const` 1.00. Below perf-frame's + 15% bar for a shape: the scope was not most of what these calls cost. `kr_rest` is still + 3.4 times `kr_kw`; the next step for this shape is the lowering itself - binding the + positionals in the calling convention, as `def m(a, b = 1, k: 2)` already is + (`KeywordsAfterOptionals`), instead of out of one splat - not the frame. Not timed. + - `Util/keyword-rest-light-matrix.rb` (new: the signatures, binding errors, positional Hash, + `**nil`, defaults, binding, local_variables, block_given?, zsuper with a rest and with + `**rest`, super_method, send, Method#call, to_proc, arity and parameters, redefinition, + TracePoint, `**h` with nil, `{}`, to_hash, non-Hashes, the caller's Hash not aliased, and + String#each_line, #lines, Data#initialize, Array#sample, Kernel#warn) prints CRuby 4.0's + output on the unchanged build, and on the change by default, with either switch off, with + `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and R2R; the keyword, lexical, + jit, jit-calls, block-given, light-rest, splat-pass and hash-literal matrices agree with the + baseline and CRuby. IronRuby.Tests `Method_LightFrameKeywordRest1` (new) and 102 named + tests pass. + - Two separate commits fix what perf/lexical found: `defined?(@@x)` and + `class_variable_defined?` answer true for a class variable an ancestor overtook + (`RubyModule.IsClassVariableDefined`, MRI's rb_cvar_defined), and a method defined in a + `refine` block reads the class variables of the module around it (the class-variable walk + passes over a refinement, as vm_get_cvar_base passes over a cref pushed by an eval). Tests + `ClassVariables_DefinedOvertaken1` and `ClassVariables_Refinement1` have CRuby's output; + `Util/lexical-light-matrix.rb` probes both again and prints CRuby's output in every mode. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, @@ -1535,7 +1593,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has jit-calls-matrix, block-given-matrix and light-rest-matrix agree with the baseline and CRuby; census `-c` on a Richards trace 0 differ; IronRuby.Tests `Method_LightFrameLexical1` (new) and 45 named class-variable, constant and light-frame tests pass. Found on the way, not - fixed (they differ on master too, so the matrix leaves them out): `defined?(@@x)` raises the + fixed here (fixed in perf/lexical2, and the matrix probes both again): `defined?(@@x)` raises the "overtaken" RuntimeError where CRuby answers "class variable"; `@@x` in a method of a `refine` block resolves to the refinement, CRuby to the module around it. And CRuby 4.0.10 crashes reading a class variable removed after its inline cache was warmed (a dangling cache), so the From 6eaffbe2be0cc9a6b055272d56502380679d0095 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:06:03 +0000 Subject: [PATCH 032/439] Add Util/hash-dup-matrix.rb and Util/bench/dup-shapes.rb; LEDGER: perf/struct2 rejected A Hash#dup that skipped its initialize_dup and initialize_copy calls when both are the built-ins (checked once per method version of Hash) saved 364 of 4,180 instructions on a three-key dup and 6% of its time in a method's loop, where it already runs at CRuby's time (134-137 ns against 144); Hash#clone, which the change does not enter, got 13% slower in both alternating runs. Rejected and reverted; the ledger has the numbers, and gap 24 now says Hash#dup is level with CRuby and String#dup (2.4x) and Array#dup (1.15x) are the dup gaps. The matrix (copies' contents, defaults, compare_by_identity, instance variables, frozenness, singleton methods, a subclass, a refinement, TracePoint, and the hooks redefined and restored) prints CRuby's output on the merged branch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Util/bench/dup-shapes.rb | 51 +++++++++++++++++++++ Util/hash-dup-matrix.rb | 97 ++++++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 26 +++++++++++ 3 files changed, 174 insertions(+) create mode 100644 Util/bench/dup-shapes.rb create mode 100644 Util/hash-dup-matrix.rb diff --git a/Util/bench/dup-shapes.rb b/Util/bench/dup-shapes.rb new file mode 100644 index 000000000..cd442b0e0 --- /dev/null +++ b/Util/bench/dup-shapes.rb @@ -0,0 +1,51 @@ +def plain(a) = a +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-14s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +N = (ENV['N'] || 200_000).to_i +H3 = { a: 1, b: 2, c: 3 } +X = {} +O = Object.new +HI = { a: 1 }.tap { |h| h.instance_variable_set(:@x, 1) } +A3 = [1, 2, 3] +S3 = "abc" +t("hash_dup", N) { |n| i = 0; c = 0; while i < n; c += H3.dup.size + i; i += 1; end; c } +t("replace", N) { |n| i = 0; c = 0; while i < n; c += X.replace(H3).size + i; i += 1; end; c } +t("hash_new", N) { |n| i = 0; c = 0; while i < n; c += Hash.new.size + i; i += 1; end; c } +t("lit3", N) { |n| i = 0; c = 0; while i < n; c += { a: 1, b: 2, c: i }.size; i += 1; end; c } +t("to_h", N) { |n| i = 0; c = 0; while i < n; c += H3.to_h.size + i; i += 1; end; c } +t("merge0", N) { |n| i = 0; c = 0; while i < n; c += H3.merge.size + i; i += 1; end; c } +t("obj_dup", N) { |n| i = 0; c = 0; while i < n; O.dup; c += i; i += 1; end; c } +t("arr_dup", N) { |n| i = 0; c = 0; while i < n; c += A3.dup.size + i; i += 1; end; c } +t("str_dup", N) { |n| i = 0; c = 0; while i < n; c += S3.dup.size + i; i += 1; end; c } +t("plain", N) { |n| i = 0; c = 0; while i < n; c += plain(i); i += 1; end; c } +t("size", N) { |n| i = 0; c = 0; while i < n; c += H3.size + i; i += 1; end; c } +t("clone", N) { |n| i = 0; c = 0; while i < n; c += H3.clone.size + i; i += 1; end; c } +t("dup_ivar", N) { |n| i = 0; c = 0; while i < n; c += HI.dup.size + i; i += 1; end; c } diff --git a/Util/hash-dup-matrix.rb b/Util/hash-dup-matrix.rb new file mode 100644 index 000000000..9a691d1f8 --- /dev/null +++ b/Util/hash-dup-matrix.rb @@ -0,0 +1,97 @@ +# Expression matrix for Hash#dup (perf/struct2's fast path, IR_FAST_DUP): what the copy holds - +# entries, order, default value and proc, compare_by_identity, instance variables, frozenness, +# singleton methods - and that initialize_dup and initialize_copy are still called when they are +# not the built-ins: redefined in Hash, in Object or Kernel, through a prepended or included +# module, on a subclass, traced by TracePoint, and restored again. +# +# ruby Util/hash-dup-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/hash-dup-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +# +# Every line is " => " or " !! : ". Each runs +# cold, again and then 200 times, and a line says so when a later answer differs from the first. +# The rows that redefine a hook (ONCE) come last, run once each, and undo what they did, in order. + +class SubHash < Hash; end +class InitHash < Hash + def initialize_copy(o) = (super; self[:copied] = true; self) +end +module LogCopy + def initialize_copy(o) = (super; self[:via] = :prepended; self) +end +module IncCopy + def initialize_copy(o) = (super; self[:via] = :included; self) +end +module RefineDup + refine Hash do + def initialize_copy(o) = (super; self[:via] = :refined; self) + end +end +module UsingRefineDup + using RefineDup + def self.dup_it = {a: 1}.dup +end +H = {a: 1, b: [2], "c" => 3} + +EXPRESSIONS = <<~'RUBY'.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + H.dup + H.dup == H + H.dup.equal?(H) + H.dup[:b].equal?(H[:b]) + (d = H.dup; d[:z] = 1; [H.key?(:z), d.size]) + {}.dup + (h = {a: 1, b: 2, c: 3}; h.delete(:a); h.delete(:b); h[:d] = 4; d = h.dup; [d, d.keys]) + (h = Hash.new(5); h[:a] = 1; d = h.dup; [d[:x], d.default]) + (h = Hash.new { |hh, k| k.to_s * 2 }; d = h.dup; [d[:ab], d.default_proc.equal?(h.default_proc)]) + (h = {}.compare_by_identity; k = "k"; h[k] = 1; d = h.dup; [d.compare_by_identity?, d["k"], d[k]]) + (h = {a: 1}; h.instance_variable_set(:@x, 9); d = h.dup; [d.instance_variable_get(:@x), d.instance_variables]) + (h = {a: 1}.freeze; d = h.dup; [d.frozen?, d]) + (h = {a: 1}; def h.extra = 1; d = h.dup; [d.respond_to?(:extra), d]) + (h = {a: 1}; h.singleton_class.define_method(:initialize_copy) { |o| super(o); self[:sing] = 1 }; h.dup) + SubHash[a: 1].dup.class + SubHash[a: 1].dup + InitHash[a: 1].dup + (h = {a: 1}; h.each { h.dup }; h) + (h = {a: 1}; r = nil; h.each { r = h.dup; r[:new] = 1 }; r) + (h = {"s" => 1}; d = h.dup; d["s"] += 1; [h, d]) + Thread.new { 100.times.map { H.dup.size }.uniq }.value + (ks = (1..20).to_a; h = ks.to_h { [_1, _1 * 2] }; d = h.dup; [d.size, d[20], d.keys == ks]) + UsingRefineDup.dup_it + (calls = []; tp = TracePoint.new(:c_call) { |t| calls << t.method_id if t.method_id.to_s.start_with?("initialize") }; tp.enable { {a: 1}.dup }; calls) +RUBY + +# These change the hooks for good and undo it, in order: each runs once, its dup warm (200 times). +ONCE = <<~'RUBY'.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + (r = nil; 200.times { r = {a: 1}.dup }; r) + (class Hash; alias_method :__saved_copy__, :initialize_copy; def initialize_copy(o) = (__saved_copy__(o); self[:mine] = 1; self); end; (r = nil; 200.times { r = {a: 1}.dup }; r)) + (class Hash; alias_method :initialize_copy, :__saved_copy__; remove_method :__saved_copy__; end; (r = nil; 200.times { r = {a: 1}.dup }; r)) + (class Object; def initialize_dup(o) = (super; self[:obj] = 1 if is_a?(Hash); self); end; (r = nil; 200.times { r = {a: 1}.dup }; r)) + (class Object; remove_method :initialize_dup; end; (r = nil; 200.times { r = {a: 1}.dup }; r)) + (module Kernel; alias_method :__saved_dup__, :initialize_dup; def initialize_dup(o) = (__saved_dup__(o); self[:kernel] = 1 if is_a?(Hash); self); end; (r = nil; 200.times { r = {a: 1}.dup }; r)) + (module Kernel; alias_method :initialize_dup, :__saved_dup__; remove_method :__saved_dup__; end; (r = nil; 200.times { r = {a: 1}.dup }; r)) + (Hash.prepend(LogCopy); (r = nil; 200.times { r = {a: 1}.dup }; r)) + (LogCopy.send(:remove_method, :initialize_copy); (r = nil; 200.times { r = {a: 1}.dup }; r)) + (Hash.include(IncCopy); (r = nil; 200.times { r = {a: 1}.dup }; r)) + ({a: 1}.clone) + ({a: 1}.freeze.clone.frozen?) +RUBY + +def clean(v) = v.inspect.gsub(/0x\h+/, "XX") +def run(source) + "=> #{clean(eval(source))}" +rescue Exception => e + "!! #{e.class}: #{e.message.gsub(/0x\h+/, "XX")}" +end + +EXPRESSIONS.each do |source| + first = run(source) + second = run(source) + warm = nil + 200.times { warm = run(source) } + line = "#{source} #{first}" + line += " [second: #{second}]" if second != first + line += " [warm: #{warm}]" if warm != first + puts line +end +ONCE.each { |source| puts "#{source} #{run(source)}" } +puts "done" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..3e07bb024 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1124,6 +1124,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has perf/struct (see Landed, not gated): Struct keyword creation is stored in C#, `kw_new` 1017 -> 198 ns against CRuby's 299 (`kw_hash` 147 against 196, `sub_kw` 379 against 356). Left from this gap: keyword initializers (`kwinit` 236 against 132) and `Hash#dup`. + perf/struct2 (see Rejected) measured both in a method's loop rather than the shape file's + block driver, which inflates them: `Hash#dup` of three keys is at CRuby's time (134-137 ns + against 144) and was dropped from this gap; `P.new(sku:, name:)` is 1.2-1.5 times CRuby there + (noisy). In the same loop `String#dup` is 2.4 times CRuby (137-142 ns against 56) and + `Array#dup` 1.15 times (143-146 against 124): the generic Kernel#dup path, worth a gap of its + own (`Util/bench/dup-shapes.rb`). 25. **Havlak: 1.4 times CRuby, 25 times TruffleRuby, and no single place** (round sixteen's breakdown; its author's numbers, taken beside two other experiments at load 2-14, so ratios). CRuby runs a copy with som.rb's `Set` renamed to `SomSet`: 2.85-3.3 @@ -4549,6 +4555,26 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/struct2 (/perf-step, 2026-11-26) - `Hash#dup` without its two hook calls** (gap 24; + switch `IR_FAST_DUP`). `RubyUtils.TryDuplicateObject` made the copy itself (a new Hash, the + instance variables, then what `Hash#initialize_copy` = `#replace` does) when the receiver's class + is Hash itself, no c_call is traced, and `initialize_dup` / `initialize_copy` resolve to the + library's KernelOps.InitializeDuplicate and HashOps.InitializeCopy - checked once per method + version of Hash, the resolutions marked InvalidateSitesOnOverride so that overriding either in + Hash, a prepended or included module, Object or Kernel moves the version. `Util/hash-dup-matrix.rb` + (new: copies' contents, defaults, compare_by_identity, ivars, frozenness, singleton methods, a + subclass, a refinement, TracePoint, and the hooks redefined and restored, once each with the dup + warm) printed CRuby's output on master, on the change and with the switch off. Instructions + (`Util/perf/callgrind/count.sh`, `dup-shapes.rb`, N=20000): `hash_dup` 4,180 -> 3,816, `plain` + 1,266 both - the two dynamic calls were an eighth of the excess. Timed in a method's loop (four + rounds each, two alternating runs, steady rounds): `H.dup` 134-137 -> 127-129 ns, CRuby 144 - + already at CRuby's time - while `H.clone`, which the change does not enter, went 174-175 -> 198 in + both runs (the bigger TryDuplicateObject, presumably no longer inlined or laid out as before). + Rejected: 6% on a shape already level with CRuby against 13% on one it should not touch. What was + learned: the "Hash#dup 2x" of gap 24 was the shape file's block driver; in a method `String#dup` + (2.4x) and `Array#dup` (1.15x) are the dup gaps, and a fast path for them belongs in a method of + its own beside TryDuplicateObject (NoInlining), not inside it. + - **perf/lsite (/perf-step, 2026-11-26) - a light site that remembers it needed the scope** (gap 16; switch `IR_LIGHT_REMEMBER`). In `LightFrameRewriter.MakeLightCall`, each site got a box (`StrongBox`, a constant of the body like a regex literal's cache, set From dc1d1369062ae286bc2adc87a234df42c1d834c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:12:46 +0000 Subject: [PATCH 033/439] start_with? with one String prefix takes no scope, and an ASCII prefix is compared in place String#start_with? had one overload, (scope, self, *prefixes): it takes the caller's scope to store $~ for a Regexp prefix. So a call from a light frame with a String prefix made that frame's scope on the call (RubyOps.LightScopeRequired) and called again: 120 ns of "abc...".start_with?("\"") against CRuby's 53. A second overload takes one MutableString prefix and no scope; the binder picks it for a String argument, and a Regexp, a #to_str object or several prefixes still go to the first. The comparison read both strings with GetByteCount and GetByte, a call each per byte, which also switch a string held as characters that are not its bytes over to bytes. An ASCII prefix of two bytes or more on a receiver in an ASCII-compatible encoding is now compared where both strings are, as characters or bytes (an ASCII byte is a character of its own there, so the prefix ends on a boundary); a one-byte prefix keeps the byte loop, which is cheaper for it (callgrind: 2,645 instructions a call against 2,789 for the in-place compare, which costs the same for any length; three bytes 3,863 against 2,828). Behind IR_FAST_SEARCH (the overload is not). Util/string-search-matrix.rb has 1,255 more start_with? rows (Shift_JIS trail bytes, EUC-JP, broken UTF-8 leads and continuations, BINARY, UTF-16, several prefixes, a Regexp among them, nil, none), which print CRuby 4.0's output on master and on this build in both modes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/Builtins/MutableStringOps.cs | 18 +++++++++ Src/Ruby/Builtins/MutableString.cs | 46 ++++++++++++++++++++++ Util/string-search-matrix.rb | 24 +++++++++++ 3 files changed, 88 insertions(+) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index e72793c5f..b73887f90 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -4674,7 +4674,25 @@ public static bool StartsWith(ConversionStorage/*!*/ stringCast, return false; } + // The usual call, one String prefix, without the scope: the overload above takes it for a Regexp + // prefix's $~, so a light frame calling it with a String made its scope on the call + // (RubyOps.LightScopeRequired) and called again - 70 ns of the 120 that "abc...".start_with?("a") + // took (Util/bench/strsearch-shapes.rb sw1_a; CRuby 55). The binder picks this one for a + // MutableString argument; a Regexp, a #to_str object or several prefixes still go above. + [RubyMethod("start_with?")] + public static bool StartsWithString(MutableString/*!*/ self, [NotNull]MutableString/*!*/ prefix) { + self.RequireCompatibleEncoding(prefix); + return StartsWith(self, prefix); + } + private static bool StartsWith(MutableString/*!*/ self, MutableString/*!*/ subString) { + // An ASCII prefix is compared where both strings are, without switching either to bytes. It + // costs the same whatever the prefix's length, which the byte loop below beats only for one + // byte (2,645 instructions a call against 2,789; three bytes 3,863 against 2,828: sw1_a, sw3_a). + if (FastSearchEnabled && self.Encoding.IsAsciiIdentity && subString.IsAscii() && subString.GetCharCount() > 1) { + return self.StartsWithAscii(subString); + } + int prefix = subString.GetByteCount(); if (self.GetByteCount() < prefix) { return false; diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index d35427371..866ef7aec 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -1647,6 +1647,52 @@ public bool StartsWith(char value) { return _content.StartsWith(value); } + /// + /// Whether the string starts with , which is ASCII, read where both + /// contents are, as bytes or as characters: neither is switched to the other representation, + /// which GetByteCount and GetByte do to a string held as characters that are not its bytes. + /// The caller sees to it that this string's encoding is ASCII compatible: then an ASCII byte + /// is a character of its own, and an ASCII character stands for that byte, wherever they are, + /// so the first characters are the prefix's exactly when the first bytes are, and the prefix + /// ends on a character boundary. + /// + public bool StartsWithAscii(MutableString/*!*/ prefix) { + Debug.Assert(_encoding.IsAsciiIdentity); + ReadOnlySpan chars, prefixChars; + ReadOnlySpan bytes, prefixBytes; + bool selfIsChars = GetRawData(_content, out chars, out bytes); + bool prefixIsChars = GetRawData(prefix._content, out prefixChars, out prefixBytes); + int count = prefixIsChars ? prefixChars.Length : prefixBytes.Length; + if ((selfIsChars ? chars.Length : bytes.Length) < count) { + return false; + } + if (selfIsChars && prefixIsChars) { + return chars.StartsWith(prefixChars); + } + if (!selfIsChars && !prefixIsChars) { + return bytes.StartsWith(prefixBytes); + } + for (int i = 0; i < count; i++) { + int a = selfIsChars ? chars[i] : bytes[i]; + int b = prefixIsChars ? prefixChars[i] : prefixBytes[i]; + if (a != b) { + return false; + } + } + return true; + } + + private static bool GetRawData(Content/*!*/ content, out ReadOnlySpan chars, out ReadOnlySpan bytes) { + if (content is BinaryContent binary) { + chars = default(ReadOnlySpan); + bytes = binary.GetDataSpan(); + return false; + } + bytes = default(ReadOnlySpan); + chars = (content is StringContent str) ? str.Data.AsSpan() : ((CharArrayContent)content).GetDataSpan(); + return true; + } + public bool EndsWith(char value) { try { return GetLastChar() == value; diff --git a/Util/string-search-matrix.rb b/Util/string-search-matrix.rb index 59fbc532c..28d3a1b2d 100644 --- a/Util/string-search-matrix.rb +++ b/Util/string-search-matrix.rb @@ -124,3 +124,27 @@ def kinds(base) try("index after <<") { "sentinel" =~ SENTINEL; b = $~; [(s << "\"x"; s.index('"', 4)), b, $~] } try("index after setbyte") { "sentinel" =~ SENTINEL; b = $~; [(t = +"abc"; t.setbyte(1, 0x22); t.index('"')), b, $~] } try("frozen literal index") { "sentinel" =~ SENTINEL; b = $~; [('x"y'.freeze.index('"')), b, $~] } + +puts "== start_with? (round two: a String prefix is answered without the caller's scope)" +SW_RECEIVERS = { + sjis_trail: "\x83\x41bc".dup.force_encoding("Shift_JIS"), sjis_ascii: "Abc\x83\x41".dup.force_encoding("Shift_JIS"), + eucjp: "\xA4\xA2ab".dup.force_encoding("EUC-JP"), broken_cont: "a\x80bc".dup.force_encoding("UTF-8"), + broken_lead: "ab\xE3\x81".dup.force_encoding("UTF-8"), utf8: "aé日b", binary: "a\xE9b".b, ascii: "abc", + usascii: "abc".dup.force_encoding("US-ASCII"), utf16: "abc".encode("UTF-16LE"), empty: "", +} +SW_PREFIXES = { + a: "a", ab: "ab", A: "A", abc: "abc", abcd: "abcd", empty: "", e_acute: "aé", sjis_lead: "\x83".dup.force_encoding("Shift_JIS"), + bin_a: "a".b, bin_hi: "a\xE9".b, usascii: "a".dup.force_encoding("US-ASCII"), broken: "a\x80".dup.force_encoding("UTF-8"), + utf16: "a".encode("UTF-16LE"), tostr: ToStr.new("a"), sub: SubStr.new("ab"), +} +SW_RECEIVERS.each do |rname, base| + kinds(base).each do |kname, s| + SW_PREFIXES.each do |pname, pre| + try("#{rname}/#{kname}.start_with?(#{pname})") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?(pre)), b, $~] } + end + try("#{rname}/#{kname}.start_with?(x, a)") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?("x", "a")), b, $~] } + try("#{rname}/#{kname}.start_with?(/b/, a)") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?(/b/, "a")), b, $~] } + try("#{rname}/#{kname}.start_with?()") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?), b, $~] } + try("#{rname}/#{kname}.start_with?(nil)") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?(nil)), b, $~] } + end +end From 45826abd3eafba12ead87401b400e46bf85057c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:14:21 +0000 Subject: [PATCH 034/439] Class#new calls a library initialize without the caller's refinements A refinement of initialize active where `new` was called reached a library initialize: `KN = Struct.new(:a, :b)` with `refine(KN) { def initialize(*) = super(:refined, :init) }` in use made `KN.new(1, 2)` [:refined, :init] once the rule of `new` was compiled (after 200 calls, every build, light frames and JIT on or off; Util/struct-matrix.rb's `UsingRefine.make`), and an Array subclass's `new` did from the first call. CRuby's rb_obj_call_init calls initialize with no refinement active: [1, 2]. BuildOverriddenInitializerCall calls a library initialize through a dynamic site of its own, which was handed the caller's scope, and a site with a scope resolves under the scope's refinements. It now takes no scope (the action is bound to the context; no library initialize takes the scope): CallArguments.GetBoundCallSiteArguments. A Ruby initialize was already called as resolved, unrefined. Checked: Refinements16 (new; CRuby 4.0's output); Util/struct-matrix.rb now prints CRuby's output in full. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RefinementTests.cs | 26 +++++++++++++++++++ Src/Ruby/Builtins/RubyClass.cs | 22 +++++++++++----- Src/Ruby/Runtime/Calls/CallArguments.cs | 10 +++++++ 4 files changed, 52 insertions(+), 7 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 834bc86db..b33358a9e 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -922,6 +922,7 @@ public Tests(Driver/*!*/ driver) { Refinements13, Refinements14, Refinements15, + Refinements16, Super1, SuperParameterless1, diff --git a/Src/IronRuby.Tests/Runtime/RefinementTests.cs b/Src/IronRuby.Tests/Runtime/RefinementTests.cs index b257c7f34..6103066ce 100644 --- a/Src/IronRuby.Tests/Runtime/RefinementTests.cs +++ b/Src/IronRuby.Tests/Runtime/RefinementTests.cs @@ -592,6 +592,32 @@ p r [[:D, :C], [:C], [:C], [:C], [:C]] [[:D, :C], [:R]] [[:R], [:C], [:C], [:D, :C]] +"); + } + + /// + /// Class#new calls initialize as MRI's rb_obj_call_init does, with no refinement active: a refinement of initialize + /// active where new is called is not seen, whether the class's initialize is Ruby's or a library's (Struct#initialize, + /// Array#initialize) and whether the rule of new is interpreted or compiled (a Struct's was, after 200 calls). + /// + public void Refinements16() { + TestOutput(@" +S = Struct.new(:a, :b) +class A < Array; end +class C; def initialize(*a) = (@a = a); attr_reader :a; end +module R + refine(S) { def initialize(*) = super(:refined, :init) } + refine(A) { def initialize(*) = super(2, :r) } + refine(C) { def initialize(*) = super(:r) } +end +module U + using R + def self.make = [S.new(1, 2).to_a, A.new(1, 0).to_a, C.new(1).a] +end +r = nil +300.times { |i| x = U.make; (p [i, x]; r = x) if x != r } +", @" +[0, [[1, 2], [0], [1]]] "); } } diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index d1c000d1b..a59e48b97 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -18,6 +18,7 @@ using System; using System.Linq; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic; using System.Reflection; @@ -2037,13 +2038,8 @@ private static void BuildOverriddenInitializerCall(MetaObjectBuilder/*!*/ metaBu } else { // TODO: we need more refactoring of RubyMethodGroupInfo.BuildCall to be able to inline this: metaBuilder.Result = AstUtils.LightDynamic( - RubyCallAction.Make(args.RubyContext, "initialize", - new RubyCallSignature( - args.Signature.ArgumentCount, - (args.Signature.Flags & ~RubyCallFlags.IsInteropCall) | RubyCallFlags.HasImplicitSelf - ) - ), - args.GetCallSiteArguments(instanceVariable) + RubyCallAction.Make(args.RubyContext, "initialize", new RubyCallSignature(args.Signature.ArgumentCount, flags)), + siteArguments ); } @@ -2051,6 +2047,18 @@ private static void BuildOverriddenInitializerCall(MetaObjectBuilder/*!*/ metaBu // PropagateRetrySingleton(instance = new (), instance.initialize()) metaBuilder.Result = Methods.PropagateRetrySingleton.OpCall( Ast.Assign(instanceVariable, instanceExpr), + // The call is Class#new's, not the caller's: MRI's rb_obj_call_init calls initialize with no refinement active, + // so the site does not take the caller's scope, whose refinements would reach initialize (a refined + // Struct#initialize did, once the rule was compiled). No library initialize takes the scope, and the action is + // bound to the context, so nothing takes the scope's place. + var flags = (args.Signature.Flags & ~RubyCallFlags.IsInteropCall) | RubyCallFlags.HasImplicitSelf; + ReadOnlyCollection siteArguments; + if (args.Signature.HasScope) { + siteArguments = args.GetBoundCallSiteArguments(instanceVariable); + flags &= ~(RubyCallFlags.HasScope | RubyCallFlags.HasLightScope); + } else { + siteArguments = args.GetCallSiteArguments(instanceVariable); + } metaBuilder.Result ); diff --git a/Src/Ruby/Runtime/Calls/CallArguments.cs b/Src/Ruby/Runtime/Calls/CallArguments.cs index d8212a433..35455dce5 100644 --- a/Src/Ruby/Runtime/Calls/CallArguments.cs +++ b/Src/Ruby/Runtime/Calls/CallArguments.cs @@ -203,6 +203,16 @@ public Expression GetRhsArgumentExpression() { return result.ToReadOnlyCollection(); } + // target, arguments: for a site bound to the context that takes no scope + internal ReadOnlyCollection/*!*/ GetBoundCallSiteArguments(Expression/*!*/ targetExpression) { + var result = new AstExpressions(ExplicitArgumentCount); + result.Add(targetExpression); + for (int j = FirstArgumentIndex; j < _args.Length; j++) { + result.Add(_args[j].Expression); + } + return result.ToReadOnlyCollection(); + } + private int GetSimpleArgumentIndex(int i) { return FirstArgumentIndex + (_signature.HasBlock ? 1 : 0) + i; } From 328f4cab39ae75f80ae4bc86cb09f0a3d08f611c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:14:21 +0000 Subject: [PATCH 035/439] Data.singleton_methods no longer lists allocate Data, Enumerator::ArithmeticSequence and Continuation refused allocation with a singleton method `allocate` written in the prelude, so `Data.singleton_methods` was [:allocate, :define] (CRuby: [:define]), `D.singleton_methods` of a Data.define class listed it too, and so did ArithmeticSequence's and Continuation's. CRuby has no such method: rb_undef_alloc_func takes the class's allocator away, and Class#allocate raises "allocator undefined for Data" for that class only. The prelude now says the same with Class#__ir_undef_alloc__ (a private helper, unlisted like the others), which marks the class; Class#allocate's rule for that class (not a subclass) raises the error. A helper alias of allocate (ArithmeticSequence's __allocate__, Continuation's __ir_allocate__) still allocates. Checked: Prelude_DataUndefinedAllocator1 (new; CRuby 4.0's output). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 30 +++++++++++++++++++++ Src/Libraries/Builtins/ClassOps.cs | 10 +++++++ Src/Ruby/Builtins/RubyClass.cs | 35 ++++++++++++++++++------- Src/Ruby/Builtins/RubyModule.cs | 2 +- Src/StdLib/ironruby/continuation.rb | 6 ++--- Src/StdLib/ironruby/ruby4.rb | 15 +++-------- 7 files changed, 73 insertions(+), 26 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index b33358a9e..a0370837f 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1051,6 +1051,7 @@ public Tests(Driver/*!*/ driver) { Marshal_LoadChecks1, Integer_SqrtPowDigits1, Prelude_DataStructErrors1, + Prelude_DataUndefinedAllocator1, Prelude_AliasNames1, Visibility_DefaultScope1, Main_PrivateAndInitializeCopy1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 7128d1114..edb7f9820 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -3755,6 +3755,36 @@ public void Prelude_DataStructErrors1() { "); } + /// + /// Data and Enumerator::ArithmeticSequence have no allocator (MRI's rb_undef_alloc_func), which the prelude says with + /// Class#__ir_undef_alloc__ rather than a singleton method allocate that singleton_methods would list. A class + /// Data.define makes, and a subclass of one, still allocates, through Class#allocate. + /// + public void Prelude_DataUndefinedAllocator1() { + TestOutput(@" +require 'ruby4' +D = Data.define(:a) +# (a test's require of ruby4 lists the prelude's __helpers__, which the prelude proper does not) +p Data.singleton_methods.sort, D.singleton_methods.sort, Enumerator::ArithmeticSequence.singleton_methods.grep_v(/\A__/).sort +p((Data.allocate rescue $!), D.allocate, (Enumerator::ArithmeticSequence.allocate rescue $!)) +p D.method(:allocate).owner, Data.respond_to?(:allocate), 1.step(10, 4).to_a, (1..2).step(1).class +E = Class.new(D); p E.allocate, E.new(5) +", @" +[:define] +[:[], :inspect, :members, :new] +[:produce, :product] +# +# +# +Class +true +[1, 5, 9] +Enumerator::ArithmeticSequence +# +# +"); + } + /// /// #yield_self is an alias of #then, as in MRI, so the Enumerator and Method#original_name say :then; the prelude's /// aliases (collect_concat, Lazy#filter/collect, select!/filter!, ENV#filter/each_pair) name the Enumerator after the diff --git a/Src/Libraries/Builtins/ClassOps.cs b/Src/Libraries/Builtins/ClassOps.cs index a895508af..5fa014f11 100644 --- a/Src/Libraries/Builtins/ClassOps.cs +++ b/Src/Libraries/Builtins/ClassOps.cs @@ -53,6 +53,16 @@ public static void Reinitialize(BlockParam body, RubyClass/*!*/ self, [Optional] return self; } + /// + /// MRI's rb_undef_alloc_func, for a core class the prelude writes in Ruby: allocate of this class (not of a subclass) + /// raises "allocator undefined", as Data.allocate does, without a singleton method allocate that Data.singleton_methods + /// would list. + /// + [RubyMethod("__ir_undef_alloc__", RubyMethodAttributes.PrivateInstance)] + public static void UndefineAllocator(RubyClass/*!*/ self) { + self.UndefineAllocator(); + } + [RubyMethod("allocate")] public static RuleGenerator/*!*/ Allocate() { return new RuleGenerator(RuleGenerators.InstanceAllocator); diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index a59e48b97..19ed6b7d6 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -85,6 +85,18 @@ public sealed partial class RubyClass : RubyModule, IDuplicable { public bool IsUninitializedAllocation { get { return _isUninitializedAllocation; } } + // MRI's rb_undef_alloc_func on a class written in Ruby (Data, Enumerator::ArithmeticSequence): Class#allocate of this + // class, not of its subclasses, raises "allocator undefined" (ClassOps.UndefineAllocator). + private bool _isAllocatorUndefined; + + public void UndefineAllocator() { + using (Context.ClassHierarchyLocker()) { + _isAllocatorUndefined = true; + // rules of allocate built for this class allocate + MethodsUpdated("allocator"); + } + } + // immutable: private readonly Delegate/*!*/[]/*!*/ _factories; @@ -1693,6 +1705,9 @@ public void BuildObjectAllocation(MetaObjectBuilder/*!*/ metaBuilder, CallArgume if (!metaBuilder.Error) { if (_isUninitializedAllocation) { metaBuilder.SetError(Methods.MakeUninitializedClassInstantiatedError.OpCall()); + } else if (_isAllocatorUndefined && !IsHelperName(methodName)) { + // (a prelude helper's alias of allocate, such as ArithmeticSequence's __allocate__, still allocates) + metaBuilder.SetError(Methods.MakeAllocatorUndefinedError.OpCall(Ast.Convert(args.TargetExpression, typeof(RubyClass)))); } else if (HasSealedClrBase() || !BuildAllocatorCall(metaBuilder, args, () => AstUtils.Constant(Name))) { metaBuilder.SetError(Methods.MakeAllocatorUndefinedError.OpCall(Ast.Convert(args.TargetExpression, typeof(RubyClass)))); } @@ -2037,16 +2052,6 @@ private static void BuildOverriddenInitializerCall(MetaObjectBuilder/*!*/ metaBu initializer.BuildCallNoFlow(metaBuilder, args, Symbols.Initialize); } else { // TODO: we need more refactoring of RubyMethodGroupInfo.BuildCall to be able to inline this: - metaBuilder.Result = AstUtils.LightDynamic( - RubyCallAction.Make(args.RubyContext, "initialize", new RubyCallSignature(args.Signature.ArgumentCount, flags)), - siteArguments - ); - } - - if (!metaBuilder.Error) { - // PropagateRetrySingleton(instance = new (), instance.initialize()) - metaBuilder.Result = Methods.PropagateRetrySingleton.OpCall( - Ast.Assign(instanceVariable, instanceExpr), // The call is Class#new's, not the caller's: MRI's rb_obj_call_init calls initialize with no refinement active, // so the site does not take the caller's scope, whose refinements would reach initialize (a refined // Struct#initialize did, once the rule was compiled). No library initialize takes the scope, and the action is @@ -2059,6 +2064,16 @@ private static void BuildOverriddenInitializerCall(MetaObjectBuilder/*!*/ metaBu } else { siteArguments = args.GetCallSiteArguments(instanceVariable); } + metaBuilder.Result = AstUtils.LightDynamic( + RubyCallAction.Make(args.RubyContext, "initialize", new RubyCallSignature(args.Signature.ArgumentCount, flags)), + siteArguments + ); + } + + if (!metaBuilder.Error) { + // PropagateRetrySingleton(instance = new (), instance.initialize()) + metaBuilder.Result = Methods.PropagateRetrySingleton.OpCall( + Ast.Assign(instanceVariable, instanceExpr), metaBuilder.Result ); diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index bfa4f284b..04e55b124 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -3709,7 +3709,7 @@ private static bool IsSystemObjectMethodName(string/*!*/ name) { return false; } - private static bool IsHelperName(string/*!*/ name) { + internal static bool IsHelperName(string/*!*/ name) { if (!name.StartsWith("__", StringComparison.Ordinal)) { return false; } diff --git a/Src/StdLib/ironruby/continuation.rb b/Src/StdLib/ironruby/continuation.rb index ab71c4b46..57e5c7b90 100644 --- a/Src/StdLib/ironruby/continuation.rb +++ b/Src/StdLib/ironruby/continuation.rb @@ -19,15 +19,13 @@ class Continuation # out of #instance_variables. Not an ObjectSpace::WeakMap entry: that holds its values # weakly too, and the array had no other reference to keep it. + __ir_undef_alloc__ + class << self alias_method :__ir_allocate__, :allocate private :__ir_allocate__ undef_method :new - def allocate - raise TypeError, "allocator undefined for #{self}" - end - # Kernel#callcc: runs the block with a new continuation, which is live until # the block finishes. private def __ir_callcc__ diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 4ccdfefcd..9d7e90999 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -7526,14 +7526,11 @@ def self.__step_each__(from, to, unit, excl, &block) end # Only Range#step, Range#% and Numeric#step make one: .new is undefined and .allocate refuses. + __ir_undef_alloc__ class << self alias :__allocate__ :allocate private :__allocate__ undef_method :new - - def allocate - ::Kernel.raise(::TypeError, "allocator undefined for #{self}") - end end def self.__build__(from, to, by, exclude_end, source, inspect_str = nil) @@ -7658,14 +7655,10 @@ def inspect # user-written #initialize was never reached, so neither the `super` idiom nor # psych's Data.instance_method(:initialize).bind_call trick worked. class Data - class << self - # Only the classes Data.define makes have instances. - alias_method :__ir_allocate__, :allocate - def allocate - ::Kernel.raise(::TypeError, "allocator undefined for Data") if equal?(::Data) - __ir_allocate__ - end + # Only the classes Data.define makes have instances (MRI: rb_undef_alloc_func(rb_cData)). + __ir_undef_alloc__ + class << self def define(*names, &block) names = names.map do |m| unless m.is_a?(::Symbol) || m.is_a?(::String) From c39265cdfc1106906cd40c7d80d2c85f4d4bb4b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:16:13 +0000 Subject: [PATCH 036/439] Census: walk the operands of every node the screen refuses The census's screen (JitScreen.CollectAll) went on after a refusal, but a refusal that returned without walking the node's operands left their own refusals uncounted: `@x ||= compute' (refused for its call, on purpose since round twenty-four) counted as "||= InstanceVariable" alone, and so did every Hash literal, interpolated String, Regexp or Range whose parts hold a call. The same hole the Body refusal had (ba4da2f). After a refusal the census's screen now screens each child expression of the refused node (CensusChildren, a Walker): not the arguments or block of a call (a call is one refusal, as before), not blocks, lambdas or definitions, not a Body (WalkClausesForCensus); an assignment's target is not read, only the expressions inside it. The real screen stops at its first refusal and never gets there. Every verdict is unchanged (census.rb -d against 2f8c31c: 0 methods changed). "One thing only", Src/StdLib + AWFY: `||= InstanceVariable` 265 -> 42, HashConstructor 150 -> 136, RegularExpression 68 -> 61, StringConstructor 61 -> 37, `||= ArrayItemAccess` 51 -> 11, `= AttributeAccess` 35 -> 28, RangeExpression 33 -> 32; StringLiteral (101) and ParallelAssignment (74) are as they were. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 130 ++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index c1cca3ad4..5af454010 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -3230,11 +3230,141 @@ private bool No(object/*!*/ node) { if (_all != null) { // the census's screen: note it and go on as if it had been taken (CollectAll) if (detail != null && !_all.Contains(detail)) { _all.Add(detail); } + CensusChildren.Screen(this, node as RExpr); return true; } return false; } + /// + /// The census's screen goes on into the operands of a node it has refused: a refusal that returns without walking + /// them (`@x ||= compute', `{k => f(v)}', `"#{f(x)}"', `a..f(b)', the final refusal of a kind the screen does not + /// know) would otherwise leave their own refusals uncounted, and the node would be reported as the only thing in + /// the way of a method that has a call behind it. Each child expression is screened as a statement would be. Not + /// the children of a call (its arguments and block are the call's own question: a call with a block is counted as + /// one refusal), of a block, lambda or definition (another scope), or of a Body (WalkClausesForCensus). Only with + /// CollectAll: the real screen has stopped at its first refusal and never gets here. + /// + private sealed class CensusChildren : Walker { + private readonly JitScreen/*!*/ _screen; + private readonly RExpr/*!*/ _root; + + private CensusChildren(JitScreen/*!*/ screen, RExpr/*!*/ root) { + _screen = screen; + _root = root; + } + + internal static void Screen(JitScreen/*!*/ screen, RExpr node) { + if (node == null || node is MethodCall || node is SuperCall || node is YieldCall || node is Body || + node is LambdaDefinition || node is DefinitionExpression) { return; } + node.Walk(new CensusChildren(screen, node)); + } + + private bool Visit(object/*!*/ node) { + if (ReferenceEquals(node, _root)) { return true; } + // An assignment's target is not read: only the expressions inside it are (`a[i] = v', `o.x = v'). + var simple = _root as SimpleAssignmentExpression; + var parallel = _root as ParallelAssignmentExpression; + if ((simple != null && ReferenceEquals(node, simple.Left)) || (parallel != null && ReferenceEquals(node, parallel.Left))) { + ScreenTarget((LeftValue)node); + return false; + } + if (node is BlockDefinition || node is LambdaDefinition || node is DefinitionExpression || node is SourceUnitTree) { return false; } + var expr = node as RExpr; + if (expr == null) { return true; } // an argument list, a maplet, a clause: go on to the expressions in it + _screen.Walk(expr); + return false; + } + + private void ScreenTarget(RExpr/*!*/ target) { + var compound = target as CompoundLeftValue; + if (compound != null) { + foreach (var item in compound.LeftValues) { ScreenTarget(item); } + return; + } + var element = target as ArrayItemAccess; + if (element != null) { + _screen.Walk(element.Array); + foreach (var arg in element.Arguments.Expressions) { _screen.Walk(arg); } + return; + } + var attribute = target as AttributeAccess; + if (attribute != null) { _screen.Walk(attribute.Qualifier); } + // a variable, or a splat of one: nothing is read + } + + public override bool Enter(SourceUnitTree/*!*/ node) { return Visit(node); } + public override bool Enter(BlockDefinition/*!*/ node) { return Visit(node); } + public override bool Enter(BlockReference/*!*/ node) { return Visit(node); } + public override bool Enter(Body/*!*/ node) { return Visit(node); } + public override bool Enter(Maplet/*!*/ node) { return Visit(node); } + public override bool Enter(Parameters/*!*/ node) { return Visit(node); } + public override bool Enter(Arguments/*!*/ node) { return Visit(node); } + public override bool Enter(SplattedArgument/*!*/ node) { return Visit(node); } + public override bool Enter(KeywordArgumentsTest/*!*/ node) { return Visit(node); } + public override bool Enter(KeywordParameterRead/*!*/ node) { return Visit(node); } + public override bool Enter(SplatParameterRead/*!*/ node) { return Visit(node); } + public override bool Enter(KeywordSplatMerge/*!*/ node) { return Visit(node); } + public override bool Enter(ClassDefinition/*!*/ node) { return Visit(node); } + public override bool Enter(ModuleDefinition/*!*/ node) { return Visit(node); } + public override bool Enter(SingletonDefinition/*!*/ node) { return Visit(node); } + public override bool Enter(MethodDefinition/*!*/ node) { return Visit(node); } + public override bool Enter(LambdaDefinition/*!*/ node) { return Visit(node); } + public override bool Enter(AndExpression/*!*/ node) { return Visit(node); } + public override bool Enter(ArrayConstructor/*!*/ node) { return Visit(node); } + public override bool Enter(AssignmentExpression/*!*/ node) { return Visit(node); } + public override bool Enter(IsDefinedExpression/*!*/ node) { return Visit(node); } + public override bool Enter(BlockExpression/*!*/ node) { return Visit(node); } + public override bool Enter(CaseExpression/*!*/ node) { return Visit(node); } + public override bool Enter(ConditionalExpression/*!*/ node) { return Visit(node); } + public override bool Enter(ForLoopExpression/*!*/ node) { return Visit(node); } + public override bool Enter(HashConstructor/*!*/ node) { return Visit(node); } + public override bool Enter(IfExpression/*!*/ node) { return Visit(node); } + public override bool Enter(Literal/*!*/ node) { return Visit(node); } + public override bool Enter(StringLiteral/*!*/ node) { return Visit(node); } + public override bool Enter(SymbolLiteral/*!*/ node) { return Visit(node); } + public override bool Enter(EncodingExpression/*!*/ node) { return Visit(node); } + public override bool Enter(MethodCall/*!*/ node) { return Visit(node); } + public override bool Enter(MatchExpression/*!*/ node) { return Visit(node); } + public override bool Enter(NotExpression/*!*/ node) { return Visit(node); } + public override bool Enter(OrExpression/*!*/ node) { return Visit(node); } + public override bool Enter(RangeExpression/*!*/ node) { return Visit(node); } + public override bool Enter(RangeCondition/*!*/ node) { return Visit(node); } + public override bool Enter(RegularExpression/*!*/ node) { return Visit(node); } + public override bool Enter(RegularExpressionCondition/*!*/ node) { return Visit(node); } + public override bool Enter(RescueExpression/*!*/ node) { return Visit(node); } + public override bool Enter(SelfReference/*!*/ node) { return Visit(node); } + public override bool Enter(StringConstructor/*!*/ node) { return Visit(node); } + public override bool Enter(SuperCall/*!*/ node) { return Visit(node); } + public override bool Enter(UnlessExpression/*!*/ node) { return Visit(node); } + public override bool Enter(WhileLoopExpression/*!*/ node) { return Visit(node); } + public override bool Enter(YieldCall/*!*/ node) { return Visit(node); } + public override bool Enter(ArrayItemAccess/*!*/ node) { return Visit(node); } + public override bool Enter(AttributeAccess/*!*/ node) { return Visit(node); } + public override bool Enter(ClassVariable/*!*/ node) { return Visit(node); } + public override bool Enter(CompoundLeftValue/*!*/ node) { return Visit(node); } + public override bool Enter(ConstantVariable/*!*/ node) { return Visit(node); } + public override bool Enter(AstGlobalVariable/*!*/ node) { return Visit(node); } + public override bool Enter(InstanceVariable/*!*/ node) { return Visit(node); } + public override bool Enter(LocalVariable/*!*/ node) { return Visit(node); } + public override bool Enter(Placeholder/*!*/ node) { return Visit(node); } + public override bool Enter(RegexMatchReference/*!*/ node) { return Visit(node); } + public override bool Enter(MemberAssignmentExpression/*!*/ node) { return Visit(node); } + public override bool Enter(ParallelAssignmentExpression/*!*/ node) { return Visit(node); } + public override bool Enter(SimpleAssignmentExpression/*!*/ node) { return Visit(node); } + public override bool Enter(AliasStatement/*!*/ node) { return Visit(node); } + public override bool Enter(ShutdownHandlerStatement/*!*/ node) { return Visit(node); } + public override bool Enter(UndefineStatement/*!*/ node) { return Visit(node); } + public override bool Enter(BreakStatement/*!*/ node) { return Visit(node); } + public override bool Enter(NextStatement/*!*/ node) { return Visit(node); } + public override bool Enter(RedoStatement/*!*/ node) { return Visit(node); } + public override bool Enter(RetryStatement/*!*/ node) { return Visit(node); } + public override bool Enter(ReturnStatement/*!*/ node) { return Visit(node); } + public override bool Enter(RescueClause/*!*/ node) { return Visit(node); } + public override bool Enter(WhenClause/*!*/ node) { return Visit(node); } + public override bool Enter(ElseIfClause/*!*/ node) { return Visit(node); } + } + /// Mirrors JitCompiler.EmitBody. private bool WalkBody(Body/*!*/ body) { if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { From dcdbade2c919d3c2950ec4b166e78b8467623351 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:16:41 +0000 Subject: [PATCH 037/439] Method JIT: take a Hash literal with plain literal keys The screen refused every Hash literal: once the census counts the operands of a refused node, the largest line of "JIT never, one thing only" that is not a call (136 methods of Src/StdLib + AWFY): `@h = {}` in initialize, `{key: @x}` returned by to_h and marshal_dump, `opts = {}` defaults. EmitHashLiteral makes the Hash the generic body makes, keys and values in order, through the same code (JitRuntime.NewHash and NewSymbolHash1..3, the bodies of RubyOps.MakeHash and MakeSymbolHash1..3 with the runtime's comparer). Only for keys the comparer hashes itself (the generic body's HasPlainLiteralKeys): then building it runs no Ruby code, so it is no effect a deopt could repeat, no way into deep recursion and no call that needs a stack check. At most five pairs; not a keyword hash; not an operand. census.rb -d against 2f8c31c: 132 methods up (74 to compiles, 58 to maybe), none down. app-shapes trace: 114 -> 116 specialized, 29 -> 30 declined after the pre-screen (CSV::FieldsConverter#initialize, at a call on self after its writes, as the unchanged build declines the same method with `options=nil`). Instructions a call 0.80-0.90 on the literal shapes, 0.14 for a method called without its `opts = {}`. Util/jit-hash-matrix.rb (new) and the JIT matrices print CRuby's output with the JIT on, off and without JIT calls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 60 ++++++++++++++++ Src/Ruby/Runtime/Jit/JitRuntime.cs | 29 ++++++++ Util/bench/jit-hash-shapes.rb | 50 ++++++++++++++ Util/jit-hash-matrix.rb | 102 ++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 55 +++++++++++++++ 5 files changed, 296 insertions(+) create mode 100644 Util/bench/jit-hash-shapes.rb create mode 100644 Util/jit-hash-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 5af454010..c5ef284ed 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1182,6 +1182,9 @@ private bool IsInitialIVarValue(RExpr/*!*/ value) { var arrayLiteral = node as ArrayConstructor; if (arrayLiteral != null) { return EmitArrayLiteral(arrayLiteral, out type); } + var hashLiteral = node as HashConstructor; + if (hashLiteral != null) { return EmitHashLiteral(hashLiteral, out type); } + var body = node as Body; if (body != null) { if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { @@ -1322,6 +1325,52 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return IronRuby.Compiler.Methods.MakeArrayOpCall(values); } + /// + /// `{}', `{a: x}', `{"k" => v, 1 => w}': the Hash the generic body makes (HashConstructor.TransformReadCore), keys and + /// values evaluated in order, built by the same code (JitRuntime.NewHash, NewSymbolHash1..3). Only with keys the + /// runtime's comparer hashes itself (IsPlainLiteralKeyed): then building it runs no Ruby code - no #hash, no #eql? - + /// and has no effect anything could observe, so it is no obstacle to a deopt, no way into deep recursion and no + /// call that needs a stack check. A String key is copied and frozen by the helper, as the generic body's is. + /// + private MSA.Expression/*!*/ EmitHashLiteral(HashConstructor/*!*/ node, out JT type) { + var maplets = node.Maplets; + if (node.IsKeywordArguments || maplets.Length > MaxArrayLiteral || !IsPlainLiteralKeyed(node)) { + throw Bail("hash literal"); + } + var values = new List(1 + 2 * maplets.Length); + values.Add(Ast.Constant(_context)); + bool symbols = maplets.Length > 0 && maplets.Length <= 3; + foreach (var maplet in maplets) { + if (!(maplet.Key is SymbolLiteral)) { symbols = false; } + JT t; + var key = Emit(maplet.Key, out t); + values.Add(Coerce(key, t, JT.Obj)); + var value = Emit(maplet.Value, out t); + values.Add(Coerce(value, t, JT.Obj)); + } + type = JT.Obj; + if (symbols) { + return Ast.Call(JitRuntime.M("NewSymbolHash" + maplets.Length), values); + } + values.RemoveAt(0); + return Ast.Call(JitRuntime.M("NewHash"), Ast.Constant(_context), Ast.NewArrayInit(typeof(object), values)); + } + + /// + /// HashConstructor.HasPlainLiteralKeys: a Symbol or String literal, or nil, true, false or a Fixnum literal - or, + /// alone, any other numeric literal (two Float or Bignum literals of one value are told apart by #eql?). + /// + internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { + foreach (var maplet in node.Maplets) { + if (maplet.Key is SymbolLiteral || maplet.Key is StringLiteral) { continue; } + var literal = maplet.Key as Literal; + if (literal == null) { return false; } + object value = literal.Value; + if (!(value == null || value is bool || value is int) && node.Maplets.Length > 1) { return false; } + } + return true; + } + private MSA.Expression/*!*/ EmitLiteral(Literal/*!*/ literal, out JT type) { object v = literal.Value; if (v is int) { type = JT.Int; return Ast.Constant((int)v, typeof(int)); } @@ -3605,6 +3654,17 @@ private bool Walk(RExpr/*!*/ node) { return Walk(retArgs.Expressions[0]); } + // `{k => v}' with plain literal keys (JitCompiler.EmitHashLiteral): any other object, never an operand + var hashLiteral = node as HashConstructor; + if (hashLiteral != null) { + if (hashLiteral.IsKeywordArguments || hashLiteral.Maplets.Length > JitCompiler.MaxArrayLiteral || _inOperand != 0 || + !JitCompiler.IsPlainLiteralKeyed(hashLiteral)) { return No(node); } + foreach (var maplet in hashLiteral.Maplets) { + if (!Walk(maplet.Key) || !Walk(maplet.Value)) { return false; } + } + return true; + } + var arrayLiteral = node as ArrayConstructor; if (arrayLiteral != null) { var items = arrayLiteral.Arguments.Expressions; diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index ff2b4cc60..c184c8f02 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1259,6 +1259,35 @@ public static long FloatToLong(double value) { // ---- reflection handles the compiler emits --------------------------------------- + // `{k => v, ...}' in a typed body (JitCompiler.EmitHashLiteral): the Hash RubyOps.MakeHash and MakeSymbolHash1..3 + // make, of the comparer of the runtime the body was compiled for. The keys are plain literals (a Symbol, String, + // Integer, nil, true or false), which the comparer hashes without calling #hash: no Ruby code runs. + public static object NewHash(RubyContext/*!*/ context, object[]/*!*/ items) { + return RubyUtils.SetHashElements(context, new Hash(context.EqualityComparer, items.Length / 2), items); + } + + public static object NewSymbolHash1(RubyContext/*!*/ context, object key1, object value1) { + var result = Hash.CreateUnlinked(context.EqualityComparer, 1); + result.AppendUnlinked(key1, value1); + return result; + } + + public static object NewSymbolHash2(RubyContext/*!*/ context, object key1, object value1, object key2, object value2) { + var result = Hash.CreateUnlinked(context.EqualityComparer, 2); + result.AppendUnlinked(key1, value1); + result.AppendUnlinked(key2, value2); + return result; + } + + public static object NewSymbolHash3(RubyContext/*!*/ context, object key1, object value1, object key2, object value2, + object key3, object value3) { + var result = Hash.CreateUnlinked(context.EqualityComparer, 3); + result.AppendUnlinked(key1, value1); + result.AppendUnlinked(key2, value2); + result.AppendUnlinked(key3, value3); + return result; + } + internal static MethodInfo/*!*/ M(string/*!*/ name) { return typeof(JitRuntime).GetMethod(name, BindingFlags.Public | BindingFlags.Static); } diff --git a/Util/bench/jit-hash-shapes.rb b/Util/bench/jit-hash-shapes.rb new file mode 100644 index 000000000..e205ba73e --- /dev/null +++ b/Util/bench/jit-hash-shapes.rb @@ -0,0 +1,50 @@ +# What a Hash literal costs in a method the method JIT can take (JitCompiler.EmitHashLiteral): ns per call of the +# method, the caller a `while' loop. empty `{}', sym2 `{a: x, b: x + 1}', str1 `{"k" => x}', init an initialize-like +# method that stores a Hash, an Array and an argument in instance variables, default a `(x, opts = {})' called +# without opts; arr2 `[x, x + 1]' is the control (the typed body took Array literals already). +# +# ruby Util/perf/ab.rb -r 6 Util/bench/jit-hash-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# ruby Util/perf/ab.rb -i -r 1 -n 20000 Util/bench/jit-hash-shapes.rb \ +# "base=env IR_CONFIG=Release Util/perf/callgrind/count.sh ../ironruby" "new=env IR_CONFIG=Release Util/perf/callgrind/count.sh ." +# +# Every line prints the sum of its results next to its time; it must be CRuby's. +$stdout.sync = true + +class HlShapes + def empty(x) = {} + def sym2(x) = {a: x, b: x + 1} + def str1(x) = {"k" => x} + def init(x) + @h = {} + @a = [] + @x = x + x + end + def default(x, opts = {}) = opts.size + x + def arr2(x) = [x, x + 1] +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +s = HlShapes.new +N = (ENV["N"] || 1_000_000).to_i +t("empty", N) { |n| i = 0; r = 0; while i < n; r += s.empty(i).size; i += 1; end; r } +t("sym2", N) { |n| i = 0; r = 0; while i < n; r += s.sym2(i).size; i += 1; end; r } +t("str1", N) { |n| i = 0; r = 0; while i < n; r += s.str1(i).size; i += 1; end; r } +t("init", N) { |n| i = 0; r = 0; while i < n; r += s.init(i & 7); i += 1; end; r } +t("default", N) { |n| i = 0; r = 0; while i < n; r += s.default(i & 7); i += 1; end; r } +t("arr2", N) { |n| i = 0; r = 0; while i < n; r += s.arr2(i).size; i += 1; end; r } diff --git a/Util/jit-hash-matrix.rb b/Util/jit-hash-matrix.rb new file mode 100644 index 000000000..35d5fefe4 --- /dev/null +++ b/Util/jit-hash-matrix.rb @@ -0,0 +1,102 @@ +# Differential matrix for Hash literals in methods the method JIT compiles (-X:JIT, +# JitCompiler.EmitHashLiteral). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-hash-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-hash-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-hash-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Every method is called past the JIT's thresholds, then probed. Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-hash-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep hl_ +# The traps: a new Hash on every evaluation (never one shared), keys and values evaluated in +# order, a String key copied and frozen (the literal's String not kept), a deopt after the +# literal (it is no effect, so the generic body may build it again), a literal kept in an +# instance variable by `||=`, and defaults that are Hash literals. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class HL + def initialize + @n = 0 + @h = nil + end + attr_reader :n + + def hl_empty; {}; end + def hl_sym1(x); {a: x}; end + def hl_sym2(x, y); {a: x, b: y}; end + def hl_sym3(x); {a: x, b: x + 1, c: x * 2}; end + def hl_sym5(x); {a: x, b: x, c: x, d: x, e: x}; end + def hl_str(x); {"k" => x, "l" => x + 1}; end + def hl_mixed(x); {1 => x, nil => :n, true => :t, false => :f, :s => "v"}; end + def hl_float(x); {1.5 => x}; end + def hl_nested(x); {a: {b: [x, {}]}}; end + def hl_ivar(x); @h = {v: x}; @h; end + def hl_memo; @m ||= {}; end + def hl_default(x, opts = {}); opts[:seen] = x; opts; end + def hl_bignum(x); {v: x * x * x * x}; end + def hl_float_val(x); {v: x / 2.0}; end + def hl_after_effect(x); @n += 1; {v: x + 1}; end + def hl_size(x); {a: x, b: x}.size + x; end + def hl_recurse(n); n == 0 ? {} : {d: hl_recurse(n - 1)}; end +end + +o = HL.new +t("empty") { warm { o.hl_empty } } +t("empty: a new one each call") { a = o.hl_empty; b = o.hl_empty; [a.equal?(b), a.frozen?] } +t("empty: mutable") { h = o.hl_empty; h[:x] = 1; [h, o.hl_empty] } +t("sym1") { warm { |i| o.hl_sym1(i) } } +t("sym1, a String value") { o.hl_sym1("s") } +t("sym2") { warm { |i| o.hl_sym2(i, i * 2) } } +t("sym3") { warm { |i| o.hl_sym3(i) } } +t("sym3, a Float") { o.hl_sym3(1.5) } +t("sym5") { warm { |i| o.hl_sym5(i) } } +t("str keys") { warm { |i| o.hl_str(i) } } +t("str keys frozen, copies") { h = o.hl_str(1); k = h.keys; [k.map(&:frozen?), k[0].equal?(o.hl_str(1).keys[0])] } +t("mixed keys") { warm { |i| o.hl_mixed(i) } } +t("mixed: value mutable") { h = o.hl_mixed(1); h[:s] << "w"; [h[:s], o.hl_mixed(1)[:s]] } +t("float key") { warm { |i| o.hl_float(i) } } +t("nested") { warm { |i| o.hl_nested(i) } } +t("nested: fresh inner") { a = o.hl_nested(1); b = o.hl_nested(1); a[:a].equal?(b[:a]) } +t("ivar") { warm { |i| o.hl_ivar(i) }; [o.hl_ivar(3), o.instance_variable_get(:@h)] } +t("memo") { a = warm { o.hl_memo }; a[:k] = 1; [o.hl_memo, a.equal?(o.hl_memo)] } +t("default") { warm { |i| o.hl_default(i) } } +t("default: fresh each call") { a = o.hl_default(1); b = o.hl_default(2); [a, b, a.equal?(b)] } +t("default: given") { h = {z: 0}; o.hl_default(5, h); h } +t("bignum value") { warm { |i| o.hl_bignum(i) }; o.hl_bignum(100_000) } +t("float value") { warm { |i| o.hl_float_val(i) } } +t("after an effect") { p2 = HL.new; warm { |i| p2.hl_after_effect(i) }; r = p2.hl_after_effect(2**62); [r, p2.n] } +t("size") { warm { |i| o.hl_size(i) } } +t("recurse") { warm(50) { |i| o.hl_recurse(i % 5) }; h = o.hl_recurse(2000); d = 0; (d += 1; h = h[:d]) while h[:d]; d } +t("compare_by_identity off") { o.hl_str(1).compare_by_identity? } +t("default proc") { [o.hl_sym1(1).default, o.hl_sym1(1)[:zz]] } +t("class") { o.hl_empty.class } + +class HL + remove_method :hl_sym1 + def hl_sym1(x); {b: x}; end +end +t("redefined") { o.hl_sym1(9) } + +o.freeze +t("frozen self, ivar store") { o.hl_ivar(1) } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..fc0a5e1ce 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1450,6 +1450,61 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitscreen (2026-11-26) - a Hash literal in a body the method JIT compiles** (`{}`, + `{a: x}`, `{"k" => v}`, `opts = {}`) - census only, not gated. The screen refused every Hash + literal, the largest line of "JIT never, one thing only" that is not a call once the census + counts honestly (first commit below). `EmitHashLiteral` makes the Hash the generic body makes + (`HashConstructor.TransformReadCore`): keys and values in order, through the same code + (`JitRuntime.NewHash`, `NewSymbolHash1..3`, the bodies of `RubyOps.MakeHash` and + `MakeSymbolHash1..3` with the compiled-for runtime's comparer). Only with keys the comparer + hashes itself (`IsPlainLiteralKeyed`, the generic body's `HasPlainLiteralKeys`: Symbol and + String literals, nil, true, false, a Fixnum, or one other numeric literal alone): building it + then runs no Ruby code - no `#hash`, no `#eql?` - so it is no effect a deopt could repeat, no + way into deep recursion and no call that needs a stack check (fault eleven under "Faults the + gate missed" was `{self => 0}`). Up to five pairs; not a keyword-arguments hash, not an + operand of a binary operator. + JIT compiles 11.6% -> 11.9% (3,296 -> 3,370), maybe 10.3% -> 10.5% (2,923 -> 2,981), never + 78.1% -> 77.6% (22,157 -> 22,025), light frames unchanged (Src/StdLib + AWFY, 28,376 methods; + 132 methods moved up - 74 to `compiles`, 58 to `maybe` - none down) - census only, not gated. + `HashConstructor` alone 136 -> 0 of its kind left (non-plain keys and literals of more than + five pairs stay refused). Moved: mostly `initialize` methods that set `@h = {}`, `to_h` and + `marshal_dump` methods returning `{key: @ivar, ...}`, and `opts = {}` defaults; in the prelude + `NilClass#to_h`, `ObjectSpace::WeakKeyMap#initialize`, `GC.latest_compact_info`; none of AWFY. + Of the 58 to `maybe`: 33 wait for a call, 12 for a constant, 10 for an index on a parameter + the census types as an Integer, 3 the census already calls "declined once typed". + **The one exception to the rules, for the gate:** a trace of `Util/bench/app-shapes.rb` + specializes 114 -> 116 methods (`Date::Format::Bag#initialize`, `Playlist#initialize`), but + declines 29 -> 30 after the pre-screen: `CSV::FieldsConverter#initialize(options={})`, whose + `{}` default was all that kept it out, is declined for a call of `need_static_convert?` on + self after its instance-variable writes - gap 1's wall, which the unchanged build hits the + same way for the same method with `options=nil` ("a deopt after an effect (call need?)"). It + pays the declined stub's delegate hop per call. (Its `declined` line says "no reason recorded": + the per-count path does not record its reason.) AWFY traces (Json, Richards, DeltaBlue, CD, + 3 x 10): 82 specialized and 19 declined on both builds; `census.rb -c` 225 agree, 0 differ; + on app-shapes the same 15 screen differences as the baseline. + Instructions a call (`Util/perf/callgrind/count.sh`, `Util/bench/jit-hash-shapes.rb`, new): + `{}` 2248 -> 1839 (0.82), `{a: x, b: x + 1}` 3317 -> 2666 (0.80), `{"k" => x}` 3452 -> 3104 + (0.90), an initialize storing `{}`, `[]` and an argument 3021 -> 2607 (0.86), `(x, opts = {})` + called without opts 14878 -> 2027 (0.14), the control `[x, x + 1]` 1961 -> 1960. Timed + (`ab.rb`, six and eight rounds, spreads of 10-25% beside other experiments): `opts = {}` 0.74 + and 0.80, `{}` 0.87 and 0.92 (overlapping), the rest overlapping (the initialize 1.13 and + 1.06 with overlapping rounds, 0.86 by instructions). + Checked: `Util/jit-hash-matrix.rb` (new, 31 rows: a new Hash per evaluation, Symbol keys 1, 2, + 3 and 5, String keys copied and frozen, mixed and Float keys, nested literals, an instance + variable store, `@m ||= {}`, `opts = {}` fresh per call and given, a Bignum and a Float value, + a literal after an effect and a deopt, 2,000-deep recursion through a literal, redefinition, a + frozen self; every `hl_*` method but one specialized under `IR_JIT_VERBOSE=1`), and jit, + jit-calls, jit-const, hash-literal, jit-scan, jit-strlit, ivar, jit-construct, jit-rescue: + CRuby's output and the unchanged build's with the JIT on, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls`, and the unchanged build's with `IR_LIGHT_FRAMES=0`. hot-shapes and + inline-matrix (one case per process) print the unchanged build's output in every mode; each + differs from CRuby in one row on both builds (`FrozenError` for + `Encoding::CompatibilityError`; "Object must be of type Int32" for a NoMethodError). + Tried and left: `NewHash*` among the helpers a body with held-back stores may call (the + trace says "stores not held back ... a call of JitRuntime.NewSymbolHash1"), as round + strlit's literal makers were; not tried here. + For the gate: no IronRuby.Tests or spec run; the decline above. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 7b22f25e6ebc0d83abe6a65eb6c8f49692172f64 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:17:21 +0000 Subject: [PATCH 038/439] Ledger: perf/jitscreen's count of Hash literals left Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index fc0a5e1ce..3f7eb47d3 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1466,8 +1466,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has JIT compiles 11.6% -> 11.9% (3,296 -> 3,370), maybe 10.3% -> 10.5% (2,923 -> 2,981), never 78.1% -> 77.6% (22,157 -> 22,025), light frames unchanged (Src/StdLib + AWFY, 28,376 methods; 132 methods moved up - 74 to `compiles`, 58 to `maybe` - none down) - census only, not gated. - `HashConstructor` alone 136 -> 0 of its kind left (non-plain keys and literals of more than - five pairs stay refused). Moved: mostly `initialize` methods that set `@h = {}`, `to_h` and + `HashConstructor` refused at all 977 -> 331, alone 136 -> 5 (keys that are not plain literals, + and literals of more than five pairs, stay refused). Moved: mostly `initialize` methods that set `@h = {}`, `to_h` and `marshal_dump` methods returning `{key: @ivar, ...}`, and `opts = {}` defaults; in the prelude `NilClass#to_h`, `ObjectSpace::WeakKeyMap#initialize`, `GC.latest_compact_info`; none of AWFY. Of the 58 to `maybe`: 33 wait for a call, 12 for a constant, 10 for an index on a parameter From 5abb0de7f64a28189015328d4f8516a4181239b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:20:14 +0000 Subject: [PATCH 039/439] String#<<, #concat and #prepend raise FrozenError before looking at the argument A frozen String given something it could not take raised that error instead: `"b".encode("UTF-16LE").freeze << "x"` was Encoding::CompatibilityError (the three lines of Util/perf/hot-shapes-matrix.rb that differed from CRuby on master), `<< -1` and `<< 2**80` RangeError, `prepend(1)` and `prepend(Object.new)` TypeError. CRuby's rb_str_concat and rb_str_update check that the receiver can be modified first, so every one of these is FrozenError there; #insert checks the encodings first in both. MutableString.MutateAppend checks frozenness when the encodings are incompatible, before it raises; String#<< of an Integer checks it before a RangeError and before ToChr, whose code may be refused; the prelude's #prepend checks it before converting. Nothing is added to the path that appends: each check is on a way to an error or on the slow path of an Integer that is not an ASCII or byte code. Left: `frozen << Object.new` is still TypeError (the conversion to String is the binder's, before the method runs), and #tr! raises FrozenError where CRuby checks the encodings first. Checked: String_AppendFrozenFirst1 (new; CRuby 4.0's output); hot-shapes-matrix prints CRuby's output; spec/core/string append, concat, prepend, insert, plus, encode, replace, squeeze, tr: no failure, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 28 ++++++++++++++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 6 +++++ Src/Ruby/Builtins/MutableString.cs | 8 ++++++- Src/StdLib/ironruby/ruby4.rb | 2 ++ 5 files changed, 44 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a0370837f..825b482f4 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -169,6 +169,7 @@ public Tests(Driver/*!*/ driver) { String_CharacterBoundaries1, String_NonCharacter1, String_SuccSeparators1, + String_AppendFrozenFirst1, String_CountDeleteSqueeze1, String_CountDeleteSqueeze2, String_CountDeleteSqueeze3, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index e6cf1649f..62d306ad6 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -356,6 +356,34 @@ p t.chars.map(&:ord) /// computes when it is parsed, negation and intersection included; anything else goes /// through the selector's sets and ranges as before. /// + /// + /// String#<<, #concat and #prepend check that the receiver can be modified before they look at what they are given + /// (MRI's rb_str_concat, rb_str_update): a frozen string raises FrozenError rather than the encoding, range or + /// conversion error the argument would bring. #insert checks the encodings first, as MRI's does. + /// + public void String_AppendFrozenFirst1() { + TestOutput(@" +require 'ruby4' +c = ""b"".encode(""UTF-16LE"").freeze +[-> { c << ""x"" }, -> { c.concat(""x"") }, -> { c.prepend(""x"") }, -> { c.prepend(1) }, -> { c << -1 }, + -> { c << 2**80 }, -> { c << 0x110000 }, -> { ""b"".freeze.prepend(Object.new) }, -> { c.insert(0, ""x"") }, + -> { c.dup << ""x"" }].each { |l| p((l.call rescue $!)) } +d = +""ab""; d << ""c"" << 0x64; p d +", @" +# +# +# +# +# +# +# +# +# +# +""abcd"" +"); + } + /// /// A carry out of a wrapped digit or letter skips over a separator to the next /// alphanumeric only when the two are of the same kind (rb_str_succ). diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index e72793c5f..ad5e774b3 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -788,6 +788,8 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { [RubyMethod("concat")] public static MutableString/*!*/ Append(MutableString/*!*/ self, int c) { if (c < 0) { + // MRI's rb_str_concat checks the receiver first: a frozen string raises FrozenError whatever it is given + self.RequireNotFrozen(); throw RubyExceptions.CreateRangeError("{0} out of char range", c); } @@ -807,12 +809,16 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { self.ForceEncoding(RubyEncoding.Binary); return self.Append((byte)c); } + // (ToChr may refuse the code: the frozen check comes first, as above) + self.RequireNotFrozen(); return self.Append(Integer.ToChr(self.Encoding, self.Encoding, c)); } [RubyMethod("<<")] [RubyMethod("concat")] public static MutableString/*!*/ Append(MutableString/*!*/ self, [NotNull]BigInteger/*!*/ c) { + self.RequireNotFrozen(); + // A code above the int range is still a number of 32 bits to MRI's rb_str_concat, and // a character where the encoding has one that wide: 0x8431A430 in GB18030. A wider // one that is still a Fixnum in MRI is named in the message. diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index d35427371..285b84468 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -800,7 +800,13 @@ private void MutateAppend(int appendCount) { /// True if all of is added, false for a part of it. /// How many of 's items are added (see FrozenOrCopyOnWrite). private void MutateAppend(MutableString/*!*/ other, bool whole, int appendCount) { - RubyEncoding newEncoding = RequireCompatibleEncoding(other); + RubyEncoding newEncoding = GetCompatibleEncoding(other); + if (newEncoding == null) { + // MRI's rb_str_append checks that the receiver can be modified before the encodings (str_modify_keep_cr in + // rb_enc_cr_str_buf_cat): a frozen string raises FrozenError whatever it is given. + RequireNotFrozen(); + throw RubyExceptions.CreateEncodingCompatibilityError(_encoding, other.Encoding); + } // an empty string is ASCII and has no surrogates, whether or not that has been worked out: bool isEmpty = _content.IsEmpty; diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 9d7e90999..789e5a4b9 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3899,6 +3899,8 @@ def __ir_rpartition__(pattern) private :__ir_rpartition__ def prepend(*others) + # MRI's rb_str_update checks the receiver before it converts or looks at what is prepended + __ir_require_unfrozen__ others = others.map do |o| # #to_str only: MRI will not call #to_s to find something to prepend. converted = o.is_a?(::String) ? o : ::String.try_convert(o) From 25e89f334448fddd1b74a197c1dad9ca411e4d9c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:24:05 +0000 Subject: [PATCH 040/439] Enter a light method's scoped twin after its first late scope (IR_LIGHT_TWIN) A light frame that makes its scope late pays for the light frame and the scope, about 230 instructions a call more than the same method scoped at entry (gap 16). The late scope's node now tells a LightFrameTwin, a constant of the compiled light body; the first time it does so in compiled code, the twin transforms the same AST with its scope (TransformBody's scopedTwin) and compiles it to IL, and the light body's lambda forwards to it at its top, outside its frame record. Measured with Util/perf/callgrind/count.sh it saves nothing: the twin costs what a scoped method does, but the forward costs what it saves (the light lambda's prologue zeroes its locals, +158, and the delegate hop, +56); light-rest-matrix's caller_locations(0, 1) also counts one frame too few under it. Reverted in the next commit; see Util/perf/LEDGER.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 89 +++++++++++++++++-- Src/Ruby/Runtime/LightFrameTwin.cs | 80 +++++++++++++++++ 2 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 Src/Ruby/Runtime/LightFrameTwin.cs diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index c31a62eec..67e3c1b1c 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -200,9 +200,11 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin /// /// : whether the body may be a light frame (see TransformLightFrame), /// whose scope description is an object constant - so not where the body is compiled ahead of time. + /// : the body of a light frame's scoped twin (LightFrameTwin): everything a body that may be + /// light gets but the light frame. /// private MSA.LambdaExpression/*!*/ TransformBody(AstGenerator/*!*/ gen, MSA.Expression/*!*/ declaringScope, MSA.Expression/*!*/ declaringModule, - string/*!*/ frameLabel, StrongBox definitionRefinements, bool allowLightFrame) { + string/*!*/ frameLabel, StrongBox definitionRefinements, bool allowLightFrame, bool scopedTwin = false) { string encodedName = RubyStackTraceBuilder.EncodeMethodName(frameLabel, gen.SourcePath, Location, gen.DebugMode); // a body built on demand adds its locals to the scope: build it before they are allocated @@ -303,13 +305,15 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin statements = Ast.Block(optionalsInitialization, statements); optionalsInitialization = AstUtils.Empty(); } - if (allowLightFrame && LightFramesEnabled && definitionRefinements == null && gen.Profiler == null && !gen.TraceEnabled && + LightFrameTwin twin = null; + if (allowLightFrame && !scopedTwin && LightFramesEnabled && definitionRefinements == null && gen.Profiler == null && !gen.TraceEnabled && !gen.CompilerOptions.IsEval && !scope.HasClosures && IsLightFrameCandidate()) { + twin = MakeTwin(gen, declaringScope, declaringModule, frameLabel); light = TransformLightFrame(gen, scope, scopeVariable, selfParameter, blockParameter, declaringScope, declaringModule, - visiblePrameterCountAndSignatureFlags, parkSlot, ref statements); + visiblePrameterCountAndSignatureFlags, parkSlot, twin, ref statements); } if ((LightFramesWhy || gen.Census != null) && light == null) { - string why = !(allowLightFrame && LightFramesEnabled) ? "not allowed" : + string why = !(allowLightFrame && LightFramesEnabled) ? "not allowed" : scopedTwin ? "a light frame's scoped twin" : definitionRefinements != null ? "refinements" : gen.Profiler != null ? "profiler" : gen.TraceEnabled ? "trace" : gen.CompilerOptions.IsEval ? "eval" : scope.HasClosures ? "defines a closure (block literal)" : WhyNotLightFrameCandidate() ?? "body needs its scope after the rewrite"; @@ -443,7 +447,75 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin gen.LeaveMethodDefinition(); - return CreateLambda(encodedName, parameters, new CompiledFrameExpression(body, encodedName, Location.Start.Line)); + var lambda = CreateLambda(encodedName, parameters, new CompiledFrameExpression(body, encodedName, Location.Start.Line)); + if (twin != null) { + lambda = ForwardToTwin(lambda, twin, light != null); + } + return lambda; + } + + /// + /// IR_LIGHT_TWIN=0 keeps a light frame that makes its scope late light for good (see LightFrameTwin): otherwise its compiled + /// code calls the method compiled with its scope from its first late scope on. + /// + internal static readonly bool LightTwinEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_TWIN") != "0"; + + private static readonly MethodInfo/*!*/ _ScopeMadeLate = typeof(LightFrameTwin).GetMethod(nameof(LightFrameTwin.ScopeMadeLate)); + + /// + /// The twin a light body compiles when it first makes its scope late: the same method, for the same declaring scope and + /// module, with its scope. Null where the body has no such twin: the switch is off, the declaring scope and module are not + /// constants (a body compiled ahead of time), or the method's calls are counted for Coverage. + /// + private LightFrameTwin MakeTwin(AstGenerator/*!*/ gen, MSA.Expression/*!*/ declaringScopeExpression, MSA.Expression/*!*/ declaringModuleExpression, + string/*!*/ frameLabel) { + var declaringScope = ConstantValue(declaringScopeExpression) as RubyScope; + var declaringModule = ConstantValue(declaringModuleExpression) as RubyModule; + if (!LightTwinEnabled || declaringScope == null || declaringModule == null || gen.Coverage != null || gen.MethodCoverage != null || + gen.Census != null) { + return null; + } + var context = gen.Context; + var document = gen.Document; + var encoding = gen.Encoding; + return new LightFrameTwin(frameLabel, () => { + MSA.LambdaExpression lambda; + // the AST is the light body's, which other compilations of the method transform too (RubyMethodBody locks itself) + lock (this) { + var twinGen = new AstGenerator(context, new RubyCompilerOptions(), document, encoding, false); + lambda = TransformBody(twinGen, ExactConstant(declaringScope, typeof(RubyScope)), ExactConstant(declaringModule, typeof(RubyModule)), + frameLabel, null, true, true); + } + // to IL at once, not light-compiled: only a compiled light body asks for it, after enough calls to compile it + return lambda.Compile(); + }); + } + + /// + /// `Twin != null ? Twin(self, block, args...) : body' at the light body's entry, outside its frame's record, so that a + /// backtrace has the twin's frame and not this one's - and only in compiled code (an interpreted frame is in a backtrace + /// whatever it does). Not for a body whose parameters come in an object[] (CreateLambda): it keeps no twin. + /// + private static MSA.LambdaExpression/*!*/ ForwardToTwin(MSA.LambdaExpression/*!*/ lambda, LightFrameTwin/*!*/ twin, bool isLight) { + if (!isLight || lambda.Type == typeof(Func)) { + twin.Disable(); + return lambda; + } + twin.DelegateType = lambda.Type; + var twinField = Ast.Field(Ast.Constant(twin), nameof(LightFrameTwin.Twin)); + return Ast.Lambda(lambda.Type, + Ast.Condition( + Ast.AndAlso( + Ast.ReferenceEqual(EnterInterpretedFrameExpression.Instance, AstUtils.Constant(null, typeof(Microsoft.Scripting.Interpreter.InterpretedFrame))), + Ast.ReferenceNotEqual(twinField, AstUtils.Constant(null, typeof(Delegate))) + ), + Ast.Invoke(Ast.Convert(twinField, lambda.Type), lambda.Parameters), + lambda.Body, + lambda.ReturnType + ), + lambda.Name, + lambda.Parameters + ); } #region Light frames @@ -1512,7 +1584,8 @@ private static bool AreScopeFree(Arguments arguments, bool blockLiterals, Strong /// private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ scope, MSA.ParameterExpression/*!*/ scopeVariable, MSA.Expression/*!*/ selfParameter, MSA.Expression/*!*/ blockParameter, MSA.Expression/*!*/ declaringScope, - MSA.Expression/*!*/ declaringModule, int visibleParameterCountAndSignatureFlags, ParkedScopeSlot parkSlot, ref MSA.Expression/*!*/ statements) { + MSA.Expression/*!*/ declaringModule, int visibleParameterCountAndSignatureFlags, ParkedScopeSlot parkSlot, LightFrameTwin twin, + ref MSA.Expression/*!*/ statements) { var names = scope.GetVariableNamesExpression() as MSA.ConstantExpression; if (names == null) { @@ -1546,6 +1619,10 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ ) ) : make(Methods.CreateMethodScopeLazy, scope.LocalsTupleVariable); + if (twin != null) { + // the first late scope compiles the scoped twin the next calls go to (LightFrameTwin) + light.MakeScope = Ast.Block(Ast.Call(Ast.Constant(twin), _ScopeMadeLate, EnterInterpretedFrameExpression.Instance), light.MakeScope); + } light.MakeScopeIfTraced = locals => make(Methods.CreateMethodScopeIfTraced, locals); var inLoop = scope.DefineHiddenVariable("#in-loop", typeof(bool)); light.LazyScope = Ast.Coalesce(scopeVariable, Ast.Assign(scopeVariable, Ast.Call(_LightScopeInLoop, light.MakeScope, inLoop))); diff --git a/Src/Ruby/Runtime/LightFrameTwin.cs b/Src/Ruby/Runtime/LightFrameTwin.cs new file mode 100644 index 000000000..276c3e2c1 --- /dev/null +++ b/Src/Ruby/Runtime/LightFrameTwin.cs @@ -0,0 +1,80 @@ +/* **************************************************************************** + * + * A light frame's scoped twin (gap 16 of Util/perf/LEDGER.md; IR_LIGHT_TWIN). + * + * A light frame that makes its scope late - a call whose light site answered + * RubyOps.LightScopeRequired, `binding', a `return' from a block - pays for the light + * frame and for the scope: the late scope's arm in the body, CreateMethodScopeLazy, the + * light frame's exit, about 230 instructions a call more than the same method with its + * scope made at entry (`s.gsub(/b/, "x")'). The first time a compiled light body makes its + * scope late, it compiles the same method with its scope (MethodDefinition.TransformBody + * with scopedTwin), and from then on its compiled code calls that twin at its entry and + * returns what it returns. The forward is outside the light body's frame record + * (CompiledFrameExpression), so a backtrace has the twin's frame only; an interpreted light + * body does not forward, since every interpreted frame is in a backtrace. + * + * The twin is one per compiled body, which is per runtime (its declaring scope is baked in). + * Twin is written once, by the thread that compiled it, and read without a lock: a call + * that reads it null runs the light body, which is right, only slower. + * + * ***************************************************************************/ + +using System; +using System.Threading; + +namespace IronRuby.Runtime { + public sealed class LightFrameTwin { + /// The method compiled with its scope, of the light body's delegate type; null until the first late scope. + public Delegate Twin; + + private Func _compile; + private int _state; + private readonly string/*!*/ _name; + + /// IR_LIGHT_TWIN=verbose names each twin compiled on stderr. + private static readonly bool Verbose = Environment.GetEnvironmentVariable("IR_LIGHT_TWIN") == "verbose"; + + /// The light body's delegate type, set once its lambda is made (MethodDefinition.ForwardToTwin). + internal Type DelegateType; + + internal LightFrameTwin(string/*!*/ name, Func/*!*/ compile) { + _name = name; + _compile = compile; + } + + /// The light body does not forward (it needs its scope after all, or takes its parameters in an array). + internal void Disable() { + _state = 1; + _compile = null; + } + + /// + /// The light body is making its scope late: compile the twin, once, if the body is compiled (it has had calls enough for + /// the light compiler to compile it). A compilation that fails, or gives another delegate type, leaves the method light. + /// + public void ScopeMadeLate(Microsoft.Scripting.Interpreter.InterpretedFrame interpretedFrame) { + // only a compiled light body forwards: one that is still interpreted has had few calls, and may not have many + if (interpretedFrame != null || _state != 0 || Interlocked.CompareExchange(ref _state, 1, 0) != 0) { + return; + } + var compile = _compile; + _compile = null; + Delegate twin; + try { + twin = compile(); + } catch (Exception e) { + if (Verbose) { + Console.Error.WriteLine("[twin] {0}: {1}", _name, e.Message); + } + return; + } + bool published = twin != null && twin.GetType() == DelegateType; + if (published) { + Volatile.Write(ref Twin, twin); + } + if (Verbose) { + Console.Error.WriteLine("[twin] {0}: {1}", _name, published ? "scoped from now on" : "not published"); + } + } + } +} From 6b1571e8a9c1d4a802b4be297d95d40a5f3533ee Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:24:05 +0000 Subject: [PATCH 041/439] Revert "Enter a light method's scoped twin after its first late scope (IR_LIGHT_TWIN)" Rejected by perf/lsite2's measurements: the regex shapes still lose 1.7-2.8% against a scope made at entry, inject(:+) and zip count 2.2% and 0.7% more with it, Pathname#+ (a twin for a method that needs its scope only sometimes) 0.5% more, and light-rest-matrix differs from CRuby on caller_locations. Util/perf/LEDGER.md (Rejected, perf/lsite2). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 89 ++----------------- Src/Ruby/Runtime/LightFrameTwin.cs | 80 ----------------- 2 files changed, 6 insertions(+), 163 deletions(-) delete mode 100644 Src/Ruby/Runtime/LightFrameTwin.cs diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 67e3c1b1c..c31a62eec 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -200,11 +200,9 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin /// /// : whether the body may be a light frame (see TransformLightFrame), /// whose scope description is an object constant - so not where the body is compiled ahead of time. - /// : the body of a light frame's scoped twin (LightFrameTwin): everything a body that may be - /// light gets but the light frame. /// private MSA.LambdaExpression/*!*/ TransformBody(AstGenerator/*!*/ gen, MSA.Expression/*!*/ declaringScope, MSA.Expression/*!*/ declaringModule, - string/*!*/ frameLabel, StrongBox definitionRefinements, bool allowLightFrame, bool scopedTwin = false) { + string/*!*/ frameLabel, StrongBox definitionRefinements, bool allowLightFrame) { string encodedName = RubyStackTraceBuilder.EncodeMethodName(frameLabel, gen.SourcePath, Location, gen.DebugMode); // a body built on demand adds its locals to the scope: build it before they are allocated @@ -305,15 +303,13 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin statements = Ast.Block(optionalsInitialization, statements); optionalsInitialization = AstUtils.Empty(); } - LightFrameTwin twin = null; - if (allowLightFrame && !scopedTwin && LightFramesEnabled && definitionRefinements == null && gen.Profiler == null && !gen.TraceEnabled && + if (allowLightFrame && LightFramesEnabled && definitionRefinements == null && gen.Profiler == null && !gen.TraceEnabled && !gen.CompilerOptions.IsEval && !scope.HasClosures && IsLightFrameCandidate()) { - twin = MakeTwin(gen, declaringScope, declaringModule, frameLabel); light = TransformLightFrame(gen, scope, scopeVariable, selfParameter, blockParameter, declaringScope, declaringModule, - visiblePrameterCountAndSignatureFlags, parkSlot, twin, ref statements); + visiblePrameterCountAndSignatureFlags, parkSlot, ref statements); } if ((LightFramesWhy || gen.Census != null) && light == null) { - string why = !(allowLightFrame && LightFramesEnabled) ? "not allowed" : scopedTwin ? "a light frame's scoped twin" : + string why = !(allowLightFrame && LightFramesEnabled) ? "not allowed" : definitionRefinements != null ? "refinements" : gen.Profiler != null ? "profiler" : gen.TraceEnabled ? "trace" : gen.CompilerOptions.IsEval ? "eval" : scope.HasClosures ? "defines a closure (block literal)" : WhyNotLightFrameCandidate() ?? "body needs its scope after the rewrite"; @@ -447,75 +443,7 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin gen.LeaveMethodDefinition(); - var lambda = CreateLambda(encodedName, parameters, new CompiledFrameExpression(body, encodedName, Location.Start.Line)); - if (twin != null) { - lambda = ForwardToTwin(lambda, twin, light != null); - } - return lambda; - } - - /// - /// IR_LIGHT_TWIN=0 keeps a light frame that makes its scope late light for good (see LightFrameTwin): otherwise its compiled - /// code calls the method compiled with its scope from its first late scope on. - /// - internal static readonly bool LightTwinEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_TWIN") != "0"; - - private static readonly MethodInfo/*!*/ _ScopeMadeLate = typeof(LightFrameTwin).GetMethod(nameof(LightFrameTwin.ScopeMadeLate)); - - /// - /// The twin a light body compiles when it first makes its scope late: the same method, for the same declaring scope and - /// module, with its scope. Null where the body has no such twin: the switch is off, the declaring scope and module are not - /// constants (a body compiled ahead of time), or the method's calls are counted for Coverage. - /// - private LightFrameTwin MakeTwin(AstGenerator/*!*/ gen, MSA.Expression/*!*/ declaringScopeExpression, MSA.Expression/*!*/ declaringModuleExpression, - string/*!*/ frameLabel) { - var declaringScope = ConstantValue(declaringScopeExpression) as RubyScope; - var declaringModule = ConstantValue(declaringModuleExpression) as RubyModule; - if (!LightTwinEnabled || declaringScope == null || declaringModule == null || gen.Coverage != null || gen.MethodCoverage != null || - gen.Census != null) { - return null; - } - var context = gen.Context; - var document = gen.Document; - var encoding = gen.Encoding; - return new LightFrameTwin(frameLabel, () => { - MSA.LambdaExpression lambda; - // the AST is the light body's, which other compilations of the method transform too (RubyMethodBody locks itself) - lock (this) { - var twinGen = new AstGenerator(context, new RubyCompilerOptions(), document, encoding, false); - lambda = TransformBody(twinGen, ExactConstant(declaringScope, typeof(RubyScope)), ExactConstant(declaringModule, typeof(RubyModule)), - frameLabel, null, true, true); - } - // to IL at once, not light-compiled: only a compiled light body asks for it, after enough calls to compile it - return lambda.Compile(); - }); - } - - /// - /// `Twin != null ? Twin(self, block, args...) : body' at the light body's entry, outside its frame's record, so that a - /// backtrace has the twin's frame and not this one's - and only in compiled code (an interpreted frame is in a backtrace - /// whatever it does). Not for a body whose parameters come in an object[] (CreateLambda): it keeps no twin. - /// - private static MSA.LambdaExpression/*!*/ ForwardToTwin(MSA.LambdaExpression/*!*/ lambda, LightFrameTwin/*!*/ twin, bool isLight) { - if (!isLight || lambda.Type == typeof(Func)) { - twin.Disable(); - return lambda; - } - twin.DelegateType = lambda.Type; - var twinField = Ast.Field(Ast.Constant(twin), nameof(LightFrameTwin.Twin)); - return Ast.Lambda(lambda.Type, - Ast.Condition( - Ast.AndAlso( - Ast.ReferenceEqual(EnterInterpretedFrameExpression.Instance, AstUtils.Constant(null, typeof(Microsoft.Scripting.Interpreter.InterpretedFrame))), - Ast.ReferenceNotEqual(twinField, AstUtils.Constant(null, typeof(Delegate))) - ), - Ast.Invoke(Ast.Convert(twinField, lambda.Type), lambda.Parameters), - lambda.Body, - lambda.ReturnType - ), - lambda.Name, - lambda.Parameters - ); + return CreateLambda(encodedName, parameters, new CompiledFrameExpression(body, encodedName, Location.Start.Line)); } #region Light frames @@ -1584,8 +1512,7 @@ private static bool AreScopeFree(Arguments arguments, bool blockLiterals, Strong /// private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ scope, MSA.ParameterExpression/*!*/ scopeVariable, MSA.Expression/*!*/ selfParameter, MSA.Expression/*!*/ blockParameter, MSA.Expression/*!*/ declaringScope, - MSA.Expression/*!*/ declaringModule, int visibleParameterCountAndSignatureFlags, ParkedScopeSlot parkSlot, LightFrameTwin twin, - ref MSA.Expression/*!*/ statements) { + MSA.Expression/*!*/ declaringModule, int visibleParameterCountAndSignatureFlags, ParkedScopeSlot parkSlot, ref MSA.Expression/*!*/ statements) { var names = scope.GetVariableNamesExpression() as MSA.ConstantExpression; if (names == null) { @@ -1619,10 +1546,6 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ ) ) : make(Methods.CreateMethodScopeLazy, scope.LocalsTupleVariable); - if (twin != null) { - // the first late scope compiles the scoped twin the next calls go to (LightFrameTwin) - light.MakeScope = Ast.Block(Ast.Call(Ast.Constant(twin), _ScopeMadeLate, EnterInterpretedFrameExpression.Instance), light.MakeScope); - } light.MakeScopeIfTraced = locals => make(Methods.CreateMethodScopeIfTraced, locals); var inLoop = scope.DefineHiddenVariable("#in-loop", typeof(bool)); light.LazyScope = Ast.Coalesce(scopeVariable, Ast.Assign(scopeVariable, Ast.Call(_LightScopeInLoop, light.MakeScope, inLoop))); diff --git a/Src/Ruby/Runtime/LightFrameTwin.cs b/Src/Ruby/Runtime/LightFrameTwin.cs deleted file mode 100644 index 276c3e2c1..000000000 --- a/Src/Ruby/Runtime/LightFrameTwin.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* **************************************************************************** - * - * A light frame's scoped twin (gap 16 of Util/perf/LEDGER.md; IR_LIGHT_TWIN). - * - * A light frame that makes its scope late - a call whose light site answered - * RubyOps.LightScopeRequired, `binding', a `return' from a block - pays for the light - * frame and for the scope: the late scope's arm in the body, CreateMethodScopeLazy, the - * light frame's exit, about 230 instructions a call more than the same method with its - * scope made at entry (`s.gsub(/b/, "x")'). The first time a compiled light body makes its - * scope late, it compiles the same method with its scope (MethodDefinition.TransformBody - * with scopedTwin), and from then on its compiled code calls that twin at its entry and - * returns what it returns. The forward is outside the light body's frame record - * (CompiledFrameExpression), so a backtrace has the twin's frame only; an interpreted light - * body does not forward, since every interpreted frame is in a backtrace. - * - * The twin is one per compiled body, which is per runtime (its declaring scope is baked in). - * Twin is written once, by the thread that compiled it, and read without a lock: a call - * that reads it null runs the light body, which is right, only slower. - * - * ***************************************************************************/ - -using System; -using System.Threading; - -namespace IronRuby.Runtime { - public sealed class LightFrameTwin { - /// The method compiled with its scope, of the light body's delegate type; null until the first late scope. - public Delegate Twin; - - private Func _compile; - private int _state; - private readonly string/*!*/ _name; - - /// IR_LIGHT_TWIN=verbose names each twin compiled on stderr. - private static readonly bool Verbose = Environment.GetEnvironmentVariable("IR_LIGHT_TWIN") == "verbose"; - - /// The light body's delegate type, set once its lambda is made (MethodDefinition.ForwardToTwin). - internal Type DelegateType; - - internal LightFrameTwin(string/*!*/ name, Func/*!*/ compile) { - _name = name; - _compile = compile; - } - - /// The light body does not forward (it needs its scope after all, or takes its parameters in an array). - internal void Disable() { - _state = 1; - _compile = null; - } - - /// - /// The light body is making its scope late: compile the twin, once, if the body is compiled (it has had calls enough for - /// the light compiler to compile it). A compilation that fails, or gives another delegate type, leaves the method light. - /// - public void ScopeMadeLate(Microsoft.Scripting.Interpreter.InterpretedFrame interpretedFrame) { - // only a compiled light body forwards: one that is still interpreted has had few calls, and may not have many - if (interpretedFrame != null || _state != 0 || Interlocked.CompareExchange(ref _state, 1, 0) != 0) { - return; - } - var compile = _compile; - _compile = null; - Delegate twin; - try { - twin = compile(); - } catch (Exception e) { - if (Verbose) { - Console.Error.WriteLine("[twin] {0}: {1}", _name, e.Message); - } - return; - } - bool published = twin != null && twin.GetType() == DelegateType; - if (published) { - Volatile.Write(ref Twin, twin); - } - if (Verbose) { - Console.Error.WriteLine("[twin] {0}: {1}", _name, published ? "scoped from now on" : "not published"); - } - } - } -} From 50844335d5f9f83c5540b1efe3fb9e5dd02e1b4b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:24:05 +0000 Subject: [PATCH 042/439] perf/lsite2: record the scoped twin as rejected The idea perf/lsite left under gap 16 - a light method that has made its scope late enters through its scoped body from then on - was built as a forward at the top of the light body to a twin compiled with its scope. The twin costs what a scoped method does; the forward costs what it saves, because the light lambda zeroes its locals in its prologue before any test. The ledger has the profile, the numbers, the caller_locations fault light-rest-matrix found, and what is left (rules that reach the twin without the light lambda, and a policy for a method that needs its scope only sometimes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/perf/LEDGER.md | 67 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 5 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..fc12fab45 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -984,11 +984,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has about the floor for one shape there. Tried and rejected (perf/lsite, see Rejected): a site that has answered `LightScopeRequired` remembers it and skips the light site from then on - the light site is +7 of the +232 instructions a light `gsub` pays; the rest is - the late scope's arm in the body and the light frame's exit. Untried: a light method - that has made its scope late once enters through its scoped body from then on (a - per-method memory, compiled twice); or the prelude gives such a method's rare path a - method of its own, so that the common path stays without a splat or a scope-reading - callee (`/perf-core`). + the late scope's arm in the body and the light frame's exit. Also tried and rejected + (perf/lsite2): a light method that has made its scope late once forwards, at the top of + its compiled body, to a scoped twin compiled from the same AST - the twin costs what a + scoped method does, but the forward costs what it saves (the light lambda's prologue, + which zeroes its locals before the first test, +158, and the delegate hop, +56). + Untried: calls reach the twin without entering the light lambda - the method's delegate + replaced and its rules rebound (not through `MethodsUpdated`, which invalidates all + compiled code), with a policy for a method that needs its scope only sometimes; or the + prelude gives such a method's rare path a method of its own, so that the common path + stays without a splat or a scope-reading callee (`/perf-core`). The second: `w_splat` is 366 ns against 188 for the bare call (CRuby 194 and 71), and still about 185 B a call more than the block-passing wrapper: the rest Array the caller's rule builds and its unpacking into the callee. Untried: a rule for a splat @@ -4549,6 +4554,58 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/lsite2 (/perf-step, 2026-11-26) - a light method that has made its scope late + enters through a scoped twin from then on** (gap 16; switch `IR_LIGHT_TWIN`, `=verbose` + names each twin). Built on the merged branch at 2f8c31c. A `LightFrameTwin`, a constant of + each compiled light body (not one compiled ahead of time, nor under Coverage), is told by + the late scope's node (`LightFrame.MakeScope`) that the body made its scope; the first time + that happens in compiled code (an interpreted body has had few calls) it transforms the + same AST for the same declaring scope and module with `scopedTwin` (everything a body that + may be light gets, parked scopes included, but the light frame), compiles it to IL and + publishes it. The light body's lambda becomes `frame == null && twin.Twin != null ? + Twin(self, block, args...) : `, the test outside its `CompiledFrameExpression`, so a + backtrace has the twin's frame only. Behaviour and backtraces matched CRuby + (`light-remember-matrix` and the others below). + - First cut light-compiled the twin (`RubyScriptCode.CompileLambda`): the forward then went + through the `LightLambda` stand-in on every call, and every late scope at start-up compiled + a twin (56 methods by `ir -e` of the shape file: `Gem::Version#canonical_segments`, + `Enumerable#each_with_index`, `Kernel#__require_relative__`...). Twins are now compiled to + IL and only from compiled light code: two (`H#gsub`, `H#eqt`) in the same run. + - **Numbers** (instructions a call, `Util/perf/callgrind/count.sh`, N=20,000; twin off -> + on): `gsub` all 12,948 -> 12,933 (on 12,715: all/on 1.017), `split` 11,037 -> 11,099 + (1.027), `case when /z/` 8,946 -> 8,863 (1.028), `=~ /d/` 6,061 -> 6,016 (1.026); + controls `size` and `tilde` unchanged, `match?` 4,047 -> 4,079, `Pathname#+` 99,960 -> + 100,486 (`Pathname#+` got a twin: it needs its scope on some calls only, and now pays a + scope and the forward on all of them). core-small (`IR_LIGHT_FRAMES=0` / twin off / on): + `inject_sym` 9,232 / 9,133 / 9,333, `zip` 13,131 / 13,132 / 13,229, `inject` with a block + 10,258 / 10,279 / 10,284, `minmax` 4,757 / 4,504 / 4,531. + - **Why: the forward costs what it saves.** callgrind with the CLR's perf map, one `gsub` + section, twin on against `on` (scope at entry): +214 a call, all of it the forward - the + light lambda +158, a delegate hop +56; the twin's own costs are `on`'s to the instruction + (`CreateMethodScope`, `LeaveMethodFrame`, the body). The light lambda pays its prologue + before its first test: the CLR zeroes its locals (each call site's `#a`/`#r` temporaries, + the tuple, `#rfc`, `#callee`...) whatever path it takes, and that is most of what a light + frame that makes its scope late loses. A forward placed anywhere in the light body cannot + win; the calls have to reach the twin without it. The delegate rules call is + `RubyMethodBody.GetDelegate`'s, baked into call plans (`RubyMethodCallPlan._method`) and + dispatchers, behind the JIT's stub until it settles; the one way to make every site + rebind, `RubyModule.MethodsUpdated`, bumps the global method version and invalidates all + compiled code (`RubyUtils.InvalidateCompiledCode`), too much to pay per twin. Nor is "the + first late scope" a policy: `Pathname#+` shows a method that needs its scope now and + then losing its light frame for good. + - **And it was not right.** light-remember, regex-light, block-given, global-light and + lexical-light printed CRuby 4.0's output on the baseline and the candidate, each as + built, with `IR_LIGHT_TWIN=0`, `IR_LIGHT_FRAMES=0`, `IR_LIGHT_REGEX=all`, `-X:NoJIT + -X:NoOSR` and `-X:NoJITCalls`, and hot-shapes the baseline's (its known + `Encoding::CompatibilityError`). light-rest did not, wherever the twin was on (as built, + `IR_LIGHT_REGEX=all`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`): `def frame_locations(*a); + caller_locations(0, 1)[0].label; end` answered `"Kernel#caller_locations"` as well as + `"Object#frame_locations"` once the twin took over - a frame counted that should not be + (the forwarding CLR frame, or the twin's call of `caller_locations` made through another + site than the light body's late call). A twin would have to answer frame questions as the + method it stands in for; the matrix caught it, keep it in any next attempt. + Not run: `IR_CONFIG=R2R` start-up, census (nothing kept). + - **perf/lsite (/perf-step, 2026-11-26) - a light site that remembers it needed the scope** (gap 16; switch `IR_LIGHT_REMEMBER`). In `LightFrameRewriter.MakeLightCall`, each site got a box (`StrongBox`, a constant of the body like a regex literal's cache, set From cc99ebeb29470aaf506036cb3a0140b7e8a025f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:25:50 +0000 Subject: [PATCH 043/439] Singleton class lookups answered from the superclass's cache Each definition on an object that gets methods of its own (OpenStruct's define_singleton_method! of every member) re-versions its singleton class and so empties that class's method lookup cache. Every name asked again (the singleton_method_added hook check, respond_to?, the shared rules' version test) then walked the ancestors under the class hierarchy lock and copied the cache's whole table to file one entry: about thirty lookups per OpenStruct, a table copy each. A singleton class of a plain object with no modules of its own and few methods now keeps a snapshot of its own method names per version and answers every other name from its superclass's cache, which stays warm across all such objects, without the lock and without filing. The superclass's fill registered the answer for invalidation, so a definition of that name re-versions the singleton class; a definition of a name nobody asked for does not, so every change of a module's method table or modules drops the snapshot under the lock, and the reader checks the snapshot is still current after taking the superclass's answer. The shared rule's test (RubyCallAction.TryShareVersion) takes a new version from this cache when it finds the rule's method there with a visibility the call sees, before resolving under the lock. IR_SINGLETON_LOOKUP=0 turns both off. Util/sdef-matrix.rb section 12: lookups on fresh and re-versioned singleton classes around a name defined that nobody had asked for, undef/remove, private in the singleton, a private forwarder in a subclass, protected, respond_to_missing? and method_missing added later, the singleton_method_added hook, include/prepend into the singleton class, extend with `extended`, a refinement, and two threads defining while a third asks. It prints CRuby 4.0's output on both builds; with the snapshot drop after a definition taken out, two of its rows go wrong. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- .../Builtins/RubyModule.MethodLookupCache.cs | 100 ++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 11 ++ Src/Ruby/Runtime/Calls/RubyCallAction.cs | 47 ++++++++ Util/sdef-matrix.rb | 66 ++++++++++++ 4 files changed, 224 insertions(+) diff --git a/Src/Ruby/Builtins/RubyModule.MethodLookupCache.cs b/Src/Ruby/Builtins/RubyModule.MethodLookupCache.cs index 01fbfe74b..d3019f212 100644 --- a/Src/Ruby/Builtins/RubyModule.MethodLookupCache.cs +++ b/Src/Ruby/Builtins/RubyModule.MethodLookupCache.cs @@ -107,6 +107,20 @@ internal MethodLookupTable(int version, Dictionary/* version = table.Version; return entry; } + + // A singleton class that finds what its superclass finds for every name it has no entry for (see InheritedLookups): + var inherited = Volatile.Read(ref _inheritedLookups); + if (inherited != null && inherited.Version == Version.Method && !inherited.HasOwn(name)) { + int superVersion; + entry = ((RubyClass)this).SuperClass.GetMethodLookup(name, out superVersion); + + // Nothing in this class changed meanwhile: a change of its own table or modules drops the snapshot under the + // class hierarchy lock, which a fill of the superclass's answer takes as well (see InheritedLookups). + if (superVersion >= 0 && Volatile.Read(ref _inheritedLookups) == inherited && inherited.Version == Version.Method) { + version = inherited.Version; + return entry; + } + } return FillMethodLookup(name, out version); } @@ -114,6 +128,24 @@ internal MethodLookupTable(int version, Dictionary/* publishedVersion = -1; using (Context.ClassHierarchyLocker()) { int version = Version.Method; + + // Not while a library method table is being populated: its methods go in without the + // version bump a later definition would make. + if (Context.MethodTableInitializationDepth == 0 && InheritsMethodLookupsNoLock()) { + var inherited = _inheritedLookups; + if (inherited == null || inherited.Version != version) { + Volatile.Write(ref _inheritedLookups, inherited = new InheritedLookups(version, _methods)); + } + if (!inherited.HasOwn(name)) { + int superVersion; + var inheritedEntry = ((RubyClass)this).SuperClass.GetMethodLookup(name, out superVersion); + if (superVersion >= 0 && Version.Method == version) { + publishedVersion = version; + } + return inheritedEntry; + } + } + var entry = ResolveMethodLookupNoLock(name); // Not while a library method table is being populated: its methods go in without the @@ -149,6 +181,74 @@ internal MethodLookupTable(int version, Dictionary/* } } + // IR_SINGLETON_LOOKUP=0: a singleton class's lookups are filed in its own cache as any class's (see InheritedLookups). + private static readonly bool _InheritLookups = Environment.GetEnvironmentVariable("IR_SINGLETON_LOOKUP") != "0"; + + /// + /// The names in the method table of a singleton class that answers every other lookup from its superclass's cache + /// (see ), as of a method version of the class. + /// + /// Each definition on an object that gets methods of its own (OpenStruct's define_singleton_method! of every member) + /// re-versions its singleton class and so empties the class's lookup cache, and each name asked again then walked the + /// ancestors and copied the cache's table to file one more entry - some thirty lookups (the hooks, respond_to?, the + /// shared rules' tests) per OpenStruct. The superclass's cache stays warm across all such objects, so a lookup of a name + /// the singleton class has no entry for is answered there, without the class hierarchy lock, and nothing is filed. + /// + /// The answer is kept by its callers under this class's version, as a filed one is, and is right for as long: the + /// superclass's fill registered it for invalidation (InvalidateSitesOnOverride, MissingMethodsCachedInSites), so a + /// definition of the name here re-versions this class, as anything that changes the superclass's answer does. A + /// definition of a name nobody has asked for does not re-version it, though, so the snapshot of the names is dropped + /// (under the class hierarchy lock) by every change of the method table or of the modules, and the reader checks it is + /// still the current one after taking the superclass's answer: a superclass fill that registered the name took the + /// lock after any definition that had not seen the registration. + /// + private sealed class InheritedLookups { + internal readonly int Version; + private readonly string/*!*/[]/*!*/ _ownNames; + + internal InheritedLookups(int version, Dictionary methods) { + Version = version; + if (methods == null || methods.Count == 0) { + _ownNames = Array.Empty(); + } else { + _ownNames = new string[methods.Count]; + methods.Keys.CopyTo(_ownNames, 0); + } + } + + // any entry, a hidden or undefined one too + internal bool HasOwn(string/*!*/ name) { + foreach (string own in _ownNames) { + if (String.Equals(own, name)) { + return true; + } + } + return false; + } + } + + // Dropped by every change of this module's method table or modules (under the class hierarchy lock): + private InheritedLookups _inheritedLookups; + + // Past this many own methods a singleton class files its lookups (the names are searched one by one). + private const int MaxInheritedLookupOwnNames = 16; + + /// + /// True if this is the singleton class of a plain Ruby object (not a module) that has no modules included in it or + /// prepended to it, nor many methods of its own: a walk from it for a name it has no entry for is its superclass's walk + /// (FindMethodInAncestorsNoLock), and finds the same method and owner. See . + /// + private bool InheritsMethodLookupsNoLock() { + var cls = this as RubyClass; + if (!_InheritLookups || cls == null || !cls.IsSingletonClass || cls.SuperClass == null || + !(cls.SingletonClassOf is IRubyObject) || cls.SingletonClassOf is RubyModule || TypeTracker != null || + _prepends.Length != 0 || _mixins.Length != 0) { + return false; + } + InitializeMethodsNoLock(); + return _methods == null || _methods.Count <= MaxInheritedLookupOwnNames; + } + /// /// The definition of in this module's own method table only (method_defined?'s /// inherit = false: MRI looks up from the origin and requires the entry's owner to be this module, so diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index bfa4f284b..bb01914c8 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -937,6 +937,7 @@ internal void InitializeMembersFrom(RubyModule/*!*/ module) { } _mixins = ArrayUtils.Copy(module._mixins); _prepends = ArrayUtils.Copy(module._prepends); + _inheritedLookups = null; // dependentModules - skip // tracker - skip, .NET members not copied @@ -2485,6 +2486,7 @@ internal void SetMethodNoMutateNoEventNoLock(RubyContext/*!*/ callerContext, str InitializeMethodsNoLock(); _methods[name] = method; + _inheritedLookups = null; if (IsHelperName(name)) { if (_context.Loader.IsLoadingCorePrelude) { @@ -2590,6 +2592,7 @@ internal void AddMethodNoCacheInvalidation(string/*!*/ name, RubyMemberInfo/*!*/ Context.RequiresClassHierarchyLock(); Debug.Assert(_methods != null); _methods.Add(name, method); + _inheritedLookups = null; } /// @@ -2598,6 +2601,7 @@ internal void AddMethodNoCacheInvalidation(string/*!*/ name, RubyMemberInfo/*!*/ internal bool RemoveMethodNoCacheInvalidation(string/*!*/ name) { Context.RequiresClassHierarchyLock(); Debug.Assert(_methods != null); + _inheritedLookups = null; return _methods.Remove(name); } @@ -2635,6 +2639,7 @@ private bool RemoveMethodNoEvent(string/*!*/ name) { } _methods.Remove(name); + _inheritedLookups = null; if (_refinedModule != null) { _context.RefinedMethodChanged(_refinedModule, name); @@ -3378,6 +3383,7 @@ private bool TryGetClrMemberNoTiming(string/*!*/ name, bool virtualLookup, out R TryGetDefaultInterfaceMember(name, unmangleNames, out method) : TryGetClrMember(_typeTracker.Type, name, mapNames, unmangleNames, out method)) { _methods.Add(name, method); + _inheritedLookups = null; return true; } } @@ -3939,6 +3945,7 @@ internal void PrependModulesNoLock(RubyModule[]/*!*/ modules) { } PrependsUpdated(oldPrepends, _prepends = expanded); + _inheritedLookups = null; _context.ConstantsChanged(); } @@ -4024,6 +4031,7 @@ internal void SpliceAncestorUpdate(RubyModule/*!*/ owner, RubyModule/*!*/[]/*!*/ var expanded = SpliceBefore(oldMixins, mixinIndex, added); if (expanded.Length != oldMixins.Length) { MixinsUpdated(oldMixins, _mixins = expanded); + _inheritedLookups = null; } } @@ -4033,6 +4041,7 @@ internal void SpliceAncestorUpdate(RubyModule/*!*/ owner, RubyModule/*!*/[]/*!*/ var expanded = SpliceBefore(old, prependIndex, added); if (expanded.Length != old.Length) { PrependsUpdated(old, _prepends = expanded); + _inheritedLookups = null; } } @@ -4086,6 +4095,7 @@ internal void IncludeModulesNoLock(RubyModule[]/*!*/ modules) { } MixinsUpdated(_mixins, _mixins = expanded); + _inheritedLookups = null; _context.ConstantsChanged(); if (!IsClass) { @@ -4132,6 +4142,7 @@ private void ReexpandMixinNoLock(RubyModule/*!*/ mixin) { } MixinsUpdated(_mixins, _mixins = expanded); + _inheritedLookups = null; _context.ConstantsChanged(); if (!IsClass) { diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index dc8cb4682..7272927c8 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -468,6 +468,10 @@ internal bool TryShareVersion(object/*!*/ target, RuleVersionSet/*!*/ versionSet } bool publicOnly = Signature.HasScope && !Signature.HasImplicitSelf && !Signature.HasLightScope && !Signature.IsInteropCall; + if (TryShareVersionFromLookup(context, target, publicOnly, versionSet)) { + return true; + } + int version; RubyMemberInfo member; bool isMissing; @@ -480,6 +484,49 @@ internal bool TryShareVersion(object/*!*/ target, RuleVersionSet/*!*/ versionSet return true; } + // IR_SINGLETON_LOOKUP=0: the test resolves a new version under the class hierarchy lock only (see TryShareVersionFromLookup). + private static readonly bool _ShareFromLookup = Environment.GetEnvironmentVariable("IR_SINGLETON_LOOKUP") != "0"; + + /// + /// TryShareVersion's answer for a version whose class has the call's method in its lookup cache (RubyModule.GetMethodLookup): + /// true if the call resolves there to the rule's method, as ResolveShared would resolve it, and the version is then added. + /// The cache is read without the class hierarchy lock, and is kept per class version and registered for invalidation as a + /// call site's resolution is, so an answer filed for the version is the one ResolveShared would give for it. Only a call + /// that finds the method is answered: a method_missing call, one whose visibility or method does not match, a name some + /// refinement has (whose call may depend on the caller's refinements) and an answer the cache does not keep go to + /// ResolveShared. A singleton class re-versioned by each definition on its object (OpenStruct's) finds its lookups in its + /// superclass's cache (RubyModule.InheritsMethodLookupNoLock), so the version is taken in without a walk of the ancestors. + /// + private bool TryShareVersionFromLookup(RubyContext/*!*/ context, object/*!*/ target, bool publicOnly, RuleVersionSet/*!*/ versionSet) { + if (!_ShareFromLookup || versionSet.IsMissing || context.IsRefinedMethodName(_methodName)) { + return false; + } + RubyClass targetClass = context.GetImmediateClassOf(target); + if (targetClass.Context != context) { + return false; + } + + int version; + var lookup = targetClass.GetMethodLookup(_methodName, out version); + if (version < 0 || !lookup.Found || lookup.Info != versionSet.Member || + lookup.Info.GetType() != typeof(RubyLibraryMethodInfo) && lookup.Info.GetType() != typeof(RubyMethodInfo)) { + return false; + } + + // ResolveShared's visibility (with the empty scope): public only, or all visible; a protected method is not shared. + var visibility = lookup.Visibility; + bool allVisible = !publicOnly && !(Signature.HasLightScope && !Signature.HasImplicitSelf) && !Signature.IsInteropCall; + if (visibility == RubyMethodVisibility.Protected || !allVisible && visibility != RubyMethodVisibility.Public) { + return false; + } + if (DispatchIntrinsics.MaySpecialize(lookup.Info, Signature, targetClass)) { + return false; + } + + versionSet.TryAdd(version); + return true; + } + internal override T BindShared(object[]/*!*/ args, bool beforeDispatcher, out bool deferred) { deferred = false; RubyContext context = Context; diff --git a/Util/sdef-matrix.rb b/Util/sdef-matrix.rb index 6aebf7402..ca5a424bb 100644 --- a/Util/sdef-matrix.rb +++ b/Util/sdef-matrix.rb @@ -270,5 +270,71 @@ def self.go(o) = o.m row "ostruct after writers", os.sum { |o| o.a + o.c + o.to_h.size } row "ostruct dig/==", [os[3].dig(:a), os[3] == os[3].dup, os[5].delete_field(:a), (os[5].a rescue $!.class), os[1].frozen?, os[1].freeze.frozen?, (begin; os[1].a = 2; rescue => e; e.class; end)] +# ---------------------------------------------------------------- 12. lookups on a singleton class that its superclass's cache answers +# A singleton class with no modules of its own finds what its superclass finds for a name it has no entry for. Each row asks +# (respond_to?, method_defined?, a call, a hook) on objects whose singleton class has just been made or re-versioned, then changes +# what the object, its singleton class or its class has, and asks again. +class C12 + def a = :a + def pv = :pv + private :pv + def pt = :pt + protected :pt +end +class C12S < C12; private :a; end +module M12; def m12 = :m12; end +module P12; def a = [:pre, super]; end +module E12 + def self.extended(o) = o.instance_variable_set(:@e12, true) + def e12 = :e12 +end +def rt12(o, n) = [o.respond_to?(n), o.respond_to?(n, true)] +# the answers of n calls of one site, counted: [answer, how many], in order of first appearance +def tally12(n = 300) = n.times.map { |i| yield i }.tally.to_a +row "name nobody asked for", tally12(300) { |i| o = C12.new; o.singleton_class; a = o.respond_to?(:a); n = :"u12_#{i}" + o.define_singleton_method(n) { i }; [a, o.respond_to?(n), o.public_send(n) == i, o.singleton_class.method_defined?(n)] } +row "def o.x after lookups", tally12(300) { |i| o = C12.new; o.singleton_class; r = rt12(o, :"d12_#{i}"); o.instance_eval("def d12_#{i} = 1") + r + rt12(o, :"d12_#{i}") } +row "asked, then defined", tally12(300) { |i| o = C12.new; o.singleton_class; r = rt12(o, :late12); (def o.late12 = 1) if i.odd? + r + rt12(o, :late12) + [o.singleton_class.method_defined?(:late12), (o.late12 rescue $!.class)] } +row "undef and remove in singleton", tally12(300) { |i| o = C12.new; o.singleton_class; r = rt12(o, :a); sc = o.singleton_class + if i % 3 == 0 then sc.send(:undef_method, :a) elsif i % 3 == 1 then (def o.a = :own); sc.send(:remove_method, :a) end + r + rt12(o, :a) + [(o.a rescue $!.class)] } +row "private in singleton", tally12(300) { |i| o = C12.new; o.singleton_class; r = rt12(o, :a); o.singleton_class.send(:private, :a) if i.even? + r + rt12(o, :a) + [(o.a rescue $!.class), o.send(:a)] } +row "private and protected", tally12(200) { |i| o = C12.new; o.singleton_class; rt12(o, :pv) + rt12(o, :pt) + [(o.pv rescue $!.class), (o.pt rescue $!.class)] } +row "forwarder in subclass", tally12(300) { |i| o = C12S.new; o.singleton_class; r = rt12(o, :a); o.singleton_class.send(:public, :a) if i % 4 == 0 + r + rt12(o, :a) + [(o.a rescue $!.class)] } +row "respond_to_missing? added", tally12(300) { |i| o = C12.new; o.singleton_class + C12.class_eval { def respond_to_missing?(n, p = false) = n == :ghost12 || super } if i == 150 + rt12(o, :ghost12) } +row "method_missing added", tally12(300) { |i| o = C12.new; o.singleton_class + C12.class_eval { def method_missing(n, *a) = n == :ghost12b ? :mm : super } if i == 150 + [(o.ghost12b rescue $!.class), o.respond_to?(:ghost12b)] } +$c12_added = [] +row "singleton_method_added hook", tally12(300) { |i| o = C12.new; o.singleton_class; o.respond_to?(:a) + C12.class_eval { def singleton_method_added(n) = $c12_added << n } if i == 150 + o.define_singleton_method(:h12) { 1 }; $c12_added.include?(:h12) } +row "include and prepend later", tally12(300) { |i| o = C12.new; o.singleton_class; r = rt12(o, :m12) + [o.a] + o.singleton_class.include(M12) if i % 3 == 0; o.singleton_class.prepend(P12) if i % 3 == 1 + r + rt12(o, :m12) + [o.a, o.singleton_class.method_defined?(:m12)] } +row "extend with extended", tally12(300) { |i| o = C12.new; o.singleton_class; r = rt12(o, :e12); o.extend(E12) if i.odd? + r + rt12(o, :e12) + [(o.e12 rescue $!.class), o.instance_variable_get(:@e12)] } +module R12; refine(C12) { def a = :refined }; end +module Use12 + using R12 + def self.go(o) = [o.a, o.respond_to?(:a)] +end +row "refined over singletons", tally12(300) { |i| o = C12.new; o.singleton_class; (def o.a = :own) if i % 5 == 0; Use12.go(o) + [o.a] } +row "class gains method later", tally12(300) { |i| o = C12.new; o.singleton_class; r = rt12(o, :gain12) + C12.class_eval { def gain12 = :g } if i == 150; r + rt12(o, :gain12) } +# two threads define and remove singleton methods on one object and ask after each, while a third asks about its class's method +s12 = C12.new; s12.singleton_class +t12 = 2.times.map { |t| Thread.new { bad = 0; 1500.times { |k| n = :"th#{t}_#{k % 7}" + s12.define_singleton_method(n) { k }; bad += 1 unless s12.respond_to?(n) && s12.public_send(n) == k + s12.singleton_class.send(:remove_method, n); bad += 1 if s12.respond_to?(n) }; bad } } +t12 << Thread.new { bad = 0; 6000.times { bad += 1 unless s12.respond_to?(:a) && s12.a == :a && !s12.respond_to?(:pv) }; bad } +row "threads define while one asks", t12.map(&:value) + $stderr.puts "jit=#{defined?(IronRuby) ? 'ironruby' : 'cruby'}" puts "end" From 9e14bdd2796b8280db091b3cfddb69c956e51030 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:27:11 +0000 Subject: [PATCH 044/439] A String subclass's instance is a Hash key as it is, not a frozen copy `k = MyS.new("k"); h = {k => 1}` stored a frozen copy of k (`h.keys[0].equal?(k)` false, frozen? true), and so did `h[k] = 1`, #store, Hash[] and the JIT's hot `h[k] = v` (LEDGER gap 34). CRuby 4.0 copies only a key whose class is String (RHASH_STRING_KEY_P: rb_obj_class(key) == rb_cString) and stores any other String as it is, unfrozen. RubyUtils.SetHashElement and JitIntrinsics.HashStoreObj now copy only a MutableString whose CLR type is MutableString (a Ruby subclass's instances are MutableString.Subclass); a plain String's key is the copy it was, interned unless it has instance variables. The other half of gap 34, `defined?({a: x.nope})` answering "expression", already answers nil on this branch, as CRuby does, light frame or not. Checked: Hash_StringSubclassKey1 (new; CRuby 4.0's output; also with -X:NoJIT -X:NoOSR, -X:NoJITCalls and IR_LIGHT_FRAMES=0); Util/hash-literal-matrix.rb gains the rows the two differences kept out ("a String subclass key is kept, unfrozen", "... by []=", "defined? of a literal whose value is a missing method"): CRuby's output on this, the first two baseline before it; spec/core/hash element_set, constructor, merge, rehash, compare_by_identity and spec/language/hash_spec: no failure, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/HashTests.cs | 35 +++++++++++++++++++++++++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 2 +- Src/Ruby/Runtime/RubyUtils.cs | 9 ++++--- Util/hash-literal-matrix.rb | 8 +++--- 5 files changed, 47 insertions(+), 8 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 825b482f4..9dd0518cf 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1394,6 +1394,7 @@ public Tests(Driver/*!*/ driver) { Hash_FetchErrorEllipsis1, Hash_InitializeCopyIsReplace1, Hash_UpdateStringKey1, + Hash_StringSubclassKey1, Hash_EqlHashRehash1, Enumerable_PatternUnusedBlockWarning1, Enumerable_PredicatePattern1, diff --git a/Src/IronRuby.Tests/Runtime/HashTests.cs b/Src/IronRuby.Tests/Runtime/HashTests.cs index 1d6a94117..0add29e3b 100644 --- a/Src/IronRuby.Tests/Runtime/HashTests.cs +++ b/Src/IronRuby.Tests/Runtime/HashTests.cs @@ -555,6 +555,41 @@ p h.fetch('a'), m['a'], h.keys[0].frozen?, i.keys[0].frozen? "); } + /// + /// Only a key whose class is String is stored as a frozen copy (MRI's RHASH_STRING_KEY_P); an instance of a subclass of + /// String is stored as it is, unfrozen, by a literal, #[]=, #store and the JIT's hot #[]= alike, so a change to it + /// needs a #rehash, as for any other mutable key. + /// + public void Hash_StringSubclassKey1() { + TestOutput(@" +class MyS < String; end +def lit(k) = {k => 1} +def aset(k) = (h = {}; h[k] = 1; h) +def st(k) = (h = {}; h.store(k, 1); h) +def hot(k) = (h = {}; i = 0; while i < 3000; h[k] = i; h.delete(k) if i < 2999; i += 1; end; h) +res = nil +3000.times do + k = MyS.new('k'); s = +'s' + res = [lit(k), aset(k), st(k), hot(k), Hash[k, 1]].map { |h| x = h.keys[0]; [x.equal?(k), x.frozen?, x.class] } + + [lit(s), aset(s), hot(s)].map { |h| x = h.keys[0]; [x.equal?(s), x.frozen?, x.class] } +end +res.each { |r| p r } +k = MyS.new('k'); h = {k => 1}; k << '2'; p h.keys, h.key?('k2'), (h.rehash; h['k2']) +", @" +[true, false, MyS] +[true, false, MyS] +[true, false, MyS] +[true, false, MyS] +[true, false, MyS] +[false, true, String] +[false, true, String] +[false, true, String] +[""k2""] +false +1 +"); + } + /// /// Hash#eql? asks an object that converts to a Hash the question the other way round (rb_hash_eql); an empty /// Hash does not hash to 0 ([Bug #9231]); and #rehash builds the new table before it lets go of the old one diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index c6080504b..41a4100f1 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -845,7 +845,7 @@ public static void HashStoreObj(RubyContext/*!*/ context, object recv, object ke // a new key while the hash is iterated is the generic code's RuntimeError if (hash.IsIterating) { throw Deopt(); } var str = key as MutableString; - if (str != null && !str.IsFrozen && !hash.ComparesByIdentity) { + if (str != null && !str.IsFrozen && str.GetType() == typeof(MutableString) && !hash.ComparesByIdentity) { key = str.Duplicate(context, false, str.Clone()).Freeze(); hashCode = key.GetHashCode(); } diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 3ccf38f53..aca28d882 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1381,14 +1381,15 @@ public static object SetHashElement(RubyContext/*!*/ context, IDictionary 1, b => 2 } t('duplicate keys keep the first key') { a = +"k"; b = +"k"; r = o_dup_str(a, b); [r, r.keys[0].equal?(a)] } t('a String key is a frozen copy') { s = +"key"; r = h_key(s, 1); k = r.keys[0]; [k.frozen?, k.equal?(s), s.frozen?, (s << "!")] } t('a frozen String key is kept') { s = "fk".freeze; h_key(s, 1).keys[0].equal?(s) } -# (not whether it is frozen: IronRuby freezes a String subclass key, CRuby 4.0 does not, light frame or not) -t('a String subclass key') { c = Class.new(String); h_key(c.new("x"), 1).keys[0].class == c } +t('a String subclass key is kept, unfrozen') { c = Class.new(String); k = c.new("x"); r = h_key(k, 1).keys[0]; [r.class == c, r.equal?(k), r.frozen?] } +t('a String subclass key by []=') { c = Class.new(String); k = c.new("x"); h = {}; h[k] = 1; [h.keys[0].equal?(k), k.frozen?] } t('an Array key') { a = [1]; r = h_key(a, 2); [r, r.keys[0].equal?(a)] } t('a NaN key') { r = h_key(Float::NAN, 1); [r.size, r.key?(Float::NAN)] } t('0 and 0.0 keys') { h_keys(0, 0.0) } @@ -237,8 +237,9 @@ def e_key(x) = { x.fetch(9) => 1 } def e_loud(k) = { k => 1 } def e_four(x) = { a: 1, b: 2, c: 3, d: x.fetch(9) } def e_str(x) = { "s" => x.fetch(9) } -# (not of a literal whose value calls a missing method: CRuby answers nil, IronRuby "expression", light frame or not) def d_lit(x) = defined?({ a: x }) +def d_missing(x) = defined?({ a: x.nope }) +def d_missing_key(x) = defined?({ x.nope => 1, b: 2 }) def d_empty = defined?({}) def traced(x) = { tr: x } @@ -250,6 +251,7 @@ def traced(x) = { tr: x } t('raise line') { begin; e_value([]); rescue IndexError => e; e.backtrace_locations[1].lineno - __LINE__; end } t('defined? of a literal') { d_lit(1) } t('defined? {}') { d_empty } +t('defined? of a literal whose value is a missing method') { [d_missing(1), d_missing_key(1)] } t('TracePoint :call sees it') do seen = [] tp = TracePoint.new(:call) { |e| seen << e.method_id if e.method_id == :traced } From 673f65d4acced721668f6c181b072633bd0cb909 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:33:18 +0000 Subject: [PATCH 045/439] A private method's call that reaches BasicObject#method_missing through super says so `C.new.x` for a private x, where C's method_missing calls super, raised "undefined method 'x' for an instance of C" (LEDGER gap 37; OpenStruct's new_ostruct_member! shows it); a protected one the same. CRuby raises "private method 'x' called for an instance of C" ("protected method ..."): vm_call_method_missing records MISSING_PRIVATE or MISSING_PROTECTED in the thread's method_missing_reason, and rb_method_missing reads it. The rule that calls a user's method_missing for a call that found a private or protected method now records that visibility with the rest of the reason (RubyOps.SetMethodMissingReasonVisibility, through a MethodInfo of RubyOps rather than a new [Emitted] helper); SetMethodMissingReason clears it; BasicObject#method_missing raises the visibility error when it is set, with the call's arguments and private_call? as for the undefined-method error. Left: an explicit `obj.method_missing(:w)` after such an error is "undefined method" here; CRuby never clears the reason and says "private method 'w' called" from the stale one. Checked: SuperAndMethodMissing3 (new; CRuby 4.0's output); spec/core/basicobject method_missing, spec/core/nomethoderror, Kernel#send/public_send/method_missing, spec/language private, protected, send, spec/library/openstruct: as before (the one send_spec error is the known into/to wording). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/SuperTests.cs | 32 ++++++++++++++++++++++++ Src/Libraries/Builtins/BasicObjectOps.cs | 11 ++++++++ Src/Ruby/Runtime/Calls/RubyCallAction.cs | 16 +++++++++--- Src/Ruby/Runtime/RubyOps.cs | 21 ++++++++++++++++ 5 files changed, 77 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9dd0518cf..ba0c5ac85 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -941,6 +941,7 @@ public Tests(Driver/*!*/ driver) { SuperToAttribute1, SuperAndMethodMissing1, SuperAndMethodMissing2, + SuperAndMethodMissing3, SuperCaching1, SuperInBlocks1, SuperInDefineMethod1, diff --git a/Src/IronRuby.Tests/Runtime/SuperTests.cs b/Src/IronRuby.Tests/Runtime/SuperTests.cs index f64075a72..69284e139 100644 --- a/Src/IronRuby.Tests/Runtime/SuperTests.cs +++ b/Src/IronRuby.Tests/Runtime/SuperTests.cs @@ -622,6 +622,38 @@ D.new.bar rescue p $! "); } + /// + /// A call of a private or protected method from outside that goes to a method_missing calling super ends in MRI's + /// "private method 'x' called" (MISSING_PRIVATE, MISSING_PROTECTED): the reason reaches BasicObject#method_missing. + /// + public void SuperAndMethodMissing3() { + TestOutput(@" +require 'ruby4' +class C + def method_missing(n, *a) = super + def respond_to_missing?(*) = super + private def x(*) = 1 + protected def y = 2 + def z = x +end +def err = yield.then { :none } rescue [$!.class, $!.message, $!.name, ($!.args rescue :na), ($!.private_call? rescue :na)] +c = C.new +p err { c.x }, err { c.x(1, 2) }, err { c.y }, err { c.nope }, err { c.z } +p err { c.instance_eval { nope2 } }, err { c.instance_eval { nope3() } }, err { c.x } +p Thread.new { err { c.y } }.value +", @" +[NoMethodError, ""private method 'x' called for an instance of C"", :x, [], false] +[NoMethodError, ""private method 'x' called for an instance of C"", :x, [1, 2], false] +[NoMethodError, ""protected method 'y' called for an instance of C"", :y, [], false] +[NoMethodError, ""undefined method 'nope' for an instance of C"", :nope, [], false] +:none +[NameError, ""undefined local variable or method 'nope2' for an instance of C"", :nope2, :na, :na] +[NoMethodError, ""undefined method 'nope3' for an instance of C"", :nope3, [], true] +[NoMethodError, ""private method 'x' called for an instance of C"", :x, [], false] +[NoMethodError, ""protected method 'y' called for an instance of C"", :y, [], false] +"); + } + public void SuperCaching1() { AssertOutput(() => CompilerTest(@" module M diff --git a/Src/Libraries/Builtins/BasicObjectOps.cs b/Src/Libraries/Builtins/BasicObjectOps.cs index a7b050054..9562e92dc 100644 --- a/Src/Libraries/Builtins/BasicObjectOps.cs +++ b/Src/Libraries/Builtins/BasicObjectOps.cs @@ -57,6 +57,17 @@ public static object MethodMissing(RubyScope/*!*/ scope, object/*!*/ self, [NotN // and the way the call was made (implicit receiver or not) is what #private_call? reports bool variableCall = RubyOps.MethodMissingVariableCall && args.Length == 0; RubyOps.MethodMissingVariableCall = false; + // a private or protected method the call found (MRI's raise_method_missing: MISSING_PRIVATE first) + var visibility = RubyOps.MethodMissingVisibility; + RubyOps.MethodMissingVisibility = RubyMethodVisibility.None; + if (visibility == RubyMethodVisibility.Private || visibility == RubyMethodVisibility.Protected) { + var visibilityError = NoMethodErrorOps.SetArguments((visibility == RubyMethodVisibility.Private) ? + RubyExceptions.CreatePrivateMethodCalled(context, self, name.ToString()) : + RubyExceptions.CreateProtectedMethodCalled(context, self, name.ToString()), args); + RubyExceptionData.GetInstance(visibilityError).PrivateCall = RubyOps.MethodMissingPrivateCall; + RubyOps.MethodMissingPrivateCall = false; + throw RubyExceptionData.MarkUnkept(visibilityError); + } if (variableCall) { // a bare name: MRI's NameError, as the call would have raised without a method_missing RubyOps.MethodMissingPrivateCall = false; diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index dc8cb4682..0b013d133 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -1074,10 +1074,18 @@ internal static bool BuildMethodMissingCall(MetaObjectBuilder/*!*/ metaBuilder, switch (BindToKernelMethodMissing(metaBuilder, args, methodName, methodMissing, incompatibleVisibility, isSuperCall)) { case MethodMissingBinding.Custom: Debug.Assert(!metaBuilder.Error); - // a user-defined method_missing may call super: record how the call was made - metaBuilder.AddInitialization(Methods.SetMethodMissingReason.OpCall( - AstUtils.Constant(args.Signature.HasImplicitSelf), AstUtils.Constant(defaultFallback && args.Signature.IsVariableCall) - )); + // a user-defined method_missing may call super: record how the call was made, and whether it found a + // private or protected method + if (incompatibleVisibility == RubyMethodVisibility.Private || incompatibleVisibility == RubyMethodVisibility.Protected) { + metaBuilder.AddInitialization(Ast.Call(RubyOps.SetMethodMissingReasonVisibilityMethod, + AstUtils.Constant(args.Signature.HasImplicitSelf), AstUtils.Constant(defaultFallback && args.Signature.IsVariableCall), + AstUtils.Constant(incompatibleVisibility) + )); + } else { + metaBuilder.AddInitialization(Methods.SetMethodMissingReason.OpCall( + AstUtils.Constant(args.Signature.HasImplicitSelf), AstUtils.Constant(defaultFallback && args.Signature.IsVariableCall) + )); + } methodMissing.BuildMethodMissingCall(metaBuilder, args, methodName); return true; diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 0df3ee308..a0bd8dd13 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -4468,12 +4468,33 @@ public static bool MethodMissingVariableCall { set { _methodMissingVariableCall = value; } } + // And whether the method was there but private or protected (MISSING_PRIVATE, MISSING_PROTECTED), so that + // BasicObject#method_missing reached through super says "private method 'x' called", as the call would have. + [ThreadStatic] + private static RubyMethodVisibility _methodMissingVisibility; + + public static RubyMethodVisibility MethodMissingVisibility { + get { return _methodMissingVisibility; } + set { _methodMissingVisibility = value; } + } + [Emitted] public static void SetMethodMissingReason(bool privateCall, bool variableCall) { _methodMissingPrivateCall = privateCall; _methodMissingVariableCall = variableCall; + _methodMissingVisibility = RubyMethodVisibility.None; } + // SetMethodMissingReason for a call that found a method it may not call (RubyCallAction.BuildMethodMissingCall) + public static void SetMethodMissingReasonVisibility(bool privateCall, bool variableCall, RubyMethodVisibility visibility) { + _methodMissingPrivateCall = privateCall; + _methodMissingVariableCall = variableCall; + _methodMissingVisibility = visibility; + } + + internal static readonly MethodInfo/*!*/ SetMethodMissingReasonVisibilityMethod = + typeof(RubyOps).GetMethod(nameof(SetMethodMissingReasonVisibility)); + [Emitted] public static Exception/*!*/ SetMissingMethodArguments(Exception/*!*/ error, object[]/*!*/ args, IList splat, object rhs, bool hasRhs, bool privateCall) { var list = new RubyArray(args); From 467d17c753afbcacbe725992a55aece8ec3b01fd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:33:54 +0000 Subject: [PATCH 046/439] Make define_method methods from the same Proc equal, as in CRuby Two methods made by define_method from the same Proc - `define_method(:a, &pr); define_method(:b, &pr)`, or from pr.dup, or from pr passed without `&' - are == as Method and UnboundMethod in CRuby, with equal hashes: rb_method_definition_eq compares the two bmethods' procs with Proc#==. IronRuby gave every define_method its own body id, so only an alias or a visibility copy of one compared equal. One block literal run in two scopes (`[1, 2].each { |i| define_method(:"m#{i}") { } }') still makes two methods, in both. RubyLambdaMethodInfo.IsEquivalentTo now also takes two methods whose procs are equal by IronRuby's Proc#== (ProcOps.Equal: the same dispatcher over the same scope, or the same Symbol#to_proc symbol), and the equivalence hash is that of the proc. Found in round one of perf/dmethjit; checked with the new DefineMethodEquality1, whose expected output is CRuby 4.0's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BlockTests.cs | 30 +++++++++++++++++++ .../Runtime/Calls/RubyLambdaMethodInfo.cs | 15 ++++++++-- 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 834bc86db..ae05c4e1d 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -363,6 +363,7 @@ public Tests(Driver/*!*/ driver) { MethodToProc1, DefineMethod1, DefineMethod2, + DefineMethodEquality1, DefineMethodBlockBreak1, ProcPosition1, diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index a38775df0..505812e99 100644 --- a/Src/IronRuby.Tests/Runtime/BlockTests.cs +++ b/Src/IronRuby.Tests/Runtime/BlockTests.cs @@ -1953,6 +1953,36 @@ p D.instance_methods(false).sort "); } + /// + /// Methods made by define_method from the same Proc - or a copy of it, or its lambda - are the same method, as in + /// MRI (rb_method_definition_eq compares the procs): == and hash agree. One block literal run in two scopes makes two. + /// + public void DefineMethodEquality1() { + TestOutput(@" +class W + PR = proc { |x| x } + define_method(:n1, &PR) + define_method(:n2, &PR) + define_method(:n3, &PR.dup) + define_method(:n4, PR) + define_method(:l1, LA = ->(x) { x }) + define_method(:l2, LA) + [1, 2].each { |i| define_method(:""m#{i}"") { |x| x } } + define_method(:o1) { |x| x } + alias o2 o1 + def d1(x) = x + define_method(:d2, instance_method(:d1)) +end +im = W.method(:instance_method).unbind.bind(W) +p [im.(:n1) == im.(:n2), im.(:n1) == im.(:n3), im.(:n1) == im.(:n4), im.(:l1) == im.(:l2), im.(:m1) == im.(:m2), im.(:o1) == im.(:o2), im.(:d1) == im.(:d2)] +w = W.new +p [w.method(:n1) == w.method(:n2), w.method(:n1).hash == w.method(:n2).hash, im.(:n1).hash == im.(:n2).hash, im.(:n1).eql?(im.(:n2))] +", @" +[true, true, true, true, false, true, true] +[true, true, true, true] +"); + } + /// /// A call of a define_method method is the frame a break from its literal block ends, wherever the /// body passes the block on to - as a def method's call is - on the first calls and on later ones. diff --git a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs index 40976773c..f88ec63d6 100644 --- a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs @@ -144,11 +144,22 @@ public override bool IsEquivalentTo(RubyMemberInfo/*!*/ other) { return true; } var info = other as RubyLambdaMethodInfo; - return info != null && info._bodyId == _bodyId; + return info != null && (info._bodyId == _bodyId || SameProc(info._block, _block)); + } + + // Two methods made by define_method from the same Proc - or a copy of it, or its lambda - are the same method + // in MRI (rb_method_definition_eq compares the procs with Proc#==): the same block literal over the same scope + // (ProcOps.Equal). One literal run in two scopes (`[1, 2].each { |i| define_method(:"m#{i}") { } }') makes two. + private static bool SameProc(Proc/*!*/ a, Proc/*!*/ b) { + if (a.SymbolName != null || b.SymbolName != null) { + return a.SymbolName == b.SymbolName; + } + return a.Dispatcher == b.Dispatcher && a.LocalScope == b.LocalScope; } public override int GetEquivalenceHashCode() { - return _bodyId; + // as ProcOps.GetHash: what SameProc compares + return (_block.SymbolName != null) ? _block.SymbolName.GetHashCode() : _block.Dispatcher.GetHashCode() ^ _block.LocalScope.GetHashCode(); } public string/*!*/ DefinitionName { From b3c20a57d138ce987caff5dcbd3b521e79eec12b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:33:58 +0000 Subject: [PATCH 047/439] Reuse the Proc of a block literal that has a literal nested in it A block literal with another literal nested in it never reused its Proc (BlockDispatcher.ReusesProc), so its method never parked its scope: NBody's `advance' made a method scope, two Procs and two BlockParams on every call, about 410 of the 600 bytes a call allocates, although its nested `((i + 1)...n).each' runs in place in the outlined loop of the `each_index' block (perf/nest) and no nested Proc is ever made once that loop is compiled. Now such a literal may reuse its Proc, and the nested literal, on the calls that do make its Proc, clears the reuse of the Procs of the blocks its scope runs in (RubyOps.KeepEnclosingProcs). That keeps the one thing the old rule kept: a Proc a nested Proc may reach is never made again, and so never parked with its method's scope (StageParkedProc). Nothing else changes for a block that makes one: its scope is still not reused and its BlockParams are handed on as before (marking the scope captured instead stopped Richards' worker Proc#call from reusing its BlockParam: +9% bytes). Nested literals no longer count against their method's parking; the literals the method's scope makes still all must reuse their Procs. The calls before the loop is outlined make the nested Proc, and a parking slot gives up after 64 failures in a row; the first run of the outlined copy gives the slot of the block's method one more try (BlockLoopInfo.ParkSlot). IR_NESTED_PROCS=0 keeps the old rule. NBody 152.0 -> 48.0 MB per iteration (Util/perf/alloc.rb), the other thirteen level. Util/nested-proc-matrix.rb (new) prints what CRuby 4.0 prints with the switch on and off and with -X:NoJIT -X:NoOSR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Builtins/Proc.cs | 3 +- Src/Ruby/Compiler/Ast/BlockDefinition.cs | 36 ++- .../Compiler/ReflectionCache.Generated.cs | 2 + Src/Ruby/Runtime/Calls/BlockDispatcher.cs | 4 +- Src/Ruby/Runtime/Osr/BlockLoopSite.cs | 11 + Src/Ruby/Runtime/RubyOps.cs | 20 +- Util/nested-proc-matrix.rb | 234 ++++++++++++++++++ 7 files changed, 301 insertions(+), 9 deletions(-) create mode 100644 Util/nested-proc-matrix.rb diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index 1de8185a1..70f015eed 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -277,7 +277,8 @@ internal Proc(ProcKind kind, object self, RubyScope/*!*/ scope, BlockDispatcher/ _scope = scope; _dispatcher = dispatcher; // (no RubyScope.MarkCaptured here: a literal block makes a Proc over its enclosing scope on every - // call, and a block with a nested block literal never reuses its scope - see BlockDefinition) + // call, and a block with a nested block literal never reuses its scope - see BlockDefinition; the + // nested literal's Proc keeps the enclosing Procs from being made again: RubyOps.KeepEnclosingProcs) } protected Proc(Proc/*!*/ proc) diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index 16a6af808..58e16092a 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -40,6 +40,12 @@ public partial class BlockDefinition : Block { // if the block has more parameters object[] is used: internal const int MaxBlockArity = BlockDispatcher.MaxBlockArity; + /// + /// IR_NESTED_PROCS=0: a block literal with a literal nested in it never reuses its Proc, and the nested literal does not + /// clear the enclosing Procs' reuse (see Transform, reusesProc). + /// + internal static readonly bool NestedProcsEnabled = Environment.GetEnvironmentVariable("IR_NESTED_PROCS") != "0"; + private readonly Parameters/*!*/ _parameters; private readonly Statements/*!*/ _body; private readonly LexicalScope/*!*/ _definedScope; @@ -323,14 +329,25 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St bool reuseScope = lazyScope == null && !hasNestedReturn && !gen.CurrentBlock.HasNestedBlock && !gen.TraceEnabled && !gen.CompilerOptions.IsEval; - // The same holds for the Proc of the literal (see BlockDispatcher.ReusesProc). - bool reusesProc = !isLambda && !hasNestedReturn && !gen.CurrentBlock.HasNestedBlock && + // The same held for the Proc of the literal (see BlockDispatcher.ReusesProc), but a nested literal's Proc is not made + // on every call: when the block runs as an iterator's outlined loop, the nested iterator's loop runs in place and makes + // none (BlockLoopSite, NestedBlockLoop). So the nested literal's Proc, when it is made, keeps this one from being made + // again (RubyOps.KeepEnclosingProcs) - and so from being parked - and a call that made + // none leaves this Proc - and the method's scope, if every literal of the method's own reuses its Proc - for the next + // call (NBody's `advance': a scope and two Procs per call). IR_NESTED_PROCS=0 keeps the old rule. + bool hasNestedBlock = gen.CurrentBlock.HasNestedBlock; + bool reusesProc = !isLambda && !hasNestedReturn && (NestedProcsEnabled || !hasNestedBlock) && !gen.TraceEnabled && !gen.CompilerOptions.IsEval; // (a method all of whose literals reuse their Procs may park its scope with them: MethodDefinition.ParkedScopesEnabled) - gen.CurrentMethod.BlockLiteralCount++; - if (!reusesProc) { - gen.CurrentMethod.HasUnreusableBlock = true; + // A literal nested in a block keeps the enclosing literals' Procs from being made again (KeepEnclosingProcs below), and + // so the method's scope from being parked, on a call that made it: only the literals the + // method's scope makes have their Procs parked, and only they count. + if (!(NestedProcsEnabled && gen.CurrentBlock.ParentBlock != null)) { + gen.CurrentMethod.BlockLiteralCount++; + if (!reusesProc) { + gen.CurrentMethod.HasUnreusableBlock = true; + } } body = gen.Traceable @@ -438,6 +455,10 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St instantiateReusable = Methods.InstantiateParkedBlock.OpCall(previousProc, gen.CurrentScopeVariable, gen.CurrentSelfVariable, dispatcher, gen.CurrentMethod.ParkedVariable, AstUtils.Constant(gen.CurrentMethod.ParkProcVariables.Count)); gen.CurrentMethod.ParkProcVariables.Add(previousProc); + if (hasNestedBlock && blockDispatcher.LoopInfo != null) { + // the calls before the loop is outlined make the nested Proc and so cannot park (see BlockLoopInfo.ParkSlot) + blockDispatcher.LoopInfo.ParkSlot = parkSlot; + } } else if (reusesProc) { instantiateReusable = Methods.InstantiateReusableBlock.OpCall(previousProc, gen.CurrentScopeVariable, gen.CurrentSelfVariable, dispatcher); } @@ -456,6 +477,11 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St ) ) ); + if (NestedProcsEnabled && gen.CurrentBlock != null) { + // a literal nested in a block (the enclosing block's HasNestedBlock): its Proc holds the scope it is made in, and that + // block's Proc may be reused (see reusesProc above) + instance = Methods.KeepEnclosingProcs.OpCall(instance, gen.CurrentScopeVariable); + } return reusesProc ? Ast.Assign(previousProc, instance) : instance; } diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 78461b40d..8d95f641e 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -432,6 +432,8 @@ public static partial class Methods { private static MethodInfo _IsTopLevelReturn; public static MethodInfo/*!*/ IsTrue { get { return _IsTrue ?? (_IsTrue = CallInstruction.CacheFunc(RubyOps.IsTrue)); } } private static MethodInfo _IsTrue; + public static MethodInfo/*!*/ KeepEnclosingProcs { get { return _KeepEnclosingProcs ?? (_KeepEnclosingProcs = CallInstruction.CacheFunc(RubyOps.KeepEnclosingProcs)); } } + private static MethodInfo _KeepEnclosingProcs; public static MethodInfo/*!*/ KeywordArgumentsMatch { get { return _KeywordArgumentsMatch ?? (_KeywordArgumentsMatch = CallInstruction.CacheFunc(RubyOps.KeywordArgumentsMatch)); } } private static MethodInfo _KeywordArgumentsMatch; public static MethodInfo/*!*/ KeywordSplatArgument { get { return _KeywordSplatArgument ?? (_KeywordSplatArgument = CallInstruction.CacheFunc(RubyOps.KeywordSplatArgument)); } } diff --git a/Src/Ruby/Runtime/Calls/BlockDispatcher.cs b/Src/Ruby/Runtime/Calls/BlockDispatcher.cs index 9c16a041e..1fa670ed9 100644 --- a/Src/Ruby/Runtime/Calls/BlockDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/BlockDispatcher.cs @@ -146,8 +146,8 @@ public BlockDispatcherN(int parameterCount, BlockSignatureAttributes attributesA public abstract class BlockDispatcher { // A literal block whose calls never leave its scope reachable but through RubyScope.MarkCaptured: not a lambda, no block - // literal nested in it (whose Proc holds the scope without marking it), no TracePoint hooks compiled in. Its Proc may be - // made again by the frame that made it (Proc.TryReuse, RubyOps.InstantiateReusableBlock). + // literal nested in it unless that clears this one's reuse (RubyOps.KeepEnclosingProcs, IR_NESTED_PROCS), no TracePoint hooks + // compiled in. Its Proc may be made again by the frame that made it (Proc.TryReuse, RubyOps.InstantiateReusableBlock). internal bool ReusesProc; // position of the block definition (opening brace): diff --git a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs index 4a5713929..e85b77da2 100644 --- a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs @@ -97,6 +97,11 @@ internal sealed class BlockLoopInfo { // The body's last statement is an iterator run in place (NestedBlockLoop), whose value the copy // does not compute: only the kinds that drop the block's value may take the block. internal readonly bool LastIsNested; + // The parking slot of the method whose own literal this is, if the block holds a nested literal (BlockDefinition, + // IR_NESTED_PROCS): every call that yields to the block generically makes the nested Proc, which keeps the method's + // scope from being parked, so the slot may have given up (ParkedScopeSlot.MaxFailures) before the loop was outlined. + // A run of the copy, which makes none, gives it one more try (BlockLoopSite.Run); then this is null. + internal ParkedScopeSlot ParkSlot; private BlockLoopInfo(BlockDefinition/*!*/ ast, RubyContext/*!*/ context, int depth, LocalVariable parameter, LocalVariable/*!*/[]/*!*/ locals, string/*!*/ name, int calls, bool lastIsNested) { @@ -667,6 +672,12 @@ private void Run(BlockParam/*!*/ block, int from, object limit, RubyArray result } try { RunIn(args, own, block, scope, depth, from, limit, result, keptBefore, out resume, out kept); + var parkSlot = _info.ParkSlot; + if (parkSlot != null && resume != from && parkSlot.Failures > ParkedScopeSlot.MaxFailures) { + // (not exact under threads, as the count itself is not: at worst the slot gives up once more) + _info.ParkSlot = null; + parkSlot.Failures = 0; + } } finally { // Nothing a run held stays reachable from the site: the block's locals, the receiver, // the result, self and the scopes. A copy that stopped part way (an exception, a throw) diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 0df3ee308..075d117a5 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -235,7 +235,7 @@ internal static void ThrowStackLevelTooDeep() { #region Parked method scopes - // A method whose block literals all reuse their Procs (BlockDispatcher.ReusesProc: no lambda or nested block in them) + // A method whose block literals all reuse their Procs (BlockDispatcher.ReusesProc: no lambda, no nested block that does not keep them: KeepEnclosingProcs) // and which calls no super makes a scope and a Proc per literal on every call, the Proc's parent (`def each; (a..b).each // { |i| yield @s[i] }; end'). Once such a call has returned normally, if nothing captured the scope (RubyScope.IsCaptured: // binding, eval, a method or Symbol proc made in it, a TracePoint, a Proc of a literal replaced) and the last Proc of @@ -956,6 +956,24 @@ public static Proc InstantiateReusableBlock(Proc previous, RubyScope/*!*/ scope, return dispatcher.HasMethod ? new Proc(ProcKind.Block, self, scope, dispatcher) : null; } + /// + /// The Proc of a literal nested in a block, made in (the enclosing block's, or a scope inside + /// it): it reaches the Procs of the blocks that scope runs in, which are therefore not made again (Proc.ClearReusable) - + /// and so not parked with their method's scope either (RubyOps.StageParkedProc). The enclosing literal reuses its Proc + /// only on calls that make no nested Proc (BlockDefinition, IR_NESTED_PROCS). Nothing else changes for a block that + /// makes one: its scope is not reused (BlockDefinition, reuseScope) and its BlockParams are handed on as they were. + /// + [Emitted] + public static Proc/*!*/ KeepEnclosingProcs(Proc/*!*/ proc, RubyScope/*!*/ scope) { + for (RubyScope s = scope; s is RubyBlockScope blockScope; s = s._parent) { + var bfc = blockScope.BlockFlowControl; + if (bfc != null) { + bfc.Proc.ClearReusable(); + } + } + return proc; + } + [Emitted] public static Proc/*!*/ DefineBlock(RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher, object/*!*/ clrMethod) { return new Proc(ProcKind.Block, self, scope, dispatcher.SetMethod(clrMethod)); diff --git a/Util/nested-proc-matrix.rb b/Util/nested-proc-matrix.rb new file mode 100644 index 000000000..05b7c846e --- /dev/null +++ b/Util/nested-proc-matrix.rb @@ -0,0 +1,234 @@ +# Differential matrix for a block literal with another literal nested in it (IR_NESTED_PROCS: Src/Ruby/Compiler/Ast/ +# BlockDefinition.cs, RubyOps.KeepEnclosingProcs). Such a block's Proc is made again for the next call of its method, and +# the method's scope is parked with it, on every call that made no nested Proc - NBody's `advance', whose nested +# `(i + 1)...n).each' runs in place in the outlined loop of its `each_index' block. A call that does make the nested Proc +# must keep everything that Proc reaches: the enclosing blocks' Procs and scopes, and the method's scope with its locals and +# self. Run it under CRuby and under ./ir.sh with the switch on and off, and with the tiers off, and diff: +# +# ruby Util/nested-proc-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/nested-proc-matrix.rb > /tmp/on.txt +# IR_NESTED_PROCS=0 ./ir.sh Util/nested-proc-matrix.rb > /tmp/off.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/nested-proc-matrix.rb > /tmp/notiers.txt +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt && diff /tmp/mri.txt /tmp/notiers.txt +# +# Every method runs hot (thousands of calls that make no nested Proc, so that its scope is parked and its Procs made +# again) before and around the calls that make one and keep it; what was kept is called at the end. + +def t(label) + print label.ljust(64), ' => ' + begin + v = yield + puts "#{v.inspect} (#{v.class})" + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +N = 3000 +KEEP = [7, 1500, 1501, 2999] + +class Keeper + def initialize; @kept = []; end + attr_reader :kept + def keep(&b); @kept << b; b; end +end + +# ---------------------------------------------------------------- 1. NBody's shape, a nested Proc kept now and then + +class Bodies + def initialize(n); @a = Array.new(n) { |i| i * 1.5 }; @k = Keeper.new; @s = 0.0; end + attr_reader :k, :s + def advance(dt, keep) + @a.each_index do |i| + x = @a[i] + ((i + 1)...@a.size).each do |j| + @s += (x - @a[j]) * dt + end + @k.keep { [i, x, dt, self.class] } if keep + end + end + def advance2(dt, keep) + @a.each_index do |i| + x = @a[i] + ((i + 1)...@a.size).each do |j| + @s += (x - @a[j]) * dt + @k.keep { [i, j, x, dt] } if keep && j == i + 1 + end + end + end +end + +t('kept in the outer block') { + b = Bodies.new(5) + N.times { |n| b.advance(n * 0.5, KEEP.include?(n)) } + [b.s, b.k.kept.map(&:call)] +} +t('kept in the inner block') { + b = Bodies.new(5) + N.times { |n| b.advance2(n * 0.5, KEEP.include?(n)) } + [b.s, b.k.kept.map(&:call)] +} +t('kept: a String element in the middle') { + b = Bodies.new(4) + r = [] + N.times do |n| + b.instance_variable_get(:@a)[2] = (n == 1500 ? 'x' : 3.0) + begin + b.advance(1.0, n == 1500 || n == 1600) + rescue TypeError, NoMethodError => e + r << [n, e.class] + end + end + [r, b.k.kept.map(&:call)] +} + +# ---------------------------------------------------------------- 2. the method's locals and self, as a kept Proc sees them + +class M + def initialize(k); @k = k; end + def m(x, keep) + y = x * 2 + [1, 2].each do |e| + [10].each do |f| + @k.keep { [x, y, e, f, self.object_id == @id] } if keep + end + y += e + end + y + end + def mark; @id = object_id; self; end +end + +t('method locals seen by a kept Proc after later calls') { + k = Keeper.new + o = M.new(k).mark + s = 0 + N.times { |n| s += o.m(n, KEEP.include?(n)) } + [s, k.kept.map(&:call)] +} +t('two receivers, alternating') { + k = Keeper.new + a = M.new(k).mark + b = M.new(k).mark + N.times { |n| (n.even? ? a : b).m(n, n % 997 == 0) } + k.kept.map(&:call) +} + +# ---------------------------------------------------------------- 3. what a nested literal can be + +class Kinds + def lam(n); r = nil; [n].each { |x| r = -> { x + n } if n % 1000 == 0 }; r; end + def prc(n); r = nil; [n].each { |x| r = proc { x * n } if n % 1000 == 0 }; r; end + def pnew(n); r = nil; [n].each { |x| r = Proc.new { x - n } if n % 1000 == 0 }; r; end + def meth(n); r = nil; [n].each { |x| r = binding if n % 1000 == 0; x }; r; end + def dm(n); [n].each { |x| self.class.send(:define_method, :"dm_#{n}") { x + 1 } if n % 1000 == 0 }; nil; end + def thr(n); r = nil; [n].each { |x| r = Thread.new { x * 3 } if n % 1000 == 0 }; r; end + def three(n); r = nil; [n].each { |x| [x].each { |y| [y].each { |z| r = proc { [x, y, z, n] } if n % 1000 == 0 } } }; r; end +end + +t('lambda, proc, Proc.new, binding, define_method, Thread') { + o = Kinds.new + out = [] + N.times do |n| + l = o.lam(n); out << [:lam, l.call] if l + pr = o.prc(n); out << [:prc, pr.call] if pr + pn = o.pnew(n); out << [:pnew, pn.call] if pn + bd = o.meth(n); out << [:binding, bd.local_variable_get(:n)] if bd + o.dm(n) + th = o.thr(n); out << [:thread, th.value] if th + tr = o.three(n); out << [:three, tr.call] if tr + end + out + [Kinds.new.dm_2000] +} +t('kept Procs called after the method ran on') { + o = Kinds.new + ks = [] + N.times { |n| r = o.three(n); ks << r if r } + ks.map(&:call) +} + +# ---------------------------------------------------------------- 4. the outer literal made twice in one call + +class Twice + def initialize; @kept = []; end + attr_reader :kept + def m(n) + i = 0 + while i < 2 + [i].each do |v| + [v].each { |w| @kept << proc { [n, v, w, i] } if n % 700 == 0 && w == 0 } + end + i += 1 + end + i + end +end + +t('outer literal evaluated twice per call') { + o = Twice.new + N.times { |n| o.m(n) } + o.kept.map(&:call) +} + +# ---------------------------------------------------------------- 5. jumps through a reused Proc + +class Jumps + def brk(n); [1, 2, 3].each { |x| [x].each { |y| break if y == 2 }; break x * n if x == 3 }; end + def nxt(n); [1, 2, 3].map { |x| [x].each { |y| next }; next x + n }; end + def ret(n); [1, 2, 3].each { |x| [x].each { |y| return y * n if y == 2 } }; :none; end +end + +t('break, next, return across nested blocks') { + o = Jumps.new + s = [] + N.times { |n| s << [o.brk(n), o.nxt(n), o.ret(n)] if n % 1000 == 999; o.brk(n); o.nxt(n); o.ret(n) } + s +} + +# ---------------------------------------------------------------- 6. recursion, fibers, threads + +class Rec + def initialize; @kept = []; end + attr_reader :kept + def m(d, n) + [d].each do |x| + [x].each { |y| @kept << proc { [y, d, n] } if n % 1000 == 0 && y == 0 } + m(d - 1, n) if d > 0 + end + d + end +end + +t('recursive calls of the method') { + o = Rec.new + N.times { |n| o.m(3, n) } + o.kept.map(&:call) +} +t('enumerator over a method with nested blocks') { + o = Bodies.new(4) + e = Enumerator.new { |y| 200.times { |n| o.advance(1.0, n == 100); y << o.s } } + vals = [] + vals << e.next while vals.size < 150 + [vals.last, o.k.kept.size, o.k.kept.map(&:call)] +} +t('threads calling one method') { + k = Keeper.new + objs = Array.new(4) { M.new(k).mark } + ths = objs.each_with_index.map { |o, ti| Thread.new { s = 0; 1000.times { |n| s += o.m(n + ti, n == 500) }; s } } + [ths.map(&:value), k.kept.map(&:call).sort] +} + +# ---------------------------------------------------------------- 7. the inner Proc as an object + +class Ident + def m(n, out) + [1].each { |x| [x].each { |y| out << proc { y } } if n % 1000 == 0 } + end +end + +t('nested Procs are distinct objects') { + o = Ident.new + out = [] + N.times { |n| o.m(n, out) } + [out.size, out.map(&:object_id).uniq.size, out.map(&:call)] +} From 1a9b14b918f3687566da7c22fec3cafd6964ff26 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:34:25 +0000 Subject: [PATCH 048/439] Let the method JIT take define_method bodies that read captured locals, and setters Round one took a define_method body only when it used none of the enclosing scopes' locals. Of the 154 define_method blocks in the standard library and the bundled gems, 66 have plain parameters and read a captured local and nothing else in the way (`{ @options[name] }`, `{ code }`, `{ |v| @h[name] = v }`), against 17 that read none; 4 write one. And a setter called as `o.x = v' never reached the stub, since the rule left assignment calls out. BlockDefinition now keeps the tree of a block that assigns no enclosing local. JitBlockMethod finds each local the block reads in the scope as many levels up from the Proc's LocalScope as the lexical depths say (RubyScope.TryGetLocalSlot), and declines the block if the runtime chain does not match. The def it hands the JIT (BlockMethodDefinition) knows those slots: JitScreen and JitCompiler.EmitLocalRead take a read of one as JitBlockMethod.ReadCaptured, the value in that scope's locals at that moment, as the block's closure reads it on each call; every other def still bails on an enclosing local. The rule of RubyLambdaMethodInfo sends assignment calls to the stub too, the value last, as Methods.Yield passes it. Checked: Util/dmeth-jit-matrix.rb (new rows: captured names per iteration with reader and writer, a method scope's local, two levels up, a captured receiver, a captured flag another method changes, a value changed through Binding to Float, Bignum and String, block-local shadowing, threads, assignment calls), dmeth-matrix, jit-matrix, jit-calls-matrix and block-given-matrix print CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls and IR_JIT_DMETH=0; inline-matrix prints what the base prints. 141 IronRuby.Tests (define_method, instance_method, JIT) pass. Instructions a call under callgrind, base -> new: `{ @h[name] }` 2592 -> 1892, its setter 2359 -> 1713, `x + captured` 1921 -> 1255, defs level. Not gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/Ruby/Compiler/Ast/BlockDefinition.cs | 7 +- .../Runtime/Calls/RubyLambdaMethodInfo.cs | 10 +- Src/Ruby/Runtime/Jit/JitBlockMethod.cs | 110 ++++++++++++++++-- Src/Ruby/Runtime/Jit/JitCompiler.cs | 20 +++- Src/Ruby/Runtime/RubyScope.cs | 15 +++ Util/bench/dmeth-shapes.rb | 59 ++++++++-- Util/dmeth-jit-matrix.rb | 60 ++++++++++ Util/perf/LEDGER.md | 52 +++++++++ 8 files changed, 309 insertions(+), 24 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index 16a6af808..b6f2cb69b 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -414,10 +414,11 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St blockDispatcher.LoopInfo = BlockLoopInfo.TryCreate(this, gen.Context, _definedScope.Depth, gen.SourcePath + ":" + Location.Start.Line); } - if (outerVariables == null && !hasNestedReturn && !gen.TraceEnabled && !gen.CompilerOptions.IsEval && + if (assignedOuterVariables == null && !hasNestedReturn && !gen.TraceEnabled && !gen.CompilerOptions.IsEval && IronRuby.Runtime.Jit.JitBlockMethod.Enabled && gen.Context.RubyOptions.Jit && IsJitMethodShape()) { - // -X:JIT: a block over none of the enclosing scope's locals may become the body of a method - // (define_method), which the method JIT can take as it takes a def's (JitBlockMethod) + // -X:JIT: a block that assigns none of the enclosing scopes' locals may become the body of a method + // (define_method), which the method JIT can take as it takes a def's (JitBlockMethod); those it reads + // the typed body reads from the scopes, as the block does blockDispatcher.JitAst = this; } diff --git a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs index f88ec63d6..45378697d 100644 --- a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs @@ -217,12 +217,14 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA // -X:JIT: plain arguments, as many as the block takes, go to the stub of the method JIT, whose generic body is // the call below (JitBlockMethod). An omitted optional argument is passed as the default sentinel, as to a def's. - if (!args.Signature.HasBlock && !args.Signature.HasSplattedArgument && !args.Signature.HasRhsArgument) { + // The value of an assignment call (o.x = v, o[k] = v) is its last argument, as the rule passes it (Methods.Yield). + if (!args.Signature.HasBlock && !args.Signature.HasSplattedArgument) { var jit = GetJit(); if (jit.Trampoline != null) { var simple = args.GetSimpleArgumentExpressions(); + var rhs = args.Signature.HasRhsArgument ? args.GetRhsArgumentExpression() : null; int jitArity = jit.Ast.Parameters.Mandatory.Length + jit.Ast.Parameters.Optional.Length; - if (simple.Count <= jitArity) { + if (simple.Count + (rhs != null ? 1 : 0) <= jitArity) { var jitArgs = new Ast[2 + jitArity]; jitArgs[0] = AstUtils.Box(args.TargetExpression); jitArgs[1] = IronRuby.Compiler.Ast.AstFactory.NullOfProc; @@ -236,6 +238,10 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA if (k > 0) { jitArgs[1 + k] = Methods.ClearKeywordArguments.OpCall(jitArgs[1 + k]); } + if (rhs != null) { + jitArgs[2 + k] = AstUtils.Box(rhs); + k++; + } for (; k < jitArity; k++) { jitArgs[2 + k] = Ast.Field(null, typeof(RubyOps).GetField("DefaultArgument")); } diff --git a/Src/Ruby/Runtime/Jit/JitBlockMethod.cs b/Src/Ruby/Runtime/Jit/JitBlockMethod.cs index ea4f3edb4..dd9a9dd7c 100644 --- a/Src/Ruby/Runtime/Jit/JitBlockMethod.cs +++ b/Src/Ruby/Runtime/Jit/JitBlockMethod.cs @@ -7,8 +7,10 @@ * (RubyLambdaMethodInfo), which it never took: such a call cost twice a def's (gap 23 of Util/perf/LEDGER.md). * * A block can be taken as a def when nothing in it tells the two apart: - * - it reads and writes none of the enclosing scopes' locals (BlockDispatcher.OuterVariableNames is null, - * so BlockDefinition kept its tree: BlockDispatcher.JitAst), and was not compiled for eval or tracing; + * - it assigns none of the enclosing scopes' locals (BlockDispatcher.AssignedOuterVariableNames is null, so + * BlockDefinition kept its tree: BlockDispatcher.JitAst), and was not compiled for eval or tracing. Those it + * reads, the typed body reads where the block does - from the locals of the scope that many levels up from + * the Proc's (ReadCaptured), at each read, so a change made after the method was defined is seen; * - its parameters are a def's (plain mandatory, then optional; BlockDefinition.IsJitMethodShape); * - its body has nothing whose meaning is the defining scope's rather than the method's: no yield and no * block_given? (the defining method's block), no super (implicit super raises; explicit super names the @@ -55,7 +57,13 @@ internal static Delegate TryWrap(RubyLambdaMethodInfo/*!*/ method, out MethodDec var context = method.DeclaringModule.Context; if (block == null || !context.RubyOptions.Jit) { return null; } - string rejectedBy = BlockScreen.Rejects(block); + List captured; + string rejectedBy = BlockScreen.Rejects(block, out captured); + var scope = lambda.LocalScope; + Dictionary slots = null; + if (rejectedBy == null && captured != null) { + slots = ResolveCaptured(block, scope, captured, out rejectedBy); + } if (rejectedBy != null) { if (JitRuntime.Verbose) { Console.Error.WriteLine("[jit] define_method {0}/{1} not taken: {2}", method.DeclaringModule.Name ?? "main", method.DefinitionName, rejectedBy); @@ -64,14 +72,13 @@ internal static Delegate TryWrap(RubyLambdaMethodInfo/*!*/ method, out MethodDec } var location = block.Location; - var def = new MethodDeclaration(block.DefinedScope, null, method.DefinitionName, block.Parameters, - new Body(block.Body, null, null, null, location), location) { + var def = new BlockMethodDefinition(block.DefinedScope, method.DefinitionName, block.Parameters, + new Body(block.Body, null, null, null, location), location, slots) { // the body neither yields nor passes a block on (BlockScreen): the call's block is nothing to it UsesBlock = false }; // The refinements the block's calls see are those active where it was written. - var scope = lambda.LocalScope; StrongBox refinements = null; if (context.HasRefinements) { var active = scope.GetActiveRefinements(); @@ -88,6 +95,78 @@ internal static Delegate TryWrap(RubyLambdaMethodInfo/*!*/ method, out MethodDec return result; } + /// + /// Where each local of an enclosing scope the block reads lives: the scope as many levels up from the Proc's as the + /// block is nested in the variable's, and its slot there - what the block's closure reads (ScopeBuilder.CreateScope). + /// The runtime chain is checked against the lexical one: a scope between that declares the name, or a level that has + /// no scope, and the block is not taken. + /// + private static Dictionary ResolveCaptured(BlockDefinition/*!*/ block, RubyScope/*!*/ scope, + List/*!*/ captured, out string rejectedBy) { + rejectedBy = null; + var result = new Dictionary(); + var byKey = new Dictionary(); + int depth = block.DefinedScope.Depth; + foreach (var local in captured) { + string key = local.Name + "@" + local.DefinitionLexicalDepth; + CapturedLocal slot; + if (!byKey.TryGetValue(key, out slot)) { + int hops = depth - 1 - local.DefinitionLexicalDepth; + RubyScope owner = scope; + int index; + for (int i = 0; i < hops && owner != null; i++) { + if (owner.TryGetLocalSlot(local.Name, out index)) { owner = null; break; } + owner = owner.Parent; + } + if (owner == null || !owner.TryGetLocalSlot(local.Name, out index)) { + rejectedBy = "captured local " + local.Name + " not found where the block was written"; + return null; + } + slot = new CapturedLocal(owner, index); + byKey.Add(key, slot); + } + result[local] = slot; + } + return result; + } + + /// A local of an enclosing scope a define_method body reads: the scope and the slot (ResolveCaptured). + internal sealed class CapturedLocal { + internal readonly RubyScope/*!*/ Scope; + internal readonly int Index; + + internal CapturedLocal(RubyScope/*!*/ scope, int index) { + Scope = scope; + Index = index; + } + } + + /// A read of a captured local in a typed body (JitCompiler.EmitLocalRead): its value now. + public static object ReadCaptured(CapturedLocal/*!*/ local) { + return local.Scope.GetLocalSlotValue(local.Index); + } + + internal static readonly System.Reflection.MethodInfo ReadCapturedMethod = typeof(JitBlockMethod).GetMethod("ReadCaptured"); + + /// + /// The def a define_method body is taken as, which knows where the locals of enclosing scopes it reads live: the + /// screen (JitScreen) and the compiler (JitCompiler.EmitLocalRead) take a read of one, which they take of no def. + /// + internal sealed class BlockMethodDefinition : MethodDeclaration { + private readonly Dictionary _captured; + + internal BlockMethodDefinition(IronRuby.Compiler.LexicalScope/*!*/ definedScope, string/*!*/ name, Parameters/*!*/ parameters, Body/*!*/ body, + Microsoft.Scripting.SourceSpan location, Dictionary captured) + : base(definedScope, null, name, parameters, body, location) { + _captured = captured; + } + + internal CapturedLocal GetCaptured(LocalVariable/*!*/ local) { + CapturedLocal slot; + return (_captured != null && _captured.TryGetValue(local, out slot)) ? slot : null; + } + } + private Delegate MakeGeneric(int arity) { switch (arity) { case 0: return new Func(Call0); @@ -189,9 +268,12 @@ private sealed class BlockScreen : Walker { }; private string _rejectedBy; + private int _depth; + // the reads of enclosing scopes' locals (BlockDefinition kept no block that assigns one) + private List _captured; - internal static string Rejects(BlockDefinition/*!*/ block) { - var screen = new BlockScreen(); + internal static string Rejects(BlockDefinition/*!*/ block, out List captured) { + var screen = new BlockScreen { _depth = block.DefinedScope.Depth }; try { foreach (var statement in block.Body) { screen.Walk(statement); @@ -204,6 +286,7 @@ internal static string Rejects(BlockDefinition/*!*/ block) { } catch (Exception) { screen._rejectedBy = "screen-error"; } + captured = screen._captured; return screen._rejectedBy; } @@ -227,6 +310,17 @@ private bool No(string/*!*/ what) { public override bool Enter(ModuleDefinition/*!*/ node) { return No("module"); } public override bool Enter(SingletonDefinition/*!*/ node) { return No("class << self"); } + public override bool Enter(LocalVariable/*!*/ node) { + int depth = node.DefinitionLexicalDepth; + if (depth < _depth) { + // -1: a local of the scope an eval runs in, which no lexical scope holds + if (depth < 0) { return No("local of an eval's scope"); } + if (_captured == null) { _captured = new List(); } + _captured.Add(node); + } + return true; + } + public override bool Enter(MethodCall/*!*/ node) { if ((node.Target == null || node.Target is SelfReference) && FrameCalls.Contains(node.MethodName)) { return No(node.MethodName); diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index c1cca3ad4..1d2791a7c 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1379,7 +1379,14 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { private JitRuntime.InterpolationSite _interpolationSite; private MSA.Expression/*!*/ EmitLocalRead(LocalVariable/*!*/ local, out JT type) { - if (_loop == null && local.DefinitionLexicalDepth != _scopeDepth) { throw JitBailout.Instance; } + if (_loop == null && local.DefinitionLexicalDepth != _scopeDepth) { + // a local a define_method body reads from an enclosing scope: read from there, each time (JitBlockMethod) + var blockMethod = _ast as JitBlockMethod.BlockMethodDefinition; + var captured = (blockMethod != null) ? blockMethod.GetCaptured(local) : null; + if (captured == null) { throw JitBailout.Instance; } + type = JT.Obj; + return Ast.Call(JitBlockMethod.ReadCapturedMethod, Ast.Constant(captured)); + } MSA.ParameterExpression p; if (!TryLookup(Key(local), out p, out type)) { KeyValuePair loaded; @@ -3134,8 +3141,12 @@ internal sealed class JitScreen { // the `while'/`until' loops around the node being walked, whose break and next Emit takes private int _loops; + // a define_method body's def, which may read the locals it captured (JitBlockMethod); null for a def + private readonly JitBlockMethod.BlockMethodDefinition _blockMethod; + private JitScreen(MethodDeclaration/*!*/ ast, JitKeywords keywords) { _scopeDepth = ast.DefinedScope.Depth; + _blockMethod = ast as JitBlockMethod.BlockMethodDefinition; _methodName = ast.Name; // a method with keywords is never called directly from its typed body (EmitCall) _arity = (keywords != null) ? -1 : ast.Parameters.Mandatory.Length + ast.Parameters.Optional.Length; @@ -3364,10 +3375,11 @@ private bool Walk(RExpr/*!*/ node) { var local = node as LocalVariable; if (local != null) { - // A local from an enclosing scope is never read from a typed body. (Emit also - // bails on a read before any assignment, which is a flow property: say yes.) + // A local from an enclosing scope is never read from a typed body, but by a define_method + // body that captured it (JitBlockMethod). (Emit also bails on a read before any assignment, + // which is a flow property: say yes.) _otherUses.Add(local.Name); - return local.DefinitionLexicalDepth == _scopeDepth || No(node); + return local.DefinitionLexicalDepth == _scopeDepth || _blockMethod != null && _blockMethod.GetCaptured(local) != null || No(node); } var assign = node as SimpleAssignmentExpression; diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 9c64af656..6a8508442 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -390,6 +390,21 @@ private void SetLocalValue(int index, object value) { } } + /// + /// The slot of a local this scope declares - not `it' or _1.._9, nor one eval added - which the method JIT reads a + /// local captured by a define_method body from (JitBlockMethod.ReadCaptured), as the block's own closure does. + /// + internal bool TryGetLocalSlot(string/*!*/ name, out int index) { + EnsureBoxes(); + index = -1; + return StaticLocalMapping != null && StaticLocalMapping.TryGetValue(name, out index) && !IsImplicitParameter(name); + } + + /// The value of the local in a slot TryGetLocalSlot gave, as the locals hold it now. + internal object GetLocalSlotValue(int index) { + return GetLocalValue(index); + } + private bool IsImplicitParameter(string/*!*/ name) { var names = OwnImplicitParameterNames; return names != null && Array.IndexOf(names, name) >= 0; diff --git a/Util/bench/dmeth-shapes.rb b/Util/bench/dmeth-shapes.rb index d65eaacce..1791a3432 100644 --- a/Util/bench/dmeth-shapes.rb +++ b/Util/bench/dmeth-shapes.rb @@ -1,14 +1,35 @@ # Calls of methods made by define_method (gap 23 of Util/perf/LEDGER.md), against a `def' of the same # body: no, one and two arguments, an instance variable read, a call to another method of self, and a -# body over a captured local (which the method JIT declines). ` ns ' per line, -# for Util/perf/ab.rb; `ruby dmeth-shapes.rb NAME...' runs only the shapes named; N scales the counts. -SCALE = (ENV["N"] || "1").to_f +# body over a captured local: `x + captured', the per-name hash reader and writer stdlib and gems define +# (`%i[a b].each { |name| define_method(name) { @h[name] } }'), a captured constant value, a captured factor. +# ` ns ' per line, for Util/perf/ab.rb; `ruby dmeth-shapes.rb NAME...' runs only the shapes +# named; N is the number of calls a section makes (ab.rb -n); INSTR=1 (ab.rb -i, or Util/perf/callgrind/count.sh) +# adds the instructions of a call, from the least of the sections as the time is. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end def t(name, n = 2_000_000) + return puts(name) if ARGV == ['--list'] return unless ARGV.empty? || ARGV.include?(name) - n = (n * SCALE).to_i - best = 1e9; r = nil - 5.times { t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC); r = yield n; d = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0; best = d if d < best } - printf "%-14s %8.1f ns %s\n", name, best * 1e9 / n, r + n = ENV['N'].to_i if ENV['N'] + best = 1e9; r = nil; fewest = nil; counted = !!INSTR + 5.times do + c0 = INSTR && INSTR.read + t0 = cpu + r = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + fewest = c1 - c0 if fewest.nil? || c1 - c0 < fewest + else + counted = false + end + end + printf "%-14s %8.1f ns %s%s\n", name, best * 1e9 / n, r, counted ? format(' %.1f instr', fewest.to_f / n) : '' end class B def initialize = (@a = 3) @@ -20,6 +41,21 @@ def helper(x) = x * 2 define_method(:bmcall) { |x| helper(x) + 1 } captured = 1 define_method(:bmcapt) { |x| x + captured } + def initialize_h = (@h = { a: 1 }) + %i[a].each do |name| + define_method(:"bmh_#{name}") { @h[name] } + define_method(:"bmh_#{name}=") { |v| @h[name] = v } + end + code = 404 + define_method(:bmconst) { code } + def self.scaled(name, k) = define_method(name) { |x| x * k } + scaled(:bmscaled, 3) + def dmh_a = @h[:a] + def dmh_a=(v) + @h[:a] = v + end + def dmconst = 404 + def dmscaled(x) = x * 3 def dm0 = 1 def dm1(x) = x + 1 def dm2(x, y) = x + y @@ -27,6 +63,7 @@ def dmivar = @a def dmcall(x) = helper(x) + 1 end o = B.new +o.initialize_h t("bm0") { |n| i = 0; c = 0; while i < n; c += o.bm0; i += 1; end; c } t("dm0") { |n| i = 0; c = 0; while i < n; c += o.dm0; i += 1; end; c } t("bm1") { |n| i = 0; c = 0; while i < n; c = o.bm1(c); i += 1; end; c } @@ -38,3 +75,11 @@ def dmcall(x) = helper(x) + 1 t("bmcall") { |n| i = 0; c = 0; while i < n; c += o.bmcall(i); i += 1; end; c } t("dmcall") { |n| i = 0; c = 0; while i < n; c += o.dmcall(i); i += 1; end; c } t("bmcapt") { |n| i = 0; c = 0; while i < n; c = o.bmcapt(c); i += 1; end; c } +t("bmh") { |n| i = 0; c = 0; while i < n; c += o.bmh_a; i += 1; end; c } +t("dmh") { |n| i = 0; c = 0; while i < n; c += o.dmh_a; i += 1; end; c } +t("bmhset") { |n| i = 0; while i < n; o.bmh_a = i; i += 1; end; o.dmh_a } +t("dmhset") { |n| i = 0; while i < n; o.dmh_a = i; i += 1; end; o.dmh_a } +t("bmconst") { |n| i = 0; c = 0; while i < n; c += o.bmconst; i += 1; end; c } +t("dmconst") { |n| i = 0; c = 0; while i < n; c += o.dmconst; i += 1; end; c } +t("bmscaled") { |n| i = 0; c = 0; while i < n; c += o.bmscaled(i); i += 1; end; c } +t("dmscaled") { |n| i = 0; c = 0; while i < n; c += o.dmscaled(i); i += 1; end; c } diff --git a/Util/dmeth-jit-matrix.rb b/Util/dmeth-jit-matrix.rb index a5f122003..9389c5181 100644 --- a/Util/dmeth-jit-matrix.rb +++ b/Util/dmeth-jit-matrix.rb @@ -239,4 +239,64 @@ module KM end row "31. constants in Class.new", [hot { |i| kc.kk(i) }, hot { |i| KM::KC.new.kk(i) }] +# Captured locals read by the body (not written): the shapes stdlib and gems write most. +class C2 + def initialize = (@h = { a: 1, b: 2, c: 3 }) + %i[a b c].each do |name| + define_method(name) { @h[name] } + define_method(:"#{name}=") { |v| @h[name] = v } + end + def self.scaled(name, k) = define_method(name) { |x| x * k } + scaled(:times2, 2) + scaled(:times3, 3) + outer = 10 + [1, 2].each do |inner| + define_method(:"two_up#{inner}") { |x| x + outer + inner } + end + recv = Object.new + def recv.helper(x) = x * 7 + define_method(:cap_recv) { |x| recv.helper(x) } + flag = nil + define_method(:cap_cond) { |x| flag ? x : -x } + define_method(:set_flag) { |v| flag = v } + val = 1 + define_method(:cap_val) { |x| val + x } + BIND = binding + shadow = 100 + define_method(:shadowed) { |x; shadow| shadow = x; shadow + 1 } + define_method(:shadow_outer) { shadow } + code = 404 + define_method(:status_code) { code } +end +c2 = C2.new +row "32. captured name per iteration", [hot { c2.a }, hot { c2.b }, hot { |i| c2.c = i; c2.c }] +row "33. captured in a method scope", [hot { |i| c2.times2(i) }, hot { |i| c2.times3(i) }] +row "34. two levels up", [hot { |i| c2.two_up1(i) }, hot { |i| c2.two_up2(i) }] +row "35. captured receiver", [hot { |i| c2.cap_recv(i) }] +r1 = hot { |i| c2.cap_cond(i) } +c2.set_flag(true) +row "36. captured flag changed by another method", [r1, hot { |i| c2.cap_cond(i) }] +r1 = hot { |i| c2.cap_val(i) } +C2::BIND.local_variable_set(:val, 2.5) +r2 = hot { |i| c2.cap_val(i) } +C2::BIND.local_variable_set(:val, 2**64) +r3 = hot { |i| c2.cap_val(i) } +C2::BIND.local_variable_set(:val, "s") +row "37. captured value changes type", [r1, r2, r3, err { c2.cap_val(1) }] +row "38. block-local shadowing", [hot { |i| c2.shadowed(i) }, hot { c2.shadow_outer }] +row "39. a captured constant value", [hot { c2.status_code }] +ths = 4.times.map { |t| Thread.new { s = 0; 20_000.times { |i| s += c2.times3(i) + c2.two_up2(t) }; s } } +row "40. threads", ths.map(&:value) + +# Assignment calls of define_method setters: the value of `o.x = v' is v whatever the method returns. +class C3 + def initialize = (@h = {}) + define_method(:x=) { |v| @h[:x] = v; :ignored } + define_method(:[]=) { |k, v| @h[k] = v * 2; :ignored } + define_method(:[]) { |k| @h[k] } + attr_reader :h +end +c3 = C3.new +row "41. assignment calls", [hot { |i| c3.x = i }, hot { |i| (c3[i % 3] = i) + c3[i % 3] }, c3.h, c3.send(:x=, 5), err { c3.send(:x=) }] + puts 'end' diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..ca2166638 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1113,6 +1113,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Round of 2026-11-26 (see Landed, perf/dmethjit, not gated): taken; `bm1` 51 -> 26.5 ns against CRuby's 24. Left: bodies over captured locals, `block_given?`/`yield` or `super`, and calls with a block or a splat, which still take the rule. + Round of 2026-11-26, second (see Landed, perf/dmethjit2, not gated): bodies that read captured + locals, and setters called as `o.x = v`, taken (`{ @h[name] }` 69.8 -> 53.3 ns, a `def` 49.7). + Left: bodies that write a captured local (4 of 154 in the stdlib and gems), `yield`/`super`, and + the `*args, &block` forwarders. 24. **Struct with `keyword_init: true`: creating an object is 3.2 times CRuby** (1162 against 369 ns; positional creation is level at 142 against 131). And `h.each_pair { |k, v| }` / `each_with_index` are 1.6 to 1.9 times CRuby (gap 13 with @@ -1450,6 +1454,54 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/dmethjit2 (2026-11-26) - a define_method body that reads captured locals, and setters, in the + method JIT (gap 23)** - not gated. Chosen by a survey of the 154 `define_method` blocks in the + standard library and the bundled gems (Prism, by parameters and what the body does with the + enclosing scopes' locals): 66 have plain or no parameters and *read* a captured local with nothing + else in the way (`{ @options[name] }`, `{ params[name] }`, `{ code }`, `{ @major_version >= v }`, + `{ |v| @h[name] = v }`), against 17 that read none (what round one took); 4 write one; the + `*args, &block` bodies of delegate.rb (`__send__(mid, *args, &block)`) are calls the typed compiler + takes in no method, and forwardable generates `def`s with `...`, not define_method. + - The change: BlockDefinition keeps the tree of a block that *assigns* no enclosing local + (`AssignedOuterVariableNames`), not only one that uses none. `JitBlockMethod.ResolveCaptured` + finds each local the block reads in the scope as many levels up from the Proc's `LocalScope` as the + lexical depths say, checking that no scope between declares the name (`RubyScope.TryGetLocalSlot`); + the def it hands the JIT is a `BlockMethodDefinition` that knows those slots, and the screen + (`JitScreen`) and `JitCompiler.EmitLocalRead` take a read of one as a call of + `JitBlockMethod.ReadCaptured` - the value in the scope's locals at that moment, an object, as the + block's own closure reads it (ScopeBuilder.CreateScope) - where they bail for any other def. And the + rule of `RubyLambdaMethodInfo` sends an assignment call (`o.x = v`, `o[k] = v`) to the stub too, + its value as the last argument (as `Methods.Yield` passes it): a setter never reached the stub. + - Instructions a call (`Util/perf/callgrind/count.sh`, N=20000; master 2f8c31c, new): `bmcapt` + (`x + captured`) 1921 -> 1255 (0.65), `bmh` (`{ @h[name] }`) 2592 -> 1892 (0.73; the `def` 1799), + `bmhset` 2359 -> 1713 (0.73; the `def` 1639), `bmconst` (`{ code }`) 1877 -> 1366 (0.73), + `bmscaled` (`{ |x| x * k }`, k a parameter of the method that called define_method) 2300 -> 1693 + (0.74); the `def` controls 1.000. + - Time (`ab.rb -r 6` on a loaded machine, ns; CRuby / master / switch off / new, new over master): + `bmcapt` 31.8 / 63.5 / 64.7 / 40.0 (0.62), `bmh` 35.7 / 69.8 / 72.6 / 53.3 (0.76; the `def` 49.7), + `bmhset` 47.3 / 65.1 / 64.8 / 43.9 (0.67; the `def` 43.2), `bmconst` 27.6 / 57.3 / 57.7 / 37.6 + (0.66), `bmscaled` 33.9 / 75.6 / 74.0 / 49.4 (0.65); `def` controls 0.93-0.99 (overlap). + - Traces: `Util/bench/app-shapes.rb` and AWFY Richards, DeltaBlue, Json, CD specialize and decline + exactly what master does (113/29, 78/19): none of their hot methods is such a body. In the matrix 15 + more define_method methods are specialized and two more are wrapped and declined (`flag ? x : -x`, + the compiler has no `-@`; `recv.helper(x)` on a captured receiver). + - Matrices, CRuby against master against new, with the JIT on, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` and `IR_JIT_DMETH=0`: `Util/dmeth-jit-matrix.rb` (41 rows now: a name captured per + iteration with its reader and writer, a captured local of a method's scope, two levels up, a captured + receiver, a captured flag another method changes, a captured value changed through Binding to a + Float, a Bignum and a String, block-local shadowing, threads, assignment calls), `dmeth-matrix`, + `jit-matrix`, `jit-calls-matrix`, `block-given-matrix`: identical to CRuby. `inline-matrix` (one + case per process): new identical to master (both differ from CRuby in `tree_int_key`, as before). + IronRuby.Tests: the 141 registered tests that use define_method or instance_method or are named for + the JIT pass. + - Also, a commit of its own: two define_method methods from the same Proc (or its dup, or its + lambda) are `==` with equal hashes, as in CRuby (`DefineMethodEquality1`), which round one found. + - For the gate: a captured local is read through the scope object found when the stub was made; a + scope whose locals tuple were replaced after that (a reused or parked scope) would be read where + the block's closure also reads it, per call, but that equivalence rests on ScopeBuilder's closure + code. More block literals keep their tree on the dispatcher with the JIT on (any that assigns no + enclosing local). + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 48495578a41d1c2b61b57ca016e85cff9c0c95a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:34:29 +0000 Subject: [PATCH 049/439] Ledger: round thirty-seven's gate passes (2f8c31c against master) IronRuby.Tests, every matrix in thirteen modes, a probe file for the gate's questions, the ruby/spec sweep, AWFY verification and timing in both orders, and start-up on the R2R host. The seven kept entries lose "not gated". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 52 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..8d74a12bd 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1450,8 +1450,44 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-26 for round thirty-seven** (perf/lglobal, perf/lexical, perf/deadconst, + perf/strsearch, perf/extiter, perf/struct, perf/dmethjit; the rejected perf/lsite's tools and + perf/jitbody's census fix): the branch `claude/happy-gauss-95wm2j` at 2f8c31c against master + f81fc19, Release net10.0, four cores: **PASS**. + IronRuby.Tests (`parallel-tests.sh`): 1,347 tests on the candidate, 1,345 on the baseline, every one + executed, no failed or flaky name on either. The script says INCOMPLETE and exits 2 on both trees + because it reads the driver's `Current culture: ` banner (an empty culture name in this container) + as a test; every listed test had an `Executing` line and every process ended `PASSED`. + `gate-matrices.rb --all` in 13 modes (the six default ones, and each switch off: `IR_LIGHT_GLOBALS`, + `IR_LIGHT_LEXICAL`, `IR_JIT_DEADCONST`, `IR_FAST_SEARCH`, `IR_FAST_NEXT`, `IR_FAST_STRUCT`, + `IR_JIT_DMETH`): 1,699 same, 403 baseline, no DIFF of the change's. callable-parameters-matrix's + `method(:puts).to_proc.source_location` is a prelude line on both trees (nil in CRuby) and moved from + ruby4.rb:13514 to 13519 because the merges added five lines above Kernel#puts; thread-backtrace-matrix's + main-thread row prints line 87 or 88 by timing on both trees (88, CRuby's, in six runs of each alone). + ffi-matrix was `cruby!` until the ffi gem was installed for CRuby, then baseline in every mode. + A probe file for the gate's questions - a million deep through a light frame that reads a global, one + with a class variable, a define_method body and a keyword Struct initialize (SystemStackError); + private, protected and `private :x` in a subclass around define_method bodies; redefinition, a + singleton method and remove_method half way; `$!` around the cursor's deferred StopIteration, loop's + result, the cause and nested loops; keyword Struct new, unknown and String keys; a global read in a + hot loop and assigned from another thread - prints CRuby's output on the candidate with the JIT on + and off (master differs in String keys, which perf/struct fixed). + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. One job + (spec/core/thread in one process) hung once under the sweep's load; ci-sweep ran its files one at a + time, all with summaries, and the batch then passed nine times out of nine (seven on the candidate, + two on master, 17-21 s each). + AWFY, 8 iterations: all fourteen verify. Timing at load about 1: micro-table in both orders, no line + more than 5% slower in both (`rangelit` 1.05 / 1.04, `veach1` 1.04 / 1.02; `empty` 1.22, `cmp` 1.19, + `poly2` 1.10 and `veach100` 1.08 in one order only). AWFY 12 in both orders: geomean new/base 0.988 + and 0.993, none more than 5% slower in both (NBody 1.016 / 1.059; Havlak 0.91 / 1.11). + Start-up on the R2R host, best of ten alternating, base -> new ms: `-e 1` 451 -> 439, `gem --version` + 472 -> 444, `gem list` 779 -> 874, `require "irb"` 871 -> 857, irb 1+1 1012 -> 999; `gem list` again, + twenty alternating runs each: best 865 -> 881, median 937 -> 942 (the 779 was one fast run). + This container refuses perf_event_open, so there is no `ab.rb -i` here; perf/lsite's + `Util/perf/callgrind/count.sh` counts instructions instead. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, + census only when merged, gated 2026-11-26 (round thirty-seven's gate entry). `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, on every call of `puts`). Only `$~` and `$_` (and what is derived from `$~`) live in the frame (RubyScope.GetInnerMostClosureScope); every other global is the runtime's (SpecialGlobalVariableInfo, @@ -1539,10 +1575,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has "overtaken" RuntimeError where CRuby answers "class variable"; `@@x` in a method of a `refine` block resolves to the refinement, CRuby to the module around it. And CRuby 4.0.10 crashes reading a class variable removed after its inline cache was warmed (a dangling cache), so the - matrix does not remove one. - census only, not gated + matrix does not remove one. - census only when merged, gated 2026-11-26 (round thirty-seven's gate entry) - **perf/deadconst (/perf-step, 2026-11-26, master f81fc19) - a statement guarded by a constant whose - value makes it dead is left out of the typed body and of a loop's copy (gap 1)** - census only, not gated. + value makes it dead is left out of the typed body and of a loop's copy (gap 1)** - census only when merged, gated 2026-11-26 (round thirty-seven's gate entry). `trace(x) if TRACING`, `log(x) unless QUIET`, `if C then a else b end` without an elsif, where C is a constant the compiler folds (`C`, `::C`, `A::B`): `JitCompiler.TryEmitConstantGuarded` resolves it as any folded read (`ResolveConstant`, so the entry's revalidation, gap 29, covers it) and emits only the @@ -1593,8 +1629,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has same question every folded constant already raises, not timed or probed beyond row 13. - **perf/strsearch (2026-11-26) - `#byteindex`/`#byterindex` with a String needle in C#, - `Regexp#match?` without a MatchData, and two searches that answered wrong (gap 21)** - not - gated. Commits ba4a151, c9a4e7c, 95d5891 on `claude/perf-strsearch`; switch + `Regexp#match?` without a MatchData, and two searches that answered wrong (gap 21)** - gated 2026-11-26 + (round thirty-seven's gate entry). Commits ba4a151, c9a4e7c, 95d5891 on `claude/perf-strsearch`; switch `IR_FAST_SEARCH=0` (both speed-ups; the fixes are not switched). The census does not see a library method's speed (0 methods moved, 28,376); judged by time, since this container has no instruction counter: `Util/perf/ab.rb -r 4 Util/bench/strsearch-shapes.rb`, CRuby / master @@ -1631,7 +1667,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has stringio/gets_spec.rb: 0 failures; 62 named MutableString/Regex IronRuby.Tests pass. - **perf/extiter (2026-11-26) - the StopIteration that ends a cursor's external iteration defers - its stack walk, and `loop` reads its result without exposing it (gap 35)** - not gated. A + its stack walk, and `loop` reads its result without exposing it (gap 35)** - gated 2026-11-26 (round thirty-seven's gate entry). A `next` over a built-in source (Array, Hash, Range, Integer#times...) runs on a cursor with no fiber already, at 67-94 ns against CRuby's 226-234; what each such iteration still paid was its end: a StopIteration thrown from C# took the catch-site walk of the whole CLR stack (22-24 us, @@ -1660,7 +1696,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (846) pass on both; 72 named IronRuby.Tests (Enumerator_*, Loop*, Backtrace*, Exception*, Raise*, Rescue*) pass. -- **perf/struct (2026-11-26, 0cfab5c..37eae81, not gated) - Struct keyword arguments stored in +- **perf/struct (2026-11-26, 0cfab5c..37eae81, gated 2026-11-26) - Struct keyword arguments stored in C#; a new struct class made without moving the global method version, its readers and its first constructions without rules (gaps 24 and 19).** Four commits, one switch (`IR_FAST_STRUCT=0`). (1) `Struct#initialize` (RubyStructOps.Initialize) stores keywords whose keys all name members @@ -1710,7 +1746,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Hash#dup` are untouched. - **perf/dmethjit (2026-11-26) - the method JIT takes the body of a method made by `define_method` - (gap 23)** - not gated. `JitBlockMethod` (Runtime/Jit) takes a block as the `def` it would be + (gap 23)** - gated 2026-11-26 (round thirty-seven's gate entry). `JitBlockMethod` (Runtime/Jit) takes a block as the `def` it would be when nothing in it tells the two apart: BlockDefinition keeps its tree on the dispatcher (`BlockDispatcher.JitAst`) when the block reads and writes none of the enclosing scope's locals, has a def's parameters (plain mandatory, then optional; no rest, post, block or keyword one) and From f4ff76a24456bf9e2a1ae06c6e25b381b92f8205 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:21:05 +0000 Subject: [PATCH 050/439] Module#dup and #clone copy the members before they call initialize_copy A module's or class's copy got its constants, methods, class variables and mixins in Module#initialize_copy (Class#initialize_copy), so an initialize_copy written in the module that read a constant before `super` read the outer one, and one that did not call super left the copy empty (LEDGER gap 37: `N.dup.constants` [] where CRuby says [:X]). CRuby 4.0 copies them in init_copy, before initialize_copy is called, and Module and Class have no initialize_copy of their own: `Module.instance_method(:initialize_copy) .owner` is Kernel. RubyModule's and RubyClass's IDuplicable.Duplicate now fill in the copy (InitializeMembersFrom, and a class copy's name cleared), and ModuleOps' and ClassOps' initialize_copy are gone, so Kernel#initialize_copy (frozen and same-class checks, no copying) is what a module or class has: initialize_copy on a module that already exists still leaves it as it is (#138), now with no flag to say so. Left: CRuby's copy of a singleton class makes initialize, initialize_copy and respond_to_missing? private in the copy (they are public singleton methods of the original); IronRuby keeps them public. Checked: ModuleCopyBeforeInitializeCopy1 (new; CRuby 4.0's output), Clone1, Dup1, CloneConstantLookup1, Main_PrivateAndInitializeCopy1, Module_CopyInvalidatesConstantLookups1; spec/core/module, spec/core/class, Kernel#dup/clone/initialize_copy/initialize_dup/ initialize_clone, spec/language class and module: as before (1050 examples in spec/core/module, the 4 known errors). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/CloningTests.cs | 43 ++++++++++++++++++++++ Src/Libraries/Builtins/ClassOps.cs | 16 +------- Src/Libraries/Builtins/ModuleOps.cs | 28 +------------- Src/Ruby/Builtins/RubyClass.cs | 23 +++--------- Src/Ruby/Builtins/RubyModule.cs | 22 ++++------- 6 files changed, 60 insertions(+), 73 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ba0c5ac85..550e03962 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1249,6 +1249,7 @@ public Tests(Driver/*!*/ driver) { Clone1, Dup1, CloneConstantLookup1, + ModuleCopyBeforeInitializeCopy1, Structs1, MetaModules1, MetaModulesDuplication1, diff --git a/Src/IronRuby.Tests/Runtime/CloningTests.cs b/Src/IronRuby.Tests/Runtime/CloningTests.cs index da88fb02b..837f7b10d 100644 --- a/Src/IronRuby.Tests/Runtime/CloningTests.cs +++ b/Src/IronRuby.Tests/Runtime/CloningTests.cs @@ -184,6 +184,49 @@ p o.foo :c1 :none :m1 +"); + } + + /// + /// #dup and #clone of a module or class copy its constants, methods and class variables before they call + /// initialize_copy, as MRI 4.0's init_copy does: an initialize_copy reading a constant before super reads the copy's, + /// one that never calls super still gets them. Module and Class have no initialize_copy of their own (Kernel's), + /// which leaves a module that already exists as it is. + /// + public void ModuleCopyBeforeInitializeCopy1() { + TestOutput(@" +K = :outer +module M + K = :inner + def self.initialize_copy(o) + p [const_get(:K), constants, instance_methods(false)] + super + end + def im = 1 +end +M.dup; M.clone +module N; X = 1; @@v = 2; def self.initialize_copy(o) = nil; def a = 1; end +n = N.dup; p n.constants, n.instance_methods(false), n.class_variables +class Q; Y = 1; def self.initialize_copy(o) = nil; def q = 1; end +q = Q.clone; p q.constants, q.instance_methods(false), q.superclass, q.name +p Module.instance_method(:initialize_copy).owner, Class.instance_method(:initialize_copy).owner +e = Module.new { def z = 1 }; c = Module.new +p c.send(:initialize_copy, e).equal?(c), c.instance_methods(false), (Module.new.send(:initialize_copy, Class.new) rescue $!) +", @" +[:inner, [:K], [:im]] +[:inner, [:K], [:im]] +[:X] +[:a] +[:@@v] +[:Y] +[:q] +Object +nil +Kernel +Kernel +true +[] +# "); } } diff --git a/Src/Libraries/Builtins/ClassOps.cs b/Src/Libraries/Builtins/ClassOps.cs index 5fa014f11..7aa0a0cab 100644 --- a/Src/Libraries/Builtins/ClassOps.cs +++ b/Src/Libraries/Builtins/ClassOps.cs @@ -38,20 +38,8 @@ public static void Reinitialize(BlockParam body, RubyClass/*!*/ self, [Optional] throw RubyExceptions.CreateTypeError("already initialized class"); } - // MRI's order: frozen, then the same class of object, then a copy only into the class #dup or - // #clone made - an existing class is left as it is (#138). - [RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)] - public static RubyClass/*!*/ InitializeCopy(RubyClass/*!*/ self, object other) { - if (self.IsFrozen) { - throw RubyExceptions.CreateObjectFrozenError(self.Context, self); - } - var otherClass = other as RubyClass; - if (otherClass == null || self.Context.GetClassOf(otherClass) != self.Context.GetClassOf(self)) { - throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); - } - self.InitializeClassCopy(otherClass); - return self; - } + // No initialize_copy: #dup and #clone fill in a class's copy before they call it (RubyClass's IDuplicable.Duplicate), + // as MRI 4.0's init_copy does, and Kernel#initialize_copy is what a class has. /// /// MRI's rb_undef_alloc_func, for a core class the prelude writes in Ruby: allocate of this class (not of a subclass) diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 18e33562d..bc03179ec 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -42,32 +42,8 @@ public static object Reinitialize(BlockParam block, RubyModule/*!*/ self) { return (block != null) ? RubyUtils.EvaluateInModule(self, block, new object[] { self }) : null; } - [RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)] - public static RubyModule/*!*/ InitializeCopy(RubyModule/*!*/ self, object other) { - // no class can be reinitialized: - if (self.IsClass) { - throw RubyExceptions.CreateTypeError("already initialized class"); - } - - if (self.IsFrozen) { - throw RubyExceptions.CreateObjectFrozenError(self.Context, self); - } - - // self could be a meta-module: - RubyClass selfClass = self.Context.GetClassOf(self); - RubyClass otherClass = self.Context.GetClassOf(other); - if (otherClass != selfClass) { - throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); - } - - // a module that already exists is left as it is; only #dup's and #clone's copy is filled in (#138) - if (!self.TakeUninitializedModuleCopy()) { - return self; - } - - self.InitializeModuleCopy((RubyModule)other); - return self; - } + // No initialize_copy: as in MRI 4.0, #dup and #clone fill in a module's copy before they call it (RubyModule's + // IDuplicable.Duplicate), and Kernel#initialize_copy is what a module has (gap 37 of Util/perf/LEDGER.md). #endregion diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index 19ed6b7d6..7cc4c7563 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -76,10 +76,6 @@ public sealed partial class RubyClass : RubyModule, IDuplicable { // if this class is a struct represents its layout: private readonly RubyStruct.Info _structInfo; - // TODO: thread safe? - // whether initialize_copy can be called (the class has just been duplicated): - private bool _isUninitializedCopy; - // Class.allocate: MRI's class has no superclass yet and can't be instantiated. private bool _isUninitializedAllocation; @@ -781,24 +777,15 @@ object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers using (Context.ClassHierarchyLocker()) { RubyClass result = Duplicate(null); - result._isUninitializedCopy = true; + // the members are copied before #dup or #clone calls initialize_copy, as MRI 4.0's init_copy does (see + // RubyModule's Duplicate); Class has no initialize_copy of its own, and Kernel's leaves a class that already + // exists as it is (#138). The copy has no name. + result.InitializeMembersFrom(this); + result.Name = null; return result; } } - public void InitializeClassCopy(RubyClass/*!*/ rubyClass) { - if (!_isUninitializedCopy) { - // MRI 4.0: a class that already exists is left as it is, no TypeError (#138) - return; - } - _isUninitializedCopy = false; - - InitializeModuleCopy(rubyClass); - - // MRI clears the name in initialize_copy: - Name = null; - } - /// /// Duplicates this class object. When duplicating singleton class a new "singletonClassOf" reference needs to be provided. /// NOT thread safe. diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 04e55b124..f8747b0f7 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -978,22 +978,14 @@ object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers // copy instance variables: _context.CopyInstanceData(this, result, false); - result._isUninitializedModuleCopy = true; - return result; - } - // Set on the module #dup and #clone make, until initialize_copy has filled it in: MRI's - // Module#initialize_copy copies only into a module allocated for the copy, and is a no-op on - // any module that already exists (#138). - private bool _isUninitializedModuleCopy; - - /// - /// Whether this module is a copy #dup or #clone made and initialize_copy has yet to fill in; - /// answering true once, as the copying then happens. - /// - public bool TakeUninitializedModuleCopy() { - bool result = _isUninitializedModuleCopy; - _isUninitializedModuleCopy = false; + // Constants, methods, class variables and mixins too, before #dup or #clone calls initialize_copy, as MRI 4.0's + // init_copy does (rb_mod_init_copy): an initialize_copy that does not call super has them, and one that reads a + // constant before super reads the copy's. Module has no initialize_copy of its own; Kernel's copies nothing, so + // initialize_copy on a module that already exists leaves it as it is (#138). + using (Context.ClassHierarchyLocker()) { + result.InitializeMembersFrom(this); + } return result; } From c958484992fbe0b16981bb64b0c36a2bda02cf47 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:21:37 +0000 Subject: [PATCH 051/439] perf: Permute's block measured; parking downto's block rejected (gap 4) Tried [BlockNotKept] on Integer#upto/#downto with both taken off NeverParkedIterators, so that parked scopes reuse the literal block's Proc and scope, as for times and each. Bytes per Permute iteration fell to 0.43 of the baseline's, time did not move, and callgrind counted more instructions (permute shape 1.043, controls 1.000): reverted. The ledger records what the measurements say about gap 4: the block-loop tier cannot take Permute's block (no bound call in a block copy, a recursive call of a method with no typed body, and the effect rule around swap's element writes), while the same block written as a while runs Permute in 0.58 of its time as generic code. The cost is the entry of any call with a literal block (about 135 ns over a plain call, against CRuby's 35-70), not the allocation and not the iterations. Kept: Util/bench/permute-shapes.rb, and two Util/block-loop-matrix.rb cases (swap redefined half way through a hot downto, a singleton swap), CRuby's output on the unchanged build in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5NtGd2eCVJ7fCeWbG --- Util/bench/permute-shapes.rb | 77 ++++++++++++++++++++++++++++++++++++ Util/block-loop-matrix.rb | 30 ++++++++++++++ Util/perf/LEDGER.md | 29 ++++++++++++++ 3 files changed, 136 insertions(+) create mode 100644 Util/bench/permute-shapes.rb diff --git a/Util/bench/permute-shapes.rb b/Util/bench/permute-shapes.rb new file mode 100644 index 000000000..e9f681d58 --- /dev/null +++ b/Util/bench/permute-shapes.rb @@ -0,0 +1,77 @@ +# Shapes for Permute (Util/perf/LEDGER.md gap 4): a call of Integer#downto with a literal block, as AWFY's +# Permute#permute makes one on most of its calls, against the same loop as a `while' and two other calls with a +# literal block, in the format Util/perf/ab.rb reads (` ns `; N from the environment; INSTR=1 +# or Util/perf/callgrind/count.sh for instructions per call). +# +# ruby Util/perf/ab.rb -i -r 1 -c none -n 20000 Util/bench/permute-shapes.rb \ +# "base=Util/perf/callgrind/count.sh ." "new=Util/perf/callgrind/count.sh ../wt-NAME" +$stdout.sync = true + +class PermShape + attr_reader :count + def initialize; @count = 0; @v = Array.new(6, 0); end + + # AWFY's Permute#permute and #swap + def permute(n) + @count += 1 + if n != 0 + n1 = n - 1 + permute(n1) + n1.downto(0) do |i| + swap(n1, i) + permute(n1) + swap(n1, i) + end + end + end + + # the same with the block written as a `while' + def permute_while(n) + @count += 1 + if n != 0 + n1 = n - 1 + permute_while(n1) + i = n1 + while i >= 0 + swap(n1, i) + permute_while(n1) + swap(n1, i) + i -= 1 + end + end + end + + def swap(i, j) + tmp = @v[i] + @v[i] = @v[j] + @v[j] = tmp + end + + def dt_call(n); k = n; n.downto(0) { |i| bump(k) }; end + def tm_call(n); k = n; (n + 1).times { |i| bump(k) }; end + def wh_call(n); k = n; i = n; while i >= 0; bump(k); i -= 1; end; end + def bump(k); @count += 1; end +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end + +o = PermShape.new +N = (ENV["N"] || 1_000_000).to_i +# a call of permute(4): 65 calls of permute, 40 of them with a downto block +t("permute", N / 50) { |n| i = 0; while i < n; o.permute(4); i += 1; end; o.count } +t("permute_while", N / 50) { |n| i = 0; while i < n; o.permute_while(4); i += 1; end; o.count } +t("dt_call", N) { |n| i = 0; while i < n; o.dt_call(1); i += 1; end; o.count } +t("tm_call", N) { |n| i = 0; while i < n; o.tm_call(1); i += 1; end; o.count } +t("wh_call", N) { |n| i = 0; while i < n; o.wh_call(1); i += 1; end; o.count } diff --git a/Util/block-loop-matrix.rb b/Util/block-loop-matrix.rb index 5fb16db28..1ee2bb9ed 100644 --- a/Util/block-loop-matrix.rb +++ b/Util/block-loop-matrix.rb @@ -602,3 +602,33 @@ def bl_fl_state(bodies) = bodies.map { |b| [b.x, b.v] } bs = bl_fl_bodies; bl_fl_loop(bs, 0.01); bs[1].instance_variable_set(:@v, 1) [bl_fl_loop(bs, 0.01), bl_fl_state(bs), bl_fl_loop(bs, 0.01), bl_fl_state(bs)] end + +# ---------------------------------------------------------------- Permute's block: a call of a method on self +# (gap 4) A hot downto whose block calls `swap' on self, a method the JIT compiles: the method redefined half way +# through the loop, and a singleton `swap' on the receiver, must be the ones the following iterations call. +class BlPerm + attr_reader :v, :log + def initialize; @v = (0...8).to_a; @log = []; end + def swap(i, j); t = @v[i]; @v[i] = @v[j]; @v[j] = t; end + def run(n, at, &event) + n.downto(0) do |i| + event.call(self) if i == at + swap(i % 8, (i + 3) % 8) + end + @v.dup + end +end +t('perm: swap redefined half way through a hot downto') do + o = BlPerm.new + 200.times { o.run(40, -1) } + r = o.run(3000, 1500) { |_| BlPerm.class_eval { def swap(i, j); @log << [i, j] if @log.size < 3; end } } + BlPerm.class_eval { def swap(i, j); t = @v[i]; @v[i] = @v[j]; @v[j] = t; end } + [r, o.log] +end +t('perm: a singleton swap on the receiver half way through a hot downto') do + o = BlPerm.new + p2 = BlPerm.new + 200.times { o.run(40, -1); p2.run(40, -1) } + r = o.run(3000, 1500) { |me| def me.swap(i, j); @log << :single if @log.size < 2; end } + [r, o.log, p2.run(3000, -1)] +end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 185a6f592..3d92c4fa8 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -762,6 +762,22 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has each call evaluates the literal once and the frame's slot is empty. `n != 0` goes through `BasicObject#!=` (gap 10), and `Object::GetType` at 4.9% is `swap`'s type guards, by that experiment's reading of the profile. + Round perf/permute (2026-11-26, on 2e9521f) measured what is left and where (see Rejected): the + block-loop tier never tries this block (runs of 1-6), and would decline it at `call: swap/2` (no + bound call in a block copy; `leaf/1` alone says the same) and then at `permute(n1)`, a recursive call + of a method that has no typed body; and since `swap` writes elements, then `permute` is called, then + `swap` runs again, any deopt after the first `swap` re-runs it - the effect rule declines the block + even with both calls bound. The method JIT declines `permute` written with a `while` too, at "a + deopt after an effect (call permute at line 44)". Yet that `while` version runs Permute in 2.39 s + against 4.10 s as written (CRuby 2.66 s, `harness.rb Permute 20 100`) as generic code: the gap is + the call with a literal block. Per call, `__send__`-driven, ns: a plain call 30, the same with any + literal block - `n.downto(0) { }`, `(n + 1).times { }`, `n.tap { }`, a Ruby method that yields once - + 160-170 (CRuby 62 and 94-133); per iteration of `downto` IronRuby is at CRuby (52 against 59 ns with + a call in the block). It is not the bytes (360 B a call, 288 of them the scope, Proc and BlockParam): + parking them for `downto` took them away and no time (below). So the next attempt is the entry of a + call with a literal block - what the rule, the BlockParam and the block's frame do per call, without + allocating - which is /perf-frame's kind of work, and which every iterator call pays, not only + Permute's. Not the loop tier. 5. **Rules bake the interpreted LightLambda of a method the JIT never wraps** (`LightLambda::Run*`, ~1% of Richards' `schedule`): a rule-level read of the body's current delegate, as b78ec3f5 did for stubs, would remove the hop once the body is @@ -4612,6 +4628,19 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/permute (2026-11-26, on 2e9521f) - `[BlockNotKept]` on Integer#upto and #downto, and both off + `NeverParkedIterators`** (gap 4). Round eight's `[BlockNotKept]` alone changed nothing, since the + Proc was made again on every call; parked scopes (later) reuse a method's literal-block Proc and + scope where the iterator is `[BlockNotKept]`, as `times` and `each` are. With both: a `downto` call + with a literal block allocates 72 B instead of 360, Permute 53.8 MB an iteration instead of 124.5 + (0.43, `alloc.rb`); time unchanged (`n.downto(0) { }` 161 against 164 ns, Permute 3.76-4.06 s + against 3.81-4.05); instructions (`callgrind/count.sh`, `Util/bench/permute-shapes.rb`, new/base): + `permute` 1.043, `dt_call` 1.023, controls `permute_while`, `tm_call`, `wh_call` 1.000. Parking + costs more instructions than the allocation it saves. Reverted; the shapes and two block-loop-matrix + cases (a `swap` on self redefined half way through a hot `downto`, a singleton `swap` on the + receiver; CRuby's output on the unchanged build with the JIT on, off and without JIT calls) kept. + What was learned is under gap 4. + - **perf/lsite (/perf-step, 2026-11-26) - a light site that remembers it needed the scope** (gap 16; switch `IR_LIGHT_REMEMBER`). In `LightFrameRewriter.MakeLightCall`, each site got a box (`StrongBox`, a constant of the body like a regex literal's cache, set From a7b9a1249b8ad05a090da2c0071176469c5bf9d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:22:53 +0000 Subject: [PATCH 052/439] LEDGER: perf/strsearch2 landed (not gated): start_with? without the caller's scope Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Util/perf/LEDGER.md | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..50a9b2dcc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1086,9 +1086,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and a BINARY needle (wrong answers); all three are dealt with. **Still open:** `s.index('"')` not found in 10 KB is 198 ns against 109 (profile: 59% in `PackedSpanHelpers.IndexOf`, the search over 20 KB of UTF-16; the rest is the call) - only a receiver held as bytes - would close it; `#start_with?` 134 / 212 ns against 55 / 90 (its caller makes a - `RubyMethodScope`, since the method takes the scope for a Regexp prefix's `$~`: gap 16 - / a scope-free overload); `#byteindex` on UTF-8 found late is 1.3 us against 117 ns + would close it; `#start_with?` 134 / 212 ns against 55 / 90 (done in round two, see + Landed: perf/strsearch2); `#byteindex` on UTF-8 found late is 1.3 us against 117 ns (the UTF-8 length of the prefix, `Encoding.UTF8.GetByteCount`, 1.1 us over 10 KB of mixed text), and from a positive offset other than 0 it walks the characters to it, so a strscan-style loop of byte offsets over UTF-8 text is quadratic where CRuby's is not. @@ -1450,6 +1449,36 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/strsearch2 (2026-11-26) - `#start_with?` with one String prefix takes no scope; an + ASCII prefix is compared in place (gap 21, round two)** - not gated. Commit dc1d136 on + `claude/perf-strsearch`, based on the merged branch 2f8c31c. `start_with?` had one overload, + which takes the caller's scope to store `$~` for a Regexp prefix, so a light frame calling it + with a String made its scope on the call (`RubyOps.LightScopeRequired`) and called again. A + second overload takes one MutableString and no scope (not switchable: an overload is + registered or not); a Regexp, a `#to_str` object or several prefixes still take the first. An + ASCII prefix of two bytes or more on an ASCII-compatible receiver is compared as characters or + bytes where both strings are, instead of `GetByteCount`/`GetByte` per byte (which also switch + a non-ASCII receiver held as characters to bytes); `IR_FAST_SEARCH=0` turns that off. The + census moved nothing (28,376 methods). Callgrind (`Util/perf/callgrind/count.sh`, N=20000), + instructions a call, base / off / new: sw1_a 3,473 / 2,645 / 2,724, sw3_a 4,704 / 3,862 / 2,850, + sw1_u 3,434 / 2,625 / 2,685, sw3_u 4,185 / 3,341 / 2,818, sw1_b 3,331 / 2,522 / 2,601, sw3_b + 4,278 / 3,434 / 2,862; controls idx1_a_e, short_idx, size within 0.6%. The in-place compare + costs the same for any length (about 2,790), so a one-byte prefix keeps the byte loop; the + check that decides it costs about 80 instructions there (+3% against off, overlapping in + time). Time, four alternating rounds, ns, CRuby / base / off / new: + + sw1_a 54.4 / 122.4 / 63.8 / 65.3 sw3_a 85.7 / 194.4 / 138.0 / 88.9 (0.64 of off) + sw1_u 51.9 / 119.8 / 60.0 / 62.8 sw3_u 92.3 / 167.1 / 107.2 / 90.8 (0.85) + sw1_b 52.0 / 119.9 / 67.6 / 67.5 sw3_b 105.6 / 179.9 / 115.8 / 101.0 (0.87) + controls overlap: idx1_a_e 67.2 -> 66.9, short_idx 84.5 -> 87.9, size 48.0 -> 47.2 + + Checked: `Util/string-search-matrix.rb` with 1,255 more `start_with?` rows (Shift_JIS trail + bytes, EUC-JP, broken UTF-8 leads and continuations, BINARY, UTF-16, several prefixes, a + Regexp among them, nil, none; 57,489 rows) prints CRuby 4.0's output on the base and on this + build in both modes; spec/core/string (3,963 examples) and spec/library/stringscanner (240): + the same on both builds, 0 failures, one error on both (`String.try_convert ... raises + TypeError if it's not a kind of String`, run as a directory). + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From bf035161c8169a6d3eeaa6a44834cb4b8b08f5e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:23:53 +0000 Subject: [PATCH 053/439] Ledger: perf/lexical3 rejected by measurement; gap 38, the cost of a keyword call into a rest The idea perf/lexical2 named - bind the positionals of `def m(a, *r, k: 1)` in the calling convention rather than out of one splat - was measured before any code (Util/perf/callgrind/count.sh, instructions a call) and rejected: the comparison it came from set a rest method against `kr_kw`, which the method JIT specializes (1,557, and 4,017 with -X:NoJIT), and the splat lowering costs about nothing net (`def v_unused(*a, k: 1) = 3` 4,798 against a plain rest method given the same keyword call, 4,815). The cost is the keyword call into a rest parameter (about 1,400 over the same Hash passed positionally; without a rest the two cost the same) and the keyword prologue (about 1,300-1,500 outside the JIT). Gap 38 records both with the shapes, now in prelude-cost.rb, and perf/lexical2's entry points at it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/bench/prelude-cost.rb | 22 +++++++++++++++++++++ Util/perf/LEDGER.md | 40 +++++++++++++++++++++++++++++++++++--- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/Util/bench/prelude-cost.rb b/Util/bench/prelude-cost.rb index 04b282a73..f3770c198 100644 --- a/Util/bench/prelude-cost.rb +++ b/Util/bench/prelude-cost.rb @@ -323,6 +323,13 @@ def kw(a, k: 1) = a + k def rest(*a, k: 1) = a.size + k def inner(*a, **o) = a.size + o.size def pass(*a, **o) = inner(*a, **o) + def plain_rest(*a) = a.size + 2 + def lead_rest(x, *a, k: 1) = x + a.size + k + # gap 38: where a keyword call to a rest method spends + def v_hash_into_rest(*a) = a.size + 1 + def v_unused(*a, k: 1) = 3 + def v_kwrest(*a, **o) = a.size + o.size + def v_two(a, b) = a end def cpu @@ -486,3 +493,18 @@ def t(name, n) t("kr_rest", N) { |n| i = 0; s = 0; while i < n; s += kr.rest(i, k: 2); i += 1; end; s } t("kr_pass", N) { |n| i = 0; s = 0; while i < n; s += kr.pass(i, k: 2); i += 1; end; s } t("kr_lines", N) { |n| i = 0; s = 0; while i < n; kl.each_line(chomp: true) { |l| s += l.size }; i += 1; end; s } +# where a keyword call to a rest method spends (gap 38 of Util/perf/LEDGER.md): the same rest method with no keyword, a +# positional Hash, a Hash literal and a keyword call; a keyword method that ignores its keyword; a method without a rest +# given the same three, which are alike there +t("kr_plain_rest", N) { |n| i = 0; s = 0; while i < n; s += kr.plain_rest(i); i += 1; end; s } +t("kr_lead_rest", N) { |n| i = 0; s = 0; while i < n; s += kr.lead_rest(i, k: 2); i += 1; end; s } +t("v_hash_into_rest", N) { |n| i = 0; s = 0; while i < n; s += kr.v_hash_into_rest(i, k: 2); i += 1; end; s } +t("v_unused", N) { |n| i = 0; s = 0; while i < n; s += kr.v_unused(i, k: 2); i += 1; end; s } +t("v_kwrest", N) { |n| i = 0; s = 0; while i < n; s += kr.v_kwrest(i, k: 2); i += 1; end; s } +KH = {k: 2} +t("v_prebuilt_hash", N) { |n| i = 0; s = 0; while i < n; s += kr.v_hash_into_rest(i, KH); i += 1; end; s } +t("v_two_positionals", N) { |n| i = 0; s = 0; while i < n; s += kr.v_hash_into_rest(i, 2); i += 1; end; s } +t("v_hash_literal_arg", N) { |n| i = 0; s = 0; while i < n; s += kr.v_hash_into_rest(i, {k: 2}); i += 1; end; s } +t("v_two_kw", N) { |n| i = 0; s = 0; while i < n; s += kr.v_two(i, k: 2); i += 1; end; s } +t("v_two_lit", N) { |n| i = 0; s = 0; while i < n; s += kr.v_two(i, {k: 2}); i += 1; end; s } +t("v_two_pos", N) { |n| i = 0; s = 0; while i < n; s += kr.v_two(i, 2); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 6c0885d2a..42960d67b 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1451,6 +1451,24 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `initialize_copy`, where CRuby has copied them before it (a `const_get` in an `initialize_copy` before `super` sees the copy's constants there, the outer ones here). +38. **A keyword call into a method with a rest parameter, and the keyword prologue, outside + the method JIT** (perf/lexical3, measured with `Util/perf/callgrind/count.sh`, instructions + a call, shapes in `prelude-cost.rb`; the method JIT specializes a trivial keyword method, + so these are the costs of every keyword method it does not take). A rest method given a + keyword call pays about 1,400 more than given the same Hash positionally: + a rest method `def r(*a) = a.size + 1` called `(i)` 2,559 (`kr_plain_rest`), and + `v_hash_into_rest` called `(i, 2)` 2,638, `(i, KH)` 2,762, + `(i, {k: 2})` 3,416, `(i, k: 2)` 4,815 - and a keyword method with a rest the same + (`def v_unused(*a, k: 1) = 3` 4,798, `kr_rest` 5,325), so it is the call into the rest, + not that method's prologue. Without a rest parameter the keyword call costs what the + literal does (`def v_two(a, b)`, JIT off: positional 1,745, `{k: 2}` 2,404, `k: 2` + 2,435). Suspects, not yet bisected: `RubyOps.NormalizeRestArgument` (a non-keyword rest + method keeps a copy of the hash) and what the rule for a site with a keyword hash does + for a rest callee (`ArgsBuilder` with a keyword signature takes no `GetRestTakesListFrom` + path, `RubyMethodInfo.GetDispatcher` none for a rest). Separately, the keyword prologue of + `def kw(a, k: 1) = a + k` costs about 1,300-1,500 with the JIT off (4,017 against + `v_two_kw` 2,435) in either lowering. Not the splat lowering: see Rejected, perf/lexical3. + ## Landed - **perf/lexical2 (/perf-step, 2026-11-26, on 2f8c31c) - keywords beside a rest or post @@ -1487,9 +1505,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (0.93), `kr_lines` (`"ab".each_line(chomp: true) { }`) 17,670 -> 17,436 (0.99); the controls `kr_kw` (`def kw(a, k: 1)`, light before) and `x_const` 1.00. Below perf-frame's 15% bar for a shape: the scope was not most of what these calls cost. `kr_rest` is still - 3.4 times `kr_kw`; the next step for this shape is the lowering itself - binding the - positionals in the calling convention, as `def m(a, b = 1, k: 2)` already is - (`KeywordsAfterOptionals`), instead of out of one splat - not the frame. Not timed. + 3.4 times `kr_kw`; the next step for this shape was thought to be the lowering itself - + binding the positionals in the calling convention - which perf/lexical3 measured and + rejected: `kr_kw` was specialized by the method JIT, and the cost is the keyword call into + a rest and the keyword prologue (gap 38). Not timed. - `Util/keyword-rest-light-matrix.rb` (new: the signatures, binding errors, positional Hash, `**nil`, defaults, binding, local_variables, block_given?, zsuper with a rest and with `**rest`, super_method, send, Method#call, to_proc, arity and parameters, redefinition, @@ -4607,6 +4626,21 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/lexical3 (/perf-step, 2026-11-26, on 3cabf57) - bind the positionals of `def m(a, *r, + k: 1)` in the calling convention instead of out of one splat** (the idea perf/lexical2's entry + named), rejected by measurement before any code. The premise was `kr_rest` 5,325 + instructions against `kr_kw` 1,557. But `kr_kw` is specialized by the method JIT (4,017 with + `-X:NoJIT`), and the splat lowering costs about nothing net: `def v_unused(*a, k: 1) = 3` + (the whole lowering and prologue, nothing used) 4,798 against `def v_hash_into_rest(*a)` + given the same keyword call 4,815, and against a rest method of the same shape called with + one positional, 2,559. What a keyword call to such a method pays is the call into the rest + (about 1,400 over a positional Hash) and, in every keyword method outside the JIT, the + keyword prologue (about 1,300-1,500): gap 38, with the shapes in `prelude-cost.rb`. The + prelude's methods of this shape (`String#each_line`, `#lines`, `Kernel#warn`, `IO.read`) + have no positionals before the rest, so there was nothing to bind in the convention + anyway. Learned: compare keyword shapes with the method JIT off (or check that it declined + both), and with a control that passes the same Hash positionally. + - **perf/lsite (/perf-step, 2026-11-26) - a light site that remembers it needed the scope** (gap 16; switch `IR_LIGHT_REMEMBER`). In `LightFrameRewriter.MakeLightCall`, each site got a box (`StrongBox`, a constant of the body like a regex literal's cache, set From 9daaab25c4e65d6380e84bf0f6425088ebd319d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:29:26 +0000 Subject: [PATCH 054/439] Make String#dup String's own: a bare string is copied without its hooks In CRuby String#dup is rb_str_dup_m, defined on String: a bare string - of class String itself, with no singleton class and no instance variables - is copied as it is (str_duplicate) and neither initialize_dup nor initialize_copy is called, even when they are redefined in String, Object or Kernel or by a prepended module; any other string goes through rb_obj_dup, which calls them. IronRuby had only Kernel#dup, so it called the hooks for every string, and String.instance_method(:dup).owner was Kernel. MutableStringOps.Duplicate does what rb_str_dup_m does; IR_FAST_DUP=0 sends every string through Kernel#dup as before. The new Util/dup-matrix.rb (String, Object and Array dup and clone: contents, encodings, broken bytes, frozen and chilled strings, instance variables, singleton classes, subclasses, a refinement, TracePoint, the hooks redefined and restored) now prints CRuby's output; master differed in six rows. The other matrices in every mode, spec/core/string and the Kernel dup/clone specs: as on master. It was tried as a speed-up of String#dup (2.4 times CRuby) and is not one: 11% fewer instructions (3,688 -> 3,291 per call with the shape's driver), but the same time in a method's loop (100-113 ns against 104-109; CRuby 55). The ledger says so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Libraries/Builtins/MutableStringOps.cs | 26 ++++ Util/bench/dup-shapes.rb | 4 + Util/dup-matrix.rb | 142 +++++++++++++++++++++ Util/perf/LEDGER.md | 21 +++ 4 files changed, 193 insertions(+) create mode 100644 Util/dup-matrix.rb diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index e72793c5f..ffc238cd8 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -699,6 +699,32 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { return self.Replace(other); } + /// + /// String#dup, MRI's rb_str_dup_m: a bare string - of class String itself, with no singleton class and no instance + /// variables - is copied as it is (str_duplicate: the content and the encoding, neither frozen nor chilled) without + /// calling initialize_dup or initialize_copy, whatever they are; any other goes through Kernel#dup (rb_obj_dup), which + /// calls them. IR_FAST_DUP=0 sends every string through Kernel#dup. + /// + [RubyMethod("dup")] + public static object/*!*/ Duplicate( + CallSiteStorage>/*!*/ initializeCopyStorage, + CallSiteStorage>/*!*/ allocateStorage, + MutableString/*!*/ self) { + + if (FastDup && self.GetType() == typeof(MutableString) && IsBare(allocateStorage.Context, self)) { + return self.CreateInstance().Replace(self); + } + return KernelOps.Duplicate(initializeCopyStorage, allocateStorage, self); + } + + private static readonly bool FastDup = Environment.GetEnvironmentVariable("IR_FAST_DUP") != "0"; + + // BARE_STRING_P: no instance variables and the class String itself (the caller has seen the CLR type is MutableString, + // so the class is String unless the string has a singleton class). + private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { + return !context.HasInstanceVariables(self) && !context.GetImmediateClassOf(self).IsSingletonClass; + } + [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static MutableString/*!*/ Reinitialize(MutableString/*!*/ self, [NotNull]byte[] other) { self.Clear(); diff --git a/Util/bench/dup-shapes.rb b/Util/bench/dup-shapes.rb index cd442b0e0..b87a47580 100644 --- a/Util/bench/dup-shapes.rb +++ b/Util/bench/dup-shapes.rb @@ -33,6 +33,8 @@ def t(name, n) H3 = { a: 1, b: 2, c: 3 } X = {} O = Object.new +class OIc; def initialize = (@a = 1; @b = 2); def size = 2; end +OI = OIc.new HI = { a: 1 }.tap { |h| h.instance_variable_set(:@x, 1) } A3 = [1, 2, 3] S3 = "abc" @@ -49,3 +51,5 @@ def t(name, n) t("size", N) { |n| i = 0; c = 0; while i < n; c += H3.size + i; i += 1; end; c } t("clone", N) { |n| i = 0; c = 0; while i < n; c += H3.clone.size + i; i += 1; end; c } t("dup_ivar", N) { |n| i = 0; c = 0; while i < n; c += HI.dup.size + i; i += 1; end; c } +t("oi_dup", N) { |n| i = 0; c = 0; while i < n; c += OI.dup.size + i; i += 1; end; c } +t("str_clone", N) { |n| i = 0; c = 0; while i < n; c += S3.clone.size + i; i += 1; end; c } diff --git a/Util/dup-matrix.rb b/Util/dup-matrix.rb new file mode 100644 index 000000000..e7f98b440 --- /dev/null +++ b/Util/dup-matrix.rb @@ -0,0 +1,142 @@ +# Expression matrix for #dup of a String, a plain Object and an Array (perf/strdup's fast path, +# IR_FAST_DUP), with #clone beside it: what the copy holds - content, encoding, broken bytes, +# frozen and chilled state, instance variables, singleton methods - and that initialize_dup and +# initialize_copy are still called when they are not the built-ins: redefined in String, Object +# or Kernel, through a prepended or included module, on a subclass, refined, traced by +# TracePoint, and restored again. (Util/hash-dup-matrix.rb does the same for Hash.) +# +# ruby Util/dup-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/dup-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +# +# Every line is " => " or " !! : ". The rows of +# EXPRESSIONS run cold, again and 200 times, and a line says so when a later answer differs from +# the first; those of ONCE change a hook for good and undo it, in order, each run once with its +# dup warm (200 times). +# -*- frozen_string_literal: false -*- + +class SubString < String; end +class CopyString < String + def initialize_copy(o) = (super; @copied = true; self) +end +class Plain + def initialize(a = 1) = (@a = a) + attr_reader :a +end +class PlainCopy < Plain + def initialize_copy(o) = (super; @a = [:copied, o.a]; self) +end +module StrHook + def initialize_copy(o) = (super; concat("+pre"); self) +end +module StrInc + def initialize_copy(o) = (super; concat("+inc"); self) +end +module ObjHook + def initialize_copy(o) = (super; @hooked = true; self) +end +module RefineDup + refine String do + def initialize_copy(o) = (super; concat("+ref"); self) + end +end +module UsingRefineDup + using RefineDup + def self.dup_it = "abc".dup +end +S = "abc" +B = "a\xffb".b +U = "\xff\xfe".dup.force_encoding("UTF-8") +O = Plain.new(5) +A = [1, [2], "s"] +def dup_n(x) = (r = nil; 200.times { r = x.dup }; r) +def dups(x) = (d = x.dup; [d, d.class, d.frozen?, d.equal?(x)]) +def ivars(x) = x.instance_variables.map { |v| [v, x.instance_variable_get(v)] } + +EXPRESSIONS = <<~'RUBY'.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + dups(S) + dups("lit") + (d = "lit".dup; d << "x"; d) + dups("x".freeze) + ("x".freeze.dup << "y") + (s = "chill"; d = s.dup; d << "!"; [d, s]) + dups(:sym.to_s) + dups(1.to_s) + (d = S.dup; d << "d"; [S, d]) + (d = S.dup; d.replace("q"); [S, d]) + [B.dup, B.dup.encoding, B.dup.valid_encoding?] + [U.dup.encoding, U.dup.valid_encoding?, U.dup.bytes] + ["é".dup.encoding, "é".dup.ascii_only?, "e".dup.ascii_only?, "é".encode("UTF-16LE").dup.encoding] + (s = "abc".dup; s.instance_variable_set(:@x, 1); ivars(s.dup)) + (s = "abc".dup; def s.extra = 1; [s.dup.respond_to?(:extra), s.clone.respond_to?(:extra)]) + (s = "abc".dup; s.singleton_class.define_method(:initialize_copy) { |o| super(o); concat("!") }; [s.dup, s.clone]) + [SubString.new("q").dup, SubString.new("q").dup.class] + [CopyString.new("q").dup, CopyString.new("q").dup.instance_variable_get(:@copied)] + ("a" * 1000).dup.size + [String.instance_method(:dup).owner, String.instance_method(:dup).arity, Object.instance_method(:dup).owner] + (s = "a" * 100; d = s.dup; d[0] = "b"; [s[0], d[0]]) + S.clone + S.freeze.clone.frozen? + "lit".clone.frozen? + (s = "abc".freeze; [s.clone(freeze: false).frozen?, s.clone(freeze: true).frozen?]) + UsingRefineDup.dup_it + (calls = []; s = "s".dup; tp = TracePoint.new(:c_call) { |t| calls << t.method_id if t.method_id.to_s.start_with?("initialize") }; tp.enable { s.dup }; calls) + (calls = []; s = "s".dup; s.instance_variable_set(:@i, 1); tp = TracePoint.new(:c_call) { |t| calls << t.method_id if t.method_id.to_s.start_with?("initialize") }; tp.enable { s.dup }; calls) + (calls = []; o = Object.new; tp = TracePoint.new(:c_call) { |t| calls << t.method_id if t.method_id.to_s.start_with?("initialize") }; tp.enable { o.dup }; calls) + Thread.new { 100.times.map { S.dup.size }.uniq }.value + # --- a plain object + (d = O.dup; [d.class, d.a, d.equal?(O), ivars(d)]) + (o = Plain.new([1]); d = o.dup; d.a.equal?(o.a)) + (o = Plain.new.freeze; [o.dup.frozen?, o.clone.frozen?]) + (o = Plain.new; def o.extra = 1; [o.dup.respond_to?(:extra), o.clone.respond_to?(:extra)]) + (o = Plain.new; o.singleton_class.define_method(:initialize_copy) { |x| super(x); @sing = 1 }; [ivars(o.dup), ivars(o.clone)]) + (d = PlainCopy.new(3).dup; d.a) + Object.new.dup.class + BasicObject.new.__send__(:dup) rescue "#{$!.class}: #{$!.message}" + (o = Object.new; o.instance_variable_set(:@q, 2); ivars(o.dup)) + Class.new(Plain).new(7).dup.a + # --- an Array + (d = A.dup; [d, d.equal?(A), d[1].equal?(A[1])]) + (d = A.dup; d << 4; [A.size, d.size]) + [[].dup, [1].freeze.dup.frozen?, [1].freeze.clone.frozen?] +RUBY + +ONCE = <<~'RUBY'.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + [dup_n(S), dup_n(O).a, dup_n(A)] + (class String; alias_method :__saved_copy__, :initialize_copy; def initialize_copy(o) = (__saved_copy__(o); concat("+mine"); self); end; dup_n(S)) + (class String; alias_method :initialize_copy, :__saved_copy__; remove_method :__saved_copy__; end; dup_n(S)) + (class Object; def initialize_copy(o) = (super; @obj = 1; self); end; [dup_n(O).instance_variable_get(:@obj), dup_n(S)]) + (class Object; remove_method :initialize_copy; end; [dup_n(O).instance_variables, dup_n(S)]) + (class Object; def initialize_dup(o) = (super; @odup = 1; self); end; [dup_n(O).instance_variable_get(:@odup), dup_n(S).instance_variable_get(:@odup)]) + (class Object; remove_method :initialize_dup; end; [dup_n(O).instance_variables, dup_n(S).instance_variables]) + (module Kernel; alias_method :__saved_dup__, :initialize_dup; def initialize_dup(o) = (__saved_dup__(o); @kdup = 1; self); end; [dup_n(O).instance_variable_get(:@kdup), dup_n(S).instance_variable_get(:@kdup)]) + (module Kernel; alias_method :initialize_dup, :__saved_dup__; remove_method :__saved_dup__; end; [dup_n(O).instance_variables, dup_n(S)]) + (module Kernel; alias_method :__saved_kcopy__, :initialize_copy; def initialize_copy(o) = (__saved_kcopy__(o); @kcopy = 1; self); end; [dup_n(O).instance_variable_get(:@kcopy), dup_n(S)]) + (module Kernel; alias_method :initialize_copy, :__saved_kcopy__; remove_method :__saved_kcopy__; end; dup_n(O).instance_variables) + (String.prepend(StrHook); dup_n(S)) + (StrHook.send(:remove_method, :initialize_copy); dup_n(S)) + (String.include(StrInc); dup_n(S)) + (Plain.include(ObjHook); dup_n(O).instance_variable_get(:@hooked)) + (ObjHook.send(:remove_method, :initialize_copy); dup_n(O).instance_variables) + [S.clone, O.clone.a, "x".freeze.clone.frozen?] +RUBY + +def clean(v) = v.inspect.gsub(/0x\h+/, "XX") +def run(source) + "=> #{clean(eval(source))}" +rescue Exception => e + "!! #{e.class}: #{e.message.gsub(/0x\h+/, "XX")}" +end + +EXPRESSIONS.each do |source| + first = run(source) + second = run(source) + warm = nil + 200.times { warm = run(source) } + line = "#{source} #{first}" + line += " [second: #{second}]" if second != first + line += " [warm: #{warm}]" if warm != first + puts line +end +ONCE.each { |source| puts "#{source} #{run(source)}" } +puts "done" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 3e07bb024..908a24efb 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1130,6 +1130,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (noisy). In the same loop `String#dup` is 2.4 times CRuby (137-142 ns against 56) and `Array#dup` 1.15 times (143-146 against 124): the generic Kernel#dup path, worth a gap of its own (`Util/bench/dup-shapes.rb`). + perf/strdup (see Landed): String#dup without the hooks, as CRuby's, is no faster on the clock + (100-113 against 104-109 ns, CRuby 55); the gap is elsewhere in the call or the copy. 25. **Havlak: 1.4 times CRuby, 25 times TruffleRuby, and no single place** (round sixteen's breakdown; its author's numbers, taken beside two other experiments at load 2-14, so ratios). CRuby runs a copy with som.rb's `Set` renamed to `SomSet`: 2.85-3.3 @@ -1456,6 +1458,25 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/strdup (2026-11-26, not gated) - `String#dup` is String's own, MRI's rb_str_dup_m** (gap + 24's dup note). Kept as a CRuby-compatibility fix, not as a speed-up. `Util/dup-matrix.rb` (new: String, + Object and Array dup and clone - content, encodings, broken bytes, frozen and chilled, ivars, + singleton classes, subclasses, a refinement, TracePoint, and the hooks redefined in String, Object + and Kernel or by prepend and include, then restored) showed master differing from CRuby in six + rows. In CRuby `String#dup` belongs to String: a bare string (class String itself, no singleton + class, no instance variables) is copied without calling initialize_dup or initialize_copy, even + redefined; any other goes through rb_obj_dup. `MutableStringOps.Duplicate` does that now, so the + matrix prints CRuby's output (switch `IR_FAST_DUP=0`: every string through Kernel#dup, as before). + Instructions (`callgrind/count.sh`, `dup-shapes.rb`): `str_dup` 3,688 -> 3,291; `str_clone`, + `hash_dup`, `clone`, `obj_dup`, `oi_dup` (an object with ivars), `arr_dup` and `plain` level. + Time in a method's loop, three alternating runs: `S.dup` 104-109 ns on master, 100-113 here, CRuby + 55 - no gain; controls within the noise. So the hooks were not what String#dup spends: the 50 ns + over CRuby lie in the call of the library method and the copy (CreateInstance, Replace's content + clone), still to be found. Checks: dup, hash-dup, struct, hash-struct, jit and hot-shapes matrices + in every mode and with the switch off: PASS (dup-matrix `same`, `baseline -2` switched off). + spec/core/string and kernel dup/clone: 4,010 examples, the one known try_convert wording error + on both builds. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 98baf5bea1ad0357f7b609d4149988d4dc75bd03 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:32:26 +0000 Subject: [PATCH 055/439] Bridge a hot call with its spent dispatcher until the compiled rule lands (experiment) A call whose LibraryDispatcher has spent its budget got a rule light-compiled at threshold 2: LightCompile served the few calls until the background compile landed. Here the spent dispatcher makes those calls again instead, and the rule's lambda (built as DynamicUtils.LightBind builds it) is compiled in the background at once; when it lands the dispatcher declines and the site's next bind gets the compiled rule, once per decline (a thread-static, as the DLR's LastInterpretedFailure). IR_HOT_BRIDGE=0 turns it off. Rejected and reverted in the next commit: only 40-55 rules of `gem list' and irb take this path now, for 0.2-0.8% of the main thread's instructions, while `-e 1' and `gem --version' (no bridge) count 0.06-0.08% more. Util/perf/LEDGER.md gap 26 has the numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/Ruby/Runtime/Calls/LibraryDispatcher.cs | 152 +++++++++++++++++++- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 9 ++ Src/Ruby/Runtime/Calls/RubyMetaBinder.cs | 53 ++++++- Src/Ruby/Runtime/Loader.cs | 5 + 4 files changed, 211 insertions(+), 8 deletions(-) diff --git a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs index e1d4d252e..e05ac6ed2 100644 --- a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs @@ -869,14 +869,152 @@ private void OnSpent() { } } - // One call more made through the dispatcher, of the budget it may make (see _remaining) + // One call more made through the dispatcher, of the budget it may make (see _remaining). A spent dispatcher that bridges + // (see _bridge) makes its calls with the budget at 0 and leaves it there. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Spend() { - if (--_remaining == 0) { + if (_remaining > 0 && --_remaining == 0) { OnSpent(); } } + // Whether the dispatcher may make a call: it has budget left, or it bridges to a rule still being compiled. + private bool HasBudget { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return _remaining > 0 || _bridge != null && _bridge.IsPending; } + } + + /// + /// IR_HOT_BRIDGE=0: the rule of a hot call (see ) is light-compiled and run interpreted until its background + /// compilation lands, rather than the spent dispatcher making the calls (see ). + /// + internal static readonly bool HotBridgeEnabled = Environment.GetEnvironmentVariable("IR_HOT_BRIDGE") != "0"; + + /// + /// The rule of a hot call, compiled in the background while the spent dispatcher that made the call hot makes its calls again. + /// + /// + /// A hot call's rule was light-compiled (the interpreter's instructions, a CallInstruction per new method signature, the + /// LightLambda's delegate) and then, two calls later, compiled in the background (see GetRuleCompilationThreshold): the light + /// compile served the few calls until the compiled rule landed - 40-55 of the ~250 rules `gem list' and irb build. + /// The spent dispatcher has made 200 such calls already: it makes them until the compiled rule lands. It then declines them, and + /// the bind that follows a decline - the call is hot, and the dispatcher would take it - hands out the compiled rule (as the + /// interpreter hands out a compiled rule, DynamicUtils.LightBind). + /// + internal abstract class Bridge { + // 0 compiling, 1 compiled, 2 failed (the site binds a rule as it did before): + private int _state; + + internal bool IsPending { + get { return Volatile.Read(ref _state) == 0; } + } + + internal bool IsCompiled { + get { return Volatile.Read(ref _state) == 1; } + } + + protected void Complete(bool compiled) { + Volatile.Write(ref _state, compiled ? 1 : 2); + } + + internal abstract object CompiledTarget { get; } + } + + internal sealed class Bridge : Bridge where T : class { + private T _compiled; + + internal void Start(Expression/*!*/ rule) { + new System.Threading.Tasks.Task(() => { + try { + _compiled = rule.Compile(); + Complete(true); + } catch (Exception) { + Complete(false); + } + }).Start(); + } + + internal override object CompiledTarget { + get { return _compiled; } + } + } + + // set once, when the dispatcher bridges (see TryBridge): + private volatile Bridge _bridge; + + /// + /// Has a spent dispatcher of the binder that would take a call on the target make the calls again until the rule of this call, + /// compiled in the background, lands: returns the dispatcher's delegate of the site's type - or the compiled rule, if the + /// dispatcher has bridged and the rule has landed - or null if there is no such dispatcher (or it bridges to a rule of another + /// type, or one not compiled yet: the site gets a rule of its own, as before). + /// + internal static T TryBridge(RubyCallAction/*!*/ binder, object target, object[]/*!*/ args) where T : class { + var spent = Volatile.Read(ref binder.SpentDispatchers); + if (spent == null) { + return null; + } + LibraryDispatcher dispatcher = null; + for (int i = 0; i < spent.Length; i++) { + if (spent[i].IsCurrent(target)) { + dispatcher = spent[i]; + break; + } + } + if (dispatcher == null) { + return null; + } + var current = dispatcher._bridge; + if (current != null) { + // the compiled rule, once for each decline: should its test fail for this call, the site's next bind builds a rule + // of its own, as an interpreted rule's site does when its compiled rule fails (DynamicUtils.LightBind) + if (LandedBridge != current) { + return null; + } + LandedBridge = null; + var compiled = current.CompiledTarget as T; + if (compiled != null && compiled.GetType() == typeof(T)) { + if (PhaseTimer.BindTrace) PhaseTimer.BindKind = "bridge-landed"; + return compiled; + } + return null; + } + object result = dispatcher.CreateDelegate(MethodDispatcher.UntypedFuncs.Contains(typeof(T))); + if (result.GetType() != typeof(T)) { + return null; + } + var rule = binder.BuildRuleLambda(args); + var bridge = new Bridge(); + #pragma warning disable 420 // a reference to a volatile field is not treated as volatile: Interlocked is + if (Interlocked.CompareExchange(ref dispatcher._bridge, bridge, null) != null) { + #pragma warning restore 420 + return null; + } + bridge.Start(rule); + if (PhaseTimer.BindTrace) PhaseTimer.BindKind = "bridge"; + return (T)result; + } + + // The bridge whose dispatcher declined a call it would have made because the rule has landed, for the bind that follows on + // this thread (see TryBridge): + [ThreadStatic] + private static Bridge LandedBridge; + + // A spent dispatcher declines the call, unless it bridges to a rule that has not landed yet: + [MethodImpl(MethodImplOptions.NoInlining)] + private bool CanCallSpent(object self) { + var bridge = _bridge; + if (bridge == null || !IsCurrent(self)) { + return false; + } + if (bridge.IsPending) { + return true; + } + if (bridge.IsCompiled) { + LandedBridge = bridge; + } + return false; + } + private void SetBudget(RubyCallAction/*!*/ binder, RubyContext/*!*/ context) { _binder = binder; _remaining = GetInitialBudget(context); @@ -965,7 +1103,7 @@ private static bool SaveInterpretedFrames(Exception/*!*/ exception) { /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool CanCall(object self) { - return _remaining > 0 && IsCurrent(self); + return (_remaining > 0) ? IsCurrent(self) : CanCallSpent(self); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -1044,7 +1182,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje if (_rubyCall != null) { // the rule passes the block and the arguments as they are (RubyMethodInfo.BuildCallNoFlow): Proc rubyBlock = blockArg as Proc; - if (_remaining <= 0 || blockArg != null && rubyBlock == null || _splatCount >= 0 && (args = ExpandSplat(args)) == null) { + if (!HasBudget || blockArg != null && rubyBlock == null || _splatCount >= 0 && (args = ExpandSplat(args)) == null) { result = null; return false; } @@ -1059,7 +1197,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje if (_send != null) { Proc sendBlock = blockArg as Proc; - if (_remaining <= 0 || blockArg != null && sendBlock == null || !_send.Matches(args)) { + if (!HasBudget || blockArg != null && sendBlock == null || !_send.Matches(args)) { result = null; return false; } @@ -1074,7 +1212,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje if (_construction != null) { Proc initializerBlock = blockArg as Proc; - if (_remaining <= 0 || !_construction.IsCurrent(args.Length) || blockArg != null && initializerBlock == null) { + if (!HasBudget || !_construction.IsCurrent(args.Length) || blockArg != null && initializerBlock == null) { result = null; return false; } @@ -1088,7 +1226,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje } Proc block = blockArg as Proc; - if (_remaining <= 0 || blockArg != null && block == null || + if (!HasBudget || blockArg != null && block == null || _splatCount >= 0 && ((args = ExpandSplat(args)) == null || _splatCount > 0 && RubyOps.IsKeywordArgumentsHash(args[args.Length - 1])) || !Matches(block, args)) { result = null; diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index dc8cb4682..3191c0704 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -115,6 +115,15 @@ internal override int GetRuleCompilationThreshold(object[]/*!*/ args, RubyContex LibraryDispatcher.GetRuleCompilationThreshold(this, args[targetIndex], context) : context.CompilationThreshold; } + internal override T BindBridge(object[]/*!*/ args, RubyContext/*!*/ context) { + int targetIndex = Signature.HasScope ? 1 : 0; + if (!LibraryDispatcher.HotBridgeEnabled || Context == null || targetIndex >= args.Length || + context.Loader.HoldsBackCompilation) { + return null; + } + return LibraryDispatcher.TryBridge(this, args[targetIndex], args); + } + protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ args) { // IsVariableCall only decides which error a call that finds no method raises; a dispatcher // is only made for a method that was found, and hands every other case back to the diff --git a/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs b/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs index 158169490..2bc36bea0 100644 --- a/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs +++ b/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs @@ -137,11 +137,62 @@ private T BindDelegateNoTiming(CallSite site, object[] args) where T : cla return result; } - result = this.LightBind(args, (argArray == null) ? GetRuleCompilationThreshold(args, context) : context.CompilationThreshold); + if (argArray != null || (result = BindBridge(args, context)) == null) { + result = this.LightBind(args, (argArray == null) ? GetRuleCompilationThreshold(args, context) : context.CompilationThreshold); + } CacheTarget(result); return result; } + /// + /// The delegate of a spent dispatcher that makes a hot call until its rule, compiled in the background, lands, or that rule + /// once it has - or null (see ). + /// + internal virtual T BindBridge(object[]/*!*/ args, RubyContext/*!*/ context) where T : class { + return null; + } + + /// + /// The rule a bind for the arguments builds, as a lambda of the site's type: the rule's test, its action, and the site's + /// update where the test fails - the lambda an interpreted rule compiles in the background (DynamicUtils.LightBind). + /// + internal Expression/*!*/ BuildRuleLambda(object[]/*!*/ args) where T : class { + var parameters = RuleParameters.Parameters; + var targetMO = DynamicMetaObject.Create(args[0], parameters[1]); + var argsMO = new DynamicMetaObject[args.Length - 1]; + for (int i = 0; i < argsMO.Length; i++) { + argsMO[i] = DynamicMetaObject.Create(args[i + 1], parameters[i + 2]); + } + var binding = Bind(targetMO, argsMO); + var body = Ast.Condition( + binding.Restrictions.ToExpression(), + AstUtils.Convert(binding.Expression, RuleParameters.Update.Type), + RuleParameters.Update + ); + return Ast.Lambda(body, "CallSite.Target", true, parameters); + } + + // The parameters and the update of a rule lambda of the delegate type (see DynamicUtils.LightBind): + private static class RuleParameters where T : class { + internal static readonly System.Collections.ObjectModel.ReadOnlyCollection/*!*/ Parameters; + internal static readonly Expression/*!*/ Update; + + static RuleParameters() { + var methodParams = typeof(T).GetMethod("Invoke").GetParameters(); + var prms = new ParameterExpression[methodParams.Length]; + var invokeArgs = new Expression[methodParams.Length]; + for (int i = 0; i < methodParams.Length; i++) { + prms[i] = Ast.Parameter(methodParams[i].ParameterType); + invokeArgs[i] = (i == 0) ? (Expression)Ast.Convert(prms[i], typeof(CallSite)) : prms[i]; + } + Parameters = new System.Collections.ObjectModel.ReadOnlyCollection(prms); + Update = Ast.Block( + Ast.Label(CallSiteBinder.UpdateLabel), + Ast.Invoke(Ast.Property(invokeArgs[0], typeof(CallSite).GetProperty("Update")), invokeArgs) + ); + } + } + // Links a precompiled dispatcher to the one the site holds now, if that serves receivers this one does not (see MemberDispatcher.Next). // The dispatcher is not published yet, so its fields need no synchronization: the DLR publishes the delegate as the site's target. private static void ChainDispatcher(CallSite/*!*/ site, T/*!*/ result) where T : class { diff --git a/Src/Ruby/Runtime/Loader.cs b/Src/Ruby/Runtime/Loader.cs index 4de7a2dc7..f57179559 100644 --- a/Src/Ruby/Runtime/Loader.cs +++ b/Src/Ruby/Runtime/Loader.cs @@ -1329,6 +1329,11 @@ private void EndAutoloads(List autoloads, string/ // later `load "ruby4.rb"` by a program is not. private Thread _corePreludeLoaderThread; + // The core prelude is loading, with background compilations held back (see LoadCorePrelude): + internal bool HoldsBackCompilation { + get { return _corePreludeLoaderThread != null; } + } + // The directory of the core prelude's ruby4.rb, with a trailing separator, once it has started. private string _corePreludeDirectory; From 7c1c0bc764b631466778f3dc4d6c9c01d604a831 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:32:42 +0000 Subject: [PATCH 056/439] Revert the hot-call bridge; record perf/startup as rejected (gap 26) The bridge (previous commit) saves 0.2-0.8% of the main thread's instructions on `gem list', `require "irb"' and irb, and costs `-e 1' and `gem --version' 0.06-0.08%, which never bridge: only 40-55 rules are still hot at start-up. LEDGER.md gap 26 has the numbers and what to measure next. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/Ruby/Runtime/Calls/LibraryDispatcher.cs | 152 +------------------- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 9 -- Src/Ruby/Runtime/Calls/RubyMetaBinder.cs | 53 +------ Src/Ruby/Runtime/Loader.cs | 5 - Util/perf/LEDGER.md | 30 ++++ 5 files changed, 38 insertions(+), 211 deletions(-) diff --git a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs index e05ac6ed2..e1d4d252e 100644 --- a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs @@ -869,152 +869,14 @@ private void OnSpent() { } } - // One call more made through the dispatcher, of the budget it may make (see _remaining). A spent dispatcher that bridges - // (see _bridge) makes its calls with the budget at 0 and leaves it there. + // One call more made through the dispatcher, of the budget it may make (see _remaining) [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Spend() { - if (_remaining > 0 && --_remaining == 0) { + if (--_remaining == 0) { OnSpent(); } } - // Whether the dispatcher may make a call: it has budget left, or it bridges to a rule still being compiled. - private bool HasBudget { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { return _remaining > 0 || _bridge != null && _bridge.IsPending; } - } - - /// - /// IR_HOT_BRIDGE=0: the rule of a hot call (see ) is light-compiled and run interpreted until its background - /// compilation lands, rather than the spent dispatcher making the calls (see ). - /// - internal static readonly bool HotBridgeEnabled = Environment.GetEnvironmentVariable("IR_HOT_BRIDGE") != "0"; - - /// - /// The rule of a hot call, compiled in the background while the spent dispatcher that made the call hot makes its calls again. - /// - /// - /// A hot call's rule was light-compiled (the interpreter's instructions, a CallInstruction per new method signature, the - /// LightLambda's delegate) and then, two calls later, compiled in the background (see GetRuleCompilationThreshold): the light - /// compile served the few calls until the compiled rule landed - 40-55 of the ~250 rules `gem list' and irb build. - /// The spent dispatcher has made 200 such calls already: it makes them until the compiled rule lands. It then declines them, and - /// the bind that follows a decline - the call is hot, and the dispatcher would take it - hands out the compiled rule (as the - /// interpreter hands out a compiled rule, DynamicUtils.LightBind). - /// - internal abstract class Bridge { - // 0 compiling, 1 compiled, 2 failed (the site binds a rule as it did before): - private int _state; - - internal bool IsPending { - get { return Volatile.Read(ref _state) == 0; } - } - - internal bool IsCompiled { - get { return Volatile.Read(ref _state) == 1; } - } - - protected void Complete(bool compiled) { - Volatile.Write(ref _state, compiled ? 1 : 2); - } - - internal abstract object CompiledTarget { get; } - } - - internal sealed class Bridge : Bridge where T : class { - private T _compiled; - - internal void Start(Expression/*!*/ rule) { - new System.Threading.Tasks.Task(() => { - try { - _compiled = rule.Compile(); - Complete(true); - } catch (Exception) { - Complete(false); - } - }).Start(); - } - - internal override object CompiledTarget { - get { return _compiled; } - } - } - - // set once, when the dispatcher bridges (see TryBridge): - private volatile Bridge _bridge; - - /// - /// Has a spent dispatcher of the binder that would take a call on the target make the calls again until the rule of this call, - /// compiled in the background, lands: returns the dispatcher's delegate of the site's type - or the compiled rule, if the - /// dispatcher has bridged and the rule has landed - or null if there is no such dispatcher (or it bridges to a rule of another - /// type, or one not compiled yet: the site gets a rule of its own, as before). - /// - internal static T TryBridge(RubyCallAction/*!*/ binder, object target, object[]/*!*/ args) where T : class { - var spent = Volatile.Read(ref binder.SpentDispatchers); - if (spent == null) { - return null; - } - LibraryDispatcher dispatcher = null; - for (int i = 0; i < spent.Length; i++) { - if (spent[i].IsCurrent(target)) { - dispatcher = spent[i]; - break; - } - } - if (dispatcher == null) { - return null; - } - var current = dispatcher._bridge; - if (current != null) { - // the compiled rule, once for each decline: should its test fail for this call, the site's next bind builds a rule - // of its own, as an interpreted rule's site does when its compiled rule fails (DynamicUtils.LightBind) - if (LandedBridge != current) { - return null; - } - LandedBridge = null; - var compiled = current.CompiledTarget as T; - if (compiled != null && compiled.GetType() == typeof(T)) { - if (PhaseTimer.BindTrace) PhaseTimer.BindKind = "bridge-landed"; - return compiled; - } - return null; - } - object result = dispatcher.CreateDelegate(MethodDispatcher.UntypedFuncs.Contains(typeof(T))); - if (result.GetType() != typeof(T)) { - return null; - } - var rule = binder.BuildRuleLambda(args); - var bridge = new Bridge(); - #pragma warning disable 420 // a reference to a volatile field is not treated as volatile: Interlocked is - if (Interlocked.CompareExchange(ref dispatcher._bridge, bridge, null) != null) { - #pragma warning restore 420 - return null; - } - bridge.Start(rule); - if (PhaseTimer.BindTrace) PhaseTimer.BindKind = "bridge"; - return (T)result; - } - - // The bridge whose dispatcher declined a call it would have made because the rule has landed, for the bind that follows on - // this thread (see TryBridge): - [ThreadStatic] - private static Bridge LandedBridge; - - // A spent dispatcher declines the call, unless it bridges to a rule that has not landed yet: - [MethodImpl(MethodImplOptions.NoInlining)] - private bool CanCallSpent(object self) { - var bridge = _bridge; - if (bridge == null || !IsCurrent(self)) { - return false; - } - if (bridge.IsPending) { - return true; - } - if (bridge.IsCompiled) { - LandedBridge = bridge; - } - return false; - } - private void SetBudget(RubyCallAction/*!*/ binder, RubyContext/*!*/ context) { _binder = binder; _remaining = GetInitialBudget(context); @@ -1103,7 +965,7 @@ private static bool SaveInterpretedFrames(Exception/*!*/ exception) { /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool CanCall(object self) { - return (_remaining > 0) ? IsCurrent(self) : CanCallSpent(self); + return _remaining > 0 && IsCurrent(self); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -1182,7 +1044,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje if (_rubyCall != null) { // the rule passes the block and the arguments as they are (RubyMethodInfo.BuildCallNoFlow): Proc rubyBlock = blockArg as Proc; - if (!HasBudget || blockArg != null && rubyBlock == null || _splatCount >= 0 && (args = ExpandSplat(args)) == null) { + if (_remaining <= 0 || blockArg != null && rubyBlock == null || _splatCount >= 0 && (args = ExpandSplat(args)) == null) { result = null; return false; } @@ -1197,7 +1059,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje if (_send != null) { Proc sendBlock = blockArg as Proc; - if (!HasBudget || blockArg != null && sendBlock == null || !_send.Matches(args)) { + if (_remaining <= 0 || blockArg != null && sendBlock == null || !_send.Matches(args)) { result = null; return false; } @@ -1212,7 +1074,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje if (_construction != null) { Proc initializerBlock = blockArg as Proc; - if (!HasBudget || !_construction.IsCurrent(args.Length) || blockArg != null && initializerBlock == null) { + if (_remaining <= 0 || !_construction.IsCurrent(args.Length) || blockArg != null && initializerBlock == null) { result = null; return false; } @@ -1226,7 +1088,7 @@ internal bool TryInvoke(RubyScope/*!*/ scope, object self, object blockArg, obje } Proc block = blockArg as Proc; - if (!HasBudget || blockArg != null && block == null || + if (_remaining <= 0 || blockArg != null && block == null || _splatCount >= 0 && ((args = ExpandSplat(args)) == null || _splatCount > 0 && RubyOps.IsKeywordArgumentsHash(args[args.Length - 1])) || !Matches(block, args)) { result = null; diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 3191c0704..dc8cb4682 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -115,15 +115,6 @@ internal override int GetRuleCompilationThreshold(object[]/*!*/ args, RubyContex LibraryDispatcher.GetRuleCompilationThreshold(this, args[targetIndex], context) : context.CompilationThreshold; } - internal override T BindBridge(object[]/*!*/ args, RubyContext/*!*/ context) { - int targetIndex = Signature.HasScope ? 1 : 0; - if (!LibraryDispatcher.HotBridgeEnabled || Context == null || targetIndex >= args.Length || - context.Loader.HoldsBackCompilation) { - return null; - } - return LibraryDispatcher.TryBridge(this, args[targetIndex], args); - } - protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ args) { // IsVariableCall only decides which error a call that finds no method raises; a dispatcher // is only made for a method that was found, and hands every other case back to the diff --git a/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs b/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs index 2bc36bea0..158169490 100644 --- a/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs +++ b/Src/Ruby/Runtime/Calls/RubyMetaBinder.cs @@ -137,62 +137,11 @@ private T BindDelegateNoTiming(CallSite site, object[] args) where T : cla return result; } - if (argArray != null || (result = BindBridge(args, context)) == null) { - result = this.LightBind(args, (argArray == null) ? GetRuleCompilationThreshold(args, context) : context.CompilationThreshold); - } + result = this.LightBind(args, (argArray == null) ? GetRuleCompilationThreshold(args, context) : context.CompilationThreshold); CacheTarget(result); return result; } - /// - /// The delegate of a spent dispatcher that makes a hot call until its rule, compiled in the background, lands, or that rule - /// once it has - or null (see ). - /// - internal virtual T BindBridge(object[]/*!*/ args, RubyContext/*!*/ context) where T : class { - return null; - } - - /// - /// The rule a bind for the arguments builds, as a lambda of the site's type: the rule's test, its action, and the site's - /// update where the test fails - the lambda an interpreted rule compiles in the background (DynamicUtils.LightBind). - /// - internal Expression/*!*/ BuildRuleLambda(object[]/*!*/ args) where T : class { - var parameters = RuleParameters.Parameters; - var targetMO = DynamicMetaObject.Create(args[0], parameters[1]); - var argsMO = new DynamicMetaObject[args.Length - 1]; - for (int i = 0; i < argsMO.Length; i++) { - argsMO[i] = DynamicMetaObject.Create(args[i + 1], parameters[i + 2]); - } - var binding = Bind(targetMO, argsMO); - var body = Ast.Condition( - binding.Restrictions.ToExpression(), - AstUtils.Convert(binding.Expression, RuleParameters.Update.Type), - RuleParameters.Update - ); - return Ast.Lambda(body, "CallSite.Target", true, parameters); - } - - // The parameters and the update of a rule lambda of the delegate type (see DynamicUtils.LightBind): - private static class RuleParameters where T : class { - internal static readonly System.Collections.ObjectModel.ReadOnlyCollection/*!*/ Parameters; - internal static readonly Expression/*!*/ Update; - - static RuleParameters() { - var methodParams = typeof(T).GetMethod("Invoke").GetParameters(); - var prms = new ParameterExpression[methodParams.Length]; - var invokeArgs = new Expression[methodParams.Length]; - for (int i = 0; i < methodParams.Length; i++) { - prms[i] = Ast.Parameter(methodParams[i].ParameterType); - invokeArgs[i] = (i == 0) ? (Expression)Ast.Convert(prms[i], typeof(CallSite)) : prms[i]; - } - Parameters = new System.Collections.ObjectModel.ReadOnlyCollection(prms); - Update = Ast.Block( - Ast.Label(CallSiteBinder.UpdateLabel), - Ast.Invoke(Ast.Property(invokeArgs[0], typeof(CallSite).GetProperty("Update")), invokeArgs) - ); - } - } - // Links a precompiled dispatcher to the one the site holds now, if that serves receivers this one does not (see MemberDispatcher.Next). // The dispatcher is not published yet, so its fields need no synchronization: the DLR publishes the delegate as the site's target. private static void ChainDispatcher(CallSite/*!*/ site, T/*!*/ result) where T : class { diff --git a/Src/Ruby/Runtime/Loader.cs b/Src/Ruby/Runtime/Loader.cs index f57179559..4de7a2dc7 100644 --- a/Src/Ruby/Runtime/Loader.cs +++ b/Src/Ruby/Runtime/Loader.cs @@ -1329,11 +1329,6 @@ private void EndAutoloads(List autoloads, string/ // later `load "ruby4.rb"` by a program is not. private Thread _corePreludeLoaderThread; - // The core prelude is loading, with background compilations held back (see LoadCorePrelude): - internal bool HoldsBackCompilation { - get { return _corePreludeLoaderThread != null; } - } - // The directory of the core prelude's ruby4.rb, with a trailing separator, once it has started. private string _corePreludeDirectory; diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..bb543ceca 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1257,6 +1257,36 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has crossing costs so much: past the threshold the shape still ran at ~50-150 us a call for hundreds of calls before its compiled code took over (steady state is 1.7 us); that cold stretch, not the IL compile, is the next thing to look at. + 2026-11-26, perf/startup (rejected, 98baf5b): lever 1 of perf/first-bind - keep the spent + dispatcher answering until the hot call's rule, compiled in the background, lands. Measured + first (R2R host, base 2f8c31c, `IR_BIND_TRACE`): the lever has shrunk since perf/first-bind + counted it. `gem list` builds 241 rules (80 ms of 2,942 binds' 183 ms inclusive), irb 268 + (90 ms), and only 43 / 51 of them are hot (bound after a dispatcher spent its budget). The + rest are first rules with no dispatcher in front. Tried: for a hot call, + `LibraryDispatcher.TryBridge` builds the rule's lambda as `DynamicUtils.LightBind` does, + starts its compile at once, and hands the site the spent dispatcher's delegate. The + dispatcher makes the calls with no budget until the compiled rule lands, then declines. + The bind after a decline gets the compiled rule once (a thread-static, as the DLR's + `LastInterpretedFailure`: without that once-only guard, a compiled rule whose test fails for + the call is handed out again forever, and `gem list` hung). Not during the core prelude, + whose compiles are held back. A bridge bind costs ~170 us against ~330 for a rule bind. + Main-thread instructions (callgrind, `DOTNET_TieredCompilation=0`, R2R host) base -> new: + `-e 1` 2,091.4 -> 2,092.8 M (+0.06%, three runs each, spread 0.1 M), `gem --version` 2,271.8 + -> 2,273.6 (+0.08%), `gem list` 3,447-3,459 -> 3,426-3,433 (-0.4..-1.0%), `require "irb"` + 3,482 -> 3,461-3,466 (-0.5%), irb 1+1 3,709 -> 3,700 (-0.2%). All threads: `gem list` -0.9%, + irb -0.4%, so starting the compiles earlier costs nothing elsewhere. Wall, best of 10 + alternating, load ~1: 360/352, 410/418, 715/701, 724/719, 782/775 ms (all within +-2%). + Steady state unchanged: AWFY 8 s DeltaBlue/Json/Richards within 2% (a 3 s run showed + DeltaBlue and Json 36% slower, which was noise), micro-table no line >5% slower in both + orders except s_map4, which is equal alone (medians 194.5 / 196.8 ns). Matrices + (shared-rule-light, hot-shapes, jit, jit-calls) in 7 modes, with `IR_HOT_BRIDGE=0` and + `IR_CONFIG=R2R`: PASS; hot-shapes-matrix makes 923 bridges. Rejected: 0.2-0.8% on three + commands, a fixed +0.06-0.08% on the two that never bridge (dispatcher and bind paths; + not the thread-static, which moving off the common bind path did not change), and ~210 + lines of cross-thread hand-off. Learned: what is left of first-bind cost is the ~200 first + rules per tool, not hot ones, so levers 2 (`CallInstruction` per signature) and 3 (typed + sites rebinding what untyped ones warmed) should be measured before anything is built. + Their perf/first-bind sizes (9-16, 6-16 ms) are as stale as lever 1's 18-21 ms was. 27. **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a From b58fecbfd1d226348c9662aeb9c46a7fc91164c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:35:44 +0000 Subject: [PATCH 057/439] Take next on with_index and with_object enumerators with a cursor over the source's Enumerator#with_index (and so #each_with_index) and #with_object made without a block are generators of the prelude, whose external iteration ran on a fiber, a thread here: 6-12 us of process CPU per #next against CRuby's 0.25-0.34. What they yield is a step of their source with its index or memo beside it, and the source usually has a cursor of its own (Array, Hash, Range, times, each_slice, map, another with_index). The prelude now marks the enumerator it returns with its source and offset or memo, and a marked one whose generator is still that one and whose #each is the built-in one gets an IndexCursor over the source's cursor. What the block answers goes on to the source's suspended yield, as MRI's with_index_i and with_object_i answer it. Enumerable#each_with_index gets the same cursor over a Hash, a Range or a Struct; it had one for an Array only. IR_FAST_NEXT=0 leaves them to the fiber. Two prelude fixes go with it, in every mode. The #with_index generator answered `i += 1` to its source, so `[1, 2].map.with_index` with :q fed collected [2, 3] (CRuby: [:q, nil]) and select.with_index kept everything. And #with_object's StopIteration#result was the source's answer, not the memo. The enumerator is returned without a local: the generator closes over the method's scope, and a local holding it kept abandoned fiber-backed ones alive until the process ran out of memory. Util/bench/extiter-shapes.rb (ab.rb -r 6, ns per next, off -> new): each.with_index 6302 -> 325 (CRuby 267), a Hash's each_with_index 8468 -> 304, map.with_index 6448 -> 368, each.with_object 6183 -> 204; the controls overlap when run alone. Util/extiter-matrix.rb (222 probes, 44 new) prints CRuby's output with the change and switched off; enum-next, block-loop, hash-order, raise, full-message, enum, enumerable2 and jit matrices agree with the baseline. spec/core/enumerator, kernel/loop, hash and enumerable give the same result in all three modes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Src/Libraries/Builtins/Enumerator.cs | 125 +++++++++++++++++++++++++-- Src/StdLib/ironruby/ruby4.rb | 14 ++- Util/bench/extiter-shapes.rb | 5 +- Util/extiter-matrix.rb | 49 +++++++++++ Util/perf/LEDGER.md | 62 ++++++++++--- 5 files changed, 235 insertions(+), 20 deletions(-) diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index ae2130776..c9a464b38 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -499,6 +499,71 @@ internal override bool MoveNext(out object value) { } } + // Enumerator#with_index, #each_with_index and #with_object made without a block (the prelude's generators, marked by + // __iter_index_source__), and Enumerable#each_with_index over a receiver whose #each a cursor walks: the source's step + // with its index, or the memo, beside it - [value, index], the values of a step of several packed into an Array as the + // generator's `a.size <= 1 ? a.first : a` packs them. What the block answers goes on to the source's suspended yield + // (with_index_i and with_object_i answer it), so `map.with_index` collects it. + private sealed class IndexCursor : ExternalCursor { + private readonly ExternalCursor/*!*/ _inner; + private readonly bool _withObject; + private readonly object _memo; + // the generator answers what the source's #each answers; Enumerable#each_with_index answers its receiver + private readonly bool _answersReceiver; + private long _index; + + internal IndexCursor(object receiver, ExternalCursor/*!*/ inner, long offset, bool answersReceiver) : base(receiver) { + _inner = inner; + _index = offset; + _answersReceiver = answersReceiver; + } + + internal IndexCursor(object receiver, ExternalCursor/*!*/ inner, object memo) : base(receiver) { + _inner = inner; + _withObject = true; + _memo = memo; + } + + internal override bool Multiple { + get { return true; } + } + + internal override bool MoveNext(out object value) { + object step; + if (!_inner.MoveNext(out step)) { + value = null; + return false; + } + if (_inner.Multiple) { + var stepValues = (RubyArray)step; + step = (stepValues.Count == 0) ? null : (stepValues.Count == 1) ? stepValues[0] : new RubyArray(stepValues); + } + var values = new RubyArray(2); + values.Add(step); + if (_withObject) { + values.Add(_memo); + } else { + long index = _index++; + values.Add((index >= Int32.MinValue && index <= Int32.MaxValue) ? + ScriptingRuntimeHelpers.Int32ToObject((int)index) : (object)(BigInteger)index); + } + value = values; + return true; + } + + internal override void Resume(object fed) { + _inner.Resume(fed); + } + + internal override void Finish() { + _inner.Finish(); + } + + internal override object Result { + get { return _withObject ? _memo : _answersReceiver ? Receiver : _inner.Result; } + } + } + // Array#reverse_each (rb_ary_reverse_each): from the length the iteration started with, down, // moving the position back when the Array has shrunk below it in the meantime. private sealed class ArrayReverseCursor : ExternalCursor { @@ -736,7 +801,7 @@ private static ExternalCursor TryCreateCursor(RubyContext/*!*/ context, Enumerat object generator; if (context.TryGetInstanceVariable(self, RubyUtils.GetCoreStateInstanceVariableName("@__generator__"), out generator) && generator != null) { - return null; + return TryCreateIndexCursor(context, self, generator); } if (!IsBuiltinMethod(context, self, "each", typeof(Enumerator), "EachFromCaller")) { @@ -807,10 +872,19 @@ private static ExternalCursor TryCreateCursor(RubyContext/*!*/ context, Enumerat case "each_with_index": // the prelude's #each_with_index, the built-in one it hands a block to, and the #each that one calls - return (array = target as RubyArray) != null && - IsPreludeMethod(context, target, name, GetPreludeMethods(context).EachWithIndex) && - IsBuiltinMethod(context, target, "__each_with_index_without_args__", typeof(Enumerable), "GetEachWithIndexEnumerator", "EachWithIndex") && - IsBuiltinMethod(context, target, "each", typeof(IListOps), "Each") ? new ArrayWithIndexCursor(array) : null; + if (!IsPreludeMethod(context, target, name, GetPreludeMethods(context).EachWithIndex) || + !IsBuiltinMethod(context, target, "__each_with_index_without_args__", typeof(Enumerable), "GetEachWithIndexEnumerator", "EachWithIndex")) { + return null; + } + if ((array = target as RubyArray) != null) { + return IsBuiltinMethod(context, target, "each", typeof(IListOps), "Each") ? new ArrayWithIndexCursor(array) : null; + } + // a Hash, a Range, a Struct: the steps of its #each with their index, and the receiver for the result + if (!_fastNext) { + return null; + } + ExternalCursor eachCursor = TryCreateEachCursor(context, target); + return eachCursor != null ? new IndexCursor(target, eachCursor, 0, true) : null; case "times": if (target is int && IsBuiltinMethod(context, target, name, typeof(Integer), "Times")) { @@ -852,6 +926,47 @@ private static ExternalCursor TryCreateCollectCursor(RubyContext/*!*/ context, o return inner != null ? new EnumerableCollectCursor(target, inner, kind) : null; } + // What the prelude's #with_index (#each_with_index) and #with_object made without a block are over, while their generator + // is the one they made (an #initialize again replaces it; a copy has no mark): see __iter_index_source__. + private Enumerator _indexSource; + private object _indexArgument; + private bool _indexWithObject; + private object _indexGenerator; + + /// + /// Marks the generator enumerator the prelude's #with_index or #with_object has just made as one over , + /// so that #next walks it with a cursor over the source's when the source has one, rather than on a fiber. + /// + [RubyMethod("__iter_index_source__", RubyMethodAttributes.PrivateInstance)] + public static Enumerator/*!*/ MarkIndexSource(RubyContext/*!*/ context, Enumerator/*!*/ self, object source, object argument, bool withObject) { + var enumerator = source as Enumerator; + object generator; + if (enumerator != null && self._indexGenerator == null && + context.TryGetInstanceVariable(self, RubyUtils.GetCoreStateInstanceVariableName("@__generator__"), out generator) && generator != null) { + self._indexSource = enumerator; + self._indexArgument = argument; + self._indexWithObject = withObject; + self._indexGenerator = generator; + } + return self; + } + + // A marked generator enumerator whose #each is the built-in one, over a source that has a cursor of its own; an index + // that is not a Fixnum leaves it to the fiber. IR_FAST_NEXT=0 leaves them all to it. + private static ExternalCursor TryCreateIndexCursor(RubyContext/*!*/ context, Enumerator/*!*/ self, object generator) { + if (!_fastNext || self._indexGenerator == null || !ReferenceEquals(generator, self._indexGenerator) || + (!self._indexWithObject && !(self._indexArgument is int)) || + !IsBuiltinMethod(context, self, "each", typeof(Enumerator), "EachFromCaller")) { + return null; + } + ExternalCursor inner = TryCreateCursor(context, self._indexSource); + if (inner == null) { + return null; + } + return self._indexWithObject ? new IndexCursor(self, inner, self._indexArgument) : + new IndexCursor(self, inner, (int)self._indexArgument, false); + } + // The receiver's own #each, when it is a built-in one a cursor can do. private static ExternalCursor TryCreateEachCursor(RubyContext/*!*/ context, object target) { RubyArray array; diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 4ccdfefcd..a342f5bf2 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -5562,10 +5562,14 @@ def with_index(*args) # yield [value, index] pairs, lazily, via the generator form above source = self n = source.size + # each step answers what the yield answered, which is what reaches a method enumerated + # through to_enum: `map.with_index` collects what was fed to it (MRI's with_index_i) + # Enumerator#next walks it with a cursor over the source's, when the source has one (Enumerator.cs). + # No local may hold the enumerator: the generator closes over this scope, and its fiber would keep it alive. return Enumerator.new(n) { |y| i = offset - source.each { |*a| y.yield(a.size <= 1 ? a.first : a, i); i += 1 } - }.__set_inspect__(self, :with_index, args) + source.each { |*a| answer = y.yield(a.size <= 1 ? a.first : a, i); i += 1; answer } + }.__set_inspect__(self, :with_index, args).__send__(:__iter_index_source__, source, offset, false) end i = offset each do |*args| @@ -5592,8 +5596,10 @@ def with_object(memo) unless block_given? source = self n = source.size - return Enumerator.new(n) { |y| source.each { |*a| y.yield(a.size <= 1 ? a.first : a, memo) } } - .__set_inspect__(self, :with_object, [memo]) + # it answers the memo, and so does StopIteration#result at the end of its #next (MRI's with_object) + # (no local holds the enumerator, as in #with_index) + return Enumerator.new(n) { |y| source.each { |*a| y.yield(a.size <= 1 ? a.first : a, memo) }; memo } + .__set_inspect__(self, :with_object, [memo]).__send__(:__iter_index_source__, source, memo, true) end each do |*args| yield(args.size <= 1 ? args.first : args, memo) diff --git a/Util/bench/extiter-shapes.rb b/Util/bench/extiter-shapes.rb index 673d303a4..8942074c8 100644 --- a/Util/bench/extiter-shapes.rb +++ b/Util/bench/extiter-shapes.rb @@ -60,9 +60,12 @@ def peeks(e) t("range_map", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain((1..1000).map) }; s } t("hash_find_all", n(20_000)) { |n| s = 0; (n / 100).times { s += drain(HSH.find_all) }; s } t("ewi_next", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.each.with_index) }; s } +t("hash_ewi", n(20_000)) { |n| s = 0; (n / 100).times { e = HSH.each_with_index; 100.times { s += e.next[1] } }; s } +t("map_wi", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.map.with_index) }; s } +t("wobj_next", n(20_000)) { |n| s = 0; (n / 1000).times { e = LARGE.each.with_object(1); 1000.times { s += e.next[0] } }; s } t("select_next", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.select) }; s } t("lazy_next", n(5_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.lazy.map { |x| x + 1 }) }; s } t("produce", n(20_000)) { |n| s = 0; (n / 1000).times { e = Enumerator.produce(1) { |x| x + 1 }; 1000.times { s += e.next } }; s } t("zip_enum", n(20_000)) { |n| s = 0; (n / 1000).times { LARGE.zip(LARGE.each) { |a, b| s += a + b } }; s } -# controls: these keep their fiber (a generator; with_index, lazy and produce above too) +# controls: these keep their fiber (a generator; lazy and produce above too) t("generator", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(Enumerator.new { |y| LARGE.each { |x| y << x } }) }; s } diff --git a/Util/extiter-matrix.rb b/Util/extiter-matrix.rb index d42ba73b6..26c730070 100644 --- a/Util/extiter-matrix.rb +++ b/Util/extiter-matrix.rb @@ -534,3 +534,52 @@ def fed_result(e, feeds) probe("coll_thread") { e = [1, 2].select; e.next; Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value } probe("coll_frozen_feed") { e = [1].map; e.next; e.freeze; (e.feed(1) rescue $!.class) } probe("coll_inspect") { e = [1, 2].select; e.next; e.inspect } + +# --- with_index, each_with_index and with_object made without a block, taken with #next ------------- +probe("wi_offsets") { [[:a, :b].each.with_index.next, [:a].each.with_index(nil).next, [:a].each.with_index(3).next, [:a].each.with_index(-2).next] } +probe("wi_float_offset") { e = [:a, :b].each.with_index(1.7); [e.next, e.next] } +probe("wi_to_int_offset") { o = Object.new; def o.to_int = 4; [:a].each.with_index(o).next } +probe("wi_big_offset") { e = [:a, :b].each.with_index(2**64); [e.next, e.next] } +probe("wi_fixnum_edge") { e = [:a, :b, :c].each.with_index(2**31 - 2); [e.next, e.next, e.next] } +probe("wi_drain") { drain([1, 2, 3].each.with_index(1)) } +probe("wi_result") { a = [1, 2]; r = stop_of(a.each.with_index).result; [r, r.equal?(a)] } +probe("wi_ewi_enum") { e = [1, 2].each.each_with_index; [drain(e), stop_of([1, 2].each.each_with_index).result] } +probe("wi_hash_ewi") { h = { a: 1, b: 2 }; [drain(h.each_with_index), stop_of(h.each_with_index).result.equal?(h)] } +probe("wi_range_ewi") { [drain((1..3).each_with_index), stop_of((1..3).each_with_index).result] } +probe("wi_struct_ewi") { S3 = Struct.new(:u, :v) unless defined?(S3); s = S3.new(1, 2); [drain(s.each_with_index), stop_of(s.each_with_index).result.equal?(s)] } +probe("wi_hash_wi") { drain({ a: 1 }.each.with_index(5)) } +probe("wi_range_wi") { [drain((1..3).each.with_index), stop_of((1..2).each.with_index).result] } +probe("wi_times_wi") { [drain(3.times.with_index(1)), stop_of(3.times.with_index).result] } +probe("wi_map_feed") { e = [1, 2].map.with_index(1); e.next; e.feed :q; e.next; [stop_of(e).result] } +probe("wi_map_nofeed") { stop_of([1, 2].map.with_index).result } +probe("wi_select_feed") { e = [1, 2, 3].select.with_index; e.next; e.feed true; e.next; e.next; e.feed 1; stop_of(e).result } +probe("wi_reject_ewi") { e = [1, 2].reject.each_with_index; e.next; e.feed true; e.next; stop_of(e).result } +probe("wi_map_ewi_values"){ e = { a: 1 }.map.each_with_index; [e.peek_values, e.next_values] } +probe("wi_nested") { e = [:a, :b].each.with_index.with_index(10); [e.next, e.next, stop_of(e).result] } +probe("wi_ewi_wi") { e = [:a].each_with_index.with_index; [e.next, e.peek_values] } +probe("wi_slice") { e = [1, 2, 3].each_slice(2).with_index; [e.next, e.next, stop_of(e).result] } +probe("wi_values") { e = [[1, 2]].each.with_index; [e.peek_values, e.next_values] } +probe("wi_peek_copy") { e = [1].each.with_index; v = e.peek; v << :x; [e.next, e.peek_values.size] rescue [$!.class] } +probe("wi_generator_src") { e = Enumerator.new { |y| y << 1; y.yield 2, 3; :g }.with_index; [e.next, e.next, stop_of(e).result] } +probe("wi_lazy") { e = [1, 2].lazy.with_index; [e.next, e.next] } +probe("wi_loop") { e = [1, 2].each.with_index(1); r = []; loop { r << e.next }; r } +probe("wi_loop_result") { e = [1, 2].map.with_index; loop { e.feed(e.next.sum) } } +probe("wi_rewind") { e = [1, 2].each.with_index; e.next; e.rewind; [e.next, e.next] } +probe("wi_append") { a = [1]; e = a.each.with_index; x = e.next; a << 2; [x, e.next, (e.next rescue :stop)] } +probe("wi_size") { [[1, 2].each.with_index.size, (1..3).each_with_index.size, { a: 1 }.each.with_object([]).size] } +probe("wi_inspect") { e = [1].each.with_index(2); e.next; [e.inspect, [1].each.each_with_index.inspect, [1].each.with_object(:m).inspect] } +probe("wi_dup") { e = [1, 2].each.with_index; d = e.dup; [d.next, e.next, (e.dup rescue $!.class)] } +probe("wi_reinit") { e = [1, 2].each.with_index; e.send(:initialize) { |y| y << :re; :r }; [e.next, stop_of(e).result] } +probe("wi_src_redef_ary") { k = Class.new(Array); e = k.new([1, 2]).each.with_index; k.class_eval { def each; yield :late; self; end }; [e.next, (e.next rescue :stop)] } +# Left out, as IronRuby differs from CRuby there with or without a cursor (LEDGER gap 35): MRI's with_index +# enumerator calls the source's method itself, so a singleton #each on the source enumerator is not called, +# and it calls #with_index by name, so redefining it after the enumerator is made changes what it does. +probe("wi_thread") { e = [1, 2].each.with_index; e.next; Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value } +probe("wi_thread_fresh") { e = [1, 2].each.with_index; Thread.new { e.next }.value } +probe("wo_drain") { drain([1, 2].each.with_object([])) } +probe("wo_result") { m = []; r = stop_of([1, 2].each.with_object(m)).result; [r, r.equal?(m)] } +probe("wo_ewo") { m = {}; e = [1, 2].each.each_with_object(m); [e.next, stop_of(e).result.equal?(m)] } +probe("wo_map") { e = [1, 2].map.with_object(:m); e.next; e.feed :f; [e.next, stop_of(e).result] } +probe("wo_hash") { drain({ a: 1 }.each.with_object(0)) } +probe("wo_memo_mutated") { m = []; e = [1, 2].each.with_object(m); e.next[1] << :x; [e.next, m] } +probe("wo_block_form") { [[1, 2].each.with_object([]) { |x, m| m << x }, [1, 2].each.with_index(1) { |x, i| x * i }, [1, 2].map.with_index(1) { |x, i| x * i }] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index cdd2a561a..811582195 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1419,16 +1419,27 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has is 67-94 ns against CRuby's 226-234 (`Util/bench/extiter-shapes.rb`). Its end was the cost left - a StopIteration thrown from C# took the catch-site walk, 22 us against CRuby's 0.8 - and perf/extiter (Landed) defers that walk; perf/extiter2 (Landed) gives `map`, `collect`, - `select`, `filter`, `find_all` and `reject` cursors of their own. Still on a fiber, 5-10 us of - process CPU per `next` against 0.22-0.36: `with_index` / `each_with_index` / `with_object` on - an enumerator, `each_with_object`, `filter_map` and `flat_map` (the prelude's), Hash#select and - #reject (Hash's own, whose result is a Hash), `Enumerator::Lazy`, `Enumerator.produce` - (generators of the prelude, which run Ruby code between two values: a cursor would call blocks - under its lock) and `Enumerator.new`. A raw fiber round trip is 2.3 us of wall clock and 4.7-6 - us of CPU (two threads spinning), so the prelude's machinery around it is not where the time - is. Untried: a cursor over a cursor for `with_index` (the prelude would have to mark the - generator it makes with its source and offset); switching fibers without a thread (a - continuation of the method JIT's own). + `select`, `filter`, `find_all` and `reject` cursors of their own, and perf/extiter3 (Landed) + `with_index`, `each_with_index` and `with_object` on an enumerator, and Enumerable# + each_with_index over a Hash, a Range or a Struct. Still on a fiber, 5-16 us of process CPU + per `next` against 0.25-0.37: `each_with_object` and `with_object` over a source with no + cursor, `filter_map` and `flat_map` (the prelude's), Hash#select and #reject (Hash's own, whose + result is a Hash), `Enumerator::Lazy`, `Enumerator.produce` (generators of the prelude, which + run Ruby code between two values: a cursor would call blocks under its lock) and + `Enumerator.new`. A raw fiber round trip is 2.3 us of wall clock and 4.7-6 us of CPU (two + threads spinning), so the prelude's machinery around it is not where the time is; an + abandoned fiber-backed enumerator costs about 0.55 ms (its thread). Untried: switching fibers + without a thread (a continuation of the method JIT's own). + Two differences from CRuby in `with_index` / `with_object` enumerators, with or without a + cursor, left as they were (the matrix leaves them out, with a comment): MRI's enumerator calls + the source's method itself, so a singleton #each on the source enumerator is not called (here + it is), and it calls #with_index by name, so redefining Enumerator#with_index after the + enumerator is made changes it (here the generator it made stays). + A trap found on the way: a local in the prelude's #with_index that held the enumerator it + returns kept every abandoned one alive - the generator block closes over the method's scope, + its fiber's thread is a root - and 2,000 of them ran the process out of memory + (`IR_FAST_NEXT=0`); the enumerator is returned without a local. + 36. **Left from round thirty-five**, each smaller than one gap of its own: `...` passed on is still a splat of an Array and a block argument (`def m(...) = n(...)` allocates the rest per call; the frame is light now); `URI::Generic#query=` and `merge` still run the @@ -1452,6 +1463,37 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/extiter3 (2026-11-26) - `with_index`, `each_with_index` and `with_object` enumerators + take `next` on a cursor over their source's (gap 35)** - not gated. Base 1efd7e6 (the merged + branch at 2f8c31c with perf/extiter2). The prelude's Enumerator#with_index (and so + #each_with_index) and #with_object made without a block are generators; they now mark the + enumerator they return with its source and offset or memo (`__iter_index_source__`), and + `TryCreateCursor` gives a marked one, while its generator is the one marked and its #each the + built-in one, an `IndexCursor` over the source's own cursor (any cursor: Array, Hash, Range, + times, each_slice, map / select, another with_index): [value, index] or [value, memo], what + the block answers handed on to the source's suspended yield (MRI's with_index_i and + with_object_i answer it). Enumerable#each_with_index has one too now over a Hash, a Range or a + Struct (it had only Array's). An offset that is not a Fixnum, a copy (#dup), and a generator + replaced by #initialize keep the fiber. Two prelude fixes go with it, in every mode: the + generator of #with_index answered `i += 1` to its source, so `[1, 2].map.with_index` fed `:q` + collected [2, 3] (CRuby [:q, nil]) and `select.with_index` kept everything; and #with_object's + StopIteration#result was the source's answer, not the memo. `IR_FAST_NEXT=0` leaves the new + cursors to the fiber. `ab.rb -r 6`, ns per `next`, CRuby / base / off / new: `[1000].each. + with_index` 267 / 10798 / 6302 / 325 (0.05 of off), a Hash's `each_with_index` 335 / 12397 / + 8468 / 304, `map.with_index` 283 / 6826 / 6448 / 368, `each.with_object` 250 / 5714 / 6183 / + 204; perf/extiter's and perf/extiter2's shapes level with base. In that run `lazy_next` read + 2.42 and `zip_enum` 1.28 of off; alone over six rounds every control overlapped, and over + eight `lazy_next` was 0.97 and `zip_enum` 0.99. `Util/extiter-matrix.rb` (222 probes: offsets + nil, negative, Float, #to_int, Bignum, at the Fixnum edge; every source; results; feed through + map / select / reject; nesting; each_slice; a generator source; peek and next_values; loop; + rewind; mutation; dup; #initialize again; a subclass's #each redefined; threads) prints CRuby's + output on new and off, and the base's on all but the 8 probes the prelude fixes correct; + enum-next-, block-loop-, hash-order-, raise-, full-message-, enum-, enumerable2- and jit-matrix + are the same on base, new and off. spec/core/enumerator, kernel/loop_spec, spec/core/hash and + spec/core/enumerable: 1,541 examples, the same one error in all three (Hash.try_convert's + known `into`/`to` wording); 117 named IronRuby.Tests (Enumerator*, Enumerable*, Array*, Hash*, + Loop*, Fiber*, Backtrace*, Exception*, Raise*, Rescue*) pass. + - **perf/extiter2 (2026-11-26) - `map`, `collect`, `select`, `filter`, `find_all` and `reject` enumerators take `next` on a cursor, with no fiber (gap 35)** - not gated. Base: the merged branch at 2f8c31c, which has perf/extiter. An enumerator of Array's own #map / #collect / From 0c41d0f6742c8fa5f0bdd61c740fcd2ad73c9ff0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:39:25 +0000 Subject: [PATCH 058/439] StringScanner on a UTF-8 subject: map bytes to characters incrementally, without switching the subject to bytes The scan pointer is a byte offset and the regex engine matches CLR characters. For a subject that is valid UTF-8 and not all ASCII, every conversion between the two copied out and counted the whole prefix (CharIndexOf before the match, MatchData.ToByteIndex after it), and eos?, matched, getch and the rest read the subject as bytes (GetByteCount, GetBinarySlice, GetByte), which switched it from characters to bytes, so the next match decoded all of it again: scanning text word by word was quadratic. 10 KB of UTF-8 took 55 ms (CRuby 0.20 ms) and 100 KB took 8.4 s (CRuby 2.1 ms); scan_until(/,/) over 100 KB 2.0 s (CRuby 0.71 ms). That is what CSV, JSON's pure parser and ERB pay on non-ASCII input. The scanner now keeps a map for such a subject, made for one snapshot of its characters (ConvertToString answers the same string until the subject changes) with its UTF-8 length counted once. Offsets are converted by walking the characters from a cursor, the last offset converted, so a step costs about the length of the token. The regex match's offsets are taken as CLR offsets (MatchData.TryGetGroupClrOffsets) and mapped; ByteLength, ByteSlice, getch's character width, charpos, bol?, an ASCII literal pattern and integer groups read the characters. An offset inside a character, a subject that is ASCII, not UTF-8 or not valid, and IR_FAST_SEARCH=0 take the old paths. A group read after the subject changed uses the old path too (the match remembers its map). Word by word over 10 KB / 100 KB of UTF-8: 55 ms / 8.4 s -> 1.5 / 13.6 ms; scan_until 13.8 ms / 2.0 s -> 0.40 / 3.5 ms (one process each, best of five). Util/string-search-matrix.rb has a StringScanner section (2,532 rows: 19 operations from every byte offset of ASCII, UTF-8, astral, broken UTF-8, BINARY and EUC-JP subjects, word loops, concat midway, string=, fixed_anchor, terminate/reset); this build prints what the base prints in both modes. The base differs from CRuby in 110 of those rows, all pre-existing and left alone: a scan from a byte offset inside a character, a non-ASCII literal on a BINARY subject, EUC-JP. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/StringScanner/StringScanner.cs | 238 ++++++++++++++++++- Src/Ruby/Builtins/MatchData.cs | 19 ++ Util/bench/strsearch-shapes.rb | 12 + Util/string-search-matrix.rb | 55 +++++ 4 files changed, 322 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index 8eca6153e..b76a6126f 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -19,6 +19,7 @@ using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; +using System.Threading; using IronRuby.Builtins; using IronRuby.Runtime; using Microsoft.Scripting.Runtime; @@ -155,14 +156,157 @@ public static object MustCVersion(object self) { #region byte / character bookkeeping + /// + /// The scan pointer is a byte offset and the regex engine matches CLR characters. For a + /// subject that is valid UTF-8 and not all ASCII, converting between the two used to copy + /// out and count everything before the offset, in both directions, and to read the subject + /// as bytes (GetByteCount, GetBinarySlice, GetByte), which switched it from characters to + /// bytes - and the next match switched it back, decoding the whole of it: a scan of 100 KB + /// of UTF-8 text word by word took 8.4 s (CRuby: 2 ms). The map converts offsets by walking + /// the subject's characters from a cursor, the last offset converted; a scanner moves + /// forward, so a step costs about the length of the token. It is made for one snapshot of + /// the subject's characters (ConvertToString answers the same string until the subject + /// changes, and a new one after) and dropped when that changes. + /// + private sealed class Utf8Map { + internal readonly string/*!*/ Text; + internal readonly int ByteLength; + internal readonly bool HasPairs; + + // the byte offset in the high half, the CLR index in the low half: one field, so that a + // scanner shared between threads can only see a cursor that was right at some point + private long _cursor; + + internal Utf8Map(string/*!*/ text) { + Text = text; + ByteLength = Encoding.UTF8.GetByteCount(text); + HasPairs = text.Length != CountRunes(text); + } + + private static int CountRunes(string/*!*/ text) { + int count = 0; + for (int i = 0; i < text.Length; i++) { + if (!Char.IsLowSurrogate(text[i])) { + count++; + } + } + return count; + } + + /// The CLR index of byte offset , or -1 when it is inside a character. + internal int ClrOf(int byteOffset) { + if (byteOffset < 0 || byteOffset > ByteLength) { + return -1; + } + int b, c; + return Seek(true, byteOffset, out b, out c) ? c : -1; + } + + /// The byte offset of CLR index , or -1 when it is between the halves of a pair. + internal int ByteOf(int clrIndex) { + if (clrIndex < 0 || clrIndex > Text.Length) { + return -1; + } + int b, c; + return Seek(false, clrIndex, out b, out c) ? b : -1; + } + + private bool Seek(bool byBytes, int target, out int b, out int c) { + long cursor = Volatile.Read(ref _cursor); + b = (int)(cursor >> 32); + c = (int)cursor; + int at = byBytes ? b : c; + if (target < at && target < at / 2) { + b = c = 0; + at = 0; + } + string text = Text; + if (target >= at) { + while ((byBytes ? b : c) < target) { + char ch = text[c]; + if (ch < 0x80) { + b += 1; c += 1; + } else if (ch < 0x800) { + b += 2; c += 1; + } else if (Char.IsHighSurrogate(ch)) { + b += 4; c += 2; + } else { + b += 3; c += 1; + } + } + } else { + while ((byBytes ? b : c) > target) { + char ch = text[c - 1]; + if (ch < 0x80) { + b -= 1; c -= 1; + } else if (ch < 0x800) { + b -= 2; c -= 1; + } else if (Char.IsLowSurrogate(ch)) { + b -= 4; c -= 2; + } else { + b -= 3; c -= 1; + } + } + } + Volatile.Write(ref _cursor, ((long)b << 32) | (uint)c); + return (byBytes ? b : c) == target; + } + } + + private Utf8Map _map; + private string _unmappedText; + + // the map _match's CLR offsets are offsets into; null when the match was not made through one + private Utf8Map _matchMap; + + /// + /// The map for the subject as it is now, or null when the subject is not one it is for: + /// not UTF-8, all ASCII (bytes and CLR characters are one for one, which the paths below + /// already know), or not valid. IR_FAST_SEARCH=0 makes none. + /// + private Utf8Map Map { + get { + if (!MutableStringOps.FastSearchEnabled) { + return null; + } + MutableString subject = _scanString; + if (subject.Encoding != RubyEncoding.UTF8 || subject.IsAscii()) { + return null; + } + // a string held as bytes is decoded once, as a match would + subject.PrepareForCharacterRead(); + string text = subject.ConvertToString(); + Utf8Map map = _map; + if (map != null && ReferenceEquals(map.Text, text)) { + return map; + } + if (ReferenceEquals(text, _unmappedText) || subject.ContainsInvalidCharacters()) { + _unmappedText = text; + return null; + } + return _map = new Utf8Map(text); + } + } + private int ByteLength { - get { return _scanString.GetByteCount(); } + get { + Utf8Map map = Map; + return (map != null) ? map.ByteLength : _scanString.GetByteCount(); + } } private MutableString/*!*/ ByteSlice(int start, int count) { if (count <= 0) { return MutableString.CreateEmpty(_scanString.Encoding); } + Utf8Map map = Map; + if (map != null) { + int clrStart = map.ClrOf(start); + int clrEnd = (clrStart >= 0) ? map.ClrOf(start + count) : -1; + if (clrEnd >= 0) { + return MutableString.Create(map.Text.Substring(clrStart, clrEnd - clrStart), _scanString.Encoding); + } + } return MutableString.CreateBinary(_scanString.GetBinarySlice(start, count), _scanString.Encoding); } @@ -185,6 +329,14 @@ private int CharWidthAtPosition() { if (available <= 0) { return 0; } + Utf8Map map = Map; + if (map != null) { + int clr = map.ClrOf(_position); + if (clr >= 0) { + char ch = map.Text[clr]; + return (ch < 0x80) ? 1 : (ch < 0x800) ? 2 : Char.IsHighSurrogate(ch) ? 4 : 3; + } + } // No encoding Ruby knows needs more than this for one character. byte[] bytes = _scanString.GetBinarySlice(_position, Math.Min(available, 8)); @@ -218,6 +370,22 @@ private int CharacterCountOf(int byteIndex) { if (_scanString.DetectSingleByteCharacters()) { return byteIndex; } + Utf8Map map = Map; + if (map != null) { + int clr = map.ClrOf(byteIndex); + if (clr >= 0) { + if (!map.HasPairs) { + return clr; + } + int count = 0; + for (int i = 0; i < clr; i++) { + if (!Char.IsLowSurrogate(map.Text[i])) { + count++; + } + } + return count; + } + } return MutableString.CreateBinary(_scanString.GetBinarySlice(0, byteIndex), _scanString.Encoding).GetCharacterCount(); } @@ -235,6 +403,13 @@ private int CharIndexOf(int byteIndex) { // every scan cost a pass over everything already scanned. return byteIndex; } + Utf8Map map = Map; + if (map != null) { + int clr = map.ClrOf(byteIndex); + if (clr >= 0) { + return clr; + } + } return MutableString.CreateBinary(_scanString.GetBinarySlice(0, byteIndex), _scanString.Encoding).GetCharCount(); } @@ -251,6 +426,7 @@ private void ClearMatch() { _matchBase = 0; _matchStart = 0; _matchEnd = 0; + _matchMap = null; } #endregion @@ -309,6 +485,37 @@ private MatchData CurrentMatch { private bool MatchRegex(RubyRegex/*!*/ pattern, bool anchored, bool advance, bool lazyGroups) { ClearMatch(); + Utf8Map map = Map; + int clrPosition = (map != null) ? map.ClrOf(_position) : -1; + if (clrPosition >= 0) { + // The MatchData is made here rather than left pending: the window match makes it anyway + // for a subject that is not one byte per character (see MatchWindowBounds). + MatchData data = _fixedAnchor + ? pattern.Match(_scanString, clrPosition, false) + : pattern.MatchWindow(_scanString, clrPosition, anchored, false); + int clrStart, clrEnd; + if (data == null || !data.TryGetGroupClrOffsets(0, out clrStart, out clrEnd)) { + return false; + } + int byteStart = map.ByteOf(clrStart); + int byteEnd = (byteStart >= 0) ? map.ByteOf(clrEnd) : -1; + if (byteEnd >= 0) { + if (anchored && byteStart != _position) { + return false; + } + _match = data; + _matchMap = map; + _matchBase = 0; + return Matched(byteStart, byteEnd, advance); + } + if (!data.TryGetGroupByteOffsets(0, out byteStart, out byteEnd) || (anchored && byteStart != _position)) { + return false; + } + _match = data; + _matchBase = 0; + return Matched(byteStart, byteEnd, advance); + } + if (lazyGroups && !_fixedAnchor) { int boundsStart, boundsEnd; RubyRegex.PendingMatch pending; @@ -362,6 +569,15 @@ private bool MatchLiteral(MutableString/*!*/ pattern, bool anchored, bool advanc if (anchored && pattern.IsAscii()) { // The usual #skip("{"): an ASCII pattern's characters are its bytes, so it can be // compared where it stands instead of being copied out to a byte array first. + Utf8Map map = Map; + int clr = (map != null) ? map.ClrOf(_position) : -1; + if (clr >= 0) { + string literal = pattern.ToString(); + if (!map.Text.AsSpan(clr).StartsWith(literal.AsSpan())) { + return false; + } + return Matched(_position, _position + literal.Length, advance); + } int length = pattern.GetByteCount(); if (_position + length > ByteLength) { return false; @@ -463,6 +679,16 @@ public static MutableString GetMatchSubgroup(ConversionStorage/*!*/ fixnumC return null; } int start, end; + Utf8Map map = self.Map; + if (map != null && map == self._matchMap) { + if (!self.CurrentMatch.TryGetGroupClrOffsets(subgroup, out start, out end)) { + return null; + } + int byteStart = map.ByteOf(start), byteEnd = map.ByteOf(end); + if (byteStart >= 0 && byteEnd >= 0) { + return self.ByteSlice(byteStart, byteEnd - byteStart); + } + } return self.CurrentMatch.TryGetGroupByteOffsets(subgroup, out start, out end) ? self.ByteSlice(self._matchBase + start, end - start) : null; @@ -535,7 +761,15 @@ public static bool IsFixedAnchor(StringScanner/*!*/ self) { [RubyMethod("beginning_of_line?")] [RubyMethod("bol?")] public static bool BeginningOfLine(StringScanner/*!*/ self) { - return (self._position == 0) || (self._scanString.GetByte(self._position - 1) == (byte)'\n'); + if (self._position == 0) { + return true; + } + Utf8Map map = self.Map; + int clr = (map != null) ? map.ClrOf(self._position) : -1; + if (clr > 0) { + return map.Text[clr - 1] == '\n'; + } + return self._scanString.GetByte(self._position - 1) == (byte)'\n'; } [RubyMethod("check")] diff --git a/Src/Ruby/Builtins/MatchData.cs b/Src/Ruby/Builtins/MatchData.cs index 7b773b8e1..a824e083a 100644 --- a/Src/Ruby/Builtins/MatchData.cs +++ b/Src/Ruby/Builtins/MatchData.cs @@ -259,6 +259,25 @@ public bool TryGetGroupByteOffsets(int groupIndex, out int start, out int end) { return true; } + /// + /// The offsets of a group in the CLR characters the regex matched (the subject's + /// ConvertToString), untranslated: for a caller that keeps its own map from those to bytes + /// (StringScanner), where ToByteIndex copies and counts the whole prefix on every call. + /// + public bool TryGetGroupClrOffsets(int groupIndex, out int start, out int end) { + if (groupIndex != 0) { + RequireExistingGroup(groupIndex); + } + Group group = (groupIndex == 0) ? _match : _match.Groups[groupIndex]; + if (!group.Success) { + start = end = 0; + return false; + } + start = group.Index; + end = group.Index + group.Length; + return true; + } + public int[] GetGroupOffsets(string/*!*/ name, bool inBytes) { if (!HasNamedGroup(name)) { throw RubyExceptions.CreateIndexError("undefined group name reference: {0}", name); diff --git a/Util/bench/strsearch-shapes.rb b/Util/bench/strsearch-shapes.rb index 2940fca1e..ad58d636f 100644 --- a/Util/bench/strsearch-shapes.rb +++ b/Util/bench/strsearch-shapes.rb @@ -33,6 +33,9 @@ def lateat(fill) = fill.size - 30 RE3 = /q"z/ RE_INT = /\A[+-]?\d+/ SHORT = "12345 rest" +require 'strscan' +SS_U = ("héllo wörld, " * 800)[0, 10000] +SS_A = ("hello world, " * 800)[0, 10000] class H def initialize @@ -168,6 +171,10 @@ def int_tilde = (RE_INT =~ @short || -1) def short_idx = (@short.index(" ") || -1) def size = @other.size def eq = (@other == @short ? 1 : 0) + # StringScanner over 10 KB, one call a whole pass (round three: the UTF-8 subject was quadratic) + def ss_words_u = (ss = StringScanner.new(SS_U); n = 0; until ss.eos?; ss.skip(/\s+/); n += 1 if ss.scan(/\S+/); end; n + ss.charpos) + def ss_until_u = (ss = StringScanner.new(SS_U); n = 0; while ss.scan_until(/,/); n += ss.matched_size; end; n) + def ss_words_a = (ss = StringScanner.new(SS_A); n = 0; until ss.eos?; ss.skip(/\s+/); n += 1 if ss.scan(/\S+/); end; n + ss.charpos) end def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end @@ -193,6 +200,8 @@ def t(name, n) # CRuby takes 9 to 60 us for a character class over the whole of a 10 KB String, IronRuby under one: # the count is the long one so that IronRuby's sections are long enough to time. REGEX = LONG +# a StringScanner pass over 10 KB takes 0.2 to 2 ms +SCAN = [LONG / 2000, 1].max t("idx1_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx1_a_e; i += 1; end; s } t("idx3_a_e", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.idx3_a_e; i += 1; end; s } @@ -314,3 +323,6 @@ def t(name, n) t("short_idx", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.short_idx; i += 1; end; s } t("size", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.size; i += 1; end; s } t("eq", SHORTN) { |n| i = 0; s = 0; while i < n; s += h.eq; i += 1; end; s } +t("ss_words_u", SCAN) { |n| i = 0; s = 0; while i < n; s += h.ss_words_u; i += 1; end; s } +t("ss_until_u", SCAN) { |n| i = 0; s = 0; while i < n; s += h.ss_until_u; i += 1; end; s } +t("ss_words_a", SCAN) { |n| i = 0; s = 0; while i < n; s += h.ss_words_a; i += 1; end; s } diff --git a/Util/string-search-matrix.rb b/Util/string-search-matrix.rb index 28d3a1b2d..621033819 100644 --- a/Util/string-search-matrix.rb +++ b/Util/string-search-matrix.rb @@ -148,3 +148,58 @@ def kinds(base) try("#{rname}/#{kname}.start_with?(nil)") { "sentinel" =~ SENTINEL; b = $~; [(s.start_with?(nil)), b, $~] } end end + +puts "== StringScanner (round three: a UTF-8 subject is mapped between bytes and characters incrementally)" +require 'strscan' +def ss_state(ss) + [ss.pos, (ss.charpos rescue $!.class), ss.matched, ss.pre_match, ss.post_match, ss[0], (ss[1] rescue $!.class), + ss.matched_size, ss.eos?, ss.bol?, ss.rest_size, ss.rest, ss.peek(3)].inspect +end +SS_SUBJECTS = { + ascii: "hello world, 12 + 34\nnext line", + utf8: "héllo wörld, 日本 + 34\nnäxt line", + astral: "a😀b 𝒳c, 😀\n𠀀 end", + broken: "ab\xE9c d\xFFe, f".dup.force_encoding("UTF-8"), + binary: "ab\xE9c d\xFFe, f".b, + eucjp: "\xA4\xA2a b\xA4\xA4, c".dup.force_encoding("EUC-JP"), +} +SS_OPS = [ + ["scan(/\\S+/)", ->(ss) { ss.scan(/\S+/) }], ["skip(/\\s+/)", ->(ss) { ss.skip(/\s+/) }], + ["scan(/(\\w)(\\w)/)", ->(ss) { ss.scan(/(\w)(\w)/) }], ["scan_until(/,/)", ->(ss) { ss.scan_until(/,/) }], + ["skip_until(/\\n/)", ->(ss) { ss.skip_until(/\n/) }], ["check(/./)", ->(ss) { ss.check(/./) }], + ["match?(/\\w+/)", ->(ss) { ss.match?(/\w+/) }], ["exist?(/ /)", ->(ss) { ss.exist?(/ /) }], + ["getch", ->(ss) { ss.getch }], ["get_byte", ->(ss) { ss.get_byte }], ["peek_byte", ->(ss) { ss.peek_byte }], + ["skip(' ')", ->(ss) { ss.skip(" ") }], ["scan('h')", ->(ss) { ss.scan("h") }], ["scan('é')", ->(ss) { ss.scan("é") }], + ["scan(/\\A./)", ->(ss) { ss.scan(/\A./) }], ["scan(/^n/)", ->(ss) { ss.scan(/^n/) }], ["unscan", ->(ss) { ss.unscan }], + ["search_full(/d/,1,1)", ->(ss) { ss.search_full(/d/, true, true) }], ["scan_full(/./,0,1)", ->(ss) { ss.scan_full(/./, false, true) }], +] +SS_SUBJECTS.each do |sname, subject| + SS_OPS.each do |oname, op| + # every op from every starting byte position, after a first op, then a second + (0..subject.bytesize).each do |start| + try("ss[#{sname}] pos=#{start} #{oname}") do + ss = StringScanner.new(subject.dup) + ss.pos = start + r = op.(ss) + [[r, ss_state(ss)].inspect, nil, nil] + end + end + end + try("ss[#{sname}] words") do + ss = StringScanner.new(subject.dup); out = [] + until ss.eos?; ss.skip(/\s+/); out << [ss.scan(/\S+/), ss.pos, ss.charpos, ss.pre_match&.size]; break if out.size > 50; end + [out.inspect, nil, nil] + end + try("ss[#{sname}] concat midway") do + s = subject.dup; ss = StringScanner.new(s); a = ss.scan(/\S+/); s << " ñu"; ss << " 😀"; b = ss.scan_until(/ñ/) + c = ss.rest; ss.string = "nüevo"; d = ss.scan(/\S/) + [[a, b, c, d, ss_state(ss)].inspect, nil, nil] + end + try("ss[#{sname}] fixed_anchor") do + ss = StringScanner.new(subject.dup, fixed_anchor: true); r = [ss.scan(/\S+/), ss.skip(/\s/), ss.scan(/\A./), ss.scan(/./), ss_state(ss)] + [r.inspect, nil, nil] + end + try("ss[#{sname}] terminate/reset") do + ss = StringScanner.new(subject.dup); ss.scan(/\S+/); ss.terminate; t = ss_state(ss); ss.reset; [[t, ss_state(ss)].inspect, nil, nil] + end +end From b87a916d0132588cab83ffa3dceadfddd7f4a2f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:39:34 +0000 Subject: [PATCH 059/439] Method JIT: record why a per-count body declined TrySpecializePerCount (a method with optional parameters, one body per count of arguments passed) skipped a count whose compile failed without saying why, so IR_JIT_VERBOSE's `declined' line said "no reason recorded" (seen for CSV::FieldsConverter#initialize). It now records the reason as TrySpecialize does: the compiler's, or the self-call's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitStub.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 0cd57e185..2882bd254 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -1101,9 +1101,17 @@ private bool TrySpecializePerCount(RefinementActivation/*!*/ refinements) { if ((_countsSeen & (1 << k)) == 0) { continue; } var code = Named(JitCompiler.TryCompile(_ast, _context, ProfiledTypes(_perCountMandatory + k), null, refinements, k, _declaringScope, Hints(), bind, epoch), epoch, version, constantVersion); - if (code == null) { continue; } + if (code == null) { + // IR_JIT_VERBOSE=1: why, as TrySpecialize records it (the last count's, if none compiles) + _declineReason = JitCompiler.LastDecline ?? "the compiler bailed out (see the `rejected' line)"; + continue; + } if (code.EmittedSelfCall) { - if (_receiverClass == null || _polymorphicReceiver || !SelfCallResolvesHere(_receiverClass, refinements)) { continue; } + if (_receiverClass == null || _polymorphicReceiver || !SelfCallResolvesHere(_receiverClass, refinements)) { + _declineReason = (_receiverClass == null || _polymorphicReceiver) ? "a class guard on a receiver of several classes" + : "the self-call resolves elsewhere"; + continue; + } pinned = true; } if (code.DirectCalls) { pinned = true; } From 7c5b6b427d0a664778d5ad5e7cd4476ca76b45b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:39:34 +0000 Subject: [PATCH 060/439] Method JIT: take a multiple assignment of a list `a, b = b, a` and `@a, @b = x, y` refused the method at the screen. After the census fix, multiple assignment was the next "one thing only" line that is not a call (75), with no earlier JIT attempt. EmitParallelAssignment follows CompoundLeftValue.TransformWrite: the right-hand values into temporaries left to right, then each target written left to right through EmitAssignment, the value an EmittedValue, so locals keep their types and instance variable writes their effect and frozen-self deopt. Locals of the method and instance variables only, two or more values, no splat, no nested target; the expression's Array only where it is used. The single-value form (a, b = f(x)) needs to_ary and is left. census.rb -d against 7b22f25: 14 up (6 to compiles, 8 to maybe), none down. app-shapes trace: 116 -> 117 specialized, declines unchanged (30). Instructions a call: swap 0.57, three values 0.44, two ivars 0.79. Util/jit-masgn-matrix.rb (new) and the JIT matrices print CRuby's output with the JIT on, off and without JIT calls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 123 +++++++++++++++++++++++ Util/bench/jit-masgn-shapes.rb | 56 +++++++++++ Util/jit-masgn-matrix.rb | 150 ++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 50 ++++++++++ 4 files changed, 379 insertions(+) create mode 100644 Util/bench/jit-masgn-shapes.rb create mode 100644 Util/jit-masgn-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index c5ef284ed..3c1875d49 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1185,6 +1185,13 @@ private bool IsInitialIVarValue(RExpr/*!*/ value) { var hashLiteral = node as HashConstructor; if (hashLiteral != null) { return EmitHashLiteral(hashLiteral, out type); } + var parallel = node as ParallelAssignmentExpression; + if (parallel != null) { return EmitParallelAssignment(parallel, out type); } + + // a value EmitParallelAssignment has already evaluated, standing for its right-hand side + var emitted = node as EmittedValue; + if (emitted != null) { type = emitted.Type; return emitted.Value; } + var body = node as Body; if (body != null) { if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { @@ -1356,6 +1363,86 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return Ast.Call(JitRuntime.M("NewHash"), Ast.Constant(_context), Ast.NewArrayInit(typeof(object), values)); } + /// + /// `a, b = x, y', `@a, @b = b, a': the generic body's order (CompoundLeftValue.TransformWrite) - every right-hand + /// value first, left to right, into a temporary, then each target written left to right, a missing value nil and + /// a value with no target dropped. Each write is the one `target = value' makes (EmitAssignment), the value an + /// EmittedValue, so a local keeps its type and an instance variable write its effect and its deopt on a frozen + /// self, exactly as the same writes spelled as statements. Only locals of the method and instance variables as + /// targets, no `*rest' and no nested target, and two or more values, none splatted (IsListAssignment): a single + /// value is destructured by to_ary, which would be Ruby code run from the typed body, or a deopt after the effect + /// that computed it. The value of the expression, an Array of the right-hand values, is made only where it is used. + /// + private MSA.Expression/*!*/ EmitParallelAssignment(ParallelAssignmentExpression/*!*/ node, out JT type) { + if (!IsListAssignment(node, _scopeDepth)) { throw Bail("parallel assignment"); } + var lefts = node.Left.LeftValues; + var rights = node.Right; + var parts = new List(); + var temps = new List(); + var values = new EmittedValue[rights.Length]; + for (int i = 0; i < rights.Length; i++) { + JT t; + var v = Emit(rights[i], out t); + if (t == JT.None || t == JT.Never) { throw Bail("parallel assignment of a value that jumps away"); } + var temp = Ast.Variable(ClrType(t), "#masgn" + i); + temps.Add(temp); + parts.Add(Ast.Assign(temp, v)); + values[i] = new EmittedValue(temp, t); + } + for (int i = 0; i < lefts.Length; i++) { + RExpr value = (i < values.Length) ? values[i] : new EmittedValue(Ast.Constant(null, typeof(object)), JT.Obj); + JT ignored; + parts.Add(Emit(new SimpleAssignmentExpression(lefts[i], value, null, node.Location), out ignored)); + } + if (IsDiscardedStatement(node)) { + parts.Add(Ast.Constant(null, typeof(object))); + } else { + var boxed = new List(values.Length); + foreach (var v in values) { boxed.Add(Coerce(v.Value, v.Type, JT.Obj)); } + parts.Add(IronRuby.Compiler.Methods.MakeArrayOpCall(boxed)); + } + type = JT.Obj; + return Ast.Block(typeof(object), temps, parts); + } + + /// The parallel assignments EmitParallelAssignment takes (JitScreen walks the same). + internal static bool IsListAssignment(ParallelAssignmentExpression/*!*/ node, int scopeDepth) { + var left = node.Left; + if (left.HasUnsplattedValue || node.Right.Length < 2) { return false; } + foreach (var target in left.LeftValues) { + if (target is InstanceVariable) { continue; } + var local = target as LocalVariable; + if (local == null || local.DefinitionLexicalDepth != scopeDepth) { return false; } + } + foreach (var value in node.Right) { + if (value is SplattedArgument) { return false; } + } + return true; + } + + private HashSet _discardedStatements; + + /// + /// A statement before the last of its list: EmitStatements drops its value. Anything else (a last statement, an + /// operand) may be used, which only costs the value being made. + /// + private bool IsDiscardedStatement(RExpr/*!*/ node) { + if (_discardedStatements == null) { + var finder = new DiscardedStatementFinder(); + if (_ast != null && _ast.Body != null) { finder.Walk(_ast.Body); } + _discardedStatements = finder.Found; + } + return _discardedStatements.Contains(node); + } + + private sealed class DiscardedStatementFinder : Walker { + internal readonly HashSet/*!*/ Found = new HashSet(); + + protected internal override void VisitStatements(Statements/*!*/ statements) { + foreach (var s in statements.AllButLast) { Found.Add(s); } + } + } + /// /// HashConstructor.HasPlainLiteralKeys: a Symbol or String literal, or nil, true, false or a Fixnum literal - or, /// alone, any other numeric literal (two Float or Bignum literals of one value are told apart by #eql?). @@ -3149,6 +3236,28 @@ protected override MSA.Expression VisitLambda(MSA.Expression node) { /// the "screen rejected" histogram printed on the way out, so a newly supported node kind /// sitting at the top of that histogram is the drift, visible without reading any code. /// + /// + /// A value the typed body has already computed, as the right side of an assignment JitCompiler emits itself + /// (EmitParallelAssignment). Never in a parsed tree, never transformed by the generic compiler. + /// + internal sealed class EmittedValue : RExpr { + internal readonly MSA.Expression/*!*/ Value; + internal readonly JT Type; + + internal EmittedValue(MSA.Expression/*!*/ value, JT type) + : base(Microsoft.Scripting.SourceSpan.None) { + Value = value; + Type = type; + } + + internal override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { + throw new InvalidOperationException("EmittedValue is the method JIT's own"); + } + + protected internal override void Walk(Walker/*!*/ walker) { + } + } + internal sealed class JitScreen { private readonly int _scopeDepth; private readonly string/*!*/ _methodName; @@ -3654,6 +3763,20 @@ private bool Walk(RExpr/*!*/ node) { return Walk(retArgs.Expressions[0]); } + // `a, b = x, y' into locals and instance variables (JitCompiler.EmitParallelAssignment) + var parallel = node as ParallelAssignmentExpression; + if (parallel != null) { + if (!JitCompiler.IsListAssignment(parallel, _scopeDepth) || _inKeywordDefault) { return No(node); } + foreach (var value in parallel.Right) { + if (!Walk(value)) { return false; } + } + foreach (var target in parallel.Left.LeftValues) { + var targetLocal = target as LocalVariable; + if (targetLocal != null) { _otherUses.Add(targetLocal.Name); } + } + return true; + } + // `{k => v}' with plain literal keys (JitCompiler.EmitHashLiteral): any other object, never an operand var hashLiteral = node as HashConstructor; if (hashLiteral != null) { diff --git a/Util/bench/jit-masgn-shapes.rb b/Util/bench/jit-masgn-shapes.rb new file mode 100644 index 000000000..5cf4b0c4c --- /dev/null +++ b/Util/bench/jit-masgn-shapes.rb @@ -0,0 +1,56 @@ +# What a multiple assignment costs in a method the method JIT can take (JitCompiler.EmitParallelAssignment): ns per +# call of the method, the caller a `while' loop. swap `x, y = y, x', three `a, b, c = x, x + 1, x * 2', ivars +# `@a, @b = x, y', value the expression's Array used; seq `a = x; b = x + 1' is the control (taken already). +# +# ruby Util/perf/ab.rb -r 6 Util/bench/jit-masgn-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# ruby Util/perf/ab.rb -i -r 1 -n 20000 Util/bench/jit-masgn-shapes.rb \ +# "base=env IR_CONFIG=Release Util/perf/callgrind/count.sh ../ironruby" "new=env IR_CONFIG=Release Util/perf/callgrind/count.sh ." +# +# Every line prints the sum of its results next to its time; it must be CRuby's. +$stdout.sync = true + +class MaShapes + def initialize; @a = 0; @b = 0; end + def swap(x, y) + x, y = y, x + x - y + end + def three(x) + a, b, c = x, x + 1, x * 2 + a + b + c + end + def ivars(x, y) + @a, @b = x, y + x + end + def value(x) = (a, b = x, x + 1).size + def seq(x) + a = x + b = x + 1 + a + b + end +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +s = MaShapes.new +N = (ENV["N"] || 1_000_000).to_i +t("swap", N) { |n| i = 0; r = 0; while i < n; r += s.swap(i, 3); i += 1; end; r } +t("three", N) { |n| i = 0; r = 0; while i < n; r += s.three(i); i += 1; end; r } +t("ivars", N) { |n| i = 0; r = 0; while i < n; r += s.ivars(i, 2); i += 1; end; r } +t("value", N) { |n| i = 0; r = 0; while i < n; r += s.value(i); i += 1; end; r } +t("seq", N) { |n| i = 0; r = 0; while i < n; r += s.seq(i); i += 1; end; r } diff --git a/Util/jit-masgn-matrix.rb b/Util/jit-masgn-matrix.rb new file mode 100644 index 000000000..8a9637787 --- /dev/null +++ b/Util/jit-masgn-matrix.rb @@ -0,0 +1,150 @@ +# Differential matrix for multiple assignment in methods the method JIT compiles (-X:JIT, +# JitCompiler.EmitParallelAssignment). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-masgn-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-masgn-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-masgn-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Every method is called past the JIT's thresholds, then probed. Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-masgn-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep ma_ +# The traps: every right-hand value is evaluated before any target is written (a swap), left to +# right; a missing value is nil and an extra one is evaluated and dropped; a local keeps its +# type (Int to Bignum after the swap, a Float, an object); an instance variable write deopts on +# a frozen self, after which the generic body must not repeat what came before; the value of +# the expression is an Array of the right-hand values where it is used. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts e.class + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class MA + def initialize; @a = 0; @b = 0; @n = 0; @log = []; end + attr_reader :a, :b, :n, :log + + def ma_swap(x, y) + x, y = y, x + x - y + end + def ma_three(x) + a, b, c = x, x + 1, x * 2 + a + b + c + end + def ma_rotate(x, y, z) + x, y, z = y, z, x + x * 100 + y * 10 + z + end + def ma_ivars(x, y) + @a, @b = x, y + @a + @b + end + def ma_ivar_swap + @a, @b = @b, @a + @a + end + def ma_mixed(x) + v, @a = x + 1, x - 1 + v + @a + end + def ma_missing(x) + a, b, c = x, x + c.nil? ? a + b : -1 + end + def ma_extra(x) + a, b = x, x + 1, x + 2 + a + b + end + def ma_value(x, y) + a, b = x, y + end + def ma_value_used(x, y) + r = (a, b = x, y) + r.size + a + b + end + def ma_float(x) + a, b = x * 1.5, x + a + b + end + def ma_objects(x) + a, b = "s#{x}", [x] + a.size + b.size + end + def ma_overflow(x) + a, b = x * x, x + a + b + end + def ma_effect(x) + @n += 1 + a, b = x + 1, x * 3 + a + b + end + def ma_frozen(x) + @a, @b = x, x + 1 + x + end + def note(v); @log << v; v; end + def ma_order(x) + a, b = note(x), note(x + 1) + a + b + end + def ma_in_loop(n) + a = 0 + b = 1 + i = 0 + while i < n + a, b = b, a + b + i += 1 + end + a + end +end + +o = MA.new +t("swap") { warm { |i| o.ma_swap(i, 1) } } +t("swap, Floats") { o.ma_swap(1.5, 0.25) } +t("swap, Strings") { begin; o.ma_swap("a", "b"); rescue NoMethodError => e; e.class; end } +t("three") { warm { |i| o.ma_three(i) } } +t("three, a Bignum") { o.ma_three(2**62) } +t("rotate") { warm { |i| o.ma_rotate(1, 2, i % 10) } } +t("ivars") { warm { |i| o.ma_ivars(i, 2) }; [o.ma_ivars(5, 6), o.a, o.b] } +t("ivar swap") { o = MA.new; o.ma_ivars(1, 2); warm(301) { o.ma_ivar_swap }; [o.a, o.b] } +t("mixed") { warm { |i| o.ma_mixed(i) }; [o.ma_mixed(10), o.a] } +t("missing") { warm { |i| o.ma_missing(i) } } +t("extra") { warm { |i| o.ma_extra(i) } } +t("value") { warm { |i| o.ma_value(i, 2) } } +t("value, objects") { o.ma_value("a", nil) } +t("value used") { warm { |i| o.ma_value_used(i, 1) } } +t("float") { warm { |i| o.ma_float(i) } } +t("objects") { warm { |i| o.ma_objects(i) } } +t("overflow") { warm { |i| o.ma_overflow(i) }; o.ma_overflow(2**40) } +t("effect then a deopt") { p2 = MA.new; warm { |i| p2.ma_effect(i) }; [p2.ma_effect(2**62), p2.n] } +t("order") { p2 = MA.new; warm(100) { |i| p2.ma_order(i) }; [p2.ma_order(7), p2.log.last(4)] } +t("in a loop") { warm(50) { |i| o.ma_in_loop(i % 20) }; [o.ma_in_loop(10), o.ma_in_loop(100)] } +t("frozen") { p2 = MA.new; warm { |i| p2.ma_frozen(i) }; p2.freeze; [(p2.ma_frozen(1) rescue $!.class), p2.a, p2.b] } + +class MA + remove_method :ma_swap + def ma_swap(x, y) + x, y = y, x + x + y + end +end +t("redefined") { o.ma_swap(3, 4) } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 3f7eb47d3..1104c834f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1450,6 +1450,56 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitscreen2 (2026-11-26) - a multiple assignment of a list in a body the method JIT + compiles** (`a, b = b, a`, `@a, @b = x, y`) - census only, not gated. With the census + counting honestly, the lines after the Hash literal were String literals (101) and multiple + assignment (75). The String literals left are arguments of calls on self (`add_tag :BOLD, + "\e[1m"`, Json's `read_char('-')`: taking them was perf/strlit's rejected first build, gap 1's + wall) and operands of String operators (`text << " @ "`, `@user + ':'`, `'%x' % n`: String + intrinsics, not a screen step). Multiple assignment had no JIT attempt (perf/masgn was light + frames). Of the 75: about 47 destructure one value (`a, b = f(x)`, `x, y = pair`), which needs + `to_ary` - Ruby code run from the typed body, or a deopt after the effect that made the value, + which the compiler declines (the trap) - and are left; the list form is taken. + `EmitParallelAssignment` follows the generic body (`CompoundLeftValue.TransformWrite`): every + right-hand value into a temporary, left to right, then each target written left to right, + nil for a missing value, an extra one evaluated and dropped. Each write is `EmitAssignment` + of `target = value` with the value an `EmittedValue` (a node the typed compiler alone makes), + so locals keep their types and an instance variable write its effect and frozen-self deopt + exactly as two statements would. Targets: locals of the method and instance variables; no + `*rest`, no nested target, two or more values, none splatted (`IsListAssignment`). The + expression's Array is made only where its value is used (not before the last statement of a + list). + JIT compiles 11.9% (3,370 -> 3,376), maybe 2,981 -> 2,989, never 22,025 -> 22,011, light + frames unchanged (Src/StdLib + AWFY, 28,376 methods; 14 methods moved up - 6 to `compiles`, 8 + to `maybe`, all 8 at a call - none down). `ParallelAssignmentExpression` alone 75 -> 60 (the + destructuring forms). Moved: initializers (`Benchmark::Report`, `RDoc::Markup::Table`, + `Net::IMAP::ResponseReader`, `IRB::Vec`), `URI::Generic#set_authority` (three copies, at + `default_port`); none of AWFY or the prelude. + Traces: app-shapes specialized 116 -> 117 (`Shop::Line#initialize`), declined after the + pre-screen 30 -> 30; AWFY Json, Richards, DeltaBlue, CD and Havlak (3 x 10) the same on both + builds; `census.rb -c` 290 agree, 0 differ, and app-shapes' known 15. + Instructions a call (`Util/perf/callgrind/count.sh`, `Util/bench/jit-masgn-shapes.rb`, new): + `x, y = y, x` 2634 -> 1492 (0.57), `a, b, c = x, x + 1, x * 2` 3559 -> 1560 (0.44), + `@a, @b = x, y` 2483 -> 1948 (0.79), the expression's value used 2608 -> 1954 (0.75), the + control (`a = x; b = x + 1`) 1518 -> 1519. Timed (`ab.rb`, six rounds): 0.44 and 0.41 for + the first two, the rest overlapping. + Checked: `Util/jit-masgn-matrix.rb` (new, 22 rows: swap of Ints, Floats and Strings, three + values and a Bignum, rotation, instance variables and their swap, a local and an instance + variable together, a missing and an extra value, the value used and dropped, Float and object + values, overflow, an effect then a deopt, the order of calls on the right, a Fibonacci swap in + a `while` loop, a frozen self, redefinition; 17 of 19 `ma_*` methods specialized, the others at + a call of `note` and at an interpolation's deopts), and jit, jit-calls, jit-const, masgn, + jit-scan, ivar, jit-hash and jit-construct: CRuby's output and the unchanged build's with the + JIT on, `-X:NoJIT -X:NoOSR` and `-X:NoJITCalls`, and the unchanged build's with + `IR_LIGHT_FRAMES=0`; hot-shapes and inline-matrix (one case per process) the unchanged build's + in every mode, with their known one-row differences from CRuby. + Also: a per-count body (a method with optional parameters) that declined said "no reason + recorded" (`TrySpecializePerCount` never set the reason); it now records it as `TrySpecialize` + does. `CSV::FieldsConverter#initialize`'s line says "the compiler bailed out (see the + `rejected' line)". + For the gate: no IronRuby.Tests or spec run; `EmittedValue` is a new kind of node only the + typed compiler makes (its TransformReadCore throws). + - **perf/jitscreen (2026-11-26) - a Hash literal in a body the method JIT compiles** (`{}`, `{a: x}`, `{"k" => v}`, `opts = {}`) - census only, not gated. The screen refused every Hash literal, the largest line of "JIT never, one thing only" that is not a call once the census From 1a60343af1034d446c5e671cf3ca6c39e6e7137f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:49:04 +0000 Subject: [PATCH 061/439] An endless def's expression is not a TracePoint :line event `def e1 = 42` reported a :line event for its body when called; CRuby reports none (LEDGER gap 33): prism gives the expression of an endless def no newline flag, and only newline-flagged nodes are lines to CRuby. Statements in parentheses in it are flagged (`def e = (y = 1; y + 1)` and `def a = (42)` report their line), and so are the statements of a block in it. The bridge adds the expression of an endless def to the body with Statements.NoLine, as it does the parameter prologue, unless the body holds parenthesized statements (which the bridge unwraps, so they would lose their event); a rescue modifier there (`def m = x rescue y`) leaves its guarded expression without a line too (RescueExpression.GuardedWithoutLine). A block in an endless body no longer reports its line twice. Left: a parenthesized default of a parameter (`def f(x = (1))`) is a line to CRuby in any def; IronRuby reports none for it (as before). Checked: TracePoint_EndlessDefLine1 (new; CRuby 4.0's output); Util/interpolation-matrix.rb gains "TracePoint :line, an endless def" (baseline before, CRuby's output now) and "to_s raises: the frame names the line", the other gap-33 difference, which already matches CRuby on this branch, with and without a scope (a heredoc's local-variable part still names the statement's line, left out with a comment); spec/core/tracepoint, set_trace_func, spec/library/coverage, spec/language def, method and string: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 27 ++++++++++++++++ Src/Prism/PrismAstBridge.cs | 31 ++++++++++++++++--- .../Ast/Expressions/RescueExpression.cs | 10 +++++- Util/interpolation-matrix.rb | 24 ++++++++++++-- 5 files changed, 84 insertions(+), 9 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 550e03962..0f9bc552b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1130,6 +1130,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrame2, Block_RegisterLocals1, Defined_ConditionNoFreeze1, + TracePoint_EndlessDefLine1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, Review212_1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index edb7f9820..55174dc79 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8501,6 +8501,33 @@ public void Comparison_AnonymousClassName1() { comparison of Float with Labeled failed comparison of Integer with Labeled failed comparison of Integer with nil failed +"); + } + + /// + /// The expression of an endless def is not a line to TracePoint :line (prism gives it no newline flag): CRuby reports + /// no event for it, with or without a rescue modifier, but does for statements in parentheses in it and in a block. + /// (The lines are one more than ruby's for the same text: the snippet starts on its second line.) + /// + public void TracePoint_EndlessDefLine1() { + TestOutput(@" +def e1 = 42 +def e2(x) = x + 1 +def e3 = (y = 1; y + 1) +def e4(x = 1) = x rescue 2 +def e5 = (42) +def e6 = [1].map { _1 } +def e7 = [1].map { |x| + x } +def n1 + 42 +end +lines = [] +tp = TracePoint.new(:line) { |t| lines << [t.lineno, t.method_id] if t.method_id } +tp.enable { e1; e2(1); e3; e4; e5; e6; e7; n1 } +p lines +", @" +[[4, :e3], [6, :e5], [7, :e6], [9, :e7], [11, :n1]] "); } } diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 58bc5d9dd..4b9e6b120 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -714,6 +714,7 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.SelfNode _: return new SelfReference(span); case Pm.ParenthesesNode parens: { + if (parens.Body != null) _parenthesizedStatements++; var inner = StatementsAsExpression(parens.Body, span); // `(self).m` is not a call with self as the receiver: MRI only lets a private method // be called on a bare `self`, so the parentheses have to survive the unwrapping. @@ -2059,8 +2060,10 @@ private Arguments OptionalArguments(Pm.PmNode argumentsNode) { // ---- bodies ---- - private Body/*!*/ BuildBeginBody(Pm.BeginNode/*!*/ node, SourceSpan span, Statements prologue) { + private Body/*!*/ BuildBeginBody(Pm.BeginNode/*!*/ node, SourceSpan span, Statements prologue, bool endless = false) { + int parenthesized = _parenthesizedStatements; var statements = BuildStatements(node.Statements); + if (endless && parenthesized == _parenthesizedStatements) statements = WithoutLines(statements); if (prologue != null) statements = Prepend(prologue, statements); List rescues = null; @@ -2079,6 +2082,20 @@ private Arguments OptionalArguments(Pm.PmNode argumentsNode) { return new Body(statements, rescues, elseStatements, ensureStatements, span); } + // Parenthesized statements mapped so far (an endless def's body with some keeps its line, see WithoutLines). + private int _parenthesizedStatements; + + // The expression of an endless def (`def m = expr') is not a line of its own to TracePoint :line: prism does not + // mark it a new line, and CRuby reports no event for it (statements inside it, in parentheses, are reported). + private static Statements/*!*/ WithoutLines(Statements/*!*/ statements) { + var result = new Statements(); + foreach (var statement in statements) { + if (statement is RescueExpression rescue) rescue.GuardedWithoutLine = true; + result.Add(statement, Statements.NoLine); + } + return result; + } + private static Statements/*!*/ Prepend(Statements/*!*/ prologue, Statements/*!*/ body) { var result = new Statements(); // the parameter-binding prologue is not a line of the source (TracePoint :line) @@ -2100,11 +2117,15 @@ private Arguments OptionalArguments(Pm.PmNode argumentsNode) { BuildStatements(node.Statements), Span(node)); } - private Body/*!*/ DefinitionBody(Pm.PmNode body, SourceSpan span, Statements prologue) { + private Body/*!*/ DefinitionBody(Pm.PmNode body, SourceSpan span, Statements prologue, bool endless = false) { if (body is Pm.BeginNode begin) { - return BuildBeginBody(begin, span, prologue); + // (`def m = x rescue y') + return BuildBeginBody(begin, span, prologue, endless); } + int parenthesized = _parenthesizedStatements; var statements = BuildStatements(body); + // (statements in parentheses are lines to CRuby, `def m = (42)' too; unwrapped, they would lose their event) + if (endless && parenthesized == _parenthesizedStatements) statements = WithoutLines(statements); if (prologue != null) statements = Prepend(prologue, statements); return new Body(statements, null, null, null, span); } @@ -2218,7 +2239,7 @@ private Parameters BlockParameters(Pm.PmNode parametersNode, bool autoSplat, out node.Body = node.DeferredBodyLoader.LoadDeferredBody(node); node.DeferredBodyLoader = null; } - var body = DefinitionBody(node.Body, span, prologue); + var body = DefinitionBody(node.Body, span, prologue, node.EqualLoc != null); return new MethodDefinition(scope, target, node.Name, parameters, body, span) { UsesBlock = _usesBlock }; } finally { _zsuperArguments = enclosingZSuperArguments; @@ -2273,7 +2294,7 @@ public DeferredMethodBody(PrismAstBridge/*!*/ bridge, Pm.DefNode/*!*/ node, Lexi _usesBlock = false; _zsuperArguments = zsuperArguments; try { - var body = DefinitionBody(bodyNode, span, prologue); + var body = DefinitionBody(bodyNode, span, prologue, node.EqualLoc != null); // the skim has to have seen what mapping the body sees System.Diagnostics.Debug.Assert(_usesBlock == ((node.BodyContents & PrismLoader.ContentsUsesBlock) != 0)); return body; diff --git a/Src/Ruby/Compiler/Ast/Expressions/RescueExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/RescueExpression.cs index 91fccd8d6..1058fde01 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/RescueExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/RescueExpression.cs @@ -46,9 +46,17 @@ public RescueExpression(Expression/*!*/ guardedExpression, Expression/*!*/ rescu _rescueSpan = rescueSpan; } + /// + /// The guarded expression is not a line of its own to TracePoint :line: set on the expression of an endless def + /// (`def m = x rescue y'), which CRuby reports no line event for. + /// + public bool GuardedWithoutLine { get; set; } + private Body/*!*/ ToBody(AstGenerator/*!*/ gen) { + var guarded = new Statements(); + guarded.Add(_guardedExpression, GuardedWithoutLine ? Statements.NoLine : _guardedExpression.Location.Start.Line); return new Body( - new Statements(_guardedExpression), + guarded, CollectionUtils.MakeList(new RescueClause(Array.Empty(), null, new Statements(_rescueClauseStatement), _rescueSpan)), null, null, Location); } diff --git a/Util/interpolation-matrix.rb b/Util/interpolation-matrix.rb index eb5c148d1..5c7f4372f 100644 --- a/Util/interpolation-matrix.rb +++ b/Util/interpolation-matrix.rb @@ -210,9 +210,20 @@ def b_frames(x) = "#{caller(0, 3).map { |l| label(l) }}" t('nested calls') { b_outer(1) } t('a raise in a part') { begin; b_raise_outer(1); rescue TypeError => e; [e.message, e.backtrace[0, 2].map { |l| label(l) }]; end } -# (not the line: IronRuby names the method's first line for a frame whose interpolated part's #to_s raised, -# with or without its scope) t('to_s raises in a heredoc') { begin; b_heredoc(ToSRaises.new); rescue IndexError => e; e.backtrace[0, 2].map { |l| label(l) }; end } +def b_line(x) + y = 1 + "a#{x}#{y}" +end +def b_line_scope(x) + y = binding.local_variable_get(:x) + "a#{y}" +end +t('to_s raises: the frame names the line') do + [b_line(ToSRaises.new), b_line_scope(ToSRaises.new)] rescue $!.backtrace_locations[1].lineno - __LINE__ +end +# (not the line of a heredoc's part that is a local variable: IronRuby names the heredoc's statement, CRuby the +# part's own line) t('a frame list in a part') { b_frames(1) } class Deep; def to_s = deep_s(self); end @@ -223,7 +234,14 @@ def r_count(n) = n == 0 ? "0" : "#{r_count(n - 1)}".size.to_s # ---------------------------------------------------------------- 6. tracing and threads -# (not an endless def: IronRuby reports a :line event for its body, CRuby none) +def traced_endless(x) = "t#{x}" +def traced_endless_parens(x) = ("t#{x}") +t('TracePoint :line, an endless def') do + seen = [] + tp = TracePoint.new(:line) { |e| seen << [e.method_id, e.lineno - __LINE__] if e.method_id.to_s.start_with?("traced_endless") } + tp.enable { traced_endless(1); traced_endless_parens(2) } + seen +end def traced(x) "t#{x.fdiv(1)}" end From 16ce9ac078c97b56cda537382c5646696b65b2af Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:49:04 +0000 Subject: [PATCH 062/439] "#{sym}" under a refinement of Symbol#to_s is the Symbol's name With a refinement of Symbol#to_s in use, `"#{x}"` for a Symbol x called the refined to_s (LEDGER gap 33); CRuby answers the Symbol's name: vm_objtostring takes it while Symbol#to_s is the built-in method (check_method_basic_definition), refined or not, and only a redefined Symbol#to_s is called as any other, under the refinements. (A literal `"#{:s}"` was already "s".) RubyOps.TryConvertToSWithRefinements, the refinement-aware conversion an interpolation tries first, now leaves a Symbol to the plain conversion while Symbol#to_s resolves to the library's SymbolOps.ToString. It runs only where some refinement defines to_s. Checked: Refinements17 (new; CRuby 4.0's output, including an aliased Symbol#to_s); Util/interpolation-matrix.rb gains "a Symbol, defined after using (no refined #to_s asked)", which the matrix had left out: CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 3 ++- Src/IronRuby.Tests/Runtime/RefinementTests.cs | 25 +++++++++++++++++++ Src/Ruby/Runtime/RubyOps.cs | 24 ++++++++++++++++++ Util/interpolation-matrix.rb | 2 +- 4 files changed, 52 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0f9bc552b..3d09fe2df 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -924,6 +924,7 @@ public Tests(Driver/*!*/ driver) { Refinements14, Refinements15, Refinements16, + Refinements17, Super1, SuperParameterless1, @@ -1129,8 +1130,8 @@ public Tests(Driver/*!*/ driver) { Method_LightFrame1, Method_LightFrame2, Block_RegisterLocals1, - Defined_ConditionNoFreeze1, TracePoint_EndlessDefLine1, + Defined_ConditionNoFreeze1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, Review212_1, diff --git a/Src/IronRuby.Tests/Runtime/RefinementTests.cs b/Src/IronRuby.Tests/Runtime/RefinementTests.cs index 6103066ce..52cd88a17 100644 --- a/Src/IronRuby.Tests/Runtime/RefinementTests.cs +++ b/Src/IronRuby.Tests/Runtime/RefinementTests.cs @@ -618,6 +618,31 @@ module U 300.times { |i| x = U.make; (p [i, x]; r = x) if x != r } ", @" [0, [[1, 2], [0], [1]]] +"); + } + + /// + /// "#{sym}" is the Symbol's name while Symbol#to_s is the built-in one, even under a refinement of it (MRI's + /// vm_objtostring); a redefined Symbol#to_s is called as any other to_s, refinements included. + /// + public void Refinements17() { + TestOutput(@" +module R + refine(Symbol) { def to_s = ""refined"" } + refine(Integer) { def to_s = ""ri"" } +end +using R +x = :s; s = +""str"" +p ""#{x}"", ""#{:t}"", ""#{s}"", ""#{1}"", x.to_s +Symbol.alias_method :to_s, :inspect +p ""#{x}"" +", @" +""s"" +""t"" +""str"" +""ri"" +""refined"" +""refined"" "); } } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index a0bd8dd13..0a4172fe9 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -842,12 +842,36 @@ public static MutableString TryConvertToSWithRefinements(RubyScope/*!*/ scope, o if (!IsRefinedHere(scope, value, "to_s")) { return null; } + // MRI's objtostring takes a Symbol's name while Symbol#to_s is the built-in one, refined or not (vm_objtostring: + // check_method_basic_definition); a redefined Symbol#to_s is called as any other, under the refinements. + if (value is RubySymbol && IsBuiltinSymbolToS(context)) { + return null; + } var site = context.GetOrCreateSendSite>( "to_s", new RubyCallSignature(0, RubyCallFlags.HasScope | RubyCallFlags.HasImplicitSelf) ); return ToSDefaultConversion(context, value, site.Target(site, scope, value)); } + private static bool IsBuiltinSymbolToS(RubyContext/*!*/ context) { + var symbolClass = context.GetClass(typeof(RubySymbol)); + RubyMemberInfo method; + using (context.ClassHierarchyLocker()) { + method = symbolClass.ResolveMethodNoLock("to_s", VisibilityContext.AllVisible).Info; + } + // the library's Symbol#to_s (SymbolOps.ToString), not another library method aliased as to_s + if (!(method is RubyLibraryMethodInfo) || method.DeclaringModule != symbolClass) { + return false; + } + var members = method.GetMembers(); + var clrMethod = (members.Length == 1) ? members[0] as MethodInfo : null; + if (clrMethod == null || clrMethod.Name != "ToString") { + return false; + } + var parameters = clrMethod.GetParameters(); + return parameters.Length == 1 && parameters[0].ParameterType == typeof(RubySymbol); + } + /// /// A block argument (&x) in a scope where refinements are active: a Symbol's proc calls the method /// with the refinements of this place (MRI's refinement-aware symbol proc), and a refined #to_proc diff --git a/Util/interpolation-matrix.rb b/Util/interpolation-matrix.rb index 5c7f4372f..5b34d801c 100644 --- a/Util/interpolation-matrix.rb +++ b/Util/interpolation-matrix.rb @@ -301,8 +301,8 @@ def r_after(x) = "#{x}" t('defined before using') { [r_before(1), r_before(:s), r_before(nil), r_before(Shown.new)] } t('defined before, subclass') { r_before(ShownSub.new) } t('a nested def run again after using') { r_nested(1) } -# (not a Symbol: CRuby interpolates one without asking a refined #to_s, IronRuby asks it) t('defined after using') { [r_after(1), r_after(nil), r_after(Shown.new)] } +t('a Symbol, defined after using (no refined #to_s asked)') { [r_after(:s), "#{:s}", (x = :t; "#{x}")] } t('defined after, subclass') { r_after(ShownSub.new) } t('a refinement that exists but is not used') { r_after(1.5) } t('at the call site') { [r_before(2), "#{2}"] } From 8fde49800609f27a0e22637e3666afff961457c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:50:28 +0000 Subject: [PATCH 063/439] Make a retired JIT entry's cool-down cost nothing per call A method whose typed body keeps failing (`x + 1' called with an Integer and a Float in turn) ran 10-16% slower than with the JIT off, a def as much as a define_method method. Its entry is retired and retried 8 times, cooling down 8 to 1024 ms - about two seconds before it settles - and all that time the stub's cooling stand-in counted every call and timed one in 8 with two Stopwatch reads, of which it used the last 16 once, when the cool-down ended. A retirement now puts the generic body itself in the fast slot, as a settled method has it, and a timer ends the cool-down by starting the probe the stub already had: 32 generic calls, each timed, after which CoolDownCheck puts the entry back. A generation count makes a timer left from an earlier rest do nothing, and GenericCompiled installs the compiled generic body during a rest too. The retire rule and the retry schedule are unchanged; a body that deopts rarely is never retired. IR_JIT_REST=0 brings back the counted cool-down. Checked: Util/bench/jit-settle-shapes.rb, ab.rb -r 6: the Integer-and-Float def 112.7 -> 97.5 ns (-X:NoJIT 95.9), the define_method one 127.6 -> 117.9 (119.8), a body that fails once in 1000 and the controls level; callgrind counts of the controls 1.000. AWFY traces specialize, decline and keep the same on both builds and retire nothing. jit, jit-calls, jit-const and dmeth-jit matrices print CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls and IR_JIT_REST=0; hot-shapes, inline and int-matrix print the base's. The 20 IronRuby.Tests named for the JIT pass. Not gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/Ruby/Runtime/Jit/JitStub.cs | 52 +++++++++++++++++++++++++++++++-- Util/bench/jit-settle-shapes.rb | 49 +++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 38 ++++++++++++++++++++++++ 3 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 Util/bench/jit-settle-shapes.rb diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 9f8a4172c..290239df6 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -253,7 +253,8 @@ private void GenericCompiled(Delegate/*!*/ compiled) { bool settled; lock (_sync) { settled = _state == Settled; - if (settled) { Install(compiled); } + // a retired entry's rest holds the generic body too (StartResting) + if (settled || _state == Cooling && _resting) { Install(compiled); } } if (settled) { NotifyOwner(); } } @@ -430,6 +431,9 @@ private void GiveUp() { // Under _sync: the generic body, for good. private void Settle() { + _resting = false; + _restTimer?.Dispose(); + _restTimer = null; _state = Settled; _current = null; _direct = null; @@ -572,6 +576,12 @@ private bool Respecialize(Specialization/*!*/ spec) { // CoolDownMs and doubles at each retirement. A retry that fails again costs one more window // of deopts, about 0.2 ms, against a cool-down of at least 8 ms; after MaxRetirements the // method keeps its generic body for good. + // + // The cool-down costs nothing per call (StartResting): the fast slot holds the generic body + // itself, as a settled method's does, and a timer ends it with a probe (ProbeCalls generic + // calls, each timed), whose CoolDownCheck puts the entry back. A stand-in that counted every + // call and timed one in 8 for the whole cool-down cost a method that keeps deopting 10-16% + // over the generic body for the two seconds before it settled (perf/jitsettle). internal const int MaxDeopts = 16; private const int DeoptWindow = MaxDeopts * 64; private const int MaxRetirements = 8; @@ -680,8 +690,12 @@ internal void OnDeopt(Specialization/*!*/ spec, long deoptCost) { final ? ", for good" : String.Format(", retry in {0} ms", CoolDownMs << (_retirements - 1))); } if (!final) { - StartCooling(Stopwatch.GetTimestamp() + (Stopwatch.Frequency * CoolDownMs / 1000) * (1L << (_retirements - 1)), - CoolCheckCalls, CoolSampleMask); + if (RestEnabled) { + StartResting(CoolDownMs << (_retirements - 1)); + } else { + StartCooling(Stopwatch.GetTimestamp() + (Stopwatch.Frequency * CoolDownMs / 1000) * (1L << (_retirements - 1)), + CoolCheckCalls, CoolSampleMask); + } return; } Settle(); @@ -708,9 +722,41 @@ private void Probe(Specialization/*!*/ spec, int entries, long deopt) { } } + // A retired entry's cool-down (OnDeopt): the generic body itself in the fast slot, nothing + // counted or timed, until a timer starts the probe that ends it (EndRest). _restGeneration + // names the rest a timer was set for, so that one left over from an earlier rest - the state + // moved on, and back to Cooling - does nothing. + // IR_JIT_REST=0: the counted, sampled cool-down of before (StartCooling for the whole of it). + internal static readonly bool RestEnabled = Environment.GetEnvironmentVariable("IR_JIT_REST") != "0"; + private bool _resting; + private int _restGeneration; + private Timer _restTimer; + + // Under _sync. + private void StartResting(int ms) { + _direct = null; + _state = Cooling; + _resting = true; + int generation = ++_restGeneration; + Install(BestGeneric); + _restTimer?.Dispose(); + _restTimer = new Timer(state => ((JitStub)state).EndRest(generation), this, ms, Timeout.Infinite); + } + + private void EndRest(int generation) { + lock (_sync) { + if (_state != Cooling || !_resting || generation != _restGeneration) { return; } + // time the generic body on the next calls, then put the entry back (CoolDownCheck) + StartCooling(0, ProbeCalls, 0); + } + } + // Under _sync: the generic body until `until' and `calls' generic calls have passed, timing // the calls Cool picks with `mask'. private void StartCooling(long until, int calls, int mask) { + _resting = false; + _restTimer?.Dispose(); + _restTimer = null; _direct = null; _coolUntil = until; _coolCalls = calls; diff --git a/Util/bench/jit-settle-shapes.rb b/Util/bench/jit-settle-shapes.rb new file mode 100644 index 000000000..2a8291b6d --- /dev/null +++ b/Util/bench/jit-settle-shapes.rb @@ -0,0 +1,49 @@ +# What a method the JIT specialized costs once its typed body keeps failing (perf/jitsettle): `x + 1' called with an +# Integer and a Float in turn, as a def and as a define_method method; one whose typed body fails on one call in 1000; +# and bodies that never fail, as controls. ` ns ' per line, for Util/perf/ab.rb; `ruby +# jit-settle-shapes.rb NAME...' runs only the shapes named; N is the number of calls a section makes (ab.rb -n); +# INSTR=1 (ab.rb -i, or Util/perf/callgrind/count.sh) adds the instructions of a call. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end +def t(name, n = 2_000_000) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + n = ENV['N'].to_i if ENV['N'] + best = 1e9; r = nil; fewest = nil; counted = !!INSTR + 5.times do + c0 = INSTR && INSTR.read + t0 = cpu + r = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + fewest = c1 - c0 if fewest.nil? || c1 - c0 < fewest + else + counted = false + end + end + printf "%-14s %8.1f ns %s%s\n", name, best * 1e9 / n, r, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +class B + def initialize = (@a = 3) + def mixed(x) = x + 1 + define_method(:bmixed) { |x| x + 1 } + def rare(x) = x + 1 + def plain(x) = x + 1 + def ivar(x) = @a + x + def two(x, y) = x * y + 1 + define_method(:bplain) { |x| x + 1 } +end +o = B.new +t("mixed_def") { |n| i = 0; c = 0; while i < n; c += o.mixed(i.odd? ? i : 0.5).to_i; i += 1; end; c } +t("mixed_dm") { |n| i = 0; c = 0; while i < n; c += o.bmixed(i.odd? ? i : 0.5).to_i; i += 1; end; c } +t("rare_def") { |n| i = 0; c = 0; while i < n; c += o.rare(i % 1000 == 999 ? 0.5 : i).to_i; i += 1; end; c } +t("plain_def") { |n| i = 0; c = 0; while i < n; c += o.plain(i); i += 1; end; c } +t("ivar_def") { |n| i = 0; c = 0; while i < n; c += o.ivar(i); i += 1; end; c } +t("two_def") { |n| i = 0; c = 0; while i < n; c += o.two(i, 2); i += 1; end; c } +t("plain_dm") { |n| i = 0; c = 0; while i < n; c += o.bplain(i); i += 1; end; c } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8e36bf943..a1551aec0 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1492,6 +1492,44 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitsettle (2026-11-26) - a retired entry's cool-down costs nothing per call** - not gated. + A method whose typed body keeps failing (`x + 1` called with an Integer and a Float in turn) ran + 10-16% slower than with the JIT off, as a `def` and as a define_method method. What it does per call, + from a trace (`IR_JIT_VERBOSE=1`, a phase-by-phase timing of 12.5 million calls): after the first + windows of 16 deopts the entry is retired and retried 8 times, cooling down 8, 16, ... 1024 ms - about + 2 s in all before it settles for good - and all that time the fast slot held the cooling stand-in + (`Cool`): a counter decremented on every call, a random pick, and one call in 8 timed with two + `Stopwatch` reads, though only the last 16 samples are used, once, when the cool-down ends. Steady + state: 115 ns a call against 101 with `-X:NoJIT`. + - The change (`JitStub.StartResting`): a retirement puts the generic body itself in the fast slot, + as a settled method has it, and a `System.Threading.Timer` ends the cool-down by starting the probe + the stub already had (`StartCooling(0, ProbeCalls, 0)`: 32 generic calls, each timed), whose + `CoolDownCheck` puts the entry back. A generation count makes a timer left from an earlier rest do + nothing; `GenericCompiled` installs the compiled generic body during a rest too. The probes before + any retirement, the retire rule and the retry schedule are unchanged; a body that deopts rarely is + never retired, so it never rests. `IR_JIT_REST=0` brings back the counted cool-down. + - Time (`Util/bench/jit-settle-shapes.rb`, `ab.rb -r 6`, ns; -X:NoJIT / base / new, new over base): + `mixed_def` 95.9 / 112.7 / 97.5 (0.87), `mixed_dm` 119.8 / 127.6 / 117.9 (0.92), `rare_def` (a Float + on one call in 1000) 70.0 / 61.9 / 61.9 (1.00), controls `plain_def`, `ivar_def`, `two_def`, + `plain_dm` 0.96-0.99 (overlap). Phase by phase the `def` goes from 115 to about 100 ns, level with + `-X:NoJIT`, and the run of 12.5 million calls ends 0.2-0.5 s sooner. + - Instructions (`Util/perf/callgrind/count.sh`, N=20000): the controls and `rare_def` 1.000; + `mixed_def` 0.987, `mixed_dm` 1.000 - the cool-down is counted in milliseconds, of which valgrind's + 20,000 calls see little: the clock is this change's measure. + - AWFY (all 14, `harness.rb B 5 10`, IR_JIT_VERBOSE=1): 138 specialized, 29 declined, 15 kept, no + retirement and one probe's retry on both builds - none of the benchmarks retires an entry, so the + change does not reach them. + - Matrices, CRuby against base (3b28a0c) against new, with the JIT on, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` and `IR_JIT_REST=0`: jit, jit-calls, jit-const, dmeth-jit identical to CRuby; + hot-shapes, inline (one case per process) and int-matrix (through int-matrix.py, `.hash` lines left + out: they are seeded per process) identical to base, each with the rows that differ from CRuby on + base too (FrozenError for Encoding::CompatibilityError; "Object must be of type Int32"; + `(2**100).equal?(2**100)` and the size of `Integer.instance_methods(false)`). IronRuby.Tests: the 20 + named for the JIT pass. + - For the gate: a timer thread now takes the stub's lock (EndRest) - a stub retired while its + runtime shuts down has a timer pending for up to a second; and the retry needs only the timer and + 32 calls, where it needed 1024 calls and the cool-down. + - **perf/dmethjit2 (2026-11-26) - a define_method body that reads captured locals, and setters, in the method JIT (gap 23)** - not gated. Chosen by a survey of the 154 `define_method` blocks in the standard library and the bundled gems (Prism, by parameters and what the body does with the From 1600af98f880280c139b8c3b212929aa8115a546 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:50:40 +0000 Subject: [PATCH 064/439] Ledger: perf/crubydiff, the differences from CRuby it closes Gaps 24 (Data's allocate), 33, 34 and 37, the perf/lrebind and perf/struct notes, and a Landed entry listing each fix, what was already matching, what is left (a heredoc part's frame line, a parenthesized parameter default's :line event, tr!'s check order, the CLR names on Integer and Float) and what the gate should look at. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 71 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 67 insertions(+), 4 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..ac821f2ac 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1119,8 +1119,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has two parameters). Round thirty-four (see Landed, perf/inv2): `Data.new`, `#with` and Data readers are direct; the invoice shapes are at CRuby's time. Left: initializers taking keywords (`Product.new(sku: - ...)`) at about 2x CRuby, `Hash#dup`, and Struct `keyword_init` as above. And - `Data.singleton_methods` lists `:allocate`, which CRuby's does not (as on the baseline). + ...)`) at about 2x CRuby, `Hash#dup`, and Struct `keyword_init` as above. (`Data.singleton_methods` + listed `:allocate`, which CRuby's does not: fixed in perf/crubydiff, see Landed.) perf/struct (see Landed, not gated): Struct keyword creation is stored in C#, `kw_new` 1017 -> 198 ns against CRuby's 299 (`kw_hash` 147 against 196, `sub_kw` 379 against 356). Left from this gap: keyword initializers (`kwinit` 236 against 132) and `Hash#dup`. @@ -1392,6 +1392,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has without a scope. A TracePoint `:line` event is reported for the body of an endless `def`, CRuby reports none. And with a refinement of `Symbol#to_s` in use, `"#{:s}"` asks the refined `to_s`; CRuby answers `"s"` without asking it. + Round thirty-seven (see Landed, perf/crubydiff): the endless `def` and the Symbol are fixed, and + the frame's line already matched CRuby on the branch (with and without a scope); the matrix has + rows for all three now. Left: in a heredoc, a part that is a local variable (`#{x}` on a line + below the statement) still names the statement's line - the bridge maps the part to the + variable's shared node, which carries the declaration's span, so the conversion gets no line of + its own (it would take a node that carries the part's span, and walker support for it). And a + parenthesized parameter default (`def f(x = (1))`) is a `:line` event to CRuby, none here. 34. **Two differences from CRuby in Hash literals**, found by the probes of `Util/hash-literal-matrix.rb` on the build before perf/hashlit and left as they were (the matrix leaves them out, with a comment); not speed gaps. A key that is an @@ -1399,6 +1406,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `h.keys[0].frozen?` is true and it is not `k`); CRuby 4.0 keeps `k` itself, unfrozen, and copies only a plain String. The same with `h[k] = 1`. And `defined?({a: 1.nope})` is `"expression"` where CRuby says nil, as both say for `defined?([1.nope])`. + Closed (see Landed, perf/crubydiff): the String subclass key is fixed; `defined?` already said + nil on the round-37 branch. The matrix has rows for both now. 35. **`Enumerator#next` and every other fiber switch cost 40 to 80 times CRuby's**: a fiber is a thread here, and a switch is a handoff between two threads (about 20-40 us against 0.5). @@ -1447,9 +1456,61 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has through `super`. And `Module#dup`/`clone` copies the constants in `super` of `initialize_copy`, where CRuby has copied them before it (a `const_get` in an `initialize_copy` before `super` sees the copy's constants there, the outer ones here). + Closed (see Landed, perf/crubydiff): both are fixed. Found on the way, left: CRuby's copy of a + singleton class makes `initialize`, `initialize_copy` and `respond_to_missing?` private in the copy; + and an explicit `obj.method_missing(:w)` after a private call's error says "private method 'w' + called" in CRuby (its method_missing_reason is never cleared), "undefined method" here. ## Landed +- **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not + gated; one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose + refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when + the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope + (`CallArguments.GetBoundCallSiteArguments`). struct-matrix: CRuby's output in full. Refinements16. + - `Data.singleton_methods` listed `:allocate` (gap 24), and so did ArithmeticSequence's and + Continuation's: the prelude's singleton `allocate` gave way to `Class#__ir_undef_alloc__`, MRI's + `rb_undef_alloc_func` (`RubyClass.UndefineAllocator`, checked in the allocate rule of that class + only). Prelude_DataUndefinedAllocator1. + - `frozen << x` raised Encoding::CompatibilityError (the three lines of hot-shapes-matrix that + differed from CRuby), `<< -1` / `<< 2**80` RangeError, `prepend(1)` TypeError: CRuby checks + frozenness first. The checks are on the error paths only (MutableString.MutateAppend when the + encodings clash, Append(int) before ToChr). hot-shapes-matrix: CRuby's output. Left: `frozen << + Object.new` is TypeError (the binder converts first), `tr!` checks frozenness before the + encodings where CRuby does the opposite. String_AppendFrozenFirst1. + - A String subclass's instance as a Hash key (gap 34): stored as it is, unfrozen, as CRuby's + RHASH_STRING_KEY_P has it (SetHashElement and the JIT's HashStoreObj). hash-literal-matrix: two + new rows, baseline before; a third for `defined?({a: x.nope})`, already same. Hash_StringSubclassKey1. + - A private or protected method's call reaching BasicObject#method_missing through a user's + `super` (gap 37): the visibility now travels with the method_missing reason + (`RubyOps.SetMethodMissingReasonVisibility`, a MethodInfo field, not a new [Emitted] helper), and + the error says "private method 'x' called". One more thread-static write per call that reaches a + user's method_missing. SuperAndMethodMissing3. + - Module#dup / #clone (gap 37): the members are copied in IDuplicable.Duplicate, before + initialize_copy, as MRI 4.0's init_copy does; Module's and Class's own initialize_copy are gone + (CRuby's owner is Kernel). ModuleCopyBeforeInitializeCopy1. + - An endless def's expression is no TracePoint `:line` event (gap 33): the bridge adds it with + Statements.NoLine unless it holds parenthesized statements; a rescue modifier there keeps no line + either. interpolation-matrix: new row, baseline before. TracePoint_EndlessDefLine1. + - `"#{sym}"` under a refinement of Symbol#to_s is the name while Symbol#to_s is the built-in + (gap 33, vm_objtostring). interpolation-matrix: new row. Refinements17. + Not fixed: `42.compare_to(o)` in inline-matrix's `tree_int_key` answers Int32#CompareTo's + "Object must be of type Int32." where CRuby has no such method. That is IronRuby's interop + (RubyModule.IsUnmangledBuiltin: snake_case CLR names on Integer and Float, `5.to_string("X")`, + which ClrTests asserts), not a leak; matching CRuby means dropping those names, or mapping them + only on request. Already matching on the branch when the round began: refinement before prepend on + Integer#+ (f7679a1), the frame line of a raising interpolation part, `defined?({a: x.nope})`. + Checked per fix (see each commit): the named IronRuby.Tests and the ruby/spec files around each + change on both trees, results as before (refine_spec 38/0, prepend_spec 55/0, spec/core/module + 1050 examples with the 4 known errors, struct, data, class, kernel dup/clone, string, hash, + tracepoint, coverage, basicobject, nomethoderror, language def/method/send/private/protected). + For the gate: the two changes on dispatch-adjacent paths - Class#new's rule for a library + initialize (no scope argument now, so a light-scope site's `Struct.new`/`Array.new` rule no longer + sets ScopeRead) and method_missing's reason - and Module#dup/#clone, which now copies before + initialize_copy (anything that relied on Module#initialize_copy copying, e.g. a re-run + initialize_copy, gets Kernel's). + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, @@ -1693,7 +1754,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has three alternating runs: 26-27 us a class on master, 20-21 here, CRuby 4.1-4.4. `Util/struct-matrix.rb` (new, 110 rows, each cold, again and warm) prints CRuby's output but for `UsingRefine.make`, a refined `initialize` that Class#new sees on every IronRuby build (master - too); master differs in eight more rows. Matrices through gate-matrices.rb, as built, `-X:NoJIT + too; fixed in perf/crubydiff, see Landed); master differs in eight more rows. Matrices through gate-matrices.rb, as built, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, `IR_LIGHT_FRAMES=0`, `IR_PARKED_SCOPES=0`, R2R and `IR_FAST_STRUCT=0`: struct, hash-struct, hash-order, keyword-light, jit, jit-calls `same` or `baseline -16`, hot-shapes `baseline`: PASS. spec/core/struct: 170 examples, 1 error (the known deconstruct_keys @@ -1944,7 +2005,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has work on the light-frame compile path, not binding: perf by DSO puts it in libcoreclr, libclrjit, CoreLib, Microsoft.Dynamic and System.Linq.Expressions. Found in passing, not fixed: CRuby calls a refinement of Integer#+ before a module prepended to - Integer; IronRuby calls the prepended module's method (light frames on and off). + Integer; IronRuby calls the prepended module's method (light frames on and off). (Fixed since by + f7679a1, "Search a refinement ahead of the modules prepended to what it refines": perf/crubydiff + found it matching CRuby in every mode, and `Util/shared-rule-light-matrix.rb` covers it.) Gate, the branch at 5b464e8c against b76d3a6f, Release net10.0: **PASS**. IronRuby.Tests PASSED on both (1,334). 36 matrices in five modes: 180 same, 0 differ. ruby/spec, all five suites: no failure the known list does not name. `ab.rb -i` on the rescue, keyword, loop and From c5b20fa284a15d32a4cb14b6438ecc38ff0789bc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:56:05 +0000 Subject: [PATCH 065/439] Enter methods without reading the pending alias name (IR_LIGHT_ENTRY) A call through an alias leaves the name it was called by in a thread-static for the method's entry to take. Every entry tested a flag first, but start-up sets it for good, so every entry of every method, light or scoped, read the thread-static - a call into the runtime from a DynamicMethod, about 60 instructions with the test. The flag is now a count of the threads with a name pending: raised by the alias call when its thread had none, lowered by the entry that takes it. A light frame without register locals also called CreateMethodScopeIfTraced on every entry to learn that nothing listens; the test is inline now, as it is in EnterWithRegisterLocals. Counted with Util/perf/callgrind/count.sh (switch off -> on): a light method that does nothing 0.913, one with three calls 0.863, scoped ones 0.945-0.974, String#bytesplice 0.992, regex-shapes and core-small 0.931-1.000. Util/light-entry-matrix.rb and twelve other matrices print the baseline's output in six modes; AliasTests and Method_LightFrame* pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 9 +++- Src/Ruby/Runtime/RubyOps.cs | 41 ++++++++++--------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index c31a62eec..fab66fbf0 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -646,7 +646,14 @@ private sealed class LightFrame { scope.MakeLocalsStorage(), Ast.Assign(Rfc, EnterMethod), Ast.Assign(Callee, Methods.TakePendingCallee.OpCall(Name)), - MakeScopeIfTraced(scope.LocalsTupleVariable) + // the test inline, as in EnterWithRegisterLocals: a call of CreateMethodScopeIfTraced, with its nine + // arguments, on every entry to find out that nothing listens (IR_LIGHT_ENTRY=0 makes the call) + RubyOps.PendingCalleesCounted + ? (MSA.Expression)Ast.Condition(Methods.IsMethodCallTraced.OpCall(), + MakeScopeIfTraced(scope.LocalsTupleVariable), + AstUtils.Constant(null, typeof(RubyMethodScope)) + ) + : MakeScopeIfTraced(scope.LocalsTupleVariable) ); } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 0df3ee308..8de26165f 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -217,14 +217,8 @@ internal static void ThrowStackLevelTooDeep() { interpretedFrame ); - if (_aliasCallSeen) { - string callee = _pendingCallee; - if (callee != null) { - _pendingCallee = null; - if (_pendingCalleeDefinition == definitionName) { - scope.CalleeName = callee; - } - } + if (_pendingCallees != 0) { + scope.CalleeName = TakePendingCalleeSlow(definitionName); } if ((TracePoint.ActiveEvents & (int)(TraceEvents.Call | TraceEvents.CCall)) != 0) { @@ -286,14 +280,8 @@ private static ParkedProcs TakeParkedScopeSlow(ParkedScopeSlot/*!*/ slot, Parked var scope = parked.Scope; scope.Reinitialize(locals, selfObject, blockParameter, interpretedFrame, null, null); - if (_aliasCallSeen) { - string callee = _pendingCallee; - if (callee != null) { - _pendingCallee = null; - if (_pendingCalleeDefinition == scope.DefinitionName) { - scope.CalleeName = callee; - } - } + if (_pendingCallees != 0) { + scope.CalleeName = TakePendingCalleeSlow(scope.DefinitionName); } if ((TracePoint.ActiveEvents & (int)(TraceEvents.Call | TraceEvents.CCall)) != 0) { @@ -480,13 +468,16 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R [Emitted] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string TakePendingCallee(string/*!*/ definitionName) { - return _aliasCallSeen ? TakePendingCalleeSlow(definitionName) : null; + return (_pendingCallees != 0) ? TakePendingCalleeSlow(definitionName) : null; } private static string TakePendingCalleeSlow(string/*!*/ definitionName) { string callee = _pendingCallee; if (callee != null) { _pendingCallee = null; + if (PendingCalleesCounted) { + Interlocked.Decrement(ref _pendingCallees); + } if (_pendingCalleeDefinition == definitionName) { return callee; } @@ -570,7 +561,15 @@ private static void LeaveLightMethodFrameSlow(RuntimeFlowControl/*!*/ rfc, RubyS private static string _pendingCallee; [ThreadStatic] private static string _pendingCalleeDefinition; - private static bool _aliasCallSeen; + + // How many threads have a name pending (_pendingCallee): a frame's entry reads the thread-static only when some thread + // has. It used to be a flag that stayed set once any alias had been called - start-up calls some - and from then on + // every method's entry, light or not, read the thread-static, which in a DynamicMethod is a call into the runtime + // (~60 instructions with the test). A name is pending from the alias call's MarkAliasCall to the next entry of a + // method on that thread, which takes it whether or not it is that method's. A stale count only costs reads. + // IR_LIGHT_ENTRY=0: the flag as it was (counted up once, never down). + private static int _pendingCallees; + internal static readonly bool PendingCalleesCounted = Environment.GetEnvironmentVariable("IR_LIGHT_ENTRY") != "0"; /// /// Wraps the last argument of a call to a method through an alias, so that the name is @@ -578,7 +577,11 @@ private static void LeaveLightMethodFrameSlow(RuntimeFlowControl/*!*/ rfc, RubyS /// [Emitted] public static object MarkAliasCall(object lastArgument, string/*!*/ calleeName, string/*!*/ definitionName) { - _aliasCallSeen = true; + if (!PendingCalleesCounted) { + _pendingCallees = 1; + } else if (_pendingCallee == null) { + Interlocked.Increment(ref _pendingCallees); + } _pendingCallee = calleeName; _pendingCalleeDefinition = definitionName; return lastArgument; From 11f2b351927eaec6a07481a2ad6b02fc1072e447 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:56:05 +0000 Subject: [PATCH 066/439] perf/lframe: frame-cost shapes, light-entry matrix, ledger entry Util/bench/frame-cost.rb measures what a method's entry and exit cost on methods that do almost nothing and on String#bytesplice. Util/light-entry-matrix.rb probes __callee__ through aliases into light and scoped methods, by every way in, across threads and an alias call that raises before its method is entered, TracePoint :call and a million-deep recursion through a light frame. The ledger records the change as landed, not gated, with what the disassembly showed about the light lambda's prologue (not the zeroing of its locals). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/bench/frame-cost.rb | 60 +++++++++++++++++ Util/light-entry-matrix.rb | 129 +++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 55 ++++++++++++++++ 3 files changed, 244 insertions(+) create mode 100644 Util/bench/frame-cost.rb create mode 100644 Util/light-entry-matrix.rb diff --git a/Util/bench/frame-cost.rb b/Util/bench/frame-cost.rb new file mode 100644 index 000000000..ffc006fa5 --- /dev/null +++ b/Util/bench/frame-cost.rb @@ -0,0 +1,60 @@ +# What entering and leaving a method's frame costs, light (MethodDefinition.TransformLightFrame) or with its scope: +# ns per call of a method that does almost nothing, the caller a `while' loop, and of String#bytesplice (a large +# light frame). The light frame's switch is the second arm; -X:NoJIT keeps the method JIT from replacing the bodies: +# +# ruby Util/perf/ab.rb -i Util/bench/frame-cost.rb "light=env IR_CONFIG=Release ./ir.sh -X:NoJIT" \ +# "scoped=env IR_LIGHT_FRAMES=0 IR_CONFIG=Release ./ir.sh -X:NoJIT" +# +# (Util/perf/callgrind/count.sh in place of ./ir.sh where the CPU's counter cannot be opened.) +$stdout.sync = true + +class F + def f0 = nil + def f1(x) = x + def fc(x) = x.itself + def fc3(x) = x.itself.itself.itself + def fy(x) = yield(x) + def fbg = block_given? ? 1 : 0 +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-12s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +f = F.new +N = (ENV['N'] || 1_000_000).to_i +src = "abcdefgh" + +t("f0", N) { |n| i = 0; c = 0; while i < n; f.f0; c += 1; i += 1; end; c } +t("f1", N) { |n| i = 0; c = 0; while i < n; c += f.f1(1); i += 1; end; c } +t("fc", N) { |n| i = 0; c = 0; while i < n; c += f.fc(1); i += 1; end; c } +t("fc3", N) { |n| i = 0; c = 0; while i < n; c += f.fc3(1); i += 1; end; c } +t("fy", N) { |n| i = 0; c = 0; while i < n; c += f.fy(1) { |x| x }; i += 1; end; c } +t("fbg", N) { |n| i = 0; c = 0; while i < n; c += f.fbg; i += 1; end; c } +t("bytesplice", N / 5) { |n| i = 0; c = 0; while i < n; c += src.dup.bytesplice(1, 2, "xy").size; i += 1; end; c } diff --git a/Util/light-entry-matrix.rb b/Util/light-entry-matrix.rb new file mode 100644 index 000000000..02b39e3d2 --- /dev/null +++ b/Util/light-entry-matrix.rb @@ -0,0 +1,129 @@ +# Differential matrix for what a method's entry takes from its caller: the name it was called by through an alias +# (__callee__; RubyOps.MarkAliasCall and TakePendingCallee) and the scope a TracePoint for :call makes at a light +# frame's entry (LightFrame.Enter) - what IR_LIGHT_ENTRY changes. Run it under CRuby and under ./ir.sh in every mode: +# +# ruby Util/light-entry-matrix.rb > mri.txt +# ./ir.sh Util/light-entry-matrix.rb > on.txt +# IR_LIGHT_ENTRY=0 ./ir.sh Util/light-entry-matrix.rb > off.txt +# IR_LIGHT_FRAMES=0 ./ir.sh Util/light-entry-matrix.rb > scoped.txt +# diff mri.txt on.txt && diff mri.txt off.txt && diff mri.txt scoped.txt +# +# A name is pending from the alias call until the next method is entered on that thread: the probes call through +# aliases light methods and scoped ones, by send, Method#call and define_method, from many threads at once, with an +# alias call that raises before its method is entered followed by an ordinary call, an alias call whose argument +# calls another method through an alias, recursion through an alias, and a million-deep recursion through a light frame. + +N = 3000 + +def t(label) + print label.ljust(56), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +class C + # light: no scope needed + def light_name = __callee__ + def light_meth = __method__ + def light_arg(x) = [__callee__, x] + def plain = :plain + # scoped: a block literal that reads a local + def scoped_name + y = 1 + [1].map { |_| y } + __callee__ + end + alias light_alias light_name + alias_method :light_alias2, :light_name + alias light_meth_alias light_meth + alias light_arg_alias light_arg + alias scoped_alias scoped_name + + def two(a, b) = [__callee__, a, b] + alias two_alias two + + def method_missing(name, *a) + name == :ghost ? [:mm, __callee__, a] : super + end + def respond_to_missing?(name, p = false) = name == :ghost || super + alias mm_alias method_missing + + define_method(:dm_name) { __callee__ } + alias dm_alias dm_name +end + +o = C.new + +# ---------------------------------------------------------------- 1. the name by alias, light and scoped +t("light by its name") { o.light_name } +t("light by alias") { o.light_alias } +t("light by alias_method") { o.light_alias2 } +t("__method__ by alias") { o.light_meth_alias } +t("light by alias with an argument") { |i| o.light_arg_alias(i % 2) } +t("scoped by its name") { o.scoped_name } +t("scoped by alias") { o.scoped_alias } +t("alternating alias and name") { |i| i.even? ? o.light_alias : o.light_name } +t("define_method body by alias") { o.dm_alias } + +# ---------------------------------------------------------------- 2. other ways in +t("send to the alias") { o.send(:light_alias) } +t("public_send to the alias") { o.public_send(:light_alias) } +t("Method#call of the alias") { o.method(:light_alias).call } +t("UnboundMethod#bind_call of the alias") { C.instance_method(:light_alias).bind_call(o) } +t("method_missing by alias") { o.mm_alias(:ghost, 1) } + +# ---------------------------------------------------------------- 3. a name that is never taken by its method +t("alias call that raises (arity), then by name") do + r = begin; o.two_alias(1); rescue ArgumentError => e; e.class; end + [r, o.light_name, o.plain, o.light_alias] +end +t("alias call whose argument calls another alias") { o.light_arg_alias(o.light_alias) } +t("alias whose arguments are both alias calls") { o.two_alias(o.light_alias2, o.scoped_alias) } + +# ---------------------------------------------------------------- 4. recursion, threads, tracing +class C + def countdown(n) = n == 0 ? __callee__ : down(n - 1) + alias down countdown +end +t("recursion through an alias") { |i| o.countdown(i % 5) } + +def thread_names(o, k) + bad = 0 + 3000.times do |j| + if (j + k).even? + bad += 1 unless o.light_alias == :light_alias && o.light_name == :light_name + else + bad += 1 unless o.scoped_alias == :scoped_alias && o.plain == :plain + end + end + bad +end +t("four threads calling aliases and names") do |i| + next nil unless i % 500 == 0 + 4.times.map { |k| Thread.new { thread_names(o, k) } }.map(&:value) +end + +def traced_calls(o) + seen = [] + tp = TracePoint.new(:call) { |tp| seen << [tp.method_id, tp.callee_id] if tp.defined_class == C } + tp.enable { o.light_alias; o.light_name; o.light_arg(1) } + seen +end +t("TracePoint :call method_id and callee_id") { traced_calls(o) } +t("after the TracePoint, by alias") { o.light_alias } + +# ---------------------------------------------------------------- 5. deep recursion through a light frame +def deep_light(n) = n == 0 ? 0 : deep_light(n - 1) +def deep_alias_light(n) = n == 0 ? 0 : deep_alias2(n - 1) +alias deep_alias2 deep_alias_light +puts "recursion a million deep: " + (begin; deep_light(1_000_000).to_s; rescue SystemStackError; "SystemStackError"; end) +puts "recursion a million deep by alias: " + (begin; deep_alias_light(1_000_000).to_s; rescue SystemStackError; "SystemStackError"; end) +puts "and after: #{o.light_alias.inspect} #{o.light_name.inspect}" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..9ed889cbb 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1450,6 +1450,61 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lframe (/perf-frame, 2026-11-26) - a cheaper method entry: the alias name and the + traced test** (switch `IR_LIGHT_ENTRY`, on unless `=0`) - instructions only, not gated. + Built on 2f8c31c. What gap 16's profiles left on every light frame, looked at on its own + with `Util/bench/frame-cost.rb` (new: a method that does nothing, one, three calls, a yield, + `block_given?`, and `String#bytesplice`), `-X:NoJIT` so that the generic bodies run. + - **Not the prologue.** perf/lsite2 put the light lambda's +158 down to zeroing its locals; + `DOTNET_JitDisasm` of the light `H#gsub` says otherwise: two 64-byte stores. What the + lambda pays up front is its closure constants (each load a bounds check and a + `CHKCASTCLASS` helper call), the frame record (`PrecompiledFrames.Enter`) and the + entry's helpers. So no `SkipLocalsInit` (the runtime compiles with the BCL's + `LambdaExpression.Compile`, which has no such switch, and the DLR patch set has nothing + to patch) and no DLR patch. + - **The alias name.** A call through an alias leaves the name it was called by in a + thread-static for the method's entry to take (`MarkAliasCall`, `TakePendingCallee`, + `CreateMethodScope`). Every entry tested a flag first, `_aliasCallSeen`, which start-up + sets for good (RubyGems and the prelude call aliases), so every entry of every method, + light or scoped, read the thread-static - a call into the runtime from a DynamicMethod: + `TakePendingCallee` 26 + `TakePendingCalleeSlow` 34 instructions a call in the `fc` + profile. The flag is now a count of the threads that have a name pending: raised by the + alias call when its thread had none, lowered by the entry that takes one, so an entry + reads the thread-static only while some thread has a name pending. A thread that dies + with one pending leaves the count up, which only costs the reads it costs today. + - **The traced test.** A light frame without register locals called + `CreateMethodScopeIfTraced` (nine arguments) on every entry to learn that no TracePoint + listens; the test is now inline, as `EnterWithRegisterLocals` has it. + - Left as they were: `EnterLightMethod` and `LeaveLightMethodFrame` already inline their + fast paths (the slow exit only for a block or a scope), and the frame record is every + compiled frame's, tuned before (#168). + - **Numbers** (instructions a call, `Util/perf/callgrind/count.sh`, N=20,000; switch off -> + on). frame-cost, light frames: `f0` 1,572 -> 1,435 (0.913), `f1` 1,656 -> 1,591 (0.961), + `fc` 2,553 -> 2,314 (0.906), `fc3` 4,280 -> 3,693 (0.863), `fy` 2,412 -> 2,347 (0.973), + `fbg` 1,932 -> 1,795 (0.929), `bytesplice` 27,120 -> 26,907 (0.992); the same with + `IR_LIGHT_FRAMES=0` (the alias count only): 0.945-0.974, `bytesplice` 0.991. Default mode, + regex-shapes: 0.977-0.993, `size` 1.000; core-small: `tap` 0.931, `then` 0.945, `minmax` + 0.969, `inject_sym` 0.973, `inject` 0.975, `sum_blk` 0.980, `zip` 0.985, `max_by` 0.984, + `each`/`each_with_index` 0.991. No shape counts more. No timing run (the counter is the + measure here; the gate owes the clock). + - Checked: `Util/light-entry-matrix.rb` (new: `__callee__` and `__method__` through `alias` + and `alias_method` into light and scoped methods, `define_method`, `send`, `public_send`, + `Method#call`, `bind_call`, method_missing; an alias call that raises ArgumentError before + its method is entered and then ordinary calls; alias calls as arguments of alias calls; + recursion through an alias; four threads calling aliases and names; TracePoint `:call`'s + `method_id`/`callee_id`; a million-deep recursion through a light frame, and through an + alias: SystemStackError, and the process goes on) and light-rest, block-given, + global-light, lexical-light, keyword-light, regex-light, rescue-light, super-light, + parked-scope, caller, light-remember and hot-shapes: the candidate prints what the + baseline prints in all 78 runs (each as built, `IR_LIGHT_ENTRY=0`, `IR_LIGHT_FRAMES=0`, + `IR_LIGHT_REGEX=all`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`), and CRuby's but where the + baseline differs too: caller's library frames, hot-shapes' FrozenError, and + light-entry's `define_method` body called through an alias, whose `__callee__` is the + definition's name on both builds (CRuby: the alias's) - a fault of master, not of this. + IronRuby.Tests: the 11 of AliasTests, `Backtrace_ArityCalleeFrame1` and the ten + `Method_LightFrame*`: PASSED. The census cannot see this (no method changes verdict). + Not run: `IR_CONFIG=R2R` start-up, the suite, a sweep, AWFY (owed to the gate). + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 9a8417f26cd143191e9fe8441293005f9624b88c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:57:39 +0000 Subject: [PATCH 067/439] Unmark a call's keyword hash in place when a rest parameter takes it A call that passes keywords to a method whose rest parameter takes them (`def r(*a)` called `r(i, k: 2)`; send, method_missing, define_method with |*a|, every delegator without ruby2_keywords) cost about 1,400 instructions more than passing the same Hash positionally (gap 38). The rule's RubyOps.NormalizeRestArgument made `new Hash(hash)` - a new table, every entry inserted again through the comparer - only so that the array held a hash no longer marked as keyword arguments. Every hash marked as keyword arguments is made for one call: the call site's MakeKeywordArgumentsHash*, KeywordSplatArgument's copy, the copies SplatRuby2Keywords and RestoreRuby2Keywords make, the C API's; and PassOnKeywordRest hands on one the method stops holding. ClearKeywordArguments already relies on that to unmark the hash in place for any other parameter. With IR_KWREST_IN_PLACE (on unless =0) the rest gets the call's own hash, unmarked; the copy stays for a ruby2_keywords method (its copy carries the other mark), for the runtime's shared frozen empty hash, and for anything not exactly a Hash. The keyword path is out of line (NoInlining), so that the test a call without keywords runs stays as small as it was. Instructions a call (Util/perf/callgrind/count.sh; unchanged build / switch off / on): a keyword call into `def r(*a)` 4,814 / 4,838 / 3,688 (0.76); plain calls, a plain rest call, a prebuilt positional Hash and the keyword methods with a rest 1.000. A Hash literal given positionally read 1.02 in that run, where the new code does not run; alone in its process it is 0.98 (a gen0 collection moved between shapes). Util/kwrest-call-matrix.rb (new) prints CRuby 4.0's output on the unchanged build and on this one by default, with the switch off, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR and -X:NoJITCalls, as do keyword-rest-light and keyword-light; splat-pass, light-rest and jit-calls print CRuby's output and hot-shapes the unchanged build's in those modes. language/keyword_arguments_spec, method_spec and send_spec give the same results on both builds (send: the one known into/to message). Method_KeywordHashIntoRest1 is new; it and 50 named keyword, method, splat, send and super tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 44 ++++++++ Src/Ruby/Runtime/RubyOps.cs | 22 ++++ Util/kwrest-call-matrix.rb | 139 ++++++++++++++++++++++++ 4 files changed, 206 insertions(+) create mode 100644 Util/kwrest-call-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e11c273f5..3ff00990a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1140,6 +1140,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGiven1, Method_LightFrameRest1, Method_LightFrameKeywordRest1, + Method_KeywordHashIntoRest1, Method_LightFrameGlobal1, Method_LightFrameLexical1, Method_ParkedScope1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 1c5e91aeb..9c6f68d58 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7814,6 +7814,50 @@ p pass(1, **h), h, pass(**nil), pass(1, **{}), S.new.m(1, j: 2), S.new.m(1) "); } + /// + /// IR_KWREST_IN_PLACE: a rest parameter that takes a call's keyword hash unmarks the call's own hash instead of + /// storing a copy (RubyOps.NormalizeRestArgument); it stays positional when passed on or kept, the caller's hash + /// is never the one, and a ruby2_keywords method still gets a marked copy (Util/kwrest-call-matrix.rb). + /// + public void Method_KeywordHashIntoRest1() { + TestOutput(@" +require 'ruby4' +def takes_kw(*a, **kw) = [a, kw] +def rest(*a) = a +def pass_on(*a) = takes_kw(*a) +def keep(*a) = a.last +ruby2_keywords def r2k(*a) = takes_kw(*a) +ruby2_keywords def r2k_last(*a) = a.last +h = {k: 1} +p rest(1, k: 2), pass_on(1, k: 2), takes_kw(*rest(k: 3)) +kept = keep(k: 4) +p takes_kw(kept), takes_kw(*[kept]), kept.frozen? +r = keep(**h) +r[:x] = 1 +p r, h, keep(h).equal?(h), pass_on(h) +p r2k(1, k: 2), r2k(1, {k: 2}), Hash.ruby2_keywords_hash?(r2k_last(k: 1)), Hash.ruby2_keywords_hash?(keep(k: 1)) +p 40.times.map { |i| pass_on(i % 2, k: i % 3) }.uniq.size, rest(1, **{}), rest(**nil) +", @" +[1, {k: 2}] +[[1, {k: 2}], {}] +[[{k: 3}], {}] +[[{k: 4}], {}] +[[{k: 4}], {}] +false +{k: 1, x: 1} +{k: 1} +true +[[{k: 1}], {}] +[[1], {k: 2}] +[[1, {k: 2}], {}] +true +false +6 +[1] +[] +"); + } + /// /// A method that reads or writes a global is a light frame too (MethodDefinition.IsLightGlobal): every global but $~ and /// $_ is the runtime's, and the frame reads and writes it through the declaring scope. A name that comes to denote $~ or $_ diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 44b3d1f7f..6644fcb52 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -2748,6 +2748,22 @@ public static object ClearKeywordArguments(object obj) { if (hash == null || !hash.IsKeywordArguments) { return args; } + return NormalizeRestKeywords(args, last, hash, ruby2Keywords); + } + + // Out of line, so that the test above - all that a call without keywords runs - stays as small as it was. + [MethodImpl(MethodImplOptions.NoInlining)] + private static RubyArray/*!*/ NormalizeRestKeywords(RubyArray/*!*/ args, int last, Hash/*!*/ hash, bool ruby2Keywords) { + // The hash is the call's own, as ClearKeywordArguments relies on for any other parameter: every hash marked + // as keyword arguments is made for one call (MakeKeywordArgumentsHash, KeywordSplatArgument's copy, the + // copies of SplatRuby2Keywords and RestoreRuby2Keywords; PassOnKeywordRest hands on one the method stops + // holding). So the mark comes off in place, which is all a copy was for - except on the runtime's shared, + // frozen empty hash, and for a ruby2_keywords method, whose copy carries a mark of its own (gap 38). + if (KwRestInPlaceEnabled && !ruby2Keywords && hash.GetType() == typeof(Hash) && !hash.IsFrozen) { + hash.IsKeywordArguments = false; + hash.IsOmittedKeywords = false; + return args; + } var copy = new Hash(hash); copy.IsRuby2KeywordsHash = ruby2Keywords; @@ -2755,6 +2771,12 @@ public static object ClearKeywordArguments(object obj) { return args; } + /// + /// IR_KWREST_IN_PLACE=0 makes a rest parameter that takes a call's keyword hash store a copy of it again, unmarked, + /// instead of unmarking the call's own (see NormalizeRestArgument). + /// + internal static readonly bool KwRestInPlaceEnabled = Environment.GetEnvironmentVariable("IR_KWREST_IN_PLACE") != "0"; + /// /// A `*args' at a call site. A hash a ruby2_keywords method is passing along goes back to /// being keyword arguments here - that is the whole point of the mark - as a copy, so that diff --git a/Util/kwrest-call-matrix.rb b/Util/kwrest-call-matrix.rb new file mode 100644 index 000000000..413f718df --- /dev/null +++ b/Util/kwrest-call-matrix.rb @@ -0,0 +1,139 @@ +# Differential matrix for a call that passes keywords to a method whose rest parameter takes them +# (`def m(*a)` called `m(k: 1)`): the rule unmarks the keyword hash it puts in the rest +# (RubyOps.NormalizeRestArgument), since in an array it is a positional Hash and passing the array on +# must not make it keywords again - and a ruby2_keywords method marks it the other way. Run it under +# CRuby and under ./ir.sh, and diff: +# +# ruby Util/kwrest-call-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/kwrest-call-matrix.rb > /tmp/on.txt 2>&1 +# IR_KWREST_IN_PLACE=0 ./ir.sh Util/kwrest-call-matrix.rb > /tmp/off.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt +# +# Every probe runs N times and reports each distinct answer once, so the rule, the interpreted body +# and the compiled one all meet the case: the hash in the rest passed on (positionally, splatted, +# double-splatted), changed, frozen, kept and passed again; ruby2_keywords; `**{}', `**nil', a Hash +# given positionally to `**kw', `**nil' methods; send, public_send, method_missing, super (zsuper and +# explicit), define_method, Method#call, to_proc, Enumerator replay, and the caller's own Hash. + +N = 3000 + +def t(label) + print label.ljust(52), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def err + yield +rescue Exception => e + "#{e.class}: #{e.message[0, 80]}" +end + +def takes_kw(*a, **kw) = [a, kw] +def takes_k(*a, k: 0) = [a, k] +def no_kw(*a) = a +def no_kw2(x, *a) = [x, a] + +# ---------------------------------------------------------------- 1. what the rest holds and passes on + +def rest(*a) = a +def rest_pass_splat(*a) = takes_kw(*a) +def rest_pass_last(*a) = takes_kw(a.last) +def rest_pass_dsplat(*a) = takes_kw(**a.last) +def rest_mutate(*a); a.last[:added] = 1; a; end +def rest_frozen?(*a) = a.last.frozen? +def rest_identity(*a) = a.last + +t('rest gets a Hash') { |i| rest(1, k: i % 2) } +t('passed on splatted: positional') { rest_pass_splat(1, k: 2) } +t('passed on as an argument: positional') { rest_pass_last(k: 2) } +t('passed on double-splatted: keywords') { rest_pass_dsplat(k: 2) } +t('passed on to k:') { err { takes_k(*rest(k: 2)) } } +t('mutated in the method') { rest_mutate(k: 2) } +t('a fresh hash each call') { |i| h = rest_identity(k: 1); h[:n] = i; rest_identity(k: 1) } +t('not frozen') { rest_frozen?(k: 1) } +t('no keywords') { rest(1, 2) } +t('**{}') { rest(1, **{}) } +t('**nil') { rest(1, **nil) } +t('positional Hash') { rest(1, {k: 2}) } +t('string keys') { rest("s" => 1) } +t('several keywords') { rest(a: 1, b: 2, c: 3, d: 4) } +t('leading mandatory and the hash') { |i| err { no_kw2(*([1][0, i % 2]), k: 2) } } +t('hash only, to a mandatory') { no_kw2(k: 2) } + +# ---------------------------------------------------------------- 2. the caller's hash + +h = {k: 1} +t('**h: the callee does not alias it') { r = rest_mutate(**h); [r, h] } +h2 = {k: 1}.freeze +t('**frozen') { [rest_frozen?(**h2), rest_mutate(**h2), h2] } +t('positional h: the same object') { |i| rest_identity(h).equal?(h) } +t('positional h stays positional after') { [rest_pass_splat(h), h] } +kept = [] +def keep(*a, into:) = into << a +t('a kept hash passed again') do |i| + kept.clear + r = rest(k: i % 2) + kept << r.last + [takes_kw(*r), takes_kw(*kept), kept.last.frozen?] +end + +# ---------------------------------------------------------------- 3. ruby2_keywords + +ruby2_keywords def r2k(*a) = takes_kw(*a) +ruby2_keywords def r2k_last(*a) = a.last +ruby2_keywords def r2k_mutate(*a); a.last[:x] = 1; takes_kw(*a); end +t('ruby2_keywords passes keywords on') { r2k(1, k: 2) } +t('ruby2_keywords, positional Hash') { r2k(1, {k: 2}) } +t('ruby2_keywords, flagged') { Hash.ruby2_keywords_hash?(r2k_last(k: 1)) } +t('ruby2_keywords, positional not flagged') { Hash.ruby2_keywords_hash?(r2k_last({k: 1})) } +t('ruby2_keywords, mutated then passed') { r2k_mutate(k: 1) } +t('ruby2_keywords later') do |i| + Object.send(:ruby2_keywords, :rest_pass_splat) if i == 1500 + rest_pass_splat(1, k: 2) +end +t('ruby2_keywords hash into a plain rest') { |i| rest(*[1, r2k_last(k: i % 2)]) } + +# ---------------------------------------------------------------- 4. other ways in + +class MM + def method_missing(name, *args) = [name, args] + def respond_to_missing?(*) = true +end +class Base; def m(*a) = [:base, a]; def mk(*a, **kw) = [:base, a, kw]; def m2(*a) = [:base2, a]; end +class Sub < Base + def m(*a) = [:sub, super] + def mk(*a, **kw) = [:sub, super] + def m2(*a) = [:sub2, super(*a)] +end +class DM; define_method(:dm) { |*a| a }; end +t('send') { send(:rest, 1, k: 2) } +t('public_send') { 1.public_send(:then) { rest(k: 2) } } +t('__send__ to a kw method') { __send__(:takes_kw, 1, k: 2) } +t('method_missing') { MM.new.foo(1, k: 2) } +t('zsuper into a rest') { Sub.new.m(1, k: 2) } +t('zsuper with **kw') { Sub.new.mk(1, k: 2) } +t('explicit super(*a)') { Sub.new.m2(1, k: 2) } +t('define_method |*a|') { DM.new.dm(1, k: 2) } +t('Method#call') { method(:rest).call(1, k: 2) } +t('to_proc') { [[1]].map(&method(:rest)) } +def rest_each(*a) = a.each { |x| yield x } +t('Enumerator replay') { to_enum(:rest_each, 1, k: 2).to_a } +t('block |*a| yielded keywords') { [1].map { |x| ->(*a) { a }.call(x, k: 2) } } + +# ---------------------------------------------------------------- 5. **nil and keyword-taking methods given a Hash + +def nokw(*a, **nil) = a +t('**nil, keywords') { err { nokw(1, k: 2) } } +t('**nil, positional Hash') { nokw(1, {k: 2}) } +t('**kw, positional Hash') { takes_kw(1, {k: 2}) } +t('**kw, keywords') { takes_kw(1, k: 2) } +t('k:, positional Hash') { takes_k({k: 2}) } From 78aab00f48656e26e9b89287d7fea6b858f85574 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:57:39 +0000 Subject: [PATCH 068/439] Ledger: perf/kwrest landed (instructions only, not gated); gap 38's first cost Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 55 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f3a5212b1..e48d99fd5 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1497,15 +1497,62 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (`def v_unused(*a, k: 1) = 3` 4,798, `kr_rest` 5,325), so it is the call into the rest, not that method's prologue. Without a rest parameter the keyword call costs what the literal does (`def v_two(a, b)`, JIT off: positional 1,745, `{k: 2}` 2,404, `k: 2` - 2,435). Suspects, not yet bisected: `RubyOps.NormalizeRestArgument` (a non-keyword rest - method keeps a copy of the hash) and what the rule for a site with a keyword hash does - for a rest callee (`ArgsBuilder` with a keyword signature takes no `GetRestTakesListFrom` - path, `RubyMethodInfo.GetDispatcher` none for a rest). Separately, the keyword prologue of + 2,435). The first suspect owned it: `RubyOps.NormalizeRestArgument` copied the hash to + unmark it; perf/kwrest (Landed) unmarks the call's own, 4,814 -> 3,688, about 270 left over + the literal. A keyword method with a rest never normalized, so `v_unused` and `kr_rest` + did not move: theirs is the prologue's cost below. Separately, the keyword prologue of `def kw(a, k: 1) = a + k` costs about 1,300-1,500 with the JIT off (4,017 against `v_two_kw` 2,435) in either lowering. Not the splat lowering: see Rejected, perf/lexical3. ## Landed +- **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that + takes a call's keyword hash unmarks the call's own instead of storing a copy + (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, not gated. A keyword + call into a method whose rest takes the hash (`def r(*a)` called `r(i, k: 2)`; send, + method_missing, `define_method { |*a| }`, every delegator without `ruby2_keywords`) paid + about 1,400 instructions over passing the same Hash positionally. Bisected: the rule's + `RubyOps.NormalizeRestArgument` made `new Hash(hash)` - a table and every entry inserted + again through the comparer - only to have an unmarked hash in the array. Every hash marked as + keyword arguments is made for one call (`MakeKeywordArgumentsHash*`, `KeywordSplatArgument`'s + copy, the copies of `SplatRuby2Keywords` and `RestoreRuby2Keywords`, the C API's; + `PassOnKeywordRest` hands on one the method stops holding), which `ClearKeywordArguments` + already relies on to unmark the hash in place for any other parameter. So the mark (and + `IsOmittedKeywords`) comes off in place; the copy stays for a `ruby2_keywords` method, whose + copy carries the other mark, for the runtime's shared frozen empty hash, and for anything not + exactly a Hash. The keyword path went out of line (`NormalizeRestKeywords`, NoInlining) so + that the test a call without keywords runs stays as small as before. The rule's other + suspect - `ArgsBuilder` for a rest callee with a keyword signature - owns nothing here: a + keyword method with a rest never normalizes, and `v_unused` / `kr_rest` did not move; what + they pay over a plain rest is the keyword prologue, gap 38's second cost, a separate + experiment. + - Instructions a call (`Util/perf/callgrind/count.sh`, `ab.rb -i -r 1 -n 20000`, unchanged + build / switch off / on, shapes in `prelude-cost.rb`): `v_hash_into_rest` 4,814 / 4,838 / + 3,688 (0.76); controls `x_const`, `v_two_pos`, `kr_plain_rest`, `v_prebuilt_hash` and the + keyword-rest methods `kr_rest`, `v_unused`, `kr_lines` 1.000. `v_hash_literal_arg` read + 1.02 in that run, where the new code does not run; alone in a process it is 3,469 -> 3,400 + (0.98): which shape's section a gen0 collection lands in moved with the allocations the + earlier shapes no longer make. (The first build had the keyword path inline and the same + 1.02 there; the off arm of the split build equals the unchanged build on every shape.) + - `Util/kwrest-call-matrix.rb` (new: the hash in the rest passed on splatted, as an argument, + double-splatted, to `k:`; mutated; a fresh one each call; frozen; `**{}`, `**nil`, a + positional Hash, String keys; the caller's hash through `**h`, `**frozen` and positionally, + a kept hash passed again; `ruby2_keywords` - passing on, positional, the flag, mutated, + applied later, its hash into a plain rest; send, public_send, `__send__`, method_missing, + zsuper into a rest and with `**kw`, `super(*a)`, `define_method |*a|`, Method#call, + to_proc, Enumerator replay, a lambda's rest; `**nil`, `**kw` and `k:` given a Hash) prints + CRuby 4.0's output on the unchanged build, and on the change by default, with + `IR_KWREST_IN_PLACE=0`, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR` and `-X:NoJITCalls`; so do + keyword-rest-light and keyword-light. splat-pass, light-rest and jit-calls print CRuby's + output in the default mode, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and `IR_LIGHT_FRAMES=0`; + hot-shapes prints the unchanged build's in all five (it differs from CRuby already in one + String probe, FrozenError against Encoding::CompatibilityError). ruby/spec + `language/keyword_arguments_spec.rb` 23 examples 0 failures, `method_spec.rb` 168 / 0, + `send_spec.rb` 78 with 1 error - the known `into`/`to` conversion message - the same on + both builds. IronRuby.Tests `Method_KeywordHashIntoRest1` (new; passes with the switch + off too) and 50 named keyword, method, splat, send and super tests pass. Not timed; no + R2R run. + - **Gate of 2026-11-26 for round thirty-seven** (perf/lglobal, perf/lexical, perf/deadconst, perf/strsearch, perf/extiter, perf/struct, perf/dmethjit; the rejected perf/lsite's tools and perf/jitbody's census fix): the branch `claude/happy-gauss-95wm2j` at 2f8c31c against master From 973314a203c785d917466727e7e519b3d892a976 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:01:39 +0000 Subject: [PATCH 069/439] Ledger: gap 26's start-up split at 79a2c30 (perf/startup2, no change) Sizes perf/first-bind's remaining levers on the current tree: lever 3 (typed rules duplicating untyped ones) is gone, and lever 2 (CallInstruction per signature) is under 2% of `gem list'. It also takes a fresh split of `-e 1' and `gem list': from Main, the main-thread JIT, and the files `gem list' requires. Four things measured on the way: the release image (self-contained composite) JITs a third of what the R2R host does and starts 15-26% faster; DOTNET_TieredPGO=0 saves 10-20 ms of JIT for 19% of steady state; RubyStackTraceBuilder.FindCopyingClasses costs 9 ms once per process; and no lever reaches 3% of `gem list'. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Util/perf/LEDGER.md | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index afdc7c668..6eeb68780 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1318,6 +1318,56 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has rules per tool, not hot ones, so levers 2 (`CallInstruction` per signature) and 3 (typed sites rebinding what untyped ones warmed) should be measured before anything is built. Their perf/first-bind sizes (9-16, 6-16 ms) are as stale as lever 1's 18-21 ms was. + 2026-11-26, perf/startup2 (no change; this split is gap 26's new starting point). Base + 79a2c30. Asked: are perf/first-bind's levers 2 and 3 still there, and where do `-e 1` and + `gem list` spend their time now. Measured with a throwaway build: `IR_BIND_TRACE` marking typed + and untyped rules, a stopwatch on uncached `CallInstruction.Create`, timestamps with main-thread + `JitInfo` at the start-up milestones, and `strace -f --seccomp-bpf -e openat` for file times. + The machine was ~40% slower than in perf/startup: `-e 1` took 505 ms here, 360 ms there, on + both trees. Only relative numbers carry over. + - Lever 3 (typed sites rebinding what untyped ones warmed): gone. `gem list` binds 48 typed + rules and one of them duplicates an untyped one (0.7 ms). Lever 2 (`CallInstruction` per + signature): 174 / 263 uncached creates in `-e 1` / `gem list`, 66 / 106 of them through + MakeGenericType and Activator. 11 / 16 ms all in, JIT included: under 2% of `gem list`. + `CallInstruction.ReadyToRun.cs` already roots the common shapes. Lever 1: perf/startup above. + - The first rule of a process (`private`, in the prelude) still costs ~12 ms. Typed rules cost + ~1 ms each in `-e 1` (22 rules, 25 ms), against ~0.45 ms for untyped ones. + - Split of `-e 1`, R2R host, ms from `Main` (fastest of three; main-thread JIT ms / methods in + brackets): to `Host.Run` 9; to the RubyContext ctor 23 (8 / 49); LoadBuiltins 40 (9 / 87); + to LoadCorePrelude 13; registering the startup library 4; the core prelude with RubyGems + 248 (69 / 495); to exit 16. The runtime starts ~40 ms before `Main`. `--disable-gems -e 1` + takes 358 ms against 511, so RubyGems is ~150 ms. `gem list`: pre-prelude ~129, prelude + ~380, then the command ~515 ms. Under strace, the command spends ~285 ms requiring what + `list_command` needs (spec_fetcher -> remote_fetcher -> net/http, socket, openssl, zlib, + resolv, securerandom: ~60 files; CRuby requires the same ones), then ~200 ms on the 93 + gemspecs (median 1.3 ms each; the 245 ms perf/startup-library-tools gave them includes the + requires that happen between them). + - JIT on the main thread (`System.Runtime.JitInfo`, normal tiering): the R2R host spends + 120-143 ms on 749 methods in `-e 1` and 180-190 ms on 1,015 in `gem list`. Of `-e 1`'s, 334 + are plain Tier0 compiles of BCL generics the framework image lacks (Dictionary and + ConcurrentDictionary over ValueTuple and over IronRuby types, SearchValues...). 75 are + "Instrumented Tier0" compiles of large methods (93 KB of code). 31 are IronRuby methods + compiled FullOpts, and 20 are rules or lambdas. + - The release image (`Util/package-release.sh`: self-contained, composite, startup profile) + JITs 216 methods in 59 ms for `-e 1` and 376 in 106 ms for `gem list`. Wall, best of 6 + alternating, R2R host / release: `-e 1` 505 / 375, `gem --version` 593 / 457, `gem list` + 992 / 847, `require "irb"` 1041 / 831, irb 1+1 1112 / 935 ms. So the host the gate's + start-up rule times (perf-gate step 4) pays ~130-210 ms more than what is released, most + of it in JIT. A change that moves JIT shows on the R2R host far more than in a release. + - `DOTNET_TieredPGO=0` takes the instrumented compiles away: main-thread JIT -20 ms in `-e 1` + on both images, -10 to -17 ms in `gem list`. AWFY 8 s geomean 1.188, NBody -26%, Havlak + -30%. Rejected. + - `RubyStackTraceBuilder.FindCopyingClasses` (the table of modules that classes copy in) + reflects over every type in IronRuby.Libraries the first time a backtrace holds a copied + module's method: 9 ms once per process in `gem list`, `require "irb"` and irb (not in + `-e 1` or `gem --version`). It also loads AngleSharp.dll and System.Net.Sockets.dll. In + `gem list` it is optparse's rescued exception in `Gem::Command#handles?`. The source + generator sees every `[Includes(Copy = true)]` and could emit the table. That is ~1%, a + small fix for whoever is nearby. + No lever reaches 3% of `gem list` on its own. What is left is spread over the prelude and + RubyGems' own Ruby (binds ~100 ms inclusive in `-e 1`, the running of precompiled code), the + files `gem list` requires, and the JIT, which the release image already halves. A next attempt + should measure on the release image, or say why the R2R host stands in for it. 27. **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a From e68ac1353e30c5e22f233722164040daaa6ec3b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:04:40 +0000 Subject: [PATCH 070/439] JIT: inline a call on a local the profile has no sample of, under class checks som.rb's Dictionary#at (Havlak) declined at `e.match(hash, key)`: `e` comes from a call (`get_bucket(hash)`), so the inliner had no sample of it and no class to check, as it has for a parameter. JitCompiler.UnsampledCallees takes the classes (constants of Object) that define the method themselves with an inlinable typed body now: one, or two with the same types, each under a check of its exact class through the inliner's two-class path; anything else deopts, and the entry's method version check covers a redefinition. An attribute read of the same local takes the variable's name from the class the call was inlined for and reads through ReadSelfAttr, which checks the class it meets. IR_JIT_UNSAMPLED=0 turns it off. Havlak: Dictionary#at specialized, declines 3 -> 2, no deopts; census -c 0 differ; the other benchmarks make the same JIT and OSR decisions. Util/bench/havlak-shapes.rb, callgrind new/base: a lookup 0.54-0.61, the control 1.000; Havlak time 0.965 over three alternating pairs. Util/unsampled-matrix.rb (new, 16 cases: another class half way, two classes, redefinitions, singletons, method_missing, subclasses, private, protected, removed, frozen) prints CRuby's output on the unchanged build and on this one in every mode; jit, jit-calls, jit-const, ivar, deadconst, hot-shapes and inline matrices unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5NtGd2eCVJ7fCeWbG --- Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs | 86 +++++++++-- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 20 ++- Src/Ruby/Runtime/Jit/JitRuntime.cs | 7 + Util/bench/havlak-shapes.rb | 81 ++++++++++ Util/perf/LEDGER.md | 50 +++++++ Util/unsampled-matrix.rb | 156 ++++++++++++++++++++ 6 files changed, 387 insertions(+), 13 deletions(-) create mode 100644 Util/bench/havlak-shapes.rb create mode 100644 Util/unsampled-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs index af0aa8432..abfe8f547 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs @@ -40,6 +40,9 @@ internal sealed partial class JitCompiler { private RubyClass _inlinedSelfClass; // A call was inlined on a parameter under a check of the one class the profile saw it hold (JitCode). private bool _inlinedOnArgumentClass; + // The locals nothing samples that a call was inlined on (UnsampledCallees), with the first class it was inlined + // for: what names the instance variable of an attribute read of the local (EmitMethodAttrRead). + private System.Collections.Generic.Dictionary _unsampledClasses; /// /// The call inlined (see the file header), or null if it is not a call of an inlinable @@ -56,23 +59,35 @@ private MSA.Expression TryInlineCall(MethodCall/*!*/ node, out JT type) { if (node.Target == null && node.IsVariableCall) { return null; } if (selfReceiver && node.MethodName == _ast.Name) { return null; } + RubyClass cls; + JitCode code; + RubyClass otherCls = null; + JitCode otherCode = null; + var receiverLocal = node.Target as LocalVariable; object sample; - if (!TrySample(node.Target, out sample) || sample == null) { return null; } - RubyClass cls = JitRuntime.ClassOf(_context, sample); - if (cls.Context != _context) { return null; } - if (selfReceiver && _inlinedSelfClass != null && _inlinedSelfClass != cls) { return null; } - // an explicit receiver is one the guard below checks the class of: an object of a Ruby class - if (!selfReceiver && !(sample is RubyObject)) { return null; } + if (!TrySample(node.Target, out sample) || sample == null) { + // A local of the method nothing samples (`e = get_bucket(hash)' before a `while e' that calls + // `e.match(hash, key)', Dictionary#at): the classes whose own method of the name has an inlinable + // typed body now, at most two, each under a check of its class; anything else deopts. + if (selfReceiver || receiverLocal == null || receiverLocal.DefinitionLexicalDepth != _scopeDepth || + !JitRuntime.InlineUnsampled || !UnsampledCallees(node.MethodName, args.Length, out cls, out code, out otherCls, out otherCode)) { + return null; + } + (_unsampledClasses ?? (_unsampledClasses = new System.Collections.Generic.Dictionary()))[receiverLocal.Name] = cls; + } else { + cls = JitRuntime.ClassOf(_context, sample); + if (cls.Context != _context) { return null; } + if (selfReceiver && _inlinedSelfClass != null && _inlinedSelfClass != cls) { return null; } + // an explicit receiver is one the guard below checks the class of: an object of a Ruby class + if (!selfReceiver && !(sample is RubyObject)) { return null; } - var code = InlinableCallee(cls, node.MethodName, selfReceiver, args.Length); - if (code == null) { return null; } + code = InlinableCallee(cls, node.MethodName, selfReceiver, args.Length); + if (code == null) { return null; } + } // A parameter the profile saw hold objects of two classes (`key' in find_node, a CallSign or a Vector2D): // both callees, each under a check of its own class, if their bodies take and give the same types. - RubyClass otherCls = null; - JitCode otherCode = null; - var receiverLocal = node.Target as LocalVariable; - if (receiverLocal != null && _hints.ArgClasses != null && receiverLocal.DefinitionLexicalDepth == _scopeDepth) { + if (otherCls == null && receiverLocal != null && _hints.ArgClasses != null && receiverLocal.DefinitionLexicalDepth == _scopeDepth) { int p = Array.IndexOf(_paramNames, receiverLocal.Name); var seen = (p >= 0 && p < _hints.ArgClasses.Length) ? _hints.ArgClasses[p] : null; if (seen != null && seen.Length == 2 && (seen[0] == cls || seen[1] == cls)) { @@ -171,6 +186,53 @@ private JitCode InlinableCallee(RubyClass/*!*/ cls, string/*!*/ name, bool selfR return code; } + /// + /// The callees of a call on a local the profile has no sample of (TryInlineCall): the classes, constants of + /// Object, that define a method of the name themselves whose typed body may be inlined now (InlinableCallee), + /// one or two of them, two only if their bodies take and give the same types. Each is called under a check of + /// its exact class, which deopts on any other (a subclass, a singleton class, a class whose method of the name + /// has no such body, one with method_missing), and the entry's method version check covers a redefinition. + /// A candidate still being profiled makes the caller wait for it only when no other is ready. + /// + private bool UnsampledCallees(string/*!*/ name, int argc, out RubyClass cls, out JitCode code, out RubyClass otherCls, out JitCode otherCode) { + cls = otherCls = null; + code = otherCode = null; + var classes = new System.Collections.Generic.List(); + using (_context.ClassHierarchyLocker()) { + _context.ObjectClass.EnumerateConstants((module, constantName, value) => { + var c = value as RubyClass; + RubyMemberInfo method; + if (c != null && c.Context == _context && !c.IsSingletonClass && !classes.Contains(c) && c.TryGetDefinedMethod(name, out method) && + method is RubyMethodInfo) { + classes.Add(c); + } + return false; + }); + } + bool notReady = _hints.CalleeNotReady; + int ready = 0; + foreach (var c in classes) { + var body = InlinableCallee(c, name, false, argc); + if (body == null) { continue; } + if (++ready > 2) { break; } + if (cls == null) { + cls = c; + code = body; + } else { + otherCls = c; + otherCode = body; + } + } + if (ready == 0) { return false; } + // a candidate that is not specialized yet is waited for only when there is none to inline + _hints.CalleeNotReady = notReady; + if (ready > 2) { return false; } + if (otherCode != null && (otherCode.ReturnType != code.ReturnType || !SameTypes(otherCode.ParameterTypes, code.ParameterTypes))) { + return false; + } + return true; + } + private static bool SameTypes(JT[]/*!*/ a, JT[]/*!*/ b) { if (a.Length != b.Length) { return false; } for (int i = 0; i < a.Length; i++) { diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 814ca49e6..578fcc626 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1751,7 +1751,25 @@ private MSA.Expression EmitMethodAttrRead(MethodCall/*!*/ node, out JT type) { if (node.Block != null || !_refinements.IsEmpty) { return null; } var target = node.Target; object sample; - if (!TrySample(target, out sample) || !(sample is RubyObject)) { return null; } + if (!TrySample(target, out sample) || !(sample is RubyObject)) { + // A local nothing samples that a call was inlined on for a class (UnsampledCallees): the reader of that + // class names the variable; ReadSelfAttr binds to whatever class the object has and deopts unless the + // name is the same variable's reader there. Its value is an object. + var local = target as LocalVariable; + RubyClass inlinedFor; + if (local == null || local.DefinitionLexicalDepth != _scopeDepth || _unsampledClasses == null || + !_unsampledClasses.TryGetValue(local.Name, out inlinedFor)) { + return null; + } + string name = JitRuntime.SelfAttrSite.ReaderVariable(inlinedFor, node.MethodName, true); + if (name == null || CanFallBack(target)) { return null; } + JT lt; + var localReceiver = Coerce(Emit(target, out lt), lt, JT.Obj); + _canDeopt = true; + type = JT.Obj; + return Ast.Call(JitRuntime.M("ReadSelfAttr"), Ast.Constant(_context), localReceiver, + Ast.Constant(new JitRuntime.SelfAttrSite(node.MethodName, name, true))); + } bool explicitReceiver = target != null && !(target is SelfReference); string variableName = JitRuntime.SelfAttrSite.ReaderVariable(JitRuntime.ClassOf(_context, sample), node.MethodName, explicitReceiver); if (variableName == null) { diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 10a50afb6..e09b0f742 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -46,6 +46,13 @@ public static partial class JitRuntime { /// internal static readonly bool DeadConstants = Environment.GetEnvironmentVariable("IR_JIT_DEADCONST") != "0"; + /// + /// IR_JIT_UNSAMPLED (on unless =0): a call on a local of the method that the profile has no sample of is + /// inlined for the classes that define an inlinable method of the name, under checks of their classes + /// (JitCompiler.UnsampledCallees). + /// + internal static readonly bool InlineUnsampled = Environment.GetEnvironmentVariable("IR_JIT_UNSAMPLED") != "0"; + /// /// Statistics, printed by -X:JITStats. /// diff --git a/Util/bench/havlak-shapes.rb b/Util/bench/havlak-shapes.rb new file mode 100644 index 000000000..f68e15d5c --- /dev/null +++ b/Util/bench/havlak-shapes.rb @@ -0,0 +1,81 @@ +# Shapes for Havlak (Util/perf/LEDGER.md gap 25): som.rb's Dictionary#at, whose `e.match(hash, key)' is a call on a +# local nothing samples (JitCompiler.UnsampledCallees, IR_JIT_UNSAMPLED), in the format Util/perf/ab.rb reads +# (` ns `; N from the environment; INSTR=1 or Util/perf/callgrind/count.sh for instructions). +# +# ruby Util/perf/ab.rb -i -r 1 -c none -n 20000 Util/bench/havlak-shapes.rb \ +# "base=Util/perf/callgrind/count.sh ." "new=Util/perf/callgrind/count.sh ../wt-NAME" +$stdout.sync = true + +class HsEntry + attr_reader :hash, :key, :value + attr_accessor :next + def initialize(hash, key, value, nxt); @hash = hash; @key = key; @value = value; @next = nxt; end + def match(hash, key); @hash == hash && @key == key; end +end + +class HsKey + def initialize(n); @n = n; end + def custom_hash; @n; end +end + +# som.rb's Dictionary, an identity one, as Havlak uses it +class HsDict + def initialize(size = 16); @buckets = Array.new(size); @size = 0; end + def hash(key) + return 0 unless key + hash = key.custom_hash + hash ^ hash >> 16 + end + def get_bucket_idx(hash); (@buckets.size - 1) & hash; end + def get_bucket(hash); @buckets[get_bucket_idx(hash)]; end + def at(key) + hash = hash(key) + e = get_bucket(hash) + while e + return e.value if e.match(hash, key) + e = e.next + end + nil + end + def at_put(key, value) + hash = hash(key) + i = get_bucket_idx(hash) + @buckets[i] = HsEntry.new(hash, key, value, @buckets[i]) + end + # control: a method of the same shape whose loop calls nothing on the local + def chain_length(key) + e = get_bucket(hash(key)) + n = 0 + while e + n += 1 + e = e.next + end + n + end +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end + +d = HsDict.new +keys = (0...24).map { |i| HsKey.new(i) } +keys.each_with_index { |k, i| d.at_put(k, i) } +first = keys[23] # the head of its chain +deep = keys[7] # behind one other in its chain +missing = HsKey.new(100) +N = (ENV["N"] || 1_000_000).to_i +t("at_first", N) { |n| i = 0; s = 0; while i < n; s += d.at(first); i += 1; end; s } +t("at_chain", N) { |n| i = 0; s = 0; while i < n; s += d.at(deep); i += 1; end; s } +t("at_miss", N) { |n| i = 0; s = 0; while i < n; s += 1 if d.at(missing).nil?; i += 1; end; s } +t("chain_len", N) { |n| i = 0; s = 0; while i < n; s += d.chain_length(deep); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index aeeca63a9..d84b1928c 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1197,6 +1197,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 475 ns a level at depth 10 and 552 at depth 1000. Narrow things to try: let `Dictionary#at` compile (type a call on a local assigned in the loop); the per-call cost of `(a..b).each { |i| yield ... }` (gap 14); `loop` through gap 22. + `Dictionary#at` compiles since perf/havlak (see Landed): Havlak's declines are + `Vector#remove_first` (a deopt after an effect) and `split_bucket` (an attribute write + on a receiver nothing samples - the same kind of local, `current` walking a chain; the + write would need what the read now has, a name from a class the call was inlined for or + from the classes that define the writer). 26. **Start-up: `gem` and `irb` answer in 0.7 to 2.2 s, CRuby in 0.1 to 0.2** (the one thing that has to stay fast while the tiers stay on by default, and it is not fast). 2026-11-18, a7060a27, the ReadyToRun host (`IR_CONFIG=R2R`, what `ir.sh` runs when @@ -1504,6 +1509,51 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/havlak (/perf-step, 2026-11-26, on 819a368) - a call on a local the profile has no sample of + is inlined for the classes that define the method, under checks of their class (gap 25)** - not + gated. som.rb's `Dictionary#at` (Havlak's `IdentityDictionary`) declined at `call: match/2`: `e` + comes from `get_bucket(hash)`, a call, so `TrySample` has nothing for it, and the inliner, which + checks a class at a call on a parameter, had no class to check. Now `UnsampledCallees` takes the + classes, constants of Object, that define a method of the name themselves whose typed body is + inlinable now (`InlinableCallee`): one, or two with the same parameter and return types, each under + a check of its exact class (the inliner's two-class path, `IsOfClass`/`GuardClass`), and anything + else deopts - a subclass, a singleton class, a class whose method has no such body, + method_missing; the entry's method version check covers a redefinition, and a private or + protected method is not inlinable for an explicit receiver. A candidate still being profiled is + waited for only when no other is ready. An attribute read of the same local (`e.value`, `e.next`) + takes the variable's name from the class the call was inlined for and reads through + `ReadSelfAttr`, which binds to the class it meets and deopts where the name is not that variable's + reader; its value is an object. Switch: `IR_JIT_UNSAMPLED=0`. + Census (Src/StdLib + AWFY): 0 methods changed (it has no specialized callees to inline). Havlak + traced (`harness.rb Havlak 1 3`): `Dictionary/at` specialized (`hash`, `get_bucket` and + `IdEntry#match` inlined), declines after the pre-screen 3 -> 2, deopts 0, invalidations 0; + `census -c` 88 agree, 0 differ. The other thirteen benchmarks traced (3 x 1): the same JIT and OSR + decisions on both builds; all fourteen verify (CD at `3 100`: its inner count 1 is not a valid + one, on either build or CRuby). `Util/bench/havlak-shapes.rb` (new; som.rb's Dictionary with + `Entry#match`), instructions a call (`callgrind/count.sh`, new/base): `at_first` 0.611, `at_chain` + (behind one entry) 0.571, `at_miss` 0.538, the control `chain_len` (the same loop calling nothing on + the local) 1.000; time on a quiet machine, ns: 142 -> 88, 172 -> 104, 180 -> 100, control 147 -> + 148. Havlak, `harness.rb Havlak 6 1`, three pairs in separate processes, the order turned in the + second: base 23.55, 22.37, 22.19 s, new 22.34, 21.62, 21.74 (0.965, new faster in each pair, inside + the benchmark's swing). + Checked: `Util/unsampled-matrix.rb` (new, 16 cases, one per process: entries of another class with + a match of its own half way, two classes both inlinable, `match` and `value` redefined, a singleton + `match` and `value`, method_missing, a subclass, a subclass with `private :value`, `value` and + `match` made private, `match` protected and removed, the entries frozen, the buckets emptied) prints + CRuby's output on the unchanged build and on the new one with the JIT on, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` and `IR_JIT_UNSAMPLED=0`; every case specializes `at` with `match` inlined. jit, + jit-calls, jit-const, ivar, deadconst matrices print CRuby's in all four modes; hot-shapes and + inline the baseline's (their known rows: a FrozenError where IronRuby raises + Encoding::CompatibilityError, and `tree_int_key`, on every build with the JIT on or off). + IronRuby.Tests Jit*, Loop*, Inline* (21) pass. + For the gate: the candidates are found by enumerating Object's constants under the hierarchy lock + at each compile of such a call (compile time only); a class not a constant of Object (nested in a + module) is not a candidate, so such a call stays uninlined. Look at the attribute read's name being + taken from the first candidate while the receiver may be of the second (ReadSelfAttr re-binds, and + deopts if that class's reader is another variable), and at "a fast path that decides from a resolved + method": the candidate's method is resolved on the candidate class with the lookup's visibility + (`InlinableCallee`), and a subclass never takes the inlined body (exact class check). + - **Gate of 2026-11-26 for round thirty-seven** (perf/lglobal, perf/lexical, perf/deadconst, perf/strsearch, perf/extiter, perf/struct, perf/dmethjit; the rejected perf/lsite's tools and perf/jitbody's census fix): the branch `claude/happy-gauss-95wm2j` at 2f8c31c against master diff --git a/Util/unsampled-matrix.rb b/Util/unsampled-matrix.rb new file mode 100644 index 000000000..bfce19305 --- /dev/null +++ b/Util/unsampled-matrix.rb @@ -0,0 +1,156 @@ +# Differential cases for a call on a local the method JIT has no sample of (JitCompiler.UnsampledCallees, +# IR_JIT_UNSAMPLED): `e = get_bucket(hash)' before a `while e' that calls `e.match(hash, key)' and reads `e.value' and +# `e.next', as som.rb's Dictionary#at (AWFY Havlak). The call is inlined for the classes that define an inlinable +# `match' themselves, each under a check of its exact class, and the reads go through a site that checks the class. +# Each case warms `at' past the JIT's threshold, then does what must change the answer half way through a long run of +# lookups, and prints what the lookups answered. +# +# One case per process, since one case's event would change what the next compiles: +# for c in $(ruby Util/unsampled-matrix.rb list); do echo "== $c"; ruby Util/unsampled-matrix.rb $c 2>&1; done > cruby.txt +# (the same with IR_CONFIG=Release ./ir.sh, with -X:NoJIT -X:NoOSR, with -X:NoJITCalls and with IR_JIT_UNSAMPLED=0) +# IR_JIT_VERBOSE=1 shows `inlined Ent#match into at' and `specialized Dict/at': the path is reached. + +CASES = %w[plain class_change two_classes redefine redefine_value singleton singleton_value method_missing + subclass subclass_private private_value private_match protected_match remove_match frozen nil_entry] + +if ARGV[0] == 'list' + puts CASES + exit +end +c = ARGV[0] + +class Ent + attr_reader :hash, :key, :value, :next + attr_writer :next + def initialize(hash, key, value, nxt); @hash = hash; @key = key; @value = value; @next = nxt; end + def match(hash, key); @hash == hash && @key == key; end +end + +class IdEnt + attr_reader :hash, :key, :value, :next + def initialize(hash, key, value, nxt); @hash = hash; @key = key; @value = value; @next = nxt; end + def match(hash, key); @hash == hash && (@key.equal? key); end +end + +class Dict + def initialize; @buckets = Array.new(16); end + def hash_of(key); key * 7; end + def get_bucket(hash); @buckets[hash & 15]; end + def put(key, value, cls = Ent) + h = hash_of(key) + @buckets[h & 15] = cls.new(h, key, value, @buckets[h & 15]) + end + + def at(key) + hash = hash_of(key) + e = get_bucket(hash) + while e + return e.value if e.match(hash, key) + e = e.next + end + nil + end +end + +def answer + yield +rescue NoMethodError, NameError => e + [e.class, e.message[/\A[^(]*/].strip] +end + +d = Dict.new +40.times { |k| d.put(k, k * 10) } +N = 4000 + +# warm, then the event at the half, then on; the sum of what was found, the count of nils, the first odd answer +def run(d, n, event) + sum = 0 + nils = 0 + odd = nil + n.times do |i| + event.call if i == n / 2 + v = answer { d.at(i % 48) } + if v.is_a?(Integer) + sum += v + elsif v.nil? + nils += 1 + else + odd ||= v + end + end + [sum, nils, odd] +end + +3000.times { |i| d.at(i % 40) } + +case c +when 'plain' + p run(d, N, -> {}) +when 'class_change' + # entries of another class with a match of its own (any key with the same hash) + p run(d, N, -> { + k2 = Class.new do + attr_reader :value, :next + def initialize(hash, key, value, nxt); @hash = hash; @value = value; @next = nxt; end + def match(hash, key); @hash == hash; end + end + 40.times { |k| d.put(k, -k, k2) } + }) +when 'two_classes' + idd = Dict.new + 40.times { |k| idd.put(k, k, IdEnt) } + 3000.times { |i| idd.at(i % 40) } + p run(d, N, -> { 20.times { |k| d.put(k, k + 1, IdEnt) } }) +when 'redefine' + p run(d, N, -> { Ent.class_eval { def match(hash, key); false; end } }) +when 'redefine_value' + p run(d, N, -> { Ent.class_eval { def value; -1; end } }) +when 'singleton' + # the entry found for key 5 answers false from now on: the lookup goes on down its chain + p run(d, N, -> { + e = d.get_bucket(d.hash_of(5)) + e = e.next until e.key == 5 + def e.match(hash, key); false; end + }) +when 'singleton_value' + p run(d, N, -> { + e = d.get_bucket(d.hash_of(7)) + e = e.next until e.key == 7 + def e.value; 7000; end + }) +when 'method_missing' + ghost = Class.new do + def initialize(nxt); @nxt = nxt; end + def method_missing(name, *args) + case name + when :match then args[0] == 3 * 7 && args[1] == 3 + when :value then :ghost + when :next then @nxt + else super + end + end + def respond_to_missing?(name, priv = false); [:match, :value, :next].include?(name) || super; end + end + p run(d, N, -> { + h = d.hash_of(3) + d.instance_variable_get(:@buckets)[h & 15] = ghost.new(d.get_bucket(h)) + }) +when 'subclass' + sub = Class.new(Ent) + p run(d, N, -> { 40.times { |k| d.put(k, k * 100, sub) } }) +when 'subclass_private' + Object.const_set(:SubPrivate, Class.new(Ent) { private :value }) + p run(d, N, -> { d.put(9, 1, SubPrivate) }) +when 'private_value' + p run(d, N, -> { Ent.send(:private, :value) }) +when 'private_match' + p run(d, N, -> { Ent.send(:private, :match) }) +when 'protected_match' + p run(d, N, -> { Ent.send(:protected, :match) }) +when 'remove_match' + p run(d, N, -> { Ent.send(:remove_method, :match) }) +when 'frozen' + p run(d, N, -> { d.instance_variable_get(:@buckets).each { |e| while e; e.freeze; e = e.next; end } }) +when 'nil_entry' + p run(d, N, -> { d.instance_variable_get(:@buckets).map! { nil } }) +end From b887bc110928f1e3f394a68193f554fea9749bec Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:09:03 +0000 Subject: [PATCH 071/439] Ledger: blank lines between the entries the round 4 merges joined Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 0987a7e0c..d8502a3fe 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1669,6 +1669,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both builds. IronRuby.Tests `Method_KeywordHashIntoRest1` (new; passes with the switch off too) and 50 named keyword, method, splat, send and super tests pass. Not timed; no R2R run. + - **perf/havlak (/perf-step, 2026-11-26, on 819a368) - a call on a local the profile has no sample of is inlined for the classes that define the method, under checks of their class (gap 25)** - not gated. som.rb's `Dictionary#at` (Havlak's `IdentityDictionary`) declined at `call: match/2`: `e` @@ -1713,6 +1714,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has deopts if that class's reader is another variable), and at "a fast path that decides from a resolved method": the candidate's method is resolved on the candidate class with the lookup's visibility (`InlinableCallee`), and a subclass never takes the inlined body (exact class check). + - **perf/jitsettle (2026-11-26) - a retired entry's cool-down costs nothing per call** - not gated. A method whose typed body keeps failing (`x + 1` called with an Integer and a Float in turn) ran 10-16% slower than with the JIT off, as a `def` and as a define_method method. What it does per call, @@ -1834,6 +1836,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has twenty alternating runs each: best 865 -> 881, median 937 -> 942 (the 779 was one fast run). This container refuses perf_event_open, so there is no `ab.rb -i` here; perf/lsite's `Util/perf/callgrind/count.sh` counts instructions instead. + - **perf/extiter3 (2026-11-26) - `with_index`, `each_with_index` and `with_object` enumerators take `next` on a cursor over their source's (gap 35)** - not gated. Base 1efd7e6 (the merged branch at 2f8c31c with perf/extiter2). The prelude's Enumerator#with_index (and so @@ -1988,6 +1991,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has deopt (`code.Deopts`), which could decline a caller with an effect before the call - none of the fourteen benchmarks has one. Look at the order in `ConstantsStillHold` and at `Folded` being set before `LoopGuard.Set` publishes the epoch. + - **perf/jitscreen2 (2026-11-26) - a multiple assignment of a list in a body the method JIT compiles** (`a, b = b, a`, `@a, @b = x, y`) - census only, not gated. With the census counting honestly, the lines after the Hash literal were String literals (101) and multiple @@ -2092,6 +2096,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has trace says "stores not held back ... a call of JitRuntime.NewSymbolHash1"), as round strlit's literal makers were; not tried here. For the gate: no IronRuby.Tests or spec run; the decline above. + - **perf/strdup (2026-11-26, not gated) - `String#dup` is String's own, MRI's rb_str_dup_m** (gap 24's dup note). Kept as a CRuby-compatibility fix, not as a speed-up. `Util/dup-matrix.rb` (new: String, Object and Array dup and clone - content, encodings, broken bytes, frozen and chilled, ivars, @@ -2110,6 +2115,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has in every mode and with the switch off: PASS (dup-matrix `same`, `baseline -2` switched off). spec/core/string and kernel dup/clone: 4,010 examples, the one known try_convert wording error on both builds. + - **perf/strsearch2 (2026-11-26) - `#start_with?` with one String prefix takes no scope; an ASCII prefix is compared in place (gap 21, round two)** - not gated. Commit dc1d136 on `claude/perf-strsearch`, based on the merged branch 2f8c31c. `start_with?` had one overload, @@ -2139,6 +2145,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has build in both modes; spec/core/string (3,963 examples) and spec/library/stringscanner (240): the same on both builds, 0 failures, one error on both (`String.try_convert ... raises TypeError if it's not a kind of String`, run as a directory). + - **perf/lframe (/perf-frame, 2026-11-26) - a cheaper method entry: the alias name and the traced test** (switch `IR_LIGHT_ENTRY`, on unless `=0`) - instructions only, not gated. Built on 2f8c31c. What gap 16's profiles left on every light frame, looked at on its own From 55c55470b82276ae63b05e9552ea6c5ecac41fdd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:10:02 +0000 Subject: [PATCH 072/439] String#dup: one look for instance data, and the copy constructor String#dup of a bare string was 2 times CRuby's time (100-113 against 55 ns). Callgrind with the CLR's perf map split a call: the bare test 553 instructions, since HasInstanceVariables and GetImmediateClassOf each looked the string up in the ConditionalWeakTable of instance data through the general TryGetInstanceData; and the copy 706, CreateInstance making a string with an empty char-array content that Replace then replaced (SetEncoding and the content's clone on top). The library call itself was not the cost. RubyContext.HasNoInstanceVariablesOrSingleton looks once, straight in the table for a String; the copy is MutableString.Clone(), the copy constructor, which leaves what CreateInstance().Replace(self) left. Instructions per call with the shape's driver: 3,290 -> 2,418; S.dup in a method's loop 97-117 -> 76-78 ns. Controls (String#clone, Hash#dup and #clone, Object and Array #dup) level; String#clone looked slower only when run after S.dup in the same process, and is level alone and in reverse order. Util/dup-matrix.rb prints CRuby's output; it and hash-dup, string-search, hot-shapes, jit and jit-calls pass in every mode and with IR_FAST_DUP=0. spec/core/string and the Kernel dup/clone specs: as on the base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Libraries/Builtins/MutableStringOps.cs | 5 ++-- Src/Ruby/Runtime/RubyContext.cs | 20 +++++++++++++++ Util/perf/LEDGER.md | 29 ++++++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index ffc238cd8..47257b2aa 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -712,7 +712,8 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { MutableString/*!*/ self) { if (FastDup && self.GetType() == typeof(MutableString) && IsBare(allocateStorage.Context, self)) { - return self.CreateInstance().Replace(self); + // the copy constructor: what CreateInstance().Replace(self) leaves, without the empty content made for it + return self.Clone(); } return KernelOps.Duplicate(initializeCopyStorage, allocateStorage, self); } @@ -722,7 +723,7 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { // BARE_STRING_P: no instance variables and the class String itself (the caller has seen the CLR type is MutableString, // so the class is String unless the string has a singleton class). private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { - return !context.HasInstanceVariables(self) && !context.GetImmediateClassOf(self).IsSingletonClass; + return context.HasNoInstanceVariablesOrSingleton(self); } [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index f3dd60b58..e43d119ce 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3012,6 +3012,26 @@ public bool HasInstanceVariables(object obj) { return data != null && data.HasInstanceVariables; } + /// + /// Neither instance variables nor a singleton class, with one look in the table of instance data (each of + /// HasInstanceVariables and GetImmediateClassOf takes one, some 200 instructions for an object of a CLR type): + /// MRI's BARE_STRING_P for String#dup (MutableStringOps.Duplicate), less the class, which the caller tests. + /// + public bool HasNoInstanceVariablesOrSingleton(object obj) { + RubyInstanceData data; + if (obj != null && obj.GetType() == typeof(MutableString)) { + // a String (not a Ruby subclass, which is an IRubyObject) keeps its data in the table (TryGetClrTypeInstanceData) + _referenceTypeInstanceData.TryGetValue(obj, out data); + } else { + data = TryGetInstanceData(obj); + } + if (data == null) { + return true; + } + var immediate = data.ImmediateClass; + return !data.HasInstanceVariables && (immediate == null || !immediate.IsSingletonClass); + } + /// /// The object's instance variables. The runtime keeps a slot or two of its own in the /// same table - the finalizer ObjectSpace.define_finalizer attaches is one - spelled with diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 77c2cd90f..1a9cd3ebb 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1157,6 +1157,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has own (`Util/bench/dup-shapes.rb`). perf/strdup (see Landed): String#dup without the hooks, as CRuby's, is no faster on the clock (100-113 against 104-109 ns, CRuby 55); the gap is elsewhere in the call or the copy. + perf/dupcost (see Landed): it was the instance-data lookups and a wasted content; `S.dup` + 77 ns against 114 (CRuby 56). 25. **Havlak: 1.4 times CRuby, 25 times TruffleRuby, and no single place** (round sixteen's breakdown; its author's numbers, taken beside two other experiments at load 2-14, so ratios). CRuby runs a copy with som.rb's `Set` renamed to `SomSet`: 2.85-3.3 @@ -1490,6 +1492,33 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/dupcost (2026-11-26, not gated) - `String#dup` of a bare string: one look for instance + data, and the copy constructor** (gap 24's dup note). Where the time went, by callgrind with the + CLR's perf map over one `str_dup` section of `dup-shapes.rb` (instructions per call, the + shape's driver included; the scratch profiler kept the section's files and named JIT frames + from /tmp/perf-PID.map): the bare test 553 - `HasInstanceVariables` and `GetImmediateClassOf` + each looked the string up in the ConditionalWeakTable of instance data, through the general + `TryGetInstanceData` - and the copy 706: `CreateInstance` 375 (a new string with an empty + char-array content, zeroed) and `Replace` 331 (`SetEncoding` 120, the content's clone 106), + which threw that content away. Not the library call. Now `RubyContext.HasNoInstanceVariablesOrSingleton` + looks once, straight in the table for a String, and the copy is `MutableString.Clone()` (the + copy constructor: content clone, encoding, character flags - what CreateInstance().Replace left). + Tried first and dropped: a per-runtime flag "no String has instance data yet" - always set, since + the Loader puts `@gem_prelude_index` on the load path's strings at start-up. + Instructions (`callgrind/count.sh`, N=20000): `str_dup` 3,290 -> 2,418 (over `plain`'s 1,266: + 2,024 -> 1,152); `str_clone`, `hash_dup`, `clone`, `obj_dup`, `oi_dup`, `arr_dup` level (one + `obj_dup` outlier on the base, 6,130, as seen before). Time in a method's loop, three alternating + runs: `S.dup` 97-113 -> 76-78 ns (CRuby 56); in reverse order 114-117 -> 77. `S.clone` read + 139-192 -> 193-220 when run after `S.dup` in one process, but alone (129-132 on both, three runs + each) and in reverse order (207-208 against 198-209) it is level: an artefact of the order of + shapes in one process - which may also be what sank perf/struct2's Hash#dup (see Rejected). + Checks: dup, hash-dup, string-search, hot-shapes, jit and jit-calls matrices in every mode and + with `IR_FAST_DUP=0`: PASS. spec/core/string with the Kernel dup/clone specs: 4,010 examples, + the one known try_convert wording error on both builds. Not measured, since the call was not + the cost: other no-argument library calls (`s.size`, `a.first`, `h.empty?`). Left: the copy + allocates two objects (the string and its content) where CRuby shares the buffer; a + copy-on-write content would take the next ~350. + - **perf/strdup (2026-11-26, not gated) - `String#dup` is String's own, MRI's rb_str_dup_m** (gap 24's dup note). Kept as a CRuby-compatibility fix, not as a speed-up. `Util/dup-matrix.rb` (new: String, Object and Array dup and clone - content, encodings, broken bytes, frozen and chilled, ivars, From 550159ba170ccdd17d7e10a2376b23f0d6c67d74 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:11:29 +0000 Subject: [PATCH 073/439] __callee__ in a define_method body called through an alias is the alias's name `define_method(:dm) { __callee__ }; alias_method :am, :dm` made `am` answer :dm; CRuby answers :am, as it does for a def (found by perf/lframe, Util/light-entry-matrix.rb's "define_method body by alias" on claude/perf-lsite). A def learns its callee from the call site (RubyOps.MarkAliasCall); a define_method body is a block, whose method scope is the call's BlockParam and the method's lambda. A call by another name than the method's own now runs a copy of that lambda that carries the name (Proc.CalleeName, in the Proc's rare state, so no Proc or BlockParam grows; RubyLambdaMethodInfo.GetLambdaFor, one copy per name, made at the first rule or first-call dispatcher), and __callee__ reads it there. The copy is the same method to super and __method__. The rule (RubyLambdaMethodInfo.BuildCallNoFlow, which then skips the method JIT's stub) and the first-call dispatchers (LambdaMethodCall, now told the name by RubyCallAction) both use it; a call by the method's own name is as before. Checked: DefineMethodCallee1 (new; CRuby 4.0's output) as built, -X:NoJIT -X:NoOSR, -X:NoJITCalls and IR_LIGHT_FRAMES=0; light-entry-matrix (from claude/perf-lsite): CRuby's output, one row differing before; Kernel#__callee__/__method__, Module#define_method and alias_method, spec/language alias and super, spec/core/method and unboundmethod: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/Runtime/MethodTests.cs | 32 +++++++++++++++++++ Src/Ruby/Builtins/Proc.cs | 11 +++++++ Src/Ruby/Runtime/Calls/LibraryDispatcher.cs | 2 +- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 7 ++-- .../Runtime/Calls/RubyLambdaMethodInfo.cs | 32 +++++++++++++++++-- Src/Ruby/Runtime/Calls/RubyMethodCallPlan.cs | 10 +++--- Src/Ruby/Runtime/RubyScope.cs | 3 +- 7 files changed, 87 insertions(+), 10 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 04bb2df05..661c5c011 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1856,6 +1856,38 @@ p t.map(&:value).uniq ""ArgumentError: no keywords accepted"" ""ArgumentError: wrong number of arguments (given 2, expected 1; required keyword: k)"" [4002000] +"); + } + + /// + /// __callee__ in a method define_method made answers the name it was called by, an alias's, as in CRuby, on the first + /// calls and on a compiled rule alike, through Method#call and send too; __method__ answers the definition's name. + /// + public void DefineMethodCallee1() { + TestOutput(@" +class C + define_method(:dm) { __callee__ } + alias_method :am, :dm + alias am2 dm + define_method(:dm2) { |x = 1| [__method__, __callee__] } + alias_method :am3, :dm2 + def m = __callee__ + alias_method :ma, :m +end +c = C.new +p c.dm, c.am, c.am2, c.dm2, c.am3, c.ma, c.method(:am).call, c.send(:am), c.public_send(:am3, 2) +r = nil; 3000.times { r = [c.am, c.am3] }; p r +", @" +:dm +:am +:am2 +[:dm2, :dm2] +[:dm2, :am3] +:ma +:am +:am +[:dm2, :am3] +[:am, [:dm2, :am3]] "); } } diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index 1de8185a1..613d4d8b8 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -83,6 +83,7 @@ private sealed class RareState { public RefinementActivation RefinementOverride; public string SymbolName; public bool IsIsolated; + public string CalleeName; } private RareState _rare; @@ -250,6 +251,16 @@ public string SymbolName { internal set { if (value != null || _rare != null) { Rare.SymbolName = value; } } } + /// + /// The name a method define_method made is called by when it is not the method's own (an alias), for + /// __callee__; null otherwise. Only on the copy of the method's lambda that such a call runs + /// (RubyLambdaMethodInfo.GetLambdaFor). + /// + internal string CalleeName { + get { var r = _rare; return (r != null) ? r.CalleeName : null; } + set { if (value != null || _rare != null) { Rare.CalleeName = value; } } + } + /// /// The proc is isolated from the scopes around it, as CRuby isolates the block of Ractor.new /// and a shareable proc: code it evals cannot reach their locals, and it has no binding. diff --git a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs index e1d4d252e..9332c50a9 100644 --- a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs @@ -1275,7 +1275,7 @@ internal static object TryCreateRubyCall(RubyCallAction/*!*/ binder, Type/*!*/ d if (method is RubyMethodInfo) { plan = RubyMethodCallPlan.TryCreate((RubyMethodInfo)method, argumentCount, name ?? ((RubyMethodInfo)method).DefinitionName); } else if (method is RubyLambdaMethodInfo && splatCount < 0) { - plan = LambdaMethodCall.TryCreate((RubyLambdaMethodInfo)method, argumentCount); + plan = LambdaMethodCall.TryCreate((RubyLambdaMethodInfo)method, argumentCount, name); } else { plan = null; } diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 0b013d133..e1e75e80a 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -291,7 +291,9 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // from sites that run a few times at start-up, each of which built and interpreted a rule (~150 us) before. if (light) { if (method.Info is RubyLambdaMethodInfo) { - return LibraryDispatcher.TryCreateRubyCall(this, delegateType, Signature, method.Info, targetClass, target, clrTest, version, args); + // (by the name it is called by: an alias's is __callee__'s) + return LibraryDispatcher.TryCreateRubyCall(this, delegateType, Signature, method.Info, targetClass, target, clrTest, version, args, + name: _methodName); } var lightLibraryMethod = method.Info as RubyLibraryMethodInfo; return (lightLibraryMethod != null && !TracePoint.CCallTracing && !DispatchIntrinsics.IsSend(lightLibraryMethod)) ? @@ -307,7 +309,8 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // and so do those of a method define_method made of a block if (method.Info is RubyLambdaMethodInfo) { - return LibraryDispatcher.TryCreateRubyCall(this, delegateType, Signature, method.Info, targetClass, target, clrTest, version, args); + return LibraryDispatcher.TryCreateRubyCall(this, delegateType, Signature, method.Info, targetClass, target, clrTest, version, args, + name: _methodName); } // The first calls of a library method from a site go without a rule. A rule built for a call is used for one diff --git a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs index 40976773c..2f90b6de3 100644 --- a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs @@ -15,6 +15,7 @@ using System; +using System.Collections.Generic; using System.Threading; using System.Reflection; using Microsoft.Scripting.Utils; @@ -110,6 +111,29 @@ public Proc/*!*/ Lambda { get { return _lambda; } } + // The copies of the lambda for calls by other names (GetLambdaFor), made at the first rule built for each. + private Dictionary _aliasLambdas; + + /// + /// The lambda a call of this method by runs: a copy of whose + /// CalleeName is the name, so that __callee__ answers it; the same method, for super and __method__. + /// + internal Proc/*!*/ GetLambdaFor(string/*!*/ name) { + var lambdas = Volatile.Read(ref _aliasLambdas); + if (lambdas == null) { + lambdas = Interlocked.CompareExchange(ref _aliasLambdas, new Dictionary(), null) ?? _aliasLambdas; + } + lock (lambdas) { + Proc result; + if (!lambdas.TryGetValue(name, out result)) { + result = _lambda.ToLambda(this); + result.CalleeName = name; + lambdas[name] = result; + } + return result; + } + } + // -X:JIT: what the method JIT made of the block (JitBlockMethod), at the first call a rule was built for; // NoJit when it took nothing. Each copy (alias, visibility) has its own, as each def copy shares its body's. private sealed class JitHolder { @@ -204,9 +228,13 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA } } + // A call by another name than the method's own (an alias) runs a copy of the lambda that knows that name, for + // __callee__ (CRuby: the alias's name, as for a def), and not through the method JIT's stub. + bool aliasCall = name != _definitionName; + // -X:JIT: plain arguments, as many as the block takes, go to the stub of the method JIT, whose generic body is // the call below (JitBlockMethod). An omitted optional argument is passed as the default sentinel, as to a def's. - if (!args.Signature.HasBlock && !args.Signature.HasSplattedArgument && !args.Signature.HasRhsArgument) { + if (!aliasCall && !args.Signature.HasBlock && !args.Signature.HasSplattedArgument && !args.Signature.HasRhsArgument) { var jit = GetJit(); if (jit.Trampoline != null) { var simple = args.GetSimpleArgumentExpressions(); @@ -243,7 +271,7 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA Proc.BuildCall( metaBuilder, - AstUtils.Constant(_lambda), // proc object + AstUtils.Constant(aliasCall ? GetLambdaFor(name) : _lambda), // proc object args.TargetExpression, // self args ); diff --git a/Src/Ruby/Runtime/Calls/RubyMethodCallPlan.cs b/Src/Ruby/Runtime/Calls/RubyMethodCallPlan.cs index 46f695ba0..8c1b7a6cc 100644 --- a/Src/Ruby/Runtime/Calls/RubyMethodCallPlan.cs +++ b/Src/Ruby/Runtime/Calls/RubyMethodCallPlan.cs @@ -176,12 +176,14 @@ internal sealed class LambdaMethodCall : RubyMemberCall { private readonly RubyLambdaMethodInfo/*!*/ _method; private readonly Proc/*!*/ _lambda; - private LambdaMethodCall(RubyLambdaMethodInfo/*!*/ method) { + // name: what the call calls the method by; another name than its own (an alias) runs the copy of the lambda that + // answers it to __callee__ (RubyLambdaMethodInfo.GetLambdaFor), as the rule does + private LambdaMethodCall(RubyLambdaMethodInfo/*!*/ method, string name) { _method = method; - _lambda = method.Lambda; + _lambda = (name != null && name != method.DefinitionName) ? method.GetLambdaFor(name) : method.Lambda; } - internal static LambdaMethodCall TryCreate(RubyLambdaMethodInfo/*!*/ method, int count) { + internal static LambdaMethodCall TryCreate(RubyLambdaMethodInfo/*!*/ method, int count, string name) { var dispatcher = method.Lambda.Dispatcher; int arity = dispatcher.Arity; int mandatory = arity >= 0 ? arity : -arity - 1; @@ -190,7 +192,7 @@ internal static LambdaMethodCall TryCreate(RubyLambdaMethodInfo/*!*/ method, int if (maximum == Int32.MaxValue && signature != null && signature.MaxArgumentCount >= 0) { maximum = signature.MaxArgumentCount; } - return (count >= mandatory && count <= maximum) ? new LambdaMethodCall(method) : null; + return (count >= mandatory && count <= maximum) ? new LambdaMethodCall(method, name) : null; } internal override object Invoke(object self, Proc block, object[]/*!*/ args) { diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 9c64af656..093dc93d8 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -938,7 +938,8 @@ public string GetCurrentMethodName(bool callee) { return callee ? methodScope.CalleeName : methodScope.DefinitionName; case ScopeKind.BlockMethod: - return ((RubyBlockScope)scope).BlockFlowControl.Proc.Method.DefinitionName; + var proc = ((RubyBlockScope)scope).BlockFlowControl.Proc; + return (callee ? proc.CalleeName : null) ?? proc.Method.DefinitionName; case ScopeKind.TopLevel: return null; From 0a38a2188f5cff8e62f66c8e45507ba44716957f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:11:30 +0000 Subject: [PATCH 074/439] Ledger: perf/crubydiff closes __callee__ through an alias of a define_method body Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index ac821f2ac..fcae54e3e 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1495,6 +1495,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has either. interpolation-matrix: new row, baseline before. TracePoint_EndlessDefLine1. - `"#{sym}"` under a refinement of Symbol#to_s is the name while Symbol#to_s is the built-in (gap 33, vm_objtostring). interpolation-matrix: new row. Refinements17. + - `__callee__` in a define_method body called through an alias answered the definition's name + (found by perf/lframe): an alias call runs a copy of the method's lambda that carries the name + (Proc.CalleeName in its rare state; RubyLambdaMethodInfo.GetLambdaFor), in the rule and the + first-call dispatcher; such a call skips the method JIT's stub. light-entry-matrix (claude/perf-lsite) + "define_method body by alias": CRuby's output. DefineMethodCallee1. Not fixed: `42.compare_to(o)` in inline-matrix's `tree_int_key` answers Int32#CompareTo's "Object must be of type Int32." where CRuby has no such method. That is IronRuby's interop (RubyModule.IsUnmangledBuiltin: snake_case CLR names on Integer and Float, `5.to_string("X")`, From 2e03e49a89cfbbb77f15ee0e1db25d60b60549ca Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:14:37 +0000 Subject: [PATCH 075/439] Method JIT: take `s + "lit"` and `s << "lit"` Behind the String literal line of the census (101 methods for which it is the only refusal) are call arguments, gap 1's wall, and operands of String operators; `+` and `<<` are the largest two. EmitStringLiteralConcat calls the library's own code, MutableString.Concat and Append, for a receiver that is exactly a String whose encoding the literal's can join, while String#+ and #<< are the public library methods, no String has a singleton method of the name and no refinement is active. Anything else deopts before anything is done (nil, other classes, a subclass, UTF-16LE, and for << a frozen or chilled receiver, whose FrozenError or warning the generic body gives). << is an effect. The screen refuses either as an operand of a binary operator: the first build let URI::Generic#userinfo through to be declined. census.rb -d against 3affb6e: 16 up (8 to compiles, 8 to maybe), none down. Traces of app-shapes and five AWFY benchmarks the baseline's. Instructions a call 0.80-0.92 on the shapes, the control 1.000. Util/jit-strop-matrix.rb (new) and the JIT matrices print CRuby's output with the JIT on, off and without JIT calls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 44 +++++++ Src/Ruby/Runtime/Jit/JitCompiler.cs | 11 ++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 26 ++++ Util/bench/jit-strop-shapes.rb | 45 +++++++ Util/jit-strop-matrix.rb | 130 ++++++++++++++++++++ Util/perf/LEDGER.md | 52 ++++++++ 6 files changed, 308 insertions(+) create mode 100644 Util/bench/jit-strop-shapes.rb create mode 100644 Util/jit-strop-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 814ca49e6..e4fad448a 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -666,6 +666,50 @@ internal static bool IsArrayConstruction(MethodCall/*!*/ node) { } /// `v == "lit"' or `v != "lit"', the literal a plain (not interpolated) String literal. + /// `v + "lit"' or `v << "lit"' (EmitStringLiteralConcat): one argument, a String literal. + internal static bool IsStringLiteralConcat(MethodCall/*!*/ node) { + if (node.MethodName != "+" && node.MethodName != "<<") { return false; } + var args = node.Arguments; + return node.Target != null && node.Block == null && args != null && args.Expressions.Length == 1 && + IsPlainStringLiteral(args.Expressions[0]); + } + + /// + /// `v + "lit"', `v << "lit"': the generic code makes a new String for the literal on every evaluation and dispatches on + /// v. For a v that is a String (JitRuntime.StringConcatLiteral, StringAppendLiteral), String#+ and #<< being the + /// library methods - public, no String with a singleton method of that name, no subclass instance (those are another + /// CLR type), no refinement where the code was written - that is the library's own MutableString.Concat or Append of + /// the literal, which neither keeps nor changes. Anything else deopts before anything is done. `+' makes a new String + /// and has no effect; `<<' changes v: an effect, after its own deopt, and not one on self only. + /// + private MSA.Expression/*!*/ EmitStringLiteralConcat(MethodCall/*!*/ node, out JT type) { + string name = node.MethodName; + bool append = name == "<<"; + if (!_refinements.IsEmpty) { throw Bail("String#" + name + " where a refinement is active"); } + if (append && _loop != null) { throw Bail("String#<< in an outlined loop"); } + var stringClass = KindClass(JitRuntime.KindString); + if (!IsPlainLibraryMethod(stringClass, name) || !IsPublic(stringClass, name)) { + throw Bail("String#" + name + " is not the built-in one"); + } + Type observed = ObservedType(node.Target); + if (observed != null && observed != MixedTypes && observed != typeof(MutableString)) { + throw Bail(name + " of a String literal on a " + ((observed == typeof(void)) ? "nil" : observed.Name)); + } + JT vt; + var v = Emit(node.Target, out vt); + if (vt != JT.Obj) { throw Bail(name + " of a String literal on a " + vt); } + + var literal = ((StringLiteral)node.Arguments.Expressions[0]).GetMutableString(); + literal.Freeze(); + _canDeopt = true; + if (append) { + _pure = false; + _effectNotOnSelf = true; + } + type = JT.Obj; + return Ast.Call(JitRuntime.M(append ? "StringAppendLiteral" : "StringConcatLiteral"), v, Ast.Constant(literal)); + } + internal static bool IsStringLiteralComparison(MethodCall/*!*/ node) { if (node.MethodName != "==" && node.MethodName != "!=") { return false; } var args = node.Arguments; diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index a7be5faa3..91f53a08f 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -2478,6 +2478,11 @@ internal static bool IsRaiseCall(MethodCall/*!*/ node) { return EmitStringLiteralComparison(node, out type); } + // `s + "lit"', `s << "lit"' (JitCompiler.Objects.cs). + if (argc == 1 && IsStringLiteralConcat(node)) { + return EmitStringLiteralConcat(node, out type); + } + // `v.nil?' on any object (JitRuntime.IsNil). if (node.Target != null && argc == 0 && node.MethodName == "nil?") { JT tt; @@ -3592,6 +3597,8 @@ private bool WalkOperand(RExpr/*!*/ node) { // a Hash query is a Bool, never a number (an element read is speculated to be one) var call = node as MethodCall; if (call != null && call.Target != null && IsBoolQueryName(call.MethodName)) { return No(node); } + // nor is `s + "lit"' or `s << "lit"' (JitCompiler.EmitStringLiteralConcat): a String (`@user + ':' + @password') + if (call != null && JitCompiler.IsStringLiteralConcat(call)) { return No(node); } // nor is anything holding a String literal (`suffixes - [".rb"]'): such an operator only deopts _inOperand++; try { @@ -4017,6 +4024,10 @@ private bool WalkCall(MethodCall/*!*/ node) { } else if (argc == 1 && JitCompiler.IsStringLiteralComparison(node)) { // `s == "lit"' or `"lit" == s' (JitCompiler.EmitStringLiteralComparison): s is any object return Walk(JitCompiler.IsReversedStringLiteralComparison(node) ? args.Expressions[0] : node.Target); + } else if (argc == 1 && JitCompiler.IsStringLiteralConcat(node)) { + // `s + "lit"', `s << "lit"' (JitCompiler.EmitStringLiteralConcat): s is any object; a String, so never + // inside an operand of a binary operator, which only deopts on one (as a String literal there) + return (_inOperand == 0) ? Walk(node.Target) : No(node); } else if (argc != 1 || !IsBinaryOperator(node.MethodName)) { // Emit only reaches EmitBinary for a one-argument call on a target, and only // EmitBinary's own operators survive there whatever the operand types are. diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index c6080504b..bb84ca3ed 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -444,6 +444,32 @@ public static bool CollectionEqualsNil(RubyContext/*!*/ context, object value, I /// the generic code would have made. Any other receiver deopts, and the generic code makes /// the call with a fresh literal. /// + /// + /// `s + "lit"' (JitCompiler.EmitStringLiteralConcat): String#+ of the library, MutableString.Concat, for an s that is a + /// String (not a subclass) whose encoding the literal's can join. Anything else deopts, before anything is done: the + /// generic body dispatches, converts or raises the Encoding::CompatibilityError from its own frame. + /// + public static object StringConcatLiteral(object value, MutableString/*!*/ literal) { + if (value != null && value.GetType() == typeof(MutableString)) { + var str = (MutableString)value; + if (str.GetCompatibleEncoding(literal) != null) { return str.Concat(literal); } + } + throw Deopt(); + } + + /// + /// `s << "lit"' (JitCompiler.EmitStringLiteralConcat): String#<< of the library, MutableString.Append, for an s + /// that is a String (not a subclass), neither frozen (FrozenError) nor chilled (the deprecation warning, and the + /// String no longer chilled), whose encoding the literal's can join. Anything else deopts before it changes s. + /// + public static object StringAppendLiteral(object value, MutableString/*!*/ literal) { + if (value != null && value.GetType() == typeof(MutableString)) { + var str = (MutableString)value; + if (!str.IsFrozen && !str.IsChilled && str.GetCompatibleEncoding(literal) != null) { return str.Append(literal); } + } + throw Deopt(); + } + public static bool StringEqualsLiteral(object value, MutableString/*!*/ literal, string ascii) { if (value != null && value.GetType() == typeof(MutableString)) { var str = (MutableString)value; diff --git a/Util/bench/jit-strop-shapes.rb b/Util/bench/jit-strop-shapes.rb new file mode 100644 index 000000000..3abf0ed83 --- /dev/null +++ b/Util/bench/jit-strop-shapes.rb @@ -0,0 +1,45 @@ +# What `s + "lit"' and `s << "lit"' cost in a method the method JIT can take (JitCompiler.EmitStringLiteralConcat): +# ns per call of the method, the caller a `while' loop. plus `s + ":"', plus2 `s + ":" + "x"', append `buf << "x"' (the +# buffer cleared every 1000 calls), userinfo `@user + ":"' on an instance variable; eq `s == "lit"' is the control (the +# typed body took it already). +# +# ruby Util/perf/ab.rb -r 6 Util/bench/jit-strop-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# ruby Util/perf/ab.rb -i -r 1 -n 20000 Util/bench/jit-strop-shapes.rb \ +# "base=env IR_CONFIG=Release Util/perf/callgrind/count.sh ../ironruby" "new=env IR_CONFIG=Release Util/perf/callgrind/count.sh ." +# +# Every line prints the sum of its results next to its time; it must be CRuby's. +$stdout.sync = true + +class SoShapes + def initialize; @user = +"user"; end + def plus(s) = s + ":" + def plus2(s) = s + ":" + "x" + def append(s) = s << "x" + def userinfo = @user + ":" + def eq(s) = s == "lit" +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +s = SoShapes.new +N = (ENV["N"] || 1_000_000).to_i +str = +"abc" +t("plus", N) { |n| i = 0; r = 0; while i < n; r += s.plus(str).size; i += 1; end; r } +t("plus2", N) { |n| i = 0; r = 0; while i < n; r += s.plus2(str).size; i += 1; end; r } +t("append", N) { |n| i = 0; r = 0; b = +""; while i < n; r += s.append(b).size; b.clear if i % 1000 == 999; i += 1; end; r } +t("userinfo", N) { |n| i = 0; r = 0; while i < n; r += s.userinfo.size; i += 1; end; r } +t("eq", N) { |n| i = 0; r = 0; while i < n; r += 1 if s.eq(str); i += 1; end; r } diff --git a/Util/jit-strop-matrix.rb b/Util/jit-strop-matrix.rb new file mode 100644 index 000000000..bcdfc67b1 --- /dev/null +++ b/Util/jit-strop-matrix.rb @@ -0,0 +1,130 @@ +# Differential matrix for `s + "lit"` and `s << "lit"` in methods the method JIT compiles (-X:JIT, +# JitCompiler.EmitStringLiteralConcat). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-strop-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-strop-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-strop-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Every method is called past the JIT's thresholds with a String, then probed. Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-strop-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep so_ +# The traps: a receiver that is not a plain String (nil, an Integer, a subclass with its own method, one +# with a singleton method), String#+ or #<< redefined or refined, encodings that do not mix (UTF-16LE), +# `<<` on a frozen or a chilled String (FrozenError; the deprecation warning), `<<` is an effect, so a +# deopt after it must not append again, and `+` makes a new, unfrozen String of the receiver's encoding. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts e.class + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class SO + def initialize; @n = 0; @buf = +""; end + attr_reader :n, :buf + + def so_plus(s) = s + ":" + def so_plus2(s, t) = s + "/" + t + def so_plus_lit = "a" + "b" + def so_append(s) = s << "!" + def so_buf(x) + @buf << "x" + x + 1 + end + def so_count(s) + @n += 1 + s << "-" + end + def so_then_ivar(s) + s << "+" + @n = s.size + end + def so_chilled + s = "abc" + s << "d" + end +end + +class SubS < String + def +(o) = "sub+" +end +class SubPlain < String; end + +o = SO.new +t("plus") { warm { |i| o.so_plus("k#{i % 3}") } } +t("plus: new, unfrozen") { s = +"k"; r = o.so_plus(s); [r.equal?(s), r.frozen?, s] } +t("plus: frozen receiver") { r = o.so_plus("k".freeze); [r, r.frozen?] } +t("plus: utf-8") { r = o.so_plus("é"); [r, r.encoding] } +t("plus: binary high byte") { r = o.so_plus("\xff".b); [r, r.encoding] } +t("plus: us-ascii") { r = o.so_plus("a".encode("US-ASCII")); [r, r.encoding] } +t("plus: utf-16le") { o.so_plus("a".encode("UTF-16LE")) } +t("plus: nil") { o.so_plus(nil) } +t("plus: Integer") { o.so_plus(1) } +t("plus: subclass with +") { o.so_plus(SubS.new("q")) } +t("plus: subclass") { r = o.so_plus(SubPlain.new("q")); [r, r.class] } +t("plus: singleton +") { s = +"z"; def s.+(o) = "single"; o.so_plus(s) } +t("plus: Array") { o.so_plus([1]) } +t("plus2") { warm { |i| o.so_plus2("a", i.to_s) } } +t("plus of literals") { warm { o.so_plus_lit } } +t("append") { s = +""; warm { o.so_append(s) }; [s.size, o.so_append(s).equal?(s)] } +t("append: frozen") { o.so_append("f".freeze) } +t("append: utf-16le") { s = "a".encode("UTF-16LE"); [(o.so_append(s) rescue $!.class), s.bytesize] } +t("append: nil") { o.so_append(nil) } +t("append: Array") { o.so_append([1]) } +t("append: binary") { s = "\xff".b; o.so_append(s); [s, s.encoding] } +t("effect then a deopt") { p2 = SO.new; warm { |i| p2.so_buf(i) }; r = p2.so_buf(2**62); [r, p2.buf.size] } +t("count then append") { p2 = SO.new; s = +""; warm { p2.so_count(s) }; p2.so_count("z".freeze) rescue nil; [p2.n, s.size] } +t("append then ivar, frozen") { p2 = SO.new; s = +""; warm { p2.so_then_ivar(s) }; p2.freeze; [(p2.so_then_ivar(s) rescue $!.class), s.size, p2.n] } + +msgs = [] +Warning.singleton_class.define_method(:warn) { |m, **| msgs << m.sub(/\A.*?: /, '') } +Warning[:deprecated] = true +t("chilled") { r = warm(5) { o.so_chilled }; [r, msgs.size] } +t("chilled, hot") { warm { o.so_chilled }; [o.so_chilled, msgs.size > 0] } +Warning[:deprecated] = false + +module PlusRefinement + refine String do + def +(o) = "refined" + end +end +class SO + using PlusRefinement + def so_refined(s) = s + ":" +end +t("refined") { warm { |i| o.so_refined("r") } } + +class String + alias_method :__orig_plus, :+ + def +(o) = "redefined" +end +t("String#+ redefined") { o.so_plus("k") } +class String + alias_method :+, :__orig_plus +end +t("String#+ restored") { o.so_plus("k") } +class String + alias_method :__orig_append, :<< + def <<(o) = "appended?" +end +t("String#<< redefined") { o.so_append(+"k") } +class String + alias_method :<<, :__orig_append +end +t("String#<< restored") { o.so_append(+"k") } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e4c5c4ddc..656b280f9 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1488,6 +1488,58 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitstr (2026-11-26) - `s + "lit"` and `s << "lit"` in a body the method JIT compiles** - + census only, not gated. Behind the String literal line (101 alone) are call arguments (44, gap 1's + wall, perf/strlit's rejected first build) and operands of String operators: `+` 12 (about 15 with + mixed forms), `<<` 11 (16 with `*` or `%` beside it), `"fmt" % x` 8, `"-" * n` 5, comparisons + a few (`s == "lit"` is perf/t3's intrinsic already). Taken: `+` and `<<` with a String literal + argument. Not `%` (format runs `to_s`/`inspect`: Ruby code from the typed body) nor `*` (left for + a step of its own). Different from round fifteen's String `==` and `String#[]` (perf/core2, + 0.92 and 0.91 on their shapes, nothing hot compiled): judged by the methods that then compile, + and the screen takes the operator only where it lets a method through; and from the rejected + "`x == "lit"` without allocating" (code outside the JIT, bytes only): this is the typed body. + `EmitStringLiteralConcat`: for a receiver whose CLR type is exactly `MutableString` (a subclass + instance is another type) and whose encoding the literal's can join, the library's own code - + `MutableString.Concat` for `+`, `Append` for `<<` (`JitRuntime.StringConcatLiteral`, + `StringAppendLiteral`), the literal one frozen copy that neither keeps nor changes. Compiled only + while `String#+`/`#<<` are the public library methods with no String carrying a singleton method + of the name (`IsPlainLibraryMethod`, as `s == "lit"`; a redefinition moves the method version the + entry checks) and no refinement active where the method was written. Anything else deopts before + anything is done: nil, an Integer, an Array, a subclass, incompatible encodings (UTF-16LE), and for + `<<` a frozen receiver (FrozenError from the generic body's frame) or a chilled one (the + deprecation warning, and the String unchilled, by the generic body). `<<` is an effect, after its + own deopt and not one on self only (`_effectNotOnSelf`), so a deopt after it declines as usual; not + in an outlined loop. The screen refuses either as an operand of a binary operator (a String, so + the operator could only deopt): the first build let `URI::Generic#userinfo` (`@user + ':' + + @password`) through, and app-shapes' trace declined it after the pre-screen (30 -> 31); with that + refused the trace is the baseline's. + JIT compiles 3,376 -> 3,384, maybe 2,989 -> 2,997, never 22,011 -> 21,995, light frames unchanged + (Src/StdLib + AWFY, 28,376 methods; 16 methods moved up - 8 to `compiles`, 8 to `maybe` - none + down). Moved: `Net::HTTP#debug` (two copies), RDoc's `accept_rule`, `accept_blank_line` and + `accept_list_end`, `REXML::Declaration#to_s`, `REXML::Text#xpath`, `IPAddr#reverse`, + `#ip6_arpa`, `#ip6_int`, Thor's `file_collision_help`, `Bundler::UI::RGProxy#say`; none of AWFY + (Json's are call arguments) or the prelude. Real code barely has it: of the methods app-shapes + calls, the String literal is the only refusal in none. + Traces: app-shapes 117 specialized and 30 declined after the pre-screen on both builds; AWFY + Json, Richards, DeltaBlue, CD and Havlak (3 x 10) the same on both; `census.rb -c` 290 agree, 0 + differ, and app-shapes' known 15. + Instructions a call (`Util/perf/callgrind/count.sh`, `Util/bench/jit-strop-shapes.rb`, new): + `s + ":"` 3308 -> 3048 (0.92), `s + ":" + "x"` 4669 -> 3979 (0.85), `buf << "x"` 3910 -> 3116 + (0.80), `@user + ":"` 3462 -> 3137 (0.91), the control `s == "lit"` 1244 -> 1244. The + concatenation itself is most of the cost; the typed body saves the literal's allocation and the + dispatch. + Checked: `Util/jit-strop-matrix.rb` (new, 31 rows: new and unfrozen results, a frozen receiver of + `+`, UTF-8, BINARY and US-ASCII receivers, UTF-16LE, nil, Integer and Array receivers, a subclass + with and without its own `+`, a singleton `+`, `<<` on frozen, chilled (with the deprecation + warning counted), UTF-16LE and BINARY receivers, an effect then a deopt, `<<` then an ivar write + on a frozen self, a refinement, `String#+` and `#<<` redefined and restored), and jit, + jit-calls, jit-strlit, jit-scan, jit-interp, jit-const: CRuby's output and the unchanged build's + with the JIT on, `-X:NoJIT -X:NoOSR` and `-X:NoJITCalls`, and the unchanged build's with + `IR_LIGHT_FRAMES=0`; hot-shapes and inline-matrix (one case per process) the unchanged build's in + every mode, with their known one-row differences from CRuby. + For the gate: no IronRuby.Tests or spec run. A String given a singleton `+` anywhere makes every + later compile of `+` bail for the life of the process (`HasPlainInstances`, as for `==`). + - **Gate of 2026-11-26 for round thirty-seven** (perf/lglobal, perf/lexical, perf/deadconst, perf/strsearch, perf/extiter, perf/struct, perf/dmethjit; the rejected perf/lsite's tools and perf/jitbody's census fix): the branch `claude/happy-gauss-95wm2j` at 2f8c31c against master From 86e85c0702fd78653a530a846df176de046796f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:16:17 +0000 Subject: [PATCH 076/439] Name a copied module's methods in backtraces from generated attributes, not by reading every type A backtrace names a method of a module that a class copies in (IList into Array, ClrInteger into Integer) by that class. To find which class, RubyStackTraceBuilder.FindCopyingClasses read the Includes(Copy = true) attributes of every type in IronRuby.Libraries the first time a backtrace held such a method. That cost ~9 ms once per process in `gem list', `require "irb"' and irb: optparse's rescued exception in Gem::Command#handles? builds one. It also loaded the assemblies those types refer to (AngleSharp, System.Net.Sockets). The initializer generator now writes an assembly attribute, RubyCopiedModuleAttribute, for each module a class with a Ruby name of its own copies in (six in IronRuby.Libraries, none in IronRuby.Libraries.Yaml). The runtime reads those for an assembly the generator wrote (it has RubyLibraryAttribute), and still reads every type's attributes for any other assembly. IR_COPIED_TABLE=0 reads the types as before. Checked: the new LibraryCopiedModuleAttributes1 test compares the written table with the reading of every type, for both library assemblies. A probe of backtraces through each copied module's methods (Array#fetch, Hash#fetch, Integer#times, Float#divmod, IO#putc...) prints the same on the base, on this build and with IR_COPIED_TABLE=0, on the Release build and the R2R host. That includes the three lines where IronRuby already differs from CRuby (Integer#div shown as Integer#/, Integer#coerce as Numeric#coerce, IO#printf's frame missing). The 30 backtrace and caller tests of IronRuby.Tests pass. caller, raise, jit-raise and set-backtrace matrices print the same in 7 modes. caller-matrix on the R2R host and thread-backtrace-matrix vary from run to run on both trees. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/InitializerGenerator/LibraryDef.cs | 24 +++++++++++++++++ .../LibraryInitializerGenerator.cs | 3 +++ Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/LibraryInitializerTests.cs | 20 ++++++++++++++ Src/Ruby/Runtime/Attributes.cs | 27 +++++++++++++++++++ Src/Ruby/Runtime/RubyStackTraceBuilder.cs | 27 ++++++++++++++++--- 6 files changed, 99 insertions(+), 3 deletions(-) diff --git a/Src/InitializerGenerator/LibraryDef.cs b/Src/InitializerGenerator/LibraryDef.cs index 5cefe2418..b90bed206 100644 --- a/Src/InitializerGenerator/LibraryDef.cs +++ b/Src/InitializerGenerator/LibraryDef.cs @@ -142,6 +142,9 @@ private sealed class ModuleDef { public ModuleKind Kind; public bool HasCopyInclusions; + // RubyModuleAttribute.Name was given (not only Extends): + public bool HasExplicitName; + public TypeRef Super; // non-null for all classes except for object // Non-null for modules nested in other Ruby modules. @@ -415,6 +418,7 @@ public void ReflectTypes(IReadOnlyList allTypes) { } def.Trait = trait; + def.HasExplicitName = module.Name != null; def.Extends = module.Extends ?? trait; def.DefineIn = module.DefineIn; @@ -997,6 +1001,26 @@ private string FormatSignature(IMethodSymbol method) { #region Code Generation + /// + /// An assembly attribute for each module a class with a Ruby name of its own copies in: what + /// RubyStackTraceBuilder.GetCopyingClassName read from the attributes of every type of the assembly before. + /// + public void GenerateCopiedModuleAttributes(IndentedWriter output) { + var worklist = new List(_moduleDefs.Values); + worklist.Sort(CompareNames); + foreach (ModuleDef def in worklist) { + if (!def.HasExplicitName) { + continue; + } + foreach (MixinRef mixin in def.Mixins) { + if (mixin.Copy) { + output.WriteLine("[assembly: {0}(typeof({1}), typeof({2}))]", "IronRuby.Runtime.RubyCopiedModuleAttribute", + _known.TypeName(mixin.Module.Type), _known.TypeName(def.Trait)); + } + } + } + } + public void GenerateCode(IndentedWriter output) { _output = output; diff --git a/Src/InitializerGenerator/LibraryInitializerGenerator.cs b/Src/InitializerGenerator/LibraryInitializerGenerator.cs index bf1524343..ade47958d 100644 --- a/Src/InitializerGenerator/LibraryInitializerGenerator.cs +++ b/Src/InitializerGenerator/LibraryInitializerGenerator.cs @@ -116,6 +116,9 @@ internal static string Generate(Compilation compilation, Action repo foreach (LibraryDef library in libraries) { output.WriteLine("[assembly: {2}(typeof({0}.{1}))]", library.Namespace, library.InitializerName, "IronRuby.Runtime.RubyLibraryAttribute"); } + foreach (LibraryDef library in libraries) { + library.GenerateCopiedModuleAttributes(output); + } output.WriteLine(); diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e11c273f5..c8449577a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -594,6 +594,7 @@ public Tests(Driver/*!*/ driver) { ClrScopedExtensions8, ClrOverloadInheritance1, LibraryInitializerOverloadAttributes1, + LibraryCopiedModuleAttributes1, ClrOverloadInheritance2, ClrOverloadInheritance3, ClrOverloadInheritance4, diff --git a/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs b/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs index 61b940e5d..9b75292e9 100644 --- a/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs +++ b/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using IronRuby.Builtins; +using IronRuby.Runtime; using IronRuby.Runtime.Calls; namespace IronRuby.Tests { @@ -86,5 +87,24 @@ public void LibraryInitializerOverloadAttributes1() { // the second walk sees the builtins again, and the libraries Assert(count - builtins > builtins, "no overload of a library loaded by require was checked"); } + + /// + /// A backtrace names a copied module's method (IList#fetch, ClrInteger#+) by the class that copies it in, which + /// RubyStackTraceBuilder reads from the RubyCopiedModuleAttributes the initializer generator writes. They must say + /// what reading the Includes(Copy = true) attributes of every type of the assembly says. + /// + public void LibraryCopiedModuleAttributes1() { + foreach (var assembly in new[] { typeof(IronRuby.Builtins.ArrayOps).Assembly, typeof(IronRuby.StandardLibrary.Yaml.RubyYaml).Assembly }) { + var read = RubyStackTraceBuilder.ReadCopyingClasses(assembly); + var scanned = RubyStackTraceBuilder.ScanCopyingClasses(assembly); + Assert(read.Count == scanned.Count, assembly.GetName().Name + ": " + read.Count + " pairs written, " + scanned.Count + " found"); + foreach (var pair in scanned) { + Type copying; + Assert(read.TryGetValue(pair.Key, out copying) && copying == pair.Value, + assembly.GetName().Name + ": " + pair.Key + " is copied into " + pair.Value + ", written " + copying); + } + } + Assert(RubyStackTraceBuilder.ReadCopyingClasses(typeof(IronRuby.Builtins.ArrayOps).Assembly).Count >= 6); + } } } diff --git a/Src/Ruby/Runtime/Attributes.cs b/Src/Ruby/Runtime/Attributes.cs index af85c597c..3aadfdc88 100644 --- a/Src/Ruby/Runtime/Attributes.cs +++ b/Src/Ruby/Runtime/Attributes.cs @@ -42,6 +42,33 @@ public RubyLibraryAttribute(Type/*!*/ initializer) { } } + /// + /// Applied to a library assembly, by the initializer generator, for each module a class of it copies in + /// () whose gives it a Ruby name of its own: + /// IListOps into Array, ClrInteger into Integer. A backtrace names a copied module's method by the class + /// (RubyStackTraceBuilder.GetCopyingClassName), and these say which without reading every type's attributes. + /// + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public sealed class RubyCopiedModuleAttribute : Attribute { + private readonly Type/*!*/ _module; + private readonly Type/*!*/ _copyingClass; + + public Type/*!*/ Module { + get { return _module; } + } + + public Type/*!*/ CopyingClass { + get { return _copyingClass; } + } + + public RubyCopiedModuleAttribute(Type/*!*/ module, Type/*!*/ copyingClass) { + ContractUtils.RequiresNotNull(module, "module"); + ContractUtils.RequiresNotNull(copyingClass, "copyingClass"); + _module = module; + _copyingClass = copyingClass; + } + } + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = true)] public sealed class RubyConstantAttribute : RubyAttribute { private readonly string _name; diff --git a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs index ee15e6af0..33697f760 100644 --- a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs +++ b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs @@ -1078,6 +1078,9 @@ private string GetLibraryModuleName(Type type) { return name; } + // IR_COPIED_TABLE=0 reads the attributes of every type of the assembly, as before RubyCopiedModuleAttribute (for comparing). + private static readonly bool CopyingClassesTableEnabled = Environment.GetEnvironmentVariable("IR_COPIED_TABLE") != "0"; + // Per library assembly: copied-in module -> the class that copies it. private static readonly ConcurrentDictionary>/*!*/ _copyingClasses = new ConcurrentDictionary>(); @@ -1090,10 +1093,28 @@ private string GetCopyingClassName(Assembly/*!*/ assembly, Type/*!*/ included) { GetLibraryModuleName(copying) : null; } - // One pass over the assembly's attributes answers every later lookup: it reads the attributes - // of every type in IronRuby.Libraries, and doing that once per copied module made each of the - // first few backtraces of a process cost ~15 ms. + // A library assembly the initializer generator wrote says which classes copy which modules in + // (RubyCopiedModuleAttribute): reading the attributes of every type in IronRuby.Libraries instead + // took ~9 ms of the first backtrace that named a copied module's method (one `gem list', irb and + // `require "irb"' make), and loaded the assemblies its types refer to (AngleSharp, + // System.Net.Sockets). Another assembly has its types read, in one pass that answers every later + // lookup: once per copied module made each of the first few backtraces of a process cost ~15 ms. private static Dictionary/*!*/ FindCopyingClasses(Assembly/*!*/ assembly) { + return (CopyingClassesTableEnabled && assembly.IsDefined(typeof(RubyLibraryAttribute), false)) ? + ReadCopyingClasses(assembly) : ScanCopyingClasses(assembly); + } + + internal static Dictionary/*!*/ ReadCopyingClasses(Assembly/*!*/ assembly) { + var result = new Dictionary(); + foreach (RubyCopiedModuleAttribute copied in assembly.GetCustomAttributes(typeof(RubyCopiedModuleAttribute), false)) { + if (!result.ContainsKey(copied.Module)) { + result.Add(copied.Module, copied.CopyingClass); + } + } + return result; + } + + internal static Dictionary/*!*/ ScanCopyingClasses(Assembly/*!*/ assembly) { var result = new Dictionary(); Type[] types; try { From a5ddcc4a079ea6a2704b33034deeb24235f15f68 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:21:43 +0000 Subject: [PATCH 077/439] Keep the JIT stub from judging an entry by its interpreted generic body A probe times the generic body to decide whether an entry that deopts pays its way. It waited for the generic body's compile for at most 8 deopt windows - microseconds, when every other call deopts - and then timed the interpreter: 4 us a call against 0.16 compiled. Until the next probe, 100 ms on, that figure kept an entry that deopted on every other call (about 1,000 windows, some 15,000 deopts at 2 us, for `x + 1' with an Integer and a Float in turn); and a probe right after the compile still read the CLR's first-tier code, 1.75 us. A cost timed before the compile is now forgotten when GenericCompiled fires, so the next window probes again; and a probe taken while the generic body is uncompiled or compiled 100 ms ago or less takes none of the six probes, and the next may come 10 ms on (at most 16 such): the cost, the least any probe read, comes down to the warm figure early. A stub whose generic body is warm probes as before. Checked: Util/bench/jit-probe-shapes.rb, ab.rb -r 6: a fresh method fed an Integer and a Float in turn 875 -> 277 ns; jit-settle-shapes level. Traces of app-shapes, gem list and all AWFY: two methods were first probed interpreted; AWFY List's Element#length, which deopts on every call, is now retired where the base kept it for the run on a 62 us figure; specialized and declined counts the same. jit, jit-calls, jit-const and dmeth-jit matrices print CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls and IR_JIT_REST=0; hot-shapes, inline and int-matrix print the base's. The 20 IronRuby.Tests named for the JIT pass. Not gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/Ruby/Runtime/Jit/JitStub.cs | 40 +++++++++++++++++++++++++--- Util/bench/jit-probe-shapes.rb | 47 +++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 34 ++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 3 deletions(-) create mode 100644 Util/bench/jit-probe-shapes.rb diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 290239df6..11d02a231 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -248,7 +248,19 @@ private void GenericCompiled(Delegate/*!*/ compiled) { if (compiled.GetType() == _generic.GetType()) { Volatile.Write(ref _compiledGeneric, compiled); } + Volatile.Write(ref _compiledAt, Stopwatch.GetTimestamp()); _genericCompiled = true; + lock (_sync) { + if (_genericCostInterpreted) { + // The generic cost was the interpreter's - a probe waits only MaxProbeDelays windows for the compile, + // which go by in microseconds when every other call deopts - and many times the compiled body's: it + // made an entry that deopts on every other call look worth keeping (4 us against 0.16, perf/jitprobe). + // Forget it, so that the next window times the compiled body (Probe). + _genericCost = 0; + _genericCostInterpreted = false; + _probeAfter = 0; + } + } if (_compiledGeneric == null) { return; } bool settled; lock (_sync) { @@ -615,6 +627,14 @@ private bool Respecialize(Specialization/*!*/ spec) { // never interpreted. A probe waits for it, for at most MaxProbeDelays windows. private volatile bool _genericCompiled; private int _probeDelays; + // _genericCost was timed before the generic body was compiled (GenericCompiled forgets it). + private bool _genericCostInterpreted; + // When GenericCompiled ran (Stopwatch ticks), and the probes taken before the compiled body warmed up (Probe). + private long _compiledAt; + private int _warmProbes; + private const int WarmMs = 100; + private const int WarmProbeIntervalMs = 10; + private const int MaxWarmProbes = 16; private static MSA.Expression/*!*/ CountEntry(Specialization/*!*/ spec) { var countdown = Ast.Field(Ast.Constant(spec), Specialization.CountdownField); @@ -711,8 +731,21 @@ internal void OnDeopt(Specialization/*!*/ spec, long deoptCost) { private void Probe(Specialization/*!*/ spec, int entries, long deopt) { lock (_sync) { if (_state != Specialized || spec != _current || _probes >= MaxProbes) { return; } - _probeAfter = Stopwatch.GetTimestamp() + (Stopwatch.Frequency * ProbeIntervalMs / 1000) * (1L << _probes); - _probes++; + // While the generic body is not compiled, or compiled WarmMs ago or less - its first calls run the CLR's + // quick first-tier code - a probe reads it high, which keeps an entry that deopts on every other call + // (1.75 us a generic call 2 ms after the compile, 0.12 at 100 ms; perf/jitprobe). Such a probe takes + // none of the MaxProbes, and the next may come WarmProbeIntervalMs on: the cost is the least any probe + // read, so it comes down to the warm one's soon. At most MaxWarmProbes of them. + long now = Stopwatch.GetTimestamp(); + bool warm = _warmProbes < MaxWarmProbes && + (!_genericCompiled || now - Volatile.Read(ref _compiledAt) < Stopwatch.Frequency * WarmMs / 1000); + if (warm) { + _warmProbes++; + _probeAfter = now + Stopwatch.Frequency * WarmProbeIntervalMs / 1000; + } else { + _probeAfter = now + (Stopwatch.Frequency * ProbeIntervalMs / 1000) * (1L << _probes); + _probes++; + } if (JitRuntime.Verbose) { Console.Error.WriteLine("[jit] timing the generic body of {0}/{1} arity {2}: {3} deopts in {4} calls (deopt {5:F1} us){6}", _declaringModule.Name ?? "main", _ast.Name, _arity, spec.WindowDeopts, entries, deopt * 1e6 / Stopwatch.Frequency, @@ -824,9 +857,10 @@ protected void CoolDownCheck() { if (_coolSampleCount > 0) { long median = Median(_coolSamples, Math.Min(_coolSampleCount, MaxDeopts)); - if (_genericCost == 0 || median < _genericCost) { _genericCost = median; } + if (_genericCost == 0 || median < _genericCost) { _genericCost = median; _genericCostInterpreted = !_genericCompiled; } } else if (_coolRaisedCount > 0 && _genericCost == 0) { _genericCost = Median(_coolRaised, Math.Min(_coolRaisedCount, MaxDeopts)); + _genericCostInterpreted = !_genericCompiled; } var spec = _current; spec.Countdown = 0; diff --git a/Util/bench/jit-probe-shapes.rb b/Util/bench/jit-probe-shapes.rb new file mode 100644 index 000000000..08544fe6b --- /dev/null +++ b/Util/bench/jit-probe-shapes.rb @@ -0,0 +1,47 @@ +# The first calls of a method the JIT specializes, while its generic body is still interpreted (perf/jitprobe): each +# section defines a method of its own (a `def' compiled from a string, so that no compiled body is shared) and calls +# it N times - `fresh_mixed' with an Integer and a Float in turn, whose typed body fails on every other call; +# `fresh_int' with Integers, which never fails; `warm_int' a method defined once, as a control. ` ns +# ' per line, for Util/perf/ab.rb; N is the calls a section makes (ab.rb -n); INSTR=1 adds instructions. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +# a section is short: the thread's CPU clock, which schedstat updates too seldom for +def cpu + Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID) +rescue SystemCallError, NameError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end +$fresh = 0 +def fresh_object + $fresh += 1 + cls = Class.new + cls.class_eval("def m(x) = x + #{$fresh}") + cls.new +end +def t(name, n = 100_000) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + n = ENV['N'].to_i if ENV['N'] + best = 1e9; r = nil; fewest = nil; counted = !!INSTR + 5.times do + o = fresh_object + c0 = INSTR && INSTR.read + t0 = cpu + r = yield n, o + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + fewest = c1 - c0 if fewest.nil? || c1 - c0 < fewest + else + counted = false + end + end + printf "%-14s %8.1f ns %s%s\n", name, best * 1e9 / n, r, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +class W + def m(x) = x + 1 +end +w = W.new +t("fresh_mixed") { |n, o| i = 0; c = 0; while i < n; c += o.m(i.odd? ? i : 0.5).to_i; i += 1; end; c - $fresh * n } +t("fresh_int") { |n, o| i = 0; c = 0; while i < n; c += o.m(i); i += 1; end; c - $fresh * n } +t("warm_int") { |n, o| i = 0; c = 0; while i < n; c += w.m(i); i += 1; end; c } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a1551aec0..a36498be6 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1492,6 +1492,40 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitprobe (2026-11-26) - the stub's generic cost is not the interpreter's** - not gated. A probe + (`JitStub.Probe`) times the generic body to decide whether an entry that deopts pays its way. It waited + for the generic body's compile for at most 8 deopt windows, which go by in microseconds when every + other call deopts, and then timed the interpreter: 4 us a call where the compiled body takes 0.16. Its + next probe is 100 ms on, and until then that figure kept the entry: `x + 1` with an Integer and a Float + in turn, in a method of its own, deopted on every other call for about 1,000 windows (some 15,000 + deopts at 2 us). Right after the compile a probe still read 1.75 us (the CLR's first-tier code; 0.12 at + 100 ms). + - The change: a cost timed before the compile is marked (`_genericCostInterpreted`) and forgotten when + `GenericCompiled` fires, which lets the next window probe again. And a probe taken while the generic + body is not compiled, or compiled 100 ms ago or less, takes none of the six probes and lets the next + come 10 ms on rather than 100 (at most 16 of them): the cost is the least any probe read, so it comes + down to the warm figure early. A stub with a warm generic body probes as before. + - Real runs (IR_JIT_VERBOSE=1: app-shapes, `gem list`, all 14 AWFY at `harness.rb B 5 10`): two methods + were first probed on an interpreted generic body. `Element#length` (AWFY List) deopts on every call + (16 in 16): the base keeps it for the whole run on a 62 us figure; the new probes twice more, reads + 8.7 us and retires it - an entry that deopts on every call never pays. `Gem::Dependency#runtime?` + (`gem list`) is retired on both. Otherwise the traces specialize and decline the same (264, 64). + (Havlak, Mandelbrot and NBody report "incorrect result" at that inner size on both builds and on CRuby: + they verify only at their own.) + - Time (`Util/bench/jit-probe-shapes.rb`, a method of its own per section, 100,000 calls; `ab.rb -r 6`, + ns; base, new): `fresh_mixed` 875 -> 277 (0.32), `fresh_int` (never deopts) 87.0 / 96.7 (overlap); + `Util/bench/jit-settle-shapes.rb` all level (0.96-1.01, overlap). `warm_int`, a method defined once, + run after the fresh shapes in the same process, reads 42.7 -> 78.7: alone it is 82.4 / 83.9, and after + 0.8 s of other work first 43-46 / 50-59 - the base spends half a second more in `fresh_mixed`, in + which the CLR tiers up the code `warm_int` runs too. Not a cost of the change. + - Matrices, CRuby against base (8fde498) against new, with the JIT on, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` and `IR_JIT_REST=0`: jit, jit-calls, jit-const, dmeth-jit identical to CRuby; + hot-shapes, inline and int-matrix identical to base (the rows that differ from CRuby differ on base: + as in perf/jitsettle). IronRuby.Tests: the 20 named for the JIT pass. + - For the gate: a stub whose generic body is still interpreted now probes more (up to 16 short + probes of 32 timed calls each in its first 100 ms after the compile); `GenericCompiled` now takes + the stub's lock on the light compiler's thread. + - **perf/jitsettle (2026-11-26) - a retired entry's cool-down costs nothing per call** - not gated. A method whose typed body keeps failing (`x + 1` called with an Integer and a Float in turn) ran 10-16% slower than with the JIT off, as a `def` and as a define_method method. What it does per call, From 5981e7b671ee9ea6d97cab44b2e804efe5ca88bb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:25:47 +0000 Subject: [PATCH 078/439] Ledger: "constant without a scope" is the census's, rejected The census's second "JIT maybe" line (455 methods) is the compiler's bailout for a null constant scope, which only the census passes: it has no running program. A real compile folds the constant from the stub's declaring scope. Traces of app-shapes and all fourteen AWFY benchmarks show no runtime rejection at a constant; of the census's 455, a census-only probe (not kept) finds 183 with nothing else behind the constant, 221 that need the constant's value, about 50 with a call behind it. No runtime change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1e2bc09da..2bdfbfa51 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -5352,6 +5352,32 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitconst (2026-11-26) - "JIT maybe: constant without a scope" is the census's, not the + runtime's; nothing to let in.** The census's second "maybe" line (455 methods of Src/StdLib + + AWFY on 9d2c89a: ENV 19, Array 12, Integer 11, URI 11, AF_INET 8, BN 7) comes from + `ResolveConstant` bailing when `_constantScope` is null, and the census calls + `JitCompiler.TryCompile` with no scope at all (it runs no program, so there is no declaring + scope to look a constant up in). A real compile gets the stub's declaring scope and folds the + constant, revalidated at entry (perf/constrev). Traces: app-shapes calls 10 of these methods and + specializes 4 (`ERB#make_compiler`, `ERB::Compiler::Scanner#initialize`, + `Gem::Specification#platform`, `Shop::Product#tax_rate`); two are declined for something else + (`OptionParser.top` and `Gem::Requirement#none?`, both at "[] on a RubyArray": `@stack[-1]`, + `@requirements[0] == ...`), four never turn hot. Fourteen AWFY benchmarks (2 x 5): 118 + specialized, and no rejection or decline anywhere names a constant, autoload or a deprecated + constant (`JitFoldedConstant.Resolve`'s failures). + What stands behind the constant, found with a census-only probe (not kept: an unresolved + constant emitted as an opaque object, and a body that then compiled reported as "constant + only"): of the 455, 221 still stop at the constant, using it where the value is needed (a class + for `new`, `when`, `::X`, a receiver such as `ENV[k]`), 183 have nothing else behind it - they + compile once a run resolves the constant to a value the body can type - and about 50 stop next at + a call or another profile question. So the line is a census blind spot, not a refusal: a step + that made the census resolve constants would change its verdicts, not what runs. The runtime + questions of gap 29 (a later constant shadowing a folded one, autoload in flight, + `const_missing`, private constants) were not touched. + Also found: two of app-shapes' methods are declined at "[] on a RubyArray" for an element read + with a negative index or of an Array instance variable compared with `==` - a typed-body + question for another step. + - **perf/lexical3 (/perf-step, 2026-11-26, on 3cabf57) - bind the positionals of `def m(a, *r, k: 1)` in the calling convention instead of out of one splat** (the idea perf/lexical2's entry named), rejected by measurement before any code. The premise was `kr_rest` 5,325 From 6b6f712055f616e77e859023295c0b21dc72eb59 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:26:15 +0000 Subject: [PATCH 079/439] Reclaim an abandoned lazy enumerator's fiber: its next walks a copy An enumerator abandoned after a #next keeps its fiber, a thread here, until the fiber's handle is collected and its finalizer unwinds the thread. That needs nothing on the thread to reach the handle. An Enumerator's fiber runs a detached copy (__enum_iteration_source__), and a generator made in a method is reclaimed. But a Lazy got itself, so the thread's `source.each` kept the lazy, its @__fiber__ and the handle alive for the life of the process: 10,000 lazies abandoned after one #next left 10,018 threads and 634-715 MB after GC, against CRuby's 2 threads and 17 MB. A Lazy with no singleton class or subclass, whose #each is the prelude's, now gives its fiber a copy (Lazy.allocate and the seven instance variables Lazy#each reads). Enumerator.__iter_detachable_lazy__ checks the class and #each. IR_FAST_NEXT=0 gives the lazy itself, as before. Util/bench/extiter-abandoned.rb (new), 10,000 each, threads and RSS after GC: a lazy made in a method 10,018 / 639 MB -> 18 / 325 MB; held in a local with Symbol#to_proc blocks 10,018 / 709 -> 18 / 344; made in a method and held in a local 10,018 / 715 -> 18 / 333. A block that runs on the fiber and closes over the scope holding the enumerator still keeps it, as before, for lazies and generators alike: a blocked thread's stack is a GC root. lazy_next per next is unchanged (0.98 run alone). 40 new probes in Util/extiter-matrix.rb (262 in all) print CRuby's output on the baseline, the change and the change switched off; enum-next, block-loop, hash-order, raise, full-message, enum and enumerable2 matrices agree with the baseline; spec/core/enumerator, hash, enumerable, fiber and kernel/loop give the same result in all three modes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Src/Libraries/Builtins/Enumerator.cs | 16 +++++++++ Src/StdLib/ironruby/ruby4.rb | 25 ++++++++++++++ Util/bench/extiter-abandoned.rb | 39 ++++++++++++++++++++++ Util/extiter-matrix.rb | 43 ++++++++++++++++++++++++ Util/perf/LEDGER.md | 50 ++++++++++++++++++++++++++-- 5 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 Util/bench/extiter-abandoned.rb diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index c9a464b38..644732f7b 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -747,6 +747,7 @@ private sealed class PreludeMethods { internal RubyMemberInfo EachSlice; internal RubyMemberInfo EachCons; internal RubyMemberInfo StopIterationResult; + internal RubyMemberInfo LazyEach; } private static readonly object _preludeMethodsKey = new object(); @@ -766,6 +767,8 @@ public static object RegisterCursorMethod(RubyContext/*!*/ context, object self, var methods = GetPreludeMethods(context); if (name == "each_with_index") { methods.EachWithIndex = method.Info; + } else if (name == "each" && module.Name == "Enumerator::Lazy") { + methods.LazyEach = method.Info; } else if (name == "each") { methods.StructEach = method.Info; } else if (name == "each_slice") { @@ -1049,6 +1052,19 @@ public static Enumerator GetIterationSource(RubyContext context, Enumerator self return source; } + /// + /// Whether a lazy enumerator's #next may run its #each on a copy of it (the prelude's Lazy#__enum_iteration_source__): + /// it is an Enumerator::Lazy and nothing more (no singleton class, no subclass), and its #each is the prelude's, which + /// reads only the instance variables the copy is given. The fiber then holds no reference to the lazy the program + /// has, and an abandoned one is reclaimed (its handle collected) as an Enumerator's is. IR_FAST_NEXT=0 keeps the lazy. + /// + [RubyMethod("__iter_detachable_lazy__", RubyMethodAttributes.PublicSingleton)] + public static bool IsDetachableLazy(RubyContext/*!*/ context, object self, object lazy) { + RubyMemberInfo expected = GetPreludeMethods(context).LazyEach; + return _fastNext && expected != null && context.GetImmediateClassOf(lazy) == expected.DeclaringModule && + IsPreludeMethod(context, lazy, "each", expected); + } + private static bool IsBuiltinMethod(RubyContext/*!*/ context, object target, string/*!*/ name, Type/*!*/ declaringType, params string[]/*!*/ clrNames) { var method = context.ResolveMethod(target, name, VisibilityContext.AllVisible); if (!method.Found || !(method.Info is RubyLibraryMethodInfo)) { diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index a342f5bf2..f9120d8ef 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -6012,6 +6012,31 @@ def each(*args, &block) block ? lazy.each(&block) : lazy end + # Enumerator#next walks the lazy on a fiber, a thread here, that runs #each: given this lazy, the + # thread kept it alive and with it the fiber's handle, so an abandoned lazy's fiber was never + # reclaimed. A plain Lazy's #each reads nothing but these, so the fiber gets a copy, as an + # Enumerator's gets one (Enumerator#__enum_iteration_source__, Enumerator.cs). + ::Enumerator.__iter_cursor_method__(self, :each) + + def __enum_iteration_source__ + return self unless ::Enumerator.__iter_detachable_lazy__(self) + Lazy.allocate.__send__(:__lazy_detach__, @__generator__, @__size__, @__lazy_source__, @__lazy_generator__, + @__deferred__, @__packed_pairs__, @__inspect__) + end + private :__enum_iteration_source__ + + def __lazy_detach__(generator, size, source, source_generator, deferred, packed_pairs, inspect) + @__generator__ = generator + @__size__ = size + @__lazy_source__ = source + @__lazy_generator__ = source_generator + @__deferred__ = deferred + @__packed_pairs__ = packed_pairs + @__inspect__ = inspect + self + end + private :__lazy_detach__ + # Enumerator#+ chains eagerly; a lazy receiver stays lazy, as in MRI: # (1..).lazy + [1] is an Enumerator::Lazy over an Enumerator::Chain. def +(other) diff --git a/Util/bench/extiter-abandoned.rb b/Util/bench/extiter-abandoned.rb new file mode 100644 index 000000000..538e27ea9 --- /dev/null +++ b/Util/bench/extiter-abandoned.rb @@ -0,0 +1,39 @@ +# Enumerators that are abandoned after one #next: threads and memory left once they are collected +# (LEDGER gap 35). A fiber-backed enumerator here is a thread; its handle's finalizer unwinds the +# thread once nothing reaches the handle, which a thread's own stack cannot see past: when a block +# that runs on the fiber closes over a scope that holds the enumerator, the thread keeps it alive. +# +# ./ir.sh Util/bench/extiter-abandoned.rb KIND [COUNT] # one kind per process (COUNT 10,000) +# for k in $(ruby Util/bench/extiter-abandoned.rb); do ./ir.sh Util/bench/extiter-abandoned.rb $k; done +# +# CRuby collects every kind: 2 threads and about 20 MB at the end. +$stdout.sync = true +def st = File.read("/proc/self/status").scan(/^(VmRSS|Threads):\s+(\d+)/).to_h +def cpu = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) +def make_lazy = [1, 2, 3].lazy.map { |x| x * 2 } +def make_lazy_sym = (1..Float::INFINITY).lazy.select(&:even?).map(&:succ) +def make_gen = Enumerator.new { |y| y << 1; y << 2 } +KINDS = { + # made in a method of its own: nothing on the fiber reaches the enumerator + "lazy_nolocal" => -> { make_lazy.next }, + "gen_nolocal" => -> { make_gen.next }, + # held in a local, its blocks Symbol#to_procs or made elsewhere: the same + "lazy_local_sym" => -> { e = (1..Float::INFINITY).lazy.select(&:even?).map(&:succ); e.next }, + "lazy_method_local" => -> { e = make_lazy_sym; e.next; e.peek }, + # the block runs on the fiber and its scope holds the enumerator: kept while the thread waits + "lazy_block_local" => -> { e = [1, 2, 3].lazy.map { |x| x * 2 }; e.next }, + "gen_block_local" => -> { e = Enumerator.new { |y| y << 1; y << 2 }; e.next }, + # a cursor: no fiber at all + "map_local" => -> { e = [1, 2, 3].map; e.next }, +} +abort(KINDS.keys.join("\n")) unless ARGV[0] +kind = ARGV[0] +n = (ARGV[1] || 10_000).to_i +make = KINDS.fetch(kind) +t0 = cpu +n.times { make.call } +t = (cpu - t0) * 1e6 / n +a = st +3.times { GC.start; sleep 1 } +b = st +printf "%-18s %6d: %7.1f us each; threads %5s -> %5s, RSS %4d -> %4d MB\n", kind, n, t, a["Threads"], b["Threads"], a["VmRSS"].to_i / 1024, b["VmRSS"].to_i / 1024 diff --git a/Util/extiter-matrix.rb b/Util/extiter-matrix.rb index 26c730070..0b8e953f0 100644 --- a/Util/extiter-matrix.rb +++ b/Util/extiter-matrix.rb @@ -583,3 +583,46 @@ def fed_result(e, feeds) probe("wo_hash") { drain({ a: 1 }.each.with_object(0)) } probe("wo_memo_mutated") { m = []; e = [1, 2].each.with_object(m); e.next[1] << :x; [e.next, m] } probe("wo_block_form") { [[1, 2].each.with_object([]) { |x, m| m << x }, [1, 2].each.with_index(1) { |x, i| x * i }, [1, 2].map.with_index(1) { |x, i| x * i }] } + +# --- Enumerator::Lazy taken with #next: the fiber walks a copy of a plain lazy ------------------------ +def lz(e, n = 4) = n.times.map { (e.next rescue :stop) } +probe("lz_map") { lz([1, 2, 3].lazy.map { |x| x * 2 }) } +probe("lz_select_map") { lz((1..Float::INFINITY).lazy.select(&:even?).map(&:succ)) } +probe("lz_reject") { lz((1..6).lazy.reject(&:odd?)) } +probe("lz_take") { lz((1..).lazy.take(2)) } +probe("lz_take_while") { lz((1..).lazy.take_while { |x| x < 3 }) } +probe("lz_drop") { lz((1..5).lazy.drop(3)) } +probe("lz_drop_while") { lz((1..5).lazy.drop_while { |x| x < 4 }) } +probe("lz_filter_map") { lz((1..5).lazy.filter_map { |x| x * 2 if x.odd? }) } +probe("lz_flat_map") { lz([[1, 2], [3]].lazy.flat_map { |x| x }) } +probe("lz_zip") { lz([1, 2].lazy.zip([3, 4])) } +probe("lz_uniq") { lz([1, 1, 2].lazy.uniq) } +probe("lz_compact") { lz([1, nil, 2].lazy.compact) } +probe("lz_with_index") { lz([:a, :b].lazy.with_index(1)) } +probe("lz_ewi") { lz([:a, :b].lazy.each_with_index) } +probe("lz_chunk_while") { lz([1, 2, 4, 5].lazy.chunk_while { |a, b| b == a + 1 }) } +probe("lz_slice_when") { lz([1, 2, 4].lazy.slice_when { |a, b| b != a + 1 }) } +probe("lz_chunk") { lz([1, 1, 2].lazy.chunk { |x| x.odd? }) } +probe("lz_grep") { lz(%w[a bb c].lazy.grep(/b/)) } +probe("lz_plain") { lz([1, 2].lazy) } +probe("lz_hash") { lz({ a: 1, b: 2 }.lazy.map { |k, v| [v, k] }) } +probe("lz_hash_plain") { lz({ a: 1 }.lazy) } +probe("lz_new") { lz(Enumerator::Lazy.new([1, 2, 3]) { |y, x| y << x * 10 if x != 2 }) } +probe("lz_eager") { lz([1, 2].lazy.map { |x| x + 1 }.eager) } +probe("lz_result") { [stop_of([1, 2].lazy).result, stop_of([1, 2].lazy.map { |x| x }).result] } +probe("lz_peek") { e = [1, 2].lazy.map { |x| x * 3 }; [e.peek, e.next, e.peek, e.next, (e.peek rescue :stop)] } +probe("lz_next_values") { e = { a: 1 }.lazy; [e.peek_values, e.next_values] } +probe("lz_rewind") { e = (1..3).lazy.map { |x| x * 2 }; e.next; e.rewind; [e.next, e.next] } +probe("lz_loop") { e = (1..3).lazy.select(&:odd?); r = []; loop { r << e.next }; r } +probe("lz_state_fresh") { e = [1, 2, 2, 3].lazy.uniq; a = [e.next, e.next, e.next]; e.rewind; [a, e.next, e.next] } +probe("lz_force_after") { e = [1, 2, 3].lazy.map { |x| x * 2 }; e.next; [e.first(2), e.to_a, e.next] } +probe("lz_inspect") { e = [1, 2].lazy.map { |x| x }; e.next; e.inspect } +probe("lz_size") { e = [1, 2].lazy.map { |x| x }; e.next; e.size } +probe("lz_feed") { e = [1, 2].lazy.map { |x| x }; e.next; e.feed :f; [e.next, (e.next rescue $!.result)] } +probe("lz_singleton_each") { e = [1, 2].lazy.map { |x| x * 2 }; def e.each(*); yield :own; :r; end; [e.next, (e.next rescue $!.result)] } +probe("lz_subclass") { c = Class.new(Enumerator::Lazy) { def each(*) = super { |x| yield x.to_s } }; e = c.new([1, 2]) { |y, x| y << x }; [e.next, e.next] } +probe("lz_ivar_after") { e = [1, 2].lazy.map { |x| x }; e.next; e.instance_variable_set(:@mine, 1); [e.next, e.instance_variables.include?(:@mine)] } +probe("lz_frozen") { e = [1].lazy.map { |x| x }.freeze; (e.next rescue $!.class) } +probe("lz_dup_fresh") { e = [1, 2].lazy.map { |x| x * 5 }; d = e.dup; [d.next, e.next] } +probe("lz_thread") { e = [1, 2].lazy.map { |x| x }; e.next; Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value } +probe("lz_raises") { e = [1, 2].lazy.map { |x| x == 2 ? raise(ArgumentError, "two") : x }; [e.next, (e.next rescue "#{$!.class}: #{$!.message}"), e.next] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 9fa6c2913..fd0df2462 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1463,9 +1463,19 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has result is a Hash), `Enumerator::Lazy`, `Enumerator.produce` (generators of the prelude, which run Ruby code between two values: a cursor would call blocks under its lock) and `Enumerator.new`. A raw fiber round trip is 2.3 us of wall clock and 4.7-6 us of CPU (two - threads spinning), so the prelude's machinery around it is not where the time is; an - abandoned fiber-backed enumerator costs about 0.55 ms (its thread). Untried: switching fibers - without a thread (a continuation of the method JIT's own). + threads spinning), so the prelude's machinery around it is not where the time is. + **An abandoned fiber-backed enumerator** costs 1.1-1.6 ms of process CPU to make and take one + value from (starting its thread), and its thread and about 60 KB stay until the handle's + finalizer unwinds it (FiberRegistration, ThreadOps.Fiber.cs). That needs nothing on the + fiber's side to reach the handle, and a blocked thread's stack is a GC root: since + perf/extiter4 (Landed) a lazy made elsewhere, or whose blocks are Symbol#to_procs, is + reclaimed as an Enumerator's generator is, but a block that runs on the fiber and closes over + a scope holding the enumerator (`e = xs.lazy.map { |x| ... }; e.next`, the same with + `Enumerator.new { |y| ... }`) keeps it for the life of the process: 10,000 of them are 10,018 + threads and 640 MB after GC (CRuby: 2 threads, 17 MB; `Util/bench/extiter-abandoned.rb`). Only + a fiber that is not a thread gets past that. Untried: switching fibers without a thread (a + continuation of the method JIT's own); a smaller stack for fiber threads (the memory, not the + thread). Two differences from CRuby in `with_index` / `with_object` enumerators, with or without a cursor, left as they were (the matrix leaves them out, with a comment): MRI's enumerator calls the source's method itself, so a singleton #each on the source enumerator is not called (here @@ -1499,6 +1509,40 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/extiter4 (2026-11-26) - an abandoned lazy enumerator's fiber is reclaimed: its #next walks + a copy (gap 35)** - not gated. Base 3bf570d (the round-37 branch at 79a2c30 with + perf/extiter3). Measured first (`Util/bench/extiter-abandoned.rb`, new: 10,000 enumerators + abandoned after one `next`, threads and RSS after three `GC.start`s): every lazy kind kept its + thread for good on the base - 10,018 threads, 634-715 MB - where a generator Enumerator made in + a method was reclaimed (18 threads). The fiber of an Enumerator gets a detached copy to run + (`__enum_iteration_source__`), so nothing on the fiber's thread reaches the enumerator, its + @__fiber__ or the handle, and the handle's finalizer unwinds the thread; a Lazy, an Enumerator + subclass, got itself, and the thread's `source.each` kept it alive. Now an Enumerator::Lazy that + is nothing more (no singleton class, no subclass) and whose #each is the prelude's + (`Enumerator.__iter_detachable_lazy__`, the prelude's Lazy#each registered with + `__iter_cursor_method__`) gives its fiber a copy made with `Lazy.allocate` and the seven + instance variables Lazy#each reads. Base -> new, threads and RSS after GC: a lazy made in a + method 10,018 / 639 MB -> 18 / 325 MB, a lazy of Symbol#to_procs in a local 10,018 / 709 -> + 18 / 344, one made in a method and held in a local 10,018 / 715 -> 18 / 333. Not reached, and + not reachable while a fiber is a thread: a block that runs on the fiber and closes over the scope + holding the enumerator (`e = xs.lazy.map { |x| ... }; e.next`; `Enumerator.new { }` alike), + 10,018 threads before and after. `IR_FAST_NEXT=0` gives the lazy itself, as before. Time per + enumerator unchanged (1.1-1.4 ms, the thread's start); `ab.rb -r 8`, alone, `lazy_next` 0.98 of + off, `generator` overlapping (1.30 and 1.48 in a run of six shapes, after shapes that use a + fiber only when switched off). `Util/extiter-matrix.rb` (262 probes, 40 new: next / peek / + rewind / loop / feed over every Lazy operation, chunk's deferred block, Lazy.new, eager, a + singleton #each, a subclass, instance variables set after the copy, frozen, dup, threads, an + exception in the block) prints CRuby's output on base, new and off; enum-next-, block-loop-, + hash-order-, raise-, full-message-, enum- and enumerable2-matrix the same on all three. + spec/core/enumerator, hash, enumerable, fiber and kernel/loop_spec: 1,729 examples, the same one + error in all three (Hash.try_convert's `into`/`to`). 125 named IronRuby.Tests (Enumerator*, + Enumerable*, Lazy*, Loop*, Fiber*, Thread*, Hash*, Backtrace*, Exception*, Raise*, Rescue*) + pass in five verbose runs on base and new and four plain runs of new. One more plain run of new + aborted on an unhandled ThreadInterruptedException in a new thread's start (RubyThreadInfo.Lookup, + interrupted by Thread#raise's delivery), and one of four plain runs of base failed + `Fiber_ThreadRaiseInSwitchBookkeeping1`: Thread#raise around thread and fiber starts is flaky on + both. + - **perf/extiter3 (2026-11-26) - `with_index`, `each_with_index` and `with_object` enumerators take `next` on a cursor over their source's (gap 35)** - not gated. Base 1efd7e6 (the merged branch at 2f8c31c with perf/extiter2). The prelude's Enumerator#with_index (and so From 69a54878a2b359a187e63dbaed78b41bdb1fc404 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:26:20 +0000 Subject: [PATCH 080/439] Ledger: perf/singleton (round thirty-seven, gaps 32 and 19) Landed entry with the instruction counts, matrices and specs, and under gap 32 what the profile found and was not taken: the shared rule per (method, receiver type, delegate type) that two sites with arguments of different types fight over, about 45 ms of per-object binds in a process's first OpenStructs; the reader binds; Ractor.shareable_proc and DefineMethod. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Util/perf/LEDGER.md | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..0e3fe8eea 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1384,6 +1384,24 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has two ConditionalWeakTable entries onto the Proc measured nothing. Next idea: a lock-free test for a singleton class with no mixins that does not define the name itself (it resolves as its superclass), at most about 10%. + Round thirty-seven (see Landed, perf/singleton, not gated): that idea, taken further - a + singleton class with no modules of its own answers every name it has no entry for from its + superclass's lookup cache, lock-free, and the shared rule's test reads that cache. The + profile behind it (callgrind with the CLR's perf map, 300 steady-state `os_app` objects, + 672K instructions each): `TryShareVersion` -> `ResolveShared` and `FillMethodLookup` about + 90K and 65K an object - some thirty fills per object, each walking the ancestors and copying + the singleton class's whole cache table to file one name, because each definition empties + it. `os_new` 0.77 of its instructions, `os_app` 0.84. + Left, measured but not taken: (1) a shared rule is one per (method, receiver type, delegate + type), so two sites calling one method with arguments of different types share it, and the + second gets a rule of its own built for each object (~200 us, `IR_BIND_TRACE` "shared-new"): + OpenStruct's `define_singleton_method!(name, ...)` (a Symbol) and `("#{name}=", ...)` (a + String) do, 220-240 binds in a process's first ~250 OpenStructs, until the interpreted + `new_ostruct_member!` is recompiled (also with `-X:NoJIT`), about 45 ms of warm-up. Several + shared rules per key, the next built when every one holds the version and none matched, + would end it. (2) The four reader binds per object (a dispatcher per new singleton class, + gap 19's "first call"), about 5% of `os_app`'s instructions. (3) `Ractor.shareable_proc` + some 5%, `ModuleOps.DefineMethod` some 11%. 33. **Three differences from CRuby in interpolation**, found by the probes of `Util/interpolation-matrix.rb` on the build before perf/interp and left as they were (the matrix avoids them); not speed gaps. When a part's `to_s` raises, the backtrace @@ -1450,6 +1468,47 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/singleton (round thirty-seven, 2026-11-26) - lookups on a re-versioned singleton class + answered from its superclass's cache (gaps 32, 19)** - not gated. Each definition on an object + that gets methods of its own (OpenStruct's `define_singleton_method!` of every member) + re-versions its singleton class and so empties the class's method lookup cache; every name asked + again - the `singleton_method_added` hook check, `respond_to?`, the shared rules' version test - + then walked the ancestors under the class hierarchy lock and copied the cache's whole table to + file one entry, about thirty times per OpenStruct. Now a singleton class of a plain object with + no modules of its own and at most 16 methods keeps a snapshot of its own method names per + version (`RubyModule.InheritedLookups`) and answers every other name from its superclass's + cache, which stays warm across all such objects, without the lock and without filing. The + superclass's fill registered the answer for invalidation, so defining that name re-versions the + singleton class; defining a name nobody asked for does not, so every change of a module's + method table or modules drops the snapshot under the lock, and a reader checks after taking the + superclass's answer that the snapshot is still current (a superclass fill that registered the + name took the lock after any definition that had not seen the registration). And + `RubyCallAction.TryShareVersion` takes a new version from that cache when it finds the rule's + method there, at a visibility the call sees, before resolving under the lock + (`TryShareVersionFromLookup`; not for method_missing, a refined name, a protected method). + `IR_SINGLETON_LOOKUP=0` turns both off. + Instructions per call (`Util/perf/callgrind/count.sh`, N=200; base / off / new): + `ostr36-shapes.rb` `os_new` 232,692 / 233,695 / 180,601 + (0.77), `os_write` 391,933 / 394,835 / 317,172 (0.80), `os_app` 565,493 / 576,944 / 482,054 (0.84), + `dsm_blk_call` 73,982 / 89,375 / 70,403 (0.95 of base), `dsm_tbl_call` 78,759 / 78,681 / 74,836 (0.95); + `app-shapes.rb` `ostruct` 5,808,127 / 5,829,182 / 4,932,345 (0.85); controls level: `delegate` + 9,469,818 / 9,470,041 / 9,473,484, `forwardable` 4,204,623 / 4,163,226 / 4,204,592. Not timed + (timing on this machine spread more than the change); `sdef-shapes.rb` has no counter. + `Util/sdef-matrix.rb` section 12 (new: a name defined that nobody had asked for, `def o.x` after + lookups, undef/remove and `private` in the singleton class, a private forwarder in a subclass, + protected, `respond_to_missing?` and `method_missing` added to the class later, the + `singleton_method_added` hook, include and prepend into the singleton class, `extend` of a module + with `extended`, a refinement, two threads defining and removing while a third asks) prints CRuby + 4.0's output on both builds; with the snapshot drop after a definition taken out, its first two + rows go wrong. `gate-matrices.rb` on hot-shapes, shared-rule-light, jit, jit-calls, sdef, extend, + respond-to, refinement, prepend (both), dmeth, struct, delegate and forwardable, in the seven + modes with `IR_SINGLETON_LOOKUP=0`: PASS (83 same, 15 baseline: struct-matrix and hot-shapes + differ from CRuby only as the baseline does). ruby/spec: library/openstruct, and + core/kernel define_singleton_method, extend, singleton_class, singleton_methods, respond_to, + public_send, method, core/basicobject/singleton_method_added, core/module method_defined, + prepend, include, refine, private, remove_method, undef_method, language/def, core/marshal/dump: + no failures on either build. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From eaeaaad0578bfac7a52cd339e92d84e719dec4af Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:35:58 +0000 Subject: [PATCH 081/439] A block that holds a block literal reuses its scope and the literal's Proc A block whose body has a block literal (`a.each { |x| o.e { |c| s += c } }`, Richards' worker block, prism walks) made a scope, a Proc and a BlockParam on every call: the literal's Proc is over the block's scope, so BlockDefinition never let such a block reuse its scope, and the literal's #proc variable is a CLR local of the block's frame. A literal written in a block's own body now registers with the block and is made by RubyOps.InstantiateNestedParkedBlock. A block all of whose literals do so reuses its scope as a block without one does: at the normal end of a call whose scope LeaveReusableBlockScope kept on the BlockParam, ParkNestedProc keeps the last Proc of each literal on the scope (RubyBlockScope.ParkedNested, with the thread) if nothing but the frame holds it (Proc.IsReusableAndInactive); otherwise UnparkBlockScope takes the scope back. A Proc the same call replaced marks the scope captured. The next call that takes the scope makes the kept Procs again with its self, dropping BlockParams made on another thread. A lambda, a literal that does not reuse its Proc or one in a module body in the block keeps the old path. IR_PARKED_BLOCK_SCOPES=0 (or IR_PARKED_SCOPES=0) is the old code. The literal inside a block: 302 -> 46 B per call, 0.51-0.70 of the time; alloc.rb: Richards 12.8 -> 2.4 MB per iteration, geomean 0.889. Every RubyBlockScope is 8 B larger. Util/block-nest-reuse-matrix.rb (new) and ten block/frame matrices in seven modes print what CRuby and the unchanged build print; Util/bench/nest-shapes.rb has the shapes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Ruby/Compiler/Ast/BlockDefinition.cs | 45 +++- Src/Ruby/Compiler/AstGenerator.cs | 6 + .../Compiler/ReflectionCache.Generated.cs | 6 + Src/Ruby/Runtime/RubyOps.cs | 90 ++++++++ Src/Ruby/Runtime/RubyScope.cs | 5 + Util/bench/nest-shapes.rb | 68 +++++++ Util/block-nest-reuse-matrix.rb | 192 ++++++++++++++++++ 7 files changed, 408 insertions(+), 4 deletions(-) create mode 100644 Util/bench/nest-shapes.rb create mode 100644 Util/block-nest-reuse-matrix.rb diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index 16a6af808..d9c8ed88f 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -172,6 +172,13 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St return parameters; } + /// + /// IR_PARKED_BLOCK_SCOPES=0 (or IR_PARKED_SCOPES=0) makes a block that holds a block literal make a new scope and new + /// Procs on every call, as it did before round thirty-seven (see RubyOps.InstantiateNestedParkedBlock). + /// + internal static readonly bool ParkedBlockScopesEnabled = MethodDefinition.ParkedScopesEnabled && + Environment.GetEnvironmentVariable("IR_PARKED_BLOCK_SCOPES") != "0"; + private ScopeBuilder/*!*/ DefineLocals(ScopeBuilder/*!*/ parentBuilder) { return new ScopeBuilder(_definedScope.AllocateClosureSlotsForLocals(0), parentBuilder, _definedScope); } @@ -319,8 +326,11 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St // A body that needs its scope but defines no closure over it can reuse the scope of the // previous call of the block, unless something captured that (see RubyScope.IsCaptured). - // A nested block literal is a Proc over the scope on every call: nothing to reuse. - bool reuseScope = lazyScope == null && !hasNestedReturn && !gen.CurrentBlock.HasNestedBlock && + // A nested block literal is a Proc over the scope on every call: the scope is reused only if each + // literal in the body reuses its Proc, and is kept with the last one (RubyOps.ParkNestedProc). + var nestedProcs = gen.CurrentBlock.ParkProcVariables; + bool parkNested = ParkedBlockScopesEnabled && nestedProcs != null && !gen.CurrentBlock.HasUnparkableNestedBlock; + bool reuseScope = lazyScope == null && !hasNestedReturn && (!gen.CurrentBlock.HasNestedBlock || parkNested) && !gen.TraceEnabled && !gen.CompilerOptions.IsEval; // The same holds for the Proc of the literal (see BlockDispatcher.ReusesProc). @@ -342,7 +352,20 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St var result = scope.DefineHiddenVariable("#result", typeof(object)); bool keepLocals = scope.HasReusableLocals; MSA.Expression leave = Methods.LeaveReusableBlockScope.OpCall(scopeVariable, AstUtils.Constant(keepLocals)); - if (keepLocals) { + if (gen.CurrentBlock.HasNestedBlock) { + // the scope was kept on the BlockParam: with the last Proc of each literal if none may be held elsewhere, + // or not at all + MSA.Expression staged = null; + for (int i = 0; i < nestedProcs.Count; i++) { + var stage = Methods.ParkNestedProc.OpCall(scopeVariable, AstUtils.Constant(i), AstUtils.Constant(nestedProcs.Count), + nestedProcs[i]); + staged = (staged == null) ? stage : Ast.AndAlso(staged, stage); + } + var unpark = Methods.UnparkBlockScope.OpCall(scopeVariable); + leave = Ast.IfThen(leave, keepLocals + ? Ast.IfThenElse(staged, scope.MakeClearLocals(), unpark) + : Ast.IfThen(Ast.Not(staged), unpark)); + } else if (keepLocals) { leave = Ast.IfThen(leave, scope.MakeClearLocals()); } body = Ast.Block( @@ -434,10 +457,24 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St // either, but its hidden variable is the module body's, which the method's staging code cannot reach. var parkSlot = gen.CurrentMethod.ParkSlot; MSA.Expression instantiateReusable = null; - if (reusesProc && parkSlot != null && gen.CurrentBlock == null && gen.CurrentScope == gen.CurrentMethod.Builder) { + // A literal written in the body of a block is kept with the block's scope when the block reuses that + // (RubyOps.InstantiateNestedParkedBlock); any other literal nested in a block keeps the block from reusing its scope. + var outerBlock = gen.CurrentBlock; + if (reusesProc && parkSlot != null && outerBlock == null && gen.CurrentScope == gen.CurrentMethod.Builder) { instantiateReusable = Methods.InstantiateParkedBlock.OpCall(previousProc, gen.CurrentScopeVariable, gen.CurrentSelfVariable, dispatcher, gen.CurrentMethod.ParkedVariable, AstUtils.Constant(gen.CurrentMethod.ParkProcVariables.Count)); gen.CurrentMethod.ParkProcVariables.Add(previousProc); + } else if (outerBlock != null && !(reusesProc && gen.CurrentScope == outerBlock.Builder)) { + outerBlock.HasUnparkableNestedBlock = true; + if (reusesProc) { + instantiateReusable = Methods.InstantiateReusableBlock.OpCall(previousProc, gen.CurrentScopeVariable, gen.CurrentSelfVariable, dispatcher); + } + } else if (outerBlock != null && ParkedBlockScopesEnabled) { + var nested = outerBlock.ParkProcVariables ?? (outerBlock.ParkProcVariables = new System.Collections.Generic.List()); + instantiateReusable = Methods.InstantiateNestedParkedBlock.OpCall(previousProc, + AstUtils.Convert(gen.CurrentScopeVariable, typeof(RubyBlockScope)), gen.CurrentSelfVariable, dispatcher, + AstUtils.Constant(nested.Count)); + nested.Add(previousProc); } else if (reusesProc) { instantiateReusable = Methods.InstantiateReusableBlock.OpCall(previousProc, gen.CurrentScopeVariable, gen.CurrentSelfVariable, dispatcher); } diff --git a/Src/Ruby/Compiler/AstGenerator.cs b/Src/Ruby/Compiler/AstGenerator.cs index 2df842a60..4dbb49e07 100644 --- a/Src/Ruby/Compiler/AstGenerator.cs +++ b/Src/Ruby/Compiler/AstGenerator.cs @@ -356,6 +356,12 @@ public MSA.LabelTarget/*!*/ RedoLabel { // A block literal (or lambda) is nested in this one: its Proc captures this block's scope. public bool HasNestedBlock; + // The hidden variables that hold the last Proc of each block literal written directly in this block's body, which + // the block keeps with its scope when it reuses that (BlockDefinition.ParkedBlockScopesEnabled); and whether a literal + // nested in it cannot be kept so: a lambda, a literal that does not reuse its Proc, one in a module body in the block. + internal List ParkProcVariables; + internal bool HasUnparkableNestedBlock; + // The lexical depth of the block's own scope (LexicalScope.Depth): a local defined at a // smaller depth belongs to an enclosing scope. internal int LexicalDepth; diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 78461b40d..cab543719 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -360,6 +360,8 @@ public static partial class Methods { private static MethodInfo _InstantiateBlock; public static MethodInfo/*!*/ InstantiateLambda { get { return _InstantiateLambda ?? (_InstantiateLambda = CallInstruction.CacheFunc(RubyOps.InstantiateLambda)); } } private static MethodInfo _InstantiateLambda; + public static MethodInfo/*!*/ InstantiateNestedParkedBlock { get { return _InstantiateNestedParkedBlock ?? (_InstantiateNestedParkedBlock = CallInstruction.CacheFunc(RubyOps.InstantiateNestedParkedBlock)); } } + private static MethodInfo _InstantiateNestedParkedBlock; public static MethodInfo/*!*/ InstantiateParkedBlock { get { return _InstantiateParkedBlock ?? (_InstantiateParkedBlock = CallInstruction.CacheFunc(RubyOps.InstantiateParkedBlock)); } } private static MethodInfo _InstantiateParkedBlock; public static MethodInfo/*!*/ InstantiateReusableBlock { get { return _InstantiateReusableBlock ?? (_InstantiateReusableBlock = CallInstruction.CacheFunc(RubyOps.InstantiateReusableBlock)); } } @@ -570,6 +572,8 @@ public static partial class Methods { private static MethodInfo _ObjectToMutableString; public static MethodInfo/*!*/ ObjectToString { get { return _ObjectToString ?? (_ObjectToString = CallInstruction.CacheFunc(RubyOps.ObjectToString)); } } private static MethodInfo _ObjectToString; + public static MethodInfo/*!*/ ParkNestedProc { get { return _ParkNestedProc ?? (_ParkNestedProc = CallInstruction.CacheFunc(RubyOps.ParkNestedProc)); } } + private static MethodInfo _ParkNestedProc; public static MethodInfo/*!*/ PassOnKeywordRest { get { return _PassOnKeywordRest ?? (_PassOnKeywordRest = CallInstruction.CacheFunc(RubyOps.PassOnKeywordRest)); } } private static MethodInfo _PassOnKeywordRest; public static MethodInfo/*!*/ PopKeywordArguments { get { return _PopKeywordArguments ?? (_PopKeywordArguments = CallInstruction.CacheFunc(RubyOps.PopKeywordArguments)); } } @@ -740,6 +744,8 @@ public static partial class Methods { private static MethodInfo _TryToStringValidator; public static MethodInfo/*!*/ UndefineMethod { get { return _UndefineMethod ?? (_UndefineMethod = CallInstruction.CacheAction(RubyOps.UndefineMethod)); } } private static MethodInfo _UndefineMethod; + public static MethodInfo/*!*/ UnparkBlockScope { get { return _UnparkBlockScope ?? (_UnparkBlockScope = CallInstruction.CacheAction(RubyOps.UnparkBlockScope)); } } + private static MethodInfo _UnparkBlockScope; public static MethodInfo/*!*/ Unsplat { get { return _Unsplat ?? (_Unsplat = CallInstruction.CacheFunc(RubyOps.Unsplat)); } } private static MethodInfo _Unsplat; public static MethodInfo/*!*/ UpdateProfileTicks { get { return _UpdateProfileTicks ?? (_UpdateProfileTicks = CallInstruction.CacheAction(RubyOps.UpdateProfileTicks)); } } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 0df3ee308..82787c002 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -746,6 +746,96 @@ public static bool LeaveReusableBlockScope(RubyBlockScope/*!*/ scope, bool keepL return scope.BlockFlowControl.ParkScope(scope); } + // A block that holds block literals - `a.each { |x| x.each_child { |c| s += c } }' - made a scope, and a Proc and a + // BlockParam per literal, on every call: the literals' Procs are over the block's scope, so it could not be reused. It + // is now, when each literal is written in the block's own body and reuses its Proc (BlockDispatcher.ReusesProc): at + // the normal end of a call that kept the scope on its BlockParam (LeaveReusableBlockScope), the last Proc of each + // literal is kept with the scope if nothing but the block's frame holds it (Proc.IsReusableAndInactive: given to light + // frames and [BlockNotKept] iterators only, and no scope it ran in captured); otherwise the scope is not kept either. The + // next call that takes the scope makes those Procs again for the literals. A Proc of a literal that the same call + // replaced may be held anywhere and reaches the scope: it marks the scope captured. IR_PARKED_BLOCK_SCOPES=0 turns it off. + + /// + /// InstantiateReusableBlock of a literal (the index-th) written in the body of a block: the Proc kept with the block's + /// scope by the call that last used the scope, if there is one. + /// + [Emitted] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Proc InstantiateNestedParkedBlock(Proc previous, RubyBlockScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher, + int index) { + if (previous == null && scope.ParkedNested == null) { + return dispatcher.HasMethod ? new Proc(ProcKind.Block, self, scope, dispatcher) : null; + } + return InstantiateNestedParkedBlockSlow(previous, scope, self, dispatcher, index); + } + + private static Proc InstantiateNestedParkedBlockSlow(Proc previous, RubyBlockScope/*!*/ scope, object self, + BlockDispatcher/*!*/ dispatcher, int index) { + if (previous != null) { + if (previous.TryReuse()) { + return previous; + } + scope.IsCaptured = true; + } else { + Proc proc; + var parked = scope.ParkedNested; + var procs = parked as Proc[]; + if (procs != null) { + proc = procs[index]; + procs[index] = null; + } else { + proc = (Proc)parked; + scope.ParkedNested = null; + } + if (proc != null) { + proc.ReuseParked(self, scope.ParkedNestedThreadId != Environment.CurrentManagedThreadId); + if (proc.TryReuse()) { + return proc; + } + } + } + return dispatcher.HasMethod ? new Proc(ProcKind.Block, self, scope, dispatcher) : null; + } + + /// + /// Keeps the last Proc of the index-th of literals of a block with the block's scope, which + /// LeaveReusableBlockScope has kept on the BlockParam; false if something else may hold the Proc (UnparkBlockScope then + /// takes the scope back). A literal the call did not reach keeps what was kept. + /// + [Emitted] + public static bool ParkNestedProc(RubyBlockScope/*!*/ scope, int index, int count, Proc proc) { + if (proc == null) { + return true; + } + if (!proc.IsReusableAndInactive) { + return false; + } + int threadId = Environment.CurrentManagedThreadId; + if (count == 1) { + scope.ParkedNested = proc; + } else { + var procs = scope.ParkedNested as Proc[]; + if (procs == null) { + scope.ParkedNested = procs = new Proc[count]; + } else if (scope.ParkedNestedThreadId != threadId) { + // the Procs another thread kept carry its BlockParams: one ParkedNestedThreadId is for all of them + Array.Clear(procs, 0, procs.Length); + } + procs[index] = proc; + } + scope.ParkedNestedThreadId = threadId; + return true; + } + + /// + /// A block scope LeaveReusableBlockScope kept on its BlockParam that cannot be reused after all: a Proc of a literal + /// in the block may be held elsewhere (ParkNestedProc). + /// + [Emitted] + public static void UnparkBlockScope(RubyBlockScope/*!*/ scope) { + scope.BlockFlowControl.TakeReusableScope(); + } + [Emitted] public static RubyBlockScope/*!*/ CreateBlockScopeLazy(MutableTuple locals, string[] variableNames, BlockParam/*!*/ blockParam, object selfObject, InterpretedFrame interpretedFrame) { diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 9c64af656..0058a2420 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1783,6 +1783,11 @@ public BlockParam/*!*/ BlockFlowControl { // (and catches a LambdaUnwinder aimed at this scope), 2 once it has finished. internal byte LambdaReturnState; + // The last Procs of the block literals in the body, kept with the scope for the call that reuses it (a Proc for one + // literal, a Proc[] for more; see RubyOps.ParkNestedProc), and the thread that kept them. Not cleared by Reinitialize. + internal object ParkedNested; + internal int ParkedNestedThreadId; + public override string[] OwnImplicitParameterNames { get { var signature = _blockFlowControl.Proc.Dispatcher.ParameterSignature; diff --git a/Util/bench/nest-shapes.rb b/Util/bench/nest-shapes.rb new file mode 100644 index 000000000..b24b3f1a5 --- /dev/null +++ b/Util/bench/nest-shapes.rb @@ -0,0 +1,68 @@ +# A block literal inside a block (round thirty-seven, perf/iter): the block that holds it made a scope, and a Proc and a +# BlockParam for the literal, on every call (BlockDefinition.ParkedBlockScopesEnabled, IR_PARKED_BLOCK_SCOPES). ns per call +# of the outer block; the switch is the third arm: +# +# ruby Util/perf/ab.rb -i Util/bench/nest-shapes.rb "off=env IR_PARKED_BLOCK_SCOPES=0 IR_CONFIG=Release ./ir.sh" \ +# "on=env IR_CONFIG=Release ./ir.sh" +# +# light, each, times, two, kids and el3 are the ones it is for (the outer block runs many times through one BlockParam); +# el2 and once run their outer block twice and once per BlockParam, where nothing is reused (what it costs there); +# flat, noblk and meth have no literal inside a block (controls). +$stdout.sync = true + +class O + def e; yield 1; end + def kids; yield 1; yield 2; end + def f; 1; end + def sh_each(a); s = 0; a.each { |x| s += x }; s; end +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the seven sections as the +# time is. See Util/perf/instructions.rb. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-12s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +o = O.new +N = (ENV['N'] || 500_000).to_i +a1 = [1] +a2 = [1, 2] +a3 = [1, 2, 3] + +t("light", N) { |n| s = 0; n.times { o.e { |c| s += c } }; s } +t("each", N) { |n| s = 0; n.times { a1.each { |c| s += c } }; s } +t("times", N) { |n| s = 0; n.times { 1.times { |c| s += c + 1 } }; s } +t("two", N) { |n| s = 0; n.times { o.e { |c| s += c }; a1.each { |c| s += c } }; s } +t("kids", N) { |n| s = 0; n.times { |x| o.kids { |c| s += c + x } }; s } +t("el3", N) { |n| i = 0; s = 0; while i < n; a3.each { |x| o.e { |c| s += c + x } }; i += 3; end; s } +t("el2", N) { |n| i = 0; s = 0; while i < n; a2.each { |x| o.e { |c| s += c + x } }; i += 2; end; s } +t("once", N) { |n| i = 0; s = 0; while i < n; o.e { |x| a1.each { |c| s += c + x } }; i += 1; end; s } +t("flat", N) { |n| s = 0; n.times { |x| s += x }; s } +t("noblk", N) { |n| s = 0; n.times { s += o.f }; s } +t("meth", N) { |n| i = 0; s = 0; while i < n; s += o.sh_each(a1); i += 1; end; s } diff --git a/Util/block-nest-reuse-matrix.rb b/Util/block-nest-reuse-matrix.rb new file mode 100644 index 000000000..3b90d3f3c --- /dev/null +++ b/Util/block-nest-reuse-matrix.rb @@ -0,0 +1,192 @@ +# Differential checks for a block that holds a block literal (round thirty-seven, perf/iter). +# +# A block whose body needs its scope reuses the scope of the previous call through the same BlockParam +# (block-scope-reuse-matrix.rb); one with a block literal in it reuses it too, with the Procs of its +# literals, when the last Proc of each was given only to light frames and [BlockNotKept] iterators and +# nothing captured the scope. Each outer block below runs several times through one BlockParam, so the +# second and later calls take that path; every way the inner Proc or the outer scope can escape is a row. +# The output must match CRuby's and the unchanged build's, with IR_PARKED_BLOCK_SCOPES=0 too: +# +# ruby Util/block-nest-reuse-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/block-nest-reuse-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +# +# (also with -X:NoJIT -X:NoOSR, IR_LIGHT_FRAMES=0 and IR_PARKED_SCOPES=0) + +class O + def e; yield 1; end + def e2; yield 1; yield 2; end + def keep(&b); (@kept ||= []) << b; nil; end + def kept; @kept; end + def ivar_keep(&b); @blk = b; nil; end + def blk; @blk; end + def yield_self_class; yield self.class; end +end +o = O.new + +# the plain case: the inner block reads and writes the outer block's locals and the method's +s = 0 +[1, 2, 3, 4].each { |x| y = x * 10; o.e { |c| s += c + x + y } } +p s +r = [] +[1, 2, 3].each { |x| o.e2 { |c| r << [x, c] } } +p r +r = [] +3.times { |i| [10, 20].each { |v| r << v + i } } +p r + +# an outer local starts nil on every call of the outer block, whatever the last call left in it +r = [] +[1, 2, 3].each { |x| y ||= x; o.e { |c| y += c }; r << y } +p r +r = [] +[1, 2, 3].each { |x| r << defined?(z).inspect; o.e { |c| r << c }; z = x; r << z } +p r + +# the inner Proc kept by a method (&b), then called after the outer block has run again +o2 = O.new +[1, 2, 3].each { |x| y = x * 2; o2.keep { [x, y] } } +p o2.kept.map(&:call) +o3 = O.new +[1, 2, 3, 4].each { |x| y = x; if x.even? then o3.keep { y } else o.e { |c| y += c } end } +p o3.kept.map(&:call) + +os = [O.new, O.new, O.new] +[0, 1, 2].each { |x| y = x * 3; os[x].ivar_keep { y + x } } +p os.map { |q| q.blk.call } + +# the inner literal made several times in one call, the middle one kept +o4 = O.new +[1, 2, 3].each { |x| i = 0; while i < 3; i += 1; if i == 2 then o4.keep { [x, i] } else o.e { |c| c } end; end } +p o4.kept.map(&:call) + +# proc, lambda, Proc.new and a block made a method +ps = [] +[1, 2, 3].each { |x| y = x + 1; ps << proc { y }; o.e { |c| c } } +p ps.map(&:call) +ls = [] +[1, 2, 3].each { |x| y = x + 2; ls << -> { y }; o.e { |c| c } } +p ls.map(&:call) +ls = [] +[1, 2, 3].each { |x| y = x + 3; o.e { |c| ls << lambda { y + c } } } +p ls.map(&:call) +class DefIn2 + [1, 2].each { |x| y = x * 5; define_method("m#{x}") { y }; [0].each { |z| z } } +end +p [DefIn2.new.m1, DefIn2.new.m2] + +# a Binding of the outer scope, or of the inner block's, taken in the inner block +bs = [] +[1, 2, 3].each { |x| y = x * 7; o.e { |c| bs << binding } } +p bs.map { |b| [b.local_variable_get(:x), b.local_variable_get(:y), b.local_variable_get(:c)] } +bs = [] +[1, 2, 3].each { |x| y = x * 9; o.e { |c| c }; bs << binding } +p bs.map { |b| [b.local_variable_get(:x), b.local_variable_get(:y)] } +r = [] +[1, 2, 3].each { |x| o.e { |c| r << eval("x + c") } } +p r + +# a block kept by the core: a Hash's default proc, an Enumerator, a lazy map, a Thread +hs = [] +[1, 2, 3].each { |x| hs << Hash.new { |h, k| h[k] = k * x }; o.e { |c| c } } +p hs.map { |h| h[2] } +es = [] +[1, 2, 3].each { |x| es << Enumerator.new { |y| y << x; y << x * 2 } } +p es.map(&:to_a) +lz = [] +[1, 2, 3].each { |x| lz << [x].lazy.map { |v| v + x } } +p lz.map(&:to_a) +ts = [] +[1, 2, 3].each { |x| y = x * 4; ts << Thread.new { y + 1 } } +p ts.map(&:value) + +# break, next, return and an exception from the inner block and from the outer one +r = [] +[1, 2, 3, 4].each { |x| v = o.e { |c| break x * 100 if x == 2; c + x }; r << v } +p r +r = [] +[1, 2, 3, 4].each { |x| v = o.e { |c| next x * 10 if x.odd?; c }; r << v } +p r +r = [] +res = [1, 2, 3, 4].each { |x| o.e { |c| r << c + x }; break :out if x == 3 } +p [r, res] +def ret_from_inner(o, a) + a.each { |x| o.e { |c| return [:ret, x] if x == 2 } } + :none +end +p [ret_from_inner(o, [1, 2, 3]), ret_from_inner(o, [1, 3]), ret_from_inner(o, [5, 2])] +r = [] +[1, 2, 3, 4].each { |x| + begin + o.e { |c| raise "boom #{x}" if x == 2; r << x } + rescue => e + r << e.message + end +} +p r +r = [] +3.times { + begin + [1, 2, 3].each { |x| y = x; o.e { |c| raise ArgumentError, "a#{y}" if y == 2; r << y } } + rescue ArgumentError => e + r << e.message + end +} +p r + +# recursion through the outer block's own Proc, and through the iterator +r = [] +pr = proc { |n| y = n * 2; o.e { |c| r << [n, y]; pr.call(n - 1) if n > 0; r << [:back, n, y] } } +pr.call(3) +pr.call(1) +p r +def walk(o, n, r) + [n, n + 10].each { |x| o.e { |c| r << x; walk(o, n - 1, r) if n > 0 && x == n } } +end +r = [] +walk(o, 2, r) +p r + +# a different self for the same outer block (define_method, instance_exec) +class SelfA; end +class SelfB; end +blk = proc { |x| o.e { |c| [self.class, x] } } +SelfA.define_method(:m, &blk) +SelfB.define_method(:m, &blk) +p [SelfA.new.m(1), SelfB.new.m(2), SelfA.new.m(3), SelfB.new.m(4)] +r = [] +[1, 2, 3].each { |x| r << (x.even? ? "s" : 5).instance_exec(x) { |v| o.e { |c| [self, v] } } } +p r + +# a fiber suspended in the inner block while the outer block runs again +fs = [] +[1, 2, 3].each { |x| y = x; fs << Fiber.new { o.e { |c| Fiber.yield y; y += 10 }; y } } +p fs.map(&:resume) +p fs.map(&:resume) +en = Enumerator.new { |yy| [1, 2, 3].each { |x| o.e2 { |c| yy << [x, c] } } } +p [en.next, en.next, en.next, en.peek] + +# two literals in the outer block, one of them kept, and one in a nested module body +o5 = O.new +[1, 2, 3].each { |x| o.e { |c| c }; o5.keep { x } if x != 2; [x].each { |v| v } } +p o5.kept.map(&:call) +r = [] +[1, 2].each { |x| class << Object.new; [1].each { |v| v }; end; o.e { |c| r << x } } +p r + +# threads running one outer block at once, each checking its own locals +pr2 = proc { |t, k| y = t * 1000 + k; z = nil; o.e { |c| z = y + c }; z == y + 1 } +ok = 4.times.map { |t| Thread.new { (1..2000).all? { |k| pr2.call(t, k) } } }.map(&:value) +p ok +ok = 4.times.map { |t| Thread.new { (1..2000).all? { |k| [k].each { |x| y = t * 1000 + x; o.e { |c| y += c } ; raise "t#{t}" unless y == t * 1000 + x + 1 } } } }.map(&:value) +p ok + +# a TracePoint enabled between calls +r = [] +tp = TracePoint.new(:b_call) { |t| r << t.binding.local_variable_defined?(:x) if t.path == __FILE__ && t.lineno == __LINE__ + 3 } +[1, 2, 3, 4].each { |x| + tp.enable if x == 3 + o.e { |c| c + x } +} +tp.disable +p r From e7cb1c35e24e4e04857ea6d9edcead7141f92fce Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:35:59 +0000 Subject: [PATCH 082/439] Ledger: perf/iter, a block holding a literal reuses its scope (gaps 13 and 6) Landed, not gated, with the instruction counts, bytes, matrices and what the gate should look at; gap 13 gets round thirty-seven's measurements of the four parts against CRuby, gap 6 that Richards allocates 12.8 MB per iteration again and 2.4 with this. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Util/perf/LEDGER.md | 72 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..be9a1f7c2 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -768,6 +768,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Closed in round ten: with `DATA_SIZE.times { }` rewritten as a `while` loop Richards allocates 3,204,249 bytes per iteration against 3,198,021 as written, so the inner block costs nothing measurable any more (round nine runs it in the compiled copy). + Round thirty-seven: it allocates 12.8 MB per iteration again (alloc.rb, 2f8c31c), and + perf/iter's reuse of a block holding a literal takes it to 2.4 MB (see Landed). 7. **Json**: the 40 B String per character read is what is left of `@input[@index]` (its content is shared now); two Integer boxes per `read` (`@input.length`, `@index += 1` - see Rejected, perf/box, for what caching them buys and costs); @@ -924,6 +926,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the walk about 12% faster and a megamorphic call without a block 2.2 times slower: reverted. A per-site table from class to dispatcher is worth at most about 10% of the walk. `Prism.parse` itself (not in the shape) is 8 times CRuby's. + Round thirty-seven (perf/iter, see Landed, not gated) measured the four parts on one + element against CRuby: a literal inside a block 111 ns and 302 B against 44 (`n.times { + o.e { |c| s += c } }`), `each1` 131/77 B against 72, a Ruby-level iterator 125/77 B + against 55, `upto1` 151/389 B against 70, `any1` 149/374 B against 52, `find1` 292/885 B + against 66, `each_with_index1` 415/1205 B against 134, `(1..k).each` 120/117 B against + 141. It took the first: a block holding a literal now reuses its scope and the literal's + Proc as a block without one reuses its scope - 302 -> 46 B (what a call without a block + allocates), 0.51-0.70 of the time. Left: `any?`, `find` and `each_with_index` (Enumerable's + C# goes through `each` and a SplattingBlock: the bytes are its own, not the parking's) and + the literal given to a core iterator outside the parked list. 14. **DeltaBlue: `Vector#each`** (`(@first_idx..(@last_idx - 1)).each { |i| yield @storage[i] }`) is about 20% of its samples by nearest Ruby frame (8.9% the method, 11.3% its block), and no call site owns more than 1.2% of the 24% in @@ -1450,6 +1462,66 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/iter (round thirty-seven, 2026-11-26) - a block that holds a block literal reuses its scope + and the literal's Proc (gaps 13 and 6)** - instructions and bytes, not gated. A block whose + body has a block literal (`a.each { |x| o.e { |c| s += c } }`, Richards' worker block with + `DATA_SIZE.times { }`, prism's `each_child_node` walks) made a scope, a Proc and a BlockParam on + every call: the literal's Proc is over the block's scope, so `BlockDefinition` never let such a + block reuse its scope (`!HasNestedBlock`) nor the literal its Proc across calls (its `#proc` + variable is a CLR local of the block's frame). Now a literal written in a block's own body + registers with the block (`BlockScope.ParkProcVariables`) and is made by + `RubyOps.InstantiateNestedParkedBlock`; a block all of whose literals do so reuses its scope as a + block without one does. At the normal end of a call whose scope `LeaveReusableBlockScope` kept on + the BlockParam, `ParkNestedProc` keeps the last Proc of each literal on the scope + (`RubyBlockScope.ParkedNested`, a Proc or a Proc[], and the thread) if `IsReusableAndInactive`, + and otherwise `UnparkBlockScope` takes the scope back: a Proc given to anything but a light frame + or a [BlockNotKept] iterator, or a scope it ran in captured, keeps the scope from being reused. A + Proc of a literal the same call replaced may be held anywhere and reaches the scope: it marks the + scope captured (as `InstantiateParkedBlock` does for a method). The next call that takes the + scope makes the kept Procs again (`Proc.ReuseParked` with its self, dropping the BlockParam + another thread made). A lambda, a literal that does not reuse its Proc, or one in a module body + inside the block keeps the old path (`HasUnparkableNestedBlock`). The first call through a + BlockParam still keeps nothing (`ParkScope`), so a block run once per BlockParam pays only the + field. `IR_PARKED_BLOCK_SCOPES=0` (or `IR_PARKED_SCOPES=0`) is the old code. + Bytes per call (`Util/bench/nest-shapes.rb`, the thread's allocated bytes): the literal inside a + block 302 -> 46 B, the same as a call without a block. Instructions (callgrind, new over the + switch off): `light` 0.927, `each` 0.910, `two` 0.946, `kids` 0.953, `el3` 0.999, `el2` 1.026 + (two elements: the second call keeps the scope and nothing reuses it), `once` 1.012 (a first run + of the whole file said 2.509 for it; counted again alone, twice, 1.012), controls `flat` 1.004, + `noblk` 1.001, `meth` 0.978. Time, four alternating rounds on a host at load 2-20: `light` 110 -> + 66 ns (0.59; CRuby 48), `each` 114 -> 64 (0.51, overlapping; CRuby 64), `two` 168 -> 127 (0.70; + CRuby 104), `kids` 0.86, `el3` 0.94, `el2` 1.07 and `once` 1.00 overlapping. alloc.rb, all + fourteen: Richards 12,843,062 -> 2,444,179 B per iteration, Bounce 7,297,784 -> 5,471,207, + geomean 0.889; up: Sieve +1.3% (+1.6 MB, the same with the switch off: `ParkedNested` makes every + RubyBlockScope 8 B larger, and Sieve makes some 200,000 a iteration that are not reused), + DeltaBlue +0.4%, Permute +0.2%, Havlak +0.2%, CD +0.1%; Towers moves by a third between runs of + the same build (113 and 147 KB). AWFY under callgrind, instructions per benchmark call, new over + off: Richards 0.999, Bounce 0.998, DeltaBlue 1.000, Queens 0.998, Permute 1.000 - Richards' bytes + are not its time (its clock on the busy host: medians 4% either way between processes). + pwalk36: `walk` 0.995, `plain` 0.989, `each_child` 0.989 and `compact` 1.013 with 5-8% between + processes (prism's walk collects inside the sections). core-small under callgrind, new over + base: `each`, `inject`, `each_with_index`, `map_w_index`, `any`, `times`, `upto`, `range_each`, + `hash_each` 1.000, `find` 0.993, `group_by` 1.001. + Matrices (`Util/perf/gate-matrices.rb`, base 2f8c31c): `Util/block-nest-reuse-matrix.rb` (new: + &b kept by a method or in an ivar, the literal made three times in one call with the middle one + kept, proc, lambda, define_method, Binding of either scope, eval, a Hash default proc, an + Enumerator, lazy, a Thread, break/next/return/raise from the inner and the outer block, + recursion through the outer Proc and through the iterator, another self by define_method and + instance_exec, a Fiber suspended in the inner block, Enumerator#next, two literals one kept, a + literal in a `class << o` body, four threads calling one outer Proc and running one each, + TracePoint enabled between calls; CRuby's output on the unchanged build first), with + block-scope-reuse, -blockpass, -race, block-loop, block-given, light-rest, hot-shapes, jit, + parked-scope and block-pass, in the seven modes (as built, -X:NoJIT -X:NoOSR, -X:NoJITCalls, + IR_LIGHT_FRAMES=0, IR_PARKED_SCOPES=0, R2R, IR_PARKED_BLOCK_SCOPES=0): PASS, 69 same, 8 as the + baseline. A WeakRef probe (receiver and argument of a define_method body with a nested literal, + arguments of Procs called five times whose scope is kept, a method's arguments, instance_exec's + self): all freed, on both builds and CRuby. + For the gate: the 8 B on every block scope (the alternative is the Procs in hidden slots of the + block's locals tuple, which `MakeClearLocals` would skip); the Proc#call path, where a kept scope + and its Procs move between threads through `CallBlockParam` (the thread check in + `InstantiateNestedParkedBlockSlow`, and the Proc[] cleared when another thread keeps); and any + way a literal's Proc reaches Ruby without clearing its reusable flag. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 90d7ac36165d3b8e4822970e28dbd6ec34a32f37 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:42:08 +0000 Subject: [PATCH 083/439] String#tr! and #tr_s! check the encodings before frozenness, and an empty string first A frozen string given sets in an incompatible encoding raised FrozenError (`"b".encode("UTF-16LE").freeze.tr!("b", "x")`), and a frozen empty string raised FrozenError where CRuby answers nil. MRI's tr_trans returns nil for an empty string before anything else, checks the sets' encodings against the string's (rb_enc_check), and only then requires the string to be modifiable, even when nothing would change. Checked: String_TranslateCheckOrder1 (new; CRuby 4.0's output); spec/core/string tr, tr_s: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 31 ++++++++++++++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 20 ++++++++++++-- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 48d9b0a9a..57f24819b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1426,6 +1426,7 @@ public Tests(Driver/*!*/ driver) { String_ToIntAsciiIncompatible1, String_UndumpUnicodeEncoding1, String_OrdWide1, + String_TranslateCheckOrder1, Integer_ChrMultibyte1, String_Cesu8_1, String_EmacsMule1, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index 62d306ad6..a5b409285 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -759,6 +759,37 @@ def t(l) = puts(""#{l}: #{(yield rescue [$!.class, $!.message]).inspect}"") "); } + /// + /// #tr! and #tr_s! (MRI's tr_trans): an empty string is nil, frozen or not; the sets' encodings are checked + /// against the string's before the string is required to be modifiable. + /// + public void String_TranslateCheckOrder1() { + TestOutput(@" +f = ""abc"".freeze; e = """".freeze; u = ""b"".encode(""UTF-16LE"").freeze +[-> { f.tr!(""x"", ""y"") }, -> { f.tr!(""a"", ""y"") }, -> { e.tr!(""a"", ""b"") }, -> { u.tr!(""b"", ""x"") }, + -> { f.tr_s!(""x"", ""y"") }, -> { e.tr_s!(""a"", ""b"") }, -> { u.tr_s!(""b"", ""x"") }, -> { f.tr!("""", ""y"") }, + -> { f.delete!(""x"") }, -> { e.delete!(""x"") }, -> { f.squeeze! }, -> { e.squeeze! }, -> { u.delete!(""x"") }, -> { u.squeeze!(""x"") }, + -> { u.count(""x"") }, -> { f.tr!(1, 2) }].each { |l| p((l.call rescue $!)) } +", @" +# +# +nil +# +# +nil +# +# +# +nil +# +# +# +# +# +# +"); + } + /// /// Integer#chr and String#<< with an Integer, in the multibyte encodings: MRI's rb_enc_uint_chr takes the /// bytes of the number and accepts them when they are exactly one well formed character of the encoding - diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 86f69f38b..a9963bf13 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -6699,11 +6699,25 @@ public static MutableString Translate(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ from, [DefaultProtocol, NotNull]MutableString/*!*/ to) { bool anyCharacterMaps; - self.RequireNotFrozen(); + if (RequireTranslatable(self, from, to)) { + return null; + } Translate(self, from, to, true, false, out anyCharacterMaps); return anyCharacterMaps ? self : null; } + // MRI's tr_trans: an empty string is nil, frozen or not; then the encodings of the two sets are checked against the + // string's, and only then is the string required to be modifiable. True for the empty string. + private static bool RequireTranslatable(MutableString/*!*/ self, MutableString/*!*/ from, MutableString/*!*/ to) { + if (self.IsEmpty) { + return true; + } + self.RequireCompatibleEncoding(from); + self.RequireCompatibleEncoding(to); + self.RequireNotFrozen(); + return false; + } + // encoding aware, TODO: KCODE [RubyMethod("tr_s")] public static MutableString/*!*/ TrSqueeze(MutableString/*!*/ self, @@ -6718,7 +6732,9 @@ public static MutableString TrSqueezeInPlace(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ from, [DefaultProtocol, NotNull]MutableString/*!*/ to) { bool anyCharacterMaps; - self.RequireNotFrozen(); + if (RequireTranslatable(self, from, to)) { + return null; + } Translate(self, from, to, true, true, out anyCharacterMaps); return anyCharacterMaps ? self : null; } From b29880e696da0403a8f6cb55e340e579a0377ad4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:42:08 +0000 Subject: [PATCH 084/439] Integer#chr and String#<< say "invalid codepoint" for a code a single byte encoding has no room for `256.chr("US-ASCII")`, `300.chr("ISO-8859-1")`, `"".encode("Windows-1252") << 256` and every other code above 0xFF in a single byte encoding (BINARY and the dummy ones too) raised "256 out of char range"; CRuby 4.0 raises "invalid codepoint 0x100 in US-ASCII": its onigmo answers ONIGERR_INVALID_CODE_POINT_VALUE for such a code, which rb_enc_uint_chr reports as an invalid codepoint. And a UTF-32 code from 0x80000000 up was taken as four bytes (older MRIs compared it as a signed number); CRuby 4.0 calls it an invalid codepoint as it does any other above 0x10FFFF. Together: 9,011 lines of Util/chr-matrix.rb, the matrix's every difference from CRuby. What stays "out of char range" is what CRuby says so for: String#<< of a code above 0xFF onto a BINARY or US-ASCII string (rb_str_concat appends a byte there), #chr with no argument and no default_internal, a negative code or one above 32 bits, and a code wider than a multibyte encoding's longest character - which ruby/spec pins. Checked: Integer_ChrSingleByte1 (new; CRuby 4.0's output), Integer_ChrMultibyte1 (its expectation regenerated from CRuby 4.0.10: the UTF-32 and US-ASCII lines), Sprintf_CharacterBytes1, Float_Format1, Io_UngetcConverted1, String_AppendFrozenFirst1; chr-matrix: baseline (9,011 lines) -> same; spec/core/integer/chr, String append, concat, format, Kernel#sprintf, Array#pack U and C: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 45 +++++++++++++++++++--- Src/Libraries/Builtins/Integer.cs | 34 +++++++--------- Src/Libraries/Builtins/MutableStringOps.cs | 34 ++++++++++------ 4 files changed, 76 insertions(+), 38 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 57f24819b..2d7c02ae5 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1426,6 +1426,7 @@ public Tests(Driver/*!*/ driver) { String_ToIntAsciiIncompatible1, String_UndumpUnicodeEncoding1, String_OrdWide1, + Integer_ChrSingleByte1, String_TranslateCheckOrder1, Integer_ChrMultibyte1, String_Cesu8_1, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index a5b409285..a99718e45 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -759,6 +759,41 @@ def t(l) = puts(""#{l}: #{(yield rescue [$!.class, $!.message]).inspect}"") "); } + /// + /// A code above 0xFF in a single byte encoding is "invalid codepoint 0x100 in US-ASCII" to Integer#chr and to + /// String#<< (CRuby 4.0's onigmo: ONIGERR_INVALID_CODE_POINT_VALUE), but "256 out of char range" for #<< onto a BINARY or + /// US-ASCII string (rb_str_concat) and for #chr with no argument and no default_internal (Util/chr-matrix.rb). + /// + public void Integer_ChrSingleByte1() { + TestOutput(@" +[-> { 256.chr(""US-ASCII"") }, -> { 0x110000.chr(""UTF-8"") }, -> { -1.chr }, -> { 256.chr }, -> { (2**32).chr(""UTF-8"") }, + -> { 0xd800.chr(""UTF-8"") }, -> { """".b << 256 }, -> { ""a"".encode(""ISO-8859-1"") << 300 }, -> { (2**40).chr(""UTF-8"") }, + -> { 256.chr(""ISO-8859-1"") }, -> { 0x80.chr(""US-ASCII"") }, -> { 0x100.chr(""Windows-1252"") }, -> { 0x81.chr(""Windows-1252"") }, + -> { 0xffff_ffff.chr(""ISO-8859-1"") }, -> { 0x1_0000_0000.chr(""ISO-8859-1"") }, -> { 0x8140.chr(""Shift_JIS"") }, -> { 0xffff.chr(""Shift_JIS"") }, + -> { $VERBOSE = nil; Encoding.default_internal = ""US-ASCII""; 256.chr }, -> { 0x80.chr }].each { |l| p((l.call rescue $!)) } +", @" +# +# +# +# +# +# +# +# +# +# +# +# +""\x81"" +# +# +""\x{8140}"" +# +# +""\x80"" +"); + } + /// /// #tr! and #tr_s! (MRI's tr_trans): an empty string is nil, frozen or not; the sets' encodings are checked /// against the string's before the string is required to be modifiable. @@ -979,16 +1014,16 @@ def t(l) UTF-32BE 110000 <<: RangeError: invalid codepoint 0x110000 in UTF-32BE UTF-32BE 7fffffff chr: RangeError: invalid codepoint 0x7FFFFFFF in UTF-32BE UTF-32BE 7fffffff <<: RangeError: invalid codepoint 0x7FFFFFFF in UTF-32BE -UTF-32BE 80000000 chr: 80000000 -UTF-32BE 80000000 <<: 80000000 +UTF-32BE 80000000 chr: RangeError: invalid codepoint 0x80000000 in UTF-32BE +UTF-32BE 80000000 <<: RangeError: invalid codepoint 0x80000000 in UTF-32BE UTF-32BE 100000000 chr: RangeError: 4294967296 out of char range UTF-32BE 100000000 <<: RangeError: 4294967296 out of char range UTF-32BE 10000000000000000 chr: RangeError: bignum out of char range UTF-32BE 10000000000000000 <<: RangeError: bignum out of char range UTF-32BE -1 chr: RangeError: -1 out of char range UTF-32BE -1 <<: RangeError: -1 out of char range -UTF-32LE 81308130 chr: 30813081 -UTF-32LE 81308130 <<: 30813081 +UTF-32LE 81308130 chr: RangeError: invalid codepoint 0x81308130 in UTF-32LE +UTF-32LE 81308130 <<: RangeError: invalid codepoint 0x81308130 in UTF-32LE UTF-32LE 100000000 chr: RangeError: 4294967296 out of char range UTF-32LE 100000000 <<: RangeError: 4294967296 out of char range UTF-32LE 10000000000000000 chr: RangeError: bignum out of char range @@ -1007,7 +1042,7 @@ def t(l) UTF-16LE -1 <<: RangeError: -1 out of char range US-ASCII 80 chr: RangeError: invalid codepoint 0x80 in US-ASCII US-ASCII 80 <<: 80 -US-ASCII 100 chr: RangeError: 256 out of char range +US-ASCII 100 chr: RangeError: invalid codepoint 0x100 in US-ASCII US-ASCII 100 <<: RangeError: 256 out of char range US-ASCII 100000000 chr: RangeError: 4294967296 out of char range US-ASCII 100000000 <<: RangeError: 4294967296 out of char range diff --git a/Src/Libraries/Builtins/Integer.cs b/Src/Libraries/Builtins/Integer.cs index fbcac2f42..8c6c77ef0 100644 --- a/Src/Libraries/Builtins/Integer.cs +++ b/Src/Libraries/Builtins/Integer.cs @@ -417,17 +417,8 @@ internal static byte[] ToFormatBytes(RubyEncoding/*!*/ encoding, uint code, out case RubyEncoding.CodePageUTF32BE: case RubyEncoding.CodePageUTF32LE: // A UTF-32 character is four bytes whatever the number, so one that is too - // large is an invalid codepoint, not one out of range. MRI compares the - // number as a signed one, though: from 0x80000000 up it passes for a small - // one, and comes out as its four bytes. - if (codepoint >= 0x80000000) { - bool bigEndian = encoding.CodePage == RubyEncoding.CodePageUTF32BE; - var raw = new byte[4]; - for (int i = 0; i < 4; i++) { - raw[bigEndian ? i : 3 - i] = (byte)(codepoint >> (8 * (3 - i))); - } - return MutableString.CreateBinary(raw, resultEncoding); - } + // large is an invalid codepoint, not one out of range - from 0x80000000 up too in + // CRuby 4.0 (older MRIs compared the number as a signed one and let it through). if (codepoint > 0x10ffff || codepoint >= 0xd800 && codepoint <= 0xdfff) { throw InvalidCodePoint(encoding, codepoint); } @@ -487,9 +478,7 @@ internal static byte[] ToFormatBytes(RubyEncoding/*!*/ encoding, uint code, out return MutableString.CreateMutable(Tokenizer.UnicodeCodePointToString((int)codepoint), resultEncoding); case RubyEncoding.CodePageAscii: - if (codepoint > 0xff) { - throw OutOfCharRange(codepoint); - } + // (any code above 0x7F, 0x100 too: see the default case) if (codepoint > 0x7f) { throw InvalidCodePoint(encoding, codepoint); } @@ -574,19 +563,22 @@ internal static byte[] ToFormatBytes(RubyEncoding/*!*/ encoding, uint code, out } throw RubyExceptions.CreateRangeError("{0} out of char range", codepoint); } - // Everything else - single byte encodings, dummy encodings, and anything whose - // structure we don't model - has no character this wide. MRI's rb_enc_uint_chr - // reports exactly that rather than refusing to answer: rb_enc_codelen returns - // ONIGERR_TOO_BIG_WIDE_CHAR_VALUE and it raises "out of char range". - throw OutOfCharRange(codepoint); + // Everything else - single byte encodings (BINARY too), dummy encodings, and anything + // whose structure we don't model - has no character this wide. CRuby 4.0's onigmo + // answers ONIGERR_INVALID_CODE_POINT_VALUE for it (a single byte encoding's + // code_to_mbclen), so rb_enc_uint_chr raises "invalid codepoint 0x100 in US-ASCII". + // (String#<< onto a BINARY or US-ASCII string says "256 out of char range": see + // MutableStringOps.Append.) + throw InvalidCodePoint(encoding, codepoint); } } /// /// MRI distinguishes two RangeErrors: a code point that is wider than the encoding's /// longest character is "out of char range", while one that fits but is not assigned is - /// "invalid codepoint". So 0x100.chr("US-ASCII") is "256 out of char range" but - /// 0x80.chr("US-ASCII") is "invalid codepoint 0x80 in US-ASCII". + /// "invalid codepoint". A single byte encoding calls a code above 0xFF invalid in CRuby + /// 4.0, as it does an unassigned one: 0x100.chr("US-ASCII") and 0x80.chr("US-ASCII") are both + /// "invalid codepoint ... in US-ASCII". /// private static Exception/*!*/ InvalidCodePoint(RubyEncoding/*!*/ encoding, uint codepoint) { return RubyExceptions.CreateRangeError("invalid codepoint 0x{0:X} in {1}", codepoint, encoding.Name); diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index a9963bf13..7eaaf944f 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -837,9 +837,18 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { } // (ToChr may refuse the code: the frozen check comes first, as above) self.RequireNotFrozen(); + RequireByteCode(self, (uint)c); return self.Append(Integer.ToChr(self.Encoding, self.Encoding, c)); } + // MRI's rb_str_concat takes a code onto a BINARY or US-ASCII string as a byte, and one above 0xFF is "256 out of char + // range" there, where Integer#chr in those encodings says "invalid codepoint 0x100 in ASCII-8BIT". + private static void RequireByteCode(MutableString/*!*/ self, uint c) { + if (c > 0xff && (self.Encoding == RubyEncoding.Binary || self.Encoding == RubyEncoding.Ascii)) { + throw RubyExceptions.CreateRangeError("{0} out of char range", c); + } + } + [RubyMethod("<<")] [RubyMethod("concat")] public static MutableString/*!*/ Append(MutableString/*!*/ self, [NotNull]BigInteger/*!*/ c) { @@ -849,6 +858,7 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { // a character where the encoding has one that wide: 0x8431A430 in GB18030. A wider // one that is still a Fixnum in MRI is named in the message. if (c.Sign > 0 && c <= UInt32.MaxValue) { + RequireByteCode(self, (uint)c); return self.Append(Integer.ToChr(self.Encoding, self.Encoding, (uint)c)); } if (c >= -((BigInteger)1 << 62) && c < ((BigInteger)1 << 62)) { @@ -6694,18 +6704,6 @@ private static void AppendCodePoint(MutableString/*!*/ str, int c) { } // encoding aware, TODO: KCODE - [RubyMethod("tr!")] - public static MutableString Translate(MutableString/*!*/ self, - [DefaultProtocol, NotNull]MutableString/*!*/ from, [DefaultProtocol, NotNull]MutableString/*!*/ to) { - - bool anyCharacterMaps; - if (RequireTranslatable(self, from, to)) { - return null; - } - Translate(self, from, to, true, false, out anyCharacterMaps); - return anyCharacterMaps ? self : null; - } - // MRI's tr_trans: an empty string is nil, frozen or not; then the encodings of the two sets are checked against the // string's, and only then is the string required to be modifiable. True for the empty string. private static bool RequireTranslatable(MutableString/*!*/ self, MutableString/*!*/ from, MutableString/*!*/ to) { @@ -6718,6 +6716,18 @@ private static bool RequireTranslatable(MutableString/*!*/ self, MutableString/* return false; } + [RubyMethod("tr!")] + public static MutableString Translate(MutableString/*!*/ self, + [DefaultProtocol, NotNull]MutableString/*!*/ from, [DefaultProtocol, NotNull]MutableString/*!*/ to) { + + bool anyCharacterMaps; + if (RequireTranslatable(self, from, to)) { + return null; + } + Translate(self, from, to, true, false, out anyCharacterMaps); + return anyCharacterMaps ? self : null; + } + // encoding aware, TODO: KCODE [RubyMethod("tr_s")] public static MutableString/*!*/ TrSqueeze(MutableString/*!*/ self, From 225031bead19d4e92dc7479db0f2f2abf39f2de9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:46:42 +0000 Subject: [PATCH 085/439] Method JIT: Array#[] per receiver once some Array has a singleton [] CSV defines `def NO_QUOTED_FIELDS.[](_index)` on one Array. That records `[]` in Array's ClrSingletonMethods, and the typed body's class-wide test (HasPlainInstances) then refused Array#[] for the rest of the process: every program requiring csv lost Array element reads in typed bodies (app-shapes: OptionParser.top and .base declined, "[] on a RubyArray"). While Array#[] is the public library method and Array has no adopted instances, the read now asks the receiver itself whether it has a singleton class (the generic site's IsClrNonSingletonRuleValid test) and deopts if it has; a singleton defined later moves Array's method version, which the entry checks. app-shapes trace: 117 -> 119 specialized, 30 -> 28 declined after the pre-screen; AWFY traces unchanged; census.rb -d 0 changed (it loads no library). Instructions a call with CSV loaded: @a[-1] 0.76, @a[i] 0.78, the control 1.000. Util/jit-aref-matrix.rb (new) and the JIT, OSR-array and CSV matrices print CRuby's output with the JIT on, off and without JIT calls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 23 +++++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 25 +++++ Util/bench/jit-aref-shapes.rb | 44 +++++++++ Util/jit-aref-matrix.rb | 102 ++++++++++++++++++++ Util/perf/LEDGER.md | 40 ++++++++ 5 files changed, 234 insertions(+) create mode 100644 Util/bench/jit-aref-shapes.rb create mode 100644 Util/jit-aref-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index a12d2ad73..624fe9baa 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1247,6 +1247,15 @@ private void RequireElementMethod(string/*!*/ name, string hashToo, out bool arr return Ast.Call(JitRuntime.M("StringIndex"), recv, Ast.Convert(index, typeof(long))); } bool arrays, hashes; + if (!IsPlainLibraryMethod(ArrayClass, "[]") && IsArrayIndexCheckedPerReceiver()) { + // some Array has a singleton `[]' or method_missing (CSV's NO_QUOTED_FIELDS): this one is asked (IndexIntChecked) + hashes = IsPlainLibraryMethod(HashClass, "[]") && IsPublic(HashClass, "[]") && IsPlainLibraryMethod(HashClass, "default") + && KeyLookupIsPlain(); + RequireCollectionReceiver(receiver, true, hashes, "[]"); + _canDeopt = true; + type = JT.Obj; + return Ast.Call(JitRuntime.M(helper + "Checked"), Ast.Constant(_context), recv, index, Ast.Constant(hashes)); + } RequireElementMethod("[]", "default", out arrays, out hashes); RequireCollectionReceiver(receiver, arrays, hashes, "[]"); _canDeopt = true; @@ -1254,6 +1263,20 @@ private void RequireElementMethod(string/*!*/ name, string hashToo, out bool arr return Ast.Call(JitRuntime.M(helper), recv, index, Ast.Constant(arrays), Ast.Constant(hashes)); } + /// + /// Array#[] is the public library method and no Array is adopted by a Ruby class, but some Array has had a singleton + /// `[]' or method_missing, so the class no longer answers for its instances (HasPlainInstances): each receiver is + /// asked whether it has a singleton class, as the generic call site asks it (RubyOps.IsClrNonSingletonRuleValid). + /// A singleton defined later moves Array's method version, which a body compiled before it checks at its entry. + /// + private bool IsArrayIndexCheckedPerReceiver() { + var array = ArrayClass; + if (!IsBuiltinMethod(array, "[]") || !IsPublic(array, "[]")) { return false; } + using (_context.ClassHierarchyLocker()) { + return !array.HasAdoptedInstances; + } + } + internal static bool IsHashQuery(string/*!*/ name, int argc) { switch (name) { case "key?": diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index bb84ca3ed..34dec0fa4 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -531,6 +531,31 @@ public static object IndexInt(object recv, int index, bool arrays, bool hashes) throw Deopt(); } + // `a[i]' once some Array has had a singleton `[]' or `method_missing' (JitCompiler.EmitIndexRead): Array#[] for an + // Array without a singleton class, the test the generic site makes (RubyOps.IsClrNonSingletonRuleValid); an Array + // with one deopts, and the generic body dispatches to its method. + private static bool HasSingletonClass(RubyContext/*!*/ context, object/*!*/ recv) { + RubyInstanceData data; + RubyClass immediate; + return context.TryGetClrTypeInstanceData(recv, out data) && (immediate = data.ImmediateClass) != null && + (immediate.IsSingletonClass || immediate.IsRubyClass); + } + + public static object IndexIntChecked(RubyContext/*!*/ context, object recv, int index, bool hashes) { + if (recv != null && recv.GetType() == typeof(RubyArray) && HasSingletonClass(context, recv)) { throw Deopt(); } + return IndexInt(recv, index, true, hashes); + } + + public static object IndexLongChecked(RubyContext/*!*/ context, object recv, long index, bool hashes) { + if (recv != null && recv.GetType() == typeof(RubyArray) && HasSingletonClass(context, recv)) { throw Deopt(); } + return IndexLong(recv, index, true, hashes); + } + + public static object IndexObjChecked(RubyContext/*!*/ context, object recv, object index, bool hashes) { + if (recv != null && recv.GetType() == typeof(RubyArray) && HasSingletonClass(context, recv)) { throw Deopt(); } + return IndexObj(recv, index, true, hashes); + } + public static object IndexLong(object recv, long index, bool arrays, bool hashes) { if (index >= Int32.MinValue && index <= Int32.MaxValue) { return IndexInt(recv, (int)index, arrays, hashes); diff --git a/Util/bench/jit-aref-shapes.rb b/Util/bench/jit-aref-shapes.rb new file mode 100644 index 000000000..445aa15ac --- /dev/null +++ b/Util/bench/jit-aref-shapes.rb @@ -0,0 +1,44 @@ +# What `a[i]' costs in a method the method JIT can take once some Array has a singleton `[]' - as every program that +# loads CSV has (CSV::FieldsConverter::NO_QUOTED_FIELDS) - JitCompiler.EmitIndexRead with JitRuntime.IndexIntChecked: +# ns per call of the method, the caller a `while' loop. top `@a[-1]', at `@a[i]', pair `x[0]' on a parameter; size +# `@a.size' is the control (not affected). +# +# ruby Util/perf/ab.rb -r 6 Util/bench/jit-aref-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# ruby Util/perf/ab.rb -i -r 1 -n 20000 Util/bench/jit-aref-shapes.rb \ +# "base=env IR_CONFIG=Release Util/perf/callgrind/count.sh ../ironruby" "new=env IR_CONFIG=Release Util/perf/callgrind/count.sh ." +# +# Every line prints the sum of its results next to its time; it must be CRuby's. +$stdout.sync = true +require 'csv' + +class ArShapes + def initialize; @a = [1, 2, 3, 4]; end + def top = @a[-1] + def at(i) = @a[i] + def pair(x) = x[0] + def size = @a.size +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +s = ArShapes.new +N = (ENV["N"] || 1_000_000).to_i +pr = [5, 6] +t("top", N) { |n| i = 0; r = 0; while i < n; r += s.top; i += 1; end; r } +t("at", N) { |n| i = 0; r = 0; while i < n; r += s.at(i & 3); i += 1; end; r } +t("pair", N) { |n| i = 0; r = 0; while i < n; r += s.pair(pr); i += 1; end; r } +t("size", N) { |n| i = 0; r = 0; while i < n; r += s.size; i += 1; end; r } diff --git a/Util/jit-aref-matrix.rb b/Util/jit-aref-matrix.rb new file mode 100644 index 000000000..d508da9e7 --- /dev/null +++ b/Util/jit-aref-matrix.rb @@ -0,0 +1,102 @@ +# Differential matrix for `a[i]` in methods the method JIT compiles once some Array has a singleton `[]` +# (as CSV's `NO_QUOTED_FIELDS` has: `def NO_QUOTED_FIELDS.[](_index)`), JitCompiler.EmitIndexRead. Run under +# CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-aref-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-aref-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-aref-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which methods are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-aref-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep ar_ +# The traps: the Array with the singleton `[]` must reach it from a body compiled before and after it was defined; +# every other Array keeps Array#[] (negative index, out of range, frozen); a singleton method_missing does not +# change `[]`; a subclass's own `[]`, a refinement and a redefinition of Array#[] are dispatched to. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts e.class + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class AR + def initialize(a); @a = a; end + def ar_top = @a[-1] + def ar_at(i) = @a[i] + def ar_first(x) = x[0] + def ar_sum(x) = x[0] + x[-1] +end + +o = AR.new([1, 2, 3]) +t("before: top") { warm { o.ar_top } } +t("before: at, out of range") { warm { |i| o.ar_at(i % 5 - 2) } } +t("before: first") { warm { |i| o.ar_first([i, 0]) } } + +SPECIAL = [7, 8, 9] +def SPECIAL.[](i) = "special #{i}" + +t("after: special, compiled before") { AR.new(SPECIAL).ar_top } +t("after: first on special") { o.ar_first(SPECIAL) } +t("after: top") { warm { o.ar_top } } +t("after: at, negative") { warm { |i| o.ar_at(-1 - i % 3) } } +t("after: at, out of range") { [o.ar_at(5), o.ar_at(-5)] } +t("after: first") { warm { |i| o.ar_first([i, 0]) } } +t("after: sum") { warm { |i| o.ar_sum([i, 1, 2]) } } +t("after: special again") { [o.ar_first(SPECIAL), AR.new(SPECIAL).ar_top, SPECIAL.first] } +t("after: frozen") { o.ar_first([4, 5].freeze) } +t("after: dup of special") { o.ar_first(SPECIAL.dup) } +t("after: clone of special") { o.ar_first(SPECIAL.clone) } + +MM = [1] +def MM.method_missing(n, *a) = :mm +t("method_missing singleton") { [o.ar_first(MM), warm { |i| o.ar_first([i]) }] } + +class SubA < Array + def [](i) = :sub +end +t("subclass with []") { o.ar_first(SubA.new([1])) } +t("hash") { o.ar_first({0 => :h}) } +t("string") { o.ar_first("xyz") } +t("nil") { o.ar_first(nil) } + +LATE = [5, 6] +t("late: before its singleton") { o.ar_first(LATE) } +def LATE.[](i) = :late +t("late: after its singleton") { [o.ar_first(LATE), warm { |i| o.ar_first([i]) }] } + +module ArefRefinement + refine Array do + def [](i) = :refined + end +end +class AR + using ArefRefinement + def ar_refined(x) = x[0] +end +t("refined") { warm { o.ar_refined([1]) } } + +class Array + alias_method :__orig_aref, :[] + def [](*a) = :redefined +end +t("Array#[] redefined") { o.ar_first([1]) } +class Array + alias_method :[], :__orig_aref +end +t("Array#[] restored") { warm { |i| o.ar_first([i]) } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 2bdfbfa51..666da2044 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1623,6 +1623,46 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitaref (2026-11-26) - `a[i]` in a typed body after some Array has a singleton `[]`** + - trace only, not gated (the census cannot see it: it loads no library). The side finding of + perf/jitconst: app-shapes declined `OptionParser.top` (`@stack[-1]`) and `.base`, and rejected + `Gem::Requirement#none?`, all at "[] on a RubyArray". The typed body takes `recv[i]` with any + Integer index already (negative from the end, out of range nil: `JitRuntime.IndexInt`); in + isolation `top` is specialized. What turned it off is CSV: `csv/fields_converter.rb` defines + `def NO_QUOTED_FIELDS.[](_index)` on one Array, which puts `[]` in Array's + `ClrSingletonMethods`, and `HasPlainInstances` then says no for the class for the rest of the + process - every program that requires `csv` lost Array element reads in every typed body whose + receiver is not a typed Array parameter. + Now, while `Array#[]` is the public library method and Array has no adopted instances, a class + that only lost `HasPlainInstances` compiles the read with `IndexIntChecked` / `IndexLongChecked` / + `IndexObjChecked`: for an exact `RubyArray` receiver they ask whether this object has a singleton + class - the generic site's own test (`RubyOps.IsClrNonSingletonRuleValid`, an instance-data + lookup) - and deopt if it has, so the generic body dispatches to its method; any other receiver + goes to the existing helpers. A singleton defined after the compile moves Array's method version, + which the body's entry checks. A refinement of `Array#[]`, a redefinition, a subclass's own `[]` + and an adopted instance are refused or deopt as before. + Traces: app-shapes specialized 117 -> 119 (`OptionParser.top`, `OptionParser.base`), declined + after the pre-screen 30 -> 28; Json, Richards, DeltaBlue, CD and Havlak (3 x 10) the same on both + builds. `census.rb -d` 0 methods changed. `Gem::Requirement#none?` now stops at its second + obstacle, `@requirements[0] == DefaultRequirement` ("== on a receiver of unknown type"): Array#== + calls `==` on the elements (Ruby code), and an identity shortcut (true for the same object, + deopt otherwise) would deopt on every requirement that is not the default; left. + Instructions a call with CSV loaded (`Util/perf/callgrind/count.sh`, + `Util/bench/jit-aref-shapes.rb`, new): `@a[-1]` 2336 -> 1778 (0.76), `@a[i]` 2582 -> 2021 + (0.78); `x[0]` on an Array parameter 2116 -> 2116 (the typed parameter path, unaffected), the + control `@a.size` 1523 -> 1523. + Checked: `Util/jit-aref-matrix.rb` (new, 24 rows: reads before and after one Array gets a + singleton `[]`, from bodies compiled before and after it, negative and out-of-range indexes, a + frozen Array, `dup` (no singleton) and `clone` (singleton kept) of the special Array, a singleton + `method_missing`, a subclass's own `[]`, Hash, String and nil receivers, an Array given its + singleton after the body compiled, a refinement, `Array#[]` redefined and restored), and jit, + jit-calls, jit-scan, osr-array and csv: CRuby's output and the unchanged build's with the JIT on, + `-X:NoJIT -X:NoOSR` and `-X:NoJITCalls`, and the unchanged build's with `IR_LIGHT_FRAMES=0`; + hot-shapes the unchanged build's in every mode with its known one-row difference from CRuby. + For the gate: an instance-data lookup per read for Arrays once the class has a singleton `[]` + anywhere - the cost the generic site pays in the same state; the other element methods (`[]=`, + `fetch`, `size`...) still use the class-wide test. + - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, not gated. A keyword From 8747187208a42830e57da53ed4309622b195a11d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:46:58 +0000 Subject: [PATCH 086/439] %c of a code above 0xFF in a single byte encoding is "invalid character" `format("%c".encode("ISO-8859-1"), 256)` and the same in every single byte encoding raised "256 out of char range"; CRuby 4.0 raises ArgumentError "invalid character": its codelen has no length for such a code, which rb_str_format reports so. BINARY and US-ASCII keep "256 out of char range", as CRuby, which puts a byte for them. The same change in onigmo as the previous commit's Integer#chr; together 4,682 lines of Util/format-c-matrix.rb and format-c-bytes-matrix.rb, all their differences from CRuby. Checked: Sprintf_CharacterSingleByte1 (new; CRuby 4.0's output), Sprintf_CharacterBytes1 (its ISO-8859-1 line regenerated from CRuby 4.0.10); format-c-matrix and format-c-bytes-matrix: baseline -> same; spec/core/string format and modulo, Kernel#sprintf and #format: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 40 +++++++++++++++++++++++++ Src/Libraries/Builtins/Integer.cs | 8 +++-- 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 2d7c02ae5..4ce0264c5 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1010,6 +1010,7 @@ public Tests(Driver/*!*/ driver) { Puma_Tls1, Sprintf_MriTieRounding1, Sprintf_CharacterBytes1, + Sprintf_CharacterSingleByte1, Float_NegativeZero1, Math_CLibrary1, Errno_MessageNotDoubled1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 766b44fd3..04e6f7f9a 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -2054,6 +2054,46 @@ Shift_JIS [128] false "); } + /// + /// %c of a code above 0xFF in a single byte encoding: CRuby 4.0's codelen has no length for it, so format raises + /// "invalid character", but for BINARY and US-ASCII, which put a byte ("256 out of char range"). Util/format-c-matrix.rb. + /// + public void Sprintf_CharacterSingleByte1() { + TestOutput(@" +%w[ISO-8859-1 Windows-1252 IBM437 KOI8-R US-ASCII BINARY].each do |e| + [0x41, 0xe9, 0x100, 0x3042].each do |c| + r = begin; s = ""%c"".encode(e) % c; [s.encoding.name, s.bytes]; rescue => x; ""#{x.class}: #{x.message}""; end + puts ""#{e} #{c.to_s(16)}: #{r.inspect}"" + end +end +", @" +ISO-8859-1 41: [""ISO-8859-1"", [65]] +ISO-8859-1 e9: [""ISO-8859-1"", [233]] +ISO-8859-1 100: ""ArgumentError: invalid character"" +ISO-8859-1 3042: ""ArgumentError: invalid character"" +Windows-1252 41: [""Windows-1252"", [65]] +Windows-1252 e9: [""Windows-1252"", [233]] +Windows-1252 100: ""ArgumentError: invalid character"" +Windows-1252 3042: ""ArgumentError: invalid character"" +IBM437 41: [""IBM437"", [65]] +IBM437 e9: [""IBM437"", [233]] +IBM437 100: ""ArgumentError: invalid character"" +IBM437 3042: ""ArgumentError: invalid character"" +KOI8-R 41: [""KOI8-R"", [65]] +KOI8-R e9: [""KOI8-R"", [233]] +KOI8-R 100: ""ArgumentError: invalid character"" +KOI8-R 3042: ""ArgumentError: invalid character"" +US-ASCII 41: [""US-ASCII"", [65]] +US-ASCII e9: [""ASCII-8BIT"", [233]] +US-ASCII 100: ""RangeError: 256 out of char range"" +US-ASCII 3042: ""RangeError: 12354 out of char range"" +BINARY 41: [""ASCII-8BIT"", [65]] +BINARY e9: [""ASCII-8BIT"", [233]] +BINARY 100: ""RangeError: 256 out of char range"" +BINARY 3042: ""RangeError: 12354 out of char range"" +"); + } + /// /// MRI's dtoa settles a rounding it cannot tell from a tie in double arithmetic by the /// parity of the last digit, whatever the exact binary value: "%.2f" % 2.675 is 2.68 diff --git a/Src/Libraries/Builtins/Integer.cs b/Src/Libraries/Builtins/Integer.cs index 8c6c77ef0..233fd0688 100644 --- a/Src/Libraries/Builtins/Integer.cs +++ b/Src/Libraries/Builtins/Integer.cs @@ -379,9 +379,13 @@ internal static byte[] ToFormatBytes(RubyEncoding/*!*/ encoding, uint code, out } if (encoding.IsSingleByteCharacterSet || encoding.StrictEncoding.IsSingleByte) { - // onigenc_single_byte_code_to_mbc + // onigenc_single_byte_code_to_mbc. CRuby 4.0's codelen has no length for a code above 0xFF (ONIGERR_INVALID_CODE_POINT_VALUE): + // "invalid character", but for BINARY and US-ASCII, whose %c rb_str_format writes as a byte ("256 out of char range"). if (code > 0xff) { - throw OutOfCharRange(code); + if (encoding == RubyEncoding.Binary || encoding == RubyEncoding.Ascii) { + throw OutOfCharRange(code); + } + return null; } return new[] { (byte)code }; } From 21f4d627b62e0b441aab2b07bd924f5d0109d864 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:47:41 +0000 Subject: [PATCH 087/439] Sprintf_CharacterBytes1: the ISO-8859-1 line of 0x100, not BINARY's, is CRuby 4.0's "invalid character" The previous commit changed neither line of the expected text (the line is there twice, and the edit refused to guess); BINARY's 0x100 stays "256 out of char range". The test passes with CRuby 4.0.10's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/Runtime/MiscTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 04e6f7f9a..e444b1c38 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -2032,7 +2032,7 @@ Shift_JIS [128] false GB18030 [1, 0, 0] true Emacs-Mule [16, 255] false ISO-8859-1 [255] true -RangeError: 256 out of char range +ArgumentError: invalid character ASCII-8BIT [128] true RangeError: 256 out of char range UTF-8 [227, 129, 130] true From 9040b98edc0de016d73b5071af81d35116788bbc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:52:45 +0000 Subject: [PATCH 088/439] Ledger: per-receiver tests for the other core operations, rejected Which class-wide tests (HasPlainInstances) fail in real runs: in app-shapes, gem list, a run requiring csv, json, set, optparse, uri, net/http, erb and logger, and the fourteen AWFY benchmarks, only Array is touched, by `[]` (CSV, taken by perf/jitaref), optparse's ARGV extension and $LOAD_PATH's resolve_feature_path; no method_missing, no adopted instance, every other core class untouched. None of those names is an operation the typed body takes, so nothing was built. Util/perf/plain-probe.rb prints that state at exit, for the next count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 18 ++++++++++++++++++ Util/perf/plain-probe.rb | 22 ++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 Util/perf/plain-probe.rb diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 666da2044..b964870e3 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -5392,6 +5392,24 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitplain (2026-11-26) - the per-receiver test of perf/jitaref for the typed body's other + core operations: nothing to take.** The other operations (`Array#[]=`, `fetch`, `size`, `first`, + `last`, `push`/`<<`, `==`, `Hash#[]`/`[]=`/`fetch`/`key?`, `String#size`/`==`/`[]`, the + Integer and Float operators) still use the class-wide `HasPlainInstances`, so the question was + which of them a real run turns off. `Util/perf/plain-probe.rb` (new) prints, at exit, every core + class whose `ClrSingletonMethods` or `HasAdoptedInstances` is set. In app-shapes, `gem list`, a + run requiring csv, json, set, optparse, uri, net/http, erb and logger, and all fourteen AWFY + benchmarks: only Array is ever touched, with the names `[]` (CSV's `NO_QUOTED_FIELDS`, which + perf/jitaref took), `getopts`, `initialize`, `options`, `options=`, `order!`, `parse!`, + `permute!` (optparse extends `ARGV` with `OptionParser::Arguable`) and `resolve_feature_path` + (`$LOAD_PATH`'s, in every process); no `method_missing`, no adopted instance, and Hash, String, + Symbol, Range, Proc, Time, Regexp, MatchData, nil, true, false, Integer and Float untouched. None + of those names is an operation the typed body takes, so no class-wide test fails for one in these + runs and a per-receiver test would change nothing they do. Not built. What would make it worth + building: a library that gives one String or Hash a singleton method of an operator's name, or a + `method_missing` (DelegateClass and SimpleDelegator do not: they are Ruby objects); the probe + finds it. + - **perf/jitconst (2026-11-26) - "JIT maybe: constant without a scope" is the census's, not the runtime's; nothing to let in.** The census's second "maybe" line (455 methods of Src/StdLib + AWFY on 9d2c89a: ENV 19, Array 12, Integer 11, URI 11, AF_INET 8, BN 7) comes from diff --git a/Util/perf/plain-probe.rb b/Util/perf/plain-probe.rb new file mode 100644 index 000000000..fb46d8f19 --- /dev/null +++ b/Util/perf/plain-probe.rb @@ -0,0 +1,22 @@ +# Which core classes no longer answer for their instances in the method JIT's class-wide test +# (JitCompiler.HasPlainInstances): a singleton method of some name, or method_missing, on any one instance of a +# CLR-typed class (Array, Hash, String...) is recorded in the class's ClrSingletonMethods, and an adopted instance in +# HasAdoptedInstances; either turns that operation (or all of them) off in every typed body for the rest of the process. +# Load it into a run; it prints what was recorded when the process ends: +# +# IR_CONFIG=Release ./ir.sh -r Util/perf/plain-probe.rb Util/bench/app-shapes.rb 2>&1 >/dev/null | grep '\[plain\]' +# IR_CONFIG=Release ./ir.sh -r Util/perf/plain-probe.rb -S gem list 2>&1 >/dev/null | grep '\[plain\]' +# +# IronRuby only (it reads internal properties through CLR reflection). +at_exit do + f = System::Reflection::BindingFlags + flags = f.NonPublic | f.Instance | f.Public + t = Array.GetType + sm = t.GetProperty("ClrSingletonMethods", flags) + ad = t.GetProperty("HasAdoptedInstances", flags) + out = [Array, Hash, String, Symbol, Range, Proc, Time, Regexp, MatchData, NilClass, TrueClass, FalseClass, Integer, Float].map do |c| + keys = (v = sm.GetValue(c)) ? v.Keys.to_a.map(&:to_s).sort : [] + keys.empty? && !ad.GetValue(c) ? nil : "#{c}: singleton names #{keys.inspect}#{ad.GetValue(c) ? ' ADOPTED' : ''}" + end.compact + $stderr.puts "[plain] " + (out.empty? ? "all plain" : out.join("; ")) +end From 7bba581d2992bbda2c6b369a3e5b589f6ce2ad3a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:54:57 +0000 Subject: [PATCH 089/439] Math.log of a base, atan2's and hypot's conversion order, and sqrt of a Complex as MRI's Util/math-matrix.rb differed from CRuby in 60 lines besides the nil wording ruby/spec pins: - Math.log(x, base) divided ln(x) by ln(base), with a NaN answered first. MRI's rb_math_log converts and domain-checks both, then answers the pole (a zero x is -Infinity, NaN for a zero base; a zero base -0.0), then log2(x) / log2(base) plus the bits a big Integer had shifted out (a size_t difference, which wraps) over log2(base): so log(2, 1) is NaN, log(0, NaN) -Infinity, log(0.5, Infinity) 0.0, log(NaN, -1) a DomainError, log(NaN, "1") a TypeError, and log(10.0, 2.0) is 3.321928094887362. RubyMath.LogBase (Floats and Fixnums) and the prelude's __ir_log__ (the rest) do this. - Math.atan2 converts its second argument first (math_atan2), and so does Math.hypot (gcc evaluates hypot(Get_Double(x), Get_Double(y)) right to left): which error a call given two bad arguments raises. - Math.sqrt of a Complex is its principal square root, as rb_math_sqrt computes it (Math.sqrt(Complex(1, 0)) is (1.0+0.0i), not 1.0; Complex(1, 1) was a RangeError). Checked: Math_LogBaseAndOrder1 (new; CRuby 4.0's output), Math_CLibrary1; math-matrix: 97 lines -> the 37 of "no implicit conversion from nil to integer" (ldexp), which ruby/spec pins as "of nil into Integer"; spec/core/math, spec/core/complex: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 47 +++++++++++++++++++++++++ Src/Libraries/Builtins/RubyMath.cs | 20 +++++++++-- Src/StdLib/ironruby/ruby4.rb | 37 ++++++++++++++----- 4 files changed, 93 insertions(+), 12 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 4ce0264c5..ee13f4154 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1013,6 +1013,7 @@ public Tests(Driver/*!*/ driver) { Sprintf_CharacterSingleByte1, Float_NegativeZero1, Math_CLibrary1, + Math_LogBaseAndOrder1, Errno_MessageNotDoubled1, Process_ClockGetTime1, Process_ThreadCpuTime1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index e444b1c38..a11aa5e83 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -2159,6 +2159,53 @@ p Math.cbrt(-27.0), Math.cbrt(27.0), Math.gamma(3.0), Math.gamma(23.0), Math.erf 1.1240007277776077e+21 0.0 1.0 +"); + } + + /// + /// Math.log of two arguments as MRI's rb_math_log: both converted and checked, the pole first (a zero x is -Infinity, + /// NaN for a zero base; a zero base -0.0), then log2(x) / log2(base) plus the shifted-out bits over log2(base) - so a base + /// of 1 is NaN, and the bits are a size_t. atan2 converts its second argument first, and so does hypot (gcc's order of + /// its arguments). Math.sqrt of a Complex is its principal root. Util/math-matrix.rb. + /// + public void Math_LogBaseAndOrder1() { + TestOutput(@" +require 'ruby4' +def t(l) = (puts ""#{l}: #{(yield rescue ""#{$!.class}: #{$!.message}"").inspect}"") +[[0, Float::NAN], [0, 2], [0, 0], [2, 1], [0.5, 0], [0.5, Float::INFINITY], [10.0, 2.0], [1.0e-16, 2.0], + [Float::INFINITY, 0], [Float::NAN, 0], [Float::NAN, -1], [Float::NAN, ""1""], [2**2000, 2], [2, 2**2000], [8, 2]].each do |x, b| + t(""log(#{x.inspect[0, 12]}, #{b.inspect[0, 12]})"") { Math.log(x, b) } +end +t(""atan2('1', nil)"") { Math.atan2(""1"", nil) } +t(""atan2(nil, '1')"") { Math.atan2(nil, ""1"") } +t(""hypot('1', nil)"") { Math.hypot(""1"", nil) } +t(""hypot(:s, '1')"") { Math.hypot(:s, ""1"") } +[Complex(1, 0), Complex(1, 1), Complex(-4, 0), Complex(-4, -0.0), Complex(3, 4)].each { |c| t(""sqrt(#{c})"") { Math.sqrt(c) } } +", @" +log(0, NaN): -Infinity +log(0, 2): -Infinity +log(0, 0): NaN +log(2, 1): NaN +log(0.5, 0): -0.0 +log(0.5, Infinity): 0.0 +log(10.0, 2.0): 3.321928094887362 +log(1.0e-16, 2.0): -53.150849518197795 +log(Infinity, 0): -0.0 +log(NaN, 0): -0.0 +log(NaN, -1): ""Math::DomainError: Numerical argument is out of domain - log"" +log(NaN, ""1""): ""TypeError: can't convert String into Float"" +log(114813069527, 2): 2000.0 +log(2, 114813069527): 3.5474507834056826e+17 +log(8, 2): 3.0 +atan2('1', nil): ""TypeError: can't convert nil into Float"" +atan2(nil, '1'): ""TypeError: can't convert String into Float"" +hypot('1', nil): ""TypeError: can't convert nil into Float"" +hypot(:s, '1'): ""TypeError: can't convert String into Float"" +sqrt(1+0i): (1.0+0.0i) +sqrt(1+1i): (1.09868411346781+0.4550898605622274i) +sqrt(-4+0i): (0.0+2.0i) +sqrt(-4-0.0i): (0.0-2.0i) +sqrt(3+4i): (2.0+1.0i) "); } diff --git a/Src/Libraries/Builtins/RubyMath.cs b/Src/Libraries/Builtins/RubyMath.cs index 4cee4396c..bbc21f40e 100644 --- a/Src/Libraries/Builtins/RubyMath.cs +++ b/Src/Libraries/Builtins/RubyMath.cs @@ -386,6 +386,22 @@ public static double LogGamma(object self, [DefaultProtocol]double x) { // or an Int64 is far below the 2**1024 from which those split the exponent off first. // Everything else - a negative number (DomainError), a Bignum, a Rational, nil, a base of // nil - goes to the Ruby definitions. + /// + /// MRI's rb_math_log of two numbers that are not negative (and fit a double): the pole first - a zero x is -Infinity, + /// or NaN for a zero base, and a zero base -0.0 - then log2(x) / log2(base) plus the bits shifted out of a big one + /// (none here) over log2(base), which makes a base of 1 NaN and turns a -0.0 quotient into 0.0. + /// + internal static double LogBase(double d, double b) { + if (d == 0.0) { + return (b != 0.0) ? Double.NegativeInfinity : Double.NaN; + } + if (b == 0.0) { + return -0.0; + } + double lb = SM.Log2(b); + return SM.Log2(d) / lb + 0.0 / lb; + } + private static bool TryGetLogArgument(RubyContext/*!*/ context, object x, out double d) { return TryGetDouble(context, x, out d) && (d >= 0.0 || double.IsNaN(d)); } @@ -405,9 +421,7 @@ public static object Log(CallSiteStorage> public static object Log(CallSiteStorage>/*!*/ general, object self, object x, object newBase) { double d, b; if (TryGetLogArgument(general.Context, x, out d) && TryGetLogArgument(general.Context, newBase, out b)) { - if (double.IsNaN(d)) return d; - if (double.IsNaN(b)) return b; - return SM.Log(d) / SM.Log(b); + return LogBase(d, b); } return General(general, "__ir_log__", self, x, newBase); } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 74effda2f..674289d36 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -8375,8 +8375,9 @@ def __ir_atan__(x) end def __ir_atan2__(y, x) - y = __flt__(y) + # x first, as MRI's math_atan2 converts them x = __flt__(x) + y = __flt__(y) return y if y.nan? return x if x.nan? ::System::Math.Atan2(y, x) @@ -8437,6 +8438,17 @@ def __ir_cbrt__(x) end def __ir_sqrt__(x) + # MRI's rb_math_sqrt takes a Complex as one: sqrt((|x| + re) / 2), sqrt((|x| - re) / 2) with the sign of + # the imaginary part (its sign bit: -0.0 counts) + if x.is_a?(::Complex) + i = x.imaginary + neg = i.is_a?(::Float) ? (i < 0.0 || (i == 0.0 && 1.0 / i < 0.0)) : i < 0 + re = __flt__(x.real) + d = __flt__(x.abs) + im = ::System::Math.Sqrt((d - re) / 2.0) + re = ::System::Math.Sqrt((d + re) / 2.0) + return ::Complex.rect(re, neg ? -im : im) + end x = __flt__(x) return x if x.nan? __dom__("sqrt") if x < 0.0 @@ -8478,14 +8490,20 @@ def __ir_log__(x, *rest) ::Kernel.raise(::ArgumentError, "wrong number of arguments (given #{rest.size + 1}, expected 1..2)") end x, bits = __log_split__(x) - r = __log__(x, "log") - return r if r - v = ::System::Math.Log(x) + bits * ::System::Math.Log(2.0) - return v if rest.empty? + if rest.empty? + r = __log__(x, "log") + return r if r + return ::System::Math.Log(x) + bits * ::System::Math.Log(2.0) + end + # MRI's rb_math_log of two: both converted and checked (a NaN is not negative), the pole, then + # log2(x) / log2(base) + (bits - base's bits, a size_t) / log2(base) - see RubyMath.LogBase + __dom__("log") if x < 0.0 b, bbits = __log_split__(rest[0]) - r = __log__(b, "log") - return r if r - v / (::System::Math.Log(b) + bbits * ::System::Math.Log(2.0)) + __dom__("log") if b < 0.0 + return (b != 0.0 ? -::Float::INFINITY : ::Float::NAN) if x == 0.0 + return -0.0 if b == 0.0 + lb = ::System::Math.Log2(b) + ::System::Math.Log2(x) / lb + ((bits - bbits) & 0xFFFF_FFFF_FFFF_FFFF).to_f / lb end def __ir_log2__(x) @@ -8536,8 +8554,9 @@ def erfc(x) end def __ir_hypot__(x, y) - x = __flt__(x).abs + # y first: MRI's hypot(Get_Double(x), Get_Double(y)) converts its arguments right to left (gcc's order) y = __flt__(y).abs + x = __flt__(x).abs # An infinity wins over a NaN, which is what C's hypot() promises. return ::Float::INFINITY if x.infinite? || y.infinite? return ::Float::NAN if x.nan? || y.nan? From 414e69321ff2eaa597682d2752d7c09fcd8414d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:56:05 +0000 Subject: [PATCH 090/439] Ledger: binding calls on other receivers, counted and not built Gap 1's three named methods: Dictionary#at is specialized already (match, hash and get_bucket inlined); Richards' queue_packet calls a callee with no typed body (add_input_and_check_priority declines at append); CD's get waits for find_node, declined at an attribute read on its loop local. Of every "call:" rejection in app-shapes and the fourteen AWFY traces, the only call on another receiver to a typed callee is Bounce's cold Ball#initialize (random.next, whose callee writes @seed). The walls are callees without typed bodies and attribute access on loop locals (gap 3). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index b964870e3..d0c212e6c 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -499,7 +499,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Richards `device_in_add`, `work_in_add` and `add_input_and_check_priority` are now offered to the compiler and declined at `append` (no typed body: a deopt after an effect) or `NO_WORK` (gap 11); in Json `HashIndexTable#add` and `#get` at - `hash_slot_for`; in DeltaBlue `Dictionary#at` at `match`; in CD `RedBlackTree#get` + `hash_slot_for`; in DeltaBlue `Dictionary#at` at `match` (compiled since perf/havlak: see + Rejected, perf/jitbind, for what the calls on other receivers wait for now); in CD `RedBlackTree#get` at `node.value` and `Node#successor` at `x.right`, attribute reads on a local (the result of the bound `find_node` in `get`, which has no profile; a local that holds self in `successor`): `get` binds `find_node` and fails only there, a small thing to @@ -5392,6 +5393,33 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitbind (2026-11-26) - binding a call on another receiver (a parameter, an ivar, a local + whose class the profile knows) to the callee's typed body, with a generic call as the fallback: + counted, not built - nothing it would take stops there.** The three methods gap 1 names: DeltaBlue's + and Havlak's `Dictionary#at` is specialized already on 9040b98 (`IdEntry#match`, the call on the + loop's `e`, `hash` and `get_bucket` are inlined into it: perf/havlak's inlining on an unsampled + local; the gap's "declines at `match`" was out of date). Richards' `queue_packet` is refused at + `t.add_input_and_check_priority`, but that callee has no typed body to bind to: it is declined + itself at `append` (the effect rule). CD's `RedBlackTree#get` waits for `find_node`, which is + declined at `current.key`, an attribute read on the local its `while` loop reassigns (the + `key.compare_to` on the parameter is inlined there already). Then every "call:" rejection in + app-shapes and the fourteen AWFY traces (3 x 10), with whether its callee had a typed body in the + same run: 24 in app-shapes and 23 in AWFY, of which the callee has none in all but a handful; + those are calls on self (`is_digit`, `is_white_space`, `set_is_root`, `is_shorter_than`, + `internal_init`: `-X:JITCalls`' already), the "no typed body yet" rejections of methods + specialized later in the run (`at`, `add`, `hash_slot_for`), and Towers' `pop_disk_from` at + `top.next`, an attribute reader on a local read from an Array (the callee "specialized" was + `Random#next`, a name match). One call on another receiver to a typed callee is left: Bounce's + `Ball#initialize`, `random.next` on a parameter, a constructor run once per ball, whose callee + writes `@seed` - so each bound call is an effect before the next one that could fail its class + check, and it needs the generic-call fallback after an effect this gap describes, for one cold + method. Not built. + What the walls are now, then: callees without typed bodies (the effect rule: `append`, + `read_string_internal`, `move_top_disk`/`push_disk`, `is_input`, `value` at `new`), and + attribute reads and writes on locals that hold an element or a loop's value (`current.key`, + `top.next`, `x.right` in `successor`). The latter is gap 3's, and the next step for CD and + Towers. + - **perf/jitplain (2026-11-26) - the per-receiver test of perf/jitaref for the typed body's other core operations: nothing to take.** The other operations (`Array#[]=`, `fetch`, `size`, `first`, `last`, `push`/`<<`, `==`, `Hash#[]`/`[]=`/`fetch`/`key?`, `String#size`/`==`/`[]`, the From 7fba338ba2f8537363469a09051200f8756c4bf2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:46:42 +0000 Subject: [PATCH 091/439] Validate the default-spec cache from one pass over the directory, not a glob and a stat per gemspec Every boot runs rubygems/defaults/ironruby.rb's ironruby_load_default_specs, IronRuby's cache of which require names belong to which default gemspec (perf/rubygems-boot). Before trusting the cache it globbed the 62 default gemspecs (Gem::Util.glob_files_in_dir, ~7 ms) and made a File::Stat and a Time for each (~6 ms). Timed with the startup library's precompiled copy, the whole function took ~31 ms of `ir -e 1', the largest part of RubyGems' boot that is IronRuby's own code. The rest of RubyGems' ~120 ms is its own class bodies: specification, requirement, platform, rbconfig. The stamp is now read in C#, in one pass over the directory (IronRuby.__gemspec_stamp__, a private singleton method like Syslog's __openlog__). It gives the name, size and mtime of each entry `Dir.glob("*.gemspec")` would match. A boot that finds the cache valid needs no list of the files, so it no longer globs. A miss, and IRONRUBY_NO_GEM_CACHE=1, still glob and evaluate the gemspecs as before. rubygems/util is required where the glob used to load it, so $LOADED_FEATURES and its order are those of upstream's boot, as CRuby's is. The cache's format version is now 2: a cache of version 1 misses once and is written again. Checked: Gem.loaded_specs, $LOADED_FEATURES, find_default_spec of ten names (default gems, nested names, a non-default name) before and after requiring json, erb and bigdecimal, and the map's size (1,484) print the same on both trees. That holds on a cache hit and with IRONRUBY_NO_GEM_CACHE=1, on the Release build and the R2R host, and with -w. Touching a default gemspec makes the next boot miss and rewrite the cache, and restoring its mtime does too; an unchanged directory hits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/Libraries/Extensions/IronRubyOps.cs | 34 +++++++++++++++++++ .../ruby/4.0/rubygems/defaults/ironruby.rb | 27 +++++++++------ 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/Src/Libraries/Extensions/IronRubyOps.cs b/Src/Libraries/Extensions/IronRubyOps.cs index 89bc661f5..66e60de8e 100644 --- a/Src/Libraries/Extensions/IronRubyOps.cs +++ b/Src/Libraries/Extensions/IronRubyOps.cs @@ -19,6 +19,8 @@ using System.Diagnostics; using System.Collections.Generic; using System.Collections.ObjectModel; +using System; +using System.IO; namespace IronRuby.Builtins { [RubyModule("IronRuby", Extends = typeof(Ruby), Restrictions = ModuleRestrictions.NotPublished)] @@ -34,6 +36,38 @@ public static class IronRubyOps { return context.DomainManager.Globals; } + /// + /// What the default-spec cache of rubygems/defaults/ironruby.rb is valid for: [name, size, mtime] of each entry of the + /// directory that `Dir.glob("*.gemspec")` would match (not a dot file), in ordinal order of the names; mtime in 100 ns + /// ticks. Empty if the directory does not exist. A boot that finds the cache valid then needs neither the glob nor a + /// File::Stat per gemspec, which took ~13 ms of `ir -e 1'. + /// + [RubyMethod("__gemspec_stamp__", RubyMethodAttributes.PrivateSingleton)] + public static RubyArray/*!*/ GetGemspecStamp(RubyContext/*!*/ context, RubyModule/*!*/ self, [NotNull]MutableString/*!*/ dir) { + // (collections of reference types only: their shared code is precompiled, where a List of KeyValuePairs was + // JIT-compiled at the first call - 26 methods, ~2 ms) + var entries = new List(); + var directory = new DirectoryInfo(context.DecodePath(dir)); + if (directory.Exists) { + foreach (FileSystemInfo entry in directory.GetFileSystemInfos()) { + string name = entry.Name; + if (name.EndsWith(".gemspec", StringComparison.Ordinal) && !name.StartsWith(".", StringComparison.Ordinal)) { + entries.Add(entry); + } + } + } + entries.Sort((x, y) => String.CompareOrdinal(x.Name, y.Name)); + + var result = new RubyArray(entries.Count); + foreach (FileSystemInfo entry in entries) { + var file = entry as FileInfo; + long size = (file != null && file.Exists) ? file.Length : 0; + long mtime = entry.Exists ? entry.LastWriteTimeUtc.Ticks : 0; + result.Add(new RubyArray(new object[] { context.EncodePath(entry.Name), Protocols.Normalize(size), Protocols.Normalize(mtime) })); + } + return result; + } + [RubyMethod("loaded_assemblies", RubyMethodAttributes.PublicSingleton)] public static RubyArray/*!*/ GetLoadedAssemblies(RubyContext/*!*/ context, RubyModule/*!*/ self) { return new RubyArray(context.DomainManager.GetLoadedAssemblyList()); diff --git a/Src/StdLib/ruby/4.0/rubygems/defaults/ironruby.rb b/Src/StdLib/ruby/4.0/rubygems/defaults/ironruby.rb index 2cbc8f766..1eae28379 100644 --- a/Src/StdLib/ruby/4.0/rubygems/defaults/ironruby.rb +++ b/Src/StdLib/ruby/4.0/rubygems/defaults/ironruby.rb @@ -322,7 +322,7 @@ def self.ironruby_default_gem_names # :nodoc: # # Set IRONRUBY_NO_GEM_CACHE=1 to fall back to upstream's eager scan. - IRONRUBY_DEFAULT_SPEC_INDEX_VERSION = 1 # :nodoc: + IRONRUBY_DEFAULT_SPEC_INDEX_VERSION = 2 # :nodoc: __hide_constant__ :IRONRUBY_DEFAULT_SPEC_INDEX_VERSION ## @@ -347,13 +347,13 @@ def self.ironruby_default_spec_index_file # :nodoc: ## # Cheap fingerprint of the default specifications directory: every gemspec's # name, size and mtime. Installing, removing or updating a default gem - # changes it, which is exactly when the mapping has to be rebuilt. + # changes it, which is exactly when the mapping has to be rebuilt. It is + # read in one pass over the directory (IronRuby.__gemspec_stamp__): a glob + # and a File::Stat per gemspec took ~13 ms of every boot, and a boot that + # finds the cache valid needs no list of the files. - def self.ironruby_default_spec_stamp(files) # :nodoc: - files.sort.map do |file| - stat = File.stat(file) - [File.basename(file), stat.size, stat.mtime.to_i] - end + def self.ironruby_default_spec_stamp(dir) # :nodoc: + IronRuby.__send__(:__gemspec_stamp__, dir) end ## @@ -386,16 +386,20 @@ def self.find_default_spec(path) # :nodoc: # while recording the mapping for next time. def self.ironruby_load_default_specs # :nodoc: + # Upstream's load_defaults globs with Gem::Util, which loads rubygems/util + # at boot; a boot that finds the cache valid needs no glob, and loads it + # here so that $LOADED_FEATURES is what upstream's boot leaves. + require_relative "../util" dir = Gem.default_specifications_dir - files = Gem::Util.glob_files_in_dir("*.gemspec", dir) - return if files.empty? stamp = nil cached = nil features = nil unless ENV["IRONRUBY_NO_GEM_CACHE"] begin - stamp = ironruby_default_spec_stamp(files) + stamp = ironruby_default_spec_stamp(dir) + # no gemspec: nothing to register (upstream's glob finds none either) + return if stamp.empty? data = File.open(ironruby_default_spec_index_file, "rb", &:read) data = Marshal.load(data) if data.is_a?(Hash) && @@ -420,6 +424,9 @@ def self.ironruby_load_default_specs # :nodoc: return end + files = Gem::Util.glob_files_in_dir("*.gemspec", dir) + return if files.empty? + loaded_before = $LOADED_FEATURES.dup # Cache miss: do exactly what upstream does, and note which gemspec each From f6885ca0fc0e305af3b2930400cb1a83bf260584 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:58:58 +0000 Subject: [PATCH 092/439] Ledger: the jump-ensure rethrow, measured and not built An ensure clause with a block call, yield, zsuper or a jump is a catch and a throw again (the DLR's FlowControlRewriter) and takes the backtrace eagerly: the first such frame on a raise's path costs about 43 us, each further one about 4.5. But the prelude has none, the stdlib's 25 are in cold code, and a raise through Monitor, Mutex, File.open, Timeout or the block iterators meets none. Timeout with a raise costs 152-164 us against CRuby's 3.1 for another reason, still to be found: the next step. Shapes: Util/bench/ensure-jump-shapes.rb, Util/bench/raise-through-shapes.rb. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/bench/ensure-jump-shapes.rb | 26 ++++++++++++++++++++++++++ Util/bench/raise-through-shapes.rb | 29 +++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 27 +++++++++++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 Util/bench/ensure-jump-shapes.rb create mode 100644 Util/bench/raise-through-shapes.rb diff --git a/Util/bench/ensure-jump-shapes.rb b/Util/bench/ensure-jump-shapes.rb new file mode 100644 index 000000000..f96ef32d2 --- /dev/null +++ b/Util/bench/ensure-jump-shapes.rb @@ -0,0 +1,26 @@ +# Raise and rescue through 1 and 20 frames whose `ensure` is plain, calls a block, or yields: an ensure clause with a jump +# (a block call, yield, zsuper, return/break/next/retry) is rewritten by the DLR into a catch and a throw again, and keeps the +# backtrace from being deferred (Body.EnsureJumpFinder, GotoFinder; frameDepth -1). us per raise, best of five. +# IR_CONFIG=Release ./ir.sh Util/bench/ensure-jump-shapes.rb; ruby Util/bench/ensure-jump-shapes.rb +$stdout.sync = true +N = (ENV['N'] || 2000).to_i +def plain(d) = d == 0 ? raise("x") : (begin; plain(d - 1); ensure; @z = 1; end) +def blk(d) = d == 0 ? raise("x") : (begin; blk(d - 1); ensure; [1].each { |v| @z = v }; end) +def yl(d, &b) = d == 0 ? raise("x") : (begin; yl(d - 1, &b); ensure; yield; end) +def none(d) = d == 0 ? raise("x") : none(d - 1) +def run(name, depth) + best = nil + 5.times do + t = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) + N.times { begin; yield depth; rescue; end } + d = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) - t + best = d if best.nil? || d < best + end + printf "%-12s depth %2d %8.2f us\n", name, depth, best * 1e6 / N +end +[1, 20].each do |dp| + run("none", dp) { |d| none(d) } + run("plain", dp) { |d| plain(d) } + run("blk", dp) { |d| blk(d) } + run("yield", dp) { |d| yl(d) { @z = 2 } } +end diff --git a/Util/bench/raise-through-shapes.rb b/Util/bench/raise-through-shapes.rb new file mode 100644 index 000000000..a6a3fe5eb --- /dev/null +++ b/Util/bench/raise-through-shapes.rb @@ -0,0 +1,29 @@ +# A raise rescued through the library frames real code puts around it (Monitor, Mutex, File.open, Timeout, iterators): +# us per raise, best of five, against a bare raise. +# IR_CONFIG=Release ./ir.sh Util/bench/raise-through-shapes.rb; ruby Util/bench/raise-through-shapes.rb +$stdout.sync = true +require 'monitor'; require 'timeout'; require 'tempfile' +N = (ENV['N'] || 1000).to_i +M = Monitor.new; MX = Mutex.new +path = File.join(Dir.tmpdir, "ens2-#{$$}"); File.write(path, "x") +def run(name) + best = nil + 5.times do + t = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) + N.times { begin; yield; rescue RuntimeError; end } + d = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) - t + best = d if best.nil? || d < best + end + printf "%-22s %8.2f us\n", name, best * 1e6 / N +end +run("bare raise") { raise "x" } +run("Monitor#synchronize") { M.synchronize { raise "x" } } +run("Mutex#synchronize") { MX.synchronize { raise "x" } } +run("File.open block") { File.open(path) { raise "x" } } +run("Timeout.timeout") { Timeout.timeout(5) { raise "x" } } +run("Array#each") { [1].each { raise "x" } } +run("Integer#times") { 1.times { raise "x" } } +run("Hash#each") { {a: 1}.each { raise "x" } } +run("loop") { loop { raise "x" } } +run("tap") { 1.tap { raise "x" } } +File.delete(path) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index d0c212e6c..18eb336d4 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -5393,6 +5393,33 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/ensure (2026-11-26) - the catch-and-rethrow of an `ensure` clause that jumps (#213 item 3): + measured, not built - real code almost never has such a frame on a raise's path.** Compiled, an + `ensure` already lets an exception go through a CLR filter (`EnsureGuardExpression`, + `RubyOps.PassEnsure`); a clause with a jump in it - a call with a block, `yield`, zsuper, + `return`/`break`/`next`/`retry` (`Body.EnsureJumpFinder`, `GotoFinder`) - is made a catch of + everything and a throw again by the DLR's FlowControlRewriter, and its guard gets frame depth -1, + so an exception whose backtrace is still to be taken is caught there. + Cost (`Util/bench/ensure-jump-shapes.rb`, new, us per raise rescued, IronRuby / CRuby): one frame + plain 12.5 / 0.79, calling a block 55 / 0.99, yielding 61 / 0.87; twenty frames plain 28 / 2.3, + block 119 / 4.2, yield 112 / 3.1. So the first such frame costs about 43 us - the backtrace taken + eagerly where the plain ensure defers it - and each further one about 4.5 us, the rethrow. + How often: the prelude's 24 `ensure` clauses have no jump; of 276 in `Src/StdLib/ironruby` and + `ruby/4.0`, 25 do, all in cold code - socket helpers (4), bundler's DSL, CLI and settings (6), + open3 (2), irb (2), resolv, mkmf, rdoc, rubygems, puma (2), pty, msgpack, bigdecimal. A raise + through the frames real code puts around it (`Util/bench/raise-through-shapes.rb`, new, us, + IronRuby / CRuby): bare 8.1 / 0.59, Monitor#synchronize 11.7 / 0.67, Mutex#synchronize 11.8 / + 0.68, File.open with a block 16.3 / 2.1, Array#each 16.0 / 0.69, Integer#times 15.9, Hash#each + 16.2, loop 17.3, tap 14.8 - none carries the ~43 us of a jump-ensure. The rethrow is real but off + the paths that raise; a DLR patch for it (Build/dlr-patches) was not written. + Found instead: **`Timeout.timeout` with a raise in its block costs 152-164 us against CRuby's 3.1** + (9.2 / 2.0 without the raise). Its own ensure (`request.finished`) has no jump; the path has + `return yield(sec)` from a Proc inside a begin/ensure, and `Error.handle_timeout`'s `rescue + ExitException => e` with `raise` again (a class list by constant, so a catch and a backtrace, then a + re-raise). Pieces of it measured alone: a `rescue E2 => e` frame 12.3 us, a Proc with `return + yield` and an ensure 15-31, the two together 44: they do not add up to 155, so the rest is still to + be found. That is the next step here, not the ensure rethrow. + - **perf/jitbind (2026-11-26) - binding a call on another receiver (a parameter, an ivar, a local whose class the profile knows) to the callee's typed body, with a generic call as the fallback: counted, not built - nothing it would take stops there.** The three methods gap 1 names: DeltaBlue's From 8d7efda2907372ab49c650e229a4efb9d49d313c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:02:42 +0000 Subject: [PATCH 093/439] Take next on Hash#select/reject, filter_map, flat_map and each_with_object with a cursor These enumerators still ran their external iteration on a fiber, a thread here: 5-14 us of process CPU per #next against CRuby's 0.24-0.34, and 1.0-1.3 ms and a thread for each enumerator abandoned after one #next. Hash's own #select, #filter and #reject copy the receiver when the iteration starts, as IDictionaryOps.Filter and MRI's rb_hash_select do. The cursor walks the copy with key and value as a step's two values, and drops a pair the fed answer does not keep; the copy is StopIteration#result. The prelude's Enumerable#filter_map, #flat_map / #collect_concat and #each_with_object, and Array's own #each_with_object, get cursors over any receiver whose #each has one, while they are the methods registered with __iter_cursor_method__. #flat_map converts an answer that is not an Array with Array.try_convert, which runs Ruby code. So such a cursor resumes before the cursor's lock is taken, on the owning thread, as MRI's flat_map_i converts after the yield. An error ends that iteration, and the next #next starts a fresh one. A conversion that calls back into the same enumerator raises FiberError, as MRI's does. next, peek, next_values and peek_values take a second call-site storage for it, since a storage holds one site. The handler around that Resume lives in a NoInlining method of its own: written in CursorStep, it made every StopIteration a cursor throws about 600 ns (15%) slower. IR_FAST_NEXT=0 leaves these to the fiber. Util/bench/extiter-shapes.rb (ab.rb -r 6, ns per next, off -> new; CRuby): a Hash's select 14310 -> 257 (314), reject 9841 -> 194 (279), [1000].filter_map 5305 -> 105 (240), flat_map 5663 -> 132 (312), each_with_object 5746 -> 155 (255); the earlier shapes level with base. Abandoned after one next: 8-20 us and no thread each. Util/extiter-matrix.rb (312 probes, 50 new) prints CRuby's output with the change; the baseline and the switched-off build differ from it only where a #to_ary calls back into the enumerator. enum-next, block-loop, hash-order, raise, full-message, enum and enumerable2 matrices agree with the baseline in every mode. spec/core/ enumerator, hash, enumerable and kernel/loop give the same result in all three. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Src/Libraries/Builtins/Enumerator.cs | 245 ++++++++++++++++++++++++--- Src/StdLib/ironruby/ruby4.rb | 9 +- Util/bench/extiter-abandoned.rb | 4 + Util/bench/extiter-shapes.rb | 6 + Util/extiter-matrix.rb | 52 ++++++ Util/perf/LEDGER.md | 52 +++++- 6 files changed, 340 insertions(+), 28 deletions(-) diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index 644732f7b..f8ef88b3d 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -260,7 +260,7 @@ public static object GetSizeInfo(RubyContext/*!*/ context, Enumerator/*!*/ self) private bool _hasFeed; // __iter_slow__'s operations. - private const int SlowAdvance = 0, SlowPeek = 1, SlowAcrossThreads = 2; + private const int SlowAdvance = 0, SlowPeek = 1, SlowAcrossThreads = 2, SlowResumeCurrent = 3; /// /// Where the iteration of a built-in method has got to. A cursor belongs to the Ruby thread @@ -297,9 +297,20 @@ internal virtual void Finish() { /// The yield of the last step has returned, with the value fed to it (Enumerator#feed) or nil: what the method's /// block would have answered. /// - internal virtual void Resume(object fed) { + internal virtual void Resume(CallSiteStorage>/*!*/ sites, object fed) { } + /// + /// Its runs Ruby code (#flat_map's Array.try_convert): CursorStep calls it before it takes the + /// lock, on the thread that owns the cursor, and an error it raises ends the iteration as an error in the method would. + /// + internal virtual bool ResumesWithRubyCode { + get { return false; } + } + + // Resume has run for the step about to be taken, outside the lock (CursorStep); it is running. + internal bool ResumedEarly, Resuming; + /// What the method answers (StopIteration#result), once it has returned. internal virtual object Result { get { return Receiver; } @@ -308,7 +319,9 @@ internal virtual object Result { // What a collecting method does with what its block answers, the block being the suspended yield of #next: #map // keeps the answers, #select (#filter, #find_all) the elements it answered true for, #reject the others. - private const int CollectMap = 0, CollectSelect = 1, CollectReject = 2; + // #filter_map keeps the answers that are true, #flat_map (#collect_concat) the elements of each answer that is an + // Array or converts to one (Array.try_convert, MRI's rb_check_array_type), and any other answer itself. + private const int CollectMap = 0, CollectSelect = 1, CollectReject = 2, CollectFilterMap = 3, CollectFlatMap = 4; // Array#map, #collect, #select, #filter and #reject (IListOps): the length is read at each step, as Array#each's // is; #select keeps the element as it is once the block has run (MRI's rb_ary_elt), #reject the one it yielded. @@ -335,7 +348,7 @@ internal override bool MoveNext(out object value) { return false; } - internal override void Resume(object fed) { + internal override void Resume(CallSiteStorage>/*!*/ sites, object fed) { if (_kind == CollectMap) { _result.Add(fed); } else if (_kind == CollectSelect) { @@ -379,14 +392,40 @@ internal override bool MoveNext(out object value) { return false; } - internal override void Resume(object fed) { - if (_kind == CollectMap) { - _result.Add(fed); - } else if (Protocols.IsTrue(fed) == (_kind == CollectSelect)) { - _result.Add(_current); + internal override void Resume(CallSiteStorage>/*!*/ sites, object fed) { + switch (_kind) { + case CollectMap: + _result.Add(fed); + break; + case CollectFilterMap: + if (Protocols.IsTrue(fed)) { + _result.Add(fed); + } + break; + case CollectFlatMap: + var array = fed as RubyArray; + if (array == null && fed != null) { + var site = sites.GetCallSite("try_convert", 1); + array = site.Target(site, sites.Context.GetClass(typeof(RubyArray)), fed) as RubyArray; + } + if (array != null) { + _result.AddRange(array); + } else { + _result.Add(fed); + } + break; + default: + if (Protocols.IsTrue(fed) == (_kind == CollectSelect)) { + _result.Add(_current); + } + break; } } + internal override bool ResumesWithRubyCode { + get { return _kind == CollectFlatMap; } + } + internal override void Finish() { _inner.Finish(); } @@ -396,6 +435,56 @@ internal override object Result { } } + // Hash#select, #filter and #reject (IDictionaryOps.Filter): as MRI's rb_hash_select, the receiver is copied - a plain + // Hash with its compare_by_identity, the entries with their hash codes - when the method starts, the copy is walked, + // and a pair the block's answer does not keep is dropped from it. The steps are key and value, two values. + private sealed class HashFilterCursor : ExternalCursor { + private readonly Hash/*!*/ _result; + private readonly bool _keepWhen; + private int _index; + + private HashFilterCursor(Hash/*!*/ receiver, Hash/*!*/ result, bool keepWhen) : base(receiver) { + _result = result; + _keepWhen = keepWhen; + } + + // null where Filter would not copy the entries (and copies the pairs one by one instead) + internal static HashFilterCursor TryCreate(RubyContext/*!*/ context, Hash/*!*/ receiver, bool keepWhen) { + var result = new Hash(context); + if (receiver.ComparesByIdentity) { + result.CompareByIdentity(); + } + return result.TryCopyEntriesFrom(receiver) ? new HashFilterCursor(receiver, result, keepWhen) : null; + } + + internal override bool Multiple { + get { return true; } + } + + internal override bool MoveNext(out object value) { + object key, entryValue; + if (_result.TryGetNextEntry(ref _index, out key, out entryValue)) { + var values = new RubyArray(2); + values.Add(CustomStringDictionary.ObjToNull(key)); + values.Add(entryValue); + value = values; + return true; + } + value = null; + return false; + } + + internal override void Resume(CallSiteStorage>/*!*/ sites, object fed) { + if (Protocols.IsTrue(fed) != _keepWhen) { + _result.RemoveEntryAt(_index - 1); + } + } + + internal override object Result { + get { return _result; } + } + } + // Enumerable#each_slice and #each_cons (EachSlice) over a cursor of the receiver's #each: a new // Array per slice; each_slice ends with the incomplete slice, each_cons drops it. private sealed class SliceCursor : ExternalCursor { @@ -551,8 +640,12 @@ internal override bool MoveNext(out object value) { return true; } - internal override void Resume(object fed) { - _inner.Resume(fed); + internal override void Resume(CallSiteStorage>/*!*/ sites, object fed) { + _inner.Resume(sites, fed); + } + + internal override bool ResumesWithRubyCode { + get { return _inner.ResumesWithRubyCode; } } internal override void Finish() { @@ -748,6 +841,10 @@ private sealed class PreludeMethods { internal RubyMemberInfo EachCons; internal RubyMemberInfo StopIterationResult; internal RubyMemberInfo LazyEach; + internal RubyMemberInfo FilterMap; + internal RubyMemberInfo FlatMap; + internal RubyMemberInfo CollectConcat; + internal RubyMemberInfo EachWithObject; } private static readonly object _preludeMethodsKey = new object(); @@ -775,6 +872,14 @@ public static object RegisterCursorMethod(RubyContext/*!*/ context, object self, methods.EachSlice = method.Info; } else if (name == "each_cons") { methods.EachCons = method.Info; + } else if (name == "filter_map") { + methods.FilterMap = method.Info; + } else if (name == "flat_map") { + methods.FlatMap = method.Info; + } else if (name == "collect_concat") { + methods.CollectConcat = method.Info; + } else if (name == "each_with_object") { + methods.EachWithObject = method.Info; } else if (name == "result") { methods.StopIterationResult = method.Info; } @@ -828,6 +933,9 @@ private static ExternalCursor TryCreateCursor(RubyContext/*!*/ context, Enumerat if (args.Length == 1 && args[0] is int && (name == "each_slice" || name == "each_cons")) { return TryCreateSliceCursor(context, target, name, (int)args[0]); } + if (args.Length == 1 && name == "each_with_object") { + return TryCreateEachWithObjectCursor(context, target, args[0]); + } if (args.Length != 0) { return null; } @@ -853,6 +961,15 @@ private static ExternalCursor TryCreateCursor(RubyContext/*!*/ context, Enumerat case "reject": return TryCreateCollectCursor(context, target, name, CollectReject); + case "filter_map": + return TryCreatePreludeCollectCursor(context, target, name, GetPreludeMethods(context).FilterMap, CollectFilterMap); + + case "flat_map": + return TryCreatePreludeCollectCursor(context, target, name, GetPreludeMethods(context).FlatMap, CollectFlatMap); + + case "collect_concat": + return TryCreatePreludeCollectCursor(context, target, name, GetPreludeMethods(context).CollectConcat, CollectFlatMap); + case "each_pair": return (hash = target as Hash) != null && IsBuiltinMethod(context, target, name, typeof(IDictionaryOps), "Each", "EachPair") ? new HashCursor(hash, HashCursor.Pairs) : null; @@ -913,6 +1030,12 @@ private static ExternalCursor TryCreateCollectCursor(RubyContext/*!*/ context, o if (!_fastNext) { return null; } + // Hash's own, whose result is a Hash + Hash hash = target as Hash; + if (hash != null && kind != CollectMap && name != "find_all") { + return IsBuiltinMethod(context, target, name, typeof(IDictionaryOps), "Select", kind == CollectReject ? "Reject" : name == "filter" ? "Filter" : "Select") ? + HashFilterCursor.TryCreate(context, hash, kind == CollectSelect) : null; + } // the C# methods of the name: the blockless one that made the enumerator, and the one with a block it stands for string impl = (kind == CollectMap) ? (name == "collect" ? "Collect" : "Map") : (kind == CollectReject) ? "Reject" : (name == "filter" ? "Filter" : name == "find_all" ? "FindAll" : "Select"); @@ -970,6 +1093,33 @@ private static ExternalCursor TryCreateIndexCursor(RubyContext/*!*/ context, Enu new IndexCursor(self, inner, (int)self._indexArgument, false); } + // Enumerable#filter_map, #flat_map and #collect_concat, the prelude's, over a receiver whose #each a cursor walks. + private static ExternalCursor TryCreatePreludeCollectCursor(RubyContext/*!*/ context, object target, string/*!*/ name, + RubyMemberInfo expected, int kind) { + if (!_fastNext || !IsPreludeMethod(context, target, name, expected)) { + return null; + } + ExternalCursor inner = TryCreateEachCursor(context, target); + return inner != null ? new EnumerableCollectCursor(target, inner, kind) : null; + } + + // #each_with_object: Array's own (IListOps, which reads the length at each step, as #each does), or Enumerable's, the + // prelude's, over a receiver whose #each a cursor walks: [element, memo], and the memo at the end. + private static ExternalCursor TryCreateEachWithObjectCursor(RubyContext/*!*/ context, object target, object memo) { + if (!_fastNext) { + return null; + } + RubyArray array = target as RubyArray; + if (array != null && IsBuiltinMethod(context, target, "each_with_object", typeof(IListOps), "GetEachWithObjectEnumerator", "EachWithObject")) { + return new IndexCursor(target, new ArrayCursor(array, false), memo); + } + if (!IsPreludeMethod(context, target, "each_with_object", GetPreludeMethods(context).EachWithObject)) { + return null; + } + ExternalCursor inner = TryCreateEachCursor(context, target); + return inner != null ? new IndexCursor(target, inner, memo) : null; + } + // The receiver's own #each, when it is a built-in one a cursor can do. private static ExternalCursor TryCreateEachCursor(RubyContext/*!*/ context, object target) { RubyArray array; @@ -1121,12 +1271,21 @@ private static ExternalCursor GetCursor(CallSiteStorage private static object CursorStep(CallSiteStorage>/*!*/ slowStorage, - Enumerator/*!*/ self, ExternalCursor/*!*/ cursor, bool consume) { + CallSiteStorage>/*!*/ convertStorage, Enumerator/*!*/ self, ExternalCursor/*!*/ cursor, + bool consume) { RubyContext context = slowStorage.Context; StopIteration stop = null; bool first = false, acrossThreads = false; object value; + + // The suspended yield returns: a cursor whose Resume runs Ruby code has it run here, before the lock. Only the owner + // advances the iteration, and only when no value is waiting (a thread that is not the owner takes a peeked one, and + // nothing else). An error ends the iteration, and the next #next starts a fresh one (MRI's next_init). + if (cursor.ResumesWithRubyCode) { + ResumeWithRubyCode(slowStorage, convertStorage, self, cursor); + } + using (new RubyUtils.UninterruptedLock(cursor)) { if (!cursor.Peeked) { if (cursor.Done) { @@ -1139,7 +1298,11 @@ private static object CursorStep(CallSiteStorage>/*!*/ slowStorage, + CallSiteStorage>/*!*/ convertStorage, Enumerator/*!*/ self, ExternalCursor/*!*/ cursor) { + + if (cursor.Thread != RubyUtils.CurrentRubyThread) { + return; + } + if (cursor.Resuming) { + // the Ruby code Resume runs is the method's, between two of its yields: the iteration is under way on this + // thread, as MRI's fiber is running + SlowStep(slowStorage, self, SlowResumeCurrent); + } + if (!cursor.Started || cursor.Peeked || cursor.Done || cursor.ResumedEarly) { + return; + } + object fed = self._hasFeed ? self._feedValue : null; + try { + cursor.Resuming = true; + cursor.Resume(convertStorage, fed); + } catch { + cursor.Resuming = false; + using (new RubyUtils.UninterruptedLock(cursor)) { + cursor.Done = true; + cursor.Finish(); + } + Interlocked.CompareExchange(ref self._cursor, null, cursor); + self._feedValue = null; + self._hasFeed = false; + throw; + } + cursor.Resuming = false; + cursor.ResumedEarly = true; + } + private static StopIteration/*!*/ CreateStopIteration(RubyContext/*!*/ context, object result, StopIteration cause) { var stop = new StopIteration("iteration reached an end"); context.SetInstanceVariable(stop, RubyUtils.GetCoreStateInstanceVariableName("@__result__"), result); @@ -1233,40 +1432,44 @@ private static object ValuesToValue(RubyArray/*!*/ values, bool copy) { } [RubyMethod("next")] - public static object Next(CallSiteStorage>/*!*/ slowStorage, Enumerator/*!*/ self) { + public static object Next(CallSiteStorage>/*!*/ slowStorage, + CallSiteStorage>/*!*/ convertStorage, Enumerator/*!*/ self) { var cursor = GetCursor(slowStorage, self); if (cursor == null) { return ValuesToValue(SlowStep(slowStorage, self, SlowAdvance), false); } - return CursorStep(slowStorage, self, cursor, true); + return CursorStep(slowStorage, convertStorage, self, cursor, true); } [RubyMethod("peek")] - public static object Peek(CallSiteStorage>/*!*/ slowStorage, Enumerator/*!*/ self) { + public static object Peek(CallSiteStorage>/*!*/ slowStorage, + CallSiteStorage>/*!*/ convertStorage, Enumerator/*!*/ self) { var cursor = GetCursor(slowStorage, self); if (cursor == null) { return ValuesToValue(SlowStep(slowStorage, self, SlowPeek), true); } - object value = CursorStep(slowStorage, self, cursor, false); + object value = CursorStep(slowStorage, convertStorage, self, cursor, false); return cursor.Multiple ? new RubyArray((RubyArray)value) : value; } [RubyMethod("next_values")] - public static RubyArray/*!*/ NextValues(CallSiteStorage>/*!*/ slowStorage, Enumerator/*!*/ self) { + public static RubyArray/*!*/ NextValues(CallSiteStorage>/*!*/ slowStorage, + CallSiteStorage>/*!*/ convertStorage, Enumerator/*!*/ self) { var cursor = GetCursor(slowStorage, self); if (cursor == null) { return SlowStep(slowStorage, self, SlowAdvance); } - return CursorValues(cursor, CursorStep(slowStorage, self, cursor, true), false); + return CursorValues(cursor, CursorStep(slowStorage, convertStorage, self, cursor, true), false); } [RubyMethod("peek_values")] - public static RubyArray/*!*/ PeekValues(CallSiteStorage>/*!*/ slowStorage, Enumerator/*!*/ self) { + public static RubyArray/*!*/ PeekValues(CallSiteStorage>/*!*/ slowStorage, + CallSiteStorage>/*!*/ convertStorage, Enumerator/*!*/ self) { var cursor = GetCursor(slowStorage, self); if (cursor == null) { return new RubyArray(SlowStep(slowStorage, self, SlowPeek)); } - return CursorValues(cursor, CursorStep(slowStorage, self, cursor, false), true); + return CursorValues(cursor, CursorStep(slowStorage, convertStorage, self, cursor, false), true); } /// diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index f9120d8ef..50c26d44f 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -246,6 +246,8 @@ def filter_map(&block) end result end unless method_defined?(:filter_map) + # Enumerator#next walks a #filter_map with a cursor while this is the method (Enumerator.cs). + ::Enumerator.__iter_cursor_method__(self, :filter_map) # The optional Hash counts into it instead of into a fresh one, which also # means the frozen check happens before the first element is looked at. @@ -487,6 +489,7 @@ def each_with_object(memo) each { |*values| yield(__enum_item__(values), memo) } memo end unless method_defined?(:each_with_object) + ::Enumerator.__iter_cursor_method__(self, :each_with_object) # Ruby 2.2 added the `n` form: the n smallest/largest, as an Array. # @@ -698,6 +701,8 @@ def collect_concat(&block) end __ir_same_method__(:collect_concat, :flat_map) end + ::Enumerator.__iter_cursor_method__(self, :flat_map) + ::Enumerator.__iter_cursor_method__(self, :collect_concat) def uniq(&block) seen = {} @@ -5897,9 +5902,11 @@ def __iter_advance__ # The fiber's half of #next (op 0: the values of the next step, taken), #peek # (op 1: the same values, left for the next #next; the caller copies them) - and - # the FiberError of a cursor another thread started (op 2). + # the FiberErrors of a cursor another thread started (op 2) and of one in use (op 3). def __iter_slow__(op) ::Kernel.raise(::FiberError, "fiber called across threads") if op == 2 + # a cursor's #flat_map converting the block's answer, which calls back into this enumerator (op 3) + ::Kernel.raise(::FiberError, "attempt to resume the current fiber") if op == 3 __iter_advance__ values = @__peek__ if op == 0 diff --git a/Util/bench/extiter-abandoned.rb b/Util/bench/extiter-abandoned.rb index 538e27ea9..9931a9b38 100644 --- a/Util/bench/extiter-abandoned.rb +++ b/Util/bench/extiter-abandoned.rb @@ -25,6 +25,10 @@ def make_gen = Enumerator.new { |y| y << 1; y << 2 } "gen_block_local" => -> { e = Enumerator.new { |y| y << 1; y << 2 }; e.next }, # a cursor: no fiber at all "map_local" => -> { e = [1, 2, 3].map; e.next }, + "hash_select_local" => -> { e = { a: 1, b: 2 }.select; e.next }, + "filter_map_local" => -> { e = [1, 2, 3].filter_map; e.next }, + "flat_map_local" => -> { e = [1, 2, 3].flat_map; e.next }, + "ewo_local" => -> { e = { a: 1, b: 2 }.each_with_object([]); e.next }, } abort(KINDS.keys.join("\n")) unless ARGV[0] kind = ARGV[0] diff --git a/Util/bench/extiter-shapes.rb b/Util/bench/extiter-shapes.rb index 8942074c8..823543a5e 100644 --- a/Util/bench/extiter-shapes.rb +++ b/Util/bench/extiter-shapes.rb @@ -63,6 +63,12 @@ def peeks(e) t("hash_ewi", n(20_000)) { |n| s = 0; (n / 100).times { e = HSH.each_with_index; 100.times { s += e.next[1] } }; s } t("map_wi", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.map.with_index) }; s } t("wobj_next", n(20_000)) { |n| s = 0; (n / 1000).times { e = LARGE.each.with_object(1); 1000.times { s += e.next[0] } }; s } +t("hash_select", n(20_000)) { |n| s = 0; (n / 100).times { e = HSH.select; 100.times { k, v = e.next; e.feed k.odd?; s += v } }; s } +t("hash_reject", n(20_000)) { |n| s = 0; (n / 100).times { e = HSH.reject; 100.times { s += e.next[1] } }; s } +t("filter_map", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.filter_map) }; s } +t("flat_map", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.flat_map) }; s } +t("ewo_next", n(20_000)) { |n| s = 0; (n / 1000).times { e = LARGE.each_with_object([]); 1000.times { s += e.next[0] } }; s } +t("hash_ewo", n(20_000)) { |n| s = 0; (n / 100).times { e = HSH.each_with_object(1); 100.times { s += e.next[1] } }; s } t("select_next", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.select) }; s } t("lazy_next", n(5_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.lazy.map { |x| x + 1 }) }; s } t("produce", n(20_000)) { |n| s = 0; (n / 1000).times { e = Enumerator.produce(1) { |x| x + 1 }; 1000.times { s += e.next } }; s } diff --git a/Util/extiter-matrix.rb b/Util/extiter-matrix.rb index 0b8e953f0..2722769c7 100644 --- a/Util/extiter-matrix.rb +++ b/Util/extiter-matrix.rb @@ -626,3 +626,55 @@ def lz(e, n = 4) = n.times.map { (e.next rescue :stop) } probe("lz_dup_fresh") { e = [1, 2].lazy.map { |x| x * 5 }; d = e.dup; [d.next, e.next] } probe("lz_thread") { e = [1, 2].lazy.map { |x| x }; e.next; Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value } probe("lz_raises") { e = [1, 2].lazy.map { |x| x == 2 ? raise(ArgumentError, "two") : x }; [e.next, (e.next rescue "#{$!.class}: #{$!.message}"), e.next] } + +# --- Hash#select / #filter / #reject (a Hash), filter_map, flat_map, each_with_object taken with #next --- +probe("hs_select") { fed_result({ a: 1, b: 2, c: 3 }.select, [true, nil, 1]) } +probe("hs_filter") { fed_result({ a: 1, b: 2 }.filter, [false, :y]) } +probe("hs_reject") { fed_result({ a: 1, b: 2, c: 3 }.reject, [true, nil, false]) } +probe("hs_no_feed") { [stop_of({ a: 1 }.select).result, stop_of({ a: 1 }.reject).result, stop_of({}.select).result] } +probe("hs_values") { e = { a: 1 }.select; [e.peek, e.peek_values, e.next_values] } +probe("hs_result_class") { c = Class.new(Hash); h = c[a: 1]; r = stop_of(h.select).result; [r, r.class == Hash] } +probe("hs_default") { h = Hash.new(5); h[:a] = 1; r = stop_of(h.reject).result; [r, r.default, r[:zz]] } +probe("hs_default_proc") { h = Hash.new { |_, k| k }; h[:a] = 1; r = stop_of(h.select).result; [r.default_proc.nil?, r[:q]] } +probe("hs_identity") { h = {}.compare_by_identity; h["a"] = 1; e = h.select; e.next; e.feed true; r = stop_of(e).result; [r.compare_by_identity?, r] } +probe("hs_add_during") { h = { a: 1 }; e = h.select; e.next; h[:b] = 2; e.feed true; [(e.next rescue :stop), h] } +probe("hs_delete_during") { h = { a: 1, b: 2 }; e = h.reject; e.next; h.delete(:b); [e.next, stop_of(e).result, h] } +probe("hs_change_during") { h = { a: 1, b: 2 }; e = h.select; e.next; h[:b] = 9; e.feed true; [e.next, stop_of(e).result] } +probe("hs_frozen_src") { h = { a: 1 }.freeze; e = h.select; e.next; e.feed true; r = stop_of(e).result; [r, r.frozen?] } +probe("hs_peek_feed") { e = { a: 1, b: 2 }.select; e.peek; e.next; e.feed true; e.peek; e.next; [stop_of(e).result] } +probe("hs_rewind") { e = { a: 1, b: 2 }.select; e.next; e.feed true; e.rewind; e.next; stop_of(e).result } +probe("hs_loop") { e = { a: 1, b: 2, c: 3 }.select; loop { _, v = e.next; e.feed v.odd? } } +probe("hs_singleton") { h = { a: 1 }; def h.select; yield :own, 0; :own_r; end; e = h.select; [e.next, stop_of(e).result] } +probe("hs_subclass_redef"){ c = Class.new(Hash) { def reject; return to_enum(:reject) unless block_given?; super.merge(extra: 1); end }; e = c[a: 1].reject; e.next; [stop_of(e).result] } +probe("hs_with_index") { e = { a: 1 }.select.with_index; [e.next, stop_of(e).result] } +probe("hs_thread") { e = { a: 1, b: 2 }.select; e.next; Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value } +probe("fm_array") { fed_result([1, 2, 3].filter_map, [:a, false, nil]) } +probe("fm_hash") { e = { a: 1, b: 2 }.filter_map; [e.next, e.peek_values].tap { e.feed :x; e.next; e.feed nil }.push(stop_of(e).result) } +probe("fm_range") { fed_result((1..3).filter_map, [1, nil, :c]) } +probe("fm_no_feed") { stop_of([1, 2].filter_map).result } +probe("fm_redef") { c = Class.new(Array) { def filter_map; return to_enum(:filter_map) unless block_given?; [:own]; end }; e = c.new([1]).filter_map; [e.next, stop_of(e).result] } +probe("fm_module_redef") { m = Module.new { def filter_map(&b) = b ? [:mod] : to_enum(:filter_map) }; c = Class.new(Array) { include m }; e = c.new([1]).filter_map; e.next; stop_of(e).result } +probe("flm_array") { fed_result([1, 2, 3].flat_map, [[:a, :b], 5, nil]) } +probe("flm_concat") { fed_result([1, 2].collect_concat, [[1, [2]], []]) } +probe("flm_hash") { e = { a: 1 }.flat_map; [e.next, e.next_values.size].tap { } rescue [$!.class] } +probe("flm_hash_feed") { e = { a: 1, b: 2 }.flat_map; e.next; e.feed [:x, :y]; e.next; [stop_of(e).result] } +probe("flm_range") { fed_result((1..2).flat_map, [[9], [8, 7]]) } +probe("flm_to_ary") { o = Object.new; def o.to_ary = [:t, :u]; fed_result([1].flat_map, [o]) } +probe("flm_to_ary_nil") { o = Object.new; def o.to_ary = nil; r = fed_result([1].flat_map, [o]); [r[0], r[1].size, r[1][0].equal?(o)] } +probe("flm_bad_to_ary") { o = Object.new; def o.to_ary = 5; e = [1, 2].flat_map; e.next; e.feed o; [(e.next rescue "#{$!.class}"), e.next, e.next, (e.next rescue $!.result)] } +probe("flm_raise_to_ary") { o = Object.new; def o.to_ary = raise(IOError, "x"); e = [1].flat_map; e.next; e.feed o; [(e.next rescue "#{$!.class}: #{$!.message}"), e.next] } +probe("flm_to_ary_next") { e = [1, 2].flat_map; o = Object.new; o.define_singleton_method(:to_ary) { [e.peek] rescue [$!.class] }; e.next; e.feed o; [e.next, (e.next rescue $!.result)] } +probe("flm_mm_to_ary") { o = Class.new { def method_missing(n, *) = n == :to_ary ? [:mm] : super; def respond_to_missing?(n, p = false) = n == :to_ary || super }.new; fed_result([1].flat_map, [o]) } +probe("flm_peek") { e = [1, 2].flat_map; e.next; e.feed [:p]; [e.peek, e.peek, e.next, stop_of(e).result] } +probe("flm_loop") { e = [1, 2].flat_map; loop { x = e.next; e.feed [x, x] } } +probe("ewo_array") { m = []; e = [1, 2].each_with_object(m); [e.next, e.next_values, stop_of(e).result.equal?(m)] } +probe("ewo_hash") { e = { a: 1 }.each_with_object(:m); [e.next, e.peek_values.size].tap { }.push(stop_of({ a: 1 }.each_with_object(:m)).result) } +probe("ewo_range") { [drain((1..2).each_with_object(0)), stop_of((1..2).each_with_object(0)).result] } +probe("ewo_struct") { S4 = Struct.new(:w) unless defined?(S4); [drain(S4.new(5).each_with_object(nil))] } +probe("ewo_feed") { e = [1, 2].each_with_object([]); e.next; e.feed :ignored; e.next; stop_of(e).result } +probe("ewo_append") { a = [1]; e = a.each_with_object(:m); x = e.next; a << 2; [x, e.next, (e.next rescue :stop)] } +probe("ewo_memo_mutate") { e = [1, 2].each_with_object([]); e.next[1] << :x; [e.next, stop_of(e).result] } +probe("ewo_singleton") { a = [1]; def a.each_with_object(m); yield :own, m; :r; end; e = a.each_with_object(0); [e.next, stop_of(e).result] } +probe("ewo_size") { [[1, 2].each_with_object(0).size, { a: 1 }.each_with_object(0).size, (1..3).each_with_object(0).size] } +probe("ewo_thread") { e = [1, 2].each_with_object(0); e.next; Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value } +probe("ewo_inspect") { e = [1].each_with_object(:m); e.next; e.inspect } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index ed82e5a3e..122e001fc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1563,12 +1563,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and perf/extiter (Landed) defers that walk; perf/extiter2 (Landed) gives `map`, `collect`, `select`, `filter`, `find_all` and `reject` cursors of their own, and perf/extiter3 (Landed) `with_index`, `each_with_index` and `with_object` on an enumerator, and Enumerable# - each_with_index over a Hash, a Range or a Struct. Still on a fiber, 5-16 us of process CPU - per `next` against 0.25-0.37: `each_with_object` and `with_object` over a source with no - cursor, `filter_map` and `flat_map` (the prelude's), Hash#select and #reject (Hash's own, whose - result is a Hash), `Enumerator::Lazy`, `Enumerator.produce` (generators of the prelude, which - run Ruby code between two values: a cursor would call blocks under its lock) and - `Enumerator.new`. A raw fiber round trip is 2.3 us of wall clock and 4.7-6 us of CPU (two + each_with_index over a Hash, a Range or a Struct, and perf/extiter5 (Landed) Hash#select, + #filter and #reject, `filter_map`, `flat_map` / `collect_concat` and `each_with_object`. + Still on a fiber, 5-16 us of process CPU per `next` against 0.25-0.40: any of these over a + source with no cursor (an IO, a custom #each, a generator), `Enumerator::Lazy`, + `Enumerator.produce` (generators of the prelude, which run Ruby code between two values: a + cursor would call blocks under its lock) and `Enumerator.new`. A raw fiber round trip is 2.3 us of wall clock and 4.7-6 us of CPU (two threads spinning), so the prelude's machinery around it is not where the time is. **An abandoned fiber-backed enumerator** costs 1.1-1.6 ms of process CPU to make and take one value from (starting its thread), and its thread and about 60 KB stay until the handle's @@ -1633,6 +1633,46 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/extiter5 (2026-11-27) - Hash#select / #filter / #reject, `filter_map`, `flat_map` and + `each_with_object` take `next` on a cursor (gap 35)** - not gated. Base 1fca3c7 (the round-38 + branch at b887bc1 with perf/extiter4). Hash's own #select, #filter and #reject copy the + receiver when the iteration starts, as IDictionaryOps.Filter and MRI's rb_hash_select do (a + plain Hash with its compare_by_identity, the entries with their hash codes), walk the copy with + key and value as the two values of a step, and drop a pair the fed answer does not keep: the + copy is StopIteration#result. The prelude's Enumerable#filter_map (the true answers), + #flat_map / #collect_concat (an answer's elements when it is an Array or Array.try_convert + makes one, MRI's rb_check_array_type; the answer itself otherwise), and #each_with_object (the + memo beside each step, `IndexCursor`), and Array's own #each_with_object, over any receiver + whose #each a cursor walks, while they are the methods registered with `__iter_cursor_method__`. + #flat_map's conversion runs Ruby code, so a cursor whose answer does (`ResumesWithRubyCode`) + resumes before the cursor's lock is taken, on the owning thread, where MRI's flat_map_i + converts; an error ends that iteration and the next #next starts again (next_init), and a + conversion that calls back into the same enumerator raises FiberError "attempt to resume the + current fiber", as MRI's does (the fiber path answers instead: the base differs from CRuby in + that one probe). `next`, `peek`, `next_values` and `peek_values` take a second call-site + storage for the conversion: a storage holds one site. A trap on the way: the handler around + that Resume, written in CursorStep, made every StopIteration a cursor throws 15% slower + (`ary_small` 1251 -> 1435, `rescue_end` 3853 -> 4483 ns, eight rounds) - a handler in the + method an exception is thrown from cost about 600 ns a throw - and in a NoInlining method of + its own it is level (1.01, 0.99, 1.02). `IR_FAST_NEXT=0` leaves them to the fiber. `ab.rb -r + 6`, ns per `next`, CRuby / base / off / new: a Hash's `select` with `feed` 314 / 14113 / 14310 + / 257, `reject` 279 / 10871 / 9841 / 194, `[1000].filter_map` 240 / 7743 / 5305 / 105, + `flat_map` 312 / 8820 / 5663 / 132, `each_with_object` 255 / 5419 / 5746 / 155, a Hash's 340 + / 10319 / 9376 / 228; the earlier rounds' shapes level with base (`lazy_next` 0.96 of off; + `generator` read 2.23 of off after shapes that use a fiber only when switched off, and 0.93 of + base alone). Abandoned after one `next` (`extiter-abandoned.rb`, 10,000 each): 1.04-1.31 ms + and a thread each (reclaimed after GC: these were detached Enumerators already), 330-340 MB -> + 8-20 us, no thread, 139-147 MB. `Util/extiter-matrix.rb` (312 probes, 50 new: results with and + without feed, the result Hash's class, default and compare_by_identity, a frozen receiver, the + receiver changed during the iteration, peek, next_values, rewind, loop, with_index, to_ary, a + #to_ary that answers nil, raises, returns an Integer or calls back in, method_missing, a + subclass's, a module's and a singleton's method, threads, size, inspect) prints CRuby's output + on new; base and off differ from it in the call-back probe only. enum-next-, block-loop-, + hash-order-, raise-, full-message-, enum- and enumerable2-matrix the same on base, new and off. + spec/core/enumerator, hash, enumerable and kernel/loop_spec: 1,541 examples, the same one error + in all three (Hash.try_convert's `into`/`to`); 117 named IronRuby.Tests pass (three verbose + runs). + - **perf/extiter4 (2026-11-26) - an abandoned lazy enumerator's fiber is reclaimed: its #next walks a copy (gap 35)** - not gated. Base 3bf570d (the round-37 branch at 79a2c30 with perf/extiter3). Measured first (`Util/bench/extiter-abandoned.rb`, new: 10,000 enumerators From 21d2a8b9f25f97ce65b84f664db5678cee451a5e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:05:58 +0000 Subject: [PATCH 094/439] A respond_to? that claims a conversion the object lacks is no conversion, not a NoMethodError An object whose overridden respond_to? says yes to :to_ary but that has no #to_ary (Util/array2-matrix.rb's NoAry) made Array.try_convert, Array(), Array#+, #concat, #product, #zip and the rest raise "undefined method 'to_ary'"; String.try_convert and Hash.try_convert the same with to_str and to_hash. CRuby's rb_check_funcall asks respond_to? and then, finding no method and BasicObject's method_missing (check_funcall_missing), takes it as no conversion: try_convert is nil, Array() wraps, + raises "no implicit conversion of NoAry into Array". The binder's conversion rule (ProtocolConversionAction, the path for an overridden respond_to?) now knows at build time - its type test covers to_xxx and method_missing - whether the class has the method or a method_missing of its own, and takes the no-conversion branch when it has neither. The prelude's try_convert asks the same through Kernel#__ir_conversion_callable__. Checked: Protocol_RespondToWithoutMethod1 (new; CRuby 4.0's output, with a method_missing that does answer to_ary too); array2-matrix 88 -> 69 lines (the 19 NoAry rows), respond-to-matrix same; try_convert of Array, String, Hash and Regexp, Kernel#Array and #String, Array flatten/plus/concat/zip, String#+, respond_to?, language/send, IO#write: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/Runtime/ProtocolTests.cs | 32 +++++++++++++++++++ Src/Libraries/Builtins/KernelOps.cs | 17 ++++++++++ .../Conversions/ProtocolConversionAction.cs | 19 ++++++++--- Src/StdLib/ironruby/ruby4.rb | 2 +- 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/ProtocolTests.cs b/Src/IronRuby.Tests/Runtime/ProtocolTests.cs index 2ec8d0fc5..35a27ecbb 100644 --- a/Src/IronRuby.Tests/Runtime/ProtocolTests.cs +++ b/Src/IronRuby.Tests/Runtime/ProtocolTests.cs @@ -735,5 +735,37 @@ class BadIO; def to_io; 1; end; end => -0.0 ", OutputFlags.Match); } + + /// + /// A respond_to? that claims a conversion method the object does not have, with the default method_missing: no conversion + /// (try_convert is nil, Array() wraps, + raises the conversion's TypeError), as MRI's rb_check_funcall has it, not a + /// NoMethodError; a method_missing that answers the conversion still does. Util/array2-matrix.rb's NoAry. + /// + public void Protocol_RespondToWithoutMethod1() { + TestOutput(@" +class NoAry + def respond_to?(name, priv = false) = name == :to_ary || name == :to_str || name == :to_hash + def inspect = ""NoAry"" +end +class MMAry + def respond_to?(name, priv = false) = name == :to_ary + def method_missing(n, *) = n == :to_ary ? [7] : super +end +o = NoAry.new +[-> { Array.try_convert(o) }, -> { Array(o) }, -> { [1].concat(o) }, -> { [1] + o }, -> { [[1, 2], o].flatten }, + -> { String.try_convert(o) }, -> { ""a"" + o }, -> { Hash.try_convert(o) }, -> { [1] + MMAry.new }, -> { Array(MMAry.new) }].each { |l| p((l.call rescue $!)) } +", @" +nil +[NoAry] +# +# +[1, 2, NoAry] +nil +# +nil +[1, 7] +[7] +"); + } } } diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index 97e201e2f..3297ace99 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1754,6 +1754,23 @@ private static RubyMethodVisibility GetDefinedVisibility(RubyClass/*!*/ cls, str return method.Info.IsNotImplemented ? RubyMethodVisibility.None : method.Visibility; } + /// + /// After respond_to? said yes to a conversion: whether calling the method could answer - the object's class has it, or a + /// method_missing other than BasicObject's. MRI's rb_check_funcall (check_funcall_missing) takes "no" for no conversion + /// rather than raising NoMethodError, as the conversions of the binder do (ProtocolConversionAction). + /// + [RubyMethod("__ir_conversion_callable__", RubyMethodAttributes.PrivateInstance)] + public static bool IsConversionCallable(ConversionStorage/*!*/ stringCast, object self, object obj, object methodName) { + var context = stringCast.Context; + string name = Protocols.CastToSymbol(stringCast, methodName); + RubyClass cls = context.GetImmediateClassOf(obj); + if (GetDefinedVisibility(cls, name) != RubyMethodVisibility.None) { + return true; + } + var methodMissing = cls.GetMethodLookup(Symbols.MethodMissing); + return methodMissing.Found && !(methodMissing.Info.DeclaringModule == context.BasicObjectClass && methodMissing.Info is RubyLibraryMethodInfo); + } + [RubyMethod("__ir_clone_with_freeze__", RubyMethodAttributes.PrivateInstance)] public static object/*!*/ CloneWithFreeze( CallSiteStorage>/*!*/ initializeCopyStorage, diff --git a/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs b/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs index ed05c347a..49b3cd1ab 100644 --- a/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs +++ b/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs @@ -346,6 +346,18 @@ internal static void BuildConversion(MetaObjectBuilder/*!*/ metaBuilder, CallArg args.TargetExpression ); + // MRI's rb_check_funcall: when respond_to? says yes but the class has no to_xxx and its method_missing is the + // default one, there is no conversion (check_funcall_missing), not a NoMethodError. Whether it has either is + // known here: the rule's type test covers to_xxx and method_missing. + bool callable; + using (targetClass.Context.ClassHierarchyLocker()) { + callable = targetClass.ResolveMethodForSiteNoLock(toMethodName, VisibilityContext.AllVisible).Found || + IsOverridden(targetClass.ResolveMethodForSiteNoLock(Symbols.MethodMissing, VisibilityContext.AllVisible).Info, + targetClass.Context.BasicObjectClass); + } + var noConversion = (i < conversions.Length - 1) ? metaBuilder.Result : + conversions[i].MakeErrorExpression(args, targetClassNameConstant, resultType); + metaBuilder.Result = Ast.Condition( // If @@ -367,15 +379,14 @@ internal static void BuildConversion(MetaObjectBuilder/*!*/ metaBuilder, CallArg // Then // to_xxx(): - ConvertResult( + callable ? ConvertResult( conversions[i].MakeValidatorCall(args, targetClassNameConstant, conversionCallSite), resultType - ), + ) : noConversion, // Else - (i < conversions.Length - 1) ? metaBuilder.Result : - conversions[i].MakeErrorExpression(args, targetClassNameConstant, resultType) + noConversion ); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 674289d36..784671707 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9,7 +9,7 @@ module Kernel # asks of an implementation other than CRuby's - "into", where CRuby still says "to". private def __ir_try_convert__(obj, method, klass, name) return obj if klass === obj - return nil unless __ir_responds_to__(obj, method) + return nil unless __ir_responds_to__(obj, method) && __ir_conversion_callable__(obj, method) converted = obj.__send__(method) return nil if converted.nil? return converted if klass === converted From 378fdc09a99e0bb9b69e13499b8e04c21b0d8a2a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:11:21 +0000 Subject: [PATCH 095/439] Matrix and test for the keyword prologue's errors and defaults; prologue shapes Util/kw-prologue-matrix.rb probes what decides which ArgumentError a keyword call gets when several things are wrong at once (a missing positional and an unknown keyword, missing and unknown keywords, a positional Hash), the defaults (side effects, order, reading earlier parameters, raising), and ruby2_keywords, send, method_missing, super, define_method, Method#call and a module function. It prints CRuby 4.0's output on this build in every mode. Method_KeywordPrologue1 is its core as a test. The p_* and d_* shapes in prelude-cost.rb split the prologue's cost (gap 38); perf/kwprologue, which used them, was rejected (see the ledger). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 42 ++++++++++ Util/bench/prelude-cost.rb | 23 ++++++ Util/kw-prologue-matrix.rb | 104 ++++++++++++++++++++++++ 4 files changed, 170 insertions(+) create mode 100644 Util/kw-prologue-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 3ff00990a..c55ef7b08 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1141,6 +1141,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameRest1, Method_LightFrameKeywordRest1, Method_KeywordHashIntoRest1, + Method_KeywordPrologue1, Method_LightFrameGlobal1, Method_LightFrameLexical1, Method_ParkedScope1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 9c6f68d58..1f7bb1c44 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7858,6 +7858,48 @@ p r2k(1, k: 2), r2k(1, {k: 2}), Hash.ruby2_keywords_hash?(r2k_last(k: 1)), Hash. "); } + /// + /// A method's keyword prologue (PrismAstBridge.LowerKeywords): which error wins when several things are wrong at once, + /// and defaults run in order and only for omitted keywords (Util/kw-prologue-matrix.rb). + /// + public void Method_KeywordPrologue1() { + TestOutput(@" +def err = yield rescue ""#{$!.class}: #{$!.message}"" +def opt(a, k: 1) = [a, k] +def req(a, k:) = [a, k] +def two(a, b, j: 1, k:) = [a, b, j, k] +def none(k: 1) = k +def rest(a, k: 1, **o) = [a, k, o] +$log = [] +def order(a, x: ($log << :x; 1), y: ($log << :y; 2)) = [a, x, y] +p opt(1), opt(1, k: 2), req(1, k: 2), two(1, 2, k: 3), none, rest(1, z: 2), order(1, y: 0), $log +p err { opt(k: 2) }, err { opt(1, z: 2, y: 3) }, err { req(1, z: 2) }, err { req }, err { req({k: 1}) } +p err { two(1, k: 2) }, err { none({k: 1}) }, err { none(""k"" => 1) }, err { rest(k: 1) }, err { order(1, z: 1) }, $log +p 40.times.map { |i| [opt(i % 2, k: i % 3), req(1, k: i % 2)] }.uniq.size +", @" +[1, 1] +[1, 2] +[1, 2] +[1, 2, 1, 3] +1 +[1, 1, {z: 2}] +[1, 1, 0] +[:x] +""ArgumentError: wrong number of arguments (given 0, expected 1)"" +""ArgumentError: unknown keywords: :z, :y"" +""ArgumentError: missing keyword: :k"" +""ArgumentError: wrong number of arguments (given 0, expected 1; required keyword: k)"" +""ArgumentError: missing keyword: :k"" +""ArgumentError: wrong number of arguments (given 1, expected 2; required keyword: k)"" +""ArgumentError: wrong number of arguments (given 1, expected 0)"" +""ArgumentError: unknown keyword: \""k\"""" +""ArgumentError: wrong number of arguments (given 0, expected 1)"" +""ArgumentError: unknown keyword: :z"" +[:x] +6 +"); + } + /// /// A method that reads or writes a global is a light frame too (MethodDefinition.IsLightGlobal): every global but $~ and /// $_ is the runtime's, and the frame reads and writes it through the declaring scope. A name that comes to denote $~ or $_ diff --git a/Util/bench/prelude-cost.rb b/Util/bench/prelude-cost.rb index f3770c198..da83cd4e2 100644 --- a/Util/bench/prelude-cost.rb +++ b/Util/bench/prelude-cost.rb @@ -330,6 +330,18 @@ def v_hash_into_rest(*a) = a.size + 1 def v_unused(*a, k: 1) = 3 def v_kwrest(*a, **o) = a.size + o.size def v_two(a, b) = a + # gap 38, the keyword prologue: the same method with a keyword, left out, required, **o, and two keywords + def p_opt(a, k: 1) = a + def p_req(a, k:) = a + def p_rest(a, **o) = a + def p_two(a, j: 1, k: 1) = a + def p_opt_only(k: 1) = k + def p_plain_opt(a, b = 1) = a + # an untaken raise in the body: does its presence cost? + def d_none(a) = a + def d_one(a); raise ArgumentError, "x" unless a; a; end + def d_two(a); raise ArgumentError, "x" unless a; raise ArgumentError, "y" unless a; a; end + def d_cond(a); b = a ? a : 0; b; end end def cpu @@ -508,3 +520,14 @@ def t(name, n) t("v_two_kw", N) { |n| i = 0; s = 0; while i < n; s += kr.v_two(i, k: 2); i += 1; end; s } t("v_two_lit", N) { |n| i = 0; s = 0; while i < n; s += kr.v_two(i, {k: 2}); i += 1; end; s } t("v_two_pos", N) { |n| i = 0; s = 0; while i < n; s += kr.v_two(i, 2); i += 1; end; s } +t("p_opt", N) { |n| i = 0; s = 0; while i < n; s += kr.p_opt(i, k: 2); i += 1; end; s } +t("p_opt_omitted", N) { |n| i = 0; s = 0; while i < n; s += kr.p_opt(i); i += 1; end; s } +t("p_req", N) { |n| i = 0; s = 0; while i < n; s += kr.p_req(i, k: 2); i += 1; end; s } +t("p_rest", N) { |n| i = 0; s = 0; while i < n; s += kr.p_rest(i, k: 2); i += 1; end; s } +t("p_two", N) { |n| i = 0; s = 0; while i < n; s += kr.p_two(i, k: 2); i += 1; end; s } +t("p_opt_only", N) { |n| i = 0; s = 0; while i < n; s += kr.p_opt_only(k: i); i += 1; end; s } +t("p_plain_opt", N) { |n| i = 0; s = 0; while i < n; s += kr.p_plain_opt(i); i += 1; end; s } +t("d_none", N) { |n| i = 0; s = 0; while i < n; s += kr.d_none(i); i += 1; end; s } +t("d_one", N) { |n| i = 0; s = 0; while i < n; s += kr.d_one(i); i += 1; end; s } +t("d_two", N) { |n| i = 0; s = 0; while i < n; s += kr.d_two(i); i += 1; end; s } +t("d_cond", N) { |n| i = 0; s = 0; while i < n; s += kr.d_cond(i); i += 1; end; s } diff --git a/Util/kw-prologue-matrix.rb b/Util/kw-prologue-matrix.rb new file mode 100644 index 000000000..9bb10fc3b --- /dev/null +++ b/Util/kw-prologue-matrix.rb @@ -0,0 +1,104 @@ +# Differential matrix for a method's keyword prologue (PrismAstBridge.LowerKeywords): the separation +# checks (the last positional is not the keyword hash, the hidden keyword parameter is one), the +# missing/unknown checks guarded by KeywordArgumentsMatch, and the reads with their defaults. Written for +# perf/kwprologue (gap 38 of Util/perf/LEDGER.md), which folded the checks into one runtime call and was +# rejected; any change to the prologue's checks or their order is what it is for. Run it under CRuby and +# under ./ir.sh in every mode, and diff: +# +# ruby Util/kw-prologue-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/kw-prologue-matrix.rb > /tmp/ir.txt 2>&1 +# ./ir.sh -X:NoJIT -X:NoOSR Util/kw-prologue-matrix.rb > /tmp/nojit.txt 2>&1 +# diff /tmp/mri.txt /tmp/ir.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# The probes are what decides which error a call gets when several things are wrong at once (a missing +# positional and an unknown keyword, missing and unknown keywords, a positional Hash), the defaults (side +# effects, their order, one reading an earlier parameter or keyword, one that raises), ruby2_keywords, and +# the other ways in: send, method_missing, super, define_method, Method#call, a module function. + +N = 3000 + +def t(label) + print label.ljust(52), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def err + yield +rescue Exception => e + "#{e.class}: #{e.message[0, 90]}" +end + +def opt(a, k: 1) = [a, k] +def req(a, k:) = [a, k] +def two(a, b, j: 1, k:) = [a, b, j, k] +def none(k: 1, j: 2) = [k, j] +def with_rest(a, k: 1, **o) = [a, k, o] +def opt_pos(a, b = 2, k: 1) = [a, b, k] + +# ---------------------------------------------------------------- 1. which error wins + +t('opt: no positional, a keyword') { err { opt(k: 2) } } +t('opt: no positional, an unknown keyword') { err { opt(z: 2) } } +t('opt: too many positionals and an unknown') { err { opt(1, 2, z: 3) } } +t('opt: unknown keywords') { err { opt(1, z: 2, y: 3) } } +t('req: missing') { err { req(1) } } +t('req: missing and unknown') { err { req(1, z: 2) } } +t('req: no positional, missing') { err { req } } +t('req: positional Hash') { err { req({k: 1}) } } +t('req: positional Hash and keywords') { err { req({k: 1}, k: 2) } } +t('two: one positional, keywords') { err { two(1, k: 2) } } +t('two: missing k, unknown z') { err { two(1, 2, z: 3) } } +t('two: all there') { two(1, 2, k: 3) } +t('none: a positional Hash') { err { none({k: 1}) } } +t('none: unknown') { err { none(x: 1) } } +t('none: string key') { err { none("k" => 1) } } +t('with_rest: anything') { with_rest(1, z: 2, k: 3) } +t('with_rest: no positional') { err { with_rest(k: 2) } } +t('opt_pos: Hash as the optional') { opt_pos(1, {k: 5}) } +t('opt_pos: Hash and keywords') { opt_pos(1, {k: 5}, k: 6) } +t('opt_pos: too many') { err { opt_pos(1, 2, 3, k: 4) } } +t('**{} and **nil') { [opt(1, **{}), opt(1, **nil), none(**{})] } +t('given, omitted, mixed') { |i| [opt(i % 2), opt(i % 2, k: i % 3), req(1, k: i % 2)] } + +# ---------------------------------------------------------------- 2. defaults + +$log = [] +def logged(v) = ($log << v; v) +def order(a, x: logged(:x), y: logged(:y)) = [a, x, y] +def reads(a, b: a + 1, c: b * 2) = [a, b, c] +def raises_default(a, k: raise("default ran")) = [a, k] +t('defaults run in order, only omitted') { |i| $log.clear; r = (i.even? ? order(1) : order(1, x: 0)); [r, $log.dup] } +t('defaults read earlier parameters') { |i| i.even? ? reads(1) : reads(1, b: 10) } +t('a default that raises') { |i| err { i.even? ? raises_default(1) : raises_default(1, k: 2) } } +t('a default not run on an error') { $log.clear; [err { order(1, z: 1) }, $log.dup] } + +# ---------------------------------------------------------------- 3. ruby2_keywords and other ways in + +ruby2_keywords def fwd(*args) = req(*args) +class MM; def method_missing(n, a, k: 0) = [n, a, k]; def respond_to_missing?(*) = true; end +class KB; def m(a, k: 1) = [:base, a, k]; def m2(a, k: 1) = [:base2, a, k]; end +class KS < KB + def m(a, k: 1) = [:sub, super] + def m2(a, k: 1) = [:sub2, super(a, k: k + 1)] +end +class KD; define_method(:dm) { |a, k: 1| [a, k] }; end +module KF; module_function def f(a, k: 1) = [a, k]; end +t('ruby2_keywords forwards keywords') { fwd(1, k: 2) } +t('ruby2_keywords, missing') { err { fwd(1) } } +t('send') { [send(:req, 1, k: 2), err { send(:req, 1) }] } +t('method_missing with keywords') { MM.new.zz(1, k: 3) } +t('zsuper') { KS.new.m(1, k: 2) } +t('explicit super') { KS.new.m2(1) } +t('define_method') { [KD.new.dm(1), KD.new.dm(1, k: 2), err { KD.new.dm(1, z: 2) }] } +t('Method#call') { [method(:opt).call(1, k: 3), err { method(:req).call(1) }] } +t('module function') { [KF.f(1), KF.f(1, k: 2)] } +t('arity and parameters') { [method(:two).arity, method(:two).parameters] } From a8feb8385510bd1df4d40e26696a321ea69fd0fc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:11:22 +0000 Subject: [PATCH 096/439] Ledger: perf/kwprologue rejected; gap 38's second cost broken down Folding the keyword prologue's checks into one runtime call saved 62 instructions of about 850 (JIT off; nothing with it on). The entry has the part-by-part breakdown, what it rules out (statement count, untaken branches, light frames, a reflection call fallback) and what is left: why one interpreted runtime call with four or five arguments costs 350 or more. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e48d99fd5..0150ccf53 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1503,6 +1503,14 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has did not move: theirs is the prologue's cost below. Separately, the keyword prologue of `def kw(a, k: 1) = a + k` costs about 1,300-1,500 with the JIT off (4,017 against `v_two_kw` 2,435) in either lowering. Not the splat lowering: see Rejected, perf/lexical3. + The prologue's parts (perf/kwprologue, Rejected, JIT off): the separation checks 242, the + `unless KeywordArgumentsMatch` statement 380-640, each read 160-210 - 850 for + `def p_opt(a, k: 1) = a` called with the keyword left out, against 1,904 for the same + method with a plain optional. Folding the checks into one call saved 62. The method JIT + takes such methods and pays none of it (1,507); what pays is a keyword method it declines + (`**o`, `p_rest` 3,906). Unexplained: why one runtime call with four or five arguments + costs 350 or more in the interpreted body. A profiler that names the DLR interpreter's + frames (perf with jitdump, where perf_event_open is allowed) is the next tool. ## Landed @@ -4867,6 +4875,34 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/kwprologue (/perf-step, 2026-11-26, on 78aab00) - a keyword method's prologue checks + the call in one runtime call** (gap 38's second cost; switch `IR_KW_PROLOGUE`, reverted). + Measured first by switching the prologue's parts off one at a time in a throwaway build + (`Util/perf/callgrind/count.sh`, `-X:NoJIT`, instructions a call): in `def p_opt(a, k: 1) = + a` the separation checks cost 242, the statement guarded by `KeywordArgumentsMatch` 380 (467 + with the keyword given, 640 for a required one), the read 160-210 a keyword - 850 in all + against a plain optional (`p_plain_opt` 1,904, `p_opt_omitted` 2,765). The helpers are a few + instructions each (`HasKeywords` returns at once on the empty hash); an untaken `raise ... + unless a` costs 108 and the next 76, so a statement costs what its test does to execute, not + by being there; light frames do not change it (885 without them against 860). Tried: one + `[Emitted]` helper, `KeywordPrologueMatch(last, kw, names, required, rest)`, as the condition + of the `unless` that guards the prologue, with the separation checks moved into its body ahead + of the missing/unknown ones - the same errors in the same order, and the shape `JitKeywords` + recognizes (the JIT still specialized `kw`, `p_opt`, `p_req`, `p_two`; census 0 moved). + Result: `p_opt_omitted` 2,764 -> 2,702, `p_opt` 3,680 -> 3,618 (-62, 2%) with the JIT off, + nothing with it on; the controls 1.000. Rejected: 62 instructions do not pay for a new emitted + helper and a second prologue shape. Learned: the cost is not the number of statements but each + runtime call in the interpreted body (one call with five arguments cost about 560, where the + three it replaced cost 622), and the DLR's call instructions are the generic ones up to ten + arguments, so it is not a reflection fallback either - unexplained, see gap 38. Kept: + `Util/kw-prologue-matrix.rb` (which error wins when several things are wrong, default order + and side effects, ruby2_keywords, send, method_missing, super, define_method, Method#call, a + module function; CRuby's output on the unchanged build in every mode, and on the candidate + with the switch on and off), `Method_KeywordPrologue1`, and the shapes in `prelude-cost.rb` + (`p_*`, `d_*`). The parent's other idea - a call site that binds literal keywords without the + hash, guarded on the callee's signature - is untried; it would save the hash (about 670 at the + site) and the reads for a callee the JIT declines. + - **perf/lexical3 (/perf-step, 2026-11-26, on 3cabf57) - bind the positionals of `def m(a, *r, k: 1)` in the calling convention instead of out of one splat** (the idea perf/lexical2's entry named), rejected by measurement before any code. The premise was `kr_rest` 5,325 From af56f45dcf5a45d6856bbdc8bd5e71a61a149120 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:15:16 +0000 Subject: [PATCH 097/439] Timeout: wake the watcher thread only when it has to be A raise rescued through Timeout.timeout cost 152-164 us against CRuby's 3.1. Each call's @condvar.signal woke the watcher thread, whose iteration then ran beside the raise and cost it as well: 145 us of process CPU, 100 on the calling thread, against 57 and 57 with the signal left out. Src/StdLib/ironruby/timeout.rb loads CRuby's timeout.rb as it is and redefines two methods of Timeout::State. The watcher publishes the deadline it waits for, and a new request signals it only when its deadline is earlier, when the watcher is not in that wait, or when 64 requests are queued. A request not signalled for is due no earlier than what the watcher wakes for, so every timeout fires when CRuby's would. Raise through Timeout: 0.62 of the calling thread's CPU (six rounds), 164 and 135 -> 76 and 69 us of process CPU; no raise unchanged. Util/timeout-matrix.rb (new, 28 rows) prints CRuby's output on both builds in every mode; ruby/spec library/timeout, core/thread/raise and core/kernel/sleep pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/StdLib/ironruby/timeout.rb | 80 ++++++++++++++++++++++++++++++++++ Util/bench/timeout-shapes.rb | 32 ++++++++++++++ Util/perf/LEDGER.md | 41 +++++++++++++++++ Util/timeout-matrix.rb | 67 ++++++++++++++++++++++++++++ 4 files changed, 220 insertions(+) create mode 100644 Src/StdLib/ironruby/timeout.rb create mode 100644 Util/bench/timeout-shapes.rb create mode 100644 Util/timeout-matrix.rb diff --git a/Src/StdLib/ironruby/timeout.rb b/Src/StdLib/ironruby/timeout.rb new file mode 100644 index 000000000..f64c20ca9 --- /dev/null +++ b/Src/StdLib/ironruby/timeout.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true +# +# CRuby's timeout (Src/StdLib/ruby/4.0/timeout.rb), loaded as it is, with one IronRuby adjustment. +# +# Every Timeout.timeout queues a request for the watcher thread and signals its condition variable, +# so the watcher wakes once per call: it drains the queue, finds the closest deadline again and goes +# back to waiting. In CRuby that costs about a microsecond. Here the watcher's wake-up runs beside the +# calling thread and costs it too: a Timeout.timeout whose block raises took 145 us of CPU against +# 57 us with the signal left out, one that returns 28 against 4 (Util/bench/timeout-shapes.rb). +# +# The signal is needed only when the watcher would otherwise sleep past the new request's deadline. +# The watcher publishes the deadline it is waiting for (@watcher_deadline, under @queue_mutex, set +# while it is in the condition variable's wait), and a new request signals it only if its own deadline +# is earlier, if the watcher is not waiting there (blocked in @queue.pop, which the push wakes, or +# between two waits, where it looks at the queue under the mutex before waiting again), or if the +# queue has grown to QUEUE_SIGNAL_LENGTH requests, so that a long-lived wait does not let finished +# requests pile up. A request not signalled for has a deadline no earlier than the one the watcher +# wakes for, and the watcher drains the queue then, before any of them can be due: every timeout +# still fires when CRuby's would. +require "rbconfig" +load File.join(RbConfig::CONFIG["rubylibdir"], "timeout.rb") + +module Timeout + class State + QUEUE_SIGNAL_LENGTH = 64 + private_constant :QUEUE_SIGNAL_LENGTH + + def create_timeout_thread + # Threads unexpectedly inherit the interrupt mask: https://github.com/ruby/timeout/issues/41 + # So reset the interrupt mask to the default one for the timeout thread + Thread.handle_interrupt(Object => :immediate) do + watcher = Thread.new do + requests = [] + while true + until @queue.empty? and !requests.empty? # wait to have at least one request + req = @queue.pop + requests << req unless req.done? + end + closest_deadline = requests.min_by(&:deadline).deadline + + now = 0.0 + @queue_mutex.synchronize do + begin + @watcher_deadline = closest_deadline + while (now = GET_TIME.call(Process::CLOCK_MONOTONIC)) < closest_deadline and @queue.empty? + @condvar.wait(@queue_mutex, closest_deadline - now) + end + ensure + @watcher_deadline = nil + end + end + + requests.each do |req| + req.interrupt if req.expired?(now) + end + requests.reject!(&:done?) + end + end + + if !watcher.group.enclosed? && (!defined?(Ractor.main?) || Ractor.main?) + ThreadGroup::Default.add(watcher) + end + + watcher.name = "Timeout stdlib thread" + watcher.thread_variable_set(:"\0__detached_thread__", true) + watcher + end + end + + def add_request(request) + Sync.synchronize @queue_mutex do + @queue << request + waiting_for = @watcher_deadline + if waiting_for.nil? || request.deadline < waiting_for || @queue.size >= QUEUE_SIGNAL_LENGTH + @condvar.signal + end + end + end + end +end diff --git a/Util/bench/timeout-shapes.rb b/Util/bench/timeout-shapes.rb new file mode 100644 index 000000000..a31277ded --- /dev/null +++ b/Util/bench/timeout-shapes.rb @@ -0,0 +1,32 @@ +# What Timeout.timeout costs, with and without a raise in its block (Src/StdLib/ironruby/timeout.rb: the watcher thread +# is woken for a new request only when it has to be). us per call; cpu is this thread's time, so the watcher thread's own +# work is not in it, nor in the instruction counts. +# +# ruby Util/perf/ab.rb -r 6 Util/bench/timeout-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# ruby Util/perf/ab.rb -i -r 1 -n 2000 Util/bench/timeout-shapes.rb \ +# "base=env IR_CONFIG=Release Util/perf/callgrind/count.sh ../ironruby" "new=env IR_CONFIG=Release Util/perf/callgrind/count.sh ." +# +# Every line prints the sum of its results next to its time; it must be CRuby's. +$stdout.sync = true +require 'timeout' + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +N = (ENV["N"] || 20_000).to_i +t("raise", N) { |n| i = 0; r = 0; while i < n; begin; Timeout.timeout(5) { raise "x" }; rescue RuntimeError; r += 1; end; i += 1; end; r } +t("no_raise", N) { |n| i = 0; r = 0; while i < n; r += Timeout.timeout(5) { 1 }; i += 1; end; r } +t("bare", N) { |n| i = 0; r = 0; while i < n; begin; raise "x"; rescue RuntimeError; r += 1; end; i += 1; end; r } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 18eb336d4..7480bfad9 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1624,6 +1624,47 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/timeout (2026-11-27) - `Timeout.timeout` wakes its watcher thread only when it has to** + (`Src/StdLib/ironruby/timeout.rb`, an override that loads CRuby's file as it is and redefines two + methods of `Timeout::State`) - timed, not gated. A raise rescued through `Timeout.timeout` cost + 152-164 us against CRuby's 3.1 (perf/ensure's finding). Taken apart with copies of timeout.rb + (each with one thing left out; no profiler: this container refuses perf_event_open and the + sampler could not be installed): without the `ensure request.finished` 21 us, without the + watcher's signal 57-60, without the handler's `rescue ExitException` 66, without the Proc's + `return` 62; and by thread (`Util/bench/timeout-shapes.rb`'s measure): with the signal 145 us of + process CPU of which 100 on the calling thread, without it 57 and 57. So each call's + `@condvar.signal` wakes the watcher, whose iteration (drain the queue, `min_by`, `reject!`, wait + again) then runs beside the raise: ~45 us of its own CPU and ~43 more on the caller. Pinned to one + CPU the difference shrinks (72 against 54): interference between the two threads, not the + watcher's work alone - not found further without a sampler (no contended Monitor entries: + `Monitor.LockContentionCount` 0 per call; no gen-0 collections). + The watcher needs a signal only when it would otherwise sleep past the new request's deadline. It + now publishes the deadline it waits for (`@watcher_deadline`, under `@queue_mutex`, while in the + condition variable's wait), and `add_request` signals when the new deadline is earlier, when the + watcher is not in that wait (in `@queue.pop`, which the push wakes, or between waits, where it + checks the queue under the mutex), or when the queue has 64 requests. A request not signalled for + is due no earlier than what the watcher wakes for, and it drains the queue then: every timeout + fires when CRuby's would. Without a raise the watcher usually finds the request finished, drops it + and blocks in `@queue.pop`, which every push wakes as before, so that path is unchanged. + Timing (`ab.rb`, six rounds, the calling thread's CPU, ns): raise 53,328 -> 32,954 (0.62); no raise + 2,765 -> 3,146 and the bare raise control 4,753 -> 4,750, both overlapping. Process CPU of a raise, + two runs (`Util/bench/timeout-shapes.rb`'s measure, us): 164 and 135 -> 76 and 69. Callgrind gives + nothing here: valgrind runs one thread at a time, so the interference cannot appear, and the + baseline's arm failed under it. + What is left of the raise (57 against a bare 8): `Error.handle_timeout`'s `rescue ExitException => + e` (a class list by constant: a catch, a backtrace, then `raise` again; a frame like it alone 29 us + against 8.6 for a core class) and the Proc's `return yield` inside begin/ensure. + Checked: `Util/timeout-matrix.rb` (new, 28 rows: firing in sleep, a busy loop, IO and Queue#pop, + nil/zero/negative, a custom class and message, the backtrace, ExitException not taken by a bare + rescue, a raise in the block with its cause and `$!`, nested both ways, a short timeout after 2,000 + long ones and inside a long one with 200 queued, two threads, one watcher thread after 10,000 + calls) prints CRuby's output on the unchanged build and on this one (with the JIT on, `-X:NoJIT + -X:NoOSR`, `-X:NoJITCalls`, `IR_LIGHT_FRAMES=0`); ruby/spec library/timeout (7), core/thread/raise + (77) and core/kernel/sleep (15) pass on both. + For the gate: Timeout's own code is CRuby's and is loaded as it is; a timeout gem installed over it + is not overridden (the override is found first on the load path only for `require "timeout"` of + the stdlib copy). + - **perf/jitaref (2026-11-26) - `a[i]` in a typed body after some Array has a singleton `[]`** - trace only, not gated (the census cannot see it: it loads no library). The side finding of perf/jitconst: app-shapes declined `OptionParser.top` (`@stack[-1]`) and `.base`, and rejected diff --git a/Util/timeout-matrix.rb b/Util/timeout-matrix.rb new file mode 100644 index 000000000..8c15411f7 --- /dev/null +++ b/Util/timeout-matrix.rb @@ -0,0 +1,67 @@ +# Differential matrix for Timeout (Src/StdLib/ruby/4.0/timeout.rb, with IronRuby's adjustment in +# Src/StdLib/ironruby/timeout.rb: the watcher thread is woken for a new request only when it has to be). +# Run under CRuby and under ./ir.sh, and diff: +# +# ruby Util/timeout-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/timeout-matrix.rb > /tmp/ir.txt +# diff /tmp/mri.txt /tmp/ir.txt +# +# Times are not printed, only whether a timeout fired within a bound and what it raised. The traps: a short timeout +# after many long ones (the watcher must be woken for an earlier deadline), a long timeout around a short one and the +# other way round, many requests queued while the watcher waits for a later deadline, firing while blocked in sleep, +# in IO and in a busy loop, a custom error class and message, the backtrace, Timeout::ExitException not caught by a +# bare rescue, and the watcher thread not multiplied by many calls. +require 'timeout' +$stdout.sync = true + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +def mono = Process.clock_gettime(Process::CLOCK_MONOTONIC) + +def fires_within(limit) + t0 = mono + begin + yield + :no_timeout + rescue Timeout::Error => e + el = mono - t0 + el < limit ? [e.class, e.message] : [:late, e.class] + end +end + +t("no timeout, value") { Timeout.timeout(1) { :v } } +t("nil and zero mean none") { [Timeout.timeout(nil) { 1 }, Timeout.timeout(0) { 2 }] } +t("negative") { Timeout.timeout(-1) { 1 } } +t("fires in sleep") { fires_within(2) { Timeout.timeout(0.1) { sleep 5 } } } +t("fires in a busy loop") { fires_within(2) { Timeout.timeout(0.1) { loop { 1 + 1 } } } } +t("fires in IO") { r, w = IO.pipe; fires_within(2) { Timeout.timeout(0.1) { r.read(1) } } } +t("fires in Queue#pop") { q = Queue.new; fires_within(2) { Timeout.timeout(0.1) { q.pop } } } +t("custom class") { begin; Timeout.timeout(0.05, ArgumentError) { sleep 5 }; rescue ArgumentError => e; [e.class, e.message]; end } +t("custom class and message") { begin; Timeout.timeout(0.05, ArgumentError, "late!") { sleep 5 }; rescue ArgumentError => e; [e.class, e.message]; end } +t("custom message") { begin; Timeout.timeout(0.05, nil, "slow") { sleep 5 }; rescue Timeout::Error => e; e.message; end } +t("backtrace has the block's line") { begin; Timeout.timeout(0.05) { sleep 5 }; rescue Timeout::Error => e; e.backtrace.any? { |l| l.include?("timeout-matrix.rb") }; end } +t("bare rescue does not take it") { fires_within(2) { Timeout.timeout(0.1) { begin; sleep 5; rescue => e; :rescued; end } } } +t("rescue Exception does") { Timeout.timeout(0.1) { begin; sleep 5; rescue Exception => e; e.class.name; end } } +t("raise in the block") { begin; Timeout.timeout(5) { raise "boom" }; rescue => e; [e.class, e.message]; end } +t("raise in the block, cause") { begin; Timeout.timeout(5) { raise "boom" }; rescue => e; e.cause; end } +t("$! after") { begin; Timeout.timeout(5) { raise "boom" }; rescue; end; $! } +t("nested, inner shorter fires") { fires_within(2) { Timeout.timeout(5) { Timeout.timeout(0.1) { sleep 5 } } } } +t("nested, outer shorter fires") { fires_within(2) { Timeout.timeout(0.1) { Timeout.timeout(5) { sleep 5 } } } } +t("nested, both long") { Timeout.timeout(5) { Timeout.timeout(6) { :ok } } } +t("short after 2000 long ones") { 2000.times { Timeout.timeout(30) { 1 } }; fires_within(2) { Timeout.timeout(0.1) { sleep 5 } } } +t("short after 2000 long raising") { 2000.times { begin; Timeout.timeout(30) { raise "x" }; rescue; end }; fires_within(2) { Timeout.timeout(0.1) { sleep 5 } } } +t("short inside a long, many queued") { Timeout.timeout(30) { 200.times { Timeout.timeout(20) { 1 } }; fires_within(2) { Timeout.timeout(0.1) { sleep 5 } } } } +t("long ones keep working after") { 500.times { Timeout.timeout(30) { 1 } }; Timeout.timeout(30) { :ok } } +t("another thread's timeout") { th = Thread.new { fires_within(2) { Timeout.timeout(0.1) { sleep 5 } } }; th.value } +t("two threads at once") { a = Thread.new { fires_within(2) { Timeout.timeout(0.2) { sleep 5 } } }; b = Thread.new { Timeout.timeout(5) { sleep 0.05; :b } }; [a.value, b.value] } +t("watcher threads after 10,000 calls") { 10_000.times { Timeout.timeout(30) { 1 } }; Thread.list.count { |th| th.name == "Timeout stdlib thread" } } +t("fires after 10,000 calls") { fires_within(2) { Timeout.timeout(0.1) { sleep 5 } } } +t("timeout method on an object") { o = Object.new; o.extend(Timeout); o.send(:timeout, 1) { :m } } From 8822aaddd06642f7e037e2cc423d26a61c657ee6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:16:03 +0000 Subject: [PATCH 098/439] StringScanner: keep the map's work out of the hot methods' bodies MatchRegex's and ByteSlice's mapped paths move to methods of their own (NoInlining), the map getter's early exit (switch off, not UTF-8, ASCII) is a small inlined check, and the switch is read into the scanner's own static. An ASCII scan word by word over 10 KB (ss_words_a) counts 14.08 M instructions a pass against the base's 13.62-13.73 M (+2.6 to 3.4%, callgrind) before and after this; with IR_FAST_SEARCH=0 it counted 13.97 M, so most of it is not the check itself. Recorded in the ledger. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/StringScanner/StringScanner.cs | 123 ++++++++++++------- 1 file changed, 76 insertions(+), 47 deletions(-) diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index b76a6126f..20580f1a7 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -16,6 +16,7 @@ using System; using System.Collections.Generic; using System.Numerics; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; @@ -256,6 +257,9 @@ private bool Seek(bool byBytes, int target, out int b, out int c) { private Utf8Map _map; private string _unmappedText; + // IR_FAST_SEARCH, read here so that the check every scan makes needs no other class + private static readonly bool MapEnabled = MutableStringOps.FastSearchEnabled; + // the map _match's CLR offsets are offsets into; null when the match was not made through one private Utf8Map _matchMap; @@ -265,27 +269,31 @@ private bool Seek(bool byBytes, int target, out int b, out int c) { /// already know), or not valid. IR_FAST_SEARCH=0 makes none. /// private Utf8Map Map { + [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - if (!MutableStringOps.FastSearchEnabled) { - return null; - } + // what every scan on an ASCII or non-UTF-8 subject asks: kept small enough to inline MutableString subject = _scanString; - if (subject.Encoding != RubyEncoding.UTF8 || subject.IsAscii()) { + if (!MapEnabled || subject.Encoding != RubyEncoding.UTF8 || subject.IsAscii()) { return null; } - // a string held as bytes is decoded once, as a match would - subject.PrepareForCharacterRead(); - string text = subject.ConvertToString(); - Utf8Map map = _map; - if (map != null && ReferenceEquals(map.Text, text)) { - return map; - } - if (ReferenceEquals(text, _unmappedText) || subject.ContainsInvalidCharacters()) { - _unmappedText = text; - return null; - } - return _map = new Utf8Map(text); + return MapFor(subject); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private Utf8Map MapFor(MutableString/*!*/ subject) { + // a string held as bytes is decoded once, as a match would + subject.PrepareForCharacterRead(); + string text = subject.ConvertToString(); + Utf8Map map = _map; + if (map != null && ReferenceEquals(map.Text, text)) { + return map; } + if (ReferenceEquals(text, _unmappedText) || subject.ContainsInvalidCharacters()) { + _unmappedText = text; + return null; + } + return _map = new Utf8Map(text); } private int ByteLength { @@ -301,15 +309,21 @@ private int ByteLength { } Utf8Map map = Map; if (map != null) { - int clrStart = map.ClrOf(start); - int clrEnd = (clrStart >= 0) ? map.ClrOf(start + count) : -1; - if (clrEnd >= 0) { - return MutableString.Create(map.Text.Substring(clrStart, clrEnd - clrStart), _scanString.Encoding); + MutableString mapped = ByteSliceMapped(map, start, count); + if (mapped != null) { + return mapped; } } return MutableString.CreateBinary(_scanString.GetBinarySlice(start, count), _scanString.Encoding); } + [MethodImpl(MethodImplOptions.NoInlining)] + private MutableString ByteSliceMapped(Utf8Map/*!*/ map, int start, int count) { + int clrStart = map.ClrOf(start); + int clrEnd = (clrStart >= 0) ? map.ClrOf(start + count) : -1; + return (clrEnd >= 0) ? MutableString.Create(map.Text.Substring(clrStart, clrEnd - clrStart), _scanString.Encoding) : null; + } + private MutableString/*!*/ RestString() { return ByteSlice(_position, ByteLength - _position); } @@ -482,38 +496,53 @@ private MatchData CurrentMatch { } } + /// + /// MatchRegex on a subject with a map: 1 matched, 0 did not, -1 the scan pointer is inside a + /// character and the old path is to decide. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private int MatchRegexMapped(Utf8Map/*!*/ map, RubyRegex/*!*/ pattern, bool anchored, bool advance) { + int clrPosition = map.ClrOf(_position); + if (clrPosition < 0) { + return -1; + } + // The MatchData is made here rather than left pending: the window match makes it anyway + // for a subject that is not one byte per character (see MatchWindowBounds). + MatchData data = _fixedAnchor + ? pattern.Match(_scanString, clrPosition, false) + : pattern.MatchWindow(_scanString, clrPosition, anchored, false); + int clrStart, clrEnd; + if (data == null || !data.TryGetGroupClrOffsets(0, out clrStart, out clrEnd)) { + return 0; + } + int byteStart = map.ByteOf(clrStart); + int byteEnd = (byteStart >= 0) ? map.ByteOf(clrEnd) : -1; + if (byteEnd >= 0) { + if (anchored && byteStart != _position) { + return 0; + } + _match = data; + _matchMap = map; + _matchBase = 0; + return Matched(byteStart, byteEnd, advance) ? 1 : 0; + } + if (!data.TryGetGroupByteOffsets(0, out byteStart, out byteEnd) || (anchored && byteStart != _position)) { + return 0; + } + _match = data; + _matchBase = 0; + return Matched(byteStart, byteEnd, advance) ? 1 : 0; + } + private bool MatchRegex(RubyRegex/*!*/ pattern, bool anchored, bool advance, bool lazyGroups) { ClearMatch(); Utf8Map map = Map; - int clrPosition = (map != null) ? map.ClrOf(_position) : -1; - if (clrPosition >= 0) { - // The MatchData is made here rather than left pending: the window match makes it anyway - // for a subject that is not one byte per character (see MatchWindowBounds). - MatchData data = _fixedAnchor - ? pattern.Match(_scanString, clrPosition, false) - : pattern.MatchWindow(_scanString, clrPosition, anchored, false); - int clrStart, clrEnd; - if (data == null || !data.TryGetGroupClrOffsets(0, out clrStart, out clrEnd)) { - return false; - } - int byteStart = map.ByteOf(clrStart); - int byteEnd = (byteStart >= 0) ? map.ByteOf(clrEnd) : -1; - if (byteEnd >= 0) { - if (anchored && byteStart != _position) { - return false; - } - _match = data; - _matchMap = map; - _matchBase = 0; - return Matched(byteStart, byteEnd, advance); - } - if (!data.TryGetGroupByteOffsets(0, out byteStart, out byteEnd) || (anchored && byteStart != _position)) { - return false; + if (map != null) { + int mapped = MatchRegexMapped(map, pattern, anchored, advance); + if (mapped >= 0) { + return mapped != 0; } - _match = data; - _matchBase = 0; - return Matched(byteStart, byteEnd, advance); } if (lazyGroups && !_fixedAnchor) { From e094889f39a8288d2f6447769144978659959ff4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:17:12 +0000 Subject: [PATCH 099/439] Copy a String slice while holding the content A slice of a string held as characters or bytes that does not share the array was copied without holding the content: Utils.GetSlice(GetDataSpan(), ...) read the array, its start and its count while a writer on another thread - #slice! off the front - moved them under its hold. `t = s[1..]` racing `s.slice!(0, 1)` came out with the string's last character several times (every run of the new Util/strcow-matrix.rb's two slice! rows differed from CRuby, 20 of 20). With a GVL CRuby never shows it. CharArrayContent.GetSlice and BinaryContent.GetSlice now enter the content (ContentState.Enter) for the copy too, as they did only to share a long slice; the decision whether to share is made once, held, instead of before and again while held. The cost is the compare-exchange: a short slice 2,877 -> 2,917 instructions (+1.4%) with the shape's driver, 92 -> 97-100 ns in a method's loop; a 5,000-character one +0.7%. Util/strcow-matrix.rb (new): dups, `+` and slices - short, long, middle, tail, of a slice - of strings held as characters, as bytes and as CLR strings, frozen and chilled, with each side then changed by <<, []=, setbyte, replace, slice!, force_encoding, encode!, squeeze!; Marshal; and threads appending to a string and its copy, readers slicing while a writer replaces, sets bytes or slices off the front. It prints CRuby's output, 10 runs of 10. Util/bench/strcow-shapes.rb times dup, `+` and slices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- .../Builtins/MutableString.BinaryContent.cs | 24 ++-- .../MutableString.CharArrayContent.cs | 24 ++-- Util/bench/strcow-shapes.rb | 55 +++++++++ Util/strcow-matrix.rb | 112 ++++++++++++++++++ 4 files changed, 191 insertions(+), 24 deletions(-) create mode 100644 Util/bench/strcow-shapes.rb create mode 100644 Util/strcow-matrix.rb diff --git a/Src/Ruby/Builtins/MutableString.BinaryContent.cs b/Src/Ruby/Builtins/MutableString.BinaryContent.cs index 3698ee015..32a815224 100644 --- a/Src/Ruby/Builtins/MutableString.BinaryContent.cs +++ b/Src/Ruby/Builtins/MutableString.BinaryContent.cs @@ -555,20 +555,20 @@ public override byte GetByte(int index) { } public override Content/*!*/ GetSlice(int start, int count) { - if (Utils.IsSharedSlice(_data.Length, Utils.NormalizeCount(_count, start, count))) { - // see Utils.IsSharedSlice; checked again while holding the content - bool shared = ContentState.Enter(ref _state); - try { - int sliceCount = Utils.NormalizeCount(_count, start, count); - if (Utils.IsSharedSlice(_data.Length, sliceCount)) { - shared = true; - return new BinaryContent(_data, _start + start, sliceCount, _owner); - } - } finally { - ContentState.Exit(ref _state, shared); + // Held for the copy too: unheld, a copy read the array, its start and its count while a writer on another thread + // moved them (a slice racing #slice! came out with characters of the string twice). + bool shared = ContentState.Enter(ref _state); + try { + int sliceCount = Utils.NormalizeCount(_count, start, count); + if (Utils.IsSharedSlice(_data.Length, sliceCount)) { + // see Utils.IsSharedSlice + shared = true; + return new BinaryContent(_data, _start + start, sliceCount, _owner); } + return Create(Utils.GetSlice(GetDataSpan(), start, count), _owner); + } finally { + ContentState.Exit(ref _state, shared); } - return Create(Utils.GetSlice(GetDataSpan(), start, count), _owner); } public override CharacterEnumerator/*!*/ GetCharacters() { diff --git a/Src/Ruby/Builtins/MutableString.CharArrayContent.cs b/Src/Ruby/Builtins/MutableString.CharArrayContent.cs index 2115da470..41e45a76f 100644 --- a/Src/Ruby/Builtins/MutableString.CharArrayContent.cs +++ b/Src/Ruby/Builtins/MutableString.CharArrayContent.cs @@ -390,20 +390,20 @@ public override byte GetByte(int index) { } public override Content/*!*/ GetSlice(int start, int count) { - if (Utils.IsSharedSlice(_data.Length, Utils.NormalizeCount(_count, start, count))) { - // see Utils.IsSharedSlice; checked again while holding the content - bool shared = ContentState.Enter(ref _state); - try { - int sliceCount = Utils.NormalizeCount(_count, start, count); - if (Utils.IsSharedSlice(_data.Length, sliceCount)) { - shared = true; - return new CharArrayContent(_data, _start + start, sliceCount, _owner, null); - } - } finally { - ContentState.Exit(ref _state, shared); + // Held for the copy too: unheld, a copy read the array, its start and its count while a writer on another thread + // moved them (a slice racing #slice! came out with characters of the string twice). + bool shared = ContentState.Enter(ref _state); + try { + int sliceCount = Utils.NormalizeCount(_count, start, count); + if (Utils.IsSharedSlice(_data.Length, sliceCount)) { + // see Utils.IsSharedSlice + shared = true; + return new CharArrayContent(_data, _start + start, sliceCount, _owner, null); } + return new CharArrayContent(Utils.GetSlice(GetDataSpan(), start, count), _owner); + } finally { + ContentState.Exit(ref _state, shared); } - return new CharArrayContent(Utils.GetSlice(GetDataSpan(), start, count), _owner); } public override CharacterEnumerator/*!*/ GetCharacters() { diff --git a/Util/bench/strcow-shapes.rb b/Util/bench/strcow-shapes.rb new file mode 100644 index 000000000..a74c7408f --- /dev/null +++ b/Util/bench/strcow-shapes.rb @@ -0,0 +1,55 @@ +# What copying a String costs (perf/strcow): a dup, a `+` and slices of short and long strings, held as characters +# (a string that was appended to), as an immutable CLR string (a literal) and frozen. ns per operation, the caller a +# `while' loop; with INSTR=1 (Util/perf/ab.rb -i, Util/perf/callgrind/count.sh) instructions too. plain, size and +# bytesize are controls. +$stdout.sync = true +def plain(a) = a +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-14s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +N = (ENV['N'] || 200_000).to_i +SHORT = ("a" * 10).tap { |s| s << "b" } +LONG = ("a" * 10_000).tap { |s| s << "b" } +LIT = "a" * 10_001 +FROZEN = ("a" * 10_001).freeze +L = "abc".dup +R = "def".dup + +t("dup_short", N) { |n| i = 0; c = 0; while i < n; c += SHORT.dup.bytesize + i; i += 1; end; c } +t("dup_long", N) { |n| i = 0; c = 0; while i < n; c += LONG.dup.bytesize + i; i += 1; end; c } +t("plus", N) { |n| i = 0; c = 0; while i < n; c += (L + R).bytesize + i; i += 1; end; c } +t("plus_long", N / 10) { |n| i = 0; c = 0; while i < n; c += (LONG + R).bytesize + i; i += 1; end; c } +t("slice_short", N) { |n| i = 0; c = 0; while i < n; c += SHORT[1, 5].bytesize + i; i += 1; end; c } +t("slice_mid", N / 10) { |n| i = 0; c = 0; while i < n; c += LONG[1, 5000].bytesize + i; i += 1; end; c } +t("slice_tail", N / 10) { |n| i = 0; c = 0; while i < n; c += LONG[5000..].bytesize + i; i += 1; end; c } +t("slice_lit", N / 10) { |n| i = 0; c = 0; while i < n; c += LIT[1, 5000].bytesize + i; i += 1; end; c } +t("slice_frozen", N / 10) { |n| i = 0; c = 0; while i < n; c += FROZEN[1, 5000].bytesize + i; i += 1; end; c } +t("size", N) { |n| i = 0; c = 0; while i < n; c += LONG.size + i; i += 1; end; c } +t("plain", N) { |n| i = 0; c = 0; while i < n; c += plain(i); i += 1; end; c } diff --git a/Util/strcow-matrix.rb b/Util/strcow-matrix.rb new file mode 100644 index 000000000..bc02081fc --- /dev/null +++ b/Util/strcow-matrix.rb @@ -0,0 +1,112 @@ +# Expression matrix for strings that share their characters or bytes (copy-on-write, perf/strcow): +# a dup, a `+` and slices - short, long, of the middle and of the tail, of a slice - of strings +# held as characters, as bytes and as an immutable CLR string, frozen and chilled; then each side +# changed by <<, []=, setbyte, replace, slice!, force_encoding, encode!, squeeze!, and the other +# side read; Marshal; and threads: two appending to a string and its copy, readers slicing while +# a writer replaces, setbyte and slice! racing a reader. A row must print what CRuby prints; +# threaded rows print only what does not depend on the interleaving. The two rows racing slice! +# tore on IronRuby before perf/strcow (a copied slice read the array unheld). +# +# ruby Util/strcow-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/strcow-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +# +# Every line is " => " or " !! : "; the rows of +# EXPRESSIONS run cold, again and 50 times, and a line says so when a later answer differs. +# -*- frozen_string_literal: false -*- + +def long(c = "a", n = 1000) = (s = c * n; s << "z"; s) # held as characters, room to spare +def bin(n = 1000) = (s = ("\xff" * n).b; s << "z".b; s) # held as bytes +def lit(n = 1000) = "a" * n # an immutable CLR string +def summary(s) = [s.size, s.bytesize, s.encoding.to_s, s[0, 3], s[-3, 3], s.valid_encoding?, s.frozen?] +def uniform?(s) = s.empty? || s.count(s[0]) == s.size + +$warnings = [] +module Warning + def self.warn(msg, category: nil) = ($warnings << msg.sub(/\A.*?: /, "")) +end + +EXPRESSIONS = <<~'RUBY'.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + # --- slices of a long string held as characters: change either side + (s = long; t = s[500..]; s << "X"; [summary(t), summary(s)]) + (s = long; t = s[500..]; t << "X"; [summary(t), summary(s)]) + (s = long; t = s[1..]; s[700] = "Q"; [t[698, 3], s[699, 3]]) + (s = long; t = s[1..]; t[700] = "Q"; [t[699, 3], s[700, 3]]) + (s = long; t = s[1..]; s.replace("x"); [summary(t), s]) + (s = long; t = s[1..]; t.replace("x"); [t, summary(s)]) + (s = long; t = s[1..]; s.slice!(0, 900); [summary(t), summary(s)]) + (s = long; t = s[1..]; t.slice!(0, 900); [summary(t), summary(s)]) + (s = long; t = s[1..]; s.setbyte(999, 66); [t[-3, 3], s[-3, 3]]) + (s = long; t = s[1..]; t.setbyte(0, 66); [t[0, 2], s[0, 2]]) + (s = long; t = s[1..]; s.force_encoding("BINARY"); s << "\xff".b; [summary(t), summary(s)]) + (s = long; t = s[1..]; t.force_encoding("UTF-16LE"); [t.encoding, summary(s)]) + (s = long; t = s[1..]; s.encode!("UTF-16LE"); [summary(t), s.bytesize]) + (s = long("ab"); t = s[1..]; s.squeeze!; [summary(t), summary(s)]) + (s = long; t = s[1..]; u = t[1..]; s << "1"; t << "2"; [summary(u), u[-3, 3]]) + (s = long; t = s[2, 600]; s << "X"; [summary(t)]) + (s = long; t = s[300, 701]; t << "Y"; [summary(t), summary(s)]) + (s = long; t = s[999..]; [t, t.size]) + (s = long; t = s[700..]; s.clear; [t.size, s]) + # --- slices of a string held as bytes + (s = bin; t = s.byteslice(1..); s.setbyte(5, 65); [t.bytes.first(6), s.bytes.first(6)]) + (s = bin; t = s[1..]; t << "!".b; [summary(t), summary(s)]) + (s = bin; t = s.byteslice(400, 601); s.force_encoding("UTF-8"); [summary(t), summary(s)]) + # --- multibyte characters + (s = long("é"); t = s[300..]; s << "ü"; [summary(t), summary(s)]) + (s = long("é"); t = s[300..]; t[0] = "x"; [t[0, 3], s[300, 3]]) + (s = long("日本"); t = s[1..]; s.force_encoding("BINARY"); [summary(t)]) + # --- immutable, frozen and chilled sources + (s = lit; t = s[1..]; t << "x"; [summary(t), summary(s)]) + (s = lit.freeze; t = s[1..]; t << "x"; [summary(t), summary(s)]) + (s = long.freeze; t = s[1..]; t << "x"; [summary(t), summary(s)]) + (s = long.freeze; t = s[1..]; [t.frozen?, t.equal?(s)]) + (s = long.freeze; d = s.dup; d << "x"; [summary(d), summary(s)]) + (d = "chilled literal".dup; d << "!"; [d, $warnings.size]) + ($warnings.clear; s = "chilled"; s << "!"; [s, $warnings]) + # --- dup and + + (s = long; d = s.dup; s << "1"; d << "2"; [s[-2, 2], d[-2, 2]]) + (s = long; d = s.dup; d.setbyte(0, 66); [s[0], d[0]]) + (s = long; c = s + "x"; s << "y"; [c[-2, 2], s[-2, 2], c.size]) + (s = long; c = s + s[1..]; s.clear; [c.size, uniform?(c[0, 1000])]) + (s = long; c = +s[1..]; c << "q"; [c[-2, 2], s[-2, 2]]) + # --- Marshal + (s = long; t = s[1..]; s << "m"; [Marshal.load(Marshal.dump(t)) == t, Marshal.load(Marshal.dump(s)) == s]) + (s = bin; t = s[1..]; Marshal.load(Marshal.dump(t)).bytesize) +RUBY + +THREADED = <<~'RUBY'.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + # two threads append to a string and its copy (a dup, a tail slice) + (s = long; d = s.dup; a = Thread.new { 5000.times { s << "s" } }; b = Thread.new { 5000.times { d << "d" } }; a.join; b.join; [s.size, d.size, s.count("d"), d.count("s")]) + (s = long; d = s[1..]; a = Thread.new { 5000.times { s << "s" } }; b = Thread.new { 5000.times { d << "d" } }; a.join; b.join; [s.size, d.size, s.count("d"), d.count("s")]) + # a reader slicing the tail while a writer replaces the whole string, letter by letter + (s = "a" * 2001; s << "a"; stop = false; w = Thread.new { i = 0; until stop; s.replace((i.even? ? "a" : "b") * 2002); i += 1; end }; bad = 0; 3000.times { t = s[1..]; bad += 1 unless uniform?(t) && t.size == 2001 }; stop = true; w.join; bad) + # a reader slicing while a writer sets bytes and another slices off the front + (s = long("a", 4000); stop = false; w = Thread.new { i = 0; until stop; s.setbyte(i % 4000, 98); s.setbyte(i % 4000, 97); i += 1; end }; bad = 0; 3000.times { t = s[1..]; bad += 1 unless t.size == 4000 && t.count("ab") == 4000 }; stop = true; w.join; bad) + # a tail slice racing slice! off the front (a long tail is shared, taken while the content is held) + (s = long("a", 4000); t = nil; w = Thread.new { 2000.times { s.slice!(0, 1) } }; r = Thread.new { 2000.times { t = s[1..]; raise "torn" unless uniform?(t[0..-2]) } }; w.join; r.join; [s.size, uniform?(s[0..-2])]) + # a middle slice racing slice!: copied, while the content is held + (s = long("a", 4000); bad = 0; w = Thread.new { 2000.times { s.slice!(0, 1) } }; r = Thread.new { 2000.times { t = s[1, 100]; bad += 1 unless uniform?(t) } }; w.join; r.join; [s.size, bad]) +RUBY + +def clean(v) = v.inspect.gsub(/0x\h+/, "XX") +def run(source) + "=> #{clean(eval(source))}" +rescue Exception => e + "!! #{e.class}: #{e.message.gsub(/0x\h+/, "XX")}" +end + +EXPRESSIONS.each do |source| + first = run(source) + second = run(source) + warm = nil + 50.times { warm = run(source) } + line = "#{source} #{first}" + line += " [second: #{second}]" if second != first + line += " [warm: #{warm}]" if warm != first + puts line +end +THREADED.each do |source| + results = 5.times.map { run(source) }.uniq + puts "#{source} #{results.join(' | ')}" +end +puts "done" From 3ed42f3fd912135e2df1b79fc5942900e0fe42e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:18:19 +0000 Subject: [PATCH 100/439] Ledger: rescue class lists in the filter, measured and not built A constant class list, core class or not, is decided in the first-pass filter already (RescueSiteCannotMatch reads the constant's site cache): a user class costs what a core class does. The filter is refused for every class list once the exception has passed an ensure, because Ruby evaluates the list after the ensure has run; the frame then catches and throws again, about 20 us for the first such frame. Deciding it in the filter is not sound (the ensure may reassign the constant, define ===, extend the exception); running the ensure from the filter would be. Shapes: Util/bench/rescue-above-ensure-shapes.rb. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/bench/rescue-above-ensure-shapes.rb | 27 ++++++++++++++++++++++++ Util/perf/LEDGER.md | 27 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 Util/bench/rescue-above-ensure-shapes.rb diff --git a/Util/bench/rescue-above-ensure-shapes.rb b/Util/bench/rescue-above-ensure-shapes.rb new file mode 100644 index 000000000..f72f045ba --- /dev/null +++ b/Util/bench/rescue-above-ensure-shapes.rb @@ -0,0 +1,27 @@ +# A raise rescued through frames whose rescue clause does not match, with and without an ensure frame below them: a +# constant class list (core or not) is decided in the CLR's first-pass filter (RubyOps.RescuePassMayTest, +# RescueSiteCannotMatch) unless the exception has already passed an ensure (PendingPassedEnsures), when the frame +# catches, completes the backtrace and throws again. us per raise, best of five. +# IR_CONFIG=Release ./ir.sh Util/bench/rescue-above-ensure-shapes.rb; ruby Util/bench/rescue-above-ensure-shapes.rb +N = 3000 +def run(name) + best = nil + 5.times { t = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID); N.times { begin; yield; rescue RuntimeError; end }; d = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) - t; best = d if !best || d < best } + printf "%-52s %8.2f us\n", name, best * 1e6 / N +end +class MyErr < StandardError; end +def ens; begin; raise "x"; ensure; @e = 1; end; end +def ens_call; begin; raise "x"; ensure; fin; end; end +def fin = @f = 1 +def r_core(&b); begin; yield; rescue ArgumentError; end; end +def r_user(&b); begin; yield; rescue MyErr; end; end +def r_user3(&b); r_user { r_user { r_user { yield } } }; end +run("bare") { raise "x" } +run("ensure frame only") { ens } +run("ensure (calls a method) only") { ens_call } +run("no ensure, rescue MyErr above") { r_user { raise "x" } } +run("ensure, rescue ArgumentError above") { r_core { ens } } +run("ensure, rescue MyErr above") { r_user { ens } } +run("ensure (call), rescue MyErr above") { r_user { ens_call } } +run("ensure, 3 x rescue MyErr above") { r_user3 { ens } } +run("no ensure, 3 x rescue MyErr above") { r_user3 { raise "x" } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 7480bfad9..3f66d936f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -5434,6 +5434,33 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/rescuefilter (2026-11-27) - deciding a constant rescue class list in the first-pass filter: + measured, not built - it is decided there already, except above a passed ensure, where it cannot + soundly be.** perf/timeout named "`rescue ExitException => e`: 29 us per frame against 8.6 for a core + class". Wrong attribution: alone, a rescue of a user class named by a constant - top-level, + qualified, lexical in a module, with or without `=> e`, of an Exception subclass followed by `raise` + - costs what a core class does (8-16 us per raise against a bare 8, + `Util/bench/rescue-above-ensure-shapes.rb`, new), because `RubyOps.RescueSiteCannotMatch` reads the + clause's constant site cache in the filter, for any constant. What turns the filter off is not the + class but an ensure the exception has already gone through: `RescuePassMayTest` refuses while + `PendingPassedEnsures` is not zero, for every class list, core classes included - Ruby evaluates the + class list after those ensures have run, and the CLR's first pass runs before them. Then the frame + catches, completes the backtrace the ensure began (`TakePassedEnsureCapture`, + `CaptureExceptionTrace`), finds no match and throws again: the first such frame above an ensure + costs about 20 us (33 against 14 without the ensure), each further one about 3 (three: 43); + CRuby 0.8 and 1.2. Timeout's raise has exactly this shape (`handle_timeout`'s rescue above the + Proc's `ensure request.finished`): with perf/timeout's override, leaving out any one of the + rescue, the ensure or the Proc takes it from 63-76 us to 25-31. + Not sound to decide in the filter: the pending ensure runs arbitrary code first (`request.finished` + calls a method), which can reassign the constant (the site's version would move, but only after + the filter answered), define `===` on the class, or `extend` the exception with a module of the + class list. What would take it: run the pending ensure clauses from the filter itself, on top of + the raise, before the class list is looked at (the order Ruby wants), and have the second pass skip + them - the pieces are there for ensure-only bodies (`PassEnsure`, `EnterPassedEnsure`, the stack + room `PassEnsureStackRoom` keeps for a clause run on top of the raise), not for a clause that a + rescue frame above has to wait for. A larger change than a step; its matrix would need every row of + raise-matrix about ensure order, `$!`, cause, retry and jumps out of an ensure. + - **perf/ensure (2026-11-26) - the catch-and-rethrow of an `ensure` clause that jumps (#213 item 3): measured, not built - real code almost never has such a frame on a raise's path.** Compiled, an `ensure` already lets an exception go through a CLR filter (`EnsureGuardExpression`, From 55be4d2aaececd918fc9bcf5186ecd76948704bd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:18:50 +0000 Subject: [PATCH 101/439] Reuse a nested block's enclosing Proc only where it can be outlined The first commit let every block literal with a literal nested in it reuse its Proc, and gave its method a parking slot. Where the nested literal's Proc is made on every call (an `Array#each' inside `Hash#each', a lambda in an `each'), that only cost the bookkeeping: callgrind counted 2.1-2.4% more instructions on such shapes, the slot trying 64 calls before it gives up and the nested Procs clearing the reuse each time. Now only a block that the block-loop screen accepts (BlockLoopInfo, read from the AST before the body is compiled) reuses its Proc although literals are nested in it: its nested iterators are the ones its outlined loop runs in place, so a call that runs the copy makes no nested Proc. A nested literal calls KeepEnclosingProcs only under such a block. Any other block with a nested literal compiles as it did before. Util/nested-proc-matrix.rb gets the cases this leaves: an outlined block whose nested `Range#each' or `times' is redefined mid-run to keep its block, the copy going stale and the generic body making the nested Proc. With KeepEnclosingProcs made a no-op those rows go wrong (a kept Proc reads the parked scope of a later call, or meets a cleared one), and they print what CRuby prints with it. Util/bench/nested-proc-shapes.rb: the shapes, in Util/perf/ab.rb's format. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Compiler/Ast/BlockDefinition.cs | 46 ++++--- Src/Ruby/Compiler/AstGenerator.cs | 5 + Util/bench/nested-proc-shapes.rb | 146 +++++++++++++++++++++++ Util/nested-proc-matrix.rb | 101 ++++++++++++++++ 4 files changed, 282 insertions(+), 16 deletions(-) create mode 100644 Util/bench/nested-proc-shapes.rb diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index 58e16092a..8f201ed40 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -206,6 +206,14 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St gen.CurrentBlock.LexicalDepth = _definedScope.Depth; gen.CurrentBlock.HasOwnCompiledFrame = true; + // -X:OSR: `n.times { }', `a.each { }' and the like run their loop in C#; a block that can be is outlined into that + // loop once it is hot (BlockLoopSite). Screened from the AST before the body is compiled: whether the block's Proc + // may be reused although literals are nested in it (see reusesProc below) is known to them as they are compiled. + BlockLoopInfo loopInfo = (!isLambda && gen.CanReplaceLoops) + ? BlockLoopInfo.TryCreate(this, gen.Context, _definedScope.Depth, gen.SourcePath + ":" + Location.Start.Line) + : null; + gen.CurrentBlock.ReusesProcWithNested = NestedProcsEnabled && loopInfo != null; + // the binding of the parameters is one assignment of each, whatever it takes to make it gen.BindingParameters = true; MSA.Expression paramInit = MakeParametersInitialization(gen, parameters); @@ -329,14 +337,15 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St bool reuseScope = lazyScope == null && !hasNestedReturn && !gen.CurrentBlock.HasNestedBlock && !gen.TraceEnabled && !gen.CompilerOptions.IsEval; - // The same held for the Proc of the literal (see BlockDispatcher.ReusesProc), but a nested literal's Proc is not made - // on every call: when the block runs as an iterator's outlined loop, the nested iterator's loop runs in place and makes - // none (BlockLoopSite, NestedBlockLoop). So the nested literal's Proc, when it is made, keeps this one from being made - // again (RubyOps.KeepEnclosingProcs) - and so from being parked - and a call that made - // none leaves this Proc - and the method's scope, if every literal of the method's own reuses its Proc - for the next - // call (NBody's `advance': a scope and two Procs per call). IR_NESTED_PROCS=0 keeps the old rule. + // The same holds for the Proc of the literal (see BlockDispatcher.ReusesProc) - unless the block may be outlined + // into its iterator's loop (ReusesProcWithNested), which runs the nested iterators in place and makes no nested Proc + // (BlockLoopSite, NestedBlockLoop). Then the nested literal's Proc, when a generic call does make it, keeps this one + // from being made again (RubyOps.KeepEnclosingProcs) - and so from being parked - and a call that made none leaves + // this Proc - and the method's scope, if every literal of the method's own reuses its Proc - for the next call + // (NBody's `advance': a scope and two Procs per call). IR_NESTED_PROCS=0 keeps the old rule; a block that is never + // outlined keeps it too, as reusing its Proc would only cost it the bookkeeping. bool hasNestedBlock = gen.CurrentBlock.HasNestedBlock; - bool reusesProc = !isLambda && !hasNestedReturn && (NestedProcsEnabled || !hasNestedBlock) && + bool reusesProc = !isLambda && !hasNestedReturn && (!hasNestedBlock || gen.CurrentBlock.ReusesProcWithNested) && !gen.TraceEnabled && !gen.CompilerOptions.IsEval; // (a method all of whose literals reuse their Procs may park its scope with them: MethodDefinition.ParkedScopesEnabled) @@ -425,12 +434,7 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St blockDispatcher.AssignedOuterVariableNames = assignedOuterVariables?.ToArray(); blockDispatcher.OuterVariableAssignments = outerVariableAssignments.ToArray(); } - if (!isLambda && gen.CanReplaceLoops) { - // -X:OSR: `n.times { }', `a.each { }' and the like run their loop in C#; a block that - // can be is outlined into that loop once it is hot (BlockLoopSite) - blockDispatcher.LoopInfo = BlockLoopInfo.TryCreate(this, gen.Context, _definedScope.Depth, - gen.SourcePath + ":" + Location.Start.Line); - } + blockDispatcher.LoopInfo = loopInfo; if (outerVariables == null && !hasNestedReturn && !gen.TraceEnabled && !gen.CompilerOptions.IsEval && IronRuby.Runtime.Jit.JitBlockMethod.Enabled && gen.Context.RubyOptions.Jit && IsJitMethodShape()) { // -X:JIT: a block over none of the enclosing scope's locals may become the body of a method @@ -477,14 +481,24 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St ) ) ); - if (NestedProcsEnabled && gen.CurrentBlock != null) { - // a literal nested in a block (the enclosing block's HasNestedBlock): its Proc holds the scope it is made in, and that - // block's Proc may be reused (see reusesProc above) + if (EnclosingBlockReusesProc(gen)) { + // a literal nested in a block whose Proc may be reused (see reusesProc above): its Proc reaches that one instance = Methods.KeepEnclosingProcs.OpCall(instance, gen.CurrentScopeVariable); } return reusesProc ? Ast.Assign(previousProc, instance) : instance; } + // A block this literal is nested in reuses its Proc although literals are nested in it (ReusesProcWithNested). Called + // after LeaveBlockDefinition: the generator's block chain is the enclosing one. + private static bool EnclosingBlockReusesProc(AstGenerator/*!*/ gen) { + for (var block = gen.CurrentBlock; block != null; block = block.ParentBlock) { + if (block.ReusesProcWithNested) { + return true; + } + } + return false; + } + // MRI labels a block frame "block in ", and counts the nesting once there // is more than one level. This runs after LeaveBlockDefinition, so the generator's // block chain is already the enclosing one and this block is the extra level. diff --git a/Src/Ruby/Compiler/AstGenerator.cs b/Src/Ruby/Compiler/AstGenerator.cs index 2df842a60..e98061055 100644 --- a/Src/Ruby/Compiler/AstGenerator.cs +++ b/Src/Ruby/Compiler/AstGenerator.cs @@ -356,6 +356,11 @@ public MSA.LabelTarget/*!*/ RedoLabel { // A block literal (or lambda) is nested in this one: its Proc captures this block's scope. public bool HasNestedBlock; + // This block may be outlined into an iterator's loop (BlockLoopInfo), which runs the nested iterators it holds in + // place and makes no Proc of their literals: its own Proc may be reused all the same (IR_NESTED_PROCS), and a literal + // nested in it keeps the enclosing Procs from being made again when it does make one (RubyOps.KeepEnclosingProcs). + public bool ReusesProcWithNested; + // The lexical depth of the block's own scope (LexicalScope.Depth): a local defined at a // smaller depth belongs to an enclosing scope. internal int LexicalDepth; diff --git a/Util/bench/nested-proc-shapes.rb b/Util/bench/nested-proc-shapes.rb new file mode 100644 index 000000000..11a6d30dc --- /dev/null +++ b/Util/bench/nested-proc-shapes.rb @@ -0,0 +1,146 @@ +# Methods whose block literals have literals nested in them, for IR_NESTED_PROCS (Util/perf/LEDGER.md, gap 2; +# RubyOps.KeepEnclosingProcs): such a literal reuses its Proc, and its method parks its scope, on the calls that make +# no nested Proc. Format of Util/perf/ab.rb: ` ns ` per shape (` instr' with INSTR=1); +# shape names as arguments, N from the environment. BYTES=1 (IronRuby only) prints bytes per call instead of ns. +# +# ruby Util/perf/ab.rb -i Util/bench/nested-proc-shapes.rb \ +# "off=env IR_NESTED_PROCS=0 Util/perf/callgrind/count.sh ../wt" "on=Util/perf/callgrind/count.sh ../wt" +# +# advance NBody's `advance' over five bodies: the nested `Range#each' runs in place in the outlined +# `each_index' loop, so no call makes a nested Proc - the shape the change is for +# nest the same nesting over Integers, a light body +# always a nested literal whose Proc every call makes (`Array#each' inside `Hash#each', which is not +# outlined): the slot tries 64 calls, gives up, and the nested Proc clears the reuse - the cost of +# the change where it cannot help +# lambda a nested lambda made on every call +# worker Richards' worker: a stored Proc called with Proc#call, `times' nested in it +# flat one literal, no nesting: a control, which the change does not touch +$stdout.sync = true +N = (ENV['N'] || 200_000).to_i +BYTES = ENV['BYTES'] == '1' + +class Body + attr_accessor :x, :y, :vx, :vy, :mass + def initialize(x, y, vx, vy, mass); @x = x; @y = y; @vx = vx; @vy = vy; @mass = mass; end +end + +class Sys + def initialize + @bodies = Array.new(5) { |i| Body.new(i * 1.5, i * 0.5 - 1.0, 0.01 * i, -0.02 * i, 1.0 + i) } + @ints = [1, 2, 3, 4, 5] + @h = { a: [1, 2], b: [3] } + end + + def advance(dt) + @bodies.each_index do |i| + i_body = @bodies[i] + ((i + 1)...@bodies.size).each do |j| + j_body = @bodies[j] + dx = i_body.x - j_body.x + dy = i_body.y - j_body.y + d2 = (dx * dx) + (dy * dy) + 0.01 + mag = dt / (d2 * Math.sqrt(d2)) + i_body.vx -= dx * j_body.mass * mag + i_body.vy -= dy * j_body.mass * mag + j_body.vx += dx * i_body.mass * mag + j_body.vy += dy * i_body.mass * mag + end + end + @bodies.each do |b| + b.x += dt * b.vx + b.y += dt * b.vy + end + end + + def energy + e = 0.0 + @bodies.each { |b| e += b.mass * (b.vx * b.vx + b.vy * b.vy) + b.x + b.y } + e + end + + def nest + s = 0 + @ints.each_index do |i| + a = @ints[i] + ((i + 1)...@ints.size).each do |j| + s += a * @ints[j] + j - i + (a & 3) + (j ^ 1) + a - 1 + end + end + s + end + + def always + s = 0 + @h.each { |_, v| v.each { |x| s += x } } + s + end + + def lambda_made + s = 0 + @ints.each { |x| f = -> { x * 2 }; s += f.call } + s + end + + def flat + s = 0 + @ints.each { |x| s += x } + s + end +end + +class Worker + def initialize + @count = 0 + data = [0] * 4 + @fn = proc do |w| + 4.times do |i| + @count += 1 + @count = 1 if @count > 26 + data[i] = 65 + @count - w + end + data[3] + end + end + def run(w) = @fn.call(w) +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + b0 = BYTES && System::GC.get_allocated_bytes_for_current_thread + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + d = (System::GC.get_allocated_bytes_for_current_thread - b0) / 1e9 if BYTES + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + sum = sum.round(6) if sum.is_a?(Float) + printf "%-12s %9.1f %s %s%s\n", name, best * 1e9 / n, BYTES ? 'B ' : 'ns', sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end + +t("advance", N) { |n| s = Sys.new; i = 0; while i < n; s.advance(0.01); i += 1; end; s.energy } +t("nest", N) { |n| s = Sys.new; i = 0; c = 0; while i < n; c += s.nest; i += 1; end; c } +t("always", N) { |n| s = Sys.new; i = 0; c = 0; while i < n; c += s.always; i += 1; end; c } +t("lambda", N) { |n| s = Sys.new; i = 0; c = 0; while i < n; c += s.lambda_made; i += 1; end; c } +t("worker", N) { |n| w = Worker.new; i = 0; c = 0; while i < n; c += w.run(i & 1); i += 1; end; c } +t("flat", N) { |n| s = Sys.new; i = 0; c = 0; while i < n; c += s.flat; i += 1; end; c } diff --git a/Util/nested-proc-matrix.rb b/Util/nested-proc-matrix.rb index 05b7c846e..00016fa7b 100644 --- a/Util/nested-proc-matrix.rb +++ b/Util/nested-proc-matrix.rb @@ -232,3 +232,104 @@ def m(n, out) N.times { |n| o.m(n, out) } [out.size, out.map(&:object_id).uniq.size, out.map(&:call)] } + +# ---------------------------------------------------------------- 8. an outlined block whose nested iterator keeps its block +# +# The blocks above are not outlined (their nested literals are given to methods that are not core iterators), so their +# Procs are never reused. These are: the nested `Range#each' and `times' run in place in the copy of the `each_index' +# block, and the method's scope is parked. Then the iterator is redefined to keep the block it is given, the copy goes +# stale, and the generic body makes the nested Proc - which must see the locals and self of its own call. + +$kept = [] +$keep = false + +class Outlined + def initialize; @a = [1.5, 2.5, 3.5, 4.5, 5.5]; @s = 0.0; end + attr_reader :s + def range(dt) + @a.each_index do |i| + x = @a[i] + ((i + 1)...@a.size).each do |j| + @s += (x - @a[j]) * dt + j + end + end + dt + end + def times(dt) + @a.each_index do |i| + x = @a[i] + (@a.size - i).times do |j| + @s += x * dt - j + end + end + dt + end +end + +def kept_values(dt_name) + r = $kept.map { |b| b.binding.local_variable_get(dt_name) rescue b.class } + $kept.clear + r +end + +t('outlined: Range#each redefined to keep its block') { + o = Outlined.new + N.times { |n| o.range(n * 0.25) } + Range.class_eval do + alias_method :__np_each, :each + def each(&b) + $kept << b if $keep + __np_each(&b) + end + end + begin + out = [] + 300.times do |n| + $keep = (n % 100 == 50) + o.range(n + 0.5) + end + $keep = false + out << kept_values(:dt) << kept_values(:dt) + out << o.s + ensure + Range.class_eval do + alias_method :each, :__np_each + remove_method :__np_each + end + end + N.times { |n| o.range(n * 0.5) } + out << o.s +} +t('outlined: kept nested blocks called later') { + o = Outlined.new + N.times { |n| o.times(n * 0.125) } + Integer.class_eval do + alias_method :__np_times, :times + def times(&b) + $kept << b if $keep + __np_times(&b) + end + end + begin + calls = [] + 200.times do |n| + $keep = (n == 10 || n == 150) + o.times(n * 2.0) + end + $keep = false + calls = $kept.map { |b| [b.call(7), b.binding.local_variable_get(:i), b.binding.local_variable_get(:x), b.binding.local_variable_get(:dt)] } + $kept.clear + [calls, o.s] + ensure + Integer.class_eval do + alias_method :times, :__np_times + remove_method :__np_times + end + end +} +t('outlined: kept again after the iterator is restored') { + o = Outlined.new + r = [] + 4.times { N.times { |n| o.range(n * 0.5) }; r << o.s } + r +} From d3b8844fc124c067c23351fb90adf66635f7105a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:19:19 +0000 Subject: [PATCH 102/439] LEDGER: perf/strsearch3 landed (not gated): StringScanner on UTF-8 no longer quadratic Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Util/perf/LEDGER.md | 51 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index d7bba8aef..096223254 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1115,7 +1115,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Landed: perf/strsearch2); `#byteindex` on UTF-8 found late is 1.3 us against 117 ns (the UTF-8 length of the prefix, `Encoding.UTF8.GetByteCount`, 1.1 us over 10 KB of mixed text), and from a positive offset other than 0 it walks the characters to it, so a - strscan-style loop of byte offsets over UTF-8 text is quadratic where CRuby's is not. + strscan-style loop of byte offsets over UTF-8 text is quadratic where CRuby's is not + (still so: `pos = s.byteindex(",", pos + 1)` over 100 KB of UTF-8, 93 ms against 0.36). + Round three (perf/strsearch3, see Landed) found that StringScanner itself, which does not + call `#byteindex`, was quadratic on UTF-8, and far worse; that is fixed. 22. **A `begin`/`rescue` or `ensure` in a method costs about 80 ns per call when nothing is raised**: `def r(x) begin; x + 1; rescue StandardError; 0; end end` 106 ns against CRuby's 24, the same with `ensure` 112 against 27 (`Util/bench/zjit-post-shapes.rb`, @@ -1487,6 +1490,52 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/strsearch3 (2026-11-27) - StringScanner on a UTF-8 subject maps bytes to characters + incrementally, without switching the subject to bytes (gap 21, round three)** - not gated. + Commits 0c41d0f, 8822aad on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j + 79a2c30 with a7b9a12 merged in. Chosen by measured size among the three items left under gap + 21: a loop over 10 KB and 100 KB of UTF-8 text (CRuby / base, ms) - StringScanner word by word + (`skip(/\s+/); scan(/\S+/)`) 0.20 / 55 and 2.1 / 8,400; `scan_until(/,/)` 0.072 / 13.8 and + 0.71 / 2,047; `byteindex(",", pos)` in a loop 0.039 / 2.7 and 0.36 / 93; `index(",", pos)` (a + character offset) 2.4 / 0.058 and 233 / 0.24 (CRuby's is the quadratic one). The scanner does not + use `#byteindex`, so its loop was its own: the scan pointer is a byte offset and the regex + matches CLR characters, and every conversion copied out and counted the whole prefix + (`CharIndexOf` before the match, `MatchData.ToByteIndex` after), while `eos?`, `matched`, + `getch`... read the subject as bytes, which switched it from characters to bytes, and the next + match decoded all of it again (profile: `SwitchToCharacters` 35%, UTF-8 transcoding 80% self). + Now a scanner keeps a map for a subject that is valid UTF-8 and not all ASCII, made for one + snapshot of its characters (ConvertToString's string; a changed subject has a new one) with its + UTF-8 length counted once; offsets are converted by walking the characters from a cursor (the + last offset converted), so a step costs about a token's length. Match offsets are taken as CLR + offsets (`MatchData.TryGetGroupClrOffsets`, new) and mapped; ByteLength, ByteSlice, getch's + width, charpos, bol?, an ASCII literal and Integer groups read the characters. An offset inside a + character, an ASCII, non-UTF-8 or broken subject, a group read after the subject changed, and + `IR_FAST_SEARCH=0` take the old paths. + Callgrind (`count.sh`, N=20000), instructions a pass over 10 KB, base / new: `ss_until_u` + 736,035,168 / 4,818,316 (0.0065); `ss_words_u` (not counted on the base: some 2.9e9) / 15,030,852; + `ss_words_a` (ASCII, a control) 13,620,867-13,727,541 / 14,080,576 (**+2.6 to +3.4%**; with + `IR_FAST_SEARCH=0` 13,969,285, so most of it is not the map's check: moving the mapped paths out + of `MatchRegex` and `ByteSlice` and inlining the early exit did not change it); `sw3_a`, `size` + unchanged. Time, `ab.rb -r 4`, ns a pass, CRuby / base / off / new: `ss_words_u` 414,855 / + 211,024,746 / 213,010,273 / 1,756,873; `ss_until_u` 150,450 / 52,087,624 / 52,459,357 / 635,316; + `ss_words_a` 364,739 / 633,832 / 635,709 / 1,439,309 - but that shape is bimodal from process to + process (0.7 to 2.1 ms on either build, five runs each), and base and off had spent minutes in the + slow shapes before it in the same process; the count is the number to go by. CSV.parse of + UTF-8 rows (`Zürich,"Müller, Jörg",42,ñandú`), CRuby / base / new: 10 KB 1.2 / 218 / 79 ms, 100 KB + 11 / 27,651 / 168 ms (the ASCII rows' times swing 17-95 ms from run to run on all three arms). + Still 4 to 8 times CRuby on UTF-8 scans (the regex call, a MatchData per match, a String per + token), about where ASCII scans already were. + Checked: `Util/string-search-matrix.rb` gained a StringScanner section (2,532 rows: 19 operations + from every byte offset of ASCII, UTF-8, astral, broken UTF-8, BINARY and EUC-JP subjects, word + loops, concat midway, `string=`, fixed_anchor, terminate/reset; 60,022 rows in all): this build + prints exactly what the base prints, switch on and off. The base differs from CRuby in 110 of the + new rows, all pre-existing and untouched: a scan started from a byte offset inside a character + (UTF-8, astral, EUC-JP: CRuby matches from the stray bytes, IronRuby finds nothing), a non-ASCII + literal on a BINARY subject (CRuby raises Encoding::CompatibilityError), EUC-JP. `csv-matrix` + and `erb-escape-matrix`: same as the base and CRuby. spec/core/string (3,963 examples), + spec/library/stringscanner (240), spec/library/csv, spec/library/erb: the same on base, new and + off, 0 failures (one error in all three, `String.try_convert`, run as a directory). + - **Gate of 2026-11-26 for round thirty-seven** (perf/lglobal, perf/lexical, perf/deadconst, perf/strsearch, perf/extiter, perf/struct, perf/dmethjit; the rejected perf/lsite's tools and perf/jitbody's census fix): the branch `claude/happy-gauss-95wm2j` at 2f8c31c against master From 6956e4eac5ebf78fb227a14c8c5b949e9dba8d03 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:20:37 +0000 Subject: [PATCH 103/439] Share a long tail slice of a String, as MRI does MRI shares the buffer of a substring that runs to the end of the string (rb_str_subseq, SHARABLE_SUBSTRING_P) and copies any other. IronRuby shared a slice only when it kept at least half of the array, so LONG[5000..] of 10,001 characters copied 5,001 characters: 1,580-1,613 ns against CRuby's 130. Utils.IsSharedSlice(length, count, toEnd) also shares a slice of 256 or more that runs to the end. Only String#[] and #slice ask for it (Content.GetSlice(start, count, shareTail), MutableString.GetSlice(start, count, shareTail)): #slice! is a slice and then a removal, and a shared array would make the removal copy all of it. The tail is decided while the content is held, as the other shared slices are. IR_SHARE_TAIL=0 turns it off. Instructions with the shape's driver: slice_tail 23,772 -> 3,505; slice_short, slice_mid, slice_lit, slice_frozen, dup, `+`, size and plain as with the held copy alone. In a method's loop, three alternating runs: 151-157 ns against 1,580-1,613. The strcow, dup, string-search, hot-shapes, jit and jit-calls matrices pass in every mode and with the switch off; Util/strcow-matrix.rb matched CRuby in 20 of 20 runs; spec/core/string and the 43 MutableString and String IronRuby.Tests as on the base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Libraries/Builtins/MutableStringOps.cs | 5 ++-- .../Builtins/MutableString.BinaryContent.cs | 19 +++++++++++++++ .../MutableString.CharArrayContent.cs | 19 +++++++++++++++ Src/Ruby/Builtins/MutableString.Content.cs | 9 +++++++ Src/Ruby/Builtins/MutableString.cs | 17 ++++++++++--- Src/Ruby/Runtime/Utils.cs | 11 +++++++++ Util/perf/LEDGER.md | 24 +++++++++++++++++++ 7 files changed, 99 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 14394066c..2138bb948 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1158,8 +1158,9 @@ public static MutableString GetSubstring(MutableString/*!*/ self, [DefaultProtoc return (start == charCount && count >= 0) ? self.CreateDerived() : null; } - // a long substring shares the receiver's array (MutableString.GetSlice) - return GetCharacterSlice(self, start, count); + // a long substring shares the receiver's array (MutableString.GetSlice), and so does a long tail + self.ToClrRange(ref start, ref count); + return self.GetSlice(start, count, true); } #region byteslice diff --git a/Src/Ruby/Builtins/MutableString.BinaryContent.cs b/Src/Ruby/Builtins/MutableString.BinaryContent.cs index 32a815224..b660ed61b 100644 --- a/Src/Ruby/Builtins/MutableString.BinaryContent.cs +++ b/Src/Ruby/Builtins/MutableString.BinaryContent.cs @@ -571,6 +571,25 @@ public override byte GetByte(int index) { } } + // A long slice that runs to the end shares the array as well (Content.GetSlice(int, int, bool)); any other is GetSlice's. + public override Content/*!*/ GetSlice(int start, int count, bool shareTail) { + int n = Utils.NormalizeCount(_count, start, count); + if (shareTail && start + n == _count && Utils.IsSharedSlice(_data.Length, n, true)) { + bool shared = ContentState.Enter(ref _state); + try { + // checked again while holding the content + int sliceCount = Utils.NormalizeCount(_count, start, count); + if (start + sliceCount == _count && Utils.IsSharedSlice(_data.Length, sliceCount, true)) { + shared = true; + return new BinaryContent(_data, _start + start, sliceCount, _owner); + } + } finally { + ContentState.Exit(ref _state, shared); + } + } + return GetSlice(start, count); + } + public override CharacterEnumerator/*!*/ GetCharacters() { if (_owner.HasByteCharacters) { return new MutableString.BinaryCharacterEnumerator(_owner.Encoding, _data, _start, _count); diff --git a/Src/Ruby/Builtins/MutableString.CharArrayContent.cs b/Src/Ruby/Builtins/MutableString.CharArrayContent.cs index 41e45a76f..d973e29a0 100644 --- a/Src/Ruby/Builtins/MutableString.CharArrayContent.cs +++ b/Src/Ruby/Builtins/MutableString.CharArrayContent.cs @@ -406,6 +406,25 @@ public override byte GetByte(int index) { } } + // A long slice that runs to the end shares the array as well (Content.GetSlice(int, int, bool)); any other is GetSlice's. + public override Content/*!*/ GetSlice(int start, int count, bool shareTail) { + int n = Utils.NormalizeCount(_count, start, count); + if (shareTail && start + n == _count && Utils.IsSharedSlice(_data.Length, n, true)) { + bool shared = ContentState.Enter(ref _state); + try { + // checked again while holding the content + int sliceCount = Utils.NormalizeCount(_count, start, count); + if (start + sliceCount == _count && Utils.IsSharedSlice(_data.Length, sliceCount, true)) { + shared = true; + return new CharArrayContent(_data, _start + start, sliceCount, _owner, null); + } + } finally { + ContentState.Exit(ref _state, shared); + } + } + return GetSlice(start, count); + } + public override CharacterEnumerator/*!*/ GetCharacters() { return new MutableString.CharArrayCharacterEnumerator(_owner.Encoding, _data, _start, _count); } diff --git a/Src/Ruby/Builtins/MutableString.Content.cs b/Src/Ruby/Builtins/MutableString.Content.cs index f073aea8e..831688ab6 100644 --- a/Src/Ruby/Builtins/MutableString.Content.cs +++ b/Src/Ruby/Builtins/MutableString.Content.cs @@ -325,6 +325,15 @@ internal virtual void PrepareForWrite(int minCapacity) { /// The owner of the result is the current owner. /// public abstract Content/*!*/ GetSlice(int start, int count); + + /// + /// GetSlice for a caller that leaves this string as it is (String#[]): a long slice that runs to the end of the string + /// may share the array too (Utils.IsSharedSlice). Not for #slice!, which removes the slice next and would then copy + /// the whole array to write it. + /// + public virtual Content/*!*/ GetSlice(int start, int count, bool shareTail) { + return GetSlice(start, count); + } public abstract string/*!*/ GetStringSlice(int start, int count); public abstract byte[]/*!*/ GetBinarySlice(int start, int count); diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index 866ef7aec..89744e1c0 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -2040,12 +2040,23 @@ public int GetFirstChar() { public MutableString/*!*/ GetSlice(int start, int count) { ContractUtils.Requires(start >= 0, "start"); ContractUtils.Requires(count >= 0, "count"); - return GetSlice(_content, start, count); + return GetSlice(_content, start, count, false); + } + + /// + /// GetSlice for String#[], which leaves this string as it is: a long slice that runs to the end may share the array too + /// (Content.GetSlice(int, int, bool)). + /// + public MutableString/*!*/ GetSlice(int start, int count, bool shareTail) { + ContractUtils.Requires(start >= 0, "start"); + ContractUtils.Requires(count >= 0, "count"); + // a slice too short to share takes the plain path + return GetSlice(_content, start, count, shareTail && count >= Utils.SharedSliceMinLength); } // The content is read once by the caller: a read on another thread can switch the string // between bytes and characters, and the indices are meant for the one the caller looked at. - private MutableString/*!*/ GetSlice(Content/*!*/ content, int start, int count) { + private MutableString/*!*/ GetSlice(Content/*!*/ content, int start, int count, bool shareTail = false) { // One ASCII character of a string held as characters, in an encoding where ASCII is itself: the // character is its own byte whatever the rest of the string holds, and its content can be shared. if (count == 1 && _encoding.IsAsciiIdentity && (content is StringContent || content is CharArrayContent) && @@ -2056,7 +2067,7 @@ public int GetFirstChar() { } } - var result = CreateDerived(content.GetSlice(start, count), _encoding); + var result = CreateDerived(shareTail ? content.GetSlice(start, count, true) : content.GetSlice(start, count), _encoding); // a part of an ASCII string is ASCII, and saying so spares the next operation a scan of it if ((_flags & (IsAsciiFlag | AsciiUnknownFlag)) == IsAsciiFlag) { result._flags = (result._flags & ~(AsciiUnknownFlag | SurrogatesUnknownFlag)) | IsAsciiFlag | NoSurrogatesFlag; diff --git a/Src/Ruby/Runtime/Utils.cs b/Src/Ruby/Runtime/Utils.cs index 1586f4700..63b58c522 100644 --- a/Src/Ruby/Runtime/Utils.cs +++ b/Src/Ruby/Runtime/Utils.cs @@ -379,6 +379,17 @@ internal static bool IsSharedSlice(int arrayLength, int count) { return count >= SharedSliceMinLength && count >= arrayLength - (arrayLength >> 1); } + /// + /// IsSharedSlice, and also a long slice that runs to the end of the string, however much of the array it keeps: + /// MRI shares the buffer of a substring that ends where the string ends (rb_str_subseq, SHARABLE_SUBSTRING_P) and + /// copies any other, so a tail keeps the array alive there too. IR_SHARE_TAIL=0: IsSharedSlice only. + /// + internal static bool IsSharedSlice(int arrayLength, int count, bool toEnd) { + return count >= SharedSliceMinLength && (toEnd && ShareTailSlices || count >= arrayLength - (arrayLength >> 1)); + } + + private static readonly bool ShareTailSlices = Environment.GetEnvironmentVariable("IR_SHARE_TAIL") != "0"; + internal const int SharedSliceMinLength = 256; internal static int NormalizeCount(int arrayLength, int start, int count) { diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 47b2e062d..4c951f307 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1625,6 +1625,30 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/strcow (2026-11-27, not gated) - a String slice copied while the content is held; a + long tail slice shares the array, as MRI's** (gap 24's dup note). Asked for: copy-on-write content + for dup, `+` and slices. Found: it is there already - CharArrayContent and BinaryContent share + their array on Clone and on a long slice and copy on the first write (ContentState, the + `MutableString_CopyOnWrite*` tests): a dup of 10,000 characters costs what a dup of 10 does (108 + ns), `+` is CRuby's time (97 against 106), a short slice too (95 against 101). What was left: + (1) a slice that is copied read the array unheld, so `s[1..]` racing `s.slice!(0, 1)` tore (the + string's last character several times; `Util/strcow-matrix.rb`'s slice! rows differed from CRuby + in 20 runs of 20). Copies are now made holding the content (`GetSlice` enters it once and decides + there): a short slice +40 instructions (2,877 -> 2,917), 92 -> 97-100 ns. (2) A tail slice, + which MRI shares (rb_str_subseq, SHARABLE_SUBSTRING_P) whatever it keeps alive, was copied + unless it kept half the array: `Utils.IsSharedSlice(length, count, toEnd)` shares a slice of 256 + or more that runs to the end, for String#[] and #slice only (`Content.GetSlice(start, count, + shareTail)`: #slice! removes the slice next and would then copy the whole array to write it). + `IR_SHARE_TAIL=0` turns (2) off. `LONG[5000..]` of 10,001 characters 23,772 -> 3,505 + instructions, 1,580-1,613 -> 151-157 ns (CRuby 130); a middle slice is copied as in MRI and stays + 1,550-1,620 (CRuby 487: half the bytes, a char is two) - a per-encoding byte store is the next + step there, not sharing. Controls level: dup, `+`, size, plain. Checks: `Util/strcow-matrix.rb` + (new; threads included) prints CRuby's output, 20 runs of 20 (master: 0 of 20); strcow, dup, + string-search, hot-shapes, jit and jit-calls matrices in every mode and with the switch off: + PASS; spec/core/string 3,963 examples, the one known try_convert wording error on both; the 43 + MutableString and String IronRuby.Tests: PASSED. Left: other readers of a content (index, each + char, the byte views) still read it unheld. + - **perf/dupcost (2026-11-26, not gated) - `String#dup` of a bare string: one look for instance data, and the copy constructor** (gap 24's dup note). Where the time went, by callgrind with the CLR's perf map over one `str_dup` section of `dup-shapes.rb` (instructions per call, the From 3c5fde4ca5b5af4383f1945ac5726226253ba9ed Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:21:00 +0000 Subject: [PATCH 104/439] Design: a rescue above a passed ensure, and why it is not built Docs/rescue-above-ensure.md: running a pending ensure clause from the first-pass filter of a rescue frame above it, so that the frame could decide there instead of catching and throwing again, is not sound. The CLR finally blocks between the raise and the ensure (a Mutex's unlock, a File's close, the DLR's and every Ruby frame's bookkeeping) run in the second pass and Ruby wants them first; a compiled clause reads its frame's CLR locals and cannot be called from outside; and a clause that raises, jumps or is interrupted cannot do so from a filter. Util/raise-matrix.rb: seventeen rows on a rescue above a passed ensure (order, $!, cause, each jump, retry, Mutex and File order, backtrace, Thread#raise and Thread#kill during the ensure), CRuby's output on the unchanged build in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Docs/rescue-above-ensure.md | 122 ++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 21 ++++++ Util/raise-matrix.rb | 129 ++++++++++++++++++++++++++++++++++++ 3 files changed, 272 insertions(+) create mode 100644 Docs/rescue-above-ensure.md diff --git a/Docs/rescue-above-ensure.md b/Docs/rescue-above-ensure.md new file mode 100644 index 000000000..36ae8e77d --- /dev/null +++ b/Docs/rescue-above-ensure.md @@ -0,0 +1,122 @@ +# A rescue above a passed ensure: design, and why stage 2 was not built + +A `rescue` whose clauses do not match costs nothing extra when its class list can be decided in +the CLR's first pass: the filter `RescuePassUnwinder || RescuePassMayTest && CannotMatch...` +(`Body.TransformExceptionHandling`, `RubyOps`) lets the exception go through without a catch. It +cannot when the exception has already gone through a compiled ensure clause that has not run yet +(`RubyExceptionData.PendingPassedEnsures`): the frame catches the exception, completes its +backtrace, matches the clauses, and throws it again. The first such frame above an ensure costs +about 20 us, each further one about 3; CRuby about 1 (`Util/bench/rescue-above-ensure-shapes.rb`). +`Timeout.timeout`'s raise has this shape (`Error.handle_timeout`'s rescue above the Proc's +`ensure request.finished`) and pays 40 of its 63-76 us for it. + +This note asks whether the pending ensure clauses could be run from the filter itself - in the +first pass, before the class list is looked at, which is the order Ruby wants - and the second +pass made to skip them. The answer is no, for reasons that are about the CLR's model, not about +the work: stage 2 was not built. The matrix rows are in `Util/raise-matrix.rb` ("a rescue above +a passed ensure") and print CRuby's output on the unchanged build. + +## What exists + +- **`EnsureGuardExpression`** guards the statements of a body that has an ensure clause and no + rescue clause. Compiled, it is a try with a filter, `RubyOps.PassEnsure`, and a fault block, + `RubyOps.EnterPassedEnsure`, inside the try/finally whose finally is the ensure clause. +- **`PassEnsure`** (first pass) lets the exception through when catching it would only have + taken note of it: the exception is marked handled, gets `$!` as its cause, and + `PendingPassedEnsures` is counted up. It refuses (the frame catches) for a stack overflow, a + stack more than `PassEnsureMaxDepth` compiled frames deep, or less than `PassEnsureStackRoom` + (512 KB) of stack left - room for the ensure clause, which in the second pass runs *on top of + the raise*: CoreCLR runs a finally funclet with the frames between the throw and the catch + still on the stack. +- **`EnterPassedEnsure`** (second pass, the fault block) sets `$!` for the clause, counts + `PendingPassedEnsures` down, and hands the frame's part of the backtrace to the exception + (`RubyExceptionData.EnterPassedEnsure`), so that a backtrace taken later still has the frame. +- **`RescuePassMayTest`** refuses while `PendingPassedEnsures` is not zero: the clauses of the + pending ensures will run Ruby code before Ruby would match this frame's class list. + +So "a clause run on top of the raise" already exists, and it is the CLR's second pass doing it in +its own order. What stage 2 needed is something else: the clause run during the *first* pass. + +## What stage 2 would have been + +The rescue frame's filter, finding `PendingPassedEnsures > 0`, would run each pending clause +itself, innermost first, then evaluate the class list as now, and mark the clauses as run so that +their finally blocks do nothing when the second pass reaches them (a flag on the exception's data +per pending clause, read by the clause's guard). The point was to keep this frame from catching +when nothing matches. + +## Why it is not sound + +1. **CLR finally blocks between the raise and the ensure run in the second pass, and Ruby wants + them first.** A clause of an outer frame runs, in Ruby, after everything inside it has been + cleaned up. Inside it there are C# `finally` blocks of library methods - `Mutex#synchronize` + unlocks in one (`RubyMutex.cs`), `File.open` with a block closes the file in one - the DLR's own + finally blocks (a Ruby frame restoring `$!`, popping its frame record), and the light frames' + bookkeeping. Run from a first-pass filter, the ensure clause would run before all of them. + `Util/raise-matrix.rb` "pe: a Mutex unlocked before the outer ensure" prints + `[[:locked, false]]` on CRuby and on IronRuby today; the early clause would see `true`, and + one that locked the mutex again would raise "deadlock; recursive locking". "pe: a File closed + before the outer ensure" is the same with `closed?`. Running those CLR blocks early too is not + possible: a filter cannot run another frame's finally, and the second pass runs it regardless. + Knowing that no such block lies between - no C# frame with a finally, no Ruby frame with + bookkeeping - would make the case too rare to matter: every Ruby frame has one. + +2. **The clause cannot be called from outside its frame.** A compiled ensure clause is code of its + frame's method, reading the frame's locals; a light frame keeps them in CLR locals, which no + other code can reach. Running it from an outer frame's filter needs it compiled as a closure + over a heap environment, for every ensure clause, raise or not - a cost on the path that does + not raise, to make the path that raises and does not match cheaper. + +3. **What the clause does may not stay inside a filter.** The CLR runs a filter and takes any + exception leaving it as "false"; a filter cannot transfer control. + - **The clause raises** ("pe: the ensure raises": the new exception replaces the old, with the + old as its cause). From the filter, the new exception would have to propagate from the + clause's frame, through the frames between it and this one, whose filters have already + answered for the old exception. There is no way to restart the first pass at an inner frame + with another exception. + - **The clause jumps** - `return` ("pe: return from the ensure": `:returned`), `break`, `next`, + `throw` (each its row), or `retry` of a rescue between. Each ends the exception and moves + control to a point inside the frames the first pass is walking. A filter can only return. + - **Thread#raise or Thread#kill while the clause runs** ("pe: Thread#raise during the ensure", + "pe: Thread#kill during the ensure"): delivered at a safe point inside the clause, the + exception would be thrown inside the filter and swallowed by the CLR; parking it again + would deliver it at the wrong place (after the old exception's handling) or lose it. + Each of these could make the filter say "catch" for the rest of the dispatch, but by then the + clause has run once, and the second pass would run it again (or skip it, and the effect of the + jump would be lost). + +4. **`$!`, `cause` and the backtrace** would be the smaller problem: `$!` in the clause is the + propagating exception (set as `EnterPassedEnsure` sets it), `cause` is decided by `PassEnsure` + already, and the backtrace part the clause's frame hands over could be handed over from the + filter as well. They do not rescue the design from 1-3. + +## What the second pass would have had to skip, and how + +Each pending clause run from a filter: the guard's finally would test a per-clause "already run" +mark on the exception's data (the frame's record index, which `EnterPassedEnsure` already has) and +do nothing - `$!` restore, the clause - while the frame's own bookkeeping still ran. This part is +easy; it is the order of everything else that is not. + +## What would be sound, and what it would win + +- **Cheaper catches**, not fewer: the first catch above a passed ensure completes the backtrace + the ensure began (`TakePassedEnsureCapture`, `CaptureExceptionTrace`) and throws again. Making + the throw again a `ExceptionDispatchInfo.Throw` of a captured dispatch, and the capture lazier, + would lower the 20 us without changing any order. That is ordinary profiling work, and needs a + sampler this environment does not have (`perf_event_open` is refused). +- **Fewer rescue frames on the path**: for `Timeout`, `handle_timeout`'s rescue exists to turn its + own `ExitException` into `Timeout::Error`. An IronRuby override could test `exc.equal?(e)` in a + way that does not need the rescue - it cannot: the rescue is how it learns that the exception + passed through. Left as it is. + +## Rows + +`Util/raise-matrix.rb`, section "a rescue above a passed ensure", seventeen rows: the ensure before +the class list (a class list that is a method call), a non-matching rescue with the ensure run +once, the constant of the class list reassigned in the ensure, `===` defined in it, the exception +extended with a module of the class list in it, `$!` in the ensure and after, the ensure raising +(cause), `return`, `break`, `next` and `throw` from the ensure, `retry` above it, a Mutex and a +File cleaned up before the outer ensure, the backtrace keeping the inner frame, and Thread#raise +and Thread#kill while the ensure runs. CRuby's output on the unchanged build with the JIT on, +`-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and `IR_LIGHT_FRAMES=0` (the matrix's one row that prints an +anonymous class's address differs from run to run, as before). diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 3f66d936f..9105a7a66 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -5434,6 +5434,27 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/passensure (2026-11-27) - running a pending ensure clause from the filter of a rescue frame + above it: designed, found unsound, not built** (stage 1 of the brief; `Docs/rescue-above-ensure.md`). + The idea (perf/rescuefilter): a rescue above a passed ensure catches and throws again (~20 us for the + first such frame) only because Ruby evaluates its class list after the ensure runs; run the ensure + from the rescue's first-pass filter, then decide there, and have the second pass skip the clause. + Not sound, for the CLR's model rather than the work: (1) the CLR finally blocks between the raise and + the ensure - a Mutex's unlock and File.open's close in C# library methods, the DLR's `$!` restores, + every Ruby frame's bookkeeping - run in the second pass, and Ruby wants them before an outer ensure: + `Util/raise-matrix.rb` "pe: a Mutex unlocked before the outer ensure" prints `[[:locked, false]]` on + CRuby and today, the early clause would see `true`; (2) a compiled or light frame's clause reads its + frame's CLR locals and cannot be called from an outer filter without compiling every ensure clause + as a closure (a cost on the path that does not raise); (3) a clause that raises, jumps (`return`, + `break`, `next`, `throw`, `retry` above) or is interrupted (Thread#raise, Thread#kill) cannot do so + from inside a filter, which can only return, and whose exceptions the CLR swallows. + `Util/raise-matrix.rb` has seventeen new rows, "a rescue above a passed ensure" (the ensure before a + class list that is a method call, a constant reassigned / `===` defined / the exception extended in + the ensure, `$!`, cause, each jump, retry, Mutex and File order, the backtrace, Thread#raise and + Thread#kill during the ensure): CRuby's output on the unchanged build in every mode. What is left + for the cost: a cheaper catch (a lazier capture, `ExceptionDispatchInfo` for the throw again), + which needs a sampler. + - **perf/rescuefilter (2026-11-27) - deciding a constant rescue class list in the first-pass filter: measured, not built - it is decided there already, except above a passed ensure, where it cannot soundly be.** perf/timeout named "`rescue ExitException => e`: 29 us per frame against 8.6 for a core diff --git a/Util/raise-matrix.rb b/Util/raise-matrix.rb index 20eafc5e4..43e0ea13e 100644 --- a/Util/raise-matrix.rb +++ b/Util/raise-matrix.rb @@ -113,3 +113,132 @@ def e2.exception; Array; end # ---- Exception#cause presence --------------------------------------------- puts "Exception#cause defined? #{Exception.method_defined?(:cause)}" puts "no-raise cause: #{StandardError.new('x').cause.inspect}" + +# ---- a rescue above a passed ensure (Docs/rescue-above-ensure.md) ----------- +# The class list of a rescue is evaluated after the ensure clauses of the frames the exception left have run, +# and those clauses can change what it answers; CLR finally blocks between (a Mutex's unlock, File.open's +# close) run before an ensure outside them. Each row raises below an ensure and rescues above it. +$pe_log = [] +def pe_log(x) = ($pe_log << x; x) +def pe_inner + begin + raise ArgumentError, "inner" + ensure + pe_log(:inner_ensure) + end +end +def pe_classes = (pe_log(:class_list); ArgumentError) +show("pe: ensure runs before the class list") { $pe_log.clear; begin; pe_inner; rescue pe_classes => e; pe_log(:rescued); end; $pe_log } +show("pe: no match, ensure ran once") { $pe_log.clear; begin; begin; pe_inner; rescue TypeError; end; rescue ArgumentError; end; $pe_log } +module PeK; end +PeK.const_set(:Target, TypeError) +def pe_reassign + begin + raise ArgumentError, "re" + ensure + PeK.send(:remove_const, :Target); PeK.const_set(:Target, ArgumentError) + end +end +show("pe: constant reassigned in the ensure") { PeK.send(:remove_const, :Target); PeK.const_set(:Target, TypeError); begin; pe_reassign; rescue PeK::Target => e; "rescued #{e.message}"; end } +PeCls = Class.new(StandardError) +def pe_eqq + begin + raise ArgumentError, "eqq" + ensure + def PeCls.===(o) = true + end +end +show("pe: === defined in the ensure") { begin; pe_eqq; rescue PeCls => e; "rescued #{e.message}"; ensure; PeCls.singleton_class.send(:remove_method, :===) rescue nil; end } +PeMod = Module.new +def pe_extend + begin + raise ArgumentError, "ext" + ensure + $!.extend(PeMod) + end +end +show("pe: exception extended in the ensure") { begin; pe_extend; rescue PeMod => e; "rescued #{e.message}"; end } +def pe_bang + begin + raise ArgumentError, "bang" + ensure + pe_log([:bang_in_ensure, $!&.message]) + end +end +show("pe: $! in the ensure and after") { $pe_log.clear; begin; pe_bang; rescue TypeError; rescue ArgumentError; end; [$pe_log, $!] } +def pe_ensure_raises + begin + raise ArgumentError, "first" + ensure + raise TypeError, "second" + end +end +show("pe: the ensure raises") { begin; begin; pe_ensure_raises; rescue ArgumentError; :wrong; end; rescue TypeError => e; [e.message, e.cause&.message]; end } +def pe_return + begin + raise ArgumentError, "ret" + ensure + return :returned + end +end +show("pe: return from the ensure") { begin; pe_return; rescue ArgumentError; :rescued; end } +show("pe: break from the ensure") { begin; [1].each { begin; raise ArgumentError, "brk"; ensure; break :broke; end }; rescue ArgumentError; :rescued; end } +show("pe: next from the ensure") { begin; [1].map { begin; raise ArgumentError, "nxt"; ensure; next :nexted; end }; rescue ArgumentError; :rescued; end } +show("pe: throw from the ensure") { catch(:pe) { begin; begin; raise ArgumentError, "thr"; ensure; throw :pe, :thrown; end; rescue ArgumentError; :rescued; end } } +show("pe: retry above") { n = 0; begin; n += 1; begin; raise ArgumentError, "try#{n}" if n < 3; ensure; pe_log(n); end; rescue TypeError; rescue ArgumentError; retry; end; n } +def pe_mutex(m) + begin + m.synchronize { raise ArgumentError, "mx" } + ensure + pe_log([:locked, m.locked?]) + end +end +show("pe: a Mutex unlocked before the outer ensure") { $pe_log.clear; begin; pe_mutex(Mutex.new); rescue TypeError; rescue ArgumentError; end; $pe_log } +def pe_file(path) + f = nil + begin + File.open(path) { |io| f = io; raise ArgumentError, "fo" } + ensure + pe_log([:closed, f.closed?]) + end +end +show("pe: a File closed before the outer ensure") { $pe_log.clear; begin; pe_file(__FILE__); rescue TypeError; rescue ArgumentError; end; $pe_log } +show("pe: backtrace has the inner frame") { begin; begin; pe_inner; rescue TypeError; end; rescue ArgumentError => e; e.backtrace.any? { |l| l.include?("pe_inner") }; end } +show("pe: Thread#raise during the ensure") do + q = Queue.new + th = Thread.new do + begin + begin + raise ArgumentError, "orig" + ensure + q.pop + end + rescue TypeError => e + [:replaced, e.message, e.cause&.message] + rescue ArgumentError + :orig_rescued + end + end + Thread.pass until th.status == "sleep" + th.raise(TypeError, "async") + th.value +end +show("pe: Thread#kill during the ensure") do + q = Queue.new; log = Queue.new + th = Thread.new do + begin + begin + raise ArgumentError, "orig" + ensure + log << :ensure_started + q.pop + log << :not_reached + end + rescue ArgumentError + log << :rescued + end + end + Thread.pass until th.status == "sleep" + th.kill; th.join + r = []; r << log.pop until log.empty?; r +end From a87b5dc87fc08416ab7348f5a10a096e03561448 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:22:02 +0000 Subject: [PATCH 105/439] Ledger: gap 16's regex line re-measured after perf/lframe; still 1.7-4.0% worse light perf/regexlight measured Util/bench/regex-shapes.rb under IR_LIGHT_REGEX=all against the default on b887bc1 with the callgrind counter, before building anything: gsub 1.017, split 1.020, kase 1.031, eqt 1.040 (214-268 instructions a call, as perf/lsite's +232), controls 1.000 and 0.985. The cheaper light entry did not flip it, so the default stays and nothing was built. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index c2e2389ff..d655d74ea 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1058,6 +1058,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has site is inside an expression, which control cannot enter). Left: the arms still double a large light frame's IL without register locals (m48 11.7 KB against 5.7), and a body with a multiple assignment and more than 24 calls loses 2-4% light for a reason not yet found. + **Re-measured after perf/lframe** (perf/regexlight, 2026-11-27, on b887bc1 + perf/lexical + a8feb83; `Util/perf/callgrind/count.sh`, `ab.rb -i -r 1 -n 20000 Util/bench/regex-shapes.rb`, + default against `IR_LIGHT_REGEX=all`): the regex literals that go to a method storing the + caller's `$~` still lose light - `gsub` 12,666 -> 12,887 (1.017), `split` 10,836 -> 11,050 + (1.020), `kase` 8,575 -> 8,843 (1.031), `eqt` 5,767 -> 5,998 (1.040), the controls `size` + 1.000 and `matchp` 0.985. 214-268 instructions a call, the +232 perf/lsite measured: the + cheaper light entry of perf/lframe did not change what the scope made late and the call + made twice cost. Nothing was built; the about 800 methods of the census's regex lines stay + out. A step on them has to make the second call or the late scope cheaper (perf/lsite and + perf/lsite2 tried the second and were rejected), not the light entry. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per site at start-up, 0.2-0.4 ms). TruffleRuby's `Primitive.x` is replaced at parse time. From 6b34d95766aae3e39ccafbec5fc1666cba199651 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:23:33 +0000 Subject: [PATCH 106/439] Integer#fdiv takes what the coerced fdiv answers as a Float `1.fdiv(Complex(1, 1))` answered (0.5-0.5i); CRuby's rb_int_fdiv_double takes the coerced result as a Float (NUM2DBL), so it is the RangeError "can't convert 0.5-0.5i into Float" (Util/coerce-matrix.rb's 10 fdiv rows). 1.fdiv(Rational(3, 2)) is still 0.666... Checked: Integer_FDivCoerced1 (new; CRuby 4.0's output); coerce-matrix's fdiv rows same; spec/core/integer/fdiv: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IntegerTests.cs | 18 ++++++++++++++++++ Src/Libraries/Extensions/ClrInteger.cs | 7 +++++-- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ee13f4154..9ae5a378f 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1445,6 +1445,7 @@ public Tests(Driver/*!*/ driver) { Kernel_IsAModuleRequired1, Struct_InspectMemberNames1, Integer_BitwiseCoerce1, + Integer_FDivCoerced1, Comparison_AnonymousClassName1, }; } diff --git a/Src/IronRuby.Tests/Runtime/IntegerTests.cs b/Src/IronRuby.Tests/Runtime/IntegerTests.cs index 63e6c9a47..b67590929 100644 --- a/Src/IronRuby.Tests/Runtime/IntegerTests.cs +++ b/Src/IronRuby.Tests/Runtime/IntegerTests.cs @@ -1603,6 +1603,24 @@ def o.coerce(x) = [1.5, 2.5] # # # +"); + } + + /// + /// Integer#fdiv of what is coerced takes the result as a Float, as MRI's rb_int_fdiv_double (NUM2DBL): of a Complex + /// a RangeError, not the Complex. Util/coerce-matrix.rb. + /// + public void Integer_FDivCoerced1() { + TestOutput(@" +require 'ruby4' +[-> { 1.fdiv(Complex(1, 1)) }, -> { -3.fdiv(Complex(2, 0)) }, -> { (2**64).fdiv(Complex(1, 1)) }, -> { 1.fdiv(Rational(3, 2)) }, + -> { 1.fdiv(""x"") }].each { |l| p((l.call rescue $!)) } +", @" +# +# +# +0.6666666666666666 +# "); } } diff --git a/Src/Libraries/Extensions/ClrInteger.cs b/Src/Libraries/Extensions/ClrInteger.cs index 69c24cb60..8c0066f44 100644 --- a/Src/Libraries/Extensions/ClrInteger.cs +++ b/Src/Libraries/Extensions/ClrInteger.cs @@ -869,8 +869,11 @@ public static double FDiv([NotNull]BigInteger/*!*/ self, double other) { /// [RubyMethod("fdiv")] public static object FDiv(BinaryOpStorage/*!*/ coercionStorage, BinaryOpStorage/*!*/ binaryOpSite, - object/*!*/ self, object other) { - return Protocols.CoerceAndApply(coercionStorage, binaryOpSite, "fdiv", self, other); + ConversionStorage/*!*/ floatConversion, object/*!*/ self, object other) { + // MRI's rb_int_fdiv_double takes what the coerced fdiv answers as a Float (NUM2DBL): 1.fdiv(Complex(1, 1)) is + // the RangeError "can't convert 0.5-0.5i into Float", not the Complex. + object result = Protocols.CoerceAndApply(coercionStorage, binaryOpSite, "fdiv", self, other); + return (result is double) ? result : Protocols.CastToFloat(floatConversion, result); } /// /// Returns self modulo other, where other is Fixnum. See for more information. From f0b2fedfa89130dcd804501e910d0473c7ddbcc9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:23:34 +0000 Subject: [PATCH 107/439] Integer#remainder: the dividend for an infinite divisor, and #remainder coerced for a Bignum `-3.remainder(Float::INFINITY)` answered -3.0; CRuby's num_remainder returns the dividend itself, -3, for an infinite divisor of the other sign (the binder had widened the Fixnum to the Bignum-by-Float overload, which took dividend % divisor). And a Bignum's remainder of something not an Integer or Float went to num_remainder's '%': CRuby's rb_big_remainder coerces and calls #remainder, so (2**64).remainder(Complex(1, 1)) is "undefined method 'remainder' for an instance of Complex". (2**63 - 1 is a long here, a Bignum in CRuby, and counts as one; the coercion has a call site storage of its own, as one holds one site.) Checked: Integer_RemainderCoerced1 (new; CRuby 4.0's output); coerce-matrix's remainder rows same; spec/core/integer/remainder, spec/core/numeric/remainder: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IntegerTests.cs | 32 ++++++++++++++++++++++ Src/Libraries/Extensions/ClrBigInteger.cs | 16 +++++++++-- 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9ae5a378f..c9eb0b548 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1446,6 +1446,7 @@ public Tests(Driver/*!*/ driver) { Struct_InspectMemberNames1, Integer_BitwiseCoerce1, Integer_FDivCoerced1, + Integer_RemainderCoerced1, Comparison_AnonymousClassName1, }; } diff --git a/Src/IronRuby.Tests/Runtime/IntegerTests.cs b/Src/IronRuby.Tests/Runtime/IntegerTests.cs index b67590929..f05a760fc 100644 --- a/Src/IronRuby.Tests/Runtime/IntegerTests.cs +++ b/Src/IronRuby.Tests/Runtime/IntegerTests.cs @@ -1621,6 +1621,38 @@ public void Integer_FDivCoerced1() { # 0.6666666666666666 # +"); + } + + /// + /// Integer#remainder: a Fixnum's is num_remainder, which answers the dividend itself for an infinite divisor of the other + /// sign (-3, not -3.0); a Bignum's is rb_big_remainder, which coerces and calls #remainder (Complex has none). + /// + public void Integer_RemainderCoerced1() { + TestOutput(@" +require 'ruby4' +[-> { (2**70).remainder(Complex(1,1)) }, -> { 3.remainder(Complex(1,1)) }, -> { -3.remainder(Float::INFINITY) }, -> { 3.remainder(-Float::INFINITY) }, + -> { (2**70).remainder(Float::INFINITY) }, -> { -3.remainder(2.5) }, -> { (-(2**70)).remainder(-Float::INFINITY) }, -> { 3.remainder(Rational(1,2)) }, + -> { -3.remainder(Rational(1,2)) }, -> { -3.0.remainder(Float::INFINITY) }, -> { 0.remainder(Float::INFINITY) }].each { |l| p((l.call rescue $!)) } +[2**64, -(2**64), 2**63 - 1].each { |x| [Complex(1, 1), 2].each { |a| p((x.__send__(:remainder, a) rescue $!)) } } +", @" +# +# +-3 +3 +1.1805916207174113e+21 +-0.5 +-1.1805916207174113e+21 +(0/1) +(0/1) +-3.0 +0.0 +# +0 +# +0 +# +1 "); } } diff --git a/Src/Libraries/Extensions/ClrBigInteger.cs b/Src/Libraries/Extensions/ClrBigInteger.cs index 97de71f2d..c3a6f7591 100644 --- a/Src/Libraries/Extensions/ClrBigInteger.cs +++ b/Src/Libraries/Extensions/ClrBigInteger.cs @@ -703,12 +703,17 @@ public static object Remainder(BigInteger/*!*/ self, int other) { /// /// Float [RubyMethod("remainder")] - public static double Remainder(RubyContext/*!*/ context, BigInteger/*!*/ self, double other) { + public static object Remainder(RubyContext/*!*/ context, BigInteger/*!*/ self, double other) { // Converted (and warned about) before the zero check, as MRI's coercion does. double dividend = Protocols.ConvertToDouble(context, self); if (other == 0.0) { throw new DivideByZeroException("divided by 0"); } + // A Fixnum's remainder is MRI's num_remainder, which answers the dividend itself - an Integer - for an infinite + // divisor of the other sign: -3.remainder(Float::INFINITY) is -3. + if (Double.IsInfinity(other) && self >= FixnumMin && self <= FixnumMax && !self.IsZero && (self.Sign < 0) != (other < 0)) { + return Protocols.Normalize(self); + } return dividend % other; } @@ -724,7 +729,14 @@ public static double Remainder(RubyContext/*!*/ context, BigInteger/*!*/ self, d /// prelude, under its alias): the coerced dividend's % and its sign, not its #remainder. /// [RubyMethod("remainder")] - public static object Remainder(BinaryOpStorage/*!*/ coercionStorage, BinaryOpStorage/*!*/ binaryOpSite, object/*!*/ self, object other) { + public static object Remainder(BinaryOpStorage/*!*/ coercionStorage, BinaryOpStorage/*!*/ binaryOpSite, + BinaryOpStorage/*!*/ coercedRemainderStorage, object/*!*/ self, object other) { + // A Bignum's is rb_big_remainder, which coerces and calls #remainder: (2**70).remainder(Complex(1, 1)) is "undefined + // method 'remainder' for an instance of Complex", where a Fixnum's num_remainder asks for '%'. + if (self is BigInteger big && (big < FixnumMin || big > FixnumMax) || self is long l && (l < (long)FixnumMin || l > (long)FixnumMax)) { + // (a storage of its own: one holds a single site, and binaryOpSite's is __ir_num_remainder__) + return Protocols.CoerceAndApply(coercionStorage, coercedRemainderStorage, "remainder", self, other); + } var site = binaryOpSite.GetCallSite("__ir_num_remainder__"); return site.Target(site, self, other); } From 10a768e28c1c8e2c177e76a5be7907e65de16e9d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:23:34 +0000 Subject: [PATCH 108/439] Float::INFINITY.divmod(-2) is FloatDomainError "Infinity", as flodivmod's quotient is the dividend CRuby's flodivmod sets the quotient to the dividend itself when it is infinite and the divisor is not, whatever the divisor's sign; IronRuby divided, so the error said "-Infinity" (Util/coerce-matrix.rb's "INF divmod -2"). Checked: Float_DivmodInfinite1 (new; CRuby 4.0's output); spec/core/float divmod and modulo: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 20 ++++++++++++++++++++ Src/Libraries/Extensions/ClrFloat.cs | 3 ++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index c9eb0b548..c31fda1fb 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1014,6 +1014,7 @@ public Tests(Driver/*!*/ driver) { Float_NegativeZero1, Math_CLibrary1, Math_LogBaseAndOrder1, + Float_DivmodInfinite1, Errno_MessageNotDoubled1, Process_ClockGetTime1, Process_ThreadCpuTime1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index a11aa5e83..89d344479 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8764,6 +8764,26 @@ def n1 p lines ", @" [[4, :e3], [6, :e5], [7, :e6], [9, :e7], [11, :n1]] +"); + } + + /// + /// Float#divmod of an infinite dividend by a finite divisor: MRI's flodivmod takes the quotient as the dividend itself, + /// so Float::INFINITY.divmod(-2) is FloatDomainError "Infinity". + /// + public void Float_DivmodInfinite1() { + TestOutput(@" +require 'ruby4' +[-> { Float::INFINITY.divmod(-2) }, -> { (-Float::INFINITY).divmod(2) }, -> { Float::INFINITY.divmod(2.5) }, -> { Float::NAN.divmod(2) }, + -> { Float::INFINITY.div(-2) }, -> { Float::INFINITY % -2 }, -> { 7.5.divmod(-2) }].each { |l| p((l.call rescue $!)) } +", @" +# +# +# +# +# +NaN +[-4, -0.5] "); } } diff --git a/Src/Libraries/Extensions/ClrFloat.cs b/Src/Libraries/Extensions/ClrFloat.cs index 09de507bb..f3c374cbe 100644 --- a/Src/Libraries/Extensions/ClrFloat.cs +++ b/Src/Libraries/Extensions/ClrFloat.cs @@ -1257,7 +1257,8 @@ private static RubyArray InternalDivMod(double self, double other) { } if (Double.IsInfinity(self) && !Double.IsInfinity(other)) { - div = self / other; + // flodivmod: div = x, whatever the divisor's sign - Float::INFINITY.divmod(-2) is "Infinity" + div = self; } else { div = Math.Round((self - mod) / other, MidpointRounding.AwayFromZero); } From 21f5ca8efc5e78a5e95b7a0bac188a0327ca2a2f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:23:34 +0000 Subject: [PATCH 109/439] Rational#coerce names the class it refuses, and Numeric#divmod takes the modulo first `Rational(3, 4).coerce(nil)` said "nil can't be coerced into Rational"; CRuby's nurat_coerce names the class (rb_obj_classname): "NilClass can't be coerced into Rational". And Numeric#divmod (Rational's) asked a #coerce twice before failing: CRuby's num_divmod is rb_assoc_new(num_div(x, y), num_modulo(x, y)), whose arguments gcc evaluates right to left, so the modulo - a coerce and then y * q - fails first, after one coerce (Util/coerce-matrix.rb's "(3/4) divmod coerce" and "(3/4) coerce nil"). Checked: Rational_CoerceAndDivmod1 (new; CRuby 4.0's output); coerce-matrix 22 -> 4 lines (those four are `x << 2**64`, a NoMemoryError in CRuby, which tries to allocate it); spec/core/rational coerce and divmod, spec/core/numeric/divmod, spec/core/complex: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 24 ++++++++++++++++++++++++ Src/StdLib/ironruby/ironruby/rational.rb | 3 ++- Src/StdLib/ironruby/ruby4.rb | 5 ++++- 4 files changed, 31 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index c31fda1fb..cab61e325 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1015,6 +1015,7 @@ public Tests(Driver/*!*/ driver) { Math_CLibrary1, Math_LogBaseAndOrder1, Float_DivmodInfinite1, + Rational_CoerceAndDivmod1, Errno_MessageNotDoubled1, Process_ClockGetTime1, Process_ThreadCpuTime1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 89d344479..0c2dd8a11 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8784,6 +8784,30 @@ public void Float_DivmodInfinite1() { # NaN [-4, -0.5] +"); + } + + /// + /// Rational#coerce of what it cannot take names the class (nurat_coerce: "NilClass can't be coerced into Rational"); and + /// Numeric#divmod computes the modulo first (gcc's order of num_divmod's arguments), so a coerce is asked once before the error. + /// + public void Rational_CoerceAndDivmod1() { + TestOutput(@" +require 'ruby4' +class C1 + @@log = [] + def self.log = @@log + def coerce(o) = (@@log << :coerce; [o, 2]) +end +p((Rational(3, 4).divmod(C1.new) rescue $!.class), C1.log) +p((Rational(3, 4).coerce(nil) rescue $!), (Rational(3, 4).coerce(""x"") rescue $!), (Rational(3, 4).coerce(:s) rescue $!), Rational(3, 4).coerce(2)) +", @" +NoMethodError +[:coerce] +# +# +# +[(2/1), (3/4)] "); } } diff --git a/Src/StdLib/ironruby/ironruby/rational.rb b/Src/StdLib/ironruby/ironruby/rational.rb index 9ab1de5b4..d43c6b1d3 100644 --- a/Src/StdLib/ironruby/ironruby/rational.rb +++ b/Src/StdLib/ironruby/ironruby/rational.rb @@ -282,7 +282,8 @@ def coerce(other) real = other.real [::Float === real ? real.to_r : ::Rational.__new_internal__(real, 1), self] else - ::Kernel.raise(::TypeError, "#{__ir_coerce_name__(other)} can't be coerced into #{self.class}") + # (nurat_coerce names the class, rb_obj_classname: "NilClass can't be coerced into Rational") + ::Kernel.raise(::TypeError, "#{other.class} can't be coerced into #{self.class}") end end diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 784671707..f730aa0b1 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3454,8 +3454,11 @@ def modulo(other) end alias :% :modulo + # MRI's num_divmod is rb_assoc_new(num_div(x, y), num_modulo(x, y)), whose arguments gcc evaluates right + # to left: the modulo first, which is what a coerce or an error in between shows. def divmod(other) - [div(other), modulo(other)] + m = modulo(other) + [div(other), m] end # The modulo moved back across zero when the two point in opposite From 8e3b2d13ac8980b92330fde2fc682db5bfcffc40 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:29:45 +0000 Subject: [PATCH 110/439] Kernel#Integer: a sign alone is "invalid value" before the radix, and the message is rb_inspect's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Integer("-", 1)` and `Integer("+", 37)` said "invalid radix"; CRuby's rb_int_parse_cstr finds a string of only whitespace and a sign empty before it looks at the radix, so it is "invalid value for Integer(): \"-\"". And the message quoted the string raw where CRuby uses rb_inspect, which escapes non-ASCII when the default external encoding is not the string's (LANG unset: US-ASCII): `Integer(" 1")` is "invalid value for Integer(): \" 1\"" (Util/numeric-conversion-matrix.rb, 14 rows). Kernel#Integer passes its context for the message (RubyContext.Inspect); ParseInteger's other callers keep #inspect's quoting. Checked: Kernel_IntegerSignOnlyAndInspect1 (new; CRuby 4.0's output), Kernel_IntegerFloat1; spec/core/kernel/Integer, String#to_i, Integer.try_convert, Time.new: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 27 +++++++++++++++++ Src/Libraries/Builtins/KernelOps.cs | 40 +++++++++++++++---------- 3 files changed, 53 insertions(+), 15 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index cab61e325..1ec06c0ec 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1016,6 +1016,7 @@ public Tests(Driver/*!*/ driver) { Math_LogBaseAndOrder1, Float_DivmodInfinite1, Rational_CoerceAndDivmod1, + Kernel_IntegerSignOnlyAndInspect1, Errno_MessageNotDoubled1, Process_ClockGetTime1, Process_ThreadCpuTime1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 0c2dd8a11..2db7b4570 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8808,6 +8808,33 @@ class C1 # # [(2/1), (3/4)] +"); + } + + /// + /// Kernel#Integer: a string of only whitespace and a sign is "invalid value" before the radix is looked at (rb_int_parse_cstr), + /// and the message quotes the string with rb_inspect, which escapes non-ASCII for a US-ASCII default external. Util/numeric-conversion-matrix.rb. + /// + public void Kernel_IntegerSignOnlyAndInspect1() { + TestOutput(@" +require 'ruby4' +v, $VERBOSE = $VERBOSE, nil; Encoding.default_external = Encoding::US_ASCII; $VERBOSE = v +[-> { Integer(""-"", 1) }, -> { Integer(""+"", 37) }, -> { Integer("" - "", 2) }, -> { Integer(""1"", 1) }, -> { Integer("""", 1) }, + -> { Integer("" "", 37) }, -> { Integer("" 1"") }, -> { Integer(""1 "", 16) }, -> { Integer(""é1"") }, -> { Integer(""1\xff"".b) }, + -> { Integer(""-"", exception: false) }, -> { Integer(""+-1"") }].each { |l| p((l.call rescue $!)) } +", @" +# +# +# +# +# +# +# +# +# +# +nil +# "); } } diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index 3297ace99..2ec27bbe6 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -209,8 +209,8 @@ internal static double FloatStepSize(double beg, double end, double unit, bool e // Integer(string), Integer(fixnum) and Integer(float), the common calls, without the storages and the keyword parameter of the // general overload below: the binder's dispatch to that one cost more than the conversion (~100 ns for a Fixnum). [RubyMethod("Integer", RubyMethodAttributes.PrivateInstance)] - public static object ToInteger(object self, [NotNull]MutableString/*!*/ value) { - return ParseInteger(value, 0, true); + public static object ToInteger(RubyContext/*!*/ context, object self, [NotNull]MutableString/*!*/ value) { + return ParseInteger(value, 0, true, context); } [RubyMethod("Integer", RubyMethodAttributes.PrivateInstance)] @@ -240,7 +240,7 @@ public static object ToInteger(ConversionStorage/*!*/ fixnumCast, UnaryOpSt // the common cases, without the keyword and protocol machinery if (radixOrOptions == Missing.Value) { if (value is MutableString str) { - return ParseInteger(str, 0, true); + return ParseInteger(str, 0, true, fixnumCast.Context); } if (value is int || value is long || value is BigInteger) { return value; @@ -277,7 +277,7 @@ public static object ToInteger(ConversionStorage/*!*/ fixnumCast, UnaryOpSt return clrInteger; } if (value is MutableString s) { - return ParseInteger(s, radix, raise); + return ParseInteger(s, radix, raise, fixnumCast.Context); } if (value == null) { if (!raise) { @@ -300,7 +300,7 @@ public static object ToInteger(ConversionStorage/*!*/ fixnumCast, UnaryOpSt MutableString text = TryConvertToStr(toStr, value); if (text != null) { - return ParseInteger(text, radix, raise); + return ParseInteger(text, radix, raise, fixnumCast.Context); } if (!raise) { @@ -604,7 +604,7 @@ private static void RequireAsciiCompatible(MutableString/*!*/ value) { /// A string that does not read as an Integer is an ArgumentError, or null when /// is false. /// - public static object ParseInteger(MutableString/*!*/ value, int radix, bool raise = true) { + public static object ParseInteger(MutableString/*!*/ value, int radix, bool raise = true, RubyContext context = null) { RequireAsciiCompatible(value); var str = value.ConvertToString(); @@ -612,7 +612,7 @@ public static object ParseInteger(MutableString/*!*/ value, int radix, bool rais // Integer("\n", 1) is "invalid value", not "invalid radix" - but not about an empty one, // whose radix is checked first: Integer("", 1) is "invalid radix", with exception: false too. if (str.Length > 0 && !HasIntegerDigits(str)) { - return raise ? throw InvalidIntegerValue(value) : null; + return raise ? throw InvalidIntegerValue(value, context) : null; } // Only a positive radix is range-checked; a negative one is a hint, and an @@ -625,7 +625,7 @@ public static object ParseInteger(MutableString/*!*/ value, int radix, bool rais if (TryParseRubyInteger(str, radix, out result)) { return result; } - return raise ? throw InvalidIntegerValue(value) : null; + return raise ? throw InvalidIntegerValue(value, context) : null; } #endregion @@ -636,24 +636,34 @@ public static object ParseInteger(MutableString/*!*/ value, int radix, bool rais // prefix of 0x, 0b, 0o or 0d may appear, and a bare leading zero means octal; single // underscores may separate digits. Derived by differential testing against CRuby 3.3.8. - /// True when the string holds anything but surrounding whitespace. + /// + /// True when the string holds anything but surrounding whitespace and a sign: MRI's rb_int_parse_cstr finds a string of + /// only those empty before it looks at the radix, so Integer("-", 1) is "invalid value", not "invalid radix". + /// private static bool HasIntegerDigits(string/*!*/ str) { + bool sign = false; foreach (char c in str) { - if (!IsIntegerWhitespace(c)) { - return true; + if (IsIntegerWhitespace(c)) { + continue; } + if ((c == '+' || c == '-') && !sign) { + sign = true; + continue; + } + return true; } return false; } /// - /// MRI quotes the offending string as #inspect does: control characters and bytes that - /// are not valid in its encoding escaped ("1\xFF"), everything else passed through. + /// MRI quotes the offending string with rb_inspect: control characters and bytes that are not valid in its + /// encoding escaped ("1\xFF"), and non-ASCII escaped too ("\u00A01") unless output reads the string's encoding + /// (RubyContext.Inspect). Without a context (a caller other than Kernel#Integer), #inspect's quoting alone. /// - private static Exception/*!*/ InvalidIntegerValue(MutableString/*!*/ value) { + private static Exception/*!*/ InvalidIntegerValue(MutableString/*!*/ value, RubyContext context) { // thrown at once by its callers, kept by nothing return RubyExceptionData.MarkUnkept(RubyExceptions.CreateArgumentError("invalid value for Integer(): {0}", - MutableStringOps.GetQuotedStringRepresentation(value, false, '"'))); + (context != null) ? context.Inspect(value) : MutableStringOps.GetQuotedStringRepresentation(value, false, '"'))); } private static bool IsIntegerWhitespace(char c) { From cf37538499b0558ec4aec609608ad2d263f406ba Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:29:45 +0000 Subject: [PATCH 111/439] Rational() and Complex() of true or false name the value, as convert_type_err does `Rational(true)` said "can't convert TrueClass into Rational"; CRuby's convert_type_err names nil, true and false by value: "can't convert true into Rational" (and Complex(false) the same; Util/numeric-conversion-matrix.rb, 4 rows). numeric-conversion-matrix: 18 -> 2 lines, the two "Object#to_i gives NilClass" that ruby/spec pins as "gives nil". Checked: Kernel_RationalComplexSpecialMessage1 (new; CRuby 4.0's output); spec/core/kernel Rational and Complex: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 18 ++++++++++++++++++ Src/StdLib/ironruby/ironruby/complex.rb | 4 +++- Src/StdLib/ironruby/ironruby/rational.rb | 3 ++- 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 1ec06c0ec..cacb489e5 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1017,6 +1017,7 @@ public Tests(Driver/*!*/ driver) { Float_DivmodInfinite1, Rational_CoerceAndDivmod1, Kernel_IntegerSignOnlyAndInspect1, + Kernel_RationalComplexSpecialMessage1, Errno_MessageNotDoubled1, Process_ClockGetTime1, Process_ThreadCpuTime1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 2db7b4570..e09229801 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8835,6 +8835,24 @@ public void Kernel_IntegerSignOnlyAndInspect1() { # nil # +"); + } + + /// + /// Rational() and Complex() of something with no to_r / to_c name nil, true and false by value (convert_type_err): + /// "can't convert true into Rational". Util/numeric-conversion-matrix.rb. + /// + public void Kernel_RationalComplexSpecialMessage1() { + TestOutput(@" +require 'ruby4' +[-> { Rational(true) }, -> { Complex(false) }, -> { Rational(nil) }, -> { Complex(nil) }, -> { Rational(:s) }, -> { Complex(Object.new) }].each { |l| p((l.call rescue $!).message.sub(/0x\h+/, ""XX"")) } +", @" +""can't convert true into Rational"" +""can't convert false into Complex"" +""can't convert nil into Rational"" +""can't convert nil into Complex"" +""can't convert Symbol into Rational"" +""can't convert Object into Complex"" "); } } diff --git a/Src/StdLib/ironruby/ironruby/complex.rb b/Src/StdLib/ironruby/ironruby/complex.rb index 57ccb77a0..dd0c0e433 100644 --- a/Src/StdLib/ironruby/ironruby/complex.rb +++ b/Src/StdLib/ironruby/ironruby/complex.rb @@ -810,7 +810,9 @@ def self.__parse_string__(str, strict, raise_error = true) # to_complex: rb_convert_type(val, T_COMPLEX, "Complex", "to_c") def self.__to_complex__(value) unless __ir_responds_to__(value, :to_c) - ::Kernel.raise(::TypeError, "can't convert #{nil.equal?(value) ? 'nil' : __ir_class_of__(value)} into Complex") + # (convert_type_err names nil, true and false by value) + special = nil.equal?(value) || true.equal?(value) || false.equal?(value) + ::Kernel.raise(::TypeError, "can't convert #{special ? value.inspect : __ir_class_of__(value)} into Complex") end result = value.to_c unless ::Complex === result diff --git a/Src/StdLib/ironruby/ironruby/rational.rb b/Src/StdLib/ironruby/ironruby/rational.rb index d43c6b1d3..56c97fce3 100644 --- a/Src/StdLib/ironruby/ironruby/rational.rb +++ b/Src/StdLib/ironruby/ironruby/rational.rb @@ -551,7 +551,8 @@ def self.__to_rational__(value) __ir_responds_to__(value, :to_r) end unless responds - name = nil.equal?(value) ? 'nil' : __ir_class_of__(value) + # (rb_convert_type's convert_type_err names nil, true and false by value) + name = (nil.equal?(value) || true.equal?(value) || false.equal?(value)) ? value.inspect : __ir_class_of__(value) ::Kernel.raise(::TypeError, "can't convert #{name} into Rational") end result = value.to_r From f7c9fb0f70c220263ef076d13446790f7c6472e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:33:55 +0000 Subject: [PATCH 112/439] Add Util/string-race-matrix.rb; LEDGER: gap 39, a String under a concurrent writer The matrix races 36 String readers against 7 writers that flip a string between known states; a reader must answer what it answers on one of those states. CRuby prints ok in every row. IronRuby, 20 runs on 6956e4e: 101 of 252 rows are not always ok - readers raise IndexOutOfRangeException, RangeError or ArgumentError, answer what no state held, and in 30 rows make the writer itself raise, because a reader switched how the string is held under it. The causes are three and run through every reader: content reads made without holding the content, representation switches made and published unheld, and the encoding read apart from the content. No reader-by-reader fix is sound against the last two, so nothing is changed here; gap 39 records the table and the design a fix would need, a decision like gap 20's for Array and Hash. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Util/perf/LEDGER.md | 28 +++++++++ Util/string-race-matrix.rb | 122 +++++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 Util/string-race-matrix.rb diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 4c951f307..f3c2287dd 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1623,6 +1623,34 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `def kw(a, k: 1) = a + k` costs about 1,300-1,500 with the JIT off (4,017 against `v_two_kw` 2,435) in either lowering. Not the splat lowering: see Rejected, perf/lexical3. +39. **A String is not safe under a concurrent writer either** - a correctness gap, like gap 20 for + Array and Hash, found by perf/strrace (2026-11-27). `Util/string-race-matrix.rb` races 36 readers + against 7 writers that flip a string between known states (replace, an append and its removal, + slice! and prepend, setbyte and back, an insertion and its removal, force_encoding there and + back, encode! there and back); a reader must answer what it answers on one of those states. + CRuby: every row ok. IronRuby (6956e4e, 20 runs): 101 of 252 rows are not always ok - every + kind of reader: `end_with?`, `getbyte`, `each_byte` and `unpack1` raise IndexOutOfRangeException; + `split` and `sum` RangeError; `hash`, `rindex`, `to_sym` and `upcase` ArgumentError; index, + rindex, `<=>`, hash, chars, count, scan, inspect, upcase, byteslice, size and valid_encoding? + answer what no state held; and in 30 rows the *writer* raises (force_encoding or encode!: + "character U+0000 can't be encoded in ASCII-8BIT"), because a reader changed how the string is + held under it. Three causes, each in every reader, so no reader-by-reader fix is sound: + (1) readers read the content's array, start and count unheld while a writer shifts the array in + place (Remove, Insert) or replaces it - the slice copy was the one reader that held it (perf/strcow); + (2) a reader that switches the representation (SwitchToBinary/SwitchToChars, from getbyte, + bytes, unpack, index of a byte string...) converts unheld and publishes with SetContent, so a + write made meanwhile is lost or decoded in the wrong encoding - readers corrupt the string; + (3) `_encoding` and `_content` are separate fields read separately, so a reader can pair the new + bytes with the old encoding. The design that would fix it, not started: every content read + held (ContentState.Enter, one compare-exchange, the cost perf/strcow measured for a slice: + +1.4% instructions, +5-8% time on a short one), with operations on two strings (==, <=>, + include?, index of a String) holding one and copying or snapshotting the other - never both, + or two threads comparing a == b and b == a spin forever; a representation switch made holding + the old content and published only if it is still the owner's (compare-exchange on + `_rawContent`), every writer re-checking after it holds that its content is still current; and + the encoding kept with the content (or read under the same hold). A decision about what + IronRuby promises, as gap 20 is, before an experiment. + ## Landed - **perf/strcow (2026-11-27, not gated) - a String slice copied while the content is held; a diff --git a/Util/string-race-matrix.rb b/Util/string-race-matrix.rb new file mode 100644 index 000000000..8fb021d86 --- /dev/null +++ b/Util/string-race-matrix.rb @@ -0,0 +1,122 @@ +# Readers of a String racing a writer on another thread (perf/strrace). There is no GVL here: a +# reader that reads a string's array, start and count while a writer moves them can answer what no +# state of the string ever held, or raise. Each writer below flips the string between a few states, +# each of them consistent (replace, an append and its removal, slice! and prepend, one byte set and +# reset, an insertion and its removal, the encoding forced back and forth, encode! there and back); +# a reader's answer must be one it gives on one of those states, computed beforehand on copies. +# CRuby, whose GVL makes each call atomic, prints "ok" in every row. +# +# ruby Util/string-race-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/string-race-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +# +# A row is " / : ok", "wrong" (an answer of no state), "raises " or, when the +# writer itself failed (a reader that changes how the string is held can do that to it), "writer +# raises ". A reader with a block (each_char, each_byte) lets the writer run between yields in +# CRuby too, so only its exceptions count. Run it +# many times (the races are rare): a single run proves little. READS sets the reads per row. +# -*- frozen_string_literal: false -*- + +READS = (ENV["READS"] || 2000).to_i +N = 300 + +ASCII = ("abcdefghij" * N).freeze +MB = ("aé日" * (N / 2)).freeze + +# writer name => [the string's states, a block that flips the string between them forever] +WRITERS = { + "replace" => [[ASCII, "XYZ" * 50], ->(s, st) { s.replace(st[1]); s.replace(st[0]) }], + "append" => [[ASCII, ASCII + "Q" * 40], ->(s, _) { s << "Q" * 40; s.slice!(-40, 40) }], + "slice!_front" => [[ASCII, ASCII[3..]], ->(s, _) { s.slice!(0, 3); s.prepend("abc") }], + "setbyte" => [[ASCII, ASCII.dup.tap { |x| x.setbyte(150, 90) }], ->(s, _) { s.setbyte(150, 90); s.setbyte(150, ASCII.getbyte(150)) }], + "insert" => [[ASCII, ASCII.dup.insert(100, "XYZ")], ->(s, _) { s[100, 0] = "XYZ"; s[100, 3] = "" }], + "force_encoding" => [[MB, MB.dup.force_encoding("BINARY")], ->(s, _) { s.force_encoding("BINARY"); s.force_encoding("UTF-8") }], + "encode!" => [[MB, MB.encode("UTF-16LE")], ->(s, _) { s.encode!("UTF-16LE"); s.encode!("UTF-8") }], +} + +READERS = { + "index" => ->(s) { s.index("hij") }, + "index_at" => ->(s) { s.index("a", 200) }, + "rindex" => ->(s) { s.rindex("abc") }, + "index_mb" => ->(s) { s.index("日") }, + "include?" => ->(s) { s.include?("jab") }, + "start_with?" => ->(s) { s.start_with?("abcdefghijab") }, + "end_with?" => ->(s) { s.end_with?("ghij") }, + "==" => ->(s) { s == ASCII }, + "eql?" => ->(s) { s.eql?(MB) }, + "<=>" => ->(s) { s <=> ASCII }, + "hash" => ->(s) { s.hash }, + "size" => ->(s) { s.size }, + "bytesize" => ->(s) { s.bytesize }, + "chars" => ->(s) { s.chars }, + "each_char" => ->(s) { n = 0; s.each_char { |c| n += 1 if c.nil? }; n }, + "bytes" => ->(s) { s.bytes }, + "each_byte" => ->(s) { n = 0; s.each_byte { |b| n += 1 unless b.is_a?(Integer) && b.between?(0, 255) }; n }, + "getbyte" => ->(s) { s.getbyte(150) }, + "byteslice" => ->(s) { s.byteslice(140, 20) }, + "[]_char" => ->(s) { s[150] }, + "[]_range" => ->(s) { s[140, 20] }, + "count" => ->(s) { s.count("a") }, + "sum" => ->(s) { s.sum }, + "to_sym" => ->(s) { s.to_sym }, + "dup" => ->(s) { s.dup }, + "+" => ->(s) { s + "!" }, + "upcase" => ->(s) { s.upcase }, + "reverse" => ->(s) { s.reverse }, + "split" => ->(s) { s.split("j") }, + "=~" => ->(s) { s =~ /hij/ }, + "scan" => ->(s) { s.scan(/a./).size }, + "unpack1" => ->(s) { s.unpack1("C*") }, + "valid_encoding?" => ->(s) { s.valid_encoding? }, + "ascii_only?" => ->(s) { s.ascii_only? }, + "inspect" => ->(s) { s.inspect }, + "encoding" => ->(s) { s.encoding }, +} + +def answer(reader, s) + [:value, reader.(s)] +rescue => e + [:raise, e.class] +end + +# comparing a torn answer can raise too (a String of a broken encoding): that is a wrong answer +def allowed?(allowed, a) + allowed.include?(a) +rescue + false +end + +Thread.report_on_exception = false +ONLY = ENV["ONLY"] +READERS.each do |rname, reader| + next if ONLY && !rname.match?(ONLY) + WRITERS.each do |wname, (states, flip)| + allowed = states.map { |st| answer(reader, st.dup) } + s = states[0].dup + stop = false + writer = Thread.new do + flip.(s, states) until stop + nil + rescue => e + e.class + end + wrong = 0 + raised = [] + READS.times do + a = answer(reader, s) + if a[0] == :raise && !allowed?(allowed, a) + raised << a[1] + elsif !allowed?(allowed, a) + wrong += 1 + end + end + stop = true + failed = writer.value + result = if failed then "writer raises #{failed}" + elsif !raised.empty? then "raises #{raised.uniq.map(&:to_s).sort.join(', ')}" + elsif wrong > 0 then "wrong" + else "ok" end + puts "#{rname} / #{wname}: #{result}" + end +end +puts "done" From 7f9c47a43535d551c5df63e419cf151849dfed53 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:37:20 +0000 Subject: [PATCH 113/439] sprintf: a directive cut short is "malformed format string", after the argument it named A format string that ended after flags ("%-", "%0"), or after "%1$" or "%", said "malformed format string - %"; CRuby 4.0 says "malformed format string" - and fetches the argument of "%1$" / "%" when it reads them, so with no arguments those are "too few arguments" and "one hash required" first. A directive a newline or NUL ends ("%\n") is the plain "malformed format string" too (case '\n', '\0' of sprintf.c), not "- %\n". Util/format-matrix.rb: 16 lines -> same. Checked: Sprintf_MalformedEnd1 (new; CRuby 4.0's output) and the other Sprintf_ tests; spec/core/kernel sprintf and format, String#% and #format: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 30 +++++++++++++++++++++++ Src/Libraries/Builtins/StringFormatter.cs | 11 ++++++++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index cacb489e5..2c4ad5a23 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1018,6 +1018,7 @@ public Tests(Driver/*!*/ driver) { Rational_CoerceAndDivmod1, Kernel_IntegerSignOnlyAndInspect1, Kernel_RationalComplexSpecialMessage1, + Sprintf_MalformedEnd1, Errno_MessageNotDoubled1, Process_ClockGetTime1, Process_ThreadCpuTime1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index e09229801..b9a70aa7c 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8853,6 +8853,36 @@ public void Kernel_RationalComplexSpecialMessage1() { ""can't convert nil into Complex"" ""can't convert Symbol into Rational"" ""can't convert Object into Complex"" +"); + } + + /// + /// A directive the format string ends in after flags, or after a %1$ or % whose argument MRI has fetched by then + /// (too few arguments, one hash required first), is "malformed format string"; so is one a newline or NUL ends. Util/format-matrix.rb. + /// + public void Sprintf_MalformedEnd1() { + TestOutput(@" +require 'ruby4' +[""%-"", ""%#"", ""% "", ""%+"", ""%0"", ""%5"", ""%."", ""%*"", ""%"", ""%1$"", ""%"", ""%{"", ""%\n"", ""%\0"", ""% \n"", ""a%\nb""].each do |f| + p [f, (format(f) rescue $!.message), (format(f, 1) rescue $!.message), (format(f, a: 1) rescue $!.message)] +end +", @" +[""%-"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""%#"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""% "", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""%+"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""%0"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""%5"", ""malformed format string - %*[0-9]"", ""malformed format string - %*[0-9]"", ""malformed format string - %*[0-9]""] +[""%."", ""malformed format string - %*[0-9]"", ""malformed format string - %*[0-9]"", ""malformed format string - %*[0-9]""] +[""%*"", ""malformed format string - %*[0-9]"", ""malformed format string - %*[0-9]"", ""malformed format string - %*[0-9]""] +[""%"", ""incomplete format specifier; use %% (double %) instead"", ""incomplete format specifier; use %% (double %) instead"", ""incomplete format specifier; use %% (double %) instead""] +[""%1$"", ""too few arguments"", ""malformed format string"", ""malformed format string""] +[""%"", ""one hash required"", ""one hash required"", ""malformed format string""] +[""%{"", ""malformed name - unmatched parenthesis"", ""malformed name - unmatched parenthesis"", ""malformed name - unmatched parenthesis""] +[""%\n"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""%\u0000"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""% \n"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +[""a%\nb"", ""malformed format string"", ""malformed format string"", ""malformed format string""] "); } } diff --git a/Src/Libraries/Builtins/StringFormatter.cs b/Src/Libraries/Builtins/StringFormatter.cs index 818676d57..9aea6508d 100644 --- a/Src/Libraries/Builtins/StringFormatter.cs +++ b/Src/Libraries/Builtins/StringFormatter.cs @@ -236,6 +236,10 @@ private static bool IsAsciiOnly(string/*!*/ str) { } private Exception/*!*/ MalformedFormat(char c) { + // a newline or NUL ends the directive in MRI's sprintf (case '\n', case '\0'): no character to name + if (c == '\n' || c == '\0') { + return RubyExceptions.CreateArgumentError("malformed format string"); + } return RubyExceptions.CreateArgumentError("malformed format string - %" + c); } @@ -265,7 +269,12 @@ private void DoFormatCode() { throw RubyExceptions.CreateArgumentError("malformed format string - %*[0-9]"); } if (flagSeen || argumentSeen) { - throw RubyExceptions.CreateArgumentError("malformed format string - %"); + // MRI's sprintf has fetched the argument of a "%1$" or "%" already (GETPOSARG, GETNAMEARG), so + // too few arguments or no hash is that error; then it is a plain "malformed format string". + if (argumentSeen) { + GetData(_opts.ArgIndex, _opts.Name); + } + throw RubyExceptions.CreateArgumentError("malformed format string"); } throw RubyExceptions.CreateArgumentError("incomplete format specifier; use %% (double %) instead"); } From 97917ad3a04a68de77f19c4b1703784e64dbeb5b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:41:42 +0000 Subject: [PATCH 114/439] Array#pack's float directives take only a Numeric, as rb_to_float does `[obj].pack("D")` of an object that has #to_f but is not a Numeric packed what to_f gave; CRuby's rb_to_float asks only a Numeric and raises "can't convert ToF into Float" for anything else (nil and true by value). Util/pack-matrix.rb: 4 lines (D, f, E, g) -> same. Checked: Pack_FloatOfNonNumeric1 (new; CRuby 4.0's output, a Numeric subclass with to_f too); spec/core/array/pack (1675 examples): as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 23 +++++++++++++++++++++++ Src/Libraries/Builtins/RubyEncoder.cs | 9 +++++++++ 3 files changed, 33 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 2c4ad5a23..a56ddfb01 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -994,6 +994,7 @@ public Tests(Driver/*!*/ driver) { Fiddle_AnsiSuffix1, PackPointer_RealAddress1, PackPointer_RelineWin32Api1, + Pack_FloatOfNonNumeric1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index b9a70aa7c..459d39643 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8883,6 +8883,29 @@ public void Sprintf_MalformedEnd1() { [""%\u0000"", ""malformed format string"", ""malformed format string"", ""malformed format string""] [""% \n"", ""malformed format string"", ""malformed format string"", ""malformed format string""] [""a%\nb"", ""malformed format string"", ""malformed format string"", ""malformed format string""] +"); + } + + /// + /// Array#pack's float directives take a Numeric only (MRI's rb_to_float): an object with #to_f that is not one is + /// "can't convert ToF into Float", nil and true by value. Util/pack-matrix.rb. + /// + public void Pack_FloatOfNonNumeric1() { + TestOutput(@" +require 'ruby4' +class ToF; def to_f = 1.5; end +class N < Numeric; def to_f = 2.5; end +[-> { [ToF.new].pack(""D"") }, -> { [N.new].pack(""g"") }, -> { [nil].pack(""D"") }, -> { [true].pack(""e"") }, -> { [""1""].pack(""D"") }, + -> { [2**70].pack(""D"") }, -> { [Rational(1, 2)].pack(""E"") }, -> { [:s].pack(""f"") }].each { |l| p((l.call rescue $!)) } +", @" +# +""@ \x00\x00"" +# +# +# +""\x00\x00\x00\x00\x00\x00PD"" +""\x00\x00\x00\x00\x00\x00\xE0?"" +# "); } } diff --git a/Src/Libraries/Builtins/RubyEncoder.cs b/Src/Libraries/Builtins/RubyEncoder.cs index 4197a6fa6..666169527 100644 --- a/Src/Libraries/Builtins/RubyEncoder.cs +++ b/Src/Libraries/Builtins/RubyEncoder.cs @@ -904,6 +904,15 @@ private static double ToPackFloat(ConversionStorage/*!*/ floatConversion if (value is MutableString) { throw RubyExceptions.CreateTypeError("can't convert String into Float"); } + // MRI's rb_to_float: only a Numeric is asked for to_f; anything else is "can't convert ToF into Float" (nil, true + // and false by value) + if (!(value is int || value is long || value is double || value is BigInteger)) { + var context = floatConversion.Context; + if (!context.GetClassOf(value).IsSubclassOf(context.GetClass(typeof(Numeric)))) { + string name = (value == null || value is bool) ? context.Inspect(value).ToString() : context.GetClassOf(value).GetNonSingletonClass().Name; + throw RubyExceptions.CreateTypeError("can't convert {0} into Float", name); + } + } double result = Protocols.CastToFloat(floatConversion, value); // the CLR's NaN has its sign bit set; MRI packs the positive quiet NaN return Double.IsNaN(result) ? BitConverter.Int64BitsToDouble(0x7FF8000000000000L) : result; From 10da68de1a5a6fc683e744b0c344f35fbf783cf6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:41:53 +0000 Subject: [PATCH 115/439] Ledger: perf/nbody, what NBody's 152 MB were and what is left Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/perf/LEDGER.md | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 90c5726ef..a35a137a6 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -671,6 +671,21 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has generic read of a raw object is a call (about 3 ns) because putting it into the inlined read cost every program 2-4% (see "Caught by the measurement (round sixteen)"). + Round thirty-eight looked at the 152 MB (see Landed, perf/nbody): 608 bytes per + `advance`, of which a method scope (160), two Procs (2 x 80) and two BlockParams + (2 x 48) were made on every call because a block literal with a literal nested in + it never reused its Proc, so `advance` never parked its scope. That is gone: 152 -> + 48 MB. The 192 bytes per `advance` left (with the harness's `times` block) are + Integer boxes (about 96), Float boxes (about 72) and the locals tuple of `advance` + (about 24; a parked scope gets a new one each call), by type only - which sites make + the boxes was not traced. Likely: the `times` index past the small-integer cache; + the copy's exits, which box Integer locals with a plain convert + (`JitLoopCompiler.Box`), not through the cache; and the `0.01` literal, boxed on + every call of the generic `times` block (the probe's driver showed one Double per + call). What the parking saves in bytes it pays in bookkeeping: + callgrind counts `advance` level and a light nested shape 0.8% dearer, so the + change is worth what the collector does not have to do, which the time on this + machine could not show. 3. **CD's red-black tree** (`put`, `tree_insert`, `find_node`, `Vector2D#compare_to`: 18.5% of self time now that `is_in_voxel` is compiled). `compare_to` is screen-rejected over its self call of `compare_numbers`, a three-line Float-only @@ -1450,6 +1465,47 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/nbody b3c20a5 55be4d2 (round thirty-eight, 2026-11-27) - a block literal with a literal + nested in it reuses its Proc when it can be outlined (gap 2)** - not gated. NBody allocated 152 MB + per iteration, 608 bytes per `advance`; an in-process GC allocation-tick listener (EventListener on + GCAllocationTick) gave RubyMethodScope 26%, Proc 26%, BlockParam 16%, Int32 16%, Double 12% of them. + `advance` is a light frame whose literal blocks could park its scope with their Procs + (RubyOps.CreateMethodScopeParked), but a literal with another literal nested in it never reused its + Proc (BlockDefinition: `!HasNestedBlock`), since the nested Proc holds its scope - although, once the + `each_index` block is outlined, the nested `Range#each` runs in place (perf/nest) and no nested Proc is + ever made. Now a block the block-loop screen accepts (BlockLoopInfo, read from the AST before the body + is compiled, `BlockScope.ReusesProcWithNested`) reuses its Proc all the same, and a literal nested in + it, on the generic calls that do make its Proc, clears the reuse of every Proc of the block scopes it + is made in (`RubyOps.KeepEnclosingProcs`, [Emitted]): a Proc a nested Proc may reach is never made + again, so never staged for parking (StageParkedProc), so the method's scope is not parked on that call. + Nothing else changes for such a block: its scope is still not reused, its BlockParams are handed on as + before (a first version marked the scope captured, which set KeptFlag and cost Richards' worker + Proc#call its BlockParam reuse: +9% bytes). Nested literals no longer count against their method's + parking. The calls before the loop is outlined make the nested Proc, and a slot gives up after 64 + failures; the first run of the copy gives the block's method's slot one more try + (`BlockLoopInfo.ParkSlot`). A first version let every block with a nested literal reuse its Proc: 2.1% + and 2.4% more instructions on a nested lambda and an `Array#each` in `Hash#each`, which make the nested + Proc on every call and gained nothing; hence the screen. Switch: IR_NESTED_PROCS=0. + Bytes (Util/perf/alloc.rb): NBody 152,025,847 -> 48,032,633 per iteration (0.316); the other thirteen + level (geomean of the fourteen 0.912). `Util/bench/nested-proc-shapes.rb` (new), bytes per call: + `advance` 593 -> 177, the five others unchanged. Instructions (Util/perf/callgrind/count.sh, switch off + -> on in one tree; a process lands in one of two modes some 400 instructions or 4% apart, so pairs are + compared mode with mode): `advance` 53,326 -> 53,354 or 51,427, `nest` (the same nesting over + Integers, light body) 41,977 -> 42,321 and 41,578 -> 41,920 (+0.8%: parking's bookkeeping costs a + little more than the allocations it saves), `always`, `lambda`, `worker`, `flat` level. Time could not + be resolved on this machine (thirteen experiments at once; ab.rb spreads 20-30%, a control at 0.75): + NBody 0.924, 0.990, 0.982, 1.007 of the base in four AWFY runs at 10 s, the fourteen 1.022 and 0.991 + in both column orders, no FAIL; NBody prints the same with -X:NoJIT -X:NoOSR. The census does not see + this (0 methods changed). + Matrices (Util/perf/gate-matrices.rb, base 2f8c31c): nested-proc (new: kept nested Procs of hot + parked methods, lambda, proc, Proc.new, binding, define_method and Thread nested, the outer literal made + twice in one call, break/next/return, recursion, an Enumerator, threads, and an outlined block whose + nested `Range#each` or `times` is redefined mid-run to keep its block), parked-scope, ivar, int, + block-loop, osr-array, jit, jit-calls, hot-shapes, block-scope-reuse, block-given, block-pass, + binding-lvar, eval, in the gate's six modes and IR_NESTED_PROCS=0: 22 baseline, 76 same, no DIFF. + `Util/ivar-stress.rb` OK three times. With KeepEnclosingProcs made a no-op the new matrix's rows go + wrong (NullReferenceException, a kept Proc reading another call's locals), so it does probe the rule. + - **perf/lglobal (round thirty-seven, 2026-11-26) - a global variable in a light frame (gap 9)** - census only, not gated. `IsScopeFree` had no case for a GlobalVariable, so `$stdout`, `$VERBOSE`, `$/`, `$!` or `$x = v` kept 258 methods out of light frames by themselves (Kernel#puts among them, From 742d004d601da0e08de20aca5a98e3d186e6e016 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:43:25 +0000 Subject: [PATCH 116/439] Run an interpreted DLR rule stuck before its compiled one compiled (gap 12) `recv != other' over four or eight plain classes took 2.2 to 3 times as long in some processes as in others on the same binary. The site is served by IronRuby's shared rule, which DynamicUtils.LightBind makes interpreted: past its count it compiles in the background and then fails its test, so that the site binds again and the binder hands out the compiled rule. Here the site got the compiled rule another way, and depending on when the background compile came back the interpreted one could stay ahead of it in the site's rules, never matching: on every call it ran in the interpreter to fail (5.25 million such failures in a slow process, 50-800 in a fast one; dotnet-trace put 53% of the slow loop under LightLambda.Run4 -> Interpreter.Run). Build/dlr-patches/0111: the interpreted rule keeps its LightLambda, and once it has failed for its compiled target 4,096 times more than the site has bound again and picked that up, it runs the compiled target itself and matches. A count of 32 switched the rules a 60-class site keeps meeting in the binder's cache too, and made it 18% slower; at 4,096 only a stuck rule switches. Checked: Util/bench/twospeed-shapes.rb in ten processes per build: four classes slow in 5 of 10 (`!=') and 3 of 10 (a call) on the base, eight classes in 7 of 10 each, none on the new build; one, two, three and sixty classes level. Callgrind: mono, two and four classes 1.000, a four-class call 1.019. shared-rule-light, jit, jit-calls and dmeth-jit matrices print CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls and IR_LIGHT_FRAMES=0; hot-shapes prints the base's. 240 named IronRuby.Tests pass. Not gated; a ../dlr checkout needs the patch applied by hand. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- .../0111-interpreted-rule-runs-compiled.patch | 80 +++++++++++++++++++ Build/dlr-patches/README.md | 1 + Util/bench/twospeed-shapes.rb | 67 ++++++++++++++++ Util/perf/LEDGER.md | 39 +++++++++ 4 files changed, 187 insertions(+) create mode 100644 Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch create mode 100644 Util/bench/twospeed-shapes.rb diff --git a/Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch b/Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch new file mode 100644 index 000000000..456015f43 --- /dev/null +++ b/Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch @@ -0,0 +1,80 @@ +diff --git a/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs b/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs +--- a/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs ++++ b/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs +@@ -151,6 +151,16 @@ + return CreateCustomDelegate(delegateType); + } + ++ /// ++ /// Runs , a compilation of the same lambda with the delegate type this LightLambda was made ++ /// for, from the next call on (DynamicUtils: an interpreted rule whose compiled rule the site never picked up). ++ /// ++ internal void UseCompiled(Delegate compiled) { ++ if (compiled is not null && _compiled is null) { ++ _compiled = compiled; ++ } ++ } ++ + private bool TryGetCompiled() { + // A nested lambda light-compiled when it first runs (LightCompiler.CompileOnFirstCall); one the light compiler + // cannot interpret is compiled. +diff --git a/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs b/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs +--- a/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs ++++ b/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs +@@ -113,6 +113,7 @@ + // we failed the rule because we have a compiled target available, return the compiled target + Debug.Assert(CachedBindingInfo.LastInterpretedFailure.CompiledTarget is not null); + var res = CachedBindingInfo.LastInterpretedFailure.CompiledTarget; ++ CachedBindingInfo.LastInterpretedFailure.Rebound++; + CachedBindingInfo.LastInterpretedFailure = null; + return res; + } +@@ -133,7 +134,10 @@ + private T/*!*/ CreateDelegate(DynamicMetaObjectBinder/*!*/ binder, DynamicMetaObject/*!*/ binding, CachedBindingInfo/*!*/ bindingInfo) { + var lambda = Compile(binding, bindingInfo); + try { +- return lambda.LightCompile(Int32.MaxValue); ++ T result = lambda.LightCompile(Int32.MaxValue); ++ // the interpreted rule, which can run its compiled body itself (CachedBindingInfo.CheckCompiled) ++ bindingInfo.Light = (result as Delegate)?.Target as Microsoft.Scripting.Interpreter.LightLambda; ++ return result; + } catch (NotImplementedException ex) { + // the interpreter doesn't support every expression, fall back to compiling the lambda + PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, $"LightBind fallback {binder.GetType().Name}: {ex.Message}"); +@@ -249,6 +253,23 @@ + [ThreadStatic] + public static CachedBindingInfo LastInterpretedFailure; + ++ // The LightLambda of the interpreted rule; null if it is not one. ++ public Microsoft.Scripting.Interpreter.LightLambda Light; ++ ++ // How often the rule has failed because its compiled target was ready, how often that failure had the site bind ++ // again and pick up the compiled rule (Bind, from LastInterpretedFailure), and how many failures that did not the ++ // rule may have before it runs its compiled target itself. A binder that binds the site some other way never picks ++ // it up, and a site whose rules come in a different order can hold both the interpreted rule and the compiled one: ++ // the interpreted one, never matching, stays before the other in the site's rules and runs in the interpreter, to ++ // fail, on every call (a `!=` site over four or eight classes, 2.2-3 times as slow), millions of times. A failure ++ // that rebinds is the scheme working and is not counted; nor is it there to count every time: a site with more classes ++ // than it keeps rules for finds the interpreted rule in the binder's cache again and again, and switching such a rule ++ // to its compiled target in place (32 failures) left the binder's cache with rules behind a LightLambda's Run: 60 ++ // classes 18% slower. Hence a count that only a rule stuck before its compiled one reaches. ++ private int _failuresForCompiled; ++ public int Rebound; ++ private const int MaxFailuresForCompiled = 4096; ++ + public CachedBindingInfo(DynamicMetaObjectBinder binder, int compilationThreshold) + : base(binder, compilationThreshold) { + } +@@ -269,6 +290,12 @@ + } + + if (CompiledTarget is not null) { ++ var light = Light; ++ if (light is not null && ++_failuresForCompiled - Rebound > MaxFailuresForCompiled) { ++ // run the compiled rule in place from the next call on, and match this one ++ light.UseCompiled(CompiledTarget as Delegate); ++ return true; ++ } + LastInterpretedFailure = this; + return false; + } diff --git a/Build/dlr-patches/README.md b/Build/dlr-patches/README.md index faf55db42..437b8283c 100644 --- a/Build/dlr-patches/README.md +++ b/Build/dlr-patches/README.md @@ -33,6 +33,7 @@ the apply step instead of with a confusing CS1061 deep inside IronRuby. | `0108-ThreadLocal-no-dead-thread-roots.patch` | `ThreadLocal`'s entries (the interpreter's current frame among them) held the Thread that owns them, and an entry stays in the array after its thread has finished, until the array next grows. Every Ruby thread that had run interpreted code was kept alive that way, and with it the CLR's native record of the dead thread and its `ManagedThreadId`: thousands of dead threads piled up in the runtime's thread list, which the finalizer thread walks to remove each one and every GC suspension walks too (`Thread.new { }.join` in a loop spent most of its process CPU in `ThreadStore::RemoveThread`). An entry now carries a per-thread token object instead (weakly mapped from the Thread for `TryGetValue`, patch 0001), so a finished thread is collected and its id reused; a new thread that gets the id replaces the stale entry on first use. | | `0109-interpret-deep-try-nesting.patch` | The CLR's JIT takes time cubic in how deeply a method's try regions nest under exception filters: for each block of a filter it goes through every region the filter's try encloses and walks that region's chain of enclosing regions up to the filter (`BasicBlock::VisitEHEnclosedHandlerSecondPassSuccs`, called by every flow-graph walk with exception edges; .NET 8 to 10, and .NET 11's is no better). IronRuby's begin/rescue is filters and finallys, four or more try expressions a level, so `begin ... rescue; end` nested 500 deep and compiled up front (`-X:CompilationThreshold 0`, as IronRuby.Tests run) spent over a minute in `DynamicMethod.CreateDelegate` (`DeepNesting1`: 75 s); interpreted it takes 1.5 s. The light compiler now records how deeply a lambda's try expressions nest - or those of a lambda nested in it, such as a block, which a compile of the outer one compiles too - and `LightDelegateCreator.Compile` leaves a lambda deeper than 64 (some 15 levels of begin/rescue) interpreted, which is linear. A lambda the light compiler cannot interpret is still compiled, and so is everything under `-X:NoAdaptiveCompilation`. `DeepNesting1` now takes 2.4 s; the 500-deep script alone, compiled up front, 0.4 s more than an empty one (1000 deep: 0.7 s). | | `0110-compile-nested-lambdas-on-first-call.patch` | The light compiler compiled every lambda nested in the one it compiled - a block, a closure - with it, whether or not it ever ran. `LightCompiler.CompileOnFirstCall` lets the language name the nested lambdas to compile when a delegate made from one first runs instead (IronRuby: lambda literals, `->`). The variables such a lambda closes over are found by a walk of its tree, so the enclosing lambda boxes them and hands them over in the same order as before; the nested lambda is compiled against exactly those (a variable the walk missed fails loudly as "unbound variable"). `LightDelegateCreator` holds the lambda until its first run (`EnsureLightCompiled`), its `LightLambda` gets the interpreter then (or, for a lambda the light compiler cannot interpret, the compiled delegate), and a compile of the enclosing lambda to IL light-compiles the ones still pending to learn how deeply their try expressions nest (0109). prism's `Serialize::Loader#define_load_node_lambdas` makes 152 lambdas and the first parse calls a few: its first call went from 160 to 105 ms. | +| `0111-interpreted-rule-runs-compiled.patch` | A rule `DynamicUtils.LightBind` makes runs interpreted until its count runs out, then compiles in the background and, once compiled, fails its test so that the site binds again and the binder hands out the compiled rule (`CachedBindingInfo.LastInterpretedFailure`). When the site gets the compiled rule some other way - IronRuby's shared rules, which serve every receiver class whose method resolves the same, are handed to a site as it binds - the interpreted one can stay ahead of it in the site's rules, never matching, and run in the interpreter to fail on every call: `recv != other` over four or eight classes took 2.2-3 times as long in some processes and not in others (gap 12, perf/twospeed). Such a rule now runs its compiled target itself (`LightLambda.UseCompiled`) once it has failed for it 4096 times without the site binding again (a stuck rule fails millions of times; the rules of a site with more classes than it keeps rules for fail far fewer, and switching those in place after 32 failures made 60 classes 18% slower), and matches again. | `Util/check-dlr-patches.sh DLR_DIR` checks that a DLR checkout has all of these applied: a local one is patched once and falls behind when a new patch lands here. diff --git a/Util/bench/twospeed-shapes.rb b/Util/bench/twospeed-shapes.rb new file mode 100644 index 000000000..f120d9f89 --- /dev/null +++ b/Util/bench/twospeed-shapes.rb @@ -0,0 +1,67 @@ +# Gap 12 of Util/perf/LEDGER.md: one `recv != other' site whose receivers are instances of k plain classes in +# turn (k = 1, 2, 3, 4, 8, 60), each k a site of its own, in a method's `while' loop; and the same with `==', +# and with a method of the classes' own (`recv.m'). ` ns ' per line, for Util/perf/ab.rb; +# `ruby twospeed-shapes.rb NAME...' runs only the shapes named; N is the calls a section makes (ab.rb -n); +# INSTR=1 (ab.rb -i, or Util/perf/callgrind/count.sh) adds instructions. Run it in many processes: the point is +# whether a process lands in one speed or another. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def cpu + Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID) +rescue SystemCallError, NameError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end +def t(name, n = 1_000_000) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + n = ENV['N'].to_i if ENV['N'] + best = 1e9; r = nil; fewest = nil; counted = !!INSTR + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + r = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + fewest = c1 - c0 if fewest.nil? || c1 - c0 < fewest + else + counted = false + end + end + printf "%-14s %8.1f ns %s%s\n", name, best * 1e9 / n, r, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +CLASSES = (1..60).map { |i| Class.new { define_method(:m) { i } } } +OTHER = Object.new +# a method per shape, so that each has a site of its own +[1, 2, 3, 4, 8, 60].each do |k| + objs = CLASSES.first(k).map(&:new) + Object.class_eval <<~RUBY + def neq#{k}(objs, n) + i = 0; c = 0 + while i < n + c += 1 if objs[i % #{k}] != OTHER + i += 1 + end + c + end + def eq#{k}(objs, n) + i = 0; c = 0 + while i < n + c += 1 if objs[i % #{k}] == OTHER + i += 1 + end + c + end + def call#{k}(objs, n) + i = 0; c = 0 + while i < n + c += objs[i % #{k}].m + i += 1 + end + c + end + RUBY + t("neq#{k}") { |n| send(:"neq#{k}", objs, n) } + t("eq#{k}") { |n| send(:"eq#{k}", objs, n) } + t("call#{k}") { |n| send(:"call#{k}", objs, n) } +end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e4577b91c..ada8a7af2 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -912,6 +912,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the next idea. A light caller's call of a JIT-typed method with a Float argument (`selfcall` of micro-table) is 3% slower by median through the dispatcher than through the rule, with the same bytes. + Round of 2026-11-27 (see Landed, perf/twospeed, not gated): found and fixed - an interpreted shared rule + left ahead of its compiled one in a site's rules, run on every call to fail (DLR patch 0111). `neq2` + still varies 59-102 ns on both builds, which is something else. 13. **Calling an iterator at all costs twice what it does in CRuby**: `a.each { |x| s += x }` over one element from a method is 166 ns against 79, `n.times` 182 against 88, `a.map` 194 against 101, and `a.any? { |x| x > 1000 }` 414 against 67, 438 against @@ -1623,6 +1626,42 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/twospeed (2026-11-27) - an interpreted rule stuck before its compiled one runs compiled + (gap 12, DLR patch 0111)** - not gated. What decides the speed: `recv != other` over four or eight plain + classes is served by IronRuby's shared rule (one rule whose test is a set of class versions, handed to + every site that calls the method on another class, RubyCallAction). `DynamicUtils.LightBind` makes it + interpreted; past its count it compiles in the background and then fails its test once compiled, so that + the site binds again and the binder hands out the compiled one (`LastInterpretedFailure`). The site got + the compiled rule another way (the shared rule replaced under it), and in some processes the interpreted + one stayed ahead of it in the site's rules: on every call of three of the four classes it ran in the + interpreter to fail, and the compiled rule behind it matched. Which order a process lands in depends on + when the background compile comes back, so on timing: `IR_BIND_TRACE=1` and `IR_PHASE_TIMES=1` made + every run fast (0 of 32 slow). Found with `dotnet-trace` (sampled, `--show-child-io`): the slow + process spent 53% of the loop in `UpdateAndExecute3 -> LightLambda.Run4 -> Interpreter.Run`, the fast one + 0.3%; and with counters in a copy of the DLR: 5.25 million failures of a compiled-ready rule in the slow + processes, 50-800 in the fast ones, the same number of rebinds in both. + - The change (Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch): the interpreted rule keeps + its `LightLambda`, and once it has failed for its compiled target 4,096 times more than the site has + bound again and picked that up, it runs the compiled target itself (`LightLambda.UseCompiled`) and + matches. 32 was tried first and made a 60-class site 18% slower: its rules, found in the binder's cache + again and again, switched too, and the cache then held rules behind a `LightLambda` Run; at 4,096 only a + stuck rule switches. + - Ten processes each (`Util/bench/twospeed-shapes.rb`, ns, base / new): `neq4` slow + (221-237) in 5 of 10 on base, 0 of 10 new (78-85); `call4` 3 of 10 / 0 (85-100); `neq8` 7 of 10 + (187-403) / 0 (102-122); `call8` 7 of 10 (178-264) / 0 (109-124). Level: 1, 2 and 3 classes, `==` at + every count, `neq60` (median 668 / 661) and `call60` (704 / 704). `neq2` varies 59-102 on both builds: + another effect, left. + - Instructions (`Util/perf/callgrind/count.sh`, N=20000): `neq1`, `call1`, `neq2`, `neq4` 1.000; `call4` + 1.019 (+53); `neq8` 0.725, `call8` 0.856, `neq60` 0.666, `call60` 0.328 (in so few calls the rules a + megamorphic site keeps meeting are still the interpreted ones). + - Matrices, CRuby against base against new, with the JIT on, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and + `IR_LIGHT_FRAMES=0`: shared-rule-light, jit, jit-calls and dmeth-jit identical to CRuby; hot-shapes + identical to base (its one row that differs from CRuby differs on base). IronRuby.Tests: 240 named + (rules and sites, Method*, Super*, Alias*, Proc*, Block*, define_method, instance_method, the JIT) pass. + - For the gate: the patch is the DLR's, so a checkout of `../dlr` needs it applied by hand (`git -C + ../dlr apply Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch`); every interpreted rule in + every program is affected. AWFY was not timed; Bounce was once seen bimodal (gap 12's note). + - **perf/jitprobe (2026-11-26) - the stub's generic cost is not the interpreter's** - not gated. A probe (`JitStub.Probe`) times the generic body to decide whether an entry that deopts pays its way. It waited for the generic body's compile for at most 8 deopt windows, which go by in microseconds when every From 15285eb6ade8b417e876e61c3a9df43f9c0650c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:45:03 +0000 Subject: [PATCH 117/439] fiber-reclaim-matrix: take a built-in enumerator that still runs on a fiber The native-enumerator check reaches into the enumerator's fiber, and it used Enumerable#each_with_index over a Hash because that still suspended a built-in method on a fiber. perf/extiter3 gave it a cursor, so @__fiber__ was nil and the matrix died at `fiber.__state__` on the candidate in every mode (the gate's round 4 reported it as a DIFF). Array#combination is C# and has no cursor. The matrix passes on master, on the branch and under CRuby. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/fiber-reclaim-matrix.rb | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Util/fiber-reclaim-matrix.rb b/Util/fiber-reclaim-matrix.rb index 8484a51fa..078ea03c2 100644 --- a/Util/fiber-reclaim-matrix.rb +++ b/Util/fiber-reclaim-matrix.rb @@ -75,15 +75,16 @@ def self.discard_enumerator(events) [WeakRef.new(enum), WeakRef.new(fiber), fiber.__state__.__core__] end - # Not Hash#each: Enumerator#next walks that one with a cursor and no fiber (Enumerator.cs); - # Enumerable#each_with_index over a Hash still suspends a built-in method on a fiber. + # A built-in method suspended on a fiber. Not Hash#each, nor Enumerable#each_with_index over a Hash + # (perf/extiter3), nor the other kinds Enumerator#next now walks with a cursor and no fiber + # (Enumerator.cs, TryCreateCursor): Array#combination is C# and has no cursor. def self.build_native_enumerator - { :a => 1, :b => 2 }.each_with_index + [1, 2, 3].combination(2) end def self.discard_native_enumerator enum = build_native_enumerator - assert(enum.next == [[:a, 1], 0], 'native enumerator did not park') + assert(enum.next == [1, 2], 'native enumerator did not park') fiber = enum.__send__(:__ir_hidden_ivar__, :@__fiber__) [WeakRef.new(enum), WeakRef.new(fiber), fiber.__state__.__core__] end From a06254ae0129903599efd2862f781623363b220c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:46:54 +0000 Subject: [PATCH 118/439] Load a compiled body's constants without a cast (IR_SEALED_CONSTANTS) LambdaExpression.Compile keeps a tree's object constants in its closure's object[] and loads one with a bounds check and a castclass, which in Ruby's compiled bodies the JIT makes a call of the runtime's cast helper (~17 instructions) - every dynamic call site of a body is such a constant. Counted with callgrind, the helper is 9.2% of a light method calling one method, 11.7% of tap's and 6.9% of inject's instructions. A new DLR patch (0111) adds LightCompilation.Rewriter, which the DLR calls with an interpreted lambda's tree just before compiling it to IL. IronRuby's CompiledConstantsRewriter reduces the extension nodes, turns each dynamic expression into the call the compiler would emit for it, and loads every constant of a class as an object, which needs no cast, through Unsafe.As, which is no code. The interpreter keeps its tree. Counted (switch off -> on): frame-cost 0.983-0.992, core-small 0.979-0.991, regex-shapes 0.980-0.996, nothing more; start-up no worse. 18 matrices in six modes print the baseline's output, and on the R2R host with its startup library what the Release build prints but for two lines that are the R2R host's own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Build/dlr-patches/0111-compile-rewriter.patch | 33 ++++++ Build/dlr-patches/README.md | 1 + Src/Ruby/Runtime/CompiledConstants.cs | 101 ++++++++++++++++++ Src/Ruby/Runtime/RubyContext.cs | 3 + Src/Ruby/Runtime/RubyScriptCode.cs | 3 +- 5 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 Build/dlr-patches/0111-compile-rewriter.patch create mode 100644 Src/Ruby/Runtime/CompiledConstants.cs diff --git a/Build/dlr-patches/0111-compile-rewriter.patch b/Build/dlr-patches/0111-compile-rewriter.patch new file mode 100644 index 000000000..b7b877ea7 --- /dev/null +++ b/Build/dlr-patches/0111-compile-rewriter.patch @@ -0,0 +1,33 @@ +diff --git a/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs b/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs +--- a/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs ++++ b/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs +@@ -13,6 +13,16 @@ + using Microsoft.Scripting.Utils; + + namespace Microsoft.Scripting.Interpreter { ++ /// ++ /// A hook for the language: , if set, is given each interpreted lambda's tree just before it is ++ /// compiled to IL, and what it returns is compiled instead. It must return a lambda of the same type and parameters that ++ /// computes the same thing - for instance one whose constants are typed so that loading them is cheaper. The interpreter ++ /// keeps running the tree it was given. Process-wide: set it once, to something that holds no state of one runtime. ++ /// ++ public static class LightCompilation { ++ public static Func Rewriter { get; set; } ++ } ++ + + /// + /// Manages creation of interpreted delegates. These delegates will get +@@ -256,6 +266,12 @@ + lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters); + } + ++ // the language's last word on the tree before it is compiled to IL (LightCompilation.Rewriter) ++ var rewriter = LightCompilation.Rewriter; ++ if (rewriter is not null) { ++ lambda = rewriter(lambda); ++ } ++ + if (HasClosure) { + _compiled = LightLambdaClosureVisitor.BindLambda(lambda, Interpreter?.ClosureVariables ?? _closureVariables); + } else { diff --git a/Build/dlr-patches/README.md b/Build/dlr-patches/README.md index faf55db42..624eeb10c 100644 --- a/Build/dlr-patches/README.md +++ b/Build/dlr-patches/README.md @@ -33,6 +33,7 @@ the apply step instead of with a confusing CS1061 deep inside IronRuby. | `0108-ThreadLocal-no-dead-thread-roots.patch` | `ThreadLocal`'s entries (the interpreter's current frame among them) held the Thread that owns them, and an entry stays in the array after its thread has finished, until the array next grows. Every Ruby thread that had run interpreted code was kept alive that way, and with it the CLR's native record of the dead thread and its `ManagedThreadId`: thousands of dead threads piled up in the runtime's thread list, which the finalizer thread walks to remove each one and every GC suspension walks too (`Thread.new { }.join` in a loop spent most of its process CPU in `ThreadStore::RemoveThread`). An entry now carries a per-thread token object instead (weakly mapped from the Thread for `TryGetValue`, patch 0001), so a finished thread is collected and its id reused; a new thread that gets the id replaces the stale entry on first use. | | `0109-interpret-deep-try-nesting.patch` | The CLR's JIT takes time cubic in how deeply a method's try regions nest under exception filters: for each block of a filter it goes through every region the filter's try encloses and walks that region's chain of enclosing regions up to the filter (`BasicBlock::VisitEHEnclosedHandlerSecondPassSuccs`, called by every flow-graph walk with exception edges; .NET 8 to 10, and .NET 11's is no better). IronRuby's begin/rescue is filters and finallys, four or more try expressions a level, so `begin ... rescue; end` nested 500 deep and compiled up front (`-X:CompilationThreshold 0`, as IronRuby.Tests run) spent over a minute in `DynamicMethod.CreateDelegate` (`DeepNesting1`: 75 s); interpreted it takes 1.5 s. The light compiler now records how deeply a lambda's try expressions nest - or those of a lambda nested in it, such as a block, which a compile of the outer one compiles too - and `LightDelegateCreator.Compile` leaves a lambda deeper than 64 (some 15 levels of begin/rescue) interpreted, which is linear. A lambda the light compiler cannot interpret is still compiled, and so is everything under `-X:NoAdaptiveCompilation`. `DeepNesting1` now takes 2.4 s; the 500-deep script alone, compiled up front, 0.4 s more than an empty one (1000 deep: 0.7 s). | | `0110-compile-nested-lambdas-on-first-call.patch` | The light compiler compiled every lambda nested in the one it compiled - a block, a closure - with it, whether or not it ever ran. `LightCompiler.CompileOnFirstCall` lets the language name the nested lambdas to compile when a delegate made from one first runs instead (IronRuby: lambda literals, `->`). The variables such a lambda closes over are found by a walk of its tree, so the enclosing lambda boxes them and hands them over in the same order as before; the nested lambda is compiled against exactly those (a variable the walk missed fails loudly as "unbound variable"). `LightDelegateCreator` holds the lambda until its first run (`EnsureLightCompiled`), its `LightLambda` gets the interpreter then (or, for a lambda the light compiler cannot interpret, the compiled delegate), and a compile of the enclosing lambda to IL light-compiles the ones still pending to learn how deeply their try expressions nest (0109). prism's `Serialize::Loader#define_load_node_lambdas` makes 152 lambdas and the first parse calls a few: its first call went from 160 to 105 ms. | +| `0111-compile-rewriter.patch` | `Microsoft.Scripting.Interpreter.LightCompilation.Rewriter`: a hook the language sets to rewrite an interpreted lambda's tree just before `LightDelegateCreator` compiles it to IL (the interpreter keeps the tree it had). IronRuby's `CompiledConstantsRewriter` uses it so that a compiled body loads its constants - its call sites among them - as objects given their class by `Unsafe.As`: `LambdaExpression.Compile` casts each closure constant to its type on every load, and in Ruby's bodies each such cast is a call of the runtime's cast helper, 7-12% of a small Ruby method's instructions. Unset, nothing changes. | `Util/check-dlr-patches.sh DLR_DIR` checks that a DLR checkout has all of these applied: a local one is patched once and falls behind when a new patch lands here. diff --git a/Src/Ruby/Runtime/CompiledConstants.cs b/Src/Ruby/Runtime/CompiledConstants.cs new file mode 100644 index 000000000..b00377d6c --- /dev/null +++ b/Src/Ruby/Runtime/CompiledConstants.cs @@ -0,0 +1,101 @@ +/* **************************************************************************** + * + * Constants a compiled Ruby body loads without a cast (IR_SEALED_CONSTANTS). + * + * LambdaExpression.Compile keeps a tree's object constants in its closure's object[] and + * loads one with a bounds check and a castclass to the constant's type. In Ruby's compiled + * bodies the .NET JIT makes each of those a call of the runtime's cast helper (about 17 + * instructions), sealed class or not - it expands such a cast inline in a small lambda, and + * why not here was not found (perf/lconst). Every dynamic call site of a body is such a + * constant, loaded each time the call is made: 7 casts a call of a light method that calls one + * method, 19-24 for `inject' and `tap''s callers - 7-12% of their instructions (callgrind, + * Util/perf/LEDGER.md: perf/lconst). + * + * So, just before an interpreted lambda is compiled to IL (the DLR's LightCompilation.Rewriter, + * Build/dlr-patches/0111), its tree is rewritten so that a constant of a class is loaded as an + * object, which needs no cast, and given its class with Unsafe.As, which costs nothing: sound, + * since a ConstantExpression's value is of its type, and this rewriter makes the call sites' + * constants itself. A dynamic expression becomes the call LambdaCompiler would emit for it - its + * site, then the site's Target with the site and the arguments - with its site such a constant. + * The extension nodes are reduced on the way, as the compiler would reduce them. The interpreter + * goes on running the tree as it was. + * + * ***************************************************************************/ + +using System; +using System.Collections.ObjectModel; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace IronRuby.Runtime { + // a DynamicExpressionVisitor: DynamicExpression.Accept calls VisitDynamic only for one; for any other visitor it is an + // extension node, and reducing it gives the site constant twice (`Constant(site).Target(Constant(site), ...)'), two casts + internal sealed class CompiledConstantsRewriter : DynamicExpressionVisitor { + internal static readonly bool Enabled = Environment.GetEnvironmentVariable("IR_SEALED_CONSTANTS") != "0"; + + /// Installs the rewriter for the whole process (it holds no state of any runtime): once is enough. + internal static void Install() { + if (Enabled && Microsoft.Scripting.Interpreter.LightCompilation.Rewriter == null) { + Microsoft.Scripting.Interpreter.LightCompilation.Rewriter = Rewrite; + } + } + + internal static LambdaExpression/*!*/ Rewrite(LambdaExpression/*!*/ lambda) { + return Enabled ? (LambdaExpression)new CompiledConstantsRewriter().Visit(lambda) : lambda; + } + + protected override Expression/*!*/ VisitExtension(Expression/*!*/ node) { + // the compiler would reduce it; reduced here, its sites and constants are seen + return node.CanReduce ? Visit(node.ReduceAndCheck()) : base.VisitExtension(node); + } + + protected override Expression/*!*/ VisitDynamic(DynamicExpression/*!*/ node) { + ReadOnlyCollection arguments = Visit(node.Arguments); + Type delegateType = node.DelegateType; + MethodInfo invoke = delegateType.GetMethod("Invoke"); + ParameterInfo[] parameters = invoke.GetParameters(); + if (parameters.Length != arguments.Count + 1 || invoke.ReturnType != node.Type || !delegateType.IsVisible) { + return node.Update(arguments); + } + foreach (var parameter in parameters) { + if (parameter.ParameterType.IsByRef) { + return node.Update(arguments); + } + } + + // what LambdaCompiler.EmitDynamicExpression does: the site, its Target, then the arguments + var site = CallSite.Create(delegateType, node.Binder); + var siteVariable = Expression.Variable(site.GetType(), "#site"); + var callArguments = new Expression[arguments.Count + 1]; + callArguments[0] = siteVariable; + for (int i = 0; i < arguments.Count; i++) { + callArguments[i + 1] = arguments[i]; + } + return Expression.Block(node.Type, new[] { siteVariable }, + Expression.Assign(siteVariable, Uncast(site, site.GetType())), + Expression.Invoke(Expression.Field(siteVariable, "Target"), callArguments) + ); + } + + protected override Expression/*!*/ VisitConstant(ConstantExpression/*!*/ node) { + object value = node.Value; + Type type = node.Type; + // what the compiler emits without a constant of the closure (ILGen.CanEmitConstant), a value type, an object + if (value == null || type.IsValueType || type == typeof(object) || type == typeof(string) || + typeof(Type).IsAssignableFrom(type) || typeof(MethodBase).IsAssignableFrom(type) || type.IsByRef || type.IsPointer) { + return node; + } + return Uncast(value, type); + } + + private static readonly MethodInfo/*!*/ _UnsafeAs = Array.Find(typeof(Unsafe).GetMethods(), + m => m.Name == nameof(Unsafe.As) && m.IsGenericMethodDefinition && m.GetGenericArguments().Length == 1 && m.GetParameters().Length == 1 && + m.GetParameters()[0].ParameterType == typeof(object)); + + // `Unsafe.As(value as an object)': no castclass, and the JIT's intrinsic is no code + private static Expression/*!*/ Uncast(object/*!*/ value, Type/*!*/ type) { + return Expression.Call(_UnsafeAs.MakeGenericMethod(type), Expression.Constant(value, typeof(object))); + } + } +} diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index f3dd60b58..7f5ab41e3 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -770,6 +770,9 @@ public RubyContext(ScriptDomainManager/*!*/ manager, IDictionary _runtimeId = Interlocked.Increment(ref _RuntimeIdGenerator); + // Compiled bodies load their call sites and sealed constants without a cast helper (CompiledConstantsRewriter). + CompiledConstantsRewriter.Install(); + // A lambda literal is light-compiled when it is first called, not with the method or file it is written in // (CompiledFrameExpression.IsCompiledOnFirstCall). Microsoft.Scripting.Interpreter.LightCompiler.CompileOnFirstCall = LazyLambdasAll ? (lambda => true) : diff --git a/Src/Ruby/Runtime/RubyScriptCode.cs b/Src/Ruby/Runtime/RubyScriptCode.cs index 4322423ba..e2f126450 100644 --- a/Src/Ruby/Runtime/RubyScriptCode.cs +++ b/Src/Ruby/Runtime/RubyScriptCode.cs @@ -119,7 +119,8 @@ private object Run(Scope/*!*/ scope, bool bindGlobals) { long traceStart = StartupTrace.Now(); try { if (noAdaptiveCompilation) { - return lambda.Compile(); + // as the light compiler's compilation would (CompiledConstantsRewriter) + return CompiledConstantsRewriter.Rewrite(lambda).Compile(); } return lambda.LightCompile(compilationThreshold); From e1e45683b3ffcf14b154d2052f484487dd4ef1bd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:46:54 +0000 Subject: [PATCH 119/439] perf/lconst: ledger entry How the cast helper's share was counted, why a sealed holder did not remove it (the JIT expands no cast in Ruby's bodies, for a reason not found, and a plain ExpressionVisitor reduces a DynamicExpression into two site loads), what landed, the numbers and the checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/perf/LEDGER.md | 65 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 0cee88a4c..0e6d6e33a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1488,6 +1488,71 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lconst (/perf-frame, 2026-11-27) - a compiled body's constants without a cast helper** + (switch `IR_SEALED_CONSTANTS`, on unless `=0`; a DLR patch, `0111-compile-rewriter`) - + instructions only, not gated. Built on 79a2c30 with claude/perf-lsite merged (980e36c). + - **Counted first** (callgrind with `DOTNET_ReadyToRun=0`, so that CoreLib's cast helpers have + names, and a caller walk of the perf map): `CastHelpers.ChkCastClass` and + `ChkCastClassSpecial` are 9.2% of `fc`'s instructions (frame-cost, `-X:NoJIT`), 11.7% of + `tap`'s and 6.9% of `inject`'s (core-small). By caller: the Ruby bodies (`F#fc` 7 casts a + call, `tap`'s caller `H#m56` 24, `H#m3` 19, `Enumerable#inject` 8), the shape file's + compiled loop (~10, every shape alike), and the rules (`CallSite.Target`, 1-6). A cast + is ~17 instructions. In a body: `LambdaExpression.Compile` keeps object constants in its + closure's object[] and loads one with a bounds check and a `castclass`; every dynamic + call site is one (`CallSite`, not sealed: `DOTNET_JitDisasm` of `F#fc3` shows 14 + helper calls). + - **Why not a sealed holder.** First cut: each site in a sealed `SiteHolder`, and every + constant typed as its own class where that is sealed. It counted more (up to 1.028): an + `ExpressionVisitor` sees a `DynamicExpression` as an extension node (`Accept` calls + `VisitDynamic` only for a `DynamicExpressionVisitor`), and reducing it gives + `Constant(site).Target(Constant(site), ...)`, two casts where the compiler emits one. + Fixed, the holder's cast was still the helper: in Ruby's bodies the JIT calls + `CORINFO_HELP_CHKCASTCLASS` even for a sealed class, where a probe lambda of the same + runtime (in its own process and inside `ir`; with a try/finally, a fault, a catch and + rethrow, 600 locals, 32 casts, `PrecompiledFrames.Current`) gets the one-compare inline + check. What makes the difference was not found. + - **What landed.** Just before an interpreted lambda is compiled to IL - the DLR's + `LightDelegateCreator`, through a hook the patch adds (`LightCompilation.Rewriter`), and + `-X:NoAdaptiveCompilation`'s compile - `CompiledConstantsRewriter` (a + `DynamicExpressionVisitor`) reduces the extension nodes, turns each dynamic expression into + the call the compiler would emit (the site, its Target, then the arguments), and loads + every constant of a class (not a string, a Type or a MethodBase, which the compiler emits + inline) as an object, which needs no cast, through `Unsafe.As`, which is no code. Sound: + a ConstantExpression's value is of its type, and the rewriter makes the sites itself. + The interpreter keeps the tree it had; the method JIT's typed bodies and the rules are + compiled elsewhere and keep their casts. `F#fc3`: 14 helper calls -> 5, 622 -> 603 lines. + - **Numbers** (instructions a call, `Util/perf/callgrind/count.sh`, N=20,000, switch off -> + on). frame-cost `-X:NoJIT`: `f0` 0.984, `f1` 0.988, `fc` 0.989, `fc3` 0.991, `fy` 0.992, + `fbg` 0.983, `bytesplice` 0.984; default mode: `f0`/`f1` 1.000 (the method JIT's), the rest + 0.983-0.992. core-small: `each` 0.979, `max_by` 0.979, `inject` 0.982, `sum_blk` 0.985, + `then` 0.985, `each_with_index` 0.987, `zip` 0.988, `minmax` 0.990, `inject_sym` 0.991, + `tap` 0.991. regex-shapes: 0.980-0.996, `size` 1.000. Two rows first read high and were + the process's history (counts move with the shapes run before in the same process): + `tap` 1.011 in a list of ten, 0.991 alone (two processes each, to the 0.1); `eqt` 0.781 + after `kase`, 0.987 alone. Some callgrind processes of both arms stopped part way under + valgrind (the .NET process dies there now and then; the same shapes complete natively and + in a rerun): their rows were measured again. Start-up (wall clock, six alternating runs, + while a publish ran): `ir -e 1` 1,609-1,779 ms on, 1,678-1,814 off; `-S gem list` + 3,244-3,443 on, 3,271-3,501 off - no worse. + - Checked: 18 matrices (light-entry, light-rest, block-given, global-light, lexical-light, + keyword-light, regex-light, rescue-light, super-light, parked-scope, light-remember, caller, + raise, jit, jit-calls, jit-scan, jit-strlit, hot-shapes) in seven modes (as built, + `IR_SEALED_CONSTANTS=0`, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, + `-X:NoAdaptiveCompilation`, and the R2R host with its precompiled startup library, rebuilt + from this tree): 108 of the six Release modes print what the baseline prints, and CRuby's + but where the baseline differs too (light-entry's `define_method` alias, caller's library + frames, raise, hot-shapes' FrozenError). The R2R host: what the Release candidate prints, + but regex-light's `raise label` (`Integer()` from a light frame is labelled "block in +
": the same with the switch off and with `IR_STARTUP_DLL=none`, the R2R host's own) + and one line of caller-matrix whose iteration counts move from run to run in both arms (when + the background compilation lands). `IR_CONFIG=R2R ./ir.sh -e ...` and `-S gem list` + run with the startup library, switch on and off. IronRuby.Tests (which compile up front): + 71 named (Method_LightFrame*, Backtrace_*, Scenario_RubyBlocks/Eval/Exceptions/Closures/ + MethodMissing/MethodAliases*, JitCore*, Dynamic*): PASSED. `Util/check-dlr-patches.sh` + passes on a `../dlr` with the patch applied. Not run: the suite, a sweep, AWFY, timing. + - Left: the method JIT's typed bodies and the rules (`CallSite.Target`, compiled by the + DLR's binder) could use the same rewrite; why the JIT expands no cast in these bodies. + - **perf/lframe (/perf-frame, 2026-11-26) - a cheaper method entry: the alias name and the traced test** (switch `IR_LIGHT_ENTRY`, on unless `=0`) - instructions only, not gated. Built on 2f8c31c. What gap 16's profiles left on every light frame, looked at on its own From 75091cc3a601dfcb4477869e22a987cb2d395f31 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:46:56 +0000 Subject: [PATCH 120/439] String#unpack: an "@" that ends the format counts 1 `"".unpack("@")` answered []; CRuby raises "@ outside of string". A directive with no count at the very end of the format gets a count of 1 in MRI's unpack (p >= pend: len = 1), "@" too, while a bare "@" anywhere else seeks to 0 - "".unpack("@C") is [nil] and "abc".unpack("C@C") [97, 97] in both. Util/unpack-matrix.rb: 1 line -> same. Checked: Unpack_AtEnd1 (new; CRuby 4.0's output); spec/core/string/unpack: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 36 +++++++++++++++++++++++++ Src/Libraries/Builtins/RubyEncoder.cs | 7 +++-- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a56ddfb01..cc369a3fd 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -995,6 +995,7 @@ public Tests(Driver/*!*/ driver) { PackPointer_RealAddress1, PackPointer_RelineWin32Api1, Pack_FloatOfNonNumeric1, + Unpack_AtEnd1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 459d39643..a14fc7c3c 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8906,6 +8906,42 @@ class N < Numeric; def to_f = 2.5; end ""\x00\x00\x00\x00\x00\x00PD"" ""\x00\x00\x00\x00\x00\x00\xE0?"" # +"); + } + + /// + /// String#unpack's "@" with no count seeks to 0, but at the end of the format it counts 1, as every directive does there + /// (MRI's p >= pend: len = 1): "".unpack("@") is "@ outside of string", "".unpack("@C") [nil]. Util/unpack-matrix.rb. + /// + public void Unpack_AtEnd1() { + TestOutput(@" +require 'ruby4' +["""", ""a"", ""ab""].each { |s| [""@"", ""C@"", ""@C"", ""x@"", ""@0"", ""C@0"", ""@*"", ""C@*""].each { |f| puts ""#{s.inspect} #{f} #{(s.unpack(f) rescue $!.message).inspect}"" } } +", @" +"""" @ ""@ outside of string"" +"""" C@ ""@ outside of string"" +"""" @C [nil] +"""" x@ ""x outside of string"" +"""" @0 [] +"""" C@0 [nil] +"""" @* [] +"""" C@* [nil] +""a"" @ [] +""a"" C@ [97] +""a"" @C [97] +""a"" x@ [] +""a"" @0 [] +""a"" C@0 [97] +""a"" @* [] +""a"" C@* [97] +""ab"" @ [] +""ab"" C@ [97] +""ab"" @C [97] +""ab"" x@ [] +""ab"" @0 [] +""ab"" C@0 [97] +""ab"" @* [] +""ab"" C@* [97] "); } } diff --git a/Src/Libraries/Builtins/RubyEncoder.cs b/Src/Libraries/Builtins/RubyEncoder.cs index 666169527..cb5c138ab 100644 --- a/Src/Libraries/Builtins/RubyEncoder.cs +++ b/Src/Libraries/Builtins/RubyEncoder.cs @@ -1227,11 +1227,14 @@ private static bool IsKnownDirective(char c) { } else if (c2 == '*') { count = null; } else { + bool last = i >= format.Length; i--; - if (c == '@' && !packing) { + if (c == '@' && !packing && !last) { // "@" with no count is the one place the two directions part company: // pack seeks to 1, like every other directive's default count, while - // unpack seeks to the start. + // unpack seeks to the start - unless the "@" ends the format, where MRI's + // unpack takes the count as 1 too (p >= pend: len = 1), so "".unpack("@") + // is "@ outside of string" while "".unpack("@C") is [nil]. count = 0; } } From 4fc1809a810cf552dff2b2f442d2562f5d9590ad Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:46:56 +0000 Subject: [PATCH 121/439] String#undump passes \s and \0 through `'"\s"'.undump` answered " " and `'"\0"'.undump` a NUL; CRuby's str_undump knows only the escapes #dump writes (\n \t \r \f \v \b \a \e, \\ \" \#, \x, \u) and passes any other through as it is: "\\s", "\\0". Util/string-methods-matrix.rb: 2 lines -> same. Checked: String_UndumpUnknownEscapes1 (new; CRuby 4.0's output, with a dump round trip of a NUL and an escape); spec/core/string undump and dump: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 24 ++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 3 +-- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index cc369a3fd..33f362a06 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -996,6 +996,7 @@ public Tests(Driver/*!*/ driver) { PackPointer_RelineWin32Api1, Pack_FloatOfNonNumeric1, Unpack_AtEnd1, + String_UndumpUnknownEscapes1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index a14fc7c3c..77a069afa 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8942,6 +8942,30 @@ public void Unpack_AtEnd1() { ""ab"" C@0 [97] ""ab"" @* [] ""ab"" C@* [97] +"); + } + + /// + /// String#undump passes \s and \0 through as they are, as MRI's str_undump does with every escape #dump does not write. + /// Util/string-methods-matrix.rb. + /// + public void String_UndumpUnknownEscapes1() { + TestOutput(@" +require 'ruby4' +['""\\s""', '""\\0""', '""\\e""', '""\\a\\b\\t\\n\\v\\f\\r""', '""\\q""', '""\\1""', '""\\x41""', '""\\u0041""', '""\\#""', '""\\""""'].each { |s| p((s.undump rescue $!)) } +p ""a\0b\e あ"".dump.undump == ""a\0b\e あ"" +", @" +""\\s"" +""\\0"" +""\e"" +""\a\b\t\n\v\f\r"" +""\\q"" +""\\1"" +""A"" +""A"" +""#"" +""\"""" +true "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index f730aa0b1..1f9bac817 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3997,11 +3997,10 @@ def undump when "b" then out << "\b" when "a" then out << "\a" when "e" then out << "\e" - when "s" then out << " " when "\\" then out << "\\" when '"' then out << '"' when "#" then out << "#" - when "0" then out << "\0" + # (not \s nor \0: #dump writes neither, and MRI's undump passes them through as they are) when "x" hex = body[(i + 1), 2] ::Kernel.raise(::RuntimeError, "invalid hex escape") unless hex =~ /\A[0-9a-fA-F]{2}\z/ From a7a8b40c5cba32f26896d0a6c9af64c3d9f32adf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:47:02 +0000 Subject: [PATCH 122/439] Ledger: perf/startup3 landed, not gated (gap 26) Records the two start-up changes measured on the release image, base and new run side by side: main-thread instructions -2.8% on `-e 1`, -2.0% on `gem list` and `require "irb"`, -1.8% on irb, and +-0.1% on `gem --version`. It also records where RubyGems' boot time goes in `-e 1`, and that callgrind's counts depend on how many runs share the CPUs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Util/perf/LEDGER.md | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 6eeb68780..90bf689ab 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1368,6 +1368,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has RubyGems' own Ruby (binds ~100 ms inclusive in `-e 1`, the running of precompiled code), the files `gem list` requires, and the JIT, which the release image already halves. A next attempt should measure on the release image, or say why the R2R host stands in for it. + 2026-11-27, perf/startup3 (Landed, not gated): measured on the release image as perf/startup2 + asks. FindCopyingClasses' type scan is now generated attributes, and the default-spec cache is + validated without a glob or a File::Stat per gemspec. Main-thread instructions -2.0% / -2.0% / + -1.8% on `gem list` / `require "irb"` / irb, and -2.8% on `-e 1` (release image). What is left of + RubyGems' boot is its own class bodies (specification, requirement, platform: ~40 ms of `-e 1`) + and rbconfig (~12 ms). 27. **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a @@ -1568,6 +1574,68 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/startup3 (2026-11-27) - start-up on the release image: a copied module's backtrace name + from generated attributes; the default-spec cache validated in one pass over the directory (gap + 26)** - not gated. Base 79a2c30 (with the round's ledger, 973314a). Two commits: + - 86e85c0: `RubyStackTraceBuilder.FindCopyingClasses` read the `Includes(Copy = true)` attributes of + every type in IronRuby.Libraries the first time a backtrace named a copied module's method. That + cost ~9 ms once per process (`gem list`, `require "irb"` and irb, through optparse's rescued + exception in `Gem::Command#handles?`) and loaded AngleSharp.dll and System.Net.Sockets.dll. The + initializer generator now emits `[assembly: RubyCopiedModule(typeof(module), typeof(class))]`, + six pairs in IronRuby.Libraries and none in Libraries.Yaml. An assembly without + `RubyLibraryAttribute` is still scanned, and `IR_COPIED_TABLE=0` scans as before. + LibraryCopiedModuleAttributes1 compares the written table with the scan for both assemblies. + - 7fba338: `rubygems/defaults/ironruby.rb`'s `ironruby_load_default_specs` checks its cache's stamp + with `IronRuby.__gemspec_stamp__`: name, size and mtime of each `*.gemspec` entry, in one C# pass. + It used to glob the 62 default gemspecs and make a File::Stat and a Time for each. A boot that + hits the cache no longer globs. A miss and `IRONRUBY_NO_GEM_CACHE=1` work as before. + `rubygems/util` is still required at boot, as upstream's glob loads it, so `$LOADED_FEATURES` and + its order are unchanged. The cache format is version 2, so old caches miss once. + The helper first used a List of KeyValuePairs, a value-type instantiation that no R2R image + holds: its first call JIT-compiled 26 methods (~3 ms on the R2R host) and made `gem --version` + +1.3%. Over a List of FileSystemInfo it compiles 5 (~1 ms). + Where RubyGems' ~120 ms of `-e 1` goes (per-file load timer, R2R host, startup library): + rubygems.rb's top level 35-42 ms self, ~31 ms of it the default-spec cache (glob 7, stamp 5.7, + index file name 2.5, read 5.6, Marshal.load 3.2, activation 3, the rest ~3); specification.rb 13-16 + self, plus requirement 13-16, platform 9-10 and specification_record 6-7 under it; rbconfig 11-14. + Only the cache is IronRuby's own code. `find_default_spec` cannot be made lazy: the runtime requires + ironruby/error_highlight, did_you_mean and syntax_suggest through RubyGems' require at every boot. + Main-thread instructions (callgrind, TieredCompilation=0), base and new run side by side, base -> + new, M: + | command | release image | R2R host | + |---|---|---| + | `-e 1` | 1,198.3 -> 1,165.0 (-2.77%) | 2,092.4 -> 2,013.4 (-3.78%) | + | `gem --version` | 1,339.5 -> 1,338.3 (-0.09%) | 2,272.6 -> 2,274.7 (+0.09%) | + | `gem list` | 2,293.6 -> 2,247.4 (-2.01%) | 3,424.3 -> 3,380.4 (-1.28%) | + | `require "irb"` | 2,412.4 -> 2,363.9 (-2.01%) | 3,469.6 -> 3,427.1 (-1.23%) | + | irb 1+1 | 2,577.6 -> 2,531.8 (-1.77%) | 3,725.5 -> 3,678.5 (-1.26%) | + The counts depend on load: under valgrind, the number of runs sharing the CPUs decides when + background compiles land, and so how long the main thread interprets. The same command moved + ~1-2% between batches of 2 and 4 runs. Compare only runs of one batch. + Split by `IR_COPIED_TABLE=0` (release image, a trio in one batch): `gem list` base 2,300.0, new + 2,280.6, new with the scan 2,303.8; `require "irb"` 2,425.0, 2,378.3, 2,420.5. So in the tools the + saving is part 1's. Part 2 saves `-e 1`'s 33-79 M (release / R2R host). In `gem --version`, `gem + list` and irb, RubyGems globs and stats the specification directories later anyway, so the + first-use cost moves there instead of going away. + Wall, best of 10 alternating (`startup2.rb`), base / new, ms: release image `-e 1` 331 / 321, + `gem --version` 388 / 384, `gem list` 721 / 684, `require "irb"` 719 / 715, irb 796 / 774. New + first: 313 / 310, 371 / 377, 663 / 684, 700 / 704, 756 / 751 (that run lists new first). R2R host: + 423 / 415, 484 / 488, 819 / 825, 864 / 861, 934 / 945. All within the machine's noise, which these + differences are under. + Checked: a probe of backtraces through each copied module's methods prints the same on base, new + and new with `IR_COPIED_TABLE=0`, on the Release build and the R2R host. That includes the three + lines where IronRuby already differs from CRuby: Integer#div shown as `Integer#/`, Integer#coerce + as `Numeric#coerce`, IO#printf's frame missing. The 30 backtrace and caller tests and the 18 + require and prelude tests of IronRuby.Tests pass. caller, raise, jit-raise and set-backtrace + matrices print the same in 7 modes (the gate's five, R2R, `IR_COPIED_TABLE=0`). + caller-matrix on the R2R host prints its Kernel#eval frames in 1 of 6 runs on either tree, a flake. + thread-backtrace-matrix's main-thread row is the known 87/88. RubyGems' state is the same on both + trees, on a hit and with `IRONRUBY_NO_GEM_CACHE=1`, Release and R2R, and with -w: + `Gem.loaded_specs`, `$LOADED_FEATURES` and its order, `find_default_spec` of ten names, and the + map's size (1,484). A touched gemspec makes the next boot miss and rewrite the cache. + Steady state: AWFY verifying, no FAIL. At 3 s the geomean was 1.062, with Permute 2.4x. At 8 s in + both orders Permute, NBody and Sieve are within 2%, and Havlak is +4% and -8%: noise. + - **Gate of 2026-11-26 for round thirty-seven** (perf/lglobal, perf/lexical, perf/deadconst, perf/strsearch, perf/extiter, perf/struct, perf/dmethjit; the rejected perf/lsite's tools and perf/jitbody's census fix): the branch `claude/happy-gauss-95wm2j` at 2f8c31c against master From 8cc8445abb73250abbcb726814111906bf0488e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:51:17 +0000 Subject: [PATCH 123/439] Raise the end of a fiber's iteration from C#, its stack walk deferred Measured first what starting a fiber costs here. A raw CLR thread started and joined is 120-150 us on this container, whatever its stack size, and Ruby's Thread.new { }.join 130-260 us. A Fiber is 2.3 us to make. One that finishes runs on a pooled thread (13-25 us). One left suspended takes a new thread and keeps it until a GC finds its handle: 316-482 us warm, 1.2-1.5 times a waiting Ruby thread. Reclaiming them sooner costs more than it saves (the unwinding), so the start is left as it is. What a drained fiber-backed enumerator cost beyond its fiber (206 us against a fiber's 24) was mostly its end. __iter_stop__ raised, with Kernel#raise, a StopIteration that Ruby code had made and that it keeps as the cause of later ones, so the frame that rescued it always took the catch-site walk (73 us). It now calls Enumerator#__iter_raise_stop__, which makes and throws the exception as a cursor's StopIteration is: unkept, the first one kept in the enumerator and exposed when handed out as a cause, forgotten by #rewind. When StopIteration's #new or #initialize is the program's, the prelude still makes it, since MRI's rb_exc_new calls them. Both paths now show the StopIteration to a TracePoint on :raise, as Hash#fetch's KeyError is shown. The cursor's was never shown; CRuby shows it. Medians of 4,000: a generator's ending next 57 -> 28-33 us, a lazy's loop end 53-57 -> 25-27 us, the first next unchanged. ab.rb -r 6: gen_end 0.27 of the switched-off build, a one-element lazy drained 0.62, the cursor shapes level with base. Util/bench/fiber-start.rb (new) measures the start. 17 new probes in Util/extiter-matrix.rb (329 in all) print CRuby's output; enum-next, block-loop, raise, full-message and enum matrices agree with the baseline in every mode; spec/core/fiber, enumerator, thread and kernel/loop pass in all three modes; the Fiber, Thread, Enumerator, Exception and Raise IronRuby.Tests pass five times on each build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Src/Libraries/Builtins/Enumerator.cs | 46 ++++++++++++++++++++++++++-- Src/StdLib/ironruby/ruby4.rb | 5 +++ Util/bench/extiter-shapes.rb | 4 +++ Util/bench/fiber-start.rb | 36 ++++++++++++++++++++++ Util/extiter-matrix.rb | 37 ++++++++++++++++++++++ Util/perf/LEDGER.md | 42 ++++++++++++++++++++++++- 6 files changed, 167 insertions(+), 3 deletions(-) create mode 100644 Util/bench/fiber-start.rb diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index f8ef88b3d..80d2e49ab 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -1339,13 +1339,13 @@ private static object CursorStep(CallSiteStorage + /// The StopIteration about to be thrown, marked unkept (), after a TracePoint on :raise has seen + /// it go by, as MRI's rb_exc_raise shows it (and as Hash#fetch's KeyError is shown, IDictionaryOps). + ///
+ private static StopIteration/*!*/ Raising(RubyContext/*!*/ context, StopIteration/*!*/ stop) { + if ((TracePoint.ActiveEvents & (int)TraceEvents.Raise) != 0) { + TracePoint.OnException(TraceEvents.Raise, null, context, stop); + } + if (ThrowsUnkept()) { + RubyExceptionData.MarkUnkept(stop); + } + return stop; + } + // CursorStep's part for a cursor whose Resume runs Ruby code, in a method of its own: the handler here would otherwise be // CursorStep's, which every StopIteration is thrown from. [MethodImpl(MethodImplOptions.NoInlining)] @@ -1399,6 +1413,33 @@ private static void ResumeWithRubyCode(CallSiteStorage + /// The end of an iteration that runs on the prelude's fiber (Enumerator#__iter_stop__), raised as a cursor's is + /// (CursorStep): once as such, and from then on as a new StopIteration whose cause is the first, each one unkept, so that + /// the frame that rescues it may leave the walk of the stack below it (perf/extiter). Raised by the prelude it was an + /// exception Ruby code had made - Kernel#raise of an instance - and every end of such an iteration took the walk. + ///
+ [RubyMethod("__iter_raise_stop__", RubyMethodAttributes.PrivateInstance)] + public static object RaiseFiberStop(RubyContext/*!*/ context, Enumerator/*!*/ self, object result) { + // MRI makes it with rb_exc_new, which calls a #new or #initialize of the program's: the prelude does then + // (and keeps the first one itself) + if (!RubyExceptionData.MakesUnkeptException(context.GetClass(typeof(StopIteration)))) { + return null; + } + StopIteration first = self._fiberStop; + if (first == null) { + var stop = self._fiberStop = CreateStopIteration(context, result, null); + throw Raising(context, stop); + } + // handed to Ruby code now (Exception#cause): the walk left for it is taken here + RubyExceptionData.ExposeCatchSite(first); + var again = CreateStopIteration(context, result, first); + throw Raising(context, again); + } + private static StopIteration/*!*/ CreateStopIteration(RubyContext/*!*/ context, object result, StopIteration cause) { var stop = new StopIteration("iteration reached an end"); context.SetInstanceVariable(stop, RubyUtils.GetCoreStateInstanceVariableName("@__result__"), result); @@ -1527,6 +1568,7 @@ public static object TakeFeed(Enumerator/*!*/ self) { [RubyMethod("__iter_reset__", RubyMethodAttributes.PrivateInstance)] public static object ResetExternalIteration(Enumerator/*!*/ self) { self._cursor = null; + self._fiberStop = null; self._onFiber = false; self._feedValue = null; self._hasFeed = false; diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 50c26d44f..c8e8e5353 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -5857,7 +5857,12 @@ def self.__iter_fiber_for__(source) # get_next_values: the end is raised once as such, and from then on as a new # StopIteration whose cause is that first one. + # get_next_values: the end is raised once as such, and from then on as a new StopIteration + # whose cause is that first one. Made and raised in C#, as a cursor's is + # (Enumerator#__iter_raise_stop__), so that a rescue that drops it skips the stack walk - + # unless StopIteration's #new or #initialize is not IronRuby's own, which it then calls here. def __iter_stop__ + __iter_raise_stop__(@__iter_result__) error = ::StopIteration.new("iteration reached an end") error.__set_result__(@__iter_result__) first = @__iter_stop_exc__ diff --git a/Util/bench/extiter-shapes.rb b/Util/bench/extiter-shapes.rb index 823543a5e..81b397521 100644 --- a/Util/bench/extiter-shapes.rb +++ b/Util/bench/extiter-shapes.rb @@ -73,5 +73,9 @@ def peeks(e) t("lazy_next", n(5_000)) { |n| s = 0; (n / 1000).times { s += drain(LARGE.lazy.map { |x| x + 1 }) }; s } t("produce", n(20_000)) { |n| s = 0; (n / 1000).times { e = Enumerator.produce(1) { |x| x + 1 }; 1000.times { s += e.next } }; s } t("zip_enum", n(20_000)) { |n| s = 0; (n / 1000).times { LARGE.zip(LARGE.each) { |a, b| s += a + b } }; s } +# a fiber-backed enumerator of one element, drained: its start and its end are the cost (per enumerator) +t("gen_one", n(2_000)) { |n| s = 0; n.times { s += drain(Enumerator.new { |y| y << 1 }) }; s } +t("lazy_one", n(2_000)) { |n| s = 0; n.times { s += drain([1].lazy.map { |x| x }) }; s } +t("gen_end", n(20_000)) { |n| s = 0; e = Enumerator.new { |y| }; n.times { begin; e.next; rescue StopIteration; s += 1; end }; s } # controls: these keep their fiber (a generator; lazy and produce above too) t("generator", n(20_000)) { |n| s = 0; (n / 1000).times { s += drain(Enumerator.new { |y| LARGE.each { |x| y << x } }) }; s } diff --git a/Util/bench/fiber-start.rb b/Util/bench/fiber-start.rb new file mode 100644 index 000000000..4c6c5ea8c --- /dev/null +++ b/Util/bench/fiber-start.rb @@ -0,0 +1,36 @@ +# What starting a fiber costs (LEDGER gap 35): a fiber is a thread here. One kind per process, in +# blocks of 500, so that warm-up and the threads abandoned fibers leave behind show block by block. +# +# ./ir.sh Util/bench/fiber-start.rb KIND [BLOCKS] +# for k in $(ruby Util/bench/fiber-start.rb); do ./ir.sh Util/bench/fiber-start.rb $k; done +# +# Wall clock and process CPU (CLOCK_PROCESS_CPUTIME_ID: the fiber's thread and the spinning of +# both sides of a switch are counted), and the process's threads after each block. +$stdout.sync = true +def th = File.read("/proc/self/status")[/^Threads:\s+(\d+)/, 1].to_i +def wall = Process.clock_gettime(Process::CLOCK_MONOTONIC) +def cpu = Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) +Q = Queue.new +KINDS = { + # a Ruby thread: started and joined; started and left waiting, as an abandoned fiber's is + "thread_join" => -> { Thread.new { }.join }, + "thread_park" => -> { Thread.new { Q << 1; sleep }; Q.pop }, + # a fiber that finishes runs on a pooled thread after the first few + "fiber_complete" => -> { Fiber.new { 1 }.resume }, + "fiber_finish" => -> { f = Fiber.new { Fiber.yield 1; 2 }; f.resume; f.resume }, + # one that is left suspended keeps its thread until a GC finds its handle + "fiber_abandon" => -> { Fiber.new { Fiber.yield 1 }.resume }, + # enumerators with a fiber: drained, and left after one #next + "gen_drain" => -> { e = Enumerator.new { |y| y << 1 }; e.next; (e.next rescue nil) }, + "gen_abandon" => -> { Enumerator.new { |y| y << 1; y << 2 }.next }, + "lazy_abandon" => -> { [1, 2].lazy.map { |x| x }.next }, +} +abort(KINDS.keys.join("\n")) unless ARGV[0] +kind = ARGV[0] +make = KINDS.fetch(kind) +(ARGV[1] || 6).to_i.times do |j| + n = 500 + w0 = wall; c0 = cpu + n.times { make.call } + printf "%-14s block %d: %7.1f us wall %7.1f us cpu, threads %d\n", kind, j, (wall - w0) * 1e6 / n, (cpu - c0) * 1e6 / n, th +end diff --git a/Util/extiter-matrix.rb b/Util/extiter-matrix.rb index 2722769c7..2ec922f48 100644 --- a/Util/extiter-matrix.rb +++ b/Util/extiter-matrix.rb @@ -678,3 +678,40 @@ def lz(e, n = 4) = n.times.map { (e.next rescue :stop) } probe("ewo_size") { [[1, 2].each_with_object(0).size, { a: 1 }.each_with_object(0).size, (1..3).each_with_object(0).size] } probe("ewo_thread") { e = [1, 2].each_with_object(0); e.next; Thread.new { begin; e.next; rescue => x; "#{x.class}: #{x.message}"; end }.value } probe("ewo_inspect") { e = [1].each_with_object(:m); e.next; e.inspect } + +# --- the StopIteration of an iteration on the fiber (a generator, a lazy): raised from C# now ---------- +def gen1 = Enumerator.new { |y| y << 1; :gen_r } +probe("fs_result") { e = gen1; e.next; s = (e.next rescue $!); [s.class, s.message, s.result] } +probe("fs_again") { e = gen1; e.next; s1 = (e.next rescue $!); s2 = (e.next rescue $!); s3 = (e.next rescue $!); [s1.equal?(s2), s2.cause.equal?(s1), s3.cause.equal?(s1), s1.cause, s3.result] } +probe("fs_dropped_cause") { e = gen1; e.next; begin; e.next; rescue StopIteration; end; s = (e.next rescue $!); [s.cause.class, s.cause.result, bt(s.cause).size > 0] } +def fs_drop(e) = (begin; e.next; rescue StopIteration; end; nil) +def fs_later(e) = [1].each { s = (e.next rescue $!); return [bt(s.cause), bt(s)] } +probe("fs_bt_cause_later") { e = gen1; e.next; fs_drop(e); fs_later(e) } +def fs_bt_direct + e = gen1 + e.next + begin + e.next + rescue StopIteration => s + bt(s) + end +end +probe("fs_bt_direct") { fs_bt_direct } +probe("fs_loop") { e = gen1; [loop { e.next }, loop { e.next }] } +probe("fs_lazy_loop") { e = [1, 2].lazy.map { |x| x * 2 }; r = []; [loop { r << e.next }, r] } +probe("fs_rewind_fresh") { e = gen1; e.next; s1 = (e.next rescue $!); e.rewind; e.next; s2 = (e.next rescue $!); [s2.equal?(s1), s2.cause.nil?] } +probe("fs_dup_after_end") { e = gen1; e.next; s1 = (e.next rescue $!); d = e.dup; d.next; s2 = (d.next rescue $!); [s2.equal?(s1), s2.cause.nil?] } +probe("fs_raise_inside") { e = Enumerator.new { |y| y << 1; raise ArgumentError, "in" }; e.next; [(e.next rescue "#{$!.class}: #{$!.message}"), e.next] } +probe("fs_cause_in_rescue") { e = gen1; e.next; begin; raise "outer"; rescue; s = (e.next rescue $!); end; [s.class, s.cause&.message] } +probe("fs_tracepoint") { seen = []; tp = TracePoint.new(:raise) { |t| seen << t.raised_exception.class }; e = gen1; e.next; tp.enable { e.next rescue nil }; [seen.uniq, seen.size <= 1] } +probe("fs_thread_after_end") { e = gen1; e.next; (e.next rescue nil); Thread.new { begin; e.next; rescue => x; [x.class, x.cause.class]; end }.value } +probe("fs_init_redefined") do + calls = [] + StopIteration.class_eval { alias_method :__fs_init__, :initialize; define_method(:initialize) { |*a| calls << a; __fs_init__(*a) } } + e = gen1; e.next + s1 = (e.next rescue $!); s2 = (e.next rescue $!) + StopIteration.class_eval { remove_method :initialize; alias_method :initialize, :__fs_init__; remove_method :__fs_init__ } + [calls.size, s2.cause.equal?(s1), s1.result] +end +probe("fs_after_restore") { e = gen1; e.next; s1 = (e.next rescue $!); s2 = (e.next rescue $!); s2.cause.equal?(s1) } +probe("cur_tracepoint") { seen = []; tp = TracePoint.new(:raise) { |t| seen << [t.raised_exception.class, t.lineno == __LINE__] }; e = [].each; tp.enable { (e.next rescue nil); (e.next rescue nil) }; seen } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 122e001fc..0a8cbbd67 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1571,7 +1571,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has cursor would call blocks under its lock) and `Enumerator.new`. A raw fiber round trip is 2.3 us of wall clock and 4.7-6 us of CPU (two threads spinning), so the prelude's machinery around it is not where the time is. **An abandoned fiber-backed enumerator** costs 1.1-1.6 ms of process CPU to make and take one - value from (starting its thread), and its thread and about 60 KB stay until the handle's + value from (starting its thread: 316-482 us of wall clock warm, a new OS thread each, as + perf/fiberstart found; one that finishes reuses a pooled thread, 13-25 us), and its thread and about 60 KB stay until the handle's finalizer unwinds it (FiberRegistration, ThreadOps.Fiber.cs). That needs nothing on the fiber's side to reach the handle, and a blocked thread's stack is a GC root: since perf/extiter4 (Landed) a lazy made elsewhere, or whose blocks are Symbol#to_procs, is @@ -1633,6 +1634,45 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/fiberstart (2026-11-27) - what a fiber's start costs, found; the end of an iteration on a + fiber raised from C# and its stack walk deferred, as a cursor's is (gap 35)** - not gated. Base + 8d7efda (the round-38 branch with perf/extiter5). Measured first (`Util/bench/fiber-start.rb`, + new: one kind per process, blocks of 500, wall and process CPU, threads), on this four-core + container: a raw CLR thread started and joined is 120-150 us whatever its stack (0, 256 KB, 1 MB, + 8 MB; a C# probe), 150-220 us with 0-3,000 threads alive; Ruby's `Thread.new { }.join` 130-260 + us, one left waiting (`thread_park`) 285-412 us - so the 41-58 us of #213 was another machine. A + Fiber made is 2.3 us; one that finishes runs on a pooled thread (`fiber_complete` 13-25 us, + 2,000 pool hits of 2,000); one left suspended takes a new thread, 316-482 us after warm-up, + 1.2-1.5 times a waiting Ruby thread's, and keeps it: without a GC.start 3,000 of them were three + GCs and 3,017 threads, and reclaiming them (GC.start every 100 or 250) bounded the threads at + 117-267 but cost more per enumerator (802-838 us against 578: the unwinding), since a reclaimed + thread beyond the pool's 8 ends. No change there: a thread for a suspended fiber is the price + while a fiber is a thread. What a drained fiber-backed enumerator cost beyond its fiber + (`gen_drain` 206 us against a fiber's 24) was mostly its end: __iter_stop__ raised a + StopIteration Ruby code had made and kept (the cause of later ones) with Kernel#raise, which + takes the catch-site walk (73 us of it). Now __iter_stop__ calls `Enumerator#__iter_raise_stop__` + (C#), which makes and throws it as CursorStep does - unkept, the first kept in the enumerator and + exposed (ExposeCatchSite) when handed out as a cause, forgotten by #rewind - unless + StopIteration's #new or #initialize is the program's (MakesUnkeptException), when the prelude + makes it as before, since MRI's rb_exc_new calls them. Both paths now show the StopIteration to + a TracePoint on :raise (`TracePoint.OnException`, as Hash#fetch's KeyError): the cursor's was + never shown (base: none of CRuby's three events), the fiber's was by Kernel#raise. Medians of + 4,000, base -> new: a generator's ending `next` 57 -> 28-33 us, a lazy's `loop { e.next }` end + 53-57 -> 25-27 us, the first `next` unchanged (65-75). `ab.rb -r 6`, ns, base / off / new: + `gen_end` (`next` again after a generator's end) 32803 / 29684 / 7929 (0.27 of off), `lazy_one` + (a one-element lazy drained) 119422 / 114263 / 70466 (0.62), `gen_one` 1.04 overlapping (its + start dominates), the cursor shapes level with base. Still open, the cursor path's own + difference from CRuby: with StopIteration#initialize redefined its cause is another object + (base too; the fiber path takes the prelude's way then and matches CRuby). `Util/extiter-matrix + .rb` (329 probes, 17 new: result, causes and their backtraces with the first end dropped in a + frame that has returned, loop, rewind, dup, an error in the generator, the cause inside a rescue, + TracePoint on both paths, threads, a redefined #initialize) prints CRuby's output on new; base + differs in the cursor TracePoint probe (fixed here), off in `flm_to_ary_next` only (perf/extiter5). + enum-next-, block-loop-, raise-, full-message- and enum-matrix the same on base, new and off. + spec/core/fiber, enumerator, thread and kernel/loop_spec: 1,026 examples, 0 failures in all + three; the Enumerator*, Lazy*, Loop*, Fiber*, Thread*, Exception* and Raise* IronRuby.Tests pass + in five plain runs on base and five on new (no abort, no failure). + - **perf/extiter5 (2026-11-27) - Hash#select / #filter / #reject, `filter_map`, `flat_map` and `each_with_object` take `next` on a cursor (gap 35)** - not gated. Base 1fca3c7 (the round-38 branch at b887bc1 with perf/extiter4). Hash's own #select, #filter and #reject copy the From 947f932ffc26912b6dfa782d379a8636a712115c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:55:34 +0000 Subject: [PATCH 124/439] String#encode takes its options as keywords only `s.encode("US-ASCII", obj)` with an object that has #to_hash, or a positional Hash, took it as the options (Protocols.TryConvertToOptions, Ruby 1.9's reading); since Ruby 3.0's keyword separation CRuby takes it as an encoding: "no implicit conversion of ToHashOptions into String", and `encode(to, from, hash)` is "wrong number of arguments (given 3, expected 0..2)". A keyword hash that reaches the method as its last positional argument (`**obj`) is still the options. Util/encode-matrix.rb: 1 line -> same. Checked: String_EncodeKeywordOptionsOnly1 (new; CRuby 4.0's output) and the 24 other encode tests; spec/core/string/encode, spec/core/encoding; encode-matrix, io-transcode-matrix same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 21 +++++++++++++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 13 ++++++++++++- 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 33f362a06..86b4d6d2d 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1438,6 +1438,7 @@ public Tests(Driver/*!*/ driver) { String_OrdWide1, Integer_ChrSingleByte1, String_TranslateCheckOrder1, + String_EncodeKeywordOptionsOnly1, Integer_ChrMultibyte1, String_Cesu8_1, String_EmacsMule1, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index a99718e45..78c3cfb50 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -1385,6 +1385,27 @@ def t(l) then %s US-ASCII: [Encoding::CompatibilityError, ""incompatible character encodings: BINARY (ASCII-8BIT) and UTF-8""] %s then %c: US-ASCII 65333831383263326131 bytes kept: [""3c8fa2b73e"", ""3cedb2803e""] +"); + } + + /// + /// String#encode and #encode! take their options as keywords only: a positional Hash, or an object with #to_hash, is an + /// encoding (TypeError), and a third positional argument too many; a keyword hash, **obj included, is the options. Util/encode-matrix.rb. + /// + public void String_EncodeKeywordOptionsOnly1() { + TestOutput(@" +require 'ruby4' +class ToHashOptions; def to_hash = {undef: :replace}; end +s = ""あ"" +[-> { s.encode(""US-ASCII"", ToHashOptions.new) }, -> { s.encode(""US-ASCII"", ""UTF-8"", ToHashOptions.new) }, -> { s.encode(""US-ASCII"", **ToHashOptions.new) }, + -> { s.encode(""US-ASCII"", {undef: :replace}) }, -> { s.encode(ToHashOptions.new) }, -> { s.dup.encode!(""US-ASCII"", ToHashOptions.new) }].each { |l| p((l.call rescue $!)) } +", @" +# +# +""?"" +# +# +# "); } } diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 7eaaf944f..e8702d78f 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -3047,7 +3047,18 @@ public static bool ValidEncoding(MutableString/*!*/ self) { [Optional]object fromEncoding, [Keywords, DefaultParameterValue(null), DefaultProtocol]IDictionary options) { - Protocols.TryConvertToOptions(toHash, ref options, ref toEncoding, ref fromEncoding); + // The options are keywords only (Ruby 3.0's separation): a trailing positional Hash, or an object with + // #to_hash, is an encoding to CRuby 4.0 and so "no implicit conversion of Hash into String". A keyword hash + // that arrived as the last positional argument (**obj) is still the options. + if (options == null) { + if (fromEncoding is Hash lastHash && lastHash.IsKeywordArguments) { + options = lastHash; + fromEncoding = Missing.Value; + } else if (fromEncoding == Missing.Value && toEncoding is Hash onlyHash && onlyHash.IsKeywordArguments) { + options = onlyHash; + toEncoding = Missing.Value; + } + } // encodings: RubyEncoding to, from; From 8d030d12814eb1ab8f4f2ab9389a52a423caedb2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:58:33 +0000 Subject: [PATCH 125/439] StringScanner: the map check is one flag test on an ASCII subject Round three's map cost an ASCII scan word by word over 10 KB 2.6 to 3.4% more instructions (ss_words_a, callgrind). A per-function count - callgrind with DOTNET_ReadyToRun=0, the JIT'd functions named from the runtime's perf map, the scanner shape's least section against the tree before round three (b887bc1) - put 4.9 of the 6.7 M instructions it added to a pass at the check every scan makes four times a token: the map getter, the switch's static (StaticsHelpers.GetNonGCStaticBase), the encoding and an IsAscii() call. The getter now tests HasByteCharacters, a flag that answers for a subject known to be ASCII, and leaves the switch, the encoding and IsAscii to the non-inlined slow path. ss_words_a: 13.62-13.73 M (before round three) / 13.97 M (round three) / 13.79-13.89 M now, +1.2%. What is left is the getter's call itself (1.1 M a section: the JIT does not inline it under count.sh's settings, AggressiveInlining or not) and HasByteCharacters (0.37 M; marking it AggressiveInlining changed nothing, so it was not kept). The matrix prints what the base prints, switch on and off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/StringScanner/StringScanner.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index 20580f1a7..a992ed569 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -271,17 +271,21 @@ private bool Seek(bool byBytes, int target, out int b, out int c) { private Utf8Map Map { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - // what every scan on an ASCII or non-UTF-8 subject asks: kept small enough to inline + // What every scan asks, four times a token: one flag test, which answers for a subject + // already known to be ASCII (or BINARY). A per-function count of an ASCII scan + // (callgrind, JIT'd code named from the perf map) put the earlier check - the switch's + // static, the encoding, an IsAscii call - at 4.9 of the 6.7 M instructions the map + // had added to a pass over 10 KB. MutableString subject = _scanString; - if (!MapEnabled || subject.Encoding != RubyEncoding.UTF8 || subject.IsAscii()) { - return null; - } - return MapFor(subject); + return subject.HasByteCharacters ? null : MapFor(subject); } } [MethodImpl(MethodImplOptions.NoInlining)] private Utf8Map MapFor(MutableString/*!*/ subject) { + if (!MapEnabled || subject.Encoding != RubyEncoding.UTF8 || subject.IsAscii()) { + return null; + } // a string held as bytes is decoded once, as a match would subject.PrepareForCharacterRead(); string text = subject.ConvertToString(); From 7621c603174da327613f720678cbc8cbc4206586 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:59:54 +0000 Subject: [PATCH 126/439] OSR loop exits: Integers through the cache, unchanged and dead locals not stored What was left of NBody's 152 MB after perf/nbody (48 MB, 192 bytes per `advance') was mostly made at the exits of the loops' typed copies. Each exit stored every slot back into its tuple, boxing it: - an Int32 with a plain convert, not through the small-integer cache: the `each_index' counter and parameter (4, 5) and the `each' counter, three 24-byte boxes per call; - a local the copy only reads (`dt', a Float): a new box of the same value at every exit, two per call; - a block loop's own parameter and block locals, into a tuple of the BlockLoopSite's own that Run clears afterwards: nothing reads them, since a generic iteration after a hand-back yields to the block, whose call has a scope of its own. Now an Int32 goes home through ScriptingRuntimeHelpers.Int32ToObject, as generic code boxes one; a slot the copy's body never assigns (AssignsVariable: no assignment, increment or by-ref argument; an irreducible extension node counts as one) is not stored back at either exit, so the tuple keeps what it held, which also leaves a value another thread or a callee wrote meanwhile; and a block loop's copy stores none of its block's own locals (OsrLoopSite.DeadAtExit). IR_LOOP_EXITS=0 restores all three. Per `advance' (an in-process GC allocation-tick probe): 166 -> 46 bytes, the 22 of the probe's driver and the 24-byte locals tuple of the parked scope left. Util/loop-exit-matrix.rb (new) prints what CRuby 4.0 prints with the switch on and off, with -X:NoJIT -X:NoOSR, and on the base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Runtime/Jit/JitLoopCompiler.cs | 95 +++++++++++++- Src/Ruby/Runtime/Osr/BlockLoopSite.cs | 6 + Src/Ruby/Runtime/Osr/OsrLoopSite.cs | 6 +- Util/loop-exit-matrix.rb | 165 ++++++++++++++++++++++++ 4 files changed, 268 insertions(+), 4 deletions(-) create mode 100644 Util/loop-exit-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs index 8e1dfbb5a..2b71ca209 100644 --- a/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs @@ -54,12 +54,29 @@ internal sealed class JitLoopSlot { ///
internal MSA.ParameterExpression Assigned; internal MSA.ParameterExpression AssignedSnapshot; + /// The local the slot is. + internal LocalVariable Local; } internal static class JitLoopCompiler { - /// The boxed form a slot's value goes home as. + /// + /// IR_LOOP_EXITS=0: an Int32 goes home as a new box, and a block loop's copy stores its block's own locals at its exits + /// (see Box, TryCompile's deadAtExit), as they did. + /// + internal static readonly bool LeanExitsEnabled = Environment.GetEnvironmentVariable("IR_LOOP_EXITS") != "0"; + + /// + /// The boxed form a slot's value goes home as: an Int32 through the small-integer cache, as the generic code boxes + /// one (a loop's counter left at 5 cost a 24-byte box at every exit - three per NBody `advance'). + /// private static MSA.Expression/*!*/ Box(MSA.Expression/*!*/ value, bool isLong) { - return isLong ? Ast.Call(JitRuntime.M("NarrowLong"), value) : (MSA.Expression)Ast.Convert(value, typeof(object)); + if (isLong) { + return Ast.Call(JitRuntime.M("NarrowLong"), value); + } + if (value.Type == typeof(int) && LeanExitsEnabled) { + return Ast.Call(typeof(Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers).GetMethod("Int32ToObject"), value); + } + return Ast.Convert(value, typeof(object)); } /// @@ -72,7 +89,7 @@ internal static class JitLoopCompiler { /// internal static Func TryCompile(WhileLoopExpression/*!*/ loop, RubyContext/*!*/ context, int scopeDepth, Dictionary/*!*/ tupleArgIndex, object[]/*!*/ args, int selfArgIndex, int scopeArgIndex, - out JitLoopGuard loopGuard, bool longRuns = false, bool lightFrame = false) { + out JitLoopGuard loopGuard, bool longRuns = false, bool lightFrame = false, ICollection deadAtExit = null) { loopGuard = null; @@ -175,6 +192,7 @@ internal static Func TryCompile(WhileLoopExpression/*!*/ loop, Accessor = accessor, Assigned = writeFirst ? Ast.Parameter(typeof(bool), local.Name + "#set") : null, AssignedSnapshot = writeFirst ? Ast.Parameter(typeof(bool), local.Name + "#set-snap") : null, + Local = local, }; }; @@ -339,6 +357,11 @@ internal static Func TryCompile(WhileLoopExpression/*!*/ loop, prologue.Add(Ast.Assign(slot.Variable, read)); prologue.Add(Ast.Assign(slot.Snapshot, slot.Variable)); } + if (LeanExitsEnabled && (deadAtExit != null && deadAtExit.Contains(slot.Local) || !AssignsVariable.In(body, slot.Variable))) { + // nothing reads it after the copy, however the copy ends, or the copy never changes it (`dt' of NBody's + // `advance', read in every iteration): the tuple holds what it should, and no box is made for it + continue; + } storeCurrent.Add(store); storeSnapshot.Add(storeSnap); } @@ -383,6 +406,72 @@ internal static Func TryCompile(WhileLoopExpression/*!*/ loop, } } + /// + /// Whether an expression tree may change a given variable: an assignment to it (compound and increments included), or + /// a call that takes it by reference. + /// + internal sealed class AssignsVariable : MSA.ExpressionVisitor { + private readonly MSA.ParameterExpression/*!*/ _variable; + private bool _found; + + private AssignsVariable(MSA.ParameterExpression/*!*/ variable) { + _variable = variable; + } + + internal static bool In(MSA.Expression/*!*/ tree, MSA.ParameterExpression/*!*/ variable) { + var finder = new AssignsVariable(variable); + finder.Visit(tree); + return finder._found; + } + + public override MSA.Expression Visit(MSA.Expression node) { + return _found ? node : base.Visit(node); + } + + protected override MSA.Expression VisitBinary(MSA.BinaryExpression/*!*/ node) { + switch (node.NodeType) { + case MSA.ExpressionType.Assign: + case MSA.ExpressionType.AddAssign: case MSA.ExpressionType.AddAssignChecked: + case MSA.ExpressionType.SubtractAssign: case MSA.ExpressionType.SubtractAssignChecked: + case MSA.ExpressionType.MultiplyAssign: case MSA.ExpressionType.MultiplyAssignChecked: + case MSA.ExpressionType.DivideAssign: case MSA.ExpressionType.ModuloAssign: case MSA.ExpressionType.PowerAssign: + case MSA.ExpressionType.AndAssign: case MSA.ExpressionType.OrAssign: case MSA.ExpressionType.ExclusiveOrAssign: + case MSA.ExpressionType.LeftShiftAssign: case MSA.ExpressionType.RightShiftAssign: + if (node.Left == _variable) { _found = true; return node; } + break; + } + return base.VisitBinary(node); + } + + protected override MSA.Expression VisitUnary(MSA.UnaryExpression/*!*/ node) { + switch (node.NodeType) { + case MSA.ExpressionType.PreIncrementAssign: case MSA.ExpressionType.PreDecrementAssign: + case MSA.ExpressionType.PostIncrementAssign: case MSA.ExpressionType.PostDecrementAssign: + if (node.Operand == _variable) { _found = true; return node; } + break; + } + return base.VisitUnary(node); + } + + protected override MSA.Expression VisitMethodCall(MSA.MethodCallExpression/*!*/ node) { + var parameters = node.Method.GetParameters(); + for (int i = 0; i < parameters.Length && i < node.Arguments.Count; i++) { + if (parameters[i].ParameterType.IsByRef && node.Arguments[i] == _variable) { _found = true; return node; } + } + return base.VisitMethodCall(node); + } + + protected override MSA.Expression VisitExtension(MSA.Expression/*!*/ node) { + // an extension node (the DLR's) may write anything it holds: reduce it and look at what it is + return node.CanReduce ? Visit(node.Reduce()) : MarkFound(node); + } + + private MSA.Expression MarkFound(MSA.Expression node) { + _found = true; + return node; + } + } + /// Whether an expression tree references a given parameter or variable. internal sealed class UsesParameter : MSA.ExpressionVisitor { private readonly MSA.ParameterExpression/*!*/ _parameter; diff --git a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs index e85b77da2..f55aa17cc 100644 --- a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs @@ -453,6 +453,12 @@ internal BlockLoopSite(BlockLoopInfo/*!*/ info, BlockLoopKind kind) { _osr.TupleArgIndex = tupleArgIndex; _osr.SelfArgIndex = depth + 1; _osr.ScopeArgIndex = depth + 2; + // Run reads back only the counter and what a select kept (the hidden locals), and clears the tuple + var dead = new List(info.Locals); + if (info.Parameter != null) { + dead.Add(info.Parameter); + } + _osr.DeadAtExit = dead; } private void Retire() { diff --git a/Src/Ruby/Runtime/Osr/OsrLoopSite.cs b/Src/Ruby/Runtime/Osr/OsrLoopSite.cs index a9dcc817f..743bedd35 100644 --- a/Src/Ruby/Runtime/Osr/OsrLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/OsrLoopSite.cs @@ -141,6 +141,10 @@ private static long ReadThreshold() { // scope, which its constants resolve in as the method scope's would, and its refinements are none, which a light // frame's always are (it is never compiled where one is active, and `using' is not allowed in a method). internal bool InLightFrame; + // Locals no one reads once the copy has returned, however it returned: a block loop's block parameter and block + // locals (BlockLoopSite), which live in a tuple of the site's own that is cleared after the run - a generic + // iteration after a hand-back yields to the block, whose call has a scope of its own. The exits store none of them. + internal ICollection DeadAtExit; private readonly object/*!*/ _lock = new object(); private readonly string/*!*/ _name; @@ -281,7 +285,7 @@ private Func Compile(object[]/*!*/ tuples) { long start = Stopwatch.GetTimestamp(); try { JitLoopGuard guard; - var typed = JitLoopCompiler.TryCompile(LoopAst, Context, ScopeDepth, TupleArgIndex, tuples, SelfArgIndex, ScopeArgIndex, out guard, LongRuns, InLightFrame); + var typed = JitLoopCompiler.TryCompile(LoopAst, Context, ScopeDepth, TupleArgIndex, tuples, SelfArgIndex, ScopeArgIndex, out guard, LongRuns, InLightFrame, DeadAtExit); _guard = guard; _typed = typed; } catch (Exception e) { diff --git a/Util/loop-exit-matrix.rb b/Util/loop-exit-matrix.rb new file mode 100644 index 000000000..c5eb56892 --- /dev/null +++ b/Util/loop-exit-matrix.rb @@ -0,0 +1,165 @@ +# Differential matrix for what an OSR loop's typed copy hands back at its exits (IR_LOOP_EXITS: Src/Ruby/Runtime/Jit/ +# JitLoopCompiler.cs): an Int32 goes home through the small-integer cache, a local the copy never assigns is not stored +# back, and a block loop's copy (BlockLoopSite) stores none of its block's own locals. Run it under CRuby and under ./ir.sh +# with the switch on and off and with the tiers off, and diff: +# +# ruby Util/loop-exit-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/loop-exit-matrix.rb > /tmp/on.txt +# IR_LOOP_EXITS=0 ./ir.sh Util/loop-exit-matrix.rb > /tmp/off.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/loop-exit-matrix.rb > /tmp/notiers.txt +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt && diff /tmp/mri.txt /tmp/notiers.txt +# +# Every loop runs well past the OSR threshold (2000 back edges or yields) before the case it probes, so the typed copy +# is what meets it. The last section has an Integer instance variable updated in a hot loop: past Int32, turned into a +# Float or a String, and read by another thread. + +def t(label) + print label.ljust(64), ' => ' + begin + v = yield + puts "#{v.inspect} (#{v.class})" + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +N = 6000 + +# ---------------------------------------------------------------- 1. Integers going home around the cache's bounds + +t('while: counter ends at 999, 1000, 1001') { [999, 1000, 1001].map { |m| i = 0; while i < m * 3 + N; i += 1; end; i - m * 3 - N + m } } +t('while: local ends at -100, -101') { [-100, -101].map { |m| i = 0; k = 0; while i < N; i += 1; k = m if i == N; end; [k, k.equal?(m)] } } +t('while: local ends past Int32') { i = 0; k = 2**31 - 3000; while i < N; i += 1; k += 1; end; [k, k.class] } +t('while: local ends past Int64') { i = 0; k = 2**63 - 3000; while i < N; i += 1; k += 1; end; [k, k.class] } +t('times: an outer Integer') { s = 0; N.times { |i| s += i & 7 }; s } +t('each: an outer Integer near the bound') { s = 990; a = Array.new(N, 0); a[-1] = 20; a.each { |x| s += x }; s } +t('object_id of an Integer that went home') { i = 0; while i < N; i += 1; end; [i.object_id == N.object_id, i.equal?(N)] } + +# ---------------------------------------------------------------- 2. locals the copy only reads + +class Reader + def initialize; @a = Array.new(50) { |i| i * 0.5 }; end + def scaled(dt) + s = 0.0 + @a.each { |x| s += x * dt } + [s, dt, dt.class] + end + def int_read(k) + s = 0 + N.times { |i| s += k } + [s, k] + end + def changed_by_callee(dt) + s = 0.0 + f = proc { dt = 2.0 } + i = 0 + while i < N + s += dt + f.call if i == N / 2 + i += 1 + end + [s, dt] + end +end + +t('a Float parameter only read in an each block') { r = Reader.new; 3000.times { r.scaled(0.25) }; r.scaled(0.75) } +t('an Integer parameter only read in a times block') { r = Reader.new; 50.times { r.int_read(3) }; r.int_read(2**40) } +t('a local the loop reads that a proc changes') { r = Reader.new; r.changed_by_callee(1.0) } + +t('a local another thread changes while the loop reads it') { + dt = 1.0 + q1 = Queue.new + q2 = Queue.new + th = Thread.new { q1.pop; dt = 3.0; q2 << :done } + s = 0.0 + i = 0 + while i < N + s += dt + if i == N / 2 + q1 << :go + q2.pop + end + i += 1 + end + th.join + [s, dt] +} + +# ---------------------------------------------------------------- 3. a block loop's own locals + +t('block parameter and locals not visible after the block') { + x = :outer + r = [1, 2, 3] * 2000 + s = 0 + r.each { |e| y = e * 2; s += y } + [s, x, defined?(y), defined?(e)] +} +t('block locals shadowing nothing, read again next call') { + out = [] + 3.times do |k| + a = Array.new(N) { |i| i + k } + t = 0 + a.each_index { |i| v = a[i] - k; t += v } + out << t + end + out +} +t('a deopt in a block loop: the iteration redone') { + a = Array.new(N) { |i| i } + a[N - 10] = 1.5 + s = 0 + a.each { |e| w = e * 2; s += w } + s +} +t('a deopt in each_index: the parameter after it') { + a = Array.new(N) { |i| i } + a[N / 2] = 'x' + r = [] + a.each_index { |i| v = a[i]; r << i if v.is_a?(String) } + r +} +t('nested: the outer block parameter after the inner loop') { + a = Array.new(100) { |i| i * 0.5 } + s = 0.0 + 40.times do + a.each_index do |i| + x = a[i] + ((i + 1)...a.size).each { |j| s += x - a[j] } + end + end + s +} + +# ---------------------------------------------------------------- 4. an Integer instance variable in a hot loop + +class Counter + attr_accessor :n, :log + def initialize(n); @n = n; @log = []; end + def bump(k); i = 0; while i < k; @n += 1; i += 1; end; @n; end + def bump_each(a); a.each { |x| @n += x }; @n; end + def bump_to(k, at, value); i = 0; while i < k; @n = value if i == at; @n += 1; i += 1; end; @n; end +end + +t('Integer ivar: past Int32 in the middle of a loop') { c = Counter.new(2**31 - 3000); c.bump(N); [c.n, c.n.class] } +t('Integer ivar: past Int64 in the middle of a loop') { c = Counter.new(2**63 - 3000); c.bump(N); [c.n, c.n.class] } +t('Integer ivar: in an each block, past Int32') { c = Counter.new(2**31 - 100); c.bump_each(Array.new(N, 1)); c.n } +t('Integer ivar: set to a Float in the middle') { c = Counter.new(0); c.bump(N); c.bump_to(N, N / 2, 0.5) } +t('Integer ivar: set to a String in the middle') { c = Counter.new(0); c.bump(N); c.bump_to(N, N / 2, 'x') } +t('Integer ivar: instance_variable_set from outside, then the loop') { + c = Counter.new(0); c.bump(N); c.instance_variable_set(:@n, 2**40); c.bump(N) +} +t('Integer ivar: a subclass with more ivars') { + k = Class.new(Counter) { def initialize(n); super; @m = 1; @o = 2; end } + c = Counter.new(0); c.bump(N) + d = k.new(5); [d.bump(N), c.bump(N)] +} +t('Integer ivar: read by another thread while a loop updates it') { + c = Counter.new(0) + c.bump(N) + seen = [] + stop = false + reader = Thread.new { last = -1; until stop; v = c.n; seen << :backwards if v < last; last = v; Thread.pass; end; seen.uniq } + 20.times { c.bump(N) } + stop = true + [reader.value, c.n] +} From 981690557132bffbff888c9aabf4c044777f287a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:01:29 +0000 Subject: [PATCH 127/439] Calls with a block argument: the hoisted splat is fresh `f(*a, &b)` evaluates its arguments into temporaries before the block argument, as MRI does, and expands the splat into a new Array there. That Array is the call's own, but the site did not say so, so a callee with a rest parameter copied it again. It now says so (RubyCallFlags.HasFreshSplat) and the callee's rest parameter takes it (RubyOps.TakeFreshSplat). A splat that is fresh already is not copied at all: the block argument cannot name it. `w(*args, &b) = rest_t(*args, &b)` 312 -> 217 B a call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs index 33776e7df..2a2ce3ef3 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs @@ -184,12 +184,19 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { ordered.Add(temp); } if (scratch.SplattedArgument != null) { + // The splat is expanded into an array here, before the block argument is evaluated: a copy, which nothing else + // refers to, and so fresh for the call (RubyCallFlags.HasFreshSplat): a rest parameter of the callee takes it + // rather than copying it again. A splat that is fresh already - an array the arguments made, or a rest parameter + // passed on where nothing can see it again (ForwardedRest) - is that array, not copied: the block argument cannot + // name it either. var temp = gen.CurrentScope.DefineHiddenVariable("#splat", typeof(RubyArray)); - assignments.Add(Ast.Assign(temp, - Ast.New(typeof(RubyArray).GetConstructor(new[] { typeof(System.Collections.IList) }), - AstUtils.Convert(scratch.SplattedArgument, typeof(System.Collections.IList))) + var list = AstUtils.Convert(scratch.SplattedArgument, typeof(System.Collections.IList)); + assignments.Add(Ast.Assign(temp, scratch.SplattedArgumentIsFresh ? + (MSA.Expression)Methods.TakeFreshSplat.OpCall(list) : + Ast.New(typeof(RubyArray).GetConstructor(new[] { typeof(System.Collections.IList) }), list) )); ordered.SplattedArgument = temp; + ordered.SplattedArgumentIsFresh = true; } hoisted = assignments; arguments = null; From 7af94ee4278a45c0b94813735c2e200370bc1193 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:01:29 +0000 Subject: [PATCH 128/439] Forward a rest parameter nothing can see again as the callee's rest `def w(*args) = n(*args)` (and `...`) copied args into n's rest parameter, since n must not share an Array the caller still holds. Where the caller cannot see the Array again there is nothing to share it with: ForwardedRest finds the splat that is the only reference to the method's rest parameter, outside loops and blocks, in a method with no block literal, binding, eval, local_variable_*, zsuper, retry or redo; its site says the splat is fresh (RubyCallFlags.HasFreshSplat) and the callee's rest parameter takes it. IR_FORWARD_REST=0 turns it off. Bytes a call: `w(...) = raw(...)` 212 -> 116, `w(...) = rest_t(...)` 309 -> 116, `w(*args) = rest_t(*args)` 214 -> 120. Instructions: prelude-cost w_splat 0.92, w_fwd 0.91; time 0.87 and 0.84. splat-pass-matrix section 10b (new, 21 rows) and the block-pass, light-rest, keyword-light and block-given matrices print CRuby's output in every mode and with each switch; ruby/spec language/send, method, delegation, super unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Compiler/Ast/Arguments.cs | 3 + .../Compiler/Ast/Definitions/ForwardedRest.cs | 117 ++++++++++++++++++ .../Ast/Definitions/MethodDefinition.cs | 1 + Src/Ruby/Compiler/AstGenerator.cs | 4 + Util/bench/forward-bytes.rb | 33 +++++ Util/perf/LEDGER.md | 36 ++++++ Util/splat-pass-matrix.rb | 48 +++++++ 7 files changed, 242 insertions(+) create mode 100644 Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs create mode 100644 Util/bench/forward-bytes.rb diff --git a/Src/Ruby/Compiler/Ast/Arguments.cs b/Src/Ruby/Compiler/Ast/Arguments.cs index 18dca6bb2..d9e818c26 100644 --- a/Src/Ruby/Compiler/Ast/Arguments.cs +++ b/Src/Ruby/Compiler/Ast/Arguments.cs @@ -88,6 +88,9 @@ private MSA.Expression TransformToCallInternal(AstGenerator/*!*/ gen, ICollectio // A call site splats one trailing array, so from the first splat on the arguments go into // one: foo(a,b,*c,*d,e,*f) is passed as foo(a,b,*[*c,*d,e,*f]). if (splattedCount == 1 && firstSplatted == _expressions.Length - 1) { + // the method's rest parameter, passed on where nothing can see it again (ForwardedRest) + var method = gen.CurrentMethod; + fresh = method != null && gen.CurrentBlock == null && ReferenceEquals(_expressions[firstSplatted], method.ForwardedRestSplat); return _expressions[firstSplatted].TransformRead(gen); } else if (splattedCount >= 1) { fresh = true; diff --git a/Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs b/Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs new file mode 100644 index 000000000..835f21d06 --- /dev/null +++ b/Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs @@ -0,0 +1,117 @@ +/* **************************************************************************** + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. + * + * ***************************************************************************/ + +using System; + +namespace IronRuby.Compiler.Ast { + + /// + /// A method that passes its rest parameter on as the splat of a call - `def w(*args, &b) = n(*args, &b)' - copies it when + /// the callee has a rest parameter of its own that takes the whole list: the callee must not share an Array the caller still + /// holds. Where the caller cannot see the Array again, there is nothing to share it with, and the call site may say so as a + /// site that made its splat itself does (RubyCallFlags.HasFreshSplat): the callee's rest parameter is the caller's Array + /// (RubyOps.TakeFreshSplat), one Array a call fewer. TruffleRuby does the same for a rest Array that does not escape. + /// + /// answers the one splat of a method body that may say so, or null. The caller cannot see the Array again + /// when the splat is the only thing in the method that names the rest parameter (no other read, no assignment, no `defined?'), + /// and nothing can name it for the method: no block literal in the method (a Proc's #binding reaches the frame), no binding, + /// eval or local_variable_* call, no zsuper (it passes the parameters on); and when it runs once per call of the method: not + /// in a loop or a block, and the method has no retry or redo. The callee may keep or change the Array as its own: in Ruby it + /// is a new one, and here the only other reference is a variable no code reads again. + /// + internal sealed class ForwardedRest : Walker { + // IR_FORWARD_REST=0 turns it off + private static readonly bool _enabled = Environment.GetEnvironmentVariable("IR_FORWARD_REST") != "0"; + + private readonly string/*!*/ _name; + private readonly int _depth; + private int _references; + private int _loops; + private int _blocks; + private bool _refused; + private SplattedArgument _splat; + + private ForwardedRest(LocalVariable/*!*/ rest) { + _name = rest.Name; + _depth = rest.DefinitionLexicalDepth; + } + + internal static SplattedArgument Find(Parameters parameters, Body body) { + if (!_enabled || parameters == null || body == null) { + return null; + } + var rest = parameters.Unsplat as LocalVariable; + if (rest == null) { + return null; + } + var finder = new ForwardedRest(rest); + // the defaults of optional parameters are part of the method too + foreach (var optional in parameters.Optional) { + optional.Walk(finder); + } + body.Walk(finder); + return (finder._refused || finder._references != 1) ? null : finder._splat; + } + + private bool IsRest(LocalVariable/*!*/ node) { + return node.Name == _name && node.DefinitionLexicalDepth == _depth; + } + + public override bool Enter(LocalVariable/*!*/ node) { + if (IsRest(node)) { _references++; } + return true; + } + + public override bool Enter(SplattedArgument/*!*/ node) { + var local = node.Argument as LocalVariable; + if (local != null && IsRest(local)) { + if (_loops > 0 || _blocks > 0 || _splat != null) { + _refused = true; + } else { + _splat = node; + } + } + return true; + } + + public override bool Enter(MethodCall/*!*/ node) { + switch (node.MethodName) { + case "binding": + case "eval": + case "local_variables": + case "local_variable_get": + case "local_variable_set": + case "local_variable_defined?": + _refused = true; + break; + } + return true; + } + + public override bool Enter(SuperCall/*!*/ node) { + if (node.HasImplicitArguments) { _refused = true; } + return true; + } + + public override bool Enter(RetryStatement/*!*/ node) { _refused = true; return true; } + public override bool Enter(RedoStatement/*!*/ node) { _refused = true; return true; } + + // a block literal's Proc has #binding, which reaches this frame + public override bool Enter(BlockDefinition/*!*/ node) { _refused = true; _blocks++; return true; } + public override void Exit(BlockDefinition/*!*/ node) { _blocks--; } + public override bool Enter(LambdaDefinition/*!*/ node) { _refused = true; _blocks++; return true; } + public override void Exit(LambdaDefinition/*!*/ node) { _blocks--; } + + public override bool Enter(WhileLoopExpression/*!*/ node) { _loops++; return true; } + public override void Exit(WhileLoopExpression/*!*/ node) { _loops--; } + public override bool Enter(ForLoopExpression/*!*/ node) { _loops++; return true; } + public override void Exit(ForLoopExpression/*!*/ node) { _loops--; } + + // a method defined inside has variables of its own + public override bool Enter(MethodDefinition/*!*/ node) { return false; } + } +} diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 1cbc41380..6e5c75da8 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -237,6 +237,7 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin // so they need the qualified form rather than the bare method name. gen.CurrentMethod.FrameLabel = frameLabel; gen.CurrentMethod.HasOwnCompiledFrame = true; + gen.CurrentMethod.ForwardedRestSplat = ForwardedRest.Find(_parameters, Body); // The literals of the body take their Procs from this slot if the body turns out to park its scope (below). if (ParkedScopesEnabled && allowLightFrame && _parameters.Block == null && definitionRefinements == null && gen.Profiler == null && diff --git a/Src/Ruby/Compiler/AstGenerator.cs b/Src/Ruby/Compiler/AstGenerator.cs index 2df842a60..443894a6b 100644 --- a/Src/Ruby/Compiler/AstGenerator.cs +++ b/Src/Ruby/Compiler/AstGenerator.cs @@ -432,6 +432,10 @@ public Parameters Parameters { // that makes it calls them, so a light frame of the method keeps its stack check (MethodDefinition.LightFrame.MakesCalls). internal bool HasHashCallingKeys; + // The splat that passes the method's rest parameter on where nothing can see the Array again (ForwardedRest): its site + // says the splat is fresh, and a rest parameter of the callee takes the Array itself. + internal SplattedArgument ForwardedRestSplat; + // The slot the method's literals take their parked Procs from (BlockDefinition), set by MethodDefinition before the // body is transformed if the method may have one at all; it is disabled afterwards if the body turns out not to qualify. internal ParkedScopeSlot ParkSlot; diff --git a/Util/bench/forward-bytes.rb b/Util/bench/forward-bytes.rb new file mode 100644 index 000000000..e4701ccd9 --- /dev/null +++ b/Util/bench/forward-bytes.rb @@ -0,0 +1,33 @@ +# Bytes allocated per call of argument-forwarding wrappers: a rest parameter splatted on (`*args`, `*args, &b`), +# `...`, into a callee with and without a rest parameter of its own (Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs, +# RubyCallFlags.HasFreshSplat; IR_FORWARD_REST=0 turns the forwarding of a dead rest off). IronRuby only. +# IR_CONFIG=Release ./ir.sh Util/bench/forward-bytes.rb +class W + def raw(a = 0) = a + def rest_t(*r) = r.size + def w_pass(a) = raw(a) + def w_splat(*args) = raw(*args) + def w_splat_rest(*args) = rest_t(*args) + def w_sb(*args, &b) = raw(*args, &b) + def w_sbr(*args, &b) = rest_t(*args, &b) + def w_fwd(...) = raw(...) + def w_fwd_rest(...) = rest_t(...) +end +o = W.new +N = 200_000 +def bytes = System::GC.GetAllocatedBytesForCurrentThread +def m(name, n) + yield; yield + b = bytes; i = 0 + while i < n; yield; i += 1; end + printf "%-40s %6.1f B per call\n", name, (bytes - b).to_f / n +end +m("rest_t(1)", N) { o.rest_t(1) } +m("w_pass(1) -> raw(a)", N) { o.w_pass(1) } +m("w_splat(1) -> raw(*args)", N) { o.w_splat(1) } +m("w_splat_rest(1) -> rest_t(*args)", N) { o.w_splat_rest(1) } +m("w_sb(1) -> raw(*args, &b)", N) { o.w_sb(1) } +m("w_sbr(1) -> rest_t(*args, &b)", N) { o.w_sbr(1) } +m("w_sb(1) { } -> raw(*args, &b)", N) { o.w_sb(1) { } } +m("w_fwd(1) -> raw(...)", N) { o.w_fwd(1) } +m("w_fwd_rest(1) -> rest_t(...)", N) { o.w_fwd_rest(1) } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 9105a7a66..b9d45558e 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1624,6 +1624,42 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/forward (2026-11-27) - a rest parameter passed on where nothing can see it again is the callee's + rest parameter; a block-passing call's hoisted splat is fresh** (gap 36 and gap 16's second part; + `IR_FORWARD_REST=0` turns the first off) - timed, not gated. Bytes a call + (`Util/bench/forward-bytes.rb`, new), base -> new: `def w(...) = raw(...)` 212 -> 116, + `w(...) = rest_t(...)` (a callee with a rest) 309 -> 116, `w(*args, &b) = raw(*args, &b)` 227 -> 132, + with a rest callee 312 -> 120, `w(*args) = rest_t(*args)` 214 -> 120, `w_splat(1) { }` 420 -> 325; + `w(*args) = raw(*args)` (one Array, the rest itself) 119 -> 118. + Two copies went. (1) `f(*a, &b)` - and `n(...)`, which is `n(*?fwd?, &?fwdblk?)` - hoists its arguments + before the block argument (MRI's order) and expanded the splat into a new Array there that the site + did not call fresh, so a rest callee copied it again; it is fresh now (`MethodCall`, the hoisted + `#splat`), and a splat that is fresh already is not copied at all. (2) `ForwardedRest` (new, the + method's AST before its body is transformed): the one splat of the method's rest parameter that may + call its Array fresh - the only reference to the parameter (no other read, assignment or + `defined?`), not in a loop or a block, and nothing that can reach the frame: no block literal (a + Proc's `#binding`), no `binding`/`eval`/`local_variable_*` call, no zsuper, no `retry`/`redo`. + `Arguments` sets the site's fresh flag for that splat only. By the same rules (a prism count) it + takes 25 of the prelude's 137 methods with a rest or `(...)`, and 216 of 744 in `ironruby/` and + `ruby/4.0`. + Instructions a call (`count.sh`, `Util/bench/prelude-cost.rb`): `w_splat` (`*args, &block`) 6223 -> + 5742 (0.92), `w_fwd` 6163 -> 5613 (0.91); controls `w_pass`, `w_anon`, `w_opt` move by +-70 between + runs in both directions (0.986-1.014), the counter's floor here. Time (`ab.rb`, six rounds): + `w_splat` 0.87, `w_fwd` 0.84, `w_pass` overlapping. + Checked: `Util/splat-pass-matrix.rb` section 10b (new, 21 rows: a rest callee changing and keeping + the Array, two calls keeping two Arrays, a chain of forwards, the rest escaping or changed first, a + binding, a loop, a block literal, a block passed on, `...` with keywords and a block and without, + ruby2_keywords with keywords and with a Hash positional, send, public_send, `super(*a)`, zsuper, + method_missing, an empty rest), block-pass, light-rest, keyword-light, block-given: CRuby's output + and the unchanged build's with the JIT on, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, and the unchanged + build's with `IR_LIGHT_FRAMES=0`, `IR_FORWARD_REST=0` and `IR_SPLAT_REST=0`; hot-shapes the unchanged + build's in every mode (its known row against CRuby). ruby/spec language/send, method, delegation, + super: the same on both builds (send's one error is the known `into`/`to` wording). + For the gate: the callee may keep the caller's rest Array; the analysis is what says the caller + cannot see it again - read `ForwardedRest`'s list of what can reach a frame. A block-passing call's + retry (Ruby 1.8's `retry` from the block) would run the call again with the hoisted Array; prism + refuses `retry` outside a rescue, so it cannot be written. + - **perf/timeout (2026-11-27) - `Timeout.timeout` wakes its watcher thread only when it has to** (`Src/StdLib/ironruby/timeout.rb`, an override that loads CRuby's file as it is and redefines two methods of `Timeout::State`) - timed, not gated. A raise rescued through `Timeout.timeout` cost diff --git a/Util/splat-pass-matrix.rb b/Util/splat-pass-matrix.rb index 7d36b3b74..c3367a16f 100644 --- a/Util/splat-pass-matrix.rb +++ b/Util/splat-pass-matrix.rb @@ -446,6 +446,54 @@ class PrivSubF < PubF; private :pub; end t('a made splat recursing') { |i| deep_fresh(100 + i % 3, 0).size } t('a made splat a million deep', 1) { dfresh(1_000_000, 0) } +# ---------------------------------------------------------------- 10b. a rest parameter passed on +# `def w(*a) = n(*a)' where nothing can see `a' again gives n's rest parameter the Array itself +# (ForwardedRest, RubyCallFlags.HasFreshSplat; IR_FORWARD_REST=0 turns it off). What n keeps or changes must +# not reach the caller's own list, another call's, or a variable of w that something still reads. + +def f_own(*a) = own(*a) +def f_keep(*a) = keep(*a) +def f_chain2(*b) = own(*b) +def f_chain(*a) = f_chain2(*a) +def f_escape(*a) = ($esc = a; own(*a)) +def f_mut(*a) = (a << :mut; own(*a)) +def f_bind(*a) = (bd = binding; r = own(*a); [r, bd.local_variable_get(:a)]) +def f_loop(*a) = (i = 0; r = []; while i < 2; r << keep(*a); i += 1; end; [r, r[0].equal?(r[1])]) +def f_blk(*a) = own(*a).map { |x| x } +def f_pass(*a, &b) = yielder(*a, &b) +def yielder(*r) = (r << yield; r) +def kwt(*r, **k, &b) = [r, k, b ? b.call : nil] +def f_dots(...) = kwt(...) +ruby2_keywords def f_r2(*a) = kwt(*a) +def f_send(*a) = send(:own, *a) +def f_pub(*a) = public_send(:own, *a) +class FwA; def m(*r) = (r << :a; r); end +class FwB < FwA; def m(*a) = super(*a); end +class FwZ < FwA; def m(*a) = super; end +class FwMM; def method_missing(n, *a) = own(*a); def respond_to_missing?(*) = true; end +def f_ret(*a) = a.size +t('forward into a rest that changes it') { |i| x = [i % 2]; r = f_own(*x); [r, x] } +t('forward a made splat') { |i| r = f_own(i % 2, 3); r } +t('two calls keep two Arrays') { $kept.clear; f_keep(1); f_keep(2); [$kept, $kept[0].equal?($kept[1])] } +t('a chain of forwards') { |i| x = [i % 2]; [f_chain(*x), x] } +t('the rest escaping first') { |i| r = f_escape(i % 2); [r, $esc] } +t('the rest changed first') { |i| x = [i % 2]; [f_mut(*x), x] } +t('a binding sees the rest') { |i| f_bind(i % 2) } +t('in a loop') { |i| f_loop(i % 2) } +t('with a block literal') { |i| f_blk(i % 2) } +t('with a block passed on') { |i| f_pass(i % 2) { :y } } +t('... with keywords and a block') { |i| f_dots(i % 2, k: 1) { :b } } +t('... without keywords') { |i| f_dots(i % 2) } +t('ruby2_keywords passes keywords on') { |i| f_r2(i % 2, k: 2) } +t('ruby2_keywords, a Hash positional') { |i| f_r2(i % 2, {k: 2}) } +t('send') { |i| x = [i % 2]; [f_send(*x), x] } +t('public_send') { |i| x = [i % 2]; [f_pub(*x), x] } +t('super(*a)') { |i| x = [i % 2]; [FwB.new.m(*x), x] } +t('zsuper') { |i| x = [i % 2]; [FwZ.new.m(*x), x] } +t('method_missing') { |i| x = [i % 2]; [FwMM.new.nothing(*x), x] } +t('a callee without a rest') { |i| f_ret(i, 2) } +t('an empty rest') { f_own } + # ---------------------------------------------------------------- 11. refinements (last: `using' keeps every method # defined after it in this file out of light frames) From fb5791db37241cabfdaabce9dbd6682a3b1f4194 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:03:47 +0000 Subject: [PATCH 129/439] Ledger: the two-class `!=' site's two speeds are the CLR's dynamic PGO (gap 12) `recv != other' over two classes took 59-102 ns from one process to the next on both builds. Alone it is 60-64 ns every time; after a `==' site and a call site on one of the classes, 61-104. With DOTNET_TieredPGO=0 it is 67-75 in every process, with DOTNET_TieredCompilation=0 66-71. The site holds a rule per class, so every other call misses its target and runs .NET's UpdateAndExecute3, tiered and instrumented code that the calls before it trained (dotnet-trace: 20-25% of the loop): its guarded devirtualization of the rule delegates guesses well or badly. Recorded, not fixed; the lever is IronRuby's, one rule for both classes. Bounce in ten processes per build is level with and without DLR patch 0111 (median 495 and 498 ms) and bimodal on neither. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Util/perf/LEDGER.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index ada8a7af2..a0a7a8da1 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -915,6 +915,19 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Round of 2026-11-27 (see Landed, perf/twospeed, not gated): found and fixed - an interpreted shared rule left ahead of its compiled one in a site's rules, run on every call to fail (DLR patch 0111). `neq2` still varies 59-102 ns on both builds, which is something else. + Round of 2026-11-27, second (perf/twospeed2, a finding, no code): `neq2`'s spread is the CLR's dynamic PGO, + not IronRuby's or the DLR's. Alone `neq2` is 60-64 ns in 12 of 12 processes; after `eq1` and `call1` (either + alone does not do it) 61-104. With `DOTNET_TieredPGO=0` it is 67-75 in 8 of 8, with + `DOTNET_TieredCompilation=0` 66-71: no slow process and no fast one. The site holds two rules, one a class + (the negated-builtin `!=` rule is per class, not shared), so every other call misses its target and runs + `System.Dynamic.UpdateDelegates.UpdateAndExecute3` (dotnet-trace: 20-25% of the loop, the rules 13-19%) - + .NET's own code, tiered and instrumented, which the calls before it trained: guarded devirtualization of the + rule delegates it invokes then guesses well (62 ns) or badly (100 ns) depending on what it saw. The rules and + the loop are dynamic methods, not tiered. Left: the lever is IronRuby's - one rule for both classes (a + version set, as a shared rule has), so that the site never misses; that is a change to how `!=`/`==` on + plain objects is bound (#215), for its own step. Bounce, 10 processes each (`harness.rb Bounce 20 1500`, + median of the last 10 iterations, ms): with DLR patch 0111 473-511 (median 495), without 477-507 (498): not + bimodal on either, and level. 13. **Calling an iterator at all costs twice what it does in CRuby**: `a.each { |x| s += x }` over one element from a method is 166 ns against 79, `n.times` 182 against 88, `a.map` 194 against 101, and `a.any? { |x| x > 1000 }` 414 against 67, 438 against From c82322a4de2d66f259d096b324077764db2253b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:07:23 +0000 Subject: [PATCH 130/439] Ledger: perf/crubydiff's second round, the causes of the baseline rows What each fix turned "same" (14,255 lines differing from CRuby across the matrices -> 414), what is left and why, and what the gate should look at. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 0b2466588..b0c347e2c 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1688,6 +1688,46 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has sets ScopeRead) and method_missing's reason - and Module#dup/#clone, which now copies before initialize_copy (anything that relied on Module#initialize_copy copying, e.g. a re-run initialize_copy, gets Kernel's). + Second round (2026-11-27, on b887bc1): the causes of the gate's "baseline" rows. All matrices, + as built, this branch against b887bc1: lines differing from CRuby 14,255 -> 414, baseline + matrices 28 -> 19 (chr, format-c, format-c-bytes, format, pack, unpack, ungetc, encode, + string-methods, value-object, hash-literal, interpolation, hot-shapes, light-entry, struct now + same). One commit per cause, each with CRuby 4.0's output as a registered IronRuby.Tests case: + - Integer#chr and String#<< of a code above 0xFF in a single byte encoding: "invalid codepoint + 0x100 in US-ASCII" (CRuby 4.0's onigmo), and UTF-32 from 0x80000000 up invalid too; "out of + char range" stays for << onto BINARY/US-ASCII and argument-less chr. chr-matrix 9,011 lines. + Integer_ChrSingleByte1 (Integer_ChrMultibyte1's expectation regenerated from 4.0.10). + - %c of such a code: "invalid character" (BINARY and US-ASCII keep "out of char range"). + format-c and format-c-bytes, 4,682 lines. Sprintf_CharacterSingleByte1. + - Math.log(x, base) as rb_math_log (pole first, log2 quotient plus the shifted bits, a size_t), + atan2/hypot converting the second argument first, Math.sqrt of a Complex. math-matrix 97 -> 37. + Math_LogBaseAndOrder1. + - A respond_to? that claims to_ary/to_str/to_hash without the method, default method_missing: + no conversion (rb_check_funcall), in the binder's rule and the prelude's try_convert. + array2 19 rows. Protocol_RespondToWithoutMethod1. + - Integer#fdiv of a coerced result as a Float; Integer#remainder (dividend for an infinite + divisor, Bignum coercing with remainder); Float::INFINITY.divmod's "Infinity"; Rational#coerce's + class name and Numeric#divmod's modulo first. coerce-matrix 22 -> 4. Four tests. + - Kernel#Integer: sign-only strings "invalid value" before the radix, message via rb_inspect; + Rational()/Complex() naming true/false. numeric-conversion 18 -> 2. Two tests. + - sprintf directives cut short: "malformed format string", after fetching %1$ / %'s + argument. format-matrix 16 -> 0. Sprintf_MalformedEnd1. + - Array#pack floats take a Numeric only (rb_to_float); unpack's "@" at the end counts 1; + String#undump passes \s and \0 through; String#encode's options keywords only; String#tr! + checks encodings before frozenness (a leftover of the first round). Five tests. + Left, with the reason: the "from nil to integer" / "gives NilClass" wording ruby/spec pins the + other way (array2 63, math 37, numeric-conversion 2); `x << 2**64`, a NoMemoryError in CRuby + (coerce 4); 42.compare_to (deliberate interop); ffi-matrix (CRuby does not exit 0); + regexp-binary-ctype's ISO-8859-1 column (25 rows: the regexp translator would need Onigmo's + ISO-8859-1 ctype table beside its ASCII one); emacs-mule (CRuby's own oddities); strftime + (%:% and friends), strptime, caller and thread-backtrace frames, marshal, converter and + io-conversion messages, stdre's URI regexp, eval's regexp warning, Enumerator::Lazy's prepended + helper in its ancestors, int-matrix's (2**100).equal?, the heredoc part's frame line and + `frozen << Object.new` (the binder converts first) - each a cause of its own, one or a few rows. + For the gate: callable-parameters-matrix shows a DIFF only because ruby4.rb's lines moved + (method(:puts).to_proc.source_location; CRuby says nil on both); Kernel#Integer(String) now + takes the context (one more argument on that fast path); the binder's conversion rule for an + overridden respond_to? resolves to_xxx and method_missing at build time. - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy From 103c7414fa82d128a1500b1ab452506240970e42 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:08:16 +0000 Subject: [PATCH 131/439] byteindex/byterindex from an offset other than 0 walk from the last search of the string, through a map shared with StringScanner #byteindex and #byterindex with a String needle on a valid UTF-8 String that is not all ASCII walked its characters from the start to the byte offset on every call, and counted the UTF-8 bytes of the prefix the answer ends at: a loop pos = s.byteindex(",", pos + 1) was quadratic, 79-94 ms over 100 KB of UTF-8 (CRuby 0.35 ms). The scanner's byte <-> CLR map (round three) moves to Builtins/Utf8OffsetMap.cs and serves both. For the searches it is shared by the readers of one snapshot of the string's characters, kept in a ConditionalWeakTable keyed by that snapshot as MutableString's character index tables are (a changed string has a new snapshot); its UTF-8 length is counted only when an offset from the end asks for it. An offset of 0 or none makes no map and takes the code it took before, so a one-off search pays nothing; a single-byte receiver (ASCII, BINARY) never comes here. The scanner keeps its own map per subject as before. Loop over 10 KB / 100 KB of UTF-8: 2.8 / 79-94 ms -> 0.23-0.29 / 2.4 ms (CRuby 0.034 / 0.35); the same loop over ASCII 0.28 / 2.64 ms on both builds. Util/string-search-matrix.rb gains the subject changed between scans (setbyte, []=, insert, replace, force_encoding, a stray byte appended) and byteindex/byterindex loops and every-offset sweeps over long ASCII, UTF-8, astral, BINARY and US-ASCII strings, with a change midway (60,164 rows): this build prints what the base prints, switch on and off; the base differs from CRuby in 5 of the new rows (the scanner after its subject was replaced by a shorter string or edited inside a character), as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Libraries/Builtins/MutableStringOps.cs | 20 ++- Src/Libraries/Builtins/Utf8OffsetMap.cs | 146 +++++++++++++++++++ Src/Libraries/StringScanner/StringScanner.cs | 139 ++++-------------- Util/bench/strsearch-shapes.rb | 8 + Util/string-search-matrix.rb | 47 ++++++ 5 files changed, 243 insertions(+), 117 deletions(-) create mode 100644 Src/Libraries/Builtins/Utf8OffsetMap.cs diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 0380cd490..f808d8df3 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -4523,6 +4523,7 @@ private static bool TryByteSearch(MutableString/*!*/ self, object[]/*!*/ args, b } ReadOnlySpan chars = default(ReadOnlySpan); + Utf8OffsetMap map = null; bool singleByte = self.DetectSingleByteCharacters(); if (!singleByte) { if (self.Encoding != RubyEncoding.UTF8 || self.ContainsInvalidCharacters()) { @@ -4556,18 +4557,30 @@ private static bool TryByteSearch(MutableString/*!*/ self, object[]/*!*/ args, b } else { // The UTF-8 size of the whole string is counted only for an offset from the end: // the walk to a positive offset finds out by itself whether it is past the end. + // An offset other than 0 is usually the last answer plus one, in a loop over the + // string: the walk then goes from where the last one stopped, through the map shared + // by every search of this snapshot of the characters, instead of from the start (93 ms + // for such a loop over 100 KB of UTF-8, CRuby 0.36). The first call, or one from 0, + // makes no map. int clrOffset; if (args.Length < 2) { clrOffset = reverse ? chars.Length : 0; } else { int offset = (int)args[1]; + if (offset != 0) { + map = Utf8OffsetMap.For(self.ConvertToString()); + if (map.Text.Length != chars.Length) { + // the string changed under the search (another thread) + return false; + } + } if (offset < 0) { - offset += Encoding.UTF8.GetByteCount(chars); + offset += map.ByteLength; if (offset < 0) { return true; } } - clrOffset = Utf8OffsetToClrIndex(chars, offset); + clrOffset = (map != null) ? map.ClrOf(offset) : Utf8OffsetToClrIndex(chars, offset); if (clrOffset == -2) { if (!reverse) { return true; @@ -4590,7 +4603,8 @@ private static bool TryByteSearch(MutableString/*!*/ self, object[]/*!*/ args, b // the string changed under the search (another thread): the helper is the one to ask return false; } - result = ScriptingRuntimeHelpers.Int32ToObject(Encoding.UTF8.GetByteCount(chars.Slice(0, foundClr))); + int foundByte = (map != null) ? map.ByteOf(foundClr) : -1; + result = ScriptingRuntimeHelpers.Int32ToObject(foundByte >= 0 ? foundByte : Encoding.UTF8.GetByteCount(chars.Slice(0, foundClr))); return true; } diff --git a/Src/Libraries/Builtins/Utf8OffsetMap.cs b/Src/Libraries/Builtins/Utf8OffsetMap.cs new file mode 100644 index 000000000..49ada5da6 --- /dev/null +++ b/Src/Libraries/Builtins/Utf8OffsetMap.cs @@ -0,0 +1,146 @@ +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Apache License, Version 2.0, please send an email to + * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound + * by the terms of the Apache License, Version 2.0. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; + +namespace IronRuby.Builtins { + + /// + /// Byte offsets into the UTF-8 form of a string of valid UTF-16 characters (one snapshot of a + /// MutableString's characters, ConvertToString's), and back. Offsets are converted by walking the + /// characters from a cursor - the last offset converted - so a reader that moves forward through + /// the string (StringScanner, a loop of String#byteindex from the last answer) pays about the + /// distance it moved, where counting from the start each time made such a loop quadratic. + /// The caller sees to it that the text has no unpaired surrogate (the string is valid UTF-8). + /// + internal sealed class Utf8OffsetMap { + internal readonly string/*!*/ Text; + private int _byteLength = -1; + private int _hasPairs = -1; + + // the byte offset in the high half, the CLR index in the low half: one field, so that threads + // sharing a map can only see a cursor that was right at some point + private long _cursor; + + // Keyed by the immutable snapshot, as MutableString's character index tables are: a string + // that changes gets a new snapshot, and a snapshot nobody holds takes its map with it. + private static readonly ConditionalWeakTable _maps = new ConditionalWeakTable(); + + internal Utf8OffsetMap(string/*!*/ text) { + Text = text; + } + + /// The map shared by every reader of this snapshot (String#byteindex and #byterindex). + internal static Utf8OffsetMap/*!*/ For(string/*!*/ text) { + return _maps.GetValue(text, t => new Utf8OffsetMap(t)); + } + + internal int ByteLength { + get { + int length = _byteLength; + if (length < 0) { + _byteLength = length = Encoding.UTF8.GetByteCount(Text); + } + return length; + } + } + + /// Whether a character of the text is a surrogate pair (two CLR chars for one Ruby character). + internal bool HasPairs { + get { + int pairs = _hasPairs; + if (pairs < 0) { + pairs = 0; + foreach (char c in Text) { + if (Char.IsLowSurrogate(c)) { + pairs = 1; + break; + } + } + _hasPairs = pairs; + } + return pairs != 0; + } + } + + /// + /// The CLR index of byte offset : -1 when it is inside a character, + /// -2 when it is past the end (or negative). + /// + internal int ClrOf(int byteOffset) { + if (byteOffset < 0) { + return -2; + } + int b, c; + if (Seek(true, byteOffset, out b, out c)) { + return c; + } + return (b < byteOffset && c >= Text.Length) ? -2 : -1; + } + + /// The byte offset of CLR index , or -1 when it is between the halves of a pair. + internal int ByteOf(int clrIndex) { + if (clrIndex < 0 || clrIndex > Text.Length) { + return -1; + } + int b, c; + return Seek(false, clrIndex, out b, out c) ? b : -1; + } + + private bool Seek(bool byBytes, int target, out int b, out int c) { + long cursor = Volatile.Read(ref _cursor); + b = (int)(cursor >> 32); + c = (int)cursor; + int at = byBytes ? b : c; + if (target < at && target < at / 2) { + b = c = 0; + at = 0; + } + string text = Text; + if (target >= at) { + while ((byBytes ? b : c) < target && c < text.Length) { + char ch = text[c]; + if (ch < 0x80) { + b += 1; c += 1; + } else if (ch < 0x800) { + b += 2; c += 1; + } else if (Char.IsHighSurrogate(ch)) { + b += 4; c += 2; + } else { + b += 3; c += 1; + } + } + } else { + while ((byBytes ? b : c) > target) { + char ch = text[c - 1]; + if (ch < 0x80) { + b -= 1; c -= 1; + } else if (ch < 0x800) { + b -= 2; c -= 1; + } else if (Char.IsLowSurrogate(ch)) { + b -= 4; c -= 2; + } else { + b -= 3; c -= 1; + } + } + } + Volatile.Write(ref _cursor, ((long)b << 32) | (uint)c); + return (byBytes ? b : c) == target; + } + } +} diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index a992ed569..b9896a691 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -157,118 +157,29 @@ public static object MustCVersion(object self) { #region byte / character bookkeeping - /// - /// The scan pointer is a byte offset and the regex engine matches CLR characters. For a - /// subject that is valid UTF-8 and not all ASCII, converting between the two used to copy - /// out and count everything before the offset, in both directions, and to read the subject - /// as bytes (GetByteCount, GetBinarySlice, GetByte), which switched it from characters to - /// bytes - and the next match switched it back, decoding the whole of it: a scan of 100 KB - /// of UTF-8 text word by word took 8.4 s (CRuby: 2 ms). The map converts offsets by walking - /// the subject's characters from a cursor, the last offset converted; a scanner moves - /// forward, so a step costs about the length of the token. It is made for one snapshot of - /// the subject's characters (ConvertToString answers the same string until the subject - /// changes, and a new one after) and dropped when that changes. - /// - private sealed class Utf8Map { - internal readonly string/*!*/ Text; - internal readonly int ByteLength; - internal readonly bool HasPairs; - - // the byte offset in the high half, the CLR index in the low half: one field, so that a - // scanner shared between threads can only see a cursor that was right at some point - private long _cursor; - - internal Utf8Map(string/*!*/ text) { - Text = text; - ByteLength = Encoding.UTF8.GetByteCount(text); - HasPairs = text.Length != CountRunes(text); - } - - private static int CountRunes(string/*!*/ text) { - int count = 0; - for (int i = 0; i < text.Length; i++) { - if (!Char.IsLowSurrogate(text[i])) { - count++; - } - } - return count; - } - - /// The CLR index of byte offset , or -1 when it is inside a character. - internal int ClrOf(int byteOffset) { - if (byteOffset < 0 || byteOffset > ByteLength) { - return -1; - } - int b, c; - return Seek(true, byteOffset, out b, out c) ? c : -1; - } - - /// The byte offset of CLR index , or -1 when it is between the halves of a pair. - internal int ByteOf(int clrIndex) { - if (clrIndex < 0 || clrIndex > Text.Length) { - return -1; - } - int b, c; - return Seek(false, clrIndex, out b, out c) ? b : -1; - } - - private bool Seek(bool byBytes, int target, out int b, out int c) { - long cursor = Volatile.Read(ref _cursor); - b = (int)(cursor >> 32); - c = (int)cursor; - int at = byBytes ? b : c; - if (target < at && target < at / 2) { - b = c = 0; - at = 0; - } - string text = Text; - if (target >= at) { - while ((byBytes ? b : c) < target) { - char ch = text[c]; - if (ch < 0x80) { - b += 1; c += 1; - } else if (ch < 0x800) { - b += 2; c += 1; - } else if (Char.IsHighSurrogate(ch)) { - b += 4; c += 2; - } else { - b += 3; c += 1; - } - } - } else { - while ((byBytes ? b : c) > target) { - char ch = text[c - 1]; - if (ch < 0x80) { - b -= 1; c -= 1; - } else if (ch < 0x800) { - b -= 2; c -= 1; - } else if (Char.IsLowSurrogate(ch)) { - b -= 4; c -= 2; - } else { - b -= 3; c -= 1; - } - } - } - Volatile.Write(ref _cursor, ((long)b << 32) | (uint)c); - return (byBytes ? b : c) == target; - } - } - - private Utf8Map _map; + // The scan pointer is a byte offset and the regex engine matches CLR characters. For a subject that is + // valid UTF-8 and not all ASCII, converting between the two used to copy out and count everything + // before the offset, in both directions, and to read the subject as bytes (GetByteCount, + // GetBinarySlice, GetByte), which switched it from characters to bytes - and the next match switched + // it back, decoding the whole of it: a scan of 100 KB of UTF-8 text word by word took 8.4 s (CRuby: + // 2 ms). The scanner keeps a Utf8OffsetMap (Builtins) for the subject's current snapshot of + // characters instead, and drops it when the subject changes (ConvertToString answers a new string). + + private Utf8OffsetMap _map; private string _unmappedText; // IR_FAST_SEARCH, read here so that the check every scan makes needs no other class private static readonly bool MapEnabled = MutableStringOps.FastSearchEnabled; // the map _match's CLR offsets are offsets into; null when the match was not made through one - private Utf8Map _matchMap; + private Utf8OffsetMap _matchMap; /// /// The map for the subject as it is now, or null when the subject is not one it is for: /// not UTF-8, all ASCII (bytes and CLR characters are one for one, which the paths below /// already know), or not valid. IR_FAST_SEARCH=0 makes none. /// - private Utf8Map Map { + private Utf8OffsetMap Map { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { // What every scan asks, four times a token: one flag test, which answers for a subject @@ -282,14 +193,14 @@ private Utf8Map Map { } [MethodImpl(MethodImplOptions.NoInlining)] - private Utf8Map MapFor(MutableString/*!*/ subject) { + private Utf8OffsetMap MapFor(MutableString/*!*/ subject) { if (!MapEnabled || subject.Encoding != RubyEncoding.UTF8 || subject.IsAscii()) { return null; } // a string held as bytes is decoded once, as a match would subject.PrepareForCharacterRead(); string text = subject.ConvertToString(); - Utf8Map map = _map; + Utf8OffsetMap map = _map; if (map != null && ReferenceEquals(map.Text, text)) { return map; } @@ -297,12 +208,12 @@ private Utf8Map MapFor(MutableString/*!*/ subject) { _unmappedText = text; return null; } - return _map = new Utf8Map(text); + return _map = new Utf8OffsetMap(text); } private int ByteLength { get { - Utf8Map map = Map; + Utf8OffsetMap map = Map; return (map != null) ? map.ByteLength : _scanString.GetByteCount(); } } @@ -311,7 +222,7 @@ private int ByteLength { if (count <= 0) { return MutableString.CreateEmpty(_scanString.Encoding); } - Utf8Map map = Map; + Utf8OffsetMap map = Map; if (map != null) { MutableString mapped = ByteSliceMapped(map, start, count); if (mapped != null) { @@ -322,7 +233,7 @@ private int ByteLength { } [MethodImpl(MethodImplOptions.NoInlining)] - private MutableString ByteSliceMapped(Utf8Map/*!*/ map, int start, int count) { + private MutableString ByteSliceMapped(Utf8OffsetMap/*!*/ map, int start, int count) { int clrStart = map.ClrOf(start); int clrEnd = (clrStart >= 0) ? map.ClrOf(start + count) : -1; return (clrEnd >= 0) ? MutableString.Create(map.Text.Substring(clrStart, clrEnd - clrStart), _scanString.Encoding) : null; @@ -347,7 +258,7 @@ private int CharWidthAtPosition() { if (available <= 0) { return 0; } - Utf8Map map = Map; + Utf8OffsetMap map = Map; if (map != null) { int clr = map.ClrOf(_position); if (clr >= 0) { @@ -388,7 +299,7 @@ private int CharacterCountOf(int byteIndex) { if (_scanString.DetectSingleByteCharacters()) { return byteIndex; } - Utf8Map map = Map; + Utf8OffsetMap map = Map; if (map != null) { int clr = map.ClrOf(byteIndex); if (clr >= 0) { @@ -421,7 +332,7 @@ private int CharIndexOf(int byteIndex) { // every scan cost a pass over everything already scanned. return byteIndex; } - Utf8Map map = Map; + Utf8OffsetMap map = Map; if (map != null) { int clr = map.ClrOf(byteIndex); if (clr >= 0) { @@ -505,7 +416,7 @@ private MatchData CurrentMatch { /// character and the old path is to decide. ///
[MethodImpl(MethodImplOptions.NoInlining)] - private int MatchRegexMapped(Utf8Map/*!*/ map, RubyRegex/*!*/ pattern, bool anchored, bool advance) { + private int MatchRegexMapped(Utf8OffsetMap/*!*/ map, RubyRegex/*!*/ pattern, bool anchored, bool advance) { int clrPosition = map.ClrOf(_position); if (clrPosition < 0) { return -1; @@ -541,7 +452,7 @@ private int MatchRegexMapped(Utf8Map/*!*/ map, RubyRegex/*!*/ pattern, bool anch private bool MatchRegex(RubyRegex/*!*/ pattern, bool anchored, bool advance, bool lazyGroups) { ClearMatch(); - Utf8Map map = Map; + Utf8OffsetMap map = Map; if (map != null) { int mapped = MatchRegexMapped(map, pattern, anchored, advance); if (mapped >= 0) { @@ -602,7 +513,7 @@ private bool MatchLiteral(MutableString/*!*/ pattern, bool anchored, bool advanc if (anchored && pattern.IsAscii()) { // The usual #skip("{"): an ASCII pattern's characters are its bytes, so it can be // compared where it stands instead of being copied out to a byte array first. - Utf8Map map = Map; + Utf8OffsetMap map = Map; int clr = (map != null) ? map.ClrOf(_position) : -1; if (clr >= 0) { string literal = pattern.ToString(); @@ -712,7 +623,7 @@ public static MutableString GetMatchSubgroup(ConversionStorage/*!*/ fixnumC return null; } int start, end; - Utf8Map map = self.Map; + Utf8OffsetMap map = self.Map; if (map != null && map == self._matchMap) { if (!self.CurrentMatch.TryGetGroupClrOffsets(subgroup, out start, out end)) { return null; @@ -797,7 +708,7 @@ public static bool BeginningOfLine(StringScanner/*!*/ self) { if (self._position == 0) { return true; } - Utf8Map map = self.Map; + Utf8OffsetMap map = self.Map; int clr = (map != null) ? map.ClrOf(self._position) : -1; if (clr > 0) { return map.Text[clr - 1] == '\n'; diff --git a/Util/bench/strsearch-shapes.rb b/Util/bench/strsearch-shapes.rb index ad58d636f..baa064e59 100644 --- a/Util/bench/strsearch-shapes.rb +++ b/Util/bench/strsearch-shapes.rb @@ -174,6 +174,11 @@ def eq = (@other == @short ? 1 : 0) # StringScanner over 10 KB, one call a whole pass (round three: the UTF-8 subject was quadratic) def ss_words_u = (ss = StringScanner.new(SS_U); n = 0; until ss.eos?; ss.skip(/\s+/); n += 1 if ss.scan(/\S+/); end; n + ss.charpos) def ss_until_u = (ss = StringScanner.new(SS_U); n = 0; while ss.scan_until(/,/); n += ss.matched_size; end; n) + # String#byteindex from the last answer, over 10 KB (round four: from an offset other than 0 it walked + # the characters from the start on every call) + def bidx_loop_u = (pos = 0; n = 0; while (pos = SS_U.byteindex(",", pos)); n += pos; pos += 1; end; n) + def bidx_loop_a = (pos = 0; n = 0; while (pos = SS_A.byteindex(",", pos)); n += pos; pos += 1; end; n) + def bridx_loop_u = (pos = SS_U.bytesize; n = 0; while pos >= 0 && (pos = SS_U.byterindex(",", pos)); n += pos; pos -= 1; end; n) def ss_words_a = (ss = StringScanner.new(SS_A); n = 0; until ss.eos?; ss.skip(/\s+/); n += 1 if ss.scan(/\S+/); end; n + ss.charpos) end @@ -326,3 +331,6 @@ def t(name, n) t("ss_words_u", SCAN) { |n| i = 0; s = 0; while i < n; s += h.ss_words_u; i += 1; end; s } t("ss_until_u", SCAN) { |n| i = 0; s = 0; while i < n; s += h.ss_until_u; i += 1; end; s } t("ss_words_a", SCAN) { |n| i = 0; s = 0; while i < n; s += h.ss_words_a; i += 1; end; s } +t("bidx_loop_u", SCAN) { |n| i = 0; s = 0; while i < n; s += h.bidx_loop_u; i += 1; end; s } +t("bidx_loop_a", SCAN) { |n| i = 0; s = 0; while i < n; s += h.bidx_loop_a; i += 1; end; s } +t("bridx_loop_u", SCAN) { |n| i = 0; s = 0; while i < n; s += h.bridx_loop_u; i += 1; end; s } diff --git a/Util/string-search-matrix.rb b/Util/string-search-matrix.rb index 621033819..fea29d0ce 100644 --- a/Util/string-search-matrix.rb +++ b/Util/string-search-matrix.rb @@ -203,3 +203,50 @@ def ss_state(ss) ss = StringScanner.new(subject.dup); ss.scan(/\S+/); ss.terminate; t = ss_state(ss); ss.reset; [[t, ss_state(ss)].inspect, nil, nil] end end + +puts "== StringScanner with the subject changed between scans (round four)" +SS_SUBJECTS.each do |sname, subject| + [["setbyte(0, 0x41)", ->(s) { s.setbyte(0, 0x41) }], ["setbyte(-1, 0x7A)", ->(s) { s.setbyte(-1, 0x7A) }], + ["setbyte(3, 0xC3)", ->(s) { s.setbyte(3, 0xC3) }], ["[0] = 'ü'", ->(s) { s[0] = "ü" }], ["[2, 3] = 'X'", ->(s) { s[2, 3] = "X" }], + ["[-1] = '😀'", ->(s) { s[-1] = "😀" }], ["insert(1, 'ñ')", ->(s) { s.insert(1, "ñ") }], ["replace('ö o')", ->(s) { s.replace("ö o") }], + ["force_encoding(BINARY)", ->(s) { s.force_encoding("BINARY") }], ["<< 0xFF byte", ->(s) { s << "\xFF".b.force_encoding(s.encoding) }], + ].each do |cname, change| + try("ss[#{sname}] #{cname} between scans") do + s = subject.dup; ss = StringScanner.new(s) + a = ss.scan(/\S+/); b = ss.skip(/\s+/) + r = begin; change.(s); [ss.scan(/\S+/), ss[0], ss.pos, ss.matched, ss.pre_match, ss.rest, (ss.charpos rescue $!.class), ss.getch, ss.bol?, ss.eos?] + rescue => e; [e.class, e.message]; end + [[a, b, r].inspect, nil, nil] + end + end +end + +puts "== byteindex/byterindex loops over long strings (round four: a map shared by the searches of one snapshot)" +LONG_SUBJECTS = { + ascii: "hello, world; " * 200, utf8: "héllo, wörld; 日本, " * 150, astral: "a😀, 𝒳b; " * 200, + binary: ("ab\xE9, c; " * 200).b, usascii: ("ab, c; " * 200).force_encoding("US-ASCII"), +} +LONG_SUBJECTS.each do |sname, subject| + [",", "; ", "日", "😀", "é"].each do |needle| + try("#{sname} byteindex loop #{needle.inspect}") do + out = []; pos = 0 + while (pos = (subject.byteindex(needle, pos) rescue (out << $!.class; nil))); out << pos; pos += 1; break if out.size > 2000; end + [out.inspect.sum(32), out.size, out.last(3)].then { |x| [x.inspect, nil, nil] } + end + try("#{sname} byterindex loop #{needle.inspect}") do + out = []; pos = subject.bytesize + while pos >= 0 && (pos = (subject.byterindex(needle, pos) rescue (out << $!.class; nil))); out << pos; pos -= 1; break if out.size > 2000; end + [out.inspect.sum(32), out.size, out.last(3)].then { |x| [x.inspect, nil, nil] } + end + try("#{sname} byteindex every offset #{needle.inspect}") do + out = (0..subject.bytesize + 1).step(7).map { |i| subject.byteindex(needle, i) rescue $!.class } + out += (1..40).map { |i| subject.byteindex(needle, -i) rescue $!.class } + out += (0..subject.bytesize + 1).step(11).map { |i| subject.byterindex(needle, i) rescue $!.class } + [[out.inspect.sum(32), out.size, out.first(5), out.last(5)].inspect, nil, nil] + end + end + try("#{sname} byteindex after a change") do + s = subject.dup; a = s.byteindex(",", 3); s[0, 1] = "ü"; b = s.byteindex(",", 3); s << "ñ,"; c = s.byterindex(",", -1); d = s.byteindex(",", 5) + [[a, b, c, d].inspect, nil, nil] + end +end From 0518f08d1788217ac8157c044c2e5e9ff01186a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 09:10:15 +0000 Subject: [PATCH 132/439] LEDGER: perf/strsearch4 landed (not gated): the ASCII scan's cost explained; byteindex loops linear on UTF-8 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Util/perf/LEDGER.md | 46 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e9af97b10..5906b5a4f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1132,7 +1132,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (the UTF-8 length of the prefix, `Encoding.UTF8.GetByteCount`, 1.1 us over 10 KB of mixed text), and from a positive offset other than 0 it walks the characters to it, so a strscan-style loop of byte offsets over UTF-8 text is quadratic where CRuby's is not - (still so: `pos = s.byteindex(",", pos + 1)` over 100 KB of UTF-8, 93 ms against 0.36). + (fixed in round four, perf/strsearch4: 79-94 -> 2.4 ms over 100 KB, CRuby 0.35). Round three (perf/strsearch3, see Landed) found that StringScanner itself, which does not call `#byteindex`, was quadratic on UTF-8, and far worse; that is fixed. 22. **A `begin`/`rescue` or `ensure` in a method costs about 80 ns per call when nothing @@ -1626,6 +1626,50 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/strsearch4 (2026-11-27) - the ASCII scan's cost of round three found and mostly removed; + `#byteindex`/`#byterindex` from an offset other than 0 walk from the last search, through a map + shared with StringScanner (gap 21, round four)** - not gated. Commits 8d030d1, 103c741 on + `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j b887bc1 with d3b8844 merged in. + 1. Round three cost an ASCII scan word by word over 10 KB (`ss_words_a`) 2.6 to 3.4% more + instructions, most of it also with `IR_FAST_SEARCH=0`. Found with a per-function count: + callgrind with `DOTNET_ReadyToRun=0` (so that the library's code is JIT'd and named in the + runtime's perf map), the dumps of `count.sh`'s sections kept, their JIT addresses named from + `/tmp/perf-PID.map`, the least section of the tree before round three (b887bc1) against round + three's. Of the 6.7 M instructions a section had gained, 4.9 M were the check every scan makes + four times a token: the map getter (1.8 M), `StaticsHelpers.GetNonGCStaticBase` for the + switch's static (1.7 M; the switch-off arm paid it too, which is why turning the switch off + did not take the cost away), `MutableString.IsAscii()` (1.4 M), the encoding; the rest the + write barrier bucket (1.1 M), `MatchRegex`, `ByteLength`, `ClearMatch`. The getter now tests + `HasByteCharacters`, one flag that answers for a subject known to be ASCII, and leaves the + switch, the encoding and IsAscii to the slow path: `ss_words_a` 13.62-13.73 M (before round + three) / 13.97 M (round three) / 13.78-13.89 M now, +0.4 to 1.2% (the tree before round three + counts 0.8% apart from one process to the next). What is left is the getter's call (1.1 M a + section; the JIT does not inline it under `count.sh`'s settings, AggressiveInlining or not) and + `HasByteCharacters`' (0.37 M; AggressiveInlining on it changed nothing and was not kept). + 2. `#byteindex`/`#byterindex` with a String needle on valid non-ASCII UTF-8 walked the characters + from the start to the offset on every call and counted the bytes of the answer's prefix: a + loop `pos = s.byteindex(",", pos + 1)` was quadratic. The scanner's map moves to + `Builtins/Utf8OffsetMap.cs`; for the searches it is shared by the readers of one snapshot of + the string's characters, in a ConditionalWeakTable keyed by the snapshot (as MutableString's + character index tables are); its UTF-8 length is counted only for an offset from the end; an + offset of 0 or none makes no map. Loop over 10 KB / 100 KB of UTF-8, base -> new (CRuby): + 2.8 / 79-94 ms -> 0.23-0.29 / 2.4 ms (0.034 / 0.35); the ASCII loop 0.28 / 2.64 ms on both. + Callgrind, instructions a pass over 10 KB, ref (before round three) / base / new: + `bidx_loop_u` 63,835,104 / 63,835,196 / 3,279,668; `bridx_loop_u` 64,766,966 / 64,768,009 / + 4,333,019; controls `bidx_loop_a` 2,325,945 / 2,308,458 (one other base run 17.0 M, not + repeated) / 2,310,130, `bidx1_a_n` 9,500 / 9,499 / 9,501, `bidx1_u_e` 4,629 / 4,628 / 4,635, + `ss_words_u` 2,943,413,146 / 15,023,760 / 15,217,309 (+1.3%: the scanner's map is the shared + class now, whose length and pair flag are computed lazily), `size` unchanged. + Checked: `Util/string-search-matrix.rb` (60,164 rows) gains the scanner's subject changed between + scans (setbyte, `[]=`, insert, replace, force_encoding, a stray byte appended) and + byteindex/byterindex loops and offset sweeps over long ASCII, UTF-8, astral, BINARY and US-ASCII + strings with a change midway; it prints exactly what the base prints, switch on and off; the base + differs from CRuby in 115 rows (the 110 of round three and 5 new ones: the scanner after its + subject was replaced by a shorter string or edited inside a character). `csv-matrix`, + `erb-escape-matrix`: CRuby's output on base, new and off. spec/core/string (3,963), + spec/library/stringscanner (240), spec/library/csv (33): the same on base, new and off, 0 + failures (the one `String.try_convert` error on all three). + - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, not gated. A keyword From bfd4a1aded7709634d5b0e19822bef3a4cb6ce0e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 09:12:25 +0000 Subject: [PATCH 133/439] Ledger: drop the three entries the round 5 merges doubled Merging branches that had each merged the branch and resolved the ledger's conflicts by keeping both sides left perf/strdup, perf/lframe and perf/crubydiff's first round twice; the copies kept are the longer ones (strdup's edge for the gate, crubydiff's second round). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 127 -------------------------------------------- 1 file changed, 127 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index dacdb9a1d..1b6a340fe 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -3025,25 +3025,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has strlit's literal makers were; not tried here. For the gate: no IronRuby.Tests or spec run; the decline above. -- **perf/strdup (2026-11-26, not gated) - `String#dup` is String's own, MRI's rb_str_dup_m** (gap - 24's dup note). Kept as a CRuby-compatibility fix, not as a speed-up. `Util/dup-matrix.rb` (new: String, - Object and Array dup and clone - content, encodings, broken bytes, frozen and chilled, ivars, - singleton classes, subclasses, a refinement, TracePoint, and the hooks redefined in String, Object - and Kernel or by prepend and include, then restored) showed master differing from CRuby in six - rows. In CRuby `String#dup` belongs to String: a bare string (class String itself, no singleton - class, no instance variables) is copied without calling initialize_dup or initialize_copy, even - redefined; any other goes through rb_obj_dup. `MutableStringOps.Duplicate` does that now, so the - matrix prints CRuby's output (switch `IR_FAST_DUP=0`: every string through Kernel#dup, as before). - Instructions (`callgrind/count.sh`, `dup-shapes.rb`): `str_dup` 3,688 -> 3,291; `str_clone`, - `hash_dup`, `clone`, `obj_dup`, `oi_dup` (an object with ivars), `arr_dup` and `plain` level. - Time in a method's loop, three alternating runs: `S.dup` 104-109 ns on master, 100-113 here, CRuby - 55 - no gain; controls within the noise. So the hooks were not what String#dup spends: the 50 ns - over CRuby lie in the call of the library method and the copy (CreateInstance, Replace's content - clone), still to be found. Checks: dup, hash-dup, struct, hash-struct, jit and hot-shapes matrices - in every mode and with the switch off: PASS (dup-matrix `same`, `baseline -2` switched off). - spec/core/string and kernel dup/clone: 4,010 examples, the one known try_convert wording error - on both builds. - - **perf/strsearch2 (2026-11-26) - `#start_with?` with one String prefix takes no scope; an ASCII prefix is compared in place (gap 21, round two)** - not gated. Commit dc1d136 on `claude/perf-strsearch`, based on the merged branch 2f8c31c. `start_with?` had one overload, @@ -3074,114 +3055,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the same on both builds, 0 failures, one error on both (`String.try_convert ... raises TypeError if it's not a kind of String`, run as a directory). -- **perf/lframe (/perf-frame, 2026-11-26) - a cheaper method entry: the alias name and the - traced test** (switch `IR_LIGHT_ENTRY`, on unless `=0`) - instructions only, not gated. - Built on 2f8c31c. What gap 16's profiles left on every light frame, looked at on its own - with `Util/bench/frame-cost.rb` (new: a method that does nothing, one, three calls, a yield, - `block_given?`, and `String#bytesplice`), `-X:NoJIT` so that the generic bodies run. - - **Not the prologue.** perf/lsite2 put the light lambda's +158 down to zeroing its locals; - `DOTNET_JitDisasm` of the light `H#gsub` says otherwise: two 64-byte stores. What the - lambda pays up front is its closure constants (each load a bounds check and a - `CHKCASTCLASS` helper call), the frame record (`PrecompiledFrames.Enter`) and the - entry's helpers. So no `SkipLocalsInit` (the runtime compiles with the BCL's - `LambdaExpression.Compile`, which has no such switch, and the DLR patch set has nothing - to patch) and no DLR patch. - - **The alias name.** A call through an alias leaves the name it was called by in a - thread-static for the method's entry to take (`MarkAliasCall`, `TakePendingCallee`, - `CreateMethodScope`). Every entry tested a flag first, `_aliasCallSeen`, which start-up - sets for good (RubyGems and the prelude call aliases), so every entry of every method, - light or scoped, read the thread-static - a call into the runtime from a DynamicMethod: - `TakePendingCallee` 26 + `TakePendingCalleeSlow` 34 instructions a call in the `fc` - profile. The flag is now a count of the threads that have a name pending: raised by the - alias call when its thread had none, lowered by the entry that takes one, so an entry - reads the thread-static only while some thread has a name pending. A thread that dies - with one pending leaves the count up, which only costs the reads it costs today. - - **The traced test.** A light frame without register locals called - `CreateMethodScopeIfTraced` (nine arguments) on every entry to learn that no TracePoint - listens; the test is now inline, as `EnterWithRegisterLocals` has it. - - Left as they were: `EnterLightMethod` and `LeaveLightMethodFrame` already inline their - fast paths (the slow exit only for a block or a scope), and the frame record is every - compiled frame's, tuned before (#168). - - **Numbers** (instructions a call, `Util/perf/callgrind/count.sh`, N=20,000; switch off -> - on). frame-cost, light frames: `f0` 1,572 -> 1,435 (0.913), `f1` 1,656 -> 1,591 (0.961), - `fc` 2,553 -> 2,314 (0.906), `fc3` 4,280 -> 3,693 (0.863), `fy` 2,412 -> 2,347 (0.973), - `fbg` 1,932 -> 1,795 (0.929), `bytesplice` 27,120 -> 26,907 (0.992); the same with - `IR_LIGHT_FRAMES=0` (the alias count only): 0.945-0.974, `bytesplice` 0.991. Default mode, - regex-shapes: 0.977-0.993, `size` 1.000; core-small: `tap` 0.931, `then` 0.945, `minmax` - 0.969, `inject_sym` 0.973, `inject` 0.975, `sum_blk` 0.980, `zip` 0.985, `max_by` 0.984, - `each`/`each_with_index` 0.991. No shape counts more. No timing run (the counter is the - measure here; the gate owes the clock). - - Checked: `Util/light-entry-matrix.rb` (new: `__callee__` and `__method__` through `alias` - and `alias_method` into light and scoped methods, `define_method`, `send`, `public_send`, - `Method#call`, `bind_call`, method_missing; an alias call that raises ArgumentError before - its method is entered and then ordinary calls; alias calls as arguments of alias calls; - recursion through an alias; four threads calling aliases and names; TracePoint `:call`'s - `method_id`/`callee_id`; a million-deep recursion through a light frame, and through an - alias: SystemStackError, and the process goes on) and light-rest, block-given, - global-light, lexical-light, keyword-light, regex-light, rescue-light, super-light, - parked-scope, caller, light-remember and hot-shapes: the candidate prints what the - baseline prints in all 78 runs (each as built, `IR_LIGHT_ENTRY=0`, `IR_LIGHT_FRAMES=0`, - `IR_LIGHT_REGEX=all`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`), and CRuby's but where the - baseline differs too: caller's library frames, hot-shapes' FrozenError, and - light-entry's `define_method` body called through an alias, whose `__callee__` is the - definition's name on both builds (CRuby: the alias's) - a fault of master, not of this. - IronRuby.Tests: the 11 of AliasTests, `Backtrace_ArityCalleeFrame1` and the ten - `Method_LightFrame*`: PASSED. The census cannot see this (no method changes verdict). - Not run: `IR_CONFIG=R2R` start-up, the suite, a sweep, AWFY (owed to the gate). - -- **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated; one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose - refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when - the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope - (`CallArguments.GetBoundCallSiteArguments`). struct-matrix: CRuby's output in full. Refinements16. - - `Data.singleton_methods` listed `:allocate` (gap 24), and so did ArithmeticSequence's and - Continuation's: the prelude's singleton `allocate` gave way to `Class#__ir_undef_alloc__`, MRI's - `rb_undef_alloc_func` (`RubyClass.UndefineAllocator`, checked in the allocate rule of that class - only). Prelude_DataUndefinedAllocator1. - - `frozen << x` raised Encoding::CompatibilityError (the three lines of hot-shapes-matrix that - differed from CRuby), `<< -1` / `<< 2**80` RangeError, `prepend(1)` TypeError: CRuby checks - frozenness first. The checks are on the error paths only (MutableString.MutateAppend when the - encodings clash, Append(int) before ToChr). hot-shapes-matrix: CRuby's output. Left: `frozen << - Object.new` is TypeError (the binder converts first), `tr!` checks frozenness before the - encodings where CRuby does the opposite. String_AppendFrozenFirst1. - - A String subclass's instance as a Hash key (gap 34): stored as it is, unfrozen, as CRuby's - RHASH_STRING_KEY_P has it (SetHashElement and the JIT's HashStoreObj). hash-literal-matrix: two - new rows, baseline before; a third for `defined?({a: x.nope})`, already same. Hash_StringSubclassKey1. - - A private or protected method's call reaching BasicObject#method_missing through a user's - `super` (gap 37): the visibility now travels with the method_missing reason - (`RubyOps.SetMethodMissingReasonVisibility`, a MethodInfo field, not a new [Emitted] helper), and - the error says "private method 'x' called". One more thread-static write per call that reaches a - user's method_missing. SuperAndMethodMissing3. - - Module#dup / #clone (gap 37): the members are copied in IDuplicable.Duplicate, before - initialize_copy, as MRI 4.0's init_copy does; Module's and Class's own initialize_copy are gone - (CRuby's owner is Kernel). ModuleCopyBeforeInitializeCopy1. - - An endless def's expression is no TracePoint `:line` event (gap 33): the bridge adds it with - Statements.NoLine unless it holds parenthesized statements; a rescue modifier there keeps no line - either. interpolation-matrix: new row, baseline before. TracePoint_EndlessDefLine1. - - `"#{sym}"` under a refinement of Symbol#to_s is the name while Symbol#to_s is the built-in - (gap 33, vm_objtostring). interpolation-matrix: new row. Refinements17. - - `__callee__` in a define_method body called through an alias answered the definition's name - (found by perf/lframe): an alias call runs a copy of the method's lambda that carries the name - (Proc.CalleeName in its rare state; RubyLambdaMethodInfo.GetLambdaFor), in the rule and the - first-call dispatcher; such a call skips the method JIT's stub. light-entry-matrix (claude/perf-lsite) - "define_method body by alias": CRuby's output. DefineMethodCallee1. - Not fixed: `42.compare_to(o)` in inline-matrix's `tree_int_key` answers Int32#CompareTo's - "Object must be of type Int32." where CRuby has no such method. That is IronRuby's interop - (RubyModule.IsUnmangledBuiltin: snake_case CLR names on Integer and Float, `5.to_string("X")`, - which ClrTests asserts), not a leak; matching CRuby means dropping those names, or mapping them - only on request. Already matching on the branch when the round began: refinement before prepend on - Integer#+ (f7679a1), the frame line of a raising interpolation part, `defined?({a: x.nope})`. - Checked per fix (see each commit): the named IronRuby.Tests and the ruby/spec files around each - change on both trees, results as before (refine_spec 38/0, prepend_spec 55/0, spec/core/module - 1050 examples with the 4 known errors, struct, data, class, kernel dup/clone, string, hash, - tracepoint, coverage, basicobject, nomethoderror, language def/method/send/private/protected). - For the gate: the two changes on dispatch-adjacent paths - Class#new's rule for a library - initialize (no scope argument now, so a light-scope site's `Struct.new`/`Array.new` rule no longer - sets ScopeRead) and method_missing's reason - and Module#dup/#clone, which now copies before - initialize_copy (anything that relied on Module#initialize_copy copying, e.g. a re-run - initialize_copy, gets Kernel's). - - **perf/iter (round thirty-seven, 2026-11-26) - a block that holds a block literal reuses its scope and the literal's Proc (gaps 13 and 6)** - instructions and bytes, not gated. A block whose body has a block literal (`a.each { |x| o.e { |c| s += c } }`, Richards' worker block with From 3882c196cddb0ce361a177fb14b262fe892990fd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 09:13:54 +0000 Subject: [PATCH 134/439] Kernel#eval keeps its backtrace frame on the ReadyToRun host On the R2R host (IR_CONFIG=R2R, what a release runs) the backtrace of an eval inside an eval lacked CRuby's `Kernel#eval` frames (Util/caller-matrix.rb's m8a and m8b rows), where the Release build printed them; master too, healing only after tier-1 recompiled the callers. A backtrace names a library method by its CLR frame, and the precompiled code had inlined KernelOps.Evaluate into its caller. It is NoInlining now, as Kernel#format and the other one-line library methods whose frame a backtrace has to show already are. Checked: caller-matrix under IR_CONFIG=R2R (published from this tree) prints what the Release build prints, m8a/m8b with CRuby's Kernel#eval frames; the rows left (Method#call, sort_by and inject frames, line 14) differ from CRuby on both builds alike. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/Libraries/Builtins/KernelOps.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index 2ec27bbe6..a55d330e8 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1942,6 +1942,7 @@ public static object Freeze(RubyContext/*!*/ context, object self) { [RubyMethod("eval", RubyMethodAttributes.PrivateInstance)] [RubyMethod("eval", RubyMethodAttributes.PublicSingleton)] + [MethodImpl(MethodImplOptions.NoInlining)] public static object Evaluate(RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]MutableString/*!*/ code, [Optional]Binding binding, [Optional, NotNull]MutableString file, [DefaultParameterValue(1)]int line) { From f6a75af39eff136dcea1eefb013563d8b36d75f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 09:14:23 +0000 Subject: [PATCH 135/439] rbconfig: ask the host for its directory and the runtime's version, not CLR interop RbConfig set bindir from the entry assembly's location and arch from the .NET runtime's version through CLR interop: System::Reflection::Assembly.get_entry_assembly.location, System::IO::Path.get_directory_name, System::Environment.Version.Major and .Minor. Each of those six call sites bound a rule of its own and looked its member up by reflection. That cost ~4 ms of every `ir -e 1' (rbconfig.rb's self time on the R2R host with the startup library: ~11 ms -> ~7 ms; its binds 34 -> 28, 5.9 -> 2.2 ms). A private singleton method, IronRuby.__host_config__ (like __gemspec_stamp__), answers both: the entry assembly's directory (nil without an entry assembly, "" if it has no location, as before) and "major.minor". The directory is a UTF-8 string, as System::String#to_s gave it. Checked: every RbConfig::CONFIG value (with its encoding and frozenness) and RbConfig.ruby print the same as before, on the R2R host and the Release build. So do Gem.loaded_specs, $LOADED_FEATURES and its order, and default-gem lookups. -w prints nothing. This round also found that the RubyGems files a boot loads are all in the startup library already. Their self time is spread over first binds, two `super' rules (~1.9 ms), Gem::Specification's string eval (~4 ms) and JIT that the release image precompiles. No other part of it is IronRuby's own code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/Libraries/Extensions/IronRubyOps.cs | 18 ++++++++++++++++++ Src/StdLib/ironruby/rbconfig.rb | 8 +++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/Src/Libraries/Extensions/IronRubyOps.cs b/Src/Libraries/Extensions/IronRubyOps.cs index 66e60de8e..9da1905a3 100644 --- a/Src/Libraries/Extensions/IronRubyOps.cs +++ b/Src/Libraries/Extensions/IronRubyOps.cs @@ -68,6 +68,24 @@ public static class IronRubyOps { return result; } + /// + /// What rbconfig.rb asks the host: [the directory of the entry assembly (nil without one, as in a host that embeds IronRuby; + /// "" if it has no location), the .NET runtime's "major.minor"]. It asked through CLR interop + /// (System::Reflection::Assembly.get_entry_assembly.location and friends), whose six call sites bound rules of their own + /// and looked their members up by reflection: ~4 ms of every `ir -e 1'. + /// + [RubyMethod("__host_config__", RubyMethodAttributes.PrivateSingleton)] + public static RubyArray/*!*/ GetHostConfig(RubyContext/*!*/ context, RubyModule/*!*/ self) { + var entry = System.Reflection.Assembly.GetEntryAssembly(); + object bindir = null; + if (entry != null) { + // UTF-8, as System::String#to_s made it + bindir = MutableString.Create(Path.GetDirectoryName(entry.Location) ?? "", RubyEncoding.UTF8); + } + Version clr = Environment.Version; + return new RubyArray(new object[] { bindir, MutableString.CreateAscii(clr.Major + "." + clr.Minor) }); + } + [RubyMethod("loaded_assemblies", RubyMethodAttributes.PublicSingleton)] public static RubyArray/*!*/ GetLoadedAssemblies(RubyContext/*!*/ context, RubyModule/*!*/ self) { return new RubyArray(context.DomainManager.GetLoadedAssemblyList()); diff --git a/Src/StdLib/ironruby/rbconfig.rb b/Src/StdLib/ironruby/rbconfig.rb index c31a7f170..3ba6cecef 100644 --- a/Src/StdLib/ironruby/rbconfig.rb +++ b/Src/StdLib/ironruby/rbconfig.rb @@ -62,8 +62,11 @@ module RbConfig CONFIG["LIBRUBY"] = "IronRuby.dll" # Set up paths - # bindir is where the running ir executable lives, so RbConfig.ruby names it. - bindir = File.expand_path(System::IO::Path.get_directory_name(System::Reflection::Assembly.get_entry_assembly.location).to_s) rescue nil + # bindir is where the running ir executable lives, so RbConfig.ruby names it: the entry + # assembly's directory, which the host answers along with the runtime's version - without + # CLR interop, whose call sites cost every boot a rule and a reflection lookup each. + host_dir, clr_version = IronRuby.__send__(:__host_config__) + bindir = (File.expand_path(host_dir) if host_dir) rescue nil prefix = TOPDIR || File.dirname(libdir) CONFIG["bindir"] = bindir || "#{prefix}/bin" @@ -80,7 +83,6 @@ module RbConfig CONFIG["host_os"] = CONFIG["target_os"] = cpu_and_os[1] # architecture - clr_version = "#{System::Environment.Version.Major}.#{System::Environment.Version.Minor}" # The .NET runtime IronRuby is running on, not the framework it was compiled for: the # net10.0 build answers "universal-dotnet11.0" under the .NET 11 runtime. CONFIG["arch"] = arch = "universal-dotnet#{clr_version}" From 3b31435d8b95b91bc0723eec0b8f1fc7a971714c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 09:16:00 +0000 Subject: [PATCH 136/439] A String's representation switch publishes only over what it switched from There is no GVL. A reader on another thread switches a string between characters and bytes (getbyte, bytes, index, unpack...), and the switch converted the content without holding it and set the result unconditionally: a write made meanwhile was put back as it was, or its bytes decoded in an encoding the writer had already changed. In the new lost-write column of Util/string-race-matrix.rb, 25 of 252 rows lost a write on master in 20 runs, and in 21 the writer itself raised ("character U+0000 can't be encoded in ASCII-8BIT" from force_encoding or encode!). - Content.WrapContent publishes through MutableString.PublishSwitch: a compare-exchange on _rawContent against the content switched from. CharArrayContent.SwitchToBinary, BinaryContent.SwitchToChars and BinaryContent.ConvertToString convert holding the content. SwitchToBytes, SwitchToCharacters and Transcode no longer store the switched content themselves. - A write to a char or byte content checks, once it holds it, that it is still the string's (EnterCurrentWrite, IsCurrent), and otherwise makes the write on the current content. - ForceEncoding sets the encoding holding the byte content it switched to, if that is still current and still bytes (Content.TrySetOwnerEncoding), or switches again. IR_SAFE_SWITCH=0 publishes unconditionally, as before. 20 runs of the matrix: rows with a lost write 25 -> 0, rows where the writer raised 21 -> 0, rows not always ok 106 -> 89 (readers that still read unheld, gap 39). Single-threaded, instructions with the shape's driver: a write +41 (append 2,022 -> 2,063), force_encoding there and back +179, index after a switch +239, a switch +41-46; size and plain level. strcow, dup, string-search and hot-shapes matrices pass in every mode and switched off; spec/core/string and 60 MutableString, String and Encoding IronRuby.Tests as on master. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- .../Builtins/MutableString.BinaryContent.cs | 114 +++++++++++++++--- .../MutableString.CharArrayContent.cs | 75 ++++++++++-- Src/Ruby/Builtins/MutableString.Content.cs | 28 ++++- Src/Ruby/Builtins/MutableString.cs | 87 +++++++++---- Util/bench/strswitch-shapes.rb | 49 ++++++++ Util/perf/LEDGER.md | 29 +++++ Util/string-race-matrix.rb | 6 +- 7 files changed, 337 insertions(+), 51 deletions(-) create mode 100644 Util/bench/strswitch-shapes.rb diff --git a/Src/Ruby/Builtins/MutableString.BinaryContent.cs b/Src/Ruby/Builtins/MutableString.BinaryContent.cs index b660ed61b..b04132143 100644 --- a/Src/Ruby/Builtins/MutableString.BinaryContent.cs +++ b/Src/Ruby/Builtins/MutableString.BinaryContent.cs @@ -113,6 +113,30 @@ private void EnterWriteSlow(int minCapacity) { } } + internal override bool TrySetOwnerEncoding(RubyEncoding/*!*/ encoding, bool bytesOnly) { + bool shared = ContentState.Enter(ref _state); + try { + if (!IsCurrent) { + return false; + } + _owner.SetEncodingHeld(encoding); + return true; + } finally { + ContentState.Exit(ref _state, shared); + } + } + + // EnterWrite, and true if this content is still its string's; otherwise released again and false, and the + // write goes to the string's content (MutableString.PublishSwitch). + private bool EnterCurrentWrite(int minCapacity) { + EnterWrite(minCapacity); + if (IsCurrent) { + return true; + } + ExitWrite(); + return false; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ExitWrite() { ContentState.Exit(ref _state, false); @@ -143,9 +167,15 @@ internal ReadOnlySpan GetDataSpan() { } /// Invalid character. + // Converted holding this content, so that no write to it is lost (see WrapContent). private CharArrayContent/*!*/ SwitchToChars(int additionalCapacity) { - char[] chars = DataToChars(additionalCapacity, _owner._encoding.EscapingEncoding); - return WrapContent(chars, chars.Length - additionalCapacity); + bool shared = ContentState.Enter(ref _state); + try { + char[] chars = DataToChars(additionalCapacity, _owner._encoding.EscapingEncoding); + return WrapContent(chars, chars.Length - additionalCapacity); + } finally { + ContentState.Exit(ref _state, shared); + } } /// Invalid character. @@ -176,7 +206,11 @@ internal ReadOnlySpan GetDataSpan() { } internal void AppendBytes(string/*!*/ str, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Append(str, start, count); + return; + } try { _count = Utils.Append(ref _data, _count, str, start, count, _owner._encoding.EscapingEncoding); } finally { @@ -185,7 +219,11 @@ internal void AppendBytes(string/*!*/ str, int start, int count) { } internal void AppendBytes(char[]/*!*/ chars, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Append(chars, start, count); + return; + } try { _count = Utils.Append(ref _data, _count, chars, start, count, _owner._encoding.EscapingEncoding); } finally { @@ -279,7 +317,11 @@ private static bool TryHashUtf8(ReadOnlySpan bytes, out int hash) { public override int Count { get { return _count; } set { - EnterWrite(value); + if (!EnterCurrentWrite(value)) { + // see MutableString.PublishSwitch + _owner._content.Count = value; + return; + } try { if (_data.Length < value) { Array.Resize(ref _data, Utils.GetExpandedSize(_data, value)); @@ -425,7 +467,13 @@ public override void SetCapacity(int capacity) { // characters and then taking a snapshot of them made two copies of a long string, and a // long ASCII sum held as bytes cost more to match than one held as characters. public override string/*!*/ ConvertToString() { - return WrapContent(DataToString()).Data; + // converted holding this content, as SwitchToChars is + bool shared = ContentState.Enter(ref _state); + try { + return WrapContent(DataToString()).Data; + } finally { + ContentState.Exit(ref _state, shared); + } } public override byte[]/*!*/ ConvertToBytes() { @@ -795,7 +843,11 @@ public override void Append(char c, int repeatCount) { if (_owner.HasByteCharacters || c < 0x80 && _owner._encoding.IsAsciiIdentity) { Append((byte)c, repeatCount); } else { - EnterWrite(_count + repeatCount); + if (!EnterCurrentWrite(_count + repeatCount)) { + // see MutableString.PublishSwitch + _owner._content.Append(c, repeatCount); + return; + } try { _count = Utils.Append(ref _data, _count, c, repeatCount, _owner._encoding.EscapingEncoding); } finally { @@ -805,7 +857,11 @@ public override void Append(char c, int repeatCount) { } public override void Append(byte b, int repeatCount) { - EnterWrite(_count + repeatCount); + if (!EnterCurrentWrite(_count + repeatCount)) { + // see MutableString.PublishSwitch + _owner._content.Append(b, repeatCount); + return; + } try { _count = Utils.Append(ref _data, _count, b, repeatCount); } finally { @@ -822,7 +878,11 @@ public override void Append(char[]/*!*/ chars, int start, int count) { } public override void Append(byte[]/*!*/ bytes, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Append(bytes, start, count); + return; + } try { _count = Utils.Append(ref _data, _count, bytes, start, count); } finally { @@ -893,7 +953,11 @@ public override void Insert(int index, char c) { } public override void Insert(int index, byte b) { - EnterWrite(_count + 1); + if (!EnterCurrentWrite(_count + 1)) { + // see MutableString.PublishSwitch + _owner._content.Insert(index, b); + return; + } try { _count = Utils.InsertAt(ref _data, _count, index, b, 1); } finally { @@ -910,7 +974,11 @@ public override void Insert(int index, char[]/*!*/ chars, int start, int count) } public override void Insert(int index, byte[]/*!*/ bytes, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Insert(index, bytes, start, count); + return; + } try { _count = Utils.InsertAt(ref _data, _count, index, bytes, start, count); } finally { @@ -929,7 +997,11 @@ public override void SetByte(int index, byte b) { if (index >= _count) { throw new IndexOutOfRangeException(); } - EnterWrite(0); + if (!EnterCurrentWrite(0)) { + // see MutableString.PublishSwitch + _owner._content.SetByte(index, b); + return; + } try { _data[index] = b; } finally { @@ -951,6 +1023,12 @@ public override void SetChar(int index, char c) { public override void Remove(int start, int count) { bool shared = ContentState.Enter(ref _state); + if (!IsCurrent) { + // see MutableString.PublishSwitch + ContentState.Exit(ref _state, shared); + _owner._content.Remove(start, count); + return; + } try { if (shared) { // Cutting off the end leaves the shared bytes as they are; anything else copies @@ -965,7 +1043,11 @@ public override void Remove(int start, int count) { } public override void Write(int offset, byte[]/*!*/ value, int start, int count) { - EnterWrite(offset + count); + if (!EnterCurrentWrite(offset + count)) { + // see MutableString.PublishSwitch + _owner._content.Write(offset, value, start, count); + return; + } try { Utils.Resize(ref _data, offset + count); _count = Math.Max(_count, offset + count); @@ -977,7 +1059,11 @@ public override void Write(int offset, byte[]/*!*/ value, int start, int count) public override void Write(int offset, byte value, int repeatCount) { int end = offset + repeatCount; - EnterWrite(end); + if (!EnterCurrentWrite(end)) { + // see MutableString.PublishSwitch + _owner._content.Write(offset, value, repeatCount); + return; + } try { Utils.Resize(ref _data, end); if (end > _count) { diff --git a/Src/Ruby/Builtins/MutableString.CharArrayContent.cs b/Src/Ruby/Builtins/MutableString.CharArrayContent.cs index d973e29a0..7fd96eb97 100644 --- a/Src/Ruby/Builtins/MutableString.CharArrayContent.cs +++ b/Src/Ruby/Builtins/MutableString.CharArrayContent.cs @@ -113,6 +113,17 @@ private void EnterWriteSlow(int minCapacity) { } } + // EnterWrite, and true if this content is still its string's; otherwise released again and false, and the + // write goes to the string's content (MutableString.PublishSwitch). + private bool EnterCurrentWrite(int minCapacity) { + EnterWrite(minCapacity); + if (IsCurrent) { + return true; + } + ExitWrite(); + return false; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ExitWrite() { ContentState.Exit(ref _state, false); @@ -134,9 +145,15 @@ internal ReadOnlySpan GetDataSpan() { return SwitchToBinary(0); } + // Converted holding this content, so that no write to it is lost (see WrapContent). private BinaryContent/*!*/ SwitchToBinary(int additionalCapacity) { - var bytes = DataToBytes(additionalCapacity); - return WrapContent(bytes, bytes.Length - additionalCapacity); + bool shared = ContentState.Enter(ref _state); + try { + var bytes = DataToBytes(additionalCapacity); + return WrapContent(bytes, bytes.Length - additionalCapacity); + } finally { + ContentState.Exit(ref _state, shared); + } } private byte[]/*!*/ DataToBytes(int additionalCapacity) { @@ -161,7 +178,11 @@ internal void GetDataBytes(byte[]/*!*/ bytes, int start) { public void DataSetChar(int index, char c) { Debug.Assert(index < _count); - EnterWrite(0); + if (!EnterCurrentWrite(0)) { + // see MutableString.PublishSwitch + _owner._content.SetChar(index, c); + return; + } try { _data[index] = c; } finally { @@ -183,7 +204,11 @@ public override int CalculateHashCode() { public override int Count { get { return _count; } set { - EnterWrite(value); + if (!EnterCurrentWrite(value)) { + // see MutableString.PublishSwitch + _owner._content.Count = value; + return; + } try { if (_data.Length < value) { Array.Resize(ref _data, Utils.GetExpandedSize(_data, value)); @@ -573,7 +598,11 @@ public override int LastIndexIn(Content/*!*/ str, int start, int count) { #region Append public override void Append(char c, int repeatCount) { - EnterWrite(_count + repeatCount); + if (!EnterCurrentWrite(_count + repeatCount)) { + // see MutableString.PublishSwitch + _owner._content.Append(c, repeatCount); + return; + } try { _count = Utils.Append(ref _data, _count, c, repeatCount); } finally { @@ -586,7 +615,11 @@ public override void Append(byte b, int repeatCount) { } public override void Append(string/*!*/ str, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Append(str, start, count); + return; + } try { _count = Utils.Append(ref _data, _count, str, start, count); } finally { @@ -595,7 +628,11 @@ public override void Append(string/*!*/ str, int start, int count) { } public override void Append(char[]/*!*/ chars, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Append(chars, start, count); + return; + } try { _count = Utils.Append(ref _data, _count, chars, start, count); } finally { @@ -653,7 +690,11 @@ public override void AppendTo(StringContent/*!*/ content, int start, int count) #region Insert public override void Insert(int index, char c) { - EnterWrite(_count + 1); + if (!EnterCurrentWrite(_count + 1)) { + // see MutableString.PublishSwitch + _owner._content.Insert(index, c); + return; + } try { _count = Utils.InsertAt(ref _data, _count, index, c, 1); } finally { @@ -670,7 +711,11 @@ public override void Insert(int index, byte b) { } public override void Insert(int index, string/*!*/ str, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Insert(index, str, start, count); + return; + } try { _count = Utils.InsertAt(ref _data, _count, index, str, start, count); } finally { @@ -679,7 +724,11 @@ public override void Insert(int index, string/*!*/ str, int start, int count) { } public override void Insert(int index, char[]/*!*/ chars, int start, int count) { - EnterWrite(_count + count); + if (!EnterCurrentWrite(_count + count)) { + // see MutableString.PublishSwitch + _owner._content.Insert(index, chars, start, count); + return; + } try { _count = Utils.InsertAt(ref _data, _count, index, chars, start, count); } finally { @@ -716,6 +765,12 @@ public override void SetChar(int index, char c) { public override void Remove(int start, int count) { bool shared = ContentState.Enter(ref _state); + if (!IsCurrent) { + // see MutableString.PublishSwitch + ContentState.Exit(ref _state, shared); + _owner._content.Remove(start, count); + return; + } try { if (shared) { // see BinaryContent.Remove diff --git a/Src/Ruby/Builtins/MutableString.Content.cs b/Src/Ruby/Builtins/MutableString.Content.cs index 831688ab6..41a97ed09 100644 --- a/Src/Ruby/Builtins/MutableString.Content.cs +++ b/Src/Ruby/Builtins/MutableString.Content.cs @@ -130,24 +130,46 @@ protected Content(MutableString owner) { return this; } + // The switched content is published only if this one is still the string's (MutableString.PublishSwitch); a + // mutable content makes the conversion holding itself. Either way the caller gets it: a reader reads it, and a + // writer that writes to it finds it is not the string's content if it was not published, and writes to that. protected BinaryContent/*!*/ WrapContent(byte[]/*!*/ bytes, int count) { BinaryContent result = new BinaryContent(bytes, count, _owner); - _owner.SetContent(result); + _owner.PublishSwitch(this, result); return result; } protected CharArrayContent/*!*/ WrapContent(char[]/*!*/ chars, int count) { var result = new CharArrayContent(chars, count, _owner); - _owner.SetContent(result); + _owner.PublishSwitch(this, result); return result; } protected StringContent/*!*/ WrapContent(string/*!*/ str) { var result = new StringContent(str, _owner); - _owner.SetContent(result); + _owner.PublishSwitch(this, result); return result; } + /// + /// Sets the owner's encoding holding this content, if it is still the owner's - and, with + /// , if it holds bytes; false otherwise (MutableString.ForceEncoding). A reader's switch + /// of representation, made holding the content, then either comes before (and this one is no longer current) or + /// after, with the new encoding. + /// + internal virtual bool TrySetOwnerEncoding(RubyEncoding/*!*/ encoding, bool bytesOnly) { + if (bytesOnly || !IsCurrent) { + return false; + } + _owner.SetEncodingHeld(encoding); + return true; + } + + /// Whether this content, held for a write, is still its string's (a content of no string is). + protected bool IsCurrent { + get { return _owner == null || _owner.IsCurrentContent(this); } + } + /// /// The length from which a string whose characters are all ASCII hashes them as bytes /// () rather than as UTF-16 characters, whatever its encoding. A shorter one costs about the same either way, and diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index 89744e1c0..947009a9b 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -167,6 +167,32 @@ private void SetContent(Content/*!*/ content) { _flags |= CharIndexChangedFlags; } + /// + /// Publishes , another representation of (Content.WrapContent), only if + /// is still this string's content. There is no GVL: a reader on another thread switches a + /// string between characters and bytes (getbyte, bytes, index...), and setting the converted content unconditionally + /// put back what the string held before a write that a writer made meanwhile - the write was lost, or its bytes were + /// decoded in an encoding the writer had already changed (Util/string-race-matrix.rb). The conversion is made holding + /// (a mutable content), and a writer that then holds it finds it is no longer current and + /// writes to the current content instead (IsCurrentContent). IR_SAFE_SWITCH=0: published unconditionally, as before. + /// + internal void PublishSwitch(Content/*!*/ from, Content/*!*/ to) { + if (!SafeSwitch) { + SetContent(to); + return; + } + if (ReferenceEquals(System.Threading.Interlocked.CompareExchange(ref _rawContent, to, from), from)) { + _flags |= CharIndexChangedFlags; + } + } + + internal static readonly bool SafeSwitch = Environment.GetEnvironmentVariable("IR_SAFE_SWITCH") != "0"; + + /// Whether a content held for a write is still this string's (see PublishSwitch). + internal bool IsCurrentContent(Content/*!*/ content) { + return !SafeSwitch || ReferenceEquals(System.Threading.Volatile.Read(ref _rawContent), content); + } + private void SetEncoding(RubyEncoding/*!*/ encoding) { uint flags = _flags; @@ -938,30 +964,45 @@ public void ForceEncoding(RubyEncoding/*!*/ newEncoding) { return; } - if (IsBinary) { - SetEncoding(newEncoding); - return; - } + // The bytes and the encoding change together: a reader on another thread that switches the string back to + // characters between the switch to bytes and the new encoding would decode them in the old one and leave + // characters under the new (MutableString.PublishSwitch). So the encoding is set holding the content, if it + // is still the string's and still the bytes, or the switch is made again. + while (true) { + if (IsBinary) { + if (_content.TrySetOwnerEncoding(newEncoding, true)) { + return; + } + continue; + } - // If the representation is character based and includes non-ascii chcaracters then we need - // to switch to binary repr before we change the encoding so that the binary repr of the string is preserved. + // If the representation is character based and includes non-ascii chcaracters then we need + // to switch to binary repr before we change the encoding so that the binary repr of the string is preserved. - // this caches hash-code, which we need to invalidate due to encoding change: - bool isAscii = IsAscii(); - Mutate(); + // this caches hash-code, which we need to invalidate due to encoding change: + bool isAscii = IsAscii(); + Mutate(); - // An all-ASCII character representation only keeps its bytes if both the old and the - // new encoding encode ASCII as itself. "ab" in UTF-16LE is 4 bytes, so forcing a - // character-based "ab" to UTF-16LE without switching to bytes first would invent two - // NUL bytes (and forcing a UTF-16LE string to UTF-8 would drop them). - if (isAscii && _encoding.IsAsciiIdentity && newEncoding.IsAsciiIdentity) { - SetEncoding(newEncoding); - } else { - SwitchToBytes(); - SetEncoding(newEncoding); + // An all-ASCII character representation only keeps its bytes if both the old and the + // new encoding encode ASCII as itself. "ab" in UTF-16LE is 4 bytes, so forcing a + // character-based "ab" to UTF-16LE without switching to bytes first would invent two + // NUL bytes (and forcing a UTF-16LE string to UTF-8 would drop them). + if (isAscii && _encoding.IsAsciiIdentity && newEncoding.IsAsciiIdentity) { + // ASCII characters convert to the same bytes in both encodings + SetEncoding(newEncoding); + return; + } + if (SwitchToBytes()._content.TrySetOwnerEncoding(newEncoding, true)) { + return; + } } } + // For Content.TrySetOwnerEncoding, which holds the content. + internal void SetEncodingHeld(RubyEncoding/*!*/ encoding) { + SetEncoding(encoding); + } + /// /// Assumes the content to be encoded in fromEncoding and trancodes it into toEncoding. /// @@ -981,7 +1022,7 @@ public void Transcode(RubyEncoding/*!*/ fromEncoding, RubyEncoding/*!*/ toEncodi // (a long ASCII sum, say) goes over to characters for UTF-16 and UTF-32, whose bytes // are then made from them, as for a string held as characters. if (IsBinary && !toEncoding.AsciiRoundTrips) { - _content = _content.SwitchToStringContent(); + _content.SwitchToStringContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } SetEncoding(toEncoding); return; @@ -996,7 +1037,7 @@ public void Transcode(RubyEncoding/*!*/ fromEncoding, RubyEncoding/*!*/ toEncodi switchToChars = true; } else if (fromEncoding != _encoding) { try { - _content = _content.SwitchToBinaryContent(); + _content.SwitchToBinaryContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (EncoderFallbackException e) { throw RubyExceptions.CreateInvalidByteSequenceError(e, _encoding); } @@ -1008,7 +1049,7 @@ public void Transcode(RubyEncoding/*!*/ fromEncoding, RubyEncoding/*!*/ toEncodi if (switchToChars) { try { - _content = _content.SwitchToStringContent(); + _content.SwitchToStringContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (DecoderFallbackException e) { throw RubyExceptions.CreateInvalidByteSequenceError(e, fromEncoding); } @@ -1339,7 +1380,7 @@ internal string/*!*/ Dump { /// public MutableString/*!*/ SwitchToBytes() { try { - _content = _content.SwitchToBinaryContent(); + _content.SwitchToBinaryContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (EncoderFallbackException e) { throw RubyExceptions.CreateInvalidByteSequenceError(e, _encoding); } @@ -1355,7 +1396,7 @@ internal string/*!*/ Dump { /// public MutableString/*!*/ SwitchToCharacters() { try { - _content = _content.SwitchToStringContent(); + _content.SwitchToStringContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (DecoderFallbackException e) { throw RubyExceptions.CreateInvalidByteSequenceError(e, _encoding); } diff --git a/Util/bench/strswitch-shapes.rb b/Util/bench/strswitch-shapes.rb new file mode 100644 index 000000000..8b1ed5b1c --- /dev/null +++ b/Util/bench/strswitch-shapes.rb @@ -0,0 +1,49 @@ +# What a String's representation switch and its writes cost (perf/strswitch): getbyte and bytes on a string held as +# characters (each switches it to bytes), index after setbyte (back to characters), force_encoding there and back, and +# the writes that now check their content is still the string's - <<, insert, setbyte, slice! - with size as a control. +# ns per operation, the caller a `while' loop; with INSTR=1 (Util/perf/callgrind/count.sh) instructions too. +$stdout.sync = true +def plain(a) = a +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-14s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +N = (ENV['N'] || 200_000).to_i +MB = ("aé" * 20).freeze +ASC = ("abcdefghij" * 4).freeze + +t("getbyte_switch", N) { |n| i = 0; c = 0; while i < n; t = MB.dup; t << "é"; c += t.getbyte(1) + i; i += 1; end; c } +t("bytes_switch", N) { |n| i = 0; c = 0; while i < n; t = MB.dup; t << "é"; c += t.bytes.size + i; i += 1; end; c } +t("index_back", N) { |n| i = 0; c = 0; t = MB.dup; while i < n; t.setbyte(0, 98); c += t.index("é") + i; i += 1; end; c } +t("force_enc", N) { |n| i = 0; c = 0; t = MB.dup; while i < n; t.force_encoding("BINARY"); t.force_encoding("UTF-8"); c += i; i += 1; end; c } +t("append", N) { |n| i = 0; c = 0; t = +""; while i < n; t << "a"; c += i; i += 1; end; c + t.size } +t("insert", N / 10) { |n| i = 0; c = 0; t = ASC.dup; while i < n; t.insert(5, "x"); t.slice!(5, 1); c += i; i += 1; end; c + t.size } +t("setbyte", N) { |n| i = 0; c = 0; t = ASC.b; while i < n; t.setbyte(i & 31, 97); c += i; i += 1; end; c } +t("size", N) { |n| i = 0; c = 0; while i < n; c += MB.size + i; i += 1; end; c } +t("plain", N) { |n| i = 0; c = 0; while i < n; c += plain(i); i += 1; end; c } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f3c2287dd..a89d2cac5 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1650,9 +1650,38 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `_rawContent`), every writer re-checking after it holds that its content is still current; and the encoding kept with the content (or read under the same hold). A decision about what IronRuby promises, as gap 20 is, before an experiment. + perf/strswitch (see Landed) took cause 2: no write is lost to a reader's switch and no + writer fails on one (21 and 25 rows of 252 on master, 0 and 0 now, 20 runs). Causes 1 and 3 + remain: 89 rows of readers that answer wrongly or raise. ## Landed +- **perf/strswitch (2026-11-27, not gated) - a String's representation switch cannot lose a write** + (gap 39's cause 2; switch `IR_SAFE_SWITCH`). A switch between characters and bytes (a reader's + getbyte, bytes, index, unpack... or a writer's) now converts holding the content it switches + from and publishes the new one only by compare-exchange on `_rawContent` against it + (`MutableString.PublishSwitch`, from `Content.WrapContent`); the callers that stored the result + unconditionally (`SwitchToBytes`, `SwitchToCharacters`, `Transcode`) no longer do. Every write to + a char or byte content checks, once it holds it, that it is still the string's + (`EnterCurrentWrite`, `IsCurrent`) and otherwise makes the write on the current content. + `ForceEncoding` sets the encoding holding the byte content it switched to, if still current and + still bytes, or switches again (`Content.TrySetOwnerEncoding`). `Util/string-race-matrix.rb` now + also reports a lost write (the string a writer leaves is not the state its flips began from). + 20 runs each: master 106 of 252 rows not always ok, 21 where the writer raised and 25 with a + lost write; this 89, 0 and 0. The 89 are cause 1 and 3 of gap 39 (readers reading unheld): under + encode! 29, slice! front 19, insert 17, replace 11, force_encoding 7, append 6; IndexOutOfRange + 24, ArgumentError 18, RangeError 7, the rest wrong answers. Single-threaded instructions + (`callgrind/count.sh`, `Util/bench/strswitch-shapes.rb`): each write +41 (append 2,022 -> 2,063, + setbyte 1,697 -> 1,739, insert and slice! 3,695 -> 3,765), force_encoding there and back 4,139 + -> 4,318, index after a switch 9,853 -> 10,092, getbyte and bytes that switch +41 and +46; size + and plain level. Checks: strcow, dup, string-search and hot-shapes matrices in every mode and with + the switch off: PASS; spec/core/string 3,963 examples, the one known try_convert wording error on + master, here and switched off; 60 MutableString, String and Encoding IronRuby.Tests: PASSED. + Left: writes into the array a caller got (`EnsureCapacity`, `GetWritableByteArray`, for buffers + and native code) are outside this; a writer's multi-step change that sets content and encoding + unheld (`Replace`, the end of `Transcode`) is safe against a reader's switch only because its + last store is unconditional. + - **perf/strcow (2026-11-27, not gated) - a String slice copied while the content is held; a long tail slice shares the array, as MRI's** (gap 24's dup note). Asked for: copy-on-write content for dup, `+` and slices. Found: it is there already - CharArrayContent and BinaryContent share diff --git a/Util/string-race-matrix.rb b/Util/string-race-matrix.rb index 8fb021d86..2441885b5 100644 --- a/Util/string-race-matrix.rb +++ b/Util/string-race-matrix.rb @@ -12,7 +12,8 @@ # # A row is " / : ok", "wrong" (an answer of no state), "raises " or, when the # writer itself failed (a reader that changes how the string is held can do that to it), "writer -# raises ". A reader with a block (each_char, each_byte) lets the writer run between yields in +# raises ", or, when the string the writer leaves is not the state it began from (each flip +# ends where it began), "lost write". A reader with a block (each_char, each_byte) lets the writer run between yields in # CRuby too, so only its exceptions count. Run it # many times (the races are rare): a single run proves little. READS sets the reads per row. # -*- frozen_string_literal: false -*- @@ -112,7 +113,10 @@ def allowed?(allowed, a) end stop = true failed = writer.value + # each flip ends where it began: a write that a reader undid leaves something else + lost = !failed && !(s.encoding == states[0].encoding && s.b == states[0].b) result = if failed then "writer raises #{failed}" + elsif lost then "lost write" elsif !raised.empty? then "raises #{raised.uniq.map(&:to_s).sort.join(', ')}" elsif wrong > 0 then "wrong" else "ok" end From 57222fda2b5f3d51961076264c4394659766ce57 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 09:41:11 +0000 Subject: [PATCH 137/439] Ledger: perf/startup4 landed, not gated (gap 26) RubyGems' boot files are precompiled in the startup library already. The entry records what their self time is made of (JIT, binds, CLR lookups, the string eval), the rbconfig change and its numbers (~10 M fewer main-thread instructions on each of the five commands, release image and R2R host), and the next leads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Util/perf/LEDGER.md | 63 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 4f270c370..824b891cf 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1400,6 +1400,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has -1.8% on `gem list` / `require "irb"` / irb, and -2.8% on `-e 1` (release image). What is left of RubyGems' boot is its own class bodies (specification, requirement, platform: ~40 ms of `-e 1`) and rbconfig (~12 ms). + 2026-11-27, perf/startup4 (Landed, not gated): RubyGems' boot files are all in the startup + library. Their self time is first binds, two `super` rules, specification.rb's string `eval` + and the R2R host's JIT. rbconfig.rb no longer uses CLR interop: -0.3 to -0.9% main-thread + instructions on all five commands. Next leads: the 4,989 CLR member lookups of ruby4.rb in `-e 1` + (5.9 ms), and eval'd strings in the startup library. 27. **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a @@ -1629,6 +1634,64 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/startup4 (2026-11-27) - RubyGems' boot files are precompiled already; rbconfig asks the host + instead of CLR interop (gap 26)** - not gated. Base c7cb16e (15285eb with perf/startup3). + Asked: are specification.rb, requirement.rb, platform.rb, specification_record.rb and rbconfig.rb + compiled at every boot? No. The startup library (`Util/aot/startup-files.txt`, written by + `Util/aot/startup-files.rb` from what `-e 1`, the gem commands and irb load; built by + `Util/aot/build-startup.sh` in the R2R publish and in `package-release.sh`) holds all 214 files a + boot loads, and `IR_STARTUP_DLL_TRACE=1` reports none stale. What a boot still parses is the method + JIT's re-parse of 11 `def`s, and specification.rb's string `eval` (line 1937, 906 chars, which + defines set_nil_attributes_to_nil and set_not_nil_attributes_to_default_values). + What their self time is (per-file load timer extended with PhaseTimer's bind and CLR-lookup counters, + R2R host, `-e 1`, ms; self = time in the file's own code, nested loads excluded): + | file | self | .NET JIT | binds | CLR lookups | rest | + |---|---|---|---|---|---| + | requirement | 13.7 | 5.9 | 3.8 (50) | 0.1 (99) | 4.0 | + | specification | 12.7 | 0.9 | 3.1 (101) | 0.2 (381) | 8.7 | + | rbconfig | 11.0 | 2.0 | 5.9 (34) | 1.4 (19) | 1.7 | + | platform | 8.5 | 3.0 | 2.3 (25) | 0.1 (68) | 3.2 | + | specification_record | 5.5 | 0.4 | 0.7 (17) | 0.0 (48) | 4.4 | + - Clock marks in specification.rb's class body: the `eval` ~3.7 ms (the process's first eval); + INITIALIZE_CODE_FOR_DEFAULTS (strings built with `inspect`) ~2.9; `Time.now.utc` ~1; the + @@attributes partition ~1. The ~15 ms around `@@default_value` is `Gem::Requirement`'s autoload, + requirement.rb itself. + - requirement.rb's JIT is BCL generics that the R2R host lacks: ConcurrentDictionary over + ValueTuple (8 methods), span helpers, and the members of + `IronRuby.Classes.Object$2`, a CLR type emitted at run time (2-3 such types per command, 10-28 JIT'd + methods). The release image precompiles the generics. + - The two dearest binds are `super` rules: Gem::Version.new 1.2 ms, Gem::Platform.new 0.7 ms. + - rbconfig.rb's binds are CLR interop: Assembly.get_entry_assembly.location 1.0 ms, get_entry_assembly + 0.5, Path.get_directory_name 0.4, Environment.Version / Major / Minor 0.2-0.3 each, plus their + reflection lookups. + Taken (f6a75af): rbconfig.rb reads the entry assembly's directory and the runtime's major.minor from + `IronRuby.__host_config__`, a private singleton method. Its bindir is a UTF-8 string, as + System::String#to_s gave it (a first try with EncodePath gave US-ASCII). rbconfig's self time + ~11 -> ~7-7.9 ms; its binds 34 -> 28, 5.9 -> 2.2 ms; its CLR lookups 19 -> 16 at ~0 ms. + Main-thread instructions (callgrind, TieredCompilation=0, base and new side by side), M: + | command | release image | R2R host | + |---|---|---| + | `-e 1` | 1,162.3 -> 1,151.8 (-0.90%) | 2,012.3 -> 2,001.8 (-0.52%) | + | `gem --version` | 1,337.2 -> 1,325.3 (-0.88%) | 2,273.7 -> 2,263.5 (-0.45%) | + | `gem list` | 2,242.6 -> 2,234.1 (-0.38%) | 3,378.4 -> 3,369.2 (-0.27%) | + | `require "irb"` | 2,358.3 -> 2,348.4 (-0.42%) | 3,424.6 -> 3,411.9 (-0.37%) | + | irb 1+1 | 2,527.4 -> 2,516.5 (-0.43%) | 3,684.9 -> 3,671.1 (-0.37%) | + ~10 M fewer on every command, none more. + Wall, best of 10 alternating, base / new, ms: release image 344 / 345, 399 / 347, 693 / 765, + 766 / 825, 843 / 852; R2R host 483 / 440, 586 / 538, 917 / 1000, 941 / 891, 1040 / 1036. Swings of + +-8-13% both ways on a machine that had just restarted: noise, far above the effect. + Checked: every RbConfig::CONFIG value, its encoding and frozenness, and RbConfig.ruby print the same + as the base on the R2R host and the Release build. So do Gem.loaded_specs, $LOADED_FEATURES and its + order, and default-gem lookups (perf/startup3's probe). -w prints nothing, and + `IronRuby.__host_config__` is private. + AWFY verifying: at 3 s CD was killed at the deadline before one iteration on both trees, on a slow + machine. At 8 s in both orders CD, NBody, Sieve and Bounce verify, and none is slower in both orders + (Bounce +16% / 0%, NBody +9% / -1%). + Left in RubyGems' boot, all of it spread thin: the `super` rules; the first `eval` (~3.7 ms; the + startup library could hold eval'd strings keyed by their exact text, a general mechanism); + ruby4.rb's 4,989 CLR member lookups in `-e 1` (5.9 ms, core prelude, not RubyGems: worth finding + out what asks); and JIT that only the R2R host pays. + - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, not gated. A keyword From e05c583f50ce6915bb18b548f91c39b22eaa8eb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:45:54 +0000 Subject: [PATCH 138/439] Ledger: round 4's gate passes (15285eb against master) IronRuby.Tests, the matrices in 11 modes and the older switches, the probes, all five ruby/spec suites and the timing all pass; every DIFF is explained in the entry. Start-up passes the 5% rule but -e 1 is 4-5% slower in both runs, which the entry leaves open for round 5's start-up changes. The round's entries are marked gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 71 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 54 insertions(+), 17 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index d8502a3fe..09e33a66d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1091,7 +1091,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has method version (reading the code: `new` and `[]` added to the struct class's singleton class override `Class#new`, which invalidates sites on override), so it throws away every running loop's copy and every typed body's entry. - perf/struct (see Landed, not gated) measured it - 8 JIT invalidations for 30 `Struct.new`s + perf/struct (see Landed) measured it - 8 JIT invalidations for 30 `Struct.new`s beside a hot loop - and fixed it for anonymous classes (0); a reader and the first `new` on a new struct class take dispatchers instead of rules (4-9 and 10-25 us under IR_BIND_TRACE). `Struct.new(:a, :b)` plus a first new and getter 79.5 -> 51 us (CRuby 5.7); `Struct.new` alone @@ -1150,10 +1150,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Tried in round thirty-one (see Rejected, perf/dmeth): without the method JIT the call is only about 1.15 times a `def`'s, and a pooled BlockParam and a direct rule bought 1.16-1.2; what is left is the JIT taking a block body (a `JitStub` over a `BlockDefinition`). - Round of 2026-11-26 (see Landed, perf/dmethjit, not gated): taken; `bm1` 51 -> 26.5 ns against + Round of 2026-11-26 (see Landed, perf/dmethjit): taken; `bm1` 51 -> 26.5 ns against CRuby's 24. Left: bodies over captured locals, `block_given?`/`yield` or `super`, and calls with a block or a splat, which still take the rule. - Round of 2026-11-26, second (see Landed, perf/dmethjit2, not gated): bodies that read captured + Round of 2026-11-26, second (see Landed, perf/dmethjit2): bodies that read captured locals, and setters called as `o.x = v`, taken (`{ @h[name] }` 69.8 -> 53.3 ns, a `def` 49.7). Left: bodies that write a captured local (4 of 154 in the stdlib and gems), `yield`/`super`, and the `*args, &block` forwarders. @@ -1165,7 +1165,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the invoice shapes are at CRuby's time. Left: initializers taking keywords (`Product.new(sku: ...)`) at about 2x CRuby, `Hash#dup`, and Struct `keyword_init` as above. And `Data.singleton_methods` lists `:allocate`, which CRuby's does not (as on the baseline). - perf/struct (see Landed, not gated): Struct keyword creation is stored in C#, `kw_new` 1017 -> + perf/struct (see Landed): Struct keyword creation is stored in C#, `kw_new` 1017 -> 198 ns against CRuby's 299 (`kw_hash` 147 against 196, `sub_kw` 379 against 356). Left from this gap: keyword initializers (`kwinit` 236 against 132) and `Hash#dup`. perf/struct2 (see Rejected) measured both in a method's loop rather than the shape file's @@ -1623,9 +1623,46 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-27 for round 4 of round thirty-seven** (perf/strdup, perf/strsearch2, + perf/extiter2 and 3, perf/lframe, perf/lexical2 and 3, perf/kwrest, perf/jitscreen and 2, + perf/deadconst2, perf/permute, perf/havlak, perf/dmethjit2, perf/jitsettle; the rejected + perf/struct2, perf/lsite2 and perf/startup's hot-rule bridge, ledger and tools only): the branch + `claude/happy-gauss-95wm2j` at 15285eb against master f81fc19, Release net10.0, four cores: **PASS**. + IronRuby.Tests (`parallel-tests.sh`): 1,352 tests, every one executed, no failed or flaky name (the + script's INCOMPLETE is the driver's `Current culture: ` banner, as at round thirty-seven's gate). + `gate-matrices.rb --all`, 171 matrices in 11 modes (the six default ones, and `IR_FAST_DUP`, + `IR_JIT_REST`, `IR_JIT_UNSAMPLED`, `IR_KWREST_IN_PLACE`, `IR_LIGHT_ENTRY` off): 1,502 same, 353 + baseline, 26 DIFF, each explained. callable-parameters-matrix (11): `method(:puts).to_proc`'s prelude + line moved again (CRuby says nil). thread-backtrace-matrix (3): the main thread's line 87 or 88 by + timing, 88 alone on both trees. caller-matrix's R2R row m8b: the R2R host leaves out Kernel#eval's + frames on both trees when run alone (master healed by timing in the sweep); a defect of the R2R + host's own, handed to perf/crubydiff. fiber-reclaim-matrix (11): its native-enumerator probe took + `each_with_index` over a Hash, which perf/extiter3 gave a cursor, so there was no fiber left to + reclaim; the probe now takes `combination(2)` (15285eb), and the matrix is then the same as the + baseline's in all 12 modes. The older switches (`IR_LIGHT_GLOBALS`, `IR_LIGHT_LEXICAL`, + `IR_LIGHT_KEYWORD_REST`, `IR_LIGHT_KEYWORD_SPLAT`, `IR_JIT_DEADCONST`, `IR_FAST_SEARCH`, `IR_FAST_NEXT`, + `IR_FAST_STRUCT`, `IR_JIT_DMETH`) over the 49 matrices of the code they touch: 440 same, 50 baseline. + Probes for the gate's questions (a million deep through the new frames, visibility around + define_method bodies, captured locals of a making method parked or called again, `$!` around the + deferred StopIteration) print CRuby's output with the JIT on and off; 2,000 abandoned enumerators + leave no more threads or memory than on master. + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against master: light frames 91.7% -> 94.1% of methods (658 up, none down), method JIT + compiles 11.6% -> 11.9% (131 up, none down). + AWFY, 8 iterations: all fourteen verify. Timing at load about 1: micro-table in both orders, no line + more than 5% slower in both (`arr` 1.07 / 1.00, `cmp` 1.13 / 1.00, `nil?` 1.14 / 1.01, one order + each). AWFY 12 in both orders: geomean new/base 0.989 and 1.013, none more than 5% slower in both + (Richards 0.996 / 1.039; Havlak 0.95 / 1.12, which follows the order). Alone, five rounds in each + order, medians new/base: NBody 1.023 / 1.005, List 1.004 / 1.000, Bounce 0.996 / 0.993. + Start-up on the R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 509 -> 528 and + 534 -> 562 (1.038, 1.052), `gem --version` 579 -> 598 and 632 -> 613, `gem list` 1073 -> 1056 and + 1052 -> 1098, `require "irb"` 986 -> 1036 and 1031 -> 1054 (1.050, 1.021), irb 1+1 1129 -> 1166 and + 1180 -> 1169. None more than 5% slower in both runs, but `-e 1` is 4-5% (20-28 ms) slower in both: + open, for perf/startup3 and 4 (round 5) to win back, and measured again at round 5's gate. + - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy - (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, not gated. A keyword + (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, gated 2026-11-27 (round 4's gate entry). A keyword call into a method whose rest takes the hash (`def r(*a)` called `r(i, k: 2)`; send, method_missing, `define_method { |*a| }`, every delegator without `ruby2_keywords`) paid about 1,400 instructions over passing the same Hash positionally. Bisected: the rule's @@ -1715,7 +1752,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has method": the candidate's method is resolved on the candidate class with the lookup's visibility (`InlinableCallee`), and a subclass never takes the inlined body (exact class check). -- **perf/jitsettle (2026-11-26) - a retired entry's cool-down costs nothing per call** - not gated. +- **perf/jitsettle (2026-11-26) - a retired entry's cool-down costs nothing per call** - gated 2026-11-27 (round 4's gate entry). A method whose typed body keeps failing (`x + 1` called with an Integer and a Float in turn) ran 10-16% slower than with the JIT off, as a `def` and as a define_method method. What it does per call, from a trace (`IR_JIT_VERBOSE=1`, a phase-by-phase timing of 12.5 million calls): after the first @@ -1754,7 +1791,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 32 calls, where it needed 1024 calls and the cool-down. - **perf/dmethjit2 (2026-11-26) - a define_method body that reads captured locals, and setters, in the - method JIT (gap 23)** - not gated. Chosen by a survey of the 154 `define_method` blocks in the + method JIT (gap 23)** - gated 2026-11-27 (round 4's gate entry). Chosen by a survey of the 154 `define_method` blocks in the standard library and the bundled gems (Prism, by parameters and what the body does with the enclosing scopes' locals): 66 have plain or no parameters and *read* a captured local with nothing else in the way (`{ @options[name] }`, `{ params[name] }`, `{ code }`, `{ @major_version >= v }`, @@ -1838,7 +1875,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Util/perf/callgrind/count.sh` counts instructions instead. - **perf/extiter3 (2026-11-26) - `with_index`, `each_with_index` and `with_object` enumerators - take `next` on a cursor over their source's (gap 35)** - not gated. Base 1efd7e6 (the merged + take `next` on a cursor over their source's (gap 35)** - gated 2026-11-27 (round 4's gate entry). Base 1efd7e6 (the merged branch at 2f8c31c with perf/extiter2). The prelude's Enumerator#with_index (and so #each_with_index) and #with_object made without a block are generators; they now mark the enumerator they return with its source and offset or memo (`__iter_index_source__`), and @@ -1869,7 +1906,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Loop*, Fiber*, Backtrace*, Exception*, Raise*, Rescue*) pass. - **perf/extiter2 (2026-11-26) - `map`, `collect`, `select`, `filter`, `find_all` and `reject` - enumerators take `next` on a cursor, with no fiber (gap 35)** - not gated. Base: the merged + enumerators take `next` on a cursor, with no fiber (gap 35)** - gated 2026-11-27 (round 4's gate entry). Base: the merged branch at 2f8c31c, which has perf/extiter. An enumerator of Array's own #map / #collect / #select / #filter / #reject, or of Enumerable's #map / #collect / #select / #filter / #find_all / #reject over a receiver whose #each a cursor walks (Range, Hash#map and @@ -1897,7 +1934,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/lexical2 (/perf-step, 2026-11-26, on 2f8c31c) - keywords beside a rest or post parameter, and a hash passed on as keywords, in light frames (`IR_LIGHT_KEYWORD_REST`, - `IR_LIGHT_KEYWORD_SPLAT`, gap 9)** - census only, not gated. Chosen over the other "not a + `IR_LIGHT_KEYWORD_SPLAT`, gap 9)** - census only, gated 2026-11-27 (round 4's gate entry). Chosen over the other "not a light frame" lines of the census of 2f8c31c because it is the one the prelude has: 24 of its 101 methods (`String#each_line`, `String#lines`, `IO#initialize`, `File#initialize`, `Data#initialize`, `Kernel#open`, `IO.readlines`, `Enumerator.produce`), against 2 of the 71 @@ -1952,7 +1989,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Util/lexical-light-matrix.rb` probes both again and prints CRuby's output in every mode. - **perf/deadconst2 (/perf-step, 2026-11-26, on claude/happy-gauss-95wm2j 2f8c31c) - a typed method body - whose loop folded a constant sees it reassigned at the loop's next safe point (gap 29)** - not gated. + whose loop folded a constant sees it reassigned at the loop's next safe point (gap 29)** - gated 2026-11-27 (round 4's gate entry). The fault perf/deadconst found: a method body's `while` that folded a constant, with nothing else that may deopt (a Float counter: an Int one's overflow check is a deopt), went on with the old value after another thread reassigned the constant, until the call returned; CRuby's next read sees the new one. @@ -1993,7 +2030,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has before `LoopGuard.Set` publishes the epoch. - **perf/jitscreen2 (2026-11-26) - a multiple assignment of a list in a body the method JIT - compiles** (`a, b = b, a`, `@a, @b = x, y`) - census only, not gated. With the census + compiles** (`a, b = b, a`, `@a, @b = x, y`) - census only, gated 2026-11-27 (round 4's gate entry). With the census counting honestly, the lines after the Hash literal were String literals (101) and multiple assignment (75). The String literals left are arguments of calls on self (`add_tag :BOLD, "\e[1m"`, Json's `read_char('-')`: taking them was perf/strlit's rejected first build, gap 1's @@ -2043,7 +2080,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has typed compiler makes (its TransformReadCore throws). - **perf/jitscreen (2026-11-26) - a Hash literal in a body the method JIT compiles** (`{}`, - `{a: x}`, `{"k" => v}`, `opts = {}`) - census only, not gated. The screen refused every Hash + `{a: x}`, `{"k" => v}`, `opts = {}`) - census only, gated 2026-11-27 (round 4's gate entry). The screen refused every Hash literal, the largest line of "JIT never, one thing only" that is not a call once the census counts honestly (first commit below). `EmitHashLiteral` makes the Hash the generic body makes (`HashConstructor.TransformReadCore`): keys and values in order, through the same code @@ -2057,7 +2094,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has operand of a binary operator. JIT compiles 11.6% -> 11.9% (3,296 -> 3,370), maybe 10.3% -> 10.5% (2,923 -> 2,981), never 78.1% -> 77.6% (22,157 -> 22,025), light frames unchanged (Src/StdLib + AWFY, 28,376 methods; - 132 methods moved up - 74 to `compiles`, 58 to `maybe` - none down) - census only, not gated. + 132 methods moved up - 74 to `compiles`, 58 to `maybe` - none down) - census only, gated 2026-11-27 (round 4's gate entry). `HashConstructor` refused at all 977 -> 331, alone 136 -> 5 (keys that are not plain literals, and literals of more than five pairs, stay refused). Moved: mostly `initialize` methods that set `@h = {}`, `to_h` and `marshal_dump` methods returning `{key: @ivar, ...}`, and `opts = {}` defaults; in the prelude @@ -2097,7 +2134,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has strlit's literal makers were; not tried here. For the gate: no IronRuby.Tests or spec run; the decline above. -- **perf/strdup (2026-11-26, not gated) - `String#dup` is String's own, MRI's rb_str_dup_m** (gap +- **perf/strdup (2026-11-26, gated 2026-11-27 (round 4's gate entry)) - `String#dup` is String's own, MRI's rb_str_dup_m** (gap 24's dup note). Kept as a CRuby-compatibility fix, not as a speed-up. `Util/dup-matrix.rb` (new: String, Object and Array dup and clone - content, encodings, broken bytes, frozen and chilled, ivars, singleton classes, subclasses, a refinement, TracePoint, and the hooks redefined in String, Object @@ -2117,7 +2154,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has on both builds. - **perf/strsearch2 (2026-11-26) - `#start_with?` with one String prefix takes no scope; an - ASCII prefix is compared in place (gap 21, round two)** - not gated. Commit dc1d136 on + ASCII prefix is compared in place (gap 21, round two)** - gated 2026-11-27 (round 4's gate entry). Commit dc1d136 on `claude/perf-strsearch`, based on the merged branch 2f8c31c. `start_with?` had one overload, which takes the caller's scope to store `$~` for a Regexp prefix, so a light frame calling it with a String made its scope on the call (`RubyOps.LightScopeRequired`) and called again. A @@ -2147,7 +2184,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has TypeError if it's not a kind of String`, run as a directory). - **perf/lframe (/perf-frame, 2026-11-26) - a cheaper method entry: the alias name and the - traced test** (switch `IR_LIGHT_ENTRY`, on unless `=0`) - instructions only, not gated. + traced test** (switch `IR_LIGHT_ENTRY`, on unless `=0`) - instructions only, gated 2026-11-27 (round 4's gate entry). Built on 2f8c31c. What gap 16's profiles left on every light frame, looked at on its own with `Util/bench/frame-cost.rb` (new: a method that does nothing, one, three calls, a yield, `block_given?`, and `String#bytesplice`), `-X:NoJIT` so that the generic bodies run. From eab3ef8d8630cbbfc84783abafc85734a94e8c39 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:51:03 +0000 Subject: [PATCH 139/439] Eval'd code remembers where a local it knows by name resolved Eval'd code reads a local its text does not declare - the binding's, or one an earlier eval defined, which an eval's own top-level locals are (ERB's _erbout) - through RubyOps.GetLocalVariable(scope, name): a walk up the scopes with a string lookup in each one's static mapping and, where an eval or Binding defined locals, a lookup in that dictionary under a lock. About 700 instructions a read (gap 31: about 300 such accesses per ERB render). The dynamic locals now hold a cell per local, kept for the scope's life, and eval'd code reads and writes them through GetLocalVariableAtSite / SetLocalVariableAtSite with a LocalVariableSite, a constant of the compiled code that the compiled-code cache shares across bindings and threads. It remembers one immutable resolution - the slot of the declaring scope's locals, or the cell - and reuses it while no scope of the runtime has gained a dynamic local or dropped its dynamic locals since (a version on RubyContext, bumped by DefineDynamicVariable for a new name and by ResetForReuse), and the scope is the same or reaches the same holder through scopes with the same locals tables (the next run of the same block: a scope's static locals are its body's table, and its parent never changes). Otherwise it resolves again; a name that does not resolve is looked up as before. IR_EVAL_LOCAL_CACHE=0 turns it off. Instructions a unit (Util/perf/callgrind/count.sh; switch off -> on): an ERB render 1,453,260 -> 1,255,820 (0.864), result_with_hash 0.879, an eval'd loop reading the binding's local 0.621, one whose every local is dynamic 0.366; eval('1 + 1') and a loop of static locals 1.000 and 1.002. Keying the resolution on the scope alone made ERB 3.5% slower (each iteration of a block is a new scope); the chain check is what makes it a gain. The timed runs overlapped on the shared machine. Util/eval-locals-matrix.rb (new) prints CRuby 4.0's output on the unchanged build and on this one in every mode (the switch off, IR_LIGHT_FRAMES=0, IR_LIGHT_ENTRY=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls); erb-escape, lexical-light, global-light, block-scope-reuse, light-entry and hot-shapes print what they did. ruby/spec core/binding, core/kernel/eval_spec.rb and library/erb pass as before. Eval_LocalVariableSites1 is new; it and 31 named eval, binding and block tests pass. ReflectionCache.Generated.cs is ClassInitGenerator's output. erb-shapes.rb counts instructions under INSTR and has the eval_reads shapes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 37 ++++++ .../Compiler/Ast/LeftValues/LocalVariable.cs | 13 ++ .../Compiler/ReflectionCache.Generated.cs | 4 + Src/Ruby/Runtime/LocalVariableSite.cs | 92 ++++++++++++++ Src/Ruby/Runtime/RubyContext.cs | 12 ++ Src/Ruby/Runtime/RubyOps.cs | 22 ++++ Src/Ruby/Runtime/RubyScope.cs | 103 ++++++++++++++-- Util/bench/erb-shapes.rb | 29 ++++- Util/eval-locals-matrix.rb | 112 ++++++++++++++++++ 10 files changed, 413 insertions(+), 12 deletions(-) create mode 100644 Src/Ruby/Runtime/LocalVariableSite.cs create mode 100644 Util/eval-locals-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index edc28ec68..c509012bd 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1278,6 +1278,7 @@ public Tests(Driver/*!*/ driver) { Binding1, TopLevelBinding_RubyProgram, EvalWithProcBinding1, + Eval_LocalVariableSites1, ModuleEvalProc1, ModuleEvalProc2, ModuleEvalProc3, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 1f7bb1c44..34b1a70ff 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7900,6 +7900,43 @@ p opt(1), opt(1, k: 2), req(1, k: 2), two(1, 2, k: 3), none, rest(1, z: 2), orde "); } + /// + /// IR_EVAL_LOCAL_CACHE: eval'd code reads and writes the locals it knows by name through a site that remembers + /// where the name resolved (LocalVariableSite) - one text on two bindings, locals an eval defined, local_variable_set + /// after a read, a block of the text, a binding of a light frame, Binding#dup, a local another thread defined + /// (Util/eval-locals-matrix.rb). + /// + public void Eval_LocalVariableSites1() { + TestOutput(@" +require 'ruby4' +def b_with(**h) = binding.tap { |b| h.each { |k, v| b.local_variable_set(k, v) } } +TEXT = ""v * 2"" +r = [b_with(v: 1), b_with(v: 2)].map { |b| eval(TEXT, b) } +b = binding +eval(""x = 1"", b); eval(""x += 1"", b) +c = b_with(v: 3) +r1 = eval(""v"", c); c.local_variable_set(:v, 4) +s = b_with(v: 1) +eval(""[1, 2].each { |e| v += e }"", s) +def light(a) = (eval(""a = a + 10"", binding); a) +d = b_with(v: 1).dup; eval(""v = 9; n = 1"", d) +t = binding +Thread.new { eval(""tt = 7"", t) }.join +p r, eval(""x"", b), b.local_variable_get(:x), [r1, eval(""v"", c)], s.local_variable_get(:v), light(1), eval(""n"", d), eval(""tt"", t) +p 30.times.map { |i| eval(""v + 1"", b_with(v: i % 3)) }.uniq +", @" +[2, 4] +2 +2 +[3, 4] +4 +11 +1 +7 +[1, 2, 3] +"); + } + /// /// A method that reads or writes a global is a light frame too (MethodDefinition.IsLightGlobal): every global but $~ and /// $_ is the runtime's, and the frame reads and writes it through the declaring scope. A name that comes to denote $~ or $_ diff --git a/Src/Ruby/Compiler/Ast/LeftValues/LocalVariable.cs b/Src/Ruby/Compiler/Ast/LeftValues/LocalVariable.cs index 2b4f28215..7c4889754 100644 --- a/Src/Ruby/Compiler/Ast/LeftValues/LocalVariable.cs +++ b/Src/Ruby/Compiler/Ast/LeftValues/LocalVariable.cs @@ -60,6 +60,9 @@ internal void SetClosureIndex(int index) { return gen.CurrentScope.GetVariableAccessor(_definitionLexicalDepth, _closureIndex); } else { // dynamic lookup: + if (LocalVariableSitesEnabled) { + return Methods.GetLocalVariableAtSite.OpCall(gen.CurrentScopeVariable, AstUtils.Constant(new IronRuby.Runtime.LocalVariableSite(Name))); + } return Methods.GetLocalVariable.OpCall(gen.CurrentScopeVariable, AstUtils.Constant(Name)); } } @@ -73,6 +76,10 @@ internal void SetClosureIndex(int index) { return Ast.Assign(gen.CurrentScope.GetVariableAccessor(_definitionLexicalDepth, _closureIndex), AstUtils.Box(rightValue)); } else { // dynamic lookup: + if (LocalVariableSitesEnabled) { + return Methods.SetLocalVariableAtSite.OpCall(AstUtils.Box(rightValue), gen.CurrentScopeVariable, + AstUtils.Constant(new IronRuby.Runtime.LocalVariableSite(Name))); + } return Methods.SetLocalVariable.OpCall(AstUtils.Box(rightValue), gen.CurrentScopeVariable, AstUtils.Constant(Name)); } } @@ -80,5 +87,11 @@ internal void SetClosureIndex(int index) { internal override string/*!*/ GetNodeName(AstGenerator/*!*/ gen) { return "local-variable"; } + + /// + /// IR_EVAL_LOCAL_CACHE=0 makes eval'd code read and write the locals it knows by name only through the lookup by + /// name on every access again, instead of a site that remembers where the name resolved (LocalVariableSite). + /// + private static readonly bool LocalVariableSitesEnabled = System.Environment.GetEnvironmentVariable("IR_EVAL_LOCAL_CACHE") != "0"; } } diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 78461b40d..4c1e9e71b 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -312,6 +312,8 @@ public static partial class Methods { private static MethodInfo _GetLocals; public static MethodInfo/*!*/ GetLocalVariable { get { return _GetLocalVariable ?? (_GetLocalVariable = CallInstruction.CacheFunc(RubyOps.GetLocalVariable)); } } private static MethodInfo _GetLocalVariable; + public static MethodInfo/*!*/ GetLocalVariableAtSite { get { return _GetLocalVariableAtSite ?? (_GetLocalVariableAtSite = CallInstruction.CacheFunc(RubyOps.GetLocalVariableAtSite)); } } + private static MethodInfo _GetLocalVariableAtSite; public static MethodInfo/*!*/ GetMetaObject { get { return _GetMetaObject ?? (_GetMetaObject = CallInstruction.CacheFunc(RubyOps.GetMetaObject)); } } private static MethodInfo _GetMetaObject; public static MethodInfo/*!*/ GetMethodBlockParameter { get { return _GetMethodBlockParameter ?? (_GetMethodBlockParameter = CallInstruction.CacheFunc(RubyOps.GetMethodBlockParameter)); } } @@ -622,6 +624,8 @@ public static partial class Methods { private static MethodInfo _SetInstanceVariable; public static MethodInfo/*!*/ SetLocalVariable { get { return _SetLocalVariable ?? (_SetLocalVariable = CallInstruction.CacheFunc(RubyOps.SetLocalVariable)); } } private static MethodInfo _SetLocalVariable; + public static MethodInfo/*!*/ SetLocalVariableAtSite { get { return _SetLocalVariableAtSite ?? (_SetLocalVariableAtSite = CallInstruction.CacheFunc(RubyOps.SetLocalVariableAtSite)); } } + private static MethodInfo _SetLocalVariableAtSite; public static MethodInfo/*!*/ SetMethodMissingReason { get { return _SetMethodMissingReason ?? (_SetMethodMissingReason = CallInstruction.CacheAction(RubyOps.SetMethodMissingReason)); } } private static MethodInfo _SetMethodMissingReason; public static MethodInfo/*!*/ SetMissingMethodArguments { get { return _SetMissingMethodArguments ?? (_SetMissingMethodArguments = CallInstruction.CacheFunc(RubyOps.SetMissingMethodArguments)); } } diff --git a/Src/Ruby/Runtime/LocalVariableSite.cs b/Src/Ruby/Runtime/LocalVariableSite.cs new file mode 100644 index 000000000..4e77aeb55 --- /dev/null +++ b/Src/Ruby/Runtime/LocalVariableSite.cs @@ -0,0 +1,92 @@ +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Apache License, Version 2.0, please send an email to + * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound + * by the terms of the Apache License, Version 2.0. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using System.Runtime.CompilerServices; + +namespace IronRuby.Runtime { + /// + /// A read or write of a local that eval'd code knows by name only - the binding's, or one an earlier eval defined + /// (LocalVariable with no lexical depth, RubyOps.GetLocalVariable / SetLocalVariable). It remembers where the name + /// resolved from the last scope it ran in: a slot of the locals of the scope that declares it, or the cell of one + /// an eval or Binding defined (RubyScope.TryResolveLocal). The compiled code of a text is shared by every eval of + /// it (EvalCodeCache) and so by every binding and thread, so the memory is one immutable object, replaced whole, + /// and good only while no scope of the runtime has gained a dynamic local since (RubyContext.LocalVariableSitesVersion) + /// and for the same scope, or one that reaches the same holder through scopes of the same bodies (the next run of a + /// block): a new dynamic local is the one thing that can make a name resolve elsewhere - a scope's static locals are + /// its body's compiled table, its parent never changes, and a cell stays the local's for the scope's life. + /// + public sealed class LocalVariableSite { + internal readonly string/*!*/ Name; + private Resolution _last; + + internal LocalVariableSite(string/*!*/ name) { + Name = name; + } + + internal sealed class Resolution { + internal readonly RubyScope/*!*/ Start; + internal readonly int Version; + private readonly RubyScope/*!*/ _holder; + private readonly int _index; + private readonly StrongBox _cell; + // the locals tables of the scopes the lookup passed on its way from Start to the holder, nearest first + private readonly string[]/*!*/[]/*!*/ _passed; + + internal Resolution(RubyScope/*!*/ start, int version, RubyScope/*!*/ holder, int index, StrongBox cell, + string[]/*!*/[]/*!*/ passed) { + Start = start; + Version = version; + _holder = holder; + _index = index; + _cell = cell; + _passed = passed; + } + + // Another scope that reaches the same holder through scopes of the same bodies: the next run of a block. + internal bool HoldsFor(RubyScope/*!*/ scope) { + return scope.ResolvesThroughSameChain(_passed, _holder); + } + + internal object Read() { + return (_cell != null) ? _cell.Value : _holder.GetLocalSlotValueForSite(_index); + } + + internal void Write(object value) { + if (_cell != null) { + _cell.Value = value; + } else { + _holder.SetLocalSlotValueForSite(_index, value); + } + } + } + + // The resolution for this scope, if the last one still holds; else a new one, remembered, or null if the name does + // not resolve (then nothing is remembered: the call is made by name, as before). + internal Resolution Resolve(RubyScope/*!*/ scope) { + var last = _last; + var context = scope.RubyContext; + int version = context.LocalVariableSitesVersion; + if (last != null && last.Version == version && (last.Start == scope || last.HoldsFor(scope))) { + return last; + } + var resolution = scope.TryResolveLocal(Name, version); + if (resolution != null) { + _last = resolution; + } + return resolution; + } + } +} diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index f3dd60b58..b348d72dc 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -353,6 +353,18 @@ public void StartRactors() { // a table it actually changed. internal int RefinementVersion = 1; + // Bumped whenever a scope of this runtime gains a dynamic local (an eval's or Binding's), or drops its dynamic + // locals: what a LocalVariableSite remembered may no longer be where its name resolves. + private int _localVariableSitesVersion; + + internal int LocalVariableSitesVersion { + get { return Volatile.Read(ref _localVariableSitesVersion); } + } + + internal void InvalidateLocalVariableSites() { + Interlocked.Increment(ref _localVariableSitesVersion); + } + // Every module that Module#refine has ever been called on. Empty in a program that never calls // refine, which is what keeps the whole feature off the fast path. private readonly Dictionary _refinedModules = new Dictionary(); diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index ac08cb622..9738a78f7 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -804,6 +804,28 @@ public static object SetLocalVariable(object value, RubyScope/*!*/ scope, string return scope.ResolveAndSetLocalVariable(name, value); } + /// + /// from a site that remembers where the name resolved (IR_EVAL_LOCAL_CACHE): a + /// read of the slot or cell, without the lookup by name and its lock, while the scope and the runtime's + /// dynamic locals are what they were. + /// + [Emitted] + public static object GetLocalVariableAtSite(RubyScope/*!*/ scope, LocalVariableSite/*!*/ site) { + var resolution = site.Resolve(scope); + return (resolution != null) ? resolution.Read() : scope.ResolveLocalVariable(site.Name); + } + + [Emitted] + public static object SetLocalVariableAtSite(object value, RubyScope/*!*/ scope, LocalVariableSite/*!*/ site) { + var resolution = site.Resolve(scope); + if (resolution != null) { + resolution.Write(value); + return value; + } + // a name not visible from here: defined in the scope that takes it, as before + return scope.ResolveAndSetLocalVariable(site.Name, value); + } + [Emitted] public static VersionHandle/*!*/ GetSelfClassVersionHandle(RubyScope/*!*/ scope) { return scope.SelfImmediateClass.Version; diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 8d73bad3c..719ee79ad 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -133,8 +133,9 @@ public void MarkCaptured() { internal sealed class RareState { // closure: name -> slot of the compiled locals, built for eval and Binding on demand public Dictionary StaticLocalMapping; - // closure: locals an eval or Binding#local_variable_set introduced - public Dictionary DynamicLocals; + // closure: locals an eval or Binding#local_variable_set introduced, each in a cell of its own that it keeps for + // the scope's life, so that a site of eval'd code can hold on to it (RubyOps.GetLocalVariable, LocalVariableSite) + public Dictionary> DynamicLocals; // Refinements activated by `using' in this scope, in activation order; null until `using' runs here. public List UsedModules; @@ -166,7 +167,7 @@ private Dictionary StaticLocalMapping { set { Rare.StaticLocalMapping = value; } } - private Dictionary DynamicLocals { + private Dictionary> DynamicLocals { get { var r = _rare; return (r != null) ? r.DynamicLocals : null; } } @@ -265,6 +266,10 @@ internal void ResetForReuse(MutableTuple locals, object selfObject, InterpretedF _selfObject = selfObject; _selfImmediateClass = null; _methodAttributes = RubyMethodAttributes.PublicInstance; + if (_rare != null && _rare.DynamicLocals != null) { + // the cells a site may hold go with them (LocalVariableSite) + RubyContext.InvalidateLocalVariableSites(); + } _rare = null; InterpretedFrame = interpretedFrame; } @@ -437,7 +442,13 @@ private bool TryGetLocal(string/*!*/ name, out object value) { } lock (DynamicLocals) { - return DynamicLocals.TryGetValue(name, out value); + StrongBox cell; + if (DynamicLocals.TryGetValue(name, out cell)) { + value = cell.Value; + return true; + } + value = null; + return false; } } @@ -456,11 +467,12 @@ private bool TrySetLocal(string/*!*/ name, object value) { } lock (DynamicLocals) { - if (!DynamicLocals.ContainsKey(name)) { + StrongBox cell; + if (!DynamicLocals.TryGetValue(name, out cell)) { return false; } - DynamicLocals[name] = value; + cell.Value = value; } return true; } @@ -478,7 +490,7 @@ private bool TrySetLocal(string/*!*/ name, object value) { if (DynamicLocals != null) { lock (DynamicLocals) { foreach (var entry in DynamicLocals) { - yield return entry; + yield return new KeyValuePair(entry.Key, entry.Value.Value); } } } @@ -708,12 +720,85 @@ internal object ResolveAndSetLocalVariable(string/*!*/ name, object value) { /// internal virtual void DefineDynamicVariable(string/*!*/ name, object value) { if (DynamicLocals == null) { - Interlocked.CompareExchange(ref Rare.DynamicLocals, new Dictionary(), null); + Interlocked.CompareExchange(ref Rare.DynamicLocals, new Dictionary>(), null); } lock (DynamicLocals) { - DynamicLocals[name] = value; + StrongBox cell; + if (DynamicLocals.TryGetValue(name, out cell)) { + cell.Value = value; + return; + } + DynamicLocals[name] = new StrongBox(value); + } + // a name new to this scope can shadow what a site resolved it to further out (LocalVariableSite) + RubyContext.InvalidateLocalVariableSites(); + } + + /// + /// Where resolves from this scope, as looks it up: a slot + /// of the locals of the scope that declares it, or the cell of one an eval or Binding defined. Null if it does not + /// resolve. For a site of eval'd code to read and write it again without the lookup (LocalVariableSite). + /// + internal LocalVariableSite.Resolution TryResolveLocal(string/*!*/ name, int version) { + RubyScope scope = this; + var passed = new List(); + while (true) { + scope.EnsureBoxes(); + int index; + var mapping = scope.StaticLocalMapping; + if (mapping != null && mapping.TryGetValue(name, out index) && !scope.IsImplicitParameter(name)) { + return new LocalVariableSite.Resolution(this, version, scope, index, null, passed.ToArray()); + } + + var dynamicLocals = scope.DynamicLocals; + if (dynamicLocals != null) { + StrongBox cell; + lock (dynamicLocals) { + dynamicLocals.TryGetValue(name, out cell); + } + if (cell != null) { + return new LocalVariableSite.Resolution(this, version, scope, -1, cell, passed.ToArray()); + } + } + + // a scope without its locals installed yet cannot be told from another by them + if (!scope.InheritsLocalVariables || scope._variableNames == null) { + return null; + } + + passed.Add(scope._variableNames); + scope = scope.Parent; + } + } + + /// + /// Whether is where a name resolves from this scope as it did from another scope whose + /// chain up to it passed scopes with these locals (, nearest first) - the same block run + /// again in a new scope: a scope's own locals are its compiled table, shared by every scope of the same body, so + /// the same table cannot hold the name now if it did not then; a dynamic local that could is covered by the + /// version of the site's resolution (LocalVariableSite). + /// + internal bool ResolvesThroughSameChain(string[]/*!*/[]/*!*/ passed, RubyScope/*!*/ holder) { + RubyScope scope = this; + for (int i = 0; i < passed.Length; i++) { + if (!ReferenceEquals(scope._variableNames, passed[i]) || !scope.InheritsLocalVariables) { + return false; + } + scope = scope.Parent; + if (scope == null) { + return false; + } } + return ReferenceEquals(scope, holder); + } + + internal object GetLocalSlotValueForSite(int index) { + return GetLocalValue(index); + } + + internal void SetLocalSlotValueForSite(int index, object value) { + SetLocalValue(index, value); } #endregion diff --git a/Util/bench/erb-shapes.rb b/Util/bench/erb-shapes.rb index 8803f7c73..cb052209e 100644 --- a/Util/bench/erb-shapes.rb +++ b/Util/bench/erb-shapes.rb @@ -31,12 +31,25 @@ def fresh_top(title) = (b = TOPLEVEL_BINDING.dup; b.local_variable_set(:title, t def fresh(title) = (b = binding; b.local_variable_set(:title, title); b.local_variable_set(:items, ITEMS); b) def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a unit, from the least of the seven sections. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) def t(name, n) return puts(name) if ARGV == ['--list'] return unless ARGV.empty? || ARGV.include?(name) - best = 1e9; sum = nil - 7.times { t0 = cpu; sum = yield n; d = cpu - t0; best = d if d < best } - printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum + best = 1e9; sum = nil; fewest = nil; counted = !!INSTR + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu; sum = yield n; d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' end N = (ENV["N"] || 1000).to_i def n(count) = [count * N / 1000, 1].max @@ -48,3 +61,13 @@ def n(count) = [count * N / 1000, 1].max t("erb_toplevel", n(3000)) { |n| s = 0; n.times { |i| b = ERBT.send(:new_toplevel, [:title, :items]); b.local_variable_set(:title, i); s += b.local_variable_get(:title) }; s } t("erb_new", n(1000)) { |n| s = 0; n.times { s += crc(ERB.new(PAGE, trim_mode: '-').src) }; s } t("eval_small", n(10000)) { |n| s = 0; n.times { s += eval('1 + 1', binding) }; s } +# a read of a local the binding holds, not the text (RubyOps.GetLocalVariable): 1000 reads of v a unit, and the loop's +# own locals, which the eval defines on the binding too +LOOP = "i = 0; s = 0; while i < 1000; s += v; i += 1; end; s" +def fresh_v = (b = binding; b.local_variable_set(:v, 1); b) +t("eval_reads", n(30)) { |n| s = 0; n.times { s += eval(LOOP, fresh_v, '(reads)', 0) }; s } +# the same loop with its own locals static (a lambda's), reading v from the binding, and reading only its own +LOOP_V = "-> { i = 0; s = 0; while i < 1000; s += v; i += 1; end; s }.()" +LOOP_S = "-> { i = 0; s = 0; w = v; while i < 1000; s += w; i += 1; end; s }.()" +t("eval_reads_v", n(30)) { |n| s = 0; n.times { s += eval(LOOP_V, fresh_v, '(reads)', 0) }; s } +t("eval_reads_static", n(30)) { |n| s = 0; n.times { s += eval(LOOP_S, fresh_v, '(reads)', 0) }; s } diff --git a/Util/eval-locals-matrix.rb b/Util/eval-locals-matrix.rb new file mode 100644 index 000000000..81bc141da --- /dev/null +++ b/Util/eval-locals-matrix.rb @@ -0,0 +1,112 @@ +# Differential matrix for the locals an eval'd text reads and writes by name - the binding's, and the ones an +# earlier eval defined on it (RubyOps.GetLocalVariable / SetLocalVariable, RubyScope's dynamic locals). The +# compiled code of a text is kept and shared by every eval of the same text (EvalCodeCache), so one site meets +# many bindings: the probes alternate bindings, define locals between two reads, change a name from the +# method's own to one an eval defined, copy bindings, and run evals from other threads. Run it under CRuby and +# under ./ir.sh, and diff: +# +# ruby Util/eval-locals-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/eval-locals-matrix.rb > /tmp/on.txt 2>&1 +# IR_EVAL_LOCAL_CACHE=0 ./ir.sh Util/eval-locals-matrix.rb > /tmp/off.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt + +N = 3000 + +def t(label) + print label.ljust(52), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def err + yield +rescue Exception => e + "#{e.class}: #{e.message[0, 70]}" +end + +# ---------------------------------------------------------------- 1. one binding + +def b_with(**h) + b = binding + h.each { |k, v| b.local_variable_set(k, v) } + b +end + +t('eval defines, next eval reads') { |i| b = binding; eval("x = #{i % 3}", b); eval("x", b) } +t('defined by an eval that does not assign') { |i| b = binding; eval("x = 1 if false", b); [b.local_variable_defined?(:x), eval("x", b)] } +t('local_variable_set, then eval reads') { |i| b = b_with(v: i % 4); eval("v + 1", b) } +t('eval writes, local_variable_get reads') { |i| b = b_with(v: 0); eval("v = #{i % 3}", b); b.local_variable_get(:v) } +t('eval writes, the same eval reads') { |i| b = b_with(v: i % 2); eval("v += 10; v * 2", b) } +t('a loop of reads and writes') { |i| b = b_with(v: i % 3); eval("s = 0; j = 0; while j < 5; s += v; j += 1; end; s", b) } +t('a block in the text reads and writes') { |i| b = b_with(v: 1); eval("[1, 2].each { |e| v += e }; v", b) } +t('several evals, one binding') do |i| + b = binding + eval("a = #{i % 2}", b); eval("b2 = a + 1", b); eval("a = b2 * 10", b) + [eval("a", b), eval("b2", b), b.local_variables.sort] +end +t('a new local between two reads') do |i| + b = b_with(v: i % 3) + r1 = eval("v", b) + eval("w#{i % 5} = 1", b) + b.local_variable_set(:v, r1 + 1) + [r1, eval("v", b)] +end + +# ---------------------------------------------------------------- 2. the same text, many bindings + +TEXT = "v * 2 + (defined?(w) ? 1 : 0)" +t('alternating bindings') { |i| bs = [b_with(v: 1), b_with(v: 2), b_with(v: 3, w: 0)]; bs.map { |b| eval(TEXT, b) } } +held = [b_with(v: 5), b_with(v: 6)] +t('two kept bindings, alternating') { |i| b = held[i % 2]; eval("v += 1; v", b) % 4 } +def method_local(v) = eval("v * 2", binding) +def method_dynamic = (b = binding; b.local_variable_set(:v, 7); eval("v * 2", b)) +t('the name the method\'s, then an eval\'s') { |i| i.even? ? method_local(i % 3) : method_dynamic } +def shadow(v) + [1].map { |v| eval("v", binding) } + [eval("v", binding)] +end +t('a block parameter shadows the method\'s') { |i| shadow(i % 3) } +t('a block\'s own local, then the method\'s') { |i| x = i % 2; [[0].map { |e| y = e + 5; eval("y + x", binding) }, eval("x", binding)] } + +# ---------------------------------------------------------------- 3. light frames, copies, the top level + +def light(a) = eval("a + 1", binding) +def light_write(a) = (eval("a = 50", binding); a) +def light_define(a) = (b = binding; eval("z = a", b); b.local_variable_get(:z)) +t('a binding taken in a light frame') { |i| [light(i % 3), light_write(i % 2), light_define(i % 4)] } +t('Binding#dup shares old, keeps new') do |i| + b = b_with(v: 1) + c = b.dup + eval("v = #{i % 3}", c); eval("n = 9", c) + [eval("v", b), b.local_variable_defined?(:n), eval("n", c)] +end +t('TOPLEVEL_BINDING.dup') { |i| b = TOPLEVEL_BINDING.dup; b.local_variable_set(:tv, i % 2); eval("tv + 1", b) } +t('instance_eval of a String reads the caller\'s local') { |i| loc = i % 3; Object.new.instance_eval("loc * 3") } +t('a missing name is a method call') { |i| b = b_with(v: 1); err { eval("vv", b) } } +t('local_variable_set after a read') { |i| b = b_with(v: 1); r = eval("v", b); b.local_variable_set(:v, i % 2); [r, eval("v", b)] } + +# ---------------------------------------------------------------- 4. threads and ERB + +require 'erb' +t('a local defined in another thread') do |i| + b = binding + Thread.new { eval("tt = #{i % 3}", b) }.join + eval("tt", b) +end +shared = b_with(c: 0) +t('evals on one binding from four threads') do |i| + next nil unless i % 500 == 0 + shared.local_variable_set(:c, 0) + 4.times.map { Thread.new { 200.times { eval("c += 1", shared) } } }.each(&:join) + eval("c", shared) > 0 +end +ERBT = ERB.new("<%= title %>:<% items.each do |it| %><%= it %>,<% end %>") +t('ERB#result_with_hash') { |i| ERBT.result_with_hash(title: "T#{i % 2}", items: [i % 3, 1]) } +t('ERB#result on bindings') { |i| title = "B"; items = [i % 2]; ERBT.result(binding) } From b45360cac58eacd1640d9527f1647fb36faad930 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:51:03 +0000 Subject: [PATCH 140/439] Ledger: perf/evallocals landed (instructions only, not gated); gap 31 updated Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index d655d74ea..bcbaa4fdd 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1500,6 +1500,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `module`) - the screen perf/evalc lacked. `erb_result` 0.31-0.33 of its time, `eval_small` 0.40. Left: the binding's locals read by name (about 300 `GetLocalVariable` per render, each under a lock), and an eval of a text the screen refuses costs what it did. + perf/evallocals (Landed): a read or write of such a local remembers where the name resolved + (`LocalVariableSite`); a render 0.86-0.88 of its instructions, a loop of eval'd reads 0.37. + Left: the first access of each site per render (a fresh binding defines `_erbout`, which + invalidates every site), and the cost of the eval itself. 32. **A singleton class, and a method defined at run time, cost 25 to 60 times CRuby's** (`Object.new.singleton_class` 17 us, `def o.x` 18, `define_singleton_method` 46, `Class.new` 12, with a `def` 37), and `OpenStruct.new(h)` of three keys, which @@ -1641,6 +1645,53 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/evallocals (/perf-step, 2026-11-27, on b887bc1 + perf/lexical a87b5dc) - a site of + eval'd code remembers where a local it knows by name resolved (`IR_EVAL_LOCAL_CACHE`, gap + 31)** - instructions only, not gated. Eval'd code reads a local the text does not declare + (the binding's, or one an earlier eval defined - an eval's own top-level locals are such, + ERB's `_erbout` among them) through `RubyOps.GetLocalVariable(scope, name)`: a walk up the + scopes, at each a string lookup in its static mapping and, where an eval or Binding defined + locals, a lookup in that dictionary under a lock. Measured first: about 700 instructions a + read (`eval_reads_v`, an eval'd loop reading `v` from the binding, 1,646 a turn against 941 + with only static locals), about 540 an access where every local is dynamic (`eval_reads`). + - The change: `DynamicLocals` holds a cell (`StrongBox`) per local, kept for the + scope's life; `GetLocalVariableAtSite` / `SetLocalVariableAtSite` take a + `LocalVariableSite` (a constant of the compiled code, shared by every eval of the text and + so by every binding and thread) that remembers one immutable resolution - the slot of the + declaring scope's locals or the cell - and reuses it while (1) no scope of the runtime has + gained a dynamic local or dropped its dynamic locals since (`RubyContext. + LocalVariableSitesVersion`, bumped by `DefineDynamicVariable` for a new name and by + `ResetForReuse`), and (2) the scope is the same, or reaches the same holder through scopes + with the same locals table at each step (the next run of the same block; a scope's static + locals are its body's compiled table and its parent never changes). Otherwise it resolves + again; a name that does not resolve is looked up by name as before. A resolution keyed on + the scope alone made ERB 1.034-1.037 *slower*: `items.each` runs each iteration in a new + block scope, so every read missed and paid the lookup and an allocation; the chain check + fixed that. + - Instructions a unit (`Util/perf/callgrind/count.sh`, `ab.rb -i -r 1 -n 1000 + Util/bench/erb-shapes.rb`; unchanged build / switch off / on): `erb_eval_top` 1,446,873 / + 1,453,260 / 1,255,820 (0.864), `erb_full` (`result_with_hash`) 1,532,485 / 1,532,762 / + 1,347,053 (0.879), `eval_reads_v` 1,636,785 / 1,652,003 / 1,025,414 (0.621), + `eval_reads` 4,145,087 / 3,839,458 / 1,406,918 (0.366); the controls `eval_small` 1.000 and + `eval_reads_static` 1.002. Timed (`ab.rb -r 3`): every row overlapped (spreads 39-95% on + the shared machine), so the clock said nothing either way. + - `Util/eval-locals-matrix.rb` (new: an eval defining a local the next eval reads, one that + does not assign, local_variable_set before and after reads, writes, a loop, a block in the + text, several evals on one binding, a new local between two reads, one text on alternating + and kept bindings, a name that is the method's in one binding and an eval's in another, a + block parameter shadowing the method's, a block's own local, a binding of a light frame, + Binding#dup, TOPLEVEL_BINDING.dup, instance_eval, a missing name, a local another thread + defined, four threads on one binding, ERB#result_with_hash and #result) prints CRuby 4.0's + output on the unchanged build, and on the change by default, with `IR_EVAL_LOCAL_CACHE=0`, + `IR_LIGHT_FRAMES=0`, `IR_LIGHT_ENTRY=0`, `-X:NoJIT -X:NoOSR` and `-X:NoJITCalls`. + erb-escape, lexical-light, global-light and block-scope-reuse print CRuby's output and + light-entry and hot-shapes the unchanged build's in all six modes. ruby/spec + `core/binding` 98 examples 0 failures, `core/kernel/eval_spec.rb` 57 / 0, `library/erb` + 53 / 0, the same on both builds. IronRuby.Tests `Eval_LocalVariableSites1` (new; passes + with the switch off too) and 31 named eval, binding and block tests pass. + `ReflectionCache.Generated.cs` from ClassInitGenerator, identical to the entries written + by hand. Not run: R2R. + - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, not gated. A keyword From e3a0b8f44593f7f192f4b4265b7303cba4ae146c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:57:50 +0000 Subject: [PATCH 141/439] Array#find, #detect, #any?, #all? and #none? are Array's own; they and #find_index park An Array's find and detect were Enumerable's: a call site to #each, a C# block (a Proc, a closure) and an Array per element, 885 bytes to find in [1], and no parked slot for the method calling them. CRuby 4.0 has them, with any?, all? and none?, as Array's own (rb_ary_find etc.): they walk the array, yield each element with a plain rb_yield and never call #each, so a subclass's #each is not what they search and a backtrace names Array#find, where IronRuby said Array#each and Enumerable#find. They are now IListOps methods over Enumerable.TrueForList and PatternForList, not inlined (ReadyToRun folded the any? forwarders and lost their frame), [BlockNotKept] with find_index and index, and the seven names are off NeverParkedIterators. IR_PARKED_FIND=0 puts them back on it. find1 298 ns / 885 B -> 113 / 69 (CRuby 66), any1 172 / 397 -> 107 / 69 (CRuby 55). Util/parked-iterator-matrix.rb (new) prints what CRuby prints in every mode; the baseline differed in the subclass-each, frame and owner rows. Util/bench/find-shapes.rb has the shapes. Integer#upto and #downto were tried the same way and left out: Permute's bytes halved but its instructions rose 3.8% and its time did not move. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Libraries/Builtins/Enumerable.cs | 92 ++++++----- Src/Libraries/Extensions/IListOps.cs | 112 +++++++++++++ .../Ast/Definitions/MethodDefinition.cs | 14 +- Util/bench/find-shapes.rb | 74 +++++++++ Util/parked-iterator-matrix.rb | 153 ++++++++++++++++++ 5 files changed, 405 insertions(+), 40 deletions(-) create mode 100644 Util/bench/find-shapes.rb create mode 100644 Util/parked-iterator-matrix.rb diff --git a/Src/Libraries/Builtins/Enumerable.cs b/Src/Libraries/Builtins/Enumerable.cs index 39d605543..80ce57bf9 100644 --- a/Src/Libraries/Builtins/Enumerable.cs +++ b/Src/Libraries/Builtins/Enumerable.cs @@ -239,12 +239,7 @@ private static object PatternForItems(CallSiteStorage/*!*/ each, Binar // An Array walks itself, as rb_ary_any_p and friends do, and does not call #each. var array = self as RubyArray; if (array != null) { - for (int i = 0; i < array.Count; i++) { - if (Protocols.IsTrue(site.Target(site, pattern, array[i])) == stop) { - return ScriptingRuntimeHelpers.BooleanToObject(positiveResult); - } - } - return ScriptingRuntimeHelpers.BooleanToObject(!positiveResult); + return PatternForList(site, array, pattern, stop, positiveResult); } object result = ScriptingRuntimeHelpers.BooleanToObject(!positiveResult); @@ -258,40 +253,63 @@ private static object PatternForItems(CallSiteStorage/*!*/ each, Binar return result; } + /// + /// The pattern form of Array#all?, #any? and #none? (rb_ary_all_p etc. with an argument): pattern === element for each + /// element, the list's length read again each time. + /// + internal static object PatternForList(CallSite>/*!*/ site, IList/*!*/ list, object pattern, + bool stop, bool positiveResult) { + for (int i = 0; i < list.Count; i++) { + if (Protocols.IsTrue(site.Target(site, pattern, list[i])) == stop) { + return ScriptingRuntimeHelpers.BooleanToObject(positiveResult); + } + } + return ScriptingRuntimeHelpers.BooleanToObject(!positiveResult); + } + + /// + /// Array#all?, #any? and #none? (rb_ary_all_p etc.), with a block or without: they walk the list and yield each element + /// once, rather than going through #each and a block of ours. + /// + internal static object TrueForList(BlockParam predicate, IList/*!*/ list, bool stop, bool positiveResult) { + var array = list as RubyArray; + // -X:OSR: once the block is hot, the rest of a plain Array's search runs in a typed copy of + // the loop this and the block make together (BlockLoopSite) + var loop = (predicate != null && array != null && array.Count >= BlockLoopSite.MinCollectRun && array.GetType() == typeof(RubyArray)) + ? BlockLoopSite.For(predicate, stop ? BlockLoopKind.FindTruthy : BlockLoopKind.FindFalsy) : null; + long countdown = (loop != null) ? loop.Countdown : Int64.MaxValue; + for (int i = 0; i < list.Count; i++) { + if (--countdown <= 0 && array.Count - i >= BlockLoopSite.MinCollectRun) { + bool found; + i = loop.Run(predicate, array, i, ref countdown, out found); + if (found) { return ScriptingRuntimeHelpers.BooleanToObject(positiveResult); } + if (i >= array.Count) { break; } + } + object item = list[i]; + if (predicate != null) { + // rb_ary_all_p and friends yield the element with a plain + // rb_yield: a lambda takes an Array element whole + object blockResult; + if (predicate.Yield(item, out blockResult)) { + return blockResult; + } + item = blockResult; + } + if (Protocols.IsTrue(item) == stop) { + if (loop != null) { loop.Leave(countdown); } + return ScriptingRuntimeHelpers.BooleanToObject(positiveResult); + } + } + if (loop != null) { loop.Leave(countdown); } + return ScriptingRuntimeHelpers.BooleanToObject(!positiveResult); + } + private static object TrueForItems(CallSiteStorage/*!*/ each, BlockParam predicate, object self, bool stop, bool positiveResult) { - // An Array's #all?, #any? and #none? are its own in MRI (rb_ary_all_p etc.): they walk the - // array and yield each element once rather than going through #each and a block of ours. + // An Array's #all?, #any? and #none? are its own (IListOps.TrueForAll etc.); Enumerable's, reached on an Array + // all the same (bind_call), walks it as they do, as it did when they were these. var array = self as RubyArray; if (array != null) { - // -X:OSR: once the block is hot, the rest of a plain Array's search runs in a typed copy of - // the loop this and the block make together (BlockLoopSite) - var loop = (predicate != null && array.Count >= BlockLoopSite.MinCollectRun && array.GetType() == typeof(RubyArray)) - ? BlockLoopSite.For(predicate, stop ? BlockLoopKind.FindTruthy : BlockLoopKind.FindFalsy) : null; - long countdown = (loop != null) ? loop.Countdown : Int64.MaxValue; - for (int i = 0; i < array.Count; i++) { - if (--countdown <= 0 && array.Count - i >= BlockLoopSite.MinCollectRun) { - bool found; - i = loop.Run(predicate, array, i, ref countdown, out found); - if (found) { return ScriptingRuntimeHelpers.BooleanToObject(positiveResult); } - if (i >= array.Count) { break; } - } - object item = array[i]; - if (predicate != null) { - // rb_ary_all_p and friends yield the element with a plain rb_yield: a - // lambda takes an Array element whole - object blockResult; - if (predicate.Yield(item, out blockResult)) { - return blockResult; - } - item = blockResult; - } - if (Protocols.IsTrue(item) == stop) { - if (loop != null) { loop.Leave(countdown); } - return ScriptingRuntimeHelpers.BooleanToObject(positiveResult); - } - } - if (loop != null) { loop.Leave(countdown); } - return ScriptingRuntimeHelpers.BooleanToObject(!positiveResult); + return TrueForList(predicate, array, stop, positiveResult); } object result = ScriptingRuntimeHelpers.BooleanToObject(!positiveResult); diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index ac3f42196..2e2e45845 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -1946,6 +1946,116 @@ public static IList FlattenInPlace(ConversionStorage/*!*/ tryToAry, IList #endregion + #region all?, any?, none? + + // Array's own in CRuby 4.0 (rb_ary_all_p, rb_ary_any_p, rb_ary_none_p), as Enumerable's answered for an Array before: + // they walk the array and never call #each (Enumerable.TrueForList). The block forms only yield to their block, so + // they are [BlockNotKept], as #find is. Not inlined: a backtrace taken in the block names the frame by this method + // ('Array#any?'), and ReadyToRun folds a forwarder this small into its caller. + + [RubyMethod("all?")] + [MethodImpl(MethodImplOptions.NoInlining)] + [BlockNotKept] + public static object TrueForAll(BlockParam predicate, IList/*!*/ self) { + return Enumerable.TrueForList(predicate, self, false, false); + } + + [RubyMethod("none?")] + [MethodImpl(MethodImplOptions.NoInlining)] + [BlockNotKept] + public static object TrueForNone(BlockParam predicate, IList/*!*/ self) { + return Enumerable.TrueForList(predicate, self, true, false); + } + + [RubyMethod("any?")] + [MethodImpl(MethodImplOptions.NoInlining)] + [BlockNotKept] + public static object TrueForAny(BlockParam predicate, IList/*!*/ self) { + return Enumerable.TrueForList(predicate, self, true, true); + } + + [RubyMethod("all?")] + [MethodImpl(MethodImplOptions.NoInlining)] + public static object TrueForAll(BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, IList/*!*/ self, object pattern) { + return PatternForList(caseEquals, predicate, self, pattern, false, false); + } + + [RubyMethod("none?")] + [MethodImpl(MethodImplOptions.NoInlining)] + public static object TrueForNone(BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, IList/*!*/ self, object pattern) { + return PatternForList(caseEquals, predicate, self, pattern, true, false); + } + + [RubyMethod("any?")] + [MethodImpl(MethodImplOptions.NoInlining)] + public static object TrueForAny(BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, IList/*!*/ self, object pattern) { + return PatternForList(caseEquals, predicate, self, pattern, true, true); + } + + private static object PatternForList(BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, IList/*!*/ self, object pattern, + bool stop, bool positiveResult) { + if (predicate != null) { + caseEquals.Context.ReportWarning("given block not used"); + } + // MRI calls #=== with rb_funcall, which a private #=== answers too, as this site's does. + return Enumerable.PatternForList(caseEquals.GetCallSite("==="), self, pattern, stop, positiveResult); + } + + #endregion + + #region find, detect + + // Array#find and #detect are Array's own in CRuby 4.0 (rb_ary_find): they walk the array, re-reading its length, yield + // each element with a plain rb_yield - a lambda of two parameters is not handed an element taken apart - and do not + // call #each, so a subclass's #each is not what they search. Enumerable#find, which an Array answered before, calls + // #each with a block of its own: a Proc, a closure and an Array per element (885 bytes to find in [1]). They only + // yield to their block, so they are [BlockNotKept]: a literal given to them reuses its Proc, and the method it is in + // may park its scope (MethodDefinition.IsNeverParkedIterator). + + [RubyMethod("find")] + [RubyMethod("detect")] + public static Enumerator/*!*/ GetFindEnumerator([CalledName]string/*!*/ name, BlockParam predicate, IList/*!*/ self, [Optional]object ifNone) { + Debug.Assert(predicate == null); + // the Enumerator calls the method again, as MRI's does: it shows as # + return (ifNone != Missing.Value) ? new Enumerator(self, name, ifNone) : new Enumerator(self, name); + } + + // a method of its own to have a frame of its own (see Map) + [RubyMethod("detect")] + [MethodImpl(MethodImplOptions.NoInlining)] + [SameRubyMethod("Find")] + [BlockNotKept] + public static object Detect(CallSiteStorage>/*!*/ callStorage, [NotNull]BlockParam/*!*/ predicate, + IList/*!*/ self, [Optional]object ifNone) { + return Find(callStorage, predicate, self, ifNone); + } + + [RubyMethod("find")] + [MethodImpl(MethodImplOptions.NoInlining)] + [BlockNotKept] + public static object Find(CallSiteStorage>/*!*/ callStorage, [NotNull]BlockParam/*!*/ predicate, + IList/*!*/ self, [Optional]object ifNone) { + for (int i = 0; i < self.Count; i++) { + object item = self[i]; + object blockResult; + if (predicate.Yield(item, out blockResult)) { + return blockResult; + } + if (Protocols.IsTrue(blockResult)) { + return item; + } + } + + // rb_ary_find calls the if-none object's #call, whatever it is, unless it is nil + if (ifNone == Missing.Value || ifNone == null) { + return null; + } + var site = callStorage.GetCallSite("call", 0); + return site.Target(site, ifNone); + } + + #endregion + #region include?, find_index/index, rindex [RubyMethod("include?")] @@ -1971,11 +2081,13 @@ public static bool Include(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object [RubyMethod("index")] [MethodImpl(MethodImplOptions.NoInlining)] [SameRubyMethod("FindIndex")] + [BlockNotKept] public static object Index([NotNull]BlockParam/*!*/ predicate, IList/*!*/ self) { return FindIndex(predicate, self); } [RubyMethod("find_index")] + [BlockNotKept] public static object FindIndex([NotNull]BlockParam/*!*/ predicate, IList/*!*/ self) { for (int i = 0; i < self.Count; i++) { object blockResult; diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 1cbc41380..a85d54ca2 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -482,15 +482,23 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin // cost: a method that calls one with a literal gets no parking slot, and a method of the same name of a program's own // class is merely not parked. private static readonly System.Collections.Generic.HashSet NeverParkedIterators = new System.Collections.Generic.HashSet { - "new", "upto", "downto", "step", "any?", "all?", "none?", "one?", "count", "delete_if", "keep_if", "each_cons", "each_slice", - "each_with_index", "each_with_object", "fill", "filter_map", "find", "detect", "find_index", "group_by", "index", "inject", + "new", "upto", "downto", "step", "one?", "count", "delete_if", "keep_if", "each_cons", "each_slice", + "each_with_index", "each_with_object", "fill", "filter_map", "group_by", "inject", "reduce", "max_by", "min_by", "partition", "reject", "reverse_each", "sort", "sort_by", "take_while", "drop_while", "uniq", "zip", "each_key", "each_value", "each_char", "each_byte", "each_line", "define_method", "lambda", "proc", "instance_eval", "instance_exec", "class_eval", "module_eval", "class_exec", "module_exec", "fetch", "tally_by", }; + // Array#find, #detect, #find_index, #index, #any?, #all? and #none? only yield ([BlockNotKept]); IR_PARKED_FIND=0 counts + // them never parked again, as they were while an Array's find and any? were Enumerable's. (Integer#upto and #downto + // only yield too, but parking a method around them costs more instructions than the bytes it saves: Util/perf/LEDGER.md, + // gap 13, perf/iter2.) + private static readonly bool ParkedFindEnabled = Environment.GetEnvironmentVariable("IR_PARKED_FIND") != "0"; + internal static bool IsNeverParkedIterator(string/*!*/ name) { - return NeverParkedIterators.Contains(name); + return NeverParkedIterators.Contains(name) || + !ParkedFindEnabled && (name == "find" || name == "detect" || name == "find_index" || name == "index" || + name == "any?" || name == "all?" || name == "none?"); } /// diff --git a/Util/bench/find-shapes.rb b/Util/bench/find-shapes.rb new file mode 100644 index 000000000..35e33bcd7 --- /dev/null +++ b/Util/bench/find-shapes.rb @@ -0,0 +1,74 @@ +# Array#find, #detect, #find_index, #any? and #all? given a literal block by a method (round thirty-seven, perf/iter2): they +# are Array's own (find walked #each through Enumerable's C# before) and [BlockNotKept], so the method parks its scope with +# the block's Proc (IR_PARKED_FIND). ns per call of the method; the switch is the third arm: +# +# ruby Util/perf/ab.rb -i Util/bench/find-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "off=env IR_PARKED_FIND=0 IR_CONFIG=Release ./ir.sh" "on=env IR_CONFIG=Release ./ir.sh" +# +# each1, times1 and map1 are controls (already parked before); upto and downto are not parked (tried, see the ledger's +# perf/iter2: more instructions, the same time). +$stdout.sync = true + +class O + def find(a) = a.find { |x| x > 2 } + def detect(a) = a.detect { |x| x > 2 } + def find_index(a) = a.find_index { |x| x > 2 } + def any(a) = a.any? { |x| x > 1000 } ? 1 : 0 + def all(a) = a.all? { |x| x > 0 } ? 1 : 0 + def upto(k); s = 0; 1.upto(k) { |j| s += j }; s; end + def downto(k); s = 0; k.downto(1) { |j| s += j }; s; end + def each(a); s = 0; a.each { |x| s += x }; s; end + def times(k); s = 0; k.times { |j| s += j + 1 }; s; end + def map(a) = a.map { |x| x + 1 }.size +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the seven sections as the +# time is. See Util/perf/instructions.rb. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-12s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +o = O.new +N = (ENV['N'] || 500_000).to_i +a1 = [3] +a4 = [1, 2, 0, 3] + +t("find1", N) { |n| i = 0; s = 0; while i < n; s += o.find(a1); i += 1; end; s } +t("find4", N) { |n| i = 0; s = 0; while i < n; s += o.find(a4); i += 1; end; s } +t("detect1", N) { |n| i = 0; s = 0; while i < n; s += o.detect(a1); i += 1; end; s } +t("findidx4", N) { |n| i = 0; s = 0; while i < n; s += o.find_index(a4); i += 1; end; s } +t("any1", N) { |n| i = 0; s = 0; while i < n; s += o.any(a1); i += 1; end; s } +t("any4", N) { |n| i = 0; s = 0; while i < n; s += o.any(a4); i += 1; end; s } +t("all4", N) { |n| i = 0; s = 0; while i < n; s += o.all(a4); i += 1; end; s } +t("upto1", N) { |n| i = 0; s = 0; while i < n; s += o.upto(1); i += 1; end; s } +t("upto4", N) { |n| i = 0; s = 0; while i < n; s += o.upto(4); i += 1; end; s } +t("downto4", N) { |n| i = 0; s = 0; while i < n; s += o.downto(4); i += 1; end; s } +t("each1", N) { |n| i = 0; s = 0; while i < n; s += o.each(a1); i += 1; end; s } +t("times1", N) { |n| i = 0; s = 0; while i < n; s += o.times(1); i += 1; end; s } +t("map1", N) { |n| i = 0; s = 0; while i < n; s += o.map(a1); i += 1; end; s } diff --git a/Util/parked-iterator-matrix.rb b/Util/parked-iterator-matrix.rb new file mode 100644 index 000000000..20826f0db --- /dev/null +++ b/Util/parked-iterator-matrix.rb @@ -0,0 +1,153 @@ +# Differential checks for Array#find, #detect, #find_index, #index, #any?, #all?, #none? and Integer#upto and #downto +# (round thirty-seven, perf/iter2): the Array methods are Array's own, as in CRuby 4.0, and with Integer#upto and #downto +# they are [BlockNotKept], so a method that gives them a literal block may park its scope with the block's Proc +# (MethodDefinition.IsNeverParkedIterator, RubyOps.TakeParkedScope). Each method below is called several times, so the +# later calls take the parked scope and Proc; every way the Proc or the scope can escape is a row. The output must match +# CRuby's and the unchanged build's, with IR_PARKED_FIND=0 and IR_PARKED_SCOPES=0 too: +# +# ruby Util/parked-iterator-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/parked-iterator-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +$stdout.sync = true +module Warning + def self.warn(msg, **) = $stdout.print("W: #{msg.sub(/\A.*?warning: /, '')}") +end + +def rows(name) = puts("#{name}: #{yield.inspect}") + +# what the methods answer, called again and again +class F + def find_gt(a, k) = a.find { |x| x > k } + def detect_gt(a, k) = a.detect { |x| x > k } + def find_none(a, k) = a.find(-> { :none }) { |x| x > k } + def find_nil(a, k) = a.find(nil) { |x| x > k } + def find_index_gt(a, k) = a.find_index { |x| x > k } + def index_gt(a, k) = a.index { |x| x > k } + def any_gt(a, k) = a.any? { |x| x > k } + def all_gt(a, k) = a.all? { |x| x > k } + def none_gt(a, k) = a.none? { |x| x > k } + def upto_sum(a, b); s = 0; a.upto(b) { |i| s += i }; s; end + def downto_sum(a, b); s = 0; a.downto(b) { |i| s += i }; s; end + def local_seen(a, k); seen = []; r = a.find { |x| seen << x; x > k }; [r, seen]; end +end +f = F.new +a = [3, 1, 4, 1, 5, 9, 2, 6] +rows("find") { [0, 3, 8, 9, 2].map { |k| f.find_gt(a, k) } } +rows("detect") { [0, 3, 8, 9, 2].map { |k| f.detect_gt(a, k) } } +rows("find ifnone") { [0, 9, 3, 9].map { |k| f.find_none(a, k) } } +rows("find nil") { [0, 9].map { |k| f.find_nil(a, k) } } +rows("find_index") { [0, 3, 9, 5].map { |k| f.find_index_gt(a, k) } } +rows("index") { [0, 3, 9, 5].map { |k| f.index_gt(a, k) } } +rows("any?") { [0, 9, 8, 100].map { |k| f.any_gt(a, k) } } +rows("all?") { [0, 1, -1, 9].map { |k| f.all_gt(a, k) } } +rows("none?") { [0, 9, 8, 100].map { |k| f.none_gt(a, k) } } +rows("upto") { [[1, 4], [5, 4], [-2, 2], [1, 1]].map { |x, y| f.upto_sum(x, y) } } +rows("downto") { [[4, 1], [4, 5], [2, -2], [1, 1]].map { |x, y| f.downto_sum(x, y) } } +rows("locals fresh") { [2, 5, 0].map { |k| f.local_seen(a, k) } } +rows("empty") { [f.find_gt([], 0), f.any_gt([], 0), f.all_gt([], 0), f.none_gt([], 0), f.find_index_gt([], 0)] } +rows("bignum upto") { [f.upto_sum(2**64, 2**64 + 2), f.downto_sum(2**64 + 1, 2**64)] } +rows("float upto") { (f.upto_sum(1, 2.5) rescue $!.class) } + +# no block, a pattern, a Symbol, a Proc, a lambda +rows("no block") { [[1].find.class, [1].find(-> { 0 }).each { false }, [nil, 1].any?, [1, nil].all?, [nil].none?, 1.upto(3).to_a] } +rows("pattern") { [a.any?(Integer), a.all?(1..9), a.none?(String), %w[ab cd].any?(/c/), [].all?(1)] } +rows("pattern+block") { [a.any?(9) { |x| x > 100 }, a.all?(Integer) { false }] } +rows("symbol") { [a.find(&:even?), a.any?(&:zero?), a.find_index(&:even?), [[1, 2]].find(&:last)] } +rows("lambda arity") { [([[1, 2]].find(&->(x, y) { y == 2 }) rescue $!.class), [[1, 2]].find(&->(x) { x == [1, 2] }), + ([[1, 2]].any?(&->(x, y) { true }) rescue $!.class), [[1, 2]].find { |x, y| y == 2 }] } +pr = proc { |x| x > 4 } +rows("stored proc") { 3.times.map { [a.find(&pr), a.any?(&pr), a.find_index(&pr)] } } + +# break, next, return, redo-free retry by hand, and an exception from the block +class F + def find_break(a) = a.find { |x| break [:broke, x] if x == 4; false } + def any_next(a) = a.any? { |x| next false if x < 5; true } + def find_return(a); a.find { |x| return [:ret, x] if x == 5; false }; :none; end + def upto_break(n) = 1.upto(n) { |i| break i * 10 if i == 3 } + def downto_return(n); n.downto(1) { |i| return i if i == 2 }; :none; end + def find_raise(a, k) + a.find { |x| raise ArgumentError, "at #{x}" if x == k; false } + rescue ArgumentError => e + e.message + end +end +rows("break") { 3.times.map { f.find_break(a) } } +rows("next") { 3.times.map { f.any_next(a) } } +rows("return") { 3.times.map { [f.find_return(a), f.find_return([1])] } } +rows("upto break") { 3.times.map { [f.upto_break(5), f.upto_break(2)] } } +rows("downto return") { 3.times.map { [f.downto_return(4), f.downto_return(1)] } } +rows("raise") { [f.find_raise(a, 4), f.find_raise(a, 100), f.find_raise(a, 9), f.find_raise(a, 3)] } + +# the block's Proc or scope escapes: binding, a proc, a lambda, a method made in it, eval +class F + def find_binding(a, k); bs = []; a.find { |x| bs << binding; x > k }; bs.map { |b| b.local_variable_get(:x) }; end + def any_proc(a, k); ps = []; y = k; a.any? { |x| ps << proc { [x, y] }; x > k }; ps.map(&:call); end + def upto_lambda(n); ls = []; 1.upto(n) { |i| ls << -> { i * n } }; ls.map(&:call); end + def find_eval(a, k) = a.find { |x| eval("x > k") } + def find_method(a, k); o = Object.new; a.find { |x| o.define_singleton_method(:v) { x }; x > k }; o.v; end + def find_outer_binding(a, k); r = a.find { |x| x > k }; b = binding; [r, b.local_variable_get(:k)]; end +end +rows("binding") { [f.find_binding(a, 3), f.find_binding(a, 0), f.find_binding(a, 4)] } +rows("proc") { [f.any_proc([1, 2, 3], 2), f.any_proc([5, 6], 0), f.any_proc([7], 9)] } +rows("lambda") { [f.upto_lambda(3), f.upto_lambda(1), f.upto_lambda(2)] } +rows("eval") { [f.find_eval(a, 3), f.find_eval(a, 5), f.find_eval(a, 0)] } +rows("method made") { [f.find_method(a, 3), f.find_method(a, 8), f.find_method(a, 4)] } +rows("outer binding") { [f.find_outer_binding(a, 3), f.find_outer_binding(a, 5)] } + +# the receiver is not a plain Array: Enumerable's find, a subclass, a redefined Array#each, Hash, Range, Struct +class EachSub < Array; def each; yield 99; end; end +class FindSub < Array; def find; :own; end; end +class F + def hash_find(h, v) = h.find { |k, x| x == v } + def range_any(r, k) = r.any? { |x| x > k } + def struct_find(s, k) = s.find { |x| x > k } + def enum_find(e, k) = e.find { |x| x > k } +end +S3 = Struct.new(:a, :b, :c) +class Kept + include Enumerable + def each(&b); @b = b; [1, 2, 3].each(&b); self; end + def again(x) = @b.call(x) +end +rows("subclass each") { [EachSub[1, 2].find { |x| x > 0 }, EachSub[1, 2].any? { |x| x == 99 }, EachSub[1].find_index { true }] } +rows("subclass find") { [FindSub[1].find] } +rows("hash") { [{ a: 1, b: 2 }, { c: 3 }, { a: 1, b: 2 }].map { |h| f.hash_find(h, 2) } } +rows("range") { [[1..5, 3], [1..2, 3], [1..5, 3]].map { |r, k| f.range_any(r, k) } } +rows("struct") { [S3.new(1, 2, 3), S3.new(5, 6, 7), S3.new(1, 2, 3)].map { |s| f.struct_find(s, 1) } } +kept = Kept.new +rows("kept by each") { r = 3.times.map { |i| f.enum_find(kept, i) }; [r, (kept.again(5) rescue $!.class), (kept.again(0) rescue $!.class), f.enum_find(kept, 1)] } +class Array + alias each_orig each + def each(&b) = each_orig(&b) +end +rows("Array#each redefined") { [f.find_gt(a, 4), f.any_gt(a, 8), f.find_index_gt(a, 4)] } +class Array + alias each each_orig +end + +# the array changes while it is searched +rows("mutation") { b = [1, 2, 3]; r = b.find { |x| b << x + 10 if b.size < 6; x > 11 }; [r, b] } +rows("shrink") { b = [1, 2, 3, 4]; r = b.any? { |x| b.pop; x > 3 }; [r, b] } + +# recursion through the iterator, re-entrancy, a fiber and threads +class F + def deep(n) = [n].find { |x| x == 0 || deep(x - 1) } && n + def nest(a, k) = a.find { |x| a.any? { |y| y > x + k } } + def count_up(n); s = []; 1.upto(n) { |i| s << (i < n ? count_up(i) : i) }; s; end + def fiber_find(a, k) = a.find { |x| Fiber.yield x; x > k } +end +rows("recursion") { [f.deep(5), f.deep(0), f.deep(3)] } +rows("re-entrant") { [f.nest(a, 4), f.nest(a, 8), f.nest(a, 0)] } +rows("upto recursion") { [f.count_up(3), f.count_up(1)] } +fb = [Fiber.new { f.fiber_find([1, 2, 3], 1) }, Fiber.new { f.fiber_find([4, 5], 4) }] +rows("fiber") { r = []; 3.times { fb.each { |x| r << x.resume if x.alive? } }; r } +ok = 4.times.map { |t| Thread.new { (1..3000).all? { |k| f.find_gt([k, t, k + t], k) == k + t && f.upto_sum(t, t + 2) == 3 * t + 3 && f.any_gt([t], t - 1) } } }.map(&:value) +rows("threads") { ok } + +# a TracePoint enabled between calls, and the backtrace from the block +rows("trace") { r = []; tp = TracePoint.new(:b_call) { |t| r << t.binding.local_variable_defined?(:x) if t.path == __FILE__ } + 4.times { |i| tp.enable if i == 2; f.find_gt([1, 2], 1) }; tp.disable; r } +def bt(m) = [1].public_send(m) { break caller(0, 2).map { |l| l[/'.*'/] } } +rows("frames") { [bt(:find), bt(:detect), bt(:any?), bt(:all?), bt(:none?), bt(:find_index), bt(:index)] } +rows("owners") { %i[find detect any? all? none? find_index index].map { |m| Array.instance_method(m).owner } } +rows("same method") { [Array.instance_method(:find) == Array.instance_method(:detect), [].method(:find).arity, [].method(:any?).arity] } From 900204671ff1aecb31db07029d5166eae5c37790 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:57:50 +0000 Subject: [PATCH 142/439] Ledger: perf/iter2, Array's own find and any? park (gap 13) Landed, not gated, with the instruction counts, bytes, time, matrices and what the gate should look at; gap 13 says what is left. The upto/downto attempt is recorded with its numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Util/perf/LEDGER.md | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 539ce07db..e4e9d071f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -972,6 +972,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has allocates), 0.51-0.70 of the time. Left: `any?`, `find` and `each_with_index` (Enumerable's C# goes through `each` and a SplattingBlock: the bytes are its own, not the parking's) and the literal given to a core iterator outside the parked list. + perf/iter2 (see Landed, not gated) took `find` and `any?`: Array's own, as in CRuby 4.0, and + parked - `find1` 298 ns / 885 B -> 113 / 69 (CRuby 66), `any1` 172 / 397 -> 107 / 69 (CRuby + 55). `upto` and `downto` were tried the same way and left out: a parked slot around them + takes Permute from 124.5 to 53.9 MB per iteration and costs 3.8% more instructions, its time + level (1.00 over six rounds), as perf/deadconst found. Left: `each_with_index` (the prelude's, + `*args, &block`), `inject`, and `upto`/`downto`'s entry, which is not their bytes. 14. **DeltaBlue: `Vector#each`** (`(@first_idx..(@last_idx - 1)).each { |i| yield @storage[i] }`) is about 20% of its samples by nearest Ruby frame (8.9% the method, 11.3% its block), and no call site owns more than 1.2% of the 24% in @@ -2213,6 +2219,55 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Method_LightFrame*`: PASSED. The census cannot see this (no method changes verdict). Not run: `IR_CONFIG=R2R` start-up, the suite, a sweep, AWFY (owed to the gate). +- **perf/iter2 (round thirty-seven, 2026-11-27) - Array#find, #detect, #any?, #all? and #none? are + Array's own and, with #find_index and #index, let the method that gives them a literal park + (gap 13)** - instructions, bytes and time, not gated. An Array's `find` and `detect` were + Enumerable's: a call site to `each`, a C# SplattingBlock (a Proc, a closure) and an Array per + element - 885 bytes to find in `[1]` - and, being in `NeverParkedIterators`, no parked slot for + the method that called them. CRuby 4.0 has them as Array's own (`rb_ary_find`), with `any?`, + `all?` and `none?`: they walk the array, re-reading its length, yield each element with a plain + `rb_yield` (a lambda of two parameters raises), and never call `#each` - so a subclass's `each` + is not what they search, and a backtrace names `Array#find`, where IronRuby said `Array#each` + and `Enumerable#find`. Now they are IListOps methods (`Find`, `Detect`, `TrueForAll`/`None`/`Any` + with their pattern forms, over `Enumerable.TrueForList` and `PatternForList`, which Enumerable's + own use for an Array as before), `[BlockNotKept]` with `find_index` and `index`, and the seven + names are off `MethodDefinition.NeverParkedIterators`. `IR_PARKED_FIND=0` puts them back on it + (the methods stay Array's). Not inlined: ReadyToRun folded the `any?` forwarders into their caller + and a backtrace lost the `Array#any?` frame (caught by the R2R mode of the matrices). + Per call (`Util/bench/find-shapes.rb`; ns, bytes, CRuby): `find1` 298 / 885 -> 113 / 69 (66), + `any1` 172 / 397 -> 107 / 69 (55); with the switch off 163 / 357 and 138 / 357. Instructions + (callgrind, new over base / over off): `find1` 0.601 / 0.988, `find4` 0.586 / 1.009, `detect1` + 0.608 / 0.988, `findidx4` 1.005 / 0.993, `any1` 1.015 / 1.014, `any4` 1.030 / 1.023, `all4` 0.996 + / 0.992; controls `each1`, `times1`, `map1` 1.000. Time, four and eight alternating rounds, new + over off: `find1` 0.82 and 0.84, `detect1` 0.76, `findidx4` 0.73, `any1` 0.82 and 0.84, `any4` + 0.75, `all4` 0.81; controls overlapping (spreads of 20-40% on a shared host). The parked slot is + bytes the counter does not see: each cell is the least of seven sections, and at N=20000 that one + runs no collection. + Tried and taken out: `[BlockNotKept]` on Integer#upto and #downto, off the list. `upto1` 389 -> + 101 B and 0.85-0.86 of the time, Permute 124,533,643 -> 53,876,246 B per iteration (alloc.rb + geomean 0.937 with it); but `upto1` +3.0% instructions, `upto4` +1.8%, Permute +3.8% over off + (+4.4% over base), and Permute's time level (1.00 over six alternating rounds; the least of forty + iterations 104 against 107-112 ms). It is perf/deadconst's result again; without it Permute and + Queens allocate what the baseline does (alloc.rb: 124,548,094 / 124,525,657, 30,446,800 / + 30,441,889). + Matrices (`Util/perf/gate-matrices.rb`, base b887bc1 with perf/iter): `Util/parked-iterator-matrix.rb` + (new: the nine methods called again and again, ifnone, empty, Bignum, no block, patterns with a + block, Symbol, lambda arity, stored Proc, break/next/return/raise, binding, proc, lambda, eval and + a method made in the block, the outer binding, a subclass's each, a subclass's find, Hash, Range, + Struct, an Enumerable whose each keeps the block, Array#each redefined, the array grown and + shrunk while searched, recursion, re-entrancy, a Fiber, four threads, a TracePoint, the frames, + the owners), enum, enumerable2, block-nest-reuse, block-scope-reuse, -blockpass, -race, + block-loop, block-given, light-rest, hot-shapes, jit, parked-scope and block-pass, in the seven + modes with IR_PARKED_FIND=0: PASS; the new matrix is CRuby's in every mode, the baseline differs + from it in three rows the change fixes (subclass each, frames, owners). ruby/spec core/array, + core/enumerable, integer/upto and downto: the baseline's one failure and three errors (Array#fill, + Array.new, Array.try_convert). WeakRef probe (find, any?, find_index, upto, downto in parked + methods, `IR_PARKED_SCOPES=verbose` confirming the slots): all freed. Census: 0 methods changed. + For the gate: Array now answers `find`, `detect`, `any?`, `all?`, `none?` itself (owners, + `instance_method`, `super` from a subclass, `Enumerable.instance_method(:find).bind_call(ary)`); + a method parked around `h.find { }` on a Hash, which is still Enumerable's and keeps no Proc, + until its slot gives up (`ParkedScopeSlot.MaxFailures`). + - **perf/iter (round thirty-seven, 2026-11-26) - a block that holds a block literal reuses its scope and the literal's Proc (gaps 13 and 6)** - instructions and bytes, not gated. A block whose body has a block literal (`a.each { |x| o.e { |c| s += c } }`, Richards' worker block with From cb8fbd6f02ab176dac3daad7262108a30985ba7c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:00:35 +0000 Subject: [PATCH 143/439] Kernel#send and #__send__ with a String name leave no backtrace frame `[1].send("sum") { raise }` showed "Array#sum < Kernel#send" (LEDGER gap 27), and `1.send("foo")` or `1.__send__` started the backtrace with "Kernel#send" / "BasicObject#__send__". CRuby's send and __send__ are invisible in a backtrace whatever the name; with a Symbol IronRuby already made the call in place (DispatchIntrinsics), but a String went through the library methods, whose frames showed. They are [RubyStackTraceHidden] now; Kernel#public_send keeps its frame, as CRuby's does. Checked: Backtrace_SendHidden1 (new; CRuby 4.0's output) and the other Backtrace_ tests; spec/core/kernel send, public_send, caller, caller_locations, BasicObject#__send__, Exception#backtrace, spec/language/send: as before; caller, raise, full-message and set-backtrace matrices unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 32 +++++++++++++++++++ Src/Libraries/Builtins/BasicObjectOps.cs | 11 +++++++ Src/Libraries/Builtins/KernelOps.cs | 11 +++++++ 4 files changed, 55 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 86b4d6d2d..cd4a81638 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1041,6 +1041,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_RaiseInRescue1, Backtrace_RedefinedSetBacktrace1, Backtrace_ArityCalleeFrame1, + Backtrace_SendHidden1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index 8230e6891..baf09f466 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -339,6 +339,38 @@ load file [[11, ""block (2 levels) in ""], [11, ""Object#internal_foo1""], [11, ""block in ""]] [[12, ""block (2 levels) in ""], [12, ""Object#internal_bar1""], [12, ""block in ""]] [[13, ""Object#arity_kw1""], [14, ""block in ""]] +"); + } + + /// + /// Kernel#send and BasicObject#__send__ leave no frame of their own in a backtrace, with a String name too (as with a + /// Symbol, whose call the binder makes in place); Kernel#public_send keeps its frame. LEDGER gap 27. + /// + public void Backtrace_SendHidden1() { + TestOutput(@" +require 'ruby4' +def bt = yield rescue $!.backtrace.first(3).map { _1.sub(/^.*?:\d+:in /, """") } +p bt { [1].send(""sum"") { raise } } +p bt { [1].send(:sum) { raise } } +p bt { [1].public_send(""sum"") { raise } } +p bt { [1].__send__(""sum"") { raise } } +p bt { 1.send(""foo"") } +p bt { [1].send(""each"") { raise } } +p bt { 1.send }, bt { 1.__send__ }, bt { 1.public_send }, bt { 1.send(:x) }, bt { 1.send(1) }, bt { 1.__send__(""foo"", 1) }, bt { [1].public_send(""sum"") { raise } } +", @" +[""'block (2 levels) in
'"", ""'Array#sum'"", ""'block in
'""] +[""'block (2 levels) in
'"", ""'Array#sum'"", ""'block in
'""] +[""'block (2 levels) in
'"", ""'Array#sum'"", ""'Kernel#public_send'""] +[""'block (2 levels) in
'"", ""'Array#sum'"", ""'block in
'""] +[""'block in
'"", ""'Object#bt'"", ""'
'""] +[""'block (2 levels) in
'"", ""'Array#each'"", ""'block in
'""] +[""'block in
'"", ""'Object#bt'"", ""'
'""] +[""'block in
'"", ""'Object#bt'"", ""'
'""] +[""'Kernel#public_send'"", ""'block in
'"", ""'Object#bt'""] +[""'block in
'"", ""'Object#bt'"", ""'
'""] +[""'block in
'"", ""'Object#bt'"", ""'
'""] +[""'block in
'"", ""'Object#bt'"", ""'
'""] +[""'block (2 levels) in
'"", ""'Array#sum'"", ""'Kernel#public_send'""] "); } } diff --git a/Src/Libraries/Builtins/BasicObjectOps.cs b/Src/Libraries/Builtins/BasicObjectOps.cs index 9562e92dc..e6be0c334 100644 --- a/Src/Libraries/Builtins/BasicObjectOps.cs +++ b/Src/Libraries/Builtins/BasicObjectOps.cs @@ -100,12 +100,14 @@ public static object MethodMissing(RubyContext/*!*/ context, object/*!*/ self, o #region __send__ [RubyMethod("__send__")] + [RubyStackTraceHidden] public static object SendMessage(RubyScope/*!*/ scope, object self) { return KernelOps.SendMessage(scope, self); } // ARGS: 0 [RubyMethod("__send__")] + [RubyStackTraceHidden] [ReceivesKeywords] public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName) { @@ -114,6 +116,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName) { @@ -122,6 +125,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -131,6 +135,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -140,6 +145,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -149,6 +155,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -158,6 +165,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -167,6 +175,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -176,6 +185,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -185,6 +195,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index a55d330e8..2182b6a1d 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -2474,6 +2474,7 @@ public static bool RespondToMissing(object self, object methodName, object inclu #region send, public_send [RubyMethod("send")] + [RubyStackTraceHidden] public static object SendMessage(RubyScope/*!*/ scope, object self) { throw RubyExceptions.CreateArgumentError("no method name given"); } @@ -2521,6 +2522,7 @@ public static object PublicSendMessage(ConversionStorage/*!*/ stringCast // ARGS: 0 [RubyMethod("send")] + [RubyStackTraceHidden] [ReceivesKeywords] public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName) { @@ -2532,6 +2534,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName) { @@ -2543,6 +2546,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2557,6 +2561,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2570,6 +2575,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2584,6 +2590,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2597,6 +2604,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2611,6 +2619,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2624,6 +2633,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2638,6 +2648,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, From 636985603dfa2270de12fbae72934f3d158db288 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:01:51 +0000 Subject: [PATCH 144/439] Format_Char2: %c of 0x100 in ISO-8859-1 is CRuby 4.0's "invalid character" perf/crubydiff (8747187) made %c of a code above 0xFF in a single byte encoding raise ArgumentError "invalid character", as CRuby 4.0 does (ruby -e 'format("<%c>".encode("ISO-8859-1"), 0x100)'), and updated Sprintf_CharacterBytes1, but Format_Char2 still expected the old RangeError for ISO-8859-1. US-ASCII and BINARY keep "256 out of char range", as in CRuby. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Src/IronRuby.Tests/Runtime/StringTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index 78c3cfb50..de8fec1a6 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -1340,7 +1340,7 @@ def t(l) BINARY ff: ASCII-8BIT 3cff3e BINARY 100: [RangeError, ""256 out of char range""] ISO-8859-1 e9: ISO-8859-1 3ce93e -ISO-8859-1 100: [RangeError, ""256 out of char range""] +ISO-8859-1 100: [ArgumentError, ""invalid character""] Shift_JIS 80: Shift_JIS 3c803e Shift_JIS 81: [ArgumentError, ""invalid character""] Shift_JIS a1: Shift_JIS 3ca13e From b493c0b670c70a2248074b5e118df9e92d3c4af1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:01:51 +0000 Subject: [PATCH 145/439] CompiledConstantsRewriter: leave a tree too deep for the stack as it is DeepNesting1 (begin/rescue nested 500 deep, compiled up front) killed the test process with a stack overflow in the rewriter perf/lconst added: an ExpressionVisitor recurses once a level and, unlike LambdaCompiler, has no StackGuard to go on on a new thread. Each Visit now checks RuntimeHelpers.TryEnsureSufficientExecutionStack, and a tree it cannot finish is handed to the compiler unrewritten, which costs that one lambda its uncast constants and nothing else. DeepNesting1, and the three tests that ran after it in the same process, pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Src/Ruby/Runtime/CompiledConstants.cs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/CompiledConstants.cs b/Src/Ruby/Runtime/CompiledConstants.cs index b00377d6c..a356f0c7a 100644 --- a/Src/Ruby/Runtime/CompiledConstants.cs +++ b/Src/Ruby/Runtime/CompiledConstants.cs @@ -42,7 +42,26 @@ internal static void Install() { } internal static LambdaExpression/*!*/ Rewrite(LambdaExpression/*!*/ lambda) { - return Enabled ? (LambdaExpression)new CompiledConstantsRewriter().Visit(lambda) : lambda; + if (!Enabled) { + return lambda; + } + try { + return (LambdaExpression)new CompiledConstantsRewriter().Visit(lambda); + } catch (TooDeepException) { + // compiled as it is: LambdaCompiler goes on deep trees on a new thread of its own (StackGuard) + return lambda; + } + } + + // A visitor recurses once a level of the tree, and has no StackGuard as LambdaCompiler does: a body nested some 500 + // levels deep (DeepNesting1, begin/rescue compiled up front) overflowed the stack of the thread that compiled it. + private sealed class TooDeepException : Exception { } + + public override Expression Visit(Expression node) { + if (!RuntimeHelpers.TryEnsureSufficientExecutionStack()) { + throw new TooDeepException(); + } + return base.Visit(node); } protected override Expression/*!*/ VisitExtension(Expression/*!*/ node) { From 4320d4a4e593924f1f93020c250735cdaa906a18 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:01:51 +0000 Subject: [PATCH 146/439] ForwardedRest off by default: the caller's frame can read its rest again Round 5's gate read a method's rest parameter after it had been passed on as the callee's own rest Array (perf/forward) by ways ForwardedRest's walk cannot see: instance_eval and class_eval of a String, send(:eval, ...), an alias of eval (any call may ask for a light frame's scope at run time) and a TracePoint's binding at :return. Each saw the callee's change to the Array, [1, 2, :x], where CRuby's caller keeps [1, 2]. It is sound only where nothing runs in the frame after the call and no TracePoint is on, which it does not check yet, so it now runs only with IR_FORWARD_REST=1. The hoisted splat of a block-passing call, a copy, is unchanged. Util/forward-rest-matrix.rb (new, from the gate's probes) prints CRuby's output but for the two rows master shares (Kernel#binding by bind_call or a Method, which CRuby refuses for a non-Ruby caller). The ledger records it under perf/forward and in the faults caught by the gate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- .../Compiler/Ast/Definitions/ForwardedRest.cs | 8 +++- Util/forward-rest-matrix.rb | 43 +++++++++++++++++++ Util/perf/LEDGER.md | 24 ++++++++++- 3 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 Util/forward-rest-matrix.rb diff --git a/Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs b/Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs index 835f21d06..bc098bc17 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/ForwardedRest.cs @@ -24,8 +24,12 @@ namespace IronRuby.Compiler.Ast { /// is a new one, and here the only other reference is a variable no code reads again. ///
internal sealed class ForwardedRest : Walker { - // IR_FORWARD_REST=0 turns it off - private static readonly bool _enabled = Environment.GetEnvironmentVariable("IR_FORWARD_REST") != "0"; + // Off unless IR_FORWARD_REST=1. The gate of round 5 (2026-11-27) reached the rest Array after the call by names this + // walk cannot see: instance_eval and class_eval of a String, send(:eval, ...), an alias of eval - any call may ask + // for the frame's scope (RubyOps.LightScopeRequired) - and a TracePoint's binding at :return; each saw what the callee + // did to its rest parameter, where CRuby's caller keeps its own Array. Sound only where nothing runs in the frame after + // the call (the method's tail, no ensure) and no TracePoint is on, which this does not check yet. + private static readonly bool _enabled = Environment.GetEnvironmentVariable("IR_FORWARD_REST") == "1"; private readonly string/*!*/ _name; private readonly int _depth; diff --git a/Util/forward-rest-matrix.rb b/Util/forward-rest-matrix.rb new file mode 100644 index 000000000..fcc77ec4d --- /dev/null +++ b/Util/forward-rest-matrix.rb @@ -0,0 +1,43 @@ +# A rest parameter passed on as the splat of a call - `def w(*args) = n(*args)' - read again after the call by ways that +# do not name it in the method's source: instance_eval and class_eval of a String, send(:eval, ...), an alias of eval, +# Kernel#binding through bind_call or a Method, and a TracePoint's binding at :return. CRuby's caller keeps its own +# Array whatever the callee does to its rest parameter. IronRuby's ForwardedRest (IR_FORWARD_REST=1) handed the callee +# the caller's Array where its walk found no other reference, and each of these saw the callee's change (the gate of +# round 5, 2026-11-27); it is off by default until it checks that nothing can run in the frame after the call. +# (The bind_call and Method rows differ from CRuby on master too: CRuby cannot make a Binding for a non-Ruby caller.) +def n(*a); a << :x; a; end +def row(label) + r = begin; yield; rescue Exception => e; "#{e.class}: #{e.message[0, 60]}"; end + puts "#{label.ljust(48)} #{r.inspect}" +end +def w_ieval(*args); n(*args); instance_eval("args"); end +def w_ceval(*args); n(*args); Object.class_eval("1"); instance_eval { 0 }; instance_eval("args.size"); end +def w_send_binding(*args); n(*args); send(:binding).local_variable_get(:args); end +def w_usend_binding(*args); n(*args); __send__(:binding).local_variable_get(:args); end +def w_send_eval(*args); n(*args); send(:eval, "args"); end +def w_bind_call(*args); n(*args); Kernel.instance_method(:binding).bind_call(self).local_variable_get(:args); end +def w_method_binding(*args); n(*args); method(:binding).call.local_variable_get(:args) rescue $!.class; end +alias e_alias eval +def w_alias_eval(*args); n(*args); e_alias("args"); end +def w_lvars(*args); n(*args); send(:local_variables); end +def w_kept(*args) = n(*args) +3.times do + row('instance_eval(string) after the call') { w_ieval(1, 2) } + row('instance_eval(string) behind other evals') { w_ceval(1, 2) } + row('send(:binding)') { w_send_binding(1, 2) } + row('__send__(:binding)') { w_usend_binding(1, 2) } + row('send(:eval, "args")') { w_send_eval(1, 2) } + row('bind_call of Kernel#binding') { w_bind_call(1, 2) } + row('method(:binding).call') { w_method_binding(1, 2) } + row('an alias of eval') { w_alias_eval(1, 2) } + row('the callee keeps the Array') { a = [1, 2]; r = w_kept(*a); [a, r] } +end +$seen = [] +tp = TracePoint.new(:return) { |t| $seen << t.binding.local_variable_get(:args) if t.method_id == :w_traced } +def w_traced(*args) = n(*args) +w_traced(0) +tp.enable { w_traced(1, 2) } +def w_traced2(*args) = n(*args) +tp2 = TracePoint.new(:return) { |t| $seen << t.binding.local_variable_get(:args) if t.method_id == :w_traced2 } +tp2.enable { w_traced2(3, 4) } +row('TracePoint :return binding') { $seen } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 955b2eb5e..660f96919 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1910,7 +1910,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has MRI's FL_EXIVAR may stay set after the removal, which would send it through rb_obj_dup. - **perf/forward (2026-11-27) - a rest parameter passed on where nothing can see it again is the callee's rest parameter; a block-passing call's hoisted splat is fresh** (gap 36 and gap 16's second part; - `IR_FORWARD_REST=0` turns the first off) - timed, not gated. Bytes a call + `IR_FORWARD_REST=0` turned the first off) - timed, not gated. **The first part is off by default since round 5's + gate (2026-11-27), behind `IR_FORWARD_REST=1`**: `Util/forward-rest-matrix.rb` (new, from the gate's probes) reads + the rest parameter again after the call by names ForwardedRest's walk cannot see - `instance_eval("args")`, + `send(:eval, "args")`, an alias of `eval` (any call may ask for the frame's scope), a TracePoint's binding at + `:return` - and each saw the callee's `a << :x` (`[1, 2, :x]`, CRuby `[1, 2]`). It is sound only where nothing + runs in the frame after the call (the method's tail, no ensure) and no TracePoint is on, which it does not check + yet; the hoisted splat of a block-passing call (the second part) is a copy and stays. Bytes a call (`Util/bench/forward-bytes.rb`, new), base -> new: `def w(...) = raw(...)` 212 -> 116, `w(...) = rest_t(...)` (a callee with a rest) 309 -> 116, `w(*args, &b) = raw(*args, &b)` 227 -> 132, with a rest callee 312 -> 120, `w(*args) = rest_t(*args)` 214 -> 120, `w_splat(1) { }` 420 -> 325; @@ -7752,3 +7758,19 @@ What to take from it: - An upper bound measured by rewriting the benchmark says what the rewrite is worth, not what the mechanism is: before building for "the bytes", take the bytes away alone (a rewrite that keeps the block and drops the allocation) and time that. + +### Caught by the gate (round thirty-seven, round 5) + +- **A rest parameter handed to the callee as its own was read again through the frame's scope** - + perf/forward's ForwardedRest, before it merged into master. Its walk refused a block literal, + `binding`, `eval`, `local_variable_*` and a zsuper in the method, and took the splat as the only + reference to the rest parameter otherwise; the gate's probe read it after the call with + `instance_eval("args")`, `send(:eval, "args")`, an alias of `eval` and a TracePoint's binding at + `:return`, and each saw the callee's change. A light frame's scope is asked for at run time by + whatever the callee turns out to be (`RubyOps.LightScopeRequired`), so a list of names in the source + cannot say that nothing will read a local again; only "nothing runs in the frame after the call" + can, and a TracePoint can still look at :return. The experiment's matrix (splat-pass, kwrest-call) + had rows for what the callee does to the Array and none for a later reader of the caller's frame. + Off by default (`IR_FORWARD_REST=1` turns it on); `Util/forward-rest-matrix.rb` pins the readers. + A question for any change that lets two frames share what Ruby copies: list every way the frame can + be read after the call - eval by any name, binding by any route, TracePoint - before the walk. From 0a78877e2927690a343bd21159d7035b6b4d4d89 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:06:32 +0000 Subject: [PATCH 147/439] case over String literals: look the subject up once while String#=== is the library's A `case value' whose `when's are all String literals, ASCII in an ASCII-compatible encoding, made a new String for each literal and a `===' call through a call site for each `when' until one matched. MRI's opt_case_dispatch looks the subject up among the literals once. AWFY Json's read_value is such a `case', over the parser's current character, with eleven literals; the method JIT declines it (it calls methods the screen refuses), so the generic code ran it: a `case' of five clauses cost 146.5 ns a call without the method JIT against CRuby's 56.0 (Util/bench/strcmp-shapes.rb kase; the plain method call around it is 56 against 30). CaseExpression now gives such a `case' a CaseStringSite (Runtime/Calls), which maps each literal's characters to the first clause it is in: a one-character literal in a 128-entry table, a longer one in a dictionary. RubyOps.CaseStringDispatch answers the clause for a String subject that MutableString.FindAsciiLiteral can read in place (a shared one-character slice, or characters in an encoding where ASCII is its own bytes: the reading EqualsAsciiLiteral already does), while String#=== resolves to MutableStringOps' own method under the current global method version and the runtime has no refinements, the way ArrayExtremeSite checks Array#min. Anything else answers NotHandled and the `when's make their `===' calls as written: each condition is `clause == NotHandled ? : clause == i', so no clause's body is emitted twice. A light frame passes its declaring scope (only the runtime is read: LightFrameRewriter.ScopeOperandIndex). The AOT compiler re-creates the site. ReflectionCache.Generated.cs regenerated (two lines). IR_CASE_DISPATCH=0 turns it off. kase without the method JIT: 146.5 -> 64.0 ns (CRuby 56.0). Methods the JIT compiles keep its own comparisons (94-99 ns), not changed here. Util/case-string-matrix.rb (786 rows: 30 subjects - one-character reads, words, empty, UTF-8, BINARY, broken, US-ASCII, UTF-16LE, EUC-JP, frozen, a subclass, nil, a Symbol, numbers, a #to_str object - through six `case's, in methods the JIT compiles and one it declines, with frozen_string_literal, a refined String#===, a prepended one and a redefined one, with the calls each makes counted) prints CRuby 4.0's output on the base, on this build and with IR_CASE_DISPATCH=0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Src/Ruby/Builtins/MutableString.cs | 23 +++ .../Ast/Definitions/MethodDefinition.cs | 4 + .../Ast/Expressions/CaseExpression.cs | 66 +++++++- .../Compiler/ReflectionCache.Generated.cs | 2 + Src/Ruby/Runtime/Calls/CaseStringSite.cs | 126 +++++++++++++++ Src/Ruby/Runtime/RubyOps.cs | 10 ++ Util/aot/IronRuby.Aot/AotCompiler.cs | 6 + Util/bench/strcmp-shapes.rb | 64 ++++++++ Util/case-string-matrix.rb | 150 ++++++++++++++++++ 9 files changed, 446 insertions(+), 5 deletions(-) create mode 100644 Src/Ruby/Runtime/Calls/CaseStringSite.cs create mode 100644 Util/bench/strcmp-shapes.rb create mode 100644 Util/case-string-matrix.rb diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index 866ef7aec..76dc1bc1d 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -1492,6 +1492,29 @@ internal int EqualsAsciiLiteral(string/*!*/ ascii) { return String.Equals(content.Data, ascii) ? 1 : 0; } + /// + /// Which of a `case''s ASCII literals this String equals (CaseStringSite): the clause of the first + /// one, CaseStringSite.NoClause for none, CaseStringSite.NotHandled when only String#=== can tell. + /// The literals are in by their one character and in + /// otherwise. The same reading of the String as EqualsAsciiLiteral's: a + /// shared one-character slice as it is, a String held as characters in an encoding where ASCII is its + /// own bytes by its characters, anything else not here. + /// + internal int FindAsciiLiteral(int[]/*!*/ byChar, System.Collections.Generic.Dictionary/*!*/ byString) { + if (!_encoding.IsAsciiIdentity) { return Runtime.Calls.CaseStringSite.NotHandled; } + int shared = SharedAsciiChar; + if (shared >= 0) { return byChar[shared]; } + var content = _content as StringContent; + if (content == null) { return Runtime.Calls.CaseStringSite.NotHandled; } + string data = content.Data; + if (data.Length == 1) { + char c = data[0]; + return (c < byChar.Length) ? byChar[c] : Runtime.Calls.CaseStringSite.NoClause; + } + int clause; + return byString.TryGetValue(data, out clause) ? clause : Runtime.Calls.CaseStringSite.NoClause; + } + public int CompareTo(object other) { var ms = other as MutableString; if (ms != null) { diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 1cbc41380..17d0fe1c8 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -1736,6 +1736,10 @@ private static int ScopeOperandIndex(MethodInfo/*!*/ method) { if (LightKeywordsEnabled && (method == Methods.GetOmittedKeywordArguments || method == Methods.MakeOmittedKeywordArguments)) { return 0; } + // a `case' over String literals looks its value up (CaseStringSite): the runtime only + if (method == Methods.CaseStringDispatch) { + return 0; + } return -1; } diff --git a/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs index 2a5f666ac..46f70f8d6 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs @@ -16,6 +16,7 @@ using MSA = System.Linq.Expressions; using System; +using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Scripting; using IronRuby.Runtime.Calls; @@ -126,6 +127,41 @@ public CaseExpression(Expression value, WhenClause/*!*/[] whenClauses, Statement return result; } + /// + /// IR_CASE_DISPATCH=0 makes every `when' of a `case' over String literals a `===' call, as before (see + /// CaseStringSite). + /// + internal static readonly bool CaseDispatchEnabled = Environment.GetEnvironmentVariable("IR_CASE_DISPATCH") != "0"; + + // A `case value' whose `when's are all String literals, each ASCII in an ASCII-compatible encoding (MRI's + // opt_case_dispatch takes the same `case's, with other literals too): the site that looks the value up + // among them, or null. + private CaseStringSite TryMakeStringDispatch() { + if (!CaseDispatchEnabled || _value == null || _whenClauses.Length == 0) { + return null; + } + var literals = new List(); + var clauses = new List(); + for (int i = 0; i < _whenClauses.Length; i++) { + if (_whenClauses[i].Comparisons.Length == 0) { + return null; + } + foreach (var comparison in _whenClauses[i].Comparisons) { + var literal = comparison as StringLiteral; + if (literal == null) { + return null; + } + var str = literal.GetMutableString(); + if (!str.Encoding.IsAsciiIdentity || !str.IsAscii()) { + return null; + } + literals.Add(str.ToString()); + clauses.Add(i); + } + } + return new CaseStringSite(literals.ToArray(), clauses.ToArray()); + } + internal override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { MSA.Expression result; if (_elseStatements != null) { @@ -143,20 +179,40 @@ public CaseExpression(Expression value, WhenClause/*!*/[] whenClauses, Statement value = null; } + // `when' i is taken if the site says so, or, if the site cannot tell, if its `===' calls say so: + // clause = CaseStringDispatch(scope, value, site) + // if (clause == NotHandled ? : clause == 0) ... elseif ... else ... end + CaseStringSite site = TryMakeStringDispatch(); + MSA.ParameterExpression clause = (site != null) ? gen.CurrentScope.DefineHiddenVariable("#case-clause", typeof(int)) : null; + for (int i = _whenClauses.Length - 1; i >= 0; i--) { + MSA.Expression condition = TransformWhenCondition(gen, _whenClauses[i].Comparisons, value); + if (site != null) { + condition = Ast.Condition( + Ast.Equal(clause, AstUtils.Constant(CaseStringSite.NotHandled)), + condition, + Ast.Equal(clause, AstUtils.Constant(i)) + ); + } // emit: else (if (condition) body else result) result = AstFactory.Condition( - TransformWhenCondition(gen, _whenClauses[i].Comparisons, value), + condition, gen.TransformStatementsToExpression(_whenClauses[i].Statements), result ); } if (_value != null) { - result = Ast.Block( - Ast.Assign(value, Ast.Convert(_value.TransformRead(gen), typeof(object))), - result - ); + result = (site == null) + ? Ast.Block( + Ast.Assign(value, Ast.Convert(_value.TransformRead(gen), typeof(object))), + result + ) + : Ast.Block( + Ast.Assign(value, Ast.Convert(_value.TransformRead(gen), typeof(object))), + Ast.Assign(clause, Methods.CaseStringDispatch.OpCall(gen.CurrentScopeVariable, value, AstUtils.Constant(site))), + result + ); } return result; diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 78461b40d..de757109d 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -60,6 +60,8 @@ public static partial class Methods { private static MethodInfo _BlockYield; public static MethodInfo/*!*/ CanRescue { get { return _CanRescue ?? (_CanRescue = CallInstruction.CacheFunc(RubyOps.CanRescue)); } } private static MethodInfo _CanRescue; + public static MethodInfo/*!*/ CaseStringDispatch { get { return _CaseStringDispatch ?? (_CaseStringDispatch = CallInstruction.CacheFunc(RubyOps.CaseStringDispatch)); } } + private static MethodInfo _CaseStringDispatch; public static MethodInfo/*!*/ CheckSplatArity { get { return _CheckSplatArity ?? (_CheckSplatArity = CallInstruction.CacheAction(RubyOps.CheckSplatArity)); } } private static MethodInfo _CheckSplatArity; public static MethodInfo/*!*/ CheckSuperClass { get { return _CheckSuperClass ?? (_CheckSuperClass = CallInstruction.CacheFunc(RubyOps.CheckSuperClass)); } } diff --git a/Src/Ruby/Runtime/Calls/CaseStringSite.cs b/Src/Ruby/Runtime/Calls/CaseStringSite.cs new file mode 100644 index 000000000..a055ed0f1 --- /dev/null +++ b/Src/Ruby/Runtime/Calls/CaseStringSite.cs @@ -0,0 +1,126 @@ +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Apache License, Version 2.0, please send an email to + * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound + * by the terms of the Apache License, Version 2.0. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System.Collections.Generic; +using IronRuby.Builtins; + +namespace IronRuby.Runtime.Calls { + + /// + /// A `case' whose `when's are all String literals, ASCII in an ASCII-compatible encoding, dispatched + /// the way MRI's opt_case_dispatch does it: the subject is looked up among the literals once, and + /// the first clause with an equal one is taken - as long as String#=== is still the library's own + /// method, which compares contents and calls nothing. Otherwise - the subject not a String, or one + /// the lookup cannot read in place, String#=== redefined, aliased or prepended over, a refinement + /// about - the compiled code makes the `===' calls as written (CaseExpression). A `case' over a + /// parser's current character (AWFY Json's read_value, eleven literals) made a String per literal + /// and a call per `when' until one matched. + /// + public sealed class CaseStringSite { + /// Returned when the `===' calls have to be made as written. + public const int NotHandled = -2; + + /// Returned when no literal equals the subject. + public const int NoClause = -1; + + private sealed class Binding { + internal readonly RubyContext/*!*/ Context; + internal readonly int Version; + internal readonly bool Intact; + + internal Binding(RubyContext/*!*/ context, int version, bool intact) { + Context = context; + Version = version; + Intact = intact; + } + } + + // public, as are Literals and Clauses: the startup library (Util/aot) re-creates the site at load time + private readonly string/*!*/[]/*!*/ _literals; + private readonly int[]/*!*/ _clauses; + + // the clause of each one-character literal, by its character, and of each longer one + private readonly int[]/*!*/ _byChar; + private readonly Dictionary/*!*/ _byString; + private volatile Binding _binding; + + /// Every literal of every `when', in order: the characters of each. + /// The index of the `when' each literal is in. + public CaseStringSite(string/*!*/[]/*!*/ literals, int[]/*!*/ clauses) { + _literals = literals; + _clauses = clauses; + _byChar = new int[128]; + for (int i = 0; i < _byChar.Length; i++) { + _byChar[i] = NoClause; + } + _byString = new Dictionary(System.StringComparer.Ordinal); + // the first `when' with a literal wins, as the calls in order would have it + for (int i = 0; i < literals.Length; i++) { + string literal = literals[i]; + if (literal.Length == 1) { + if (_byChar[literal[0]] == NoClause) { + _byChar[literal[0]] = clauses[i]; + } + } else if (!_byString.ContainsKey(literal)) { + _byString.Add(literal, clauses[i]); + } + } + } + + public string/*!*/[]/*!*/ Literals => _literals; + public int[]/*!*/ Clauses => _clauses; + + /// The index of the clause to take, , or . + internal int Dispatch(RubyContext/*!*/ context, object value) { + var str = value as MutableString; + if (str == null || context.HasRefinements) { + return NotHandled; + } + + var binding = _binding; + if (binding == null || binding.Version != RubyModule.GlobalMethodVersion || binding.Context != context) { + _binding = binding = Bind(context); + } + if (!binding.Intact) { + return NotHandled; + } + + return str.FindAsciiLiteral(_byChar, _byString); + } + + private static Binding/*!*/ Bind(RubyContext/*!*/ context) { + // read before the lookup: a change that races with it leaves the binding stale, not wrong + int version = RubyModule.GlobalMethodVersion; + var lookup = context.GetClass(typeof(MutableString)).ResolveMethod("===", VisibilityContext.AllVisible); + return new Binding(context, version, lookup.Found && IsLibraryEquals(lookup.Info)); + } + + // MutableStringOps' ==/=== overloads: two StringEquals (a String, a CLR string) and Equals (anything + // else, through to_str) + private static bool IsLibraryEquals(RubyMemberInfo/*!*/ method) { + var libraryMethod = method as RubyLibraryMethodInfo; + if (libraryMethod == null) { + return false; + } + foreach (var member in libraryMethod.GetMembers()) { + if ((member.Name != "StringEquals" && member.Name != "Equals") || + member.DeclaringType.FullName != "IronRuby.Builtins.MutableStringOps") { + return false; + } + } + return true; + } + } +} diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index ac08cb622..96ca4ba0e 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -2410,6 +2410,16 @@ public static object ArrayLiteralExtreme(RubyScope/*!*/ scope, object item1, obj return site.Invoke(scope, item1, item2); } + /// + /// The clause of a `case' over String literals the subject is to take (CaseStringSite): its index, + /// CaseStringSite.NoClause, or CaseStringSite.NotHandled when the `===' calls are to be made as + /// written. The scope is only asked for its runtime. + /// + [Emitted] + public static int CaseStringDispatch(RubyScope/*!*/ scope, object value, CaseStringSite/*!*/ site) { + return site.Dispatch(scope.RubyContext, value); + } + [Emitted] public static bool IsArrayExtremeNotHandled(object result) { return ReferenceEquals(result, ArrayExtremeSite.NotHandled); diff --git a/Util/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index b3afb7173..6af84e9aa 100644 --- a/Util/aot/IronRuby.Aot/AotCompiler.cs +++ b/Util/aot/IronRuby.Aot/AotCompiler.cs @@ -1036,6 +1036,12 @@ private Expression Serialize(object value, out string hint) { hint = "extreme"; return Expression.New(typeof(ArrayExtremeSite).GetConstructor(new[] { typeof(bool) }), Expression.Constant(extreme.IsMax)); + case CaseStringSite caseSite: + hint = "casestr"; + return Expression.New(typeof(CaseStringSite).GetConstructor(new[] { typeof(string[]), typeof(int[]) }), + Expression.NewArrayInit(typeof(string), caseSite.Literals.Select(l => (Expression)Expression.Constant(l))), + Expression.NewArrayInit(typeof(int), caseSite.Clauses.Select(c => (Expression)Expression.Constant(c)))); + case BinaryOpStorage: hint = "opstorage"; return Expression.New(typeof(BinaryOpStorage).GetConstructor(new[] { typeof(RubyContext) }), ContextExpression); diff --git a/Util/bench/strcmp-shapes.rb b/Util/bench/strcmp-shapes.rb new file mode 100644 index 000000000..5f18ca6d4 --- /dev/null +++ b/Util/bench/strcmp-shapes.rb @@ -0,0 +1,64 @@ +# A one-character String compared with a one-character literal, the way AWFY Json's parser does it +# (ledger gap 7): `@current == '"'`, `'"' == @current`, `@current != '"'`, `case @current when ...`, +# `@input[@index] == ...`, in a method the method JIT compiles (jit_*) and in one it declines for +# a `raise` (the rest, as Json's read_string_internal, read_value, read_char are). ns per call of a +# method on H, the caller a `while` loop; the sum of the results is the checksum. +# +# ruby Util/perf/ab.rb Util/bench/strcmp-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ./ir.sh" \ +# "new=env IR_CONFIG=Release ../wt-json/ir.sh" -- eq ne lit_eq kase ws +# ruby Util/bench/strcmp-shapes.rb --list +$stdout.sync = true + +class H + def initialize + @s = 'ab"c d1{-' * 20 + @i = 0 + @c = @s[2] + @n = nil + end + + def jit_eq = (@c == '"') ? 1 : 0 + def eq; raise "never" if @n; (@c == '"') ? 1 : 0; end + def ne; raise "never" if @n; (@c != '"') ? 1 : 0; end + def lit_eq; raise "never" if @n; ('"' == @c) ? 1 : 0; end + def kase + raise "never" if @n + case @c + when 'n' then 1 + when 't' then 2 + when '{' then 3 + when '-', '0', '1', '2' then 4 + when '"' then 5 + else 6 + end + end + def ws; raise "never" if @n; (' ' == @c || "\t" == @c || "\n" == @c || "\r" == @c) ? 1 : 0; end + def idx_eq; raise "never" if @n; @i = (@i + 1) % 180; (@s[@i] == '"') ? 1 : 0; end + def idx; raise "never" if @n; @i = (@i + 1) % 180; @s[@i].size; end + def plain; raise "never" if @n; @c.size; end +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +h = H.new +N = (ENV["N"] || 1_000_000).to_i +t("jit_eq", N) { |n| i = 0; s = 0; while i < n; s += h.jit_eq; i += 1; end; s } +t("eq", N) { |n| i = 0; s = 0; while i < n; s += h.eq; i += 1; end; s } +t("ne", N) { |n| i = 0; s = 0; while i < n; s += h.ne; i += 1; end; s } +t("lit_eq", N) { |n| i = 0; s = 0; while i < n; s += h.lit_eq; i += 1; end; s } +t("kase", N) { |n| i = 0; s = 0; while i < n; s += h.kase; i += 1; end; s } +t("ws", N) { |n| i = 0; s = 0; while i < n; s += h.ws; i += 1; end; s } +t("idx_eq", N) { |n| i = 0; s = 0; while i < n; s += h.idx_eq; i += 1; end; s } +t("idx", N) { |n| i = 0; s = 0; while i < n; s += h.idx; i += 1; end; s } +t("plain", N) { |n| i = 0; s = 0; while i < n; s += h.plain; i += 1; end; s } diff --git a/Util/case-string-matrix.rb b/Util/case-string-matrix.rb new file mode 100644 index 000000000..757bbaad3 --- /dev/null +++ b/Util/case-string-matrix.rb @@ -0,0 +1,150 @@ +# Differential matrix for `case' over String literals (CaseExpression, CaseStringSite: a `case' whose +# `when's are all ASCII String literals looks its subject up once, as MRI's opt_case_dispatch does). +# +# ruby Util/case-string-matrix.rb > /tmp/case.mri +# ./ir.sh Util/case-string-matrix.rb > /tmp/case.ir +# IR_CASE_DISPATCH=0 ./ir.sh Util/case-string-matrix.rb > /tmp/case.off +# diff /tmp/case.mri /tmp/case.ir +# +# Every subject goes through each `case' in a method the method JIT compiles and in one it declines (a +# `raise' with a call in its argument, as AWFY Json's read_value), many times, so that both compilers, +# both tiers and the sites' bindings are exercised; then String#=== is redefined, prepended over and +# refined, and the same `case's run again. + +class SubStr < String; end +$calls = 0 +class ToStr; def initialize(s) = @s = s; def to_str = @s; def ==(o) = ($calls += 1; @s == o); end +class EqOnly; def ==(o) = true; end + +SUBJECTS = { + "read q" => 'a"b'[1], "read n" => 'xn'[1], "read digit" => '19'[1], "read dash" => '-'[0], "read brace" => '{x'[0], + "read other" => 'z'[0], "lit q" => '"', "built q" => +"" << '"', "multi" => "true", "multi2" => "null", + "multi3" => "nul", "empty" => "", "utf8" => "é", "utf8 n" => "ñ", "binary q" => '"'.b, "binary hi" => "\xE9".b, + "broken" => "\xE9".dup.force_encoding("UTF-8"), "usascii q" => '"'.dup.force_encoding("US-ASCII"), + "utf16 q" => '"'.encode("UTF-16LE"), "eucjp" => "\xA4\xA2".dup.force_encoding("EUC-JP"), "frozen q" => '"'.freeze, + "substr q" => SubStr.new('"'), "nil" => nil, "sym" => :n, "int" => 1, "float" => 1.0, "tostr" => ToStr.new('"'), + "eqonly" => EqOnly.new, "chars n" => "n".chars[0], "slice multi" => "xtrue"[1..], +} + +def value_case(c) + case c + when 'n' then :null + when 't' then :true + when 'f' then :false + when '"' then :string + when '[' then :array + when '{' then :object + when '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' then :number + else :other + end +end + +def value_case_declined(c) + raise expected('value') if c.equal?(:never) + case c + when 'n' then :null + when 't' then :true + when '"' then :string + when '-', '0', '1', '9' then :number + else :other + end +end +def expected(x) = "expected #{x}" + +def multi_case(c) + raise expected('x') if c.equal?(:never) + case c + when 'true', 'null' then :word + when 'n', 'nul' then :short + when '' then :empty + when 'true' then :duplicate + end +end + +def dup_case(c) + case c + when '"' then 1 + when 'x', '"' then 2 + end +end + +def mixed_case(c) + case c + when 'n' then 1 + when 'é' then 2 + when /\d/ then 3 + else 4 + end +end + +def no_value_case(c) + case + when c == '"' then 1 + else 2 + end +end + +CASES = %i[value_case value_case_declined multi_case dup_case mixed_case no_value_case] + +def run(label) + puts "== #{label}" + SUBJECTS.each do |name, s| + CASES.each do |m| + $calls = 0 + r = begin + a = 30.times.map { send(m, s) }.uniq + a.size == 1 ? a[0].inspect : "UNSTABLE #{a.inspect}" + rescue Exception => e + "#{e.class}: #{e.message}" + end + puts "#{name}\t#{m}\t#{r}\tcalls=#{$calls}" + end + end +end + +run "library String#===" + +eval <<~'RUBY' + # frozen_string_literal: true + def frozen_case(c) + case c + when 'n' then :null + when '"' then :string + else :other + end + end +RUBY +puts "== frozen_string_literal" +SUBJECTS.each { |name, s| puts "#{name}\tfrozen_case\t#{(30.times.map { frozen_case(s) }.uniq.inspect rescue $!.class)}" } + +module Ref + refine String do + def ===(o) = ($calls += 1; (o.respond_to?(:to_str) && o.to_str == "z") || super) + end +end +using Ref +def refined_case(c) + case c + when 'n' then :null + when '"' then :string + else :other + end +end +puts "== refined String#===" +SUBJECTS.each { |name, s| $calls = 0; r = (30.times.map { refined_case(s) }.uniq.inspect rescue $!.class); puts "#{name}\trefined_case\t#{r}\tcalls=#{$calls}" } +run "after `using' (the methods above were defined before it)" + +module Loud + def ===(o) + $calls += 1 + super + end +end +String.prepend(Loud) +run "String#=== prepended over" + +# last: the library String#=== is gone for good +class String + def ===(o) = ($calls += 1; o.is_a?(String) ? (self == o || (o.size == 1 && o == "z")) : false) +end +run "String#=== redefined (z matches every one-character literal; Loud still prepended)" From a4cc7edb9ddca831aacd25f234e71d769ab52aea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:08:17 +0000 Subject: [PATCH 148/439] Ledger: perf/nbody2; ivar-float-shapes counts instructions with INSTR=1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/bench/ivar-float-shapes.rb | 8 +++++- Util/perf/LEDGER.md | 50 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/Util/bench/ivar-float-shapes.rb b/Util/bench/ivar-float-shapes.rb index f4c4d1ad1..cd91508ce 100644 --- a/Util/bench/ivar-float-shapes.rb +++ b/Util/bench/ivar-float-shapes.rb @@ -9,6 +9,8 @@ $stdout.sync = true N = (ENV['N'] || 2_000_000).to_i BYTES = ENV['BYTES'] == '1' +# INSTR=1 (Util/perf/ab.rb -i): instructions per operation as well, the least of the repetitions +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) A = Object.new B = Object.new @@ -65,11 +67,13 @@ def run_shape(name) op, kind = name.split('_') cls, x, vx, m = KINDS[kind] best = nil + fewest = nil r = nil 6.times do o = cls.new b = IvBody.new(x, vx, m) c = IvBody.new(vx, x, m) + c0 = INSTR && INSTR.read t = BYTES ? System::GC.get_total_allocated_bytes(true) : Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) i = 0 r = case op @@ -80,6 +84,8 @@ def run_shape(name) when 'read' then read_op(kind, b, c, i) end d = BYTES ? System::GC.get_total_allocated_bytes(true) - t : Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) - t + c1 = INSTR && INSTR.read + fewest = c1 - c0 if c0 && c1 && (fewest.nil? || c1 - c0 < fewest) best = d if best.nil? || d < best end r = r.round(6) if r.is_a?(Float) @@ -87,7 +93,7 @@ def run_shape(name) if BYTES puts format('%s %.1f B %s', name, best.to_f / N, r) else - puts format('%s %.1f ns %s', name, best * 1e9 / N, r) + puts format('%s %.1f ns %s%s', name, best * 1e9 / N, r, fewest ? format(' %.1f instr', fewest.to_f / N) : '') end end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 973ae36f3..145e16009 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -703,6 +703,15 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has callgrind counts `advance` level and a light nested shape 0.8% dearer, so the change is worth what the collector does not have to do, which the time on this machine could not show. + Round thirty-nine traced them (see Landed, perf/nbody2): the boxes were made at the + exits of the loops' typed copies - the `each_index` and `each` counters and the + `each_index` parameter boxed without the small-integer cache, and `dt`, which the + copies only read, boxed again at every exit. Gone: 48 -> 18 MB per iteration. Per + `advance` there is left the 24-byte locals tuple of the parked scope (made new on + each call); the rest of NBody's 18 MB is the harness's `times` block (its index + past the cache, the `0.01` literal) and `energy`. TruffleRuby allocates nothing + there; the next step for the tuple is a parked scope that keeps its tuple when no + Proc of the call outlived it. 3. **CD's red-black tree** (`put`, `tree_insert`, `find_node`, `Vector2D#compare_to`: 18.5% of self time now that `is_in_voxel` is compiled). `compare_to` is screen-rejected over its self call of `compare_numbers`, a three-line Float-only @@ -2216,6 +2225,47 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Method_LightFrame*`: PASSED. The census cannot see this (no method changes verdict). Not run: `IR_CONFIG=R2R` start-up, the suite, a sweep, AWFY (owed to the gate). +- **perf/nbody2 7621c60 (round thirty-nine, 2026-11-27) - an OSR loop's exits box Integers through + the cache and store back only what the copy changed and someone reads (gap 2)** - not gated. + What perf/nbody left of NBody (48 MB, 192 bytes per `advance`) was traced by variants of `advance` + under the allocation-tick probe (the outer `each_index` alone; with the nested loop; with the inner + body; the `each` loop; a block local), each subtracted from the next: the boxes were made at the + exits of the loops' typed copies, which stored every slot back into its tuple and boxed it. An Int32 + went home with a plain convert (`JitLoopCompiler.Box`), not through the small-integer cache: the + `each_index` counter (5) and parameter (4) and the `each` counter, three 24-byte boxes per call. A + local the copy only reads - `dt` - was boxed again at every exit, two Float boxes per call. And a + block loop's own parameter and block locals went into the BlockLoopSite's private tuple, which Run + clears afterwards. Now an Int32 goes home through `ScriptingRuntimeHelpers.Int32ToObject`; a slot + the copy's body never assigns (`AssignsVariable`: no assignment, compound assignment, increment or + by-ref argument; an irreducible extension node counts as one) is stored back at neither exit, which + also leaves a value another thread or a callee wrote meanwhile (the old exit wrote the copy's stale + value over it); and a block loop's copy stores none of its block's own locals + (`OsrLoopSite.DeadAtExit`: a generic iteration after a hand-back yields to the block, whose call + has a scope of its own). Switch: IR_LOOP_EXITS=0. + Bytes (Util/perf/alloc.rb, against the merge of perf/nbody into b887bc1): NBody 48,028,049 -> + 18,033,212 per iteration (0.375; 152 MB before perf/nbody), Richards 12,831,820 -> 11,171,978, + Sieve 98,655,217 -> 89,044,457, the other eleven level; geomean of the fourteen 0.924. Per `advance` + (the probe): 166 -> 46 bytes, the probe's driver (22) and the locals tuple (24) left. + Instructions (callgrind, IR_LOOP_EXITS=0 -> 1, one tree): Util/bench/ivar-float-shapes.rb (which + counts instructions now, INSTR=1) level on all fifteen shapes in three pairs of processes, to 0.1; + two earlier runs, made while the AWFY timing ran beside them, gave `wloop_o` 13,947 against 1,421 + with the switch on, which three later runs (one traced) did not repeat and which no tier explains + (the loop is not specialized in either mode): noted, not believed. nested-proc-shapes: in the + noise of its two modes (some 400 instructions apart from process to process). Time, on a quiet + machine (load 0.1, the container restarted): NBody 598.3 -> 484.4 and 696.0 -> 574.6 ms (0.81, 0.83) + in the two column orders at 10 s; the fourteen 0.993 and 0.966; nothing else outside the table's + noise in both orders. No FAIL; NBody prints the same with -X:NoJIT -X:NoOSR. + Matrices (Util/perf/gate-matrices.rb, base the merge above): loop-exit (new: Integers ending at the + cache's bounds, past Int32 and Int64, an Integer's identity after it went home, a Float and an + Integer parameter only read, a local the loop reads that a proc or another thread changes during + it, block locals after the block, deopts in block loops, the outer parameter after a nested loop, + and an Integer instance variable updated in a hot loop that passes Int32 and Int64, is set to a + Float or a String in the middle, is set from outside, has a subclass with more variables, and is + read by another thread), nested-proc, ivar, int, block-loop, osr-array, jit, jit-calls, hot-shapes, + parked-scope, in the gate's six modes and IR_LOOP_EXITS=0: 15 baseline, 55 same, no DIFF. + `Util/ivar-stress.rb` OK three times. Not done: the Integer instance variables of gap 2 (NBody has + none in its hot loops; the allocations were not there). + - **perf/nbody b3c20a5 55be4d2 (round thirty-eight, 2026-11-27) - a block literal with a literal nested in it reuses its Proc when it can be outlined (gap 2)** - not gated. NBody allocated 152 MB per iteration, 608 bytes per `advance`; an in-process GC allocation-tick listener (EventListener on From dc9b5720198f0c213ed988321325aeaa80518b55 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:09:02 +0000 Subject: [PATCH 149/439] The unused-block warning knows the block-using method names of the whole file `-w` warned "the block passed to 'A#given' ... may be ignored" for a method that does not use its block even when another method of that name, defined later in the file, does (LEDGER gap 28: the warning showed in a long file where CRuby 4.0 stays quiet). CRuby's rule (vm_insnhelper.c warn_unused_block, compile.c iseq_set_use_block): a method that uses its block puts its name in a table when it is compiled, and a block passed to any method of that name is not warned about unless Warning[:strict_unused_block]; CRuby compiles the whole file before running it, so a later def, or one never run, counts. IronRuby noted the name only when the def ran. The prism bridge now notes it when it maps the def (PrismAstBridge.NoteUsesBlock), as CRuby's compiler does. Not changed: CRuby can repeat the warning for another call site of the same method on its uncached call path (its call caches are shared per class and name); IronRuby warns once per method. And block_given? does not count as using the block, in either. Checked: UnusedBlock_LaterDefinition1 (new; CRuby 4.0's output, through Warning.warn), RubyBlocks12-14C; spec/language method and block, spec/core/warning: as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BlockTests.cs | 20 ++++++++++++++++++++ Src/Prism/PrismAstBridge.cs | 15 ++++++++++++--- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index cd4a81638..4b50100bc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -320,6 +320,7 @@ public Tests(Driver/*!*/ driver) { RubyBlocks14A, RubyBlocks14B, RubyBlocks14C, + UnusedBlock_LaterDefinition1, RubyBlocks16, RubyBlocks18, diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index 505812e99..32a0f64a5 100644 --- a/Src/IronRuby.Tests/Runtime/BlockTests.cs +++ b/Src/IronRuby.Tests/Runtime/BlockTests.cs @@ -2462,6 +2462,26 @@ p o.first ""unexpected break"" :break ""break from proc-closure"" +"); + } + + /// + /// A block passed to a method that does not use it is not warned about when some method of the same name uses a block, + /// a def later in the file included: MRI notes those names when it compiles the file (iseq_set_use_block). LEDGER gap 28. + /// + public void UnusedBlock_LaterDefinition1() { + // the one warning, about C#other, is the runtime's to count too + AssertOutput(() => CompilerTest(@" +def Warning.warn(msg, category: nil) = print(""warn: "", msg.sub(/\A.*?warning: /, """").sub(/ defined at \S+/, """")) +class A; def given; block_given?; end; end +class C; def other; 1; end; end +def outer(&b) = A.new.given(&b) +p outer { }, C.new.other { } +class B; def given; yield; end; end +", 0, 1), @" +warn: the block passed to 'C#other' may be ignored +true +1 "); } } diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 4b9e6b120..acfcda485 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -2232,15 +2232,15 @@ private Parameters BlockParameters(Pm.PmNode parametersNode, bool autoSplat, out // What mapping it now would have set _usesBlock to the skim has noted. if ((node.BodyContents & PrismLoader.ContentsEager) == 0) { var deferred = new DeferredMethodBody(this, node, scope, span, prologue, _zsuperArguments); - return new MethodDefinition(scope, target, node.Name, parameters, deferred.Materialize, span) { + return NoteUsesBlock(new MethodDefinition(scope, target, node.Name, parameters, deferred.Materialize, span) { UsesBlock = _usesBlock || (node.BodyContents & PrismLoader.ContentsUsesBlock) != 0 - }; + }); } node.Body = node.DeferredBodyLoader.LoadDeferredBody(node); node.DeferredBodyLoader = null; } var body = DefinitionBody(node.Body, span, prologue, node.EqualLoc != null); - return new MethodDefinition(scope, target, node.Name, parameters, body, span) { UsesBlock = _usesBlock }; + return NoteUsesBlock(new MethodDefinition(scope, target, node.Name, parameters, body, span) { UsesBlock = _usesBlock }); } finally { _zsuperArguments = enclosingZSuperArguments; } @@ -2250,6 +2250,15 @@ private Parameters BlockParameters(Pm.PmNode parametersNode, bool autoSplat, out } } + // MRI's iseq_set_use_block: a method that uses its block makes a block passed to any method of its name exempt from the + // "may be ignored" warning from when the file is compiled - so a def later in the file, or one never run, counts too. + private MethodDefinition/*!*/ NoteUsesBlock(MethodDefinition/*!*/ definition) { + if (definition.UsesBlock && _sourceUnit != null && _sourceUnit.LanguageContext is RubyContext context) { + context.NoteMethodUsingBlock(definition.Name); + } + return definition; + } + /// /// A method body left in prism's buffer, mapped the first time the method's AST body is asked /// for - normally when the method is first called and compiled. It is mapped as Def would have From e1e5003e451880a6757bfd87d2b90d8376800679 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:09:58 +0000 Subject: [PATCH 150/439] An outlined loop looks its folded constants up again at its entry A loop outlined by OSR (JitLoopCompiler) that folded a constant guarded its entry on the constant version as it was when the copy was compiled. Every new constant, extend, singleton class and require moves that version, so the copy handed itself back and the site rebuilt it, once per event: under -X:NoJIT a loop reading TOP beside one extend, const_set or require per round was specialized 14-20 times in 20 rounds and ran 1.6x as long as with no events. perf/constrev did this for method bodies. The loop's guard now holds what the copy folded (JitLoopFacts.FoldedConstants, null when a directly called body folded constants it did not record), and the entry calls JitRuntime.LoopConstantsCurrent: the version unchanged since the guard's snapshot, or each folded constant still the same object found in the same module (JitLoopGuard.ConstantsStillHold, as a method body's safe point already uses it). IR_LOOP_CONSTANTS=0 turns it off. A reassignment still moves the code epoch and hands a running copy back at its safe point. Util/loop-const-matrix.rb (new): outlined loops under every kind of constant change between entries - unrelated events, reassignment, removal, nearer constants lexically, by superclass and include, an autoload registered nearer and one in flight, other threads. CRuby 4.0's output on both builds in each mode; six rows go wrong with the check answering true always. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 9 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 4 + Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 11 ++ Src/Ruby/Runtime/Jit/JitLoopCompiler.cs | 13 ++- Src/Ruby/Runtime/Jit/JitRuntime.cs | 5 +- Util/loop-const-matrix.rb | 113 ++++++++++++++++++++ 6 files changed, 148 insertions(+), 7 deletions(-) create mode 100644 Util/loop-const-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 578fcc626..30e1f9c37 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -158,6 +158,9 @@ public override void Exit(MethodCall/*!*/ node) { // moved (JitFoldedConstant.StillHolds). private List _foldedConstants; + // A body this one calls folded constants it did not record: what this one folded cannot all be looked up again. + private bool _foldedIncomplete; + /// /// What the constant resolves to right now (JitFoldedConstant.Resolve), or a bailout wherever that would /// not be a value the constant version alone keeps valid. Every constant it answers is recorded, for @@ -173,8 +176,8 @@ private object ResolveConstant(ConstantVariable/*!*/ node) { _resolvedConstantOwner = owner; (_foldedConstants ?? (_foldedConstants = new List())).Add(new JitFoldedConstant(scope, node, value, owner)); _usesConstants = true; - // a method body's loop runs on past the entry's revalidation (TryCompile); an outlined loop's copy hands - // itself back on any reassignment + // a method body's loop runs on past the entry's revalidation (TryCompile); an outlined loop's copy looks its + // constants up again at its entry (JitRuntime.LoopConstantsCurrent) and hands itself back on any reassignment if (_loop == null) { if (_hasLoop) { _foldedInLoop = true; } if (_calleeLoop) { _foldedAfterCalleeLoop = true; } @@ -184,7 +187,7 @@ private object ResolveConstant(ConstantVariable/*!*/ node) { /// Takes over what a body this one calls directly folded (EmitDirectCall). private void TakeFoldedConstants(JitCode/*!*/ code) { - if (code.FoldedConstants == null) { return; } + if (code.FoldedConstants == null) { _foldedIncomplete = true; return; } (_foldedConstants ?? (_foldedConstants = new List())).AddRange(code.FoldedConstants); } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 0cf6b2970..fee47c7b9 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -343,6 +343,9 @@ internal static MSA.Expression TryCompileLoop(WhileLoopExpression/*!*/ loop, Rub internal struct JitLoopFacts { // the body folded constants: the entry guards on the constant version internal bool UsesConstants; + // what it folded, for the entry to look up again when the constant version has moved + // (JitRuntime.LoopConstantsCurrent); null if it folded none, or some it did not record + internal JitFoldedConstant[] FoldedConstants; // the body writes Hash elements: the iteration's writes go into the undo log, which the // body commits at the top of each iteration (UndoLog) from the mark the entry sets (UndoMark) internal MSA.ParameterExpression UndoLog; @@ -402,6 +405,7 @@ internal static MSA.Expression TryCompileLoop(WhileLoopExpression/*!*/ loop, Rub } slots = c._slots; facts.UsesConstants = c._usesConstants; + facts.FoldedConstants = (c._usesConstants && c._foldedConstants != null && !c._foldedIncomplete) ? c._foldedConstants.ToArray() : null; facts.UndoLog = c._undoLog; facts.UndoMark = c._undoMark; facts.Arrays = c._arrayLoads; diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index c6080504b..be9596dea 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -974,6 +974,17 @@ public static bool ConstantsOk(RubyContext/*!*/ context, int snapshot) { return context.ConstantAccessVersion == snapshot; } + /// + /// The entry guard of an outlined loop that folded constants and recorded them all: nothing has changed any constant + /// since the guard's snapshot, or the constants it folded are still what they were (JitLoopGuard.ConstantsStillHold, + /// which then moves the snapshot up - as JitStub.RevalidateConstants does for a method entry). + /// + public static bool LoopConstantsCurrent(object/*!*/ guard) { + var loopGuard = (JitLoopGuard)guard; + return System.Threading.Volatile.Read(ref loopGuard.ConstantsOf.ConstantAccessVersion) == + System.Threading.Volatile.Read(ref loopGuard.ConstantVersion) || loopGuard.ConstantsStillHold(); + } + /// /// The guard of a method entry whose typed bodies folded constants: nothing has changed any constant /// since the specialization's snapshot, or the constants they folded are still what they were diff --git a/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs index 8e1dfbb5a..d895e3757 100644 --- a/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs @@ -57,6 +57,9 @@ internal sealed class JitLoopSlot { } internal static class JitLoopCompiler { + // IR_LOOP_CONSTANTS=0: an outlined loop that folded constants is handed back after any constant change, as before. + private static readonly bool _RevalidateConstants = Environment.GetEnvironmentVariable("IR_LOOP_CONSTANTS") != "0"; + /// The boxed form a slot's value goes home as. private static MSA.Expression/*!*/ Box(MSA.Expression/*!*/ value, bool isLong) { return isLong ? Ast.Call(JitRuntime.M("NarrowLong"), value) : (MSA.Expression)Ast.Convert(value, typeof(object)); @@ -267,10 +270,16 @@ internal static Func TryCompile(WhileLoopExpression/*!*/ loop, Ast.Not(Ast.Call(JitRuntime.M("VersionOk"), Ast.Constant(version))), Ast.Return(exit, Ast.Call(JitRuntime.M("OsrVersionStale"))) )); - // and no constant may have changed since the ones the body folded were read + // and no constant may have changed since the ones the body folded were read - or each of those is still what + // it was (JitRuntime.LoopConstantsCurrent): a new constant elsewhere, an extend, a singleton class or a + // require moves the one constant version, and each handed the loop back for a rebuild at its next entry if (facts.UsesConstants) { + bool revalidate = facts.FoldedConstants != null && _RevalidateConstants; + if (revalidate) { facts.Guard.Folded = facts.FoldedConstants; } prologue.Add(Ast.IfThen( - Ast.Not(Ast.Call(JitRuntime.M("ConstantsOk"), Ast.Constant(context), Ast.Constant(constantVersion))), + Ast.Not(revalidate + ? Ast.Call(JitRuntime.M("LoopConstantsCurrent"), Ast.Constant(facts.Guard)) + : Ast.Call(JitRuntime.M("ConstantsOk"), Ast.Constant(context), Ast.Constant(constantVersion))), Ast.Return(exit, Ast.Call(JitRuntime.M("OsrVersionStale"))) )); } diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index e09b0f742..fa0933cdb 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1323,8 +1323,9 @@ public sealed class JitLoopGuard { internal RubyContext ConstantsOf; // a typed method body may deopt at its loop's safe point (see MethodLoopSafePointSlow) internal bool MayDeopt; - // what the typed method body folded (JitCode.FoldedConstants), for its loops' safe points to look up again; null - // if it folded none, or is an outlined loop's copy (which hands itself back instead). Set before the code runs. + // what the typed method body folded (JitCode.FoldedConstants), for its loops' safe points to look up again, or what + // an outlined loop's copy folded, for its entry to (JitRuntime.LoopConstantsCurrent); null if it folded none or + // some it did not record. Set before the code runs. internal JitFoldedConstant[] Folded; internal static readonly System.Reflection.FieldInfo/*!*/ EpochField = typeof(JitLoopGuard).GetField("Epoch"); diff --git a/Util/loop-const-matrix.rb b/Util/loop-const-matrix.rb new file mode 100644 index 000000000..5b48a90db --- /dev/null +++ b/Util/loop-const-matrix.rb @@ -0,0 +1,113 @@ +# Differential matrix for outlined (OSR) loops that fold constants (JitLoopCompiler, gap 29): a loop long enough to be +# outlined (IR_OSR_THRESHOLD, 2,000 back edges) reads constants; between its entries something happens to constants - +# a new one elsewhere, an extend, a require, the same value set again, a removal, a reassignment, a nearer one +# lexically or through the ancestors, an autoload - and each entry's sum is printed. The loops are written in blocks, +# which the method JIT does not take, so they are outlined with the JIT on as well as off. Run under CRuby and under +# ./ir.sh in each mode and diff: +# +# ruby Util/loop-const-matrix.rb > /tmp/mri.txt; echo $? +# ./ir.sh Util/loop-const-matrix.rb > /tmp/jit.txt; echo $? +# ./ir.sh -X:NoJIT Util/loop-const-matrix.rb > /tmp/nojit.txt +# IR_LOOP_CONSTANTS=0 ./ir.sh Util/loop-const-matrix.rb > /tmp/off.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt && diff /tmp/mri.txt /tmp/off.txt +# +# All must exit 0, end with the row `end', and be identical. Warnings ("already initialized constant") go to stderr, +# which is not compared; IR_OSR_VERBOSE=1 says what the loops did. +$stdout.sync = true +$VERBOSE = nil +require 'tmpdir' + +N = 3000 +def run = yield +def row(label, value) = puts("#{label}: #{value.inspect}") +# n entries of the loop the block runs, with what `between' does before each one; the sums, as runs [sum, how many] +def entries(n, between) + out = [] + n.times { |k| between&.call(k); out << yield } + out.chunk_while { |a, b| a == b }.map { |c| [c[0], c.size] } +end + +# ---------------------------------------------------------------- 1. events that must not change the answer +TOP = 2 +module G; module P; RUBY = 3; end; end +module M1; end +DIR = Dir.mktmpdir("loopconst") +loop1 = -> { run { i = 0; s = 0; while i < N; s += TOP + G::P::RUBY; i += 1; end; s } } +row "nothing", entries(12, nil) { loop1.() } +row "new constant elsewhere", entries(12, ->(k) { Object.const_set("NEW1_#{k}", k) }) { loop1.() } +row "extend", entries(12, ->(k) { Object.new.extend(M1) }) { loop1.() } +row "singleton class", entries(12, ->(k) { Object.new.singleton_class }) { loop1.() } +row "require", entries(12, ->(k) { File.write("#{DIR}/r1_#{k}.rb", "R1_#{k} = #{k}\n"); require "#{DIR}/r1_#{k}" }) { loop1.() } +row "same value set again", entries(12, ->(k) { Object.const_set(:TOP, TOP) }) { loop1.() } +row "include into an unrelated class", entries(12, ->(k) { Class.new.include(Module.new { const_set(:TOP, 99) }) }) { loop1.() } + +# ---------------------------------------------------------------- 2. changes that must +TOP2 = 1 +loop2 = -> { run { i = 0; s = 0; while i < N; s += TOP2; i += 1; end; s } } +row "reassigned", entries(12, ->(k) { Object.const_set(:TOP2, k) if k % 4 == 0 }) { loop2.() } +TOP3 = 1 +loop3 = -> { run { i = 0; s = 0; while i < N; s += (defined?(TOP3) ? TOP3 : 0); i += 1; end; s } } +row "removed and set again", entries(12, ->(k) { Object.send(:remove_const, :TOP3) if k == 4; Object.const_set(:TOP3, 7) if k == 8 }) { loop3.() } +TOP4 = 1 +loop4 = -> { begin; run { i = 0; s = 0; while i < N; s += TOP4; i += 1; end; s }; rescue NameError => e; e.class; end } +row "removed for good", entries(8, ->(k) { Object.send(:remove_const, :TOP4) if k == 4 }) { loop4.() } + +# a nearer constant appears between entries: lexically, through a superclass, an included and a prepended module +X5 = 1 +module L5 + def self.go = run { i = 0; s = 0; while i < N; s += X5; i += 1; end; s } +end +row "nearer lexical", entries(10, ->(k) { L5.const_set(:X5, 10) if k == 5 }) { L5.go } +class B6; end +class C6 < B6 + def self.go = run { i = 0; s = 0; while i < N; s += X6; i += 1; end; s } +end +X6 = 1 +row "nearer in a superclass", entries(10, ->(k) { B6.const_set(:X6, 20) if k == 5 }) { C6.go } +X7 = 1 +class C7 + def self.go = run { i = 0; s = 0; while i < N; s += X7; i += 1; end; s } +end +row "nearer by include", entries(10, ->(k) { C7.include(Module.new { const_set(:X7, 30) }) if k == 5 }) { C7.go } +module Q8; X = 1; end +module R8; end +loop8 = -> { run { i = 0; s = 0; while i < N; s += Q8::X; i += 1; end; s } } +# (not `Q8.prepend(Module.new { const_set(:X, 40) })`: IronRuby finds the prepended X in every mode, CRuby Q8's own) +row "qualified, its path replaced", entries(10, ->(k) { Object.const_set(:Q8, Module.new { const_set(:X, 50) }) if k == 5 }) { loop8.() } + +# an autoload registered nearer between entries, and a loop entered while an autoload of that name is in flight +X9 = 1 +File.write("#{DIR}/x9.rb", "module L9; X9 = 9; end\n") +module L9 + def self.go = run { i = 0; s = 0; while i < N; s += X9; i += 1; end; s } +end +row "autoload registered nearer", entries(8, ->(k) { L9.autoload(:X9, "#{DIR}/x9.rb") if k == 4 }) { L9.go } +X10 = 1 +File.write("#{DIR}/x10.rb", "$x10_inside = 4.times.map { L10.go }\nmodule L10; X10 = 10; end\n") +module L10 + def self.go = run { i = 0; s = 0; while i < N; s += X10; i += 1; end; s } +end +before = 6.times.map { L10.go } +L10.autoload(:X10, "#{DIR}/x10.rb") +row "loop entered during the autoload", [before, (L10::X10 rescue $!.class), $x10_inside, L10.go] + +# ---------------------------------------------------------------- 3. another thread +TOP11 = 1 +loop11 = -> { run { i = 0; s = 0; while i < N; s += TOP11; i += 1; end; s } } +stop = false +definer = Thread.new { k = 0; until stop; Object.const_set("T11_#{k % 500}", k); Object.new.extend(M1); k += 1; end } +sums = 400.times.map { loop11.() } +stop = true; definer.join +row "another thread defining elsewhere", sums.uniq +X12 = 1 +module L12 + def self.go = run { i = 0; s = 0; while i < N; s += X12; i += 1; end; s } +end +seen = [] +t = Thread.new { k = 0; until (k += 1) > 20000 || seen.last == 100 * N; seen << L12.go; Thread.pass; end } +sleep 0.01 until seen.size > 50 +L12.const_set(:X12, 100) +t.join +row "nearer defined on another thread (between entries)", [seen.first, seen.last, seen.uniq.size <= 2, seen.drop_while { |v| v == N }.uniq] + +puts "end" From e25f7e0c6e2c290d0c015bc93b3e9b20845e1e4b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:09:58 +0000 Subject: [PATCH 151/439] Ledger: perf/loopconst (round thirty-eight, gap 29) Landed entry with the probe's counts and times, the cost of one revalidation beside an extend on every entry, the matrices and specs; under gap 29 what is still open (a nearer constant appearing while a loop runs, an outlined loop's safe point on a reassignment) and the prepend difference from CRuby found on the way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Util/perf/LEDGER.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 6513c9aad..c2147e086 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1452,6 +1452,14 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has What is left of this gap's running-loop faults: a nearer constant appearing (rminor's case above), and a method body with an effect that only a method redefinition makes stale, which goes on with the old method until it returns (`MethodLoopSafePointSlow`'s impure branch). + Done for outlined loops in round thirty-eight (see Landed, perf/loopconst): an outlined loop's + entry looks its folded constants up again rather than comparing a baked version. Still open: a + running loop (outlined or a method body's) does not see a nearer constant appear (only the + constant version moves, which its safe point does not read; the fix keys on the folded lookups' + paths and is untried); an outlined loop's safe point still hands the loop back on any reassignment + (the code epoch, compared as an immediate), which rebuilds the copy. Found on the way, in every + mode on master: `Q8::X` after `Q8.prepend(Module.new { const_set(:X, 40) })` answers the prepended + module's X; CRuby 4.0 answers Q8's own (`Util/loop-const-matrix.rb` notes it). 30. **`Binding#local_variable_get`, `_set`, `_defined?` and `local_variables` are an `eval` of source text each** (the prelude, `class Binding`): 436 us for a set against 0.1 on CRuby. `ERB#result_with_hash` sets one per key (237 times CRuby), irb sets `_` @@ -1641,6 +1649,42 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/loopconst (round thirty-eight, 2026-11-27) - an outlined loop looks its folded constants up + again at its entry (gap 29)** - not gated. A loop outlined by OSR (`JitLoopCompiler`) that folded a + constant guarded its entry on the runtime's constant version as it was when the copy was compiled, + which every new constant, `extend`, singleton class and `require` moves: the copy handed itself back + (`OsrVersionStale`), the site rebuilt it after `StaleRebuildSpacing` of the generic loop, and so on + for each event. perf/constrev did this for method bodies; now the loop's guard holds what the copy + folded (`JitLoopFacts.FoldedConstants` -> `JitLoopGuard.Folded`, null when a directly called body + folded some it did not record) and the entry calls `JitRuntime.LoopConstantsCurrent`: the version + unchanged since the guard's snapshot, or each folded constant still the same object found in the + same module (`JitLoopGuard.ConstantsStillHold`, the method version unchanged, no autoload in flight; + the version read before the lookups stored after). `IR_LOOP_CONSTANTS=0` turns it off. The safe point + is unchanged: a reassignment moves the code epoch and hands a running copy back. + The probe (`top_loop`/`qual_loop` reading `TOP` and `G::P::RUBY`, and a control without constants, + 400 iterations, 300 calls in each of 20 rounds, one event per round; `-X:NoJIT`, where the loops are + outlined - with the method JIT on they are typed method bodies, which constrev covers, and both + builds specialize 3 loops with 0 stale): base, per event `extend` / `const_set` / `require`: + specialized 17 / 14 / 20, stale rebuilds 14 / 13 / 19, 365 / 352 / 347 ms against 217 with no event; + new: specialized 3, stale 0, 211 / 207 / 225 ms (none 232). A loop entered after an + `Object.new.extend(M)` every time (20,000 entries, two folded constants, best of 7): 40 iterations + base 5,250 ns an entry, switch off 4,713, new 4,873 (the extend is about 4.3 us; one revalidation, + two lookups under the hierarchy lock, about 150 ns at most); 400 iterations base 30,183 (244 rebuilds), + off 26,602 (224), new 4,936 (none 921-1,011). Revalidating costs less than handing back. + `Util/loop-const-matrix.rb` (new, 18 rows, loops written in blocks so they are outlined with the JIT + on as well): events that must not change the answer (a new constant elsewhere, extend, a singleton + class, require, the same value set again, an include into an unrelated class), reassignment, removal + and setting again, removal for good, a nearer constant lexically, in a superclass, by include, a + qualified path replaced, an autoload registered nearer, a loop entered while the autoload of its + constant is in flight, another thread defining elsewhere while loops run, and a nearer constant + defined on another thread between entries. CRuby 4.0's output on both builds with the JIT on, + `-X:NoJIT`, `-X:NoJITCalls`, `IR_LIGHT_FRAMES=0` and `IR_LOOP_CONSTANTS=0`; with the check answering + true always, six rows go wrong. `gate-matrices.rb` on hot-shapes, jit, jit-calls, osr-array, deadconst, jit-const, + loop-const, block-loop and sdef in eight modes (the gate's six, `IR_LOOP_CONSTANTS=0`, `IR_SINGLETON_LOOKUP=0`): + PASS, 63 same, 9 baseline (hot-shapes in every mode, block-loop under R2R, as the baseline). ruby/spec language/constants, core/module const_set, + remove_const, autoload, core/kernel autoload: no failures on either build. The census cannot see + this (no method changes verdict). + - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy (`IR_KWREST_IN_PLACE`, gap 38's first cost)** - instructions only, not gated. A keyword From d7398a6b680eaa8c62d6fe8343a546816671df6f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:10:38 +0000 Subject: [PATCH 152/439] Return a block's `return' after the frame's try (IR_UNWIND_RETURN) The handler that takes the MethodUnwinder of a `return' from a block of the method returned from the method itself, a jump out of a catch through the frame's finally. In a method that has such a jump, the .NET JIT expands no cast inline: every castclass, sealed class or not, is a call of CORINFO_HELP_CHKCASTCLASS (reproduced in a lambda of its own: remove the jump or the finally and the one-compare checks come back). The handler now keeps the value and a flag, and the method returns it after the try, once the finally has run, as before. The casts do come back inline (six Ruby bodies of regex-shapes: 23 -> 102 inline checks), but no gain could be shown on top of IR_SEALED_CONSTANTS, which already loads the constants without a cast, and the callgrind counter cannot see it: under valgrind these bodies are compiled MinOpts. Reverted in the next commit; see Util/perf/LEDGER.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 1cbc41380..b70b73812 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -328,22 +328,48 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin // n compiled methods was thrown n + 1 times. Any other exception now goes through with its // CLR trace growing as it passes, and the frame that finally handles it - a rescue, a block, // an interpreted frame, the top level - captures the same backtrace from there. + // + // The handler does not return from the method itself: it keeps the value and the method returns it after the try, + // once the finally has run, as it would have. A jump out of a catch handler through a finally makes the .NET JIT + // leave every cast of the whole method to the runtime's helper (CORINFO_HELP_CHKCASTCLASS, ~17 instructions, for + // every closure constant a compiled body loads), even to a sealed class (perf/castcheck; IR_UNWIND_RETURN=0 jumps). + MSA.ParameterExpression unwound = null, unwinding = null; + MSA.Expression handlerResult; + if (UnwindReturnAfterTry) { + unwound = Ast.Variable(typeof(object), "#unwound"); + unwinding = Ast.Variable(typeof(bool), "#unwinding"); + } + unwinder = Ast.Parameter(typeof(MethodUnwinder), "#u"); + handlerResult = (unwound != null) + ? (MSA.Expression)Ast.Block( + Ast.Assign(unwound, Methods.GetMethodUnwinderReturnValue.OpCall(unwinder)), + Ast.Assign(unwinding, AstUtils.Constant(true)), + AstUtils.Empty() + ) + : Ast.Return(gen.ReturnLabel, Methods.GetMethodUnwinderReturnValue.OpCall(unwinder)); MSA.Expression body = AstUtils.Try( countCall, recordRefinements, profileStart, optionalsInitialization, statements - ).Filter(unwinder = Ast.Parameter(typeof(MethodUnwinder), "#u"), + ).Filter(unwinder, // a light frame makes a scope for the filter only when a MethodUnwinder passes: Methods.IsMethodUnwinderTargetFrame.OpCall((light != null) ? Ast.Coalesce(scopeVariable, light.MakeScope) : (MSA.Expression)scopeVariable, unwinder), - Ast.Return(gen.ReturnLabel, Methods.GetMethodUnwinderReturnValue.OpCall(unwinder)) + handlerResult ).Finally( // leave frame: (light != null) ? Methods.LeaveLightMethodFrame.OpCall(light.Rfc, scopeVariable) : Methods.LeaveMethodFrame.OpCall(scopeVariable), Ast.Empty(), profileEnd ); + if (unwound != null) { + body = Ast.Block(new[] { unwound, unwinding }, + Ast.Assign(unwinding, AstUtils.Constant(false)), + body, + Ast.IfThen(unwinding, Ast.Return(gen.ReturnLabel, unwound)) + ); + } // TracePoint :return: falling off the end reports the line of `end'; an explicit // `return' reports its own line and jumps past this hook (see ReturnStatement). @@ -455,6 +481,12 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin /// internal static readonly bool LightFramesEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_FRAMES") != "0"; + /// + /// IR_UNWIND_RETURN=0: a method's frame returns the value a `return' from one of its blocks carries from inside its + /// handler, through its finally, as it used to (see TransformBody: that jump disables the JIT's inline casts). + /// + internal static readonly bool UnwindReturnAfterTry = Environment.GetEnvironmentVariable("IR_UNWIND_RETURN") != "0"; + /// /// IR_LIGHT_CALLS=0 keeps every method that makes a call out of light frames (see LightFrameRewriter.LightScopeCall). From 2ad002b82561e88e1e0ce87afa96993e1d58c0f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:10:38 +0000 Subject: [PATCH 153/439] Revert "Return a block's `return' after the frame's try (IR_UNWIND_RETURN)" Rejected by perf/castcheck: the casts it lets the JIT expand are mostly the closure constants IR_SEALED_CONSTANTS already loads without one, and timing shows no difference (ab.rb, ten rounds: frame-cost within its spread). Util/perf/LEDGER.md (Rejected, perf/castcheck) has what was found. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 36 ++----------------- 1 file changed, 2 insertions(+), 34 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index b70b73812..1cbc41380 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -328,48 +328,22 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin // n compiled methods was thrown n + 1 times. Any other exception now goes through with its // CLR trace growing as it passes, and the frame that finally handles it - a rescue, a block, // an interpreted frame, the top level - captures the same backtrace from there. - // - // The handler does not return from the method itself: it keeps the value and the method returns it after the try, - // once the finally has run, as it would have. A jump out of a catch handler through a finally makes the .NET JIT - // leave every cast of the whole method to the runtime's helper (CORINFO_HELP_CHKCASTCLASS, ~17 instructions, for - // every closure constant a compiled body loads), even to a sealed class (perf/castcheck; IR_UNWIND_RETURN=0 jumps). - MSA.ParameterExpression unwound = null, unwinding = null; - MSA.Expression handlerResult; - if (UnwindReturnAfterTry) { - unwound = Ast.Variable(typeof(object), "#unwound"); - unwinding = Ast.Variable(typeof(bool), "#unwinding"); - } - unwinder = Ast.Parameter(typeof(MethodUnwinder), "#u"); - handlerResult = (unwound != null) - ? (MSA.Expression)Ast.Block( - Ast.Assign(unwound, Methods.GetMethodUnwinderReturnValue.OpCall(unwinder)), - Ast.Assign(unwinding, AstUtils.Constant(true)), - AstUtils.Empty() - ) - : Ast.Return(gen.ReturnLabel, Methods.GetMethodUnwinderReturnValue.OpCall(unwinder)); MSA.Expression body = AstUtils.Try( countCall, recordRefinements, profileStart, optionalsInitialization, statements - ).Filter(unwinder, + ).Filter(unwinder = Ast.Parameter(typeof(MethodUnwinder), "#u"), // a light frame makes a scope for the filter only when a MethodUnwinder passes: Methods.IsMethodUnwinderTargetFrame.OpCall((light != null) ? Ast.Coalesce(scopeVariable, light.MakeScope) : (MSA.Expression)scopeVariable, unwinder), - handlerResult + Ast.Return(gen.ReturnLabel, Methods.GetMethodUnwinderReturnValue.OpCall(unwinder)) ).Finally( // leave frame: (light != null) ? Methods.LeaveLightMethodFrame.OpCall(light.Rfc, scopeVariable) : Methods.LeaveMethodFrame.OpCall(scopeVariable), Ast.Empty(), profileEnd ); - if (unwound != null) { - body = Ast.Block(new[] { unwound, unwinding }, - Ast.Assign(unwinding, AstUtils.Constant(false)), - body, - Ast.IfThen(unwinding, Ast.Return(gen.ReturnLabel, unwound)) - ); - } // TracePoint :return: falling off the end reports the line of `end'; an explicit // `return' reports its own line and jumps past this hook (see ReturnStatement). @@ -481,12 +455,6 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin /// internal static readonly bool LightFramesEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_FRAMES") != "0"; - /// - /// IR_UNWIND_RETURN=0: a method's frame returns the value a `return' from one of its blocks carries from inside its - /// handler, through its finally, as it used to (see TransformBody: that jump disables the JIT's inline casts). - /// - internal static readonly bool UnwindReturnAfterTry = Environment.GetEnvironmentVariable("IR_UNWIND_RETURN") != "0"; - /// /// IR_LIGHT_CALLS=0 keeps every method that makes a call out of light frames (see LightFrameRewriter.LightScopeCall). From 062383436cae7cd5b9d002b13a191bf231885f75 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:11:00 +0000 Subject: [PATCH 154/439] perf/castcheck: record what disables the JIT's inline casts, and the counter's limit A jump out of a catch handler through an enclosing finally - every Ruby method frame's handler of a `return' from a block - makes the .NET JIT leave every cast of the method to the runtime's helper. Removing it brings the inline checks back but showed no gain on top of perf/lconst, so the change is reverted. Under valgrind the runtime compiles many methods MinOpts, Ruby bodies among them, so the callgrind counter cannot judge a change to what the JIT emits; the entry says which numbers that leaves standing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/perf/LEDGER.md | 49 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 83a3bbf88..24fe23807 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -5366,6 +5366,55 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/castcheck (/perf-frame, 2026-11-27) - why the JIT expands no cast in Ruby's compiled + bodies, and a fix that was not worth keeping** (switch `IR_UNWIND_RETURN`, reverted; built on + 15285eb with claude/perf-lsite merged, 054d132). perf/lconst found every `castclass` in a Ruby + body to be a call of `CORINFO_HELP_CHKCASTCLASS`, even to a sealed class, while a probe lambda + of the same runtime got the one-compare inline check. + - **What decides it.** Not the tier (`DOTNET_JitDisasmSummary`: `F#f0` and `F#fc3` FullOpts, + IL 460 and 1,106 bytes), the class's assembly (IronRuby.dll's sealed `ConstantSiteCache` is + checked inline from a probe, in its own process and inside `ir`), skip-visibility, a + try/finally, a fault, a catch, a catch with rethrow, a try-catch-finally, nested tries, 32 + casts, a constant cached in a local (three or more uses), or `PrecompiledFrames.Current`. + Found by bisecting Ruby's own trees in the compile hook (a temporary switch that dropped or + emptied parts of each TryExpression, then a dump of the reduced tree): a **jump out of a + catch handler through an enclosing finally**. Every method frame has one: the handler of + a `return` from a block (`MethodUnwinder`) did `return GetMethodUnwinderReturnValue(u)` + through the frame's finally (`LeaveMethodFrame`/`LeaveLightMethodFrame`). Reproduced in a + lambda of its own: `TryFault(Block(casts, Label(TryCatchFinally(Return(label), catch: + Return(label), finally: call))))` - 0 inline checks, every cast a helper call; take away + the catch's `Return` or the finally and all of them are inline again. A second, unrelated + cliff on the way: a lambda with 664 or more variables (663: inline) loses every inline cast + too, which looks like the JIT's "too many locals" bail-out (1,024 locals with its own + temporaries); `DOTNET_JitMaxLocalsToTrack` does not move it in this release runtime. No + Ruby body seen comes near it. + - **Who else.** The rule bodies (`CallSite.Target`) and the method JIT's typed bodies have no + such jump and already check inline: in a regex-shapes run, 32 rules had 100-120 inline checks + (the helper calls beside them are the expansions' slow paths), the typed body 4. Only the + generic bodies of methods suffer. + - **The fix tried.** The handler keeps the value and a flag in two locals and the method + returns after the try, once the finally has run - the same order. A block's `return` (in an + `each`, from inside `ensure`, a `map`) still answers right. The six Ruby bodies of a + regex-shapes run: 23 -> 102 inline checks; `F#fc3` with `IR_SEALED_CONSTANTS=0`: 0 -> 9. + - **Why rejected.** The casts it frees are mostly the closure constants perf/lconst already + loads without a cast (`Unsafe.As`), and nothing showed a gain: `ab.rb -r 10` of frame-cost, + `-X:NoJIT`, both switches off / this one on / both on - `f0` 39.9 / 35.9 / 36.0 ns, `fc3` + 72.0 / 71.9 / 71.6, `bytesplice` 912 / 898 / 826, every small shape within its 10-70% spread. + It costs a store and a test a call, and two locals live into the handler. + - **And the callgrind counter cannot judge such a change.** Under valgrind the runtime compiles + many methods MinOpts that it compiles FullOpts natively, `DOTNET_TieredCompilation=0` + notwithstanding: 4,588 of 8,011 compilations of an `ir` run of frame-cost (natively 0 of + 5,445), among them `Host:Main`, `RubyContext..cctor` and the Ruby body `F#fc3` (4,485 + bytes of code against 2,721) - MinOpts expands no cast, so the counter measured the helper + calls whichever way this switch was. A probe program shows the same (60 of 89 MinOpts, its + expression-tree lambda FullOpts); `DOTNET_JITMinOpts=0`, `DOTNET_JitMinOpts=0` and + `DOTNET_ZapDisable=1` change nothing. So `Util/perf/callgrind/count.sh` counts are a fair + measure of work a change removes (calls, allocations, helper calls) but not of what the JIT + does with optimized code: perf/lframe's and perf/lconst's numbers are of the first kind, + but what they are worth natively is owed to a clock or a machine with a counter. + - Left: the jump is easy to remove if a later change (another helper expansion, a cheaper + `isinst`) can show a gain from it; the commits are d7398a6 (the change) and 2ad002b. + - **perf/lexical3 (/perf-step, 2026-11-26, on 3cabf57) - bind the positionals of `def m(a, *r, k: 1)` in the calling convention instead of out of one splat** (the idea perf/lexical2's entry named), rejected by measurement before any code. The premise was `kr_rest` 5,325 From 26ac46c1fe93d656fd39f066aabc3c207d9da911 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:12:10 +0000 Subject: [PATCH 155/439] Bound fibers abandoned while suspended: collect as they pile up A suspended fiber holds a thread until a collection finds its handle, and the collector knows nothing of that thread: 3,000 abandoned generator enumerators were three collections and 3,017 threads. CRuby's fibers are garbage like any other object. ThreadOps.FiberCore.Run now counts the fibers that hold a thread. A fiber about to start collects when that count has grown by 256 since the lowest it has been since the last collection. The pool of parked fiber threads is as large as the bound (it was 8), so the reclaimed threads serve the next fibers instead of ending; with a pool of 8 the bound cost 15-25% per abandoned enumerator. A collection that reclaims fewer than a quarter of the interval's fibers doubles the interval. So a program whose fibers are alive, or held by a block that runs on them (which no collector sees past), pays a handful of collections, not one per 256 starts; that had doubled its cost. GC.AddMemoryPressure per fiber stack was tried too and bounded half as well. IR_FIBER_BOUND=0 turns it off. With it, the cursor path's end when StopIteration#new or #initialize is the program's. Made in C#, the StopIteration was another object than the one the program rescued, so a later end's cause was not the first, and map's result was lost. The cursor now hands that end to the prelude's __iter_stop__, as the fiber path does. Util/bench/extiter-abandoned.rb, 10,000 each: a lazy made in a method 1,229 us, 1,066 threads at the peak, 359 MB -> 689 us, 281, 174 MB; a generator 1,282 us, 513, 335 MB -> 700 us, 280, 165 MB. The ones a block holds are unchanged (10,017 threads, the same time). Fibers that finish, Ruby threads and cursor shapes are level. Util/extiter-matrix.rb (332 probes) prints CRuby's output with the bound and without; fiber-reclaim-matrix passes in every mode; enum-next and raise matrices agree with the baseline; spec/core/fiber, enumerator, thread and kernel/loop pass in every mode; the Fiber, Thread, Enumerator, Exception and Raise IronRuby.Tests pass five times on each build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Src/Libraries/Builtins/Enumerator.cs | 10 ++- Src/Libraries/Builtins/ThreadOps.Fiber.cs | 84 ++++++++++++++++++++++- Src/StdLib/ironruby/ruby4.rb | 5 +- Util/extiter-matrix.rb | 11 +++ Util/perf/LEDGER.md | 39 ++++++++++- 5 files changed, 145 insertions(+), 4 deletions(-) diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index 80d2e49ab..ff106c100 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -260,7 +260,7 @@ public static object GetSizeInfo(RubyContext/*!*/ context, Enumerator/*!*/ self) private bool _hasFeed; // __iter_slow__'s operations. - private const int SlowAdvance = 0, SlowPeek = 1, SlowAcrossThreads = 2, SlowResumeCurrent = 3; + private const int SlowAdvance = 0, SlowPeek = 1, SlowAcrossThreads = 2, SlowResumeCurrent = 3, SlowRaiseEnd = 4; /// /// Where the iteration of a built-in method has got to. A cursor belongs to the Ruby thread @@ -1336,6 +1336,14 @@ private static object CursorStep(CallSiteStorage :immediate) // around the fiber's block. Its own handle_interrupt(Object => :never) is not up // yet at the safe point of the call to __run__: one raised there, before the @@ -418,6 +419,7 @@ public void Run(object state) { Terminate(); IronRuby.StandardLibrary.Threading.RubyMutex.ReleaseLocksOf(Thread.CurrentThread); } finally { + LeaveFiberRun(RubyUtils.IsReclaimingFiber); RubyUtils.PopInterruptMask(); info.InFiberRun = false; RubyUtils.EndFiberReclamation(); @@ -539,6 +541,84 @@ public static object GetCurrentFiberState(RubyContext context, object self) { [ThreadStatic] private static RubyContext _currentFiberContext; + #region the bound on fibers that hold a thread + + // A fiber holds a thread - its stack, a megabyte or more of address space and the pages it has touched - from its start + // until it finishes or its handle is collected (FiberRegistration). The collector knows nothing of that: an abandoned + // suspended fiber is a few small objects to it, and a program that abandons fiber-backed enumerators (`e.next` and + // never the end) piled up a thread for each until a collection happened to run - 3,017 threads after 3,000 of them, + // three collections in all, where MRI's fibers are garbage like any other object. + // + // So the number of fibers that hold a thread is counted (FiberCore.Run, from start to finish or reclamation), and when + // it has grown by _fiberBound since the lowest it has been since the last collection, a fiber about to start collects + // first: the handles of the abandoned ones are found, and their threads unwind (RequestReclaim) and park, the pool + // being as large as the bound, for the fibers that start next - a reclaimed thread that ended instead made the next + // start make a new one, and bounding cost 15-25% per abandoned enumerator; parked, it costs nothing. The baseline makes + // the bound relative: a program that keeps many fibers alive on purpose collects once for every _fiberBound more of + // them, and one whose fibers finish never does. The count is the process's, as threads are. GC.AddMemoryPressure for + // each fiber's stack was tried instead: fewer collections, and twice the threads at the peak. + // A collection that finds nothing to reclaim - the fibers are alive, or held by a block on their own thread that closes + // over them, which no collector can see past - doubles the interval to the next, so a program that keeps that many + // fibers pays a handful of collections and not one per _fiberBound: each one stops every thread. One that reclaims + // brings the interval back. IR_FIBER_BOUND=0 turns the bound off (and the pool back to 8). + private static int _fibersRunning; + private static int _fibersRunningBaseline; + private static readonly int _fiberBound = ReadFiberBound(); + private static readonly object _fiberBoundLock = new object(); + private static int _fiberBoundInterval = _fiberBound; + // fibers that ended by being reclaimed, in all, and at the last collection + private static int _fibersReclaimed; + private static int _fibersReclaimedAtCollection; + + private static int ReadFiberBound() { + int value; + return Int32.TryParse(Environment.GetEnvironmentVariable("IR_FIBER_BOUND"), out value) && value >= 0 ? value : 256; + } + + private static void EnterFiberRun() { + Interlocked.Increment(ref _fibersRunning); + } + + private static void LeaveFiberRun(bool reclaimed) { + Interlocked.Decrement(ref _fibersRunning); + if (reclaimed) { + Interlocked.Increment(ref _fibersReclaimed); + } + } + + private static void BoundSuspendedFibers() { + if (_fiberBound == 0) { + return; + } + int running = Volatile.Read(ref _fibersRunning); + int baseline = Volatile.Read(ref _fibersRunningBaseline); + if (running < baseline) { + // fibers have finished or been reclaimed since: the bound counts from here + Interlocked.CompareExchange(ref _fibersRunningBaseline, running, baseline); + return; + } + if (running - baseline < Volatile.Read(ref _fiberBoundInterval)) { + return; + } + lock (_fiberBoundLock) { + baseline = _fibersRunningBaseline; + if (running - baseline < _fiberBoundInterval) { + return; + } + // what the last collection reclaimed, counted as the threads unwound (asynchronously: the finalizers, then each + // thread), an interval of fiber starts later; a quarter of the interval says it found abandoned fibers + int reclaimed = Volatile.Read(ref _fibersReclaimed); + bool effective = reclaimed - _fibersReclaimedAtCollection >= _fiberBoundInterval / 4; + _fiberBoundInterval = effective ? _fiberBound : Math.Min(_fiberBoundInterval * 2, 1 << 20); + _fibersReclaimedAtCollection = reclaimed; + Volatile.Write(ref _fibersRunningBaseline, running); + } + // the reclaimed threads unwind on their own, and park for the fibers that start next + GC.Collect(); + } + + #endregion + #region the pool of fiber threads // Starting a CLR thread waits until the OS has scheduled it, which is most of what creating @@ -557,7 +637,8 @@ internal FiberWorker(Thread/*!*/ thread) { } private static readonly List/*!*/ _idleFiberWorkers = new List(); - private const int MaxIdleFiberWorkers = 8; + // as many as the bound on fibers that hold a thread lets pile up, so that the threads it reclaims are used again + private static readonly int MaxIdleFiberWorkers = Math.Max(8, _fiberBound); private const int FiberWorkerIdleMilliseconds = 2000; [ThreadStatic] @@ -569,6 +650,7 @@ internal FiberWorker(Thread/*!*/ thread) { /// [RubyMethod("__fiber_reuse__", RubyMethodAttributes.PublicSingleton)] public static Thread ReuseFiberThread(RubyContext/*!*/ context, object self, object fiber) { + BoundSuspendedFibers(); FiberWorker worker; while (true) { using (new RubyUtils.UninterruptedLock(_idleFiberWorkers)) { diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index c8e8e5353..ae4e1979b 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -5907,11 +5907,14 @@ def __iter_advance__ # The fiber's half of #next (op 0: the values of the next step, taken), #peek # (op 1: the same values, left for the next #next; the caller copies them) - and - # the FiberErrors of a cursor another thread started (op 2) and of one in use (op 3). + # the FiberErrors of a cursor another thread started (op 2) and of one in use (op 3), and the + # end of a cursor's iteration raised as the fiber's is (op 4). def __iter_slow__(op) ::Kernel.raise(::FiberError, "fiber called across threads") if op == 2 # a cursor's #flat_map converting the block's answer, which calls back into this enumerator (op 3) ::Kernel.raise(::FiberError, "attempt to resume the current fiber") if op == 3 + # the end of a cursor's iteration, when StopIteration is made with the program's #new or #initialize (op 4) + __iter_stop__ if op == 4 __iter_advance__ values = @__peek__ if op == 0 diff --git a/Util/extiter-matrix.rb b/Util/extiter-matrix.rb index 2ec922f48..ceada98fc 100644 --- a/Util/extiter-matrix.rb +++ b/Util/extiter-matrix.rb @@ -715,3 +715,14 @@ def fs_bt_direct end probe("fs_after_restore") { e = gen1; e.next; s1 = (e.next rescue $!); s2 = (e.next rescue $!); s2.cause.equal?(s1) } probe("cur_tracepoint") { seen = []; tp = TracePoint.new(:raise) { |t| seen << [t.raised_exception.class, t.lineno == __LINE__] }; e = [].each; tp.enable { (e.next rescue nil); (e.next rescue nil) }; seen } +probe("cur_init_redefined") do + calls = [] + StopIteration.class_eval { alias_method :__ci_init__, :initialize; define_method(:initialize) { |*a| calls << a; __ci_init__(*a) } } + e = [1, 2].each; e.next; e.next + s1 = (e.next rescue $!); s2 = (e.next rescue $!) + m = [3].map; m.next; m.feed :f + s3 = (m.next rescue $!) + StopIteration.class_eval { remove_method :initialize; alias_method :initialize, :__ci_init__; remove_method :__ci_init__ } + [calls.size, s2.cause.equal?(s1), s1.result.equal?(e.size && s1.result), s3.result] +end +probe("cur_after_restore") { e = [1].each; e.next; s1 = (e.next rescue $!); s2 = (e.next rescue $!); s2.cause.equal?(s1) } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 0a8cbbd67..3f87073a1 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1579,7 +1579,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has reclaimed as an Enumerator's generator is, but a block that runs on the fiber and closes over a scope holding the enumerator (`e = xs.lazy.map { |x| ... }; e.next`, the same with `Enumerator.new { |y| ... }`) keeps it for the life of the process: 10,000 of them are 10,018 - threads and 640 MB after GC (CRuby: 2 threads, 17 MB; `Util/bench/extiter-abandoned.rb`). Only + threads and 640 MB after GC (CRuby: 2 threads, 17 MB; `Util/bench/extiter-abandoned.rb`). The + reclaimable ones no longer wait for a collection to happen by: perf/fiberbound collects when + the fibers holding a thread have grown by 256 (peak 280 threads, about 170 MB). Only a fiber that is not a thread gets past that. Untried: switching fibers without a thread (a continuation of the method JIT's own); a smaller stack for fiber threads (the memory, not the thread). @@ -1634,6 +1636,41 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/fiberbound (2026-11-27) - fibers abandoned while suspended are bounded: a collection when + the fibers holding a thread have grown by 256, the reclaimed threads parked for the next ones + (gap 35)** - not gated. Base 78bbfb1 (the round-38 branch at 15285eb with perf/fiberstart). A + suspended fiber holds a thread until a collection finds its handle, and the collector knows + nothing of the thread: 3,000 abandoned generators were three collections and 3,017 threads. Now + `ThreadOps.FiberCore.Run` counts the fibers that hold a thread, and a fiber about to start + (`__fiber_reuse__`) collects when the count has grown by 256 since the lowest it has been since + the last collection; the pool of parked fiber threads is as large as the bound (8 before), so + the threads the collection reclaims are the next fibers' instead of ending (a pool of 8 made the + bound cost 15-25% per abandoned enumerator: 862-927 against 748 us). A collection that reclaims + fewer than a quarter of the interval's fibers (counted as they unwind, an interval of starts + later) doubles the interval: a program whose fibers are alive, or held by a block on their own + thread that closes over them (`e = xs.lazy.map { |x| ... }; e.next`), which no collector sees + past, paid twice per enumerator when every 256 starts collected over 10,000 threads (1,073 -> + 1,918 us); a first try that judged by the lowest count since the collection doubled the interval + while the reclaimed threads were still unwinding and let 2,787 pile up. GC.AddMemoryPressure for + each fiber's stack, tried instead: 18-21 collections in 3,000, 608-742 threads at the peak. + `IR_FIBER_BOUND=0` turns it off (and the pool back to 8); bounds of 64-1024 measured, 256 kept. + `extiter-abandoned.rb`, 10,000 each, base -> new: a lazy made in a method 1,229 us, peak 1,066 + threads, 359 MB -> 689 us, 281, 174 MB; a generator 1,282 us, 513, 335 MB -> 700 us, 280, 165 MB; + the ones a block holds 1,073-1,126 us, 10,018 threads -> 1,119-1,145 us, 10,017 (unchanged: not + reachable while a fiber is a thread). `fiber-start.rb`: fibers that finish and threads level + (`fiber_complete` 13 / 18 us, `gen_drain` 136 / 142, `thread_join` 199 / 196), abandoned ones + 281-294 threads after 3,000 against 2,823-3,017. Cursor shapes level (`ab.rb -r 6`, 0.96-1.07, all + overlapping). With it, the cursor path's StopIteration when StopIteration#new or #initialize is the + program's: made in C# it was another object than the one rescued, so a later end's cause was not + the first, and `map`'s result was lost; now the cursor hands the end to the prelude's + __iter_stop__ as the fiber path does (`__iter_slow__` op 4). `Util/extiter-matrix.rb` (332 probes) + prints CRuby's output with the bound and without; base differs in that probe only, off + (IR_FAST_NEXT=0) in `flm_to_ary_next` only. fiber-reclaim-matrix passes in every mode; + enum-next- and raise-matrix the same on base, new, off and without the bound. spec/core/fiber, + enumerator, thread and kernel/loop_spec: 1,026 examples, 0 failures on base, new and without + the bound; the Enumerator*, Lazy*, Loop*, Fiber*, Thread*, Exception* and Raise* IronRuby.Tests + (60) pass in five plain runs on base and five on new. + - **perf/fiberstart (2026-11-27) - what a fiber's start costs, found; the end of an iteration on a fiber raised from C# and its stack walk deferred, as a cursor's is (gap 35)** - not gated. Base 8d7efda (the round-38 branch with perf/extiter5). Measured first (`Util/bench/fiber-start.rb`, From d6d2a10181d90cea618418eef1a0f2e9dd01b83a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:17:18 +0000 Subject: [PATCH 156/439] Regexp: an ISO-8859-1 subject matches with Onigmo's ISO-8859-1 ctype table CRuby compiles a regexp that is not fixed-encoding against the subject's encoding (rb_reg_prepare_enc), so an ISO-8859-1 subject sees Onigmo's ISO-8859-1 ctype table: the superscripts and vulgar fractions are word characters, U+00A7 and U+00B6 are not punctuation while the soft hyphen is, U+0085 is neither a space nor a \R line break, (?a)[[:alpha:]] keeps the Latin-1 letters, and /i pairs no case onto U+00DF, U+00FF or U+00B5. IronRuby matched the decoded chars with Unicode's tables instead. The translator gets a Latin1Ctype mode beside the ASCII one used for binary subjects, and RubyRegex caches a third translation, used only for an ISO-8859-1 subject that is not ASCII-only. The ISO-8859-1 column of Util/regexp-binary-ctype-matrix.rb now agrees with CRuby 4.0 (25 rows differed, 9 do, all in the UTF-8 column); spec/core/regexp, language/regexp, core/matchdata and String#scan/gsub/match/index/split/sub are unchanged, and Regex_Latin1Ctype1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 32 ++++++++++ Src/Ruby/Builtins/RegexpTransformer.cs | 77 ++++++++++++++++++++++-- Src/Ruby/Builtins/RubyRegex.cs | 36 +++++++++++ Util/regexp-binary-ctype-matrix.rb | 11 ++-- 5 files changed, 145 insertions(+), 12 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 4b50100bc..aeb8b542d 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -212,6 +212,7 @@ public Tests(Driver/*!*/ driver) { Regex_LiteralEncodings1, Regex_PropertyEncoding1, Regex_BinaryCtype1, + Regex_Latin1Ctype1, Regex_InspectResultEncoding1, Regex_EscapedByteEncoding1, Regex_EscapedByteEncoding2, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 328a22ee8..4dc5c078f 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -902,6 +902,38 @@ def t(l) /// sees U+0080-U+00FF. ISO-8859-1 and UTF-8 subjects keep their own letters, and a BINARY /// regexp's \p{Punct} is [[:punct:]] even on ASCII text. /// + /// + /// Against an ISO-8859-1 subject Onigmo uses its ISO-8859-1 ctype table, not Unicode's: + /// the superscripts and vulgar fractions are word characters, U+00A7 and U+00B6 are not + /// punctuation but the soft hyphen is, U+0085 is neither a space nor a line break, and + /// /i folds no case pair onto U+00DF, U+00FF or U+00B5. + /// + public void Regex_Latin1Ctype1() { + TestOutput(@" +def l(s) = s.dup.force_encoding(""ISO-8859-1"") +s = l(""\xAA\xA7\xB2\xA0\xD7\xB6\xAD\xBC"") +p s.scan(/[[:word:]]/).map(&:ord) +p s.scan(/(?u)\w/).map(&:ord) +p s.scan(/[[:punct:]]/).map(&:ord) +p s.scan(/[[:space:]]|\s/).map(&:ord) +p s.scan(/(?a)[[:alpha:]]/).map(&:ord) +p s.scan(/\b./).map(&:ord) +p l(""a\x85"").scan(/\R/).size +p l(""\xDF\xFF\xB5\xC0"").scan(/[[:upper:]]/i).map(&:ord) +p l(""abc"").scan(/\w/).size +", @" +[170, 178, 188] +[170, 178, 188] +[173] +[160] +[170] +[170, 167, 178, 160, 188] +0 +[192] +3 +"); + } + public void Regex_BinaryCtype1() { TestOutput(@" require 'ruby4' diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index f379491cb..d59da1aeb 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -115,6 +115,8 @@ private sealed class SharedState { public bool AstralSafe; // see Transform(..., asciiCtype) public bool AsciiCtype; + // see Transform(..., latin1Ctype) + public bool Latin1Ctype; // Whether /i or an inline (?i) may be in effect anywhere in the pattern (AsciiCtype only). public bool MayIgnoreCase; // Whether AsciiCtype made the translation differ from the plain one. @@ -246,6 +248,19 @@ internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions optio /// internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions options, out bool hasGAnchor, bool astralSafe, bool asciiCtype, out bool asciiCtypeApplied) { + return Transform(rubyPattern, options, out hasGAnchor, astralSafe, asciiCtype, false, out asciiCtypeApplied); + } + + /// + /// With the translation is for an ISO-8859-1 subject with bytes above 0x7F, which MRI + /// matches with Onigmo's ISO-8859-1 ctype table (enc/iso_8859_1.c) rather than Unicode's: [[:punct:]] is + /// U+00A1 U+00AB U+00AD U+00B7 U+00BB U+00BF there (not U+00A7 U+00B6), space is U+00A0 but not U+0085 (\s and + /// [[:space:]] alike, \R neither), word characters include the superscripts and vulgar fractions (\w, [[:word:]], + /// \b, \B), (?a) does not narrow a POSIX bracket, and case folds only within the Latin-1 letters. + /// then says whether any of that changed the translation. + /// + internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions options, out bool hasGAnchor, bool astralSafe, + bool asciiCtype, bool latin1Ctype, out bool asciiCtypeApplied) { // TODO: surrogates (REXML uses this pattern) if (rubyPattern == "^[\t\n\r -\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF]*$") { hasGAnchor = false; @@ -257,6 +272,7 @@ internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions optio transformer._clrOptions = RubyRegex.ToClrOptions(options); transformer._state.AstralSafe = astralSafe; transformer._state.AsciiCtype = asciiCtype; + transformer._state.Latin1Ctype = latin1Ctype; var result = transformer.Transform(); hasGAnchor = transformer._hasGAnchor; asciiCtypeApplied = transformer._state.AsciiCtypeApplied; @@ -694,9 +710,11 @@ private static bool HasInlineIgnoreCase(string/*!*/ pattern) { for (int depth = DefaultMaxCallDepth; ; depth /= 2) { bool astralSafe = _state.AstralSafe; bool asciiCtype = _state.AsciiCtype; + bool latin1Ctype = _state.Latin1Ctype; _state = new SharedState(); _state.AstralSafe = astralSafe; _state.AsciiCtype = asciiCtype; + _state.Latin1Ctype = latin1Ctype; _state.MayIgnoreCase = asciiCtype && ((_clrOptions & RegexOptions.IgnoreCase) != 0 || HasInlineIgnoreCase(_rubyPattern)); _state.MaxCallDepth = depth; @@ -1627,12 +1645,14 @@ private void ParseEscape(int escape) { switch (escape) { case 'b': // word boundary case 'B': // not a word boundary - if (_state.AsciiCtype) { - // a BINARY subject's word characters are ASCII ones + if (_state.AsciiCtype || _state.Latin1Ctype) { + // a BINARY subject's word characters are ASCII ones; an ISO-8859-1 subject's are its letters, the + // superscripts and the vulgar fractions too _state.AsciiCtypeApplied = true; + string w = _state.AsciiCtype ? "[0-9A-Za-z_]" : Latin1WordClass; _sb.Append(escape == 'b' - ? "(?:(?<=[0-9A-Za-z_])(?![0-9A-Za-z_])|(?\\r\\n|[\\n\\v\\f\\r])" : "(?>\\r\\n|[\\n\\v\\f\\r\\u0085\\u2028\\u2029])"); + // Nor in an ISO-8859-1 one. + _state.AsciiCtypeApplied |= _state.AsciiCtype || _state.Latin1Ctype; + _sb.Append(_state.AsciiCtype || _state.Latin1Ctype ? "(?>\\r\\n|[\\n\\v\\f\\r])" : "(?>\\r\\n|[\\n\\v\\f\\r\\u0085\\u2028\\u2029])"); break; case 'K': @@ -2311,6 +2332,9 @@ private void AppendCharacterSet(CharacterSet/*!*/ set, bool parenthesize) { private static readonly int[] _latin1WordQuirk = new int[] { 0xb2, 0xb3, 0xb9, 0xb9, 0xbc, 0xbe }; private static readonly int[] _asciiHexDigit = new int[] { '0', '9', 'A', 'F', 'a', 'f' }; private static readonly int[] _asciiSpace = new int[] { 0x09, 0x0d, 0x20, 0x20 }; + private static readonly int[] _latin1Space = new int[] { 0x09, 0x0d, 0x20, 0x20, 0xa0, 0xa0 }; + // Onigmo's ISO-8859-1 word characters (Transform(..., latin1Ctype)) + private const string Latin1WordClass = @"[0-9A-Za-z_\xaa\xb2\xb3\xb5\xb9\xba\xbc-\xbe\xc0-\xd6\xd8-\xf6\xf8-\xff]"; private static readonly int[] _asciiDigit = new int[] { '0', '9' }; private static readonly int[] _asciiWord = new int[] { '0', '9', 'A', 'Z', '_', '_', 'a', 'z' }; @@ -2319,6 +2343,19 @@ private void AppendCharacterSet(CharacterSet/*!*/ set, bool parenthesize) { /// Space, Digit and Word properties. /// private CharacterSet/*!*/ MakeAsciiAware(string/*!*/ property, int[]/*!*/ ascii, string/*!*/ asciiText, bool positive) { + if (_state.Latin1Ctype) { + // ISO-8859-1's table: \s and (?u)\s take in U+00A0 (not U+0085), and (?u)\w the superscripts and fractions + if (property == "space") { + _state.AsciiCtypeApplied = true; + var space = CharacterSet.MakeSet(_latin1Space, null); + return positive ? space : space.Complement(); + } + if (property == "word" && _characterClassMode == CharacterClassMode.Unicode) { + _state.AsciiCtypeApplied = true; + var word = CharacterSet.MakeProperty(UnicodeProperties.Find(property), true).Union(CharacterSet.MakeSet(_latin1WordQuirk, null)); + return positive ? word : word.Complement(); + } + } if (_characterClassMode == CharacterClassMode.Unicode) { if (!_state.AsciiCtype) { return CharacterSet.MakeProperty(UnicodeProperties.Find(property), positive); @@ -3162,6 +3199,9 @@ private CharacterSet ParsePosixCharacterClass() { if (table < 0) { throw MakeError("invalid POSIX bracket type"); } + if (_state.Latin1Ctype) { + return MakeLatin1PosixCharacterClass(table, name, positive); + } return MakePosixCharacterClass(table, positive); } @@ -3182,6 +3222,31 @@ private CharacterSet ParsePosixCharacterClass() { return positive ? result : result.Complement(); } + /// + /// [[:name:]] for an ISO-8859-1 subject (Transform(..., latin1Ctype)): Onigmo's ISO-8859-1 class, whatever (?a) says - + /// Unicode's below U+0100 (nothing above: the subject has nothing there, and a member above, as U+0178 or U+1E9E, would + /// fold a Latin-1 letter under /i that Onigmo's table does not fold), but for the punctuation, the space and the word + /// characters, which differ. + /// + private CharacterSet/*!*/ MakeLatin1PosixCharacterClass(int table, string/*!*/ name, bool positive) { + _state.AsciiCtypeApplied = true; + var result = CharacterSet.MakeProperty(table, true).Intersect(CharacterSet.MakeSet(_latin1Range, null)); + switch (name) { + case "punct": + result = result.Subtract(CharacterSet.MakeSet(new[] { 0xa7, 0xa7, 0xb6, 0xb6 }, null)).Union(CharacterSet.MakeSet(new[] { 0xad, 0xad }, null)); + break; + case "space": + result = result.Subtract(CharacterSet.MakeSet(new[] { 0x85, 0x85 }, null)); + break; + case "word": + result = result.Union(CharacterSet.MakeSet(_latin1WordQuirk, null)); + break; + } + return positive ? result : result.Complement(); + } + + private static readonly int[] _latin1Range = new int[] { 0, 0xff }; + /// The ASCII members of , or every character but those. private static CharacterSet/*!*/ RestrictToAscii(CharacterSet/*!*/ set, bool positive) { var result = set.Intersect(CharacterSet.MakeSet(_asciiRange, null)); diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index b7c3ac165..0fa8c26ed 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -61,6 +61,11 @@ public partial class RubyRegex : IEquatable, IDuplicable, IRubyObject // matching with _cachedRegex, which is compiled once it has been used enough. private bool _binaryIsPlain; + // The same for an ISO-8859-1 subject with bytes above 0x7F, which Onigmo matches with its ISO-8859-1 ctype table + // (RegexpTransformer.Transform(..., latin1Ctype)). + private Tuple _cachedLatin1; + private bool _latin1IsPlain; + // The same CLR regex forced to start where the search starts, for the scanning operations // that only ever look at the current position (StringScanner#scan, #skip, #check, #match?). // Cached against the regex it was derived from, so it follows _cachedRegex's own lifetime. @@ -443,6 +448,9 @@ private bool IsRecompiledCached(RubyEncoding/*!*/ encoding) { if (target.UsesAsciiCtype(input)) { return target.TransformBinaryPattern(countUse); } + if (input.Encoding.CodePage == 28591 && !input.IsAscii()) { + return target.TransformLatin1Pattern(countUse); + } return target.TransformPattern(countUse); } @@ -495,6 +503,34 @@ private bool UsesAsciiCtype(MutableString/*!*/ input) { return result; } + private Regex/*!*/ TransformLatin1Pattern(bool countUse) { + TimeSpan timeout = EffectiveTimeout; + if (_latin1IsPlain) { + return TransformPattern(countUse); + } + var cached = _cachedLatin1; + if (cached != null && timeout == cached.Item1) { + return cached.Item2; + } + + Regex plain = TransformPattern(false); + Regex result; + try { + bool hasGAnchor, applied; + string translated = RegexpTransformer.Transform(GetClrPatternSource(), _options, out hasGAnchor, false, false, true, out applied); + if (!applied) { + _latin1IsPlain = true; + return plain; + } + result = new Regex(translated, plain.Options, timeout); + } catch (Exception) { + result = plain; + } + + _cachedLatin1 = Tuple.Create(timeout, result); + return result; + } + private Regex/*!*/ TransformAstralPattern() { TimeSpan timeout = EffectiveTimeout; if (_cachedAstralRegex != null && timeout == _cachedAstralTimeout) { diff --git a/Util/regexp-binary-ctype-matrix.rb b/Util/regexp-binary-ctype-matrix.rb index e0bd33e61..1ace7ff1d 100644 --- a/Util/regexp-binary-ctype-matrix.rb +++ b/Util/regexp-binary-ctype-matrix.rb @@ -16,12 +16,11 @@ # A row lists, for each subject encoding, which of the characters 0x80-0xFF (and 0x00-0x7F, # as a check that ASCII is unchanged) the pattern matches, as hex ranges. # -# The BINARY and US-ASCII columns and the entry points agree with CRuby 4.0. Rows that still -# differ, all in the other columns and all older than this matrix: ISO-8859-1 subjects are -# matched with Unicode's tables rather than Onigmo's ISO-8859-1 ctype table ([[:punct:]], -# [[:space:]], \s, (?u)\s, \R and 0x85, [[:word:]] and \b with the superscripts and fractions, -# (?a)[[:alpha:]], [[:upper:]]/i), UTF-8's \b and \B do not count U+00B2 U+00B3 U+00B9 -# U+00BC-U+00BE as word characters, and UTF-8's [[:upper:]]/i misses U+00B5. +# The BINARY, US-ASCII and ISO-8859-1 columns and the entry points agree with CRuby 4.0 +# (an ISO-8859-1 subject that is not ASCII-only is matched with Onigmo's ISO-8859-1 ctype +# table). Rows that still differ, all in the UTF-8 column and older than this matrix: UTF-8's +# \b and \B do not count U+00B2 U+00B3 U+00B9 U+00BC-U+00BE as word characters, and UTF-8's +# [[:upper:]]/i misses U+00B5. require "strscan" From 3ea2ea5d2d83ee92e080bc0921aa4c7d7ab850aa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:17:51 +0000 Subject: [PATCH 157/439] Ledger: delegation patterns against CRuby, measured and not built SimpleDelegator, DelegateClass, Forwardable and a method_missing with public_send cost, per layer, what IronRuby's calls cost against CRuby's (1.1-1.9, a direct call 1.5). What a forwarding layer pays over a fixed call, by instructions: the rest Array 1,170, a nil block parameter or argument about 600. The unused-block rule (no precompiled dispatcher for a block passed to a method that uses none) is not where that goes: a probe without it counted the same. Shapes: Util/bench/delegate-shapes.rb, Util/bench/forward-shapes.rb. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/bench/delegate-shapes.rb | 54 +++++++++++++++++++++++++++++++++++ Util/bench/forward-shapes.rb | 42 +++++++++++++++++++++++++++ Util/perf/LEDGER.md | 25 ++++++++++++++++ 3 files changed, 121 insertions(+) create mode 100644 Util/bench/delegate-shapes.rb create mode 100644 Util/bench/forward-shapes.rb diff --git a/Util/bench/delegate-shapes.rb b/Util/bench/delegate-shapes.rb new file mode 100644 index 000000000..b2b687af3 --- /dev/null +++ b/Util/bench/delegate-shapes.rb @@ -0,0 +1,54 @@ +# A call through each of Ruby's delegation patterns to a trivial method: SimpleDelegator (method_missing), a +# DelegateClass (generated `def m(...); __getobj__.m(...); end`), Forwardable's def_delegators, and a plain +# method_missing with public_send; with zero and two arguments and with a block. direct is the control. +# +# ruby Util/perf/ab.rb -r 6 Util/bench/delegate-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# ruby Util/perf/ab.rb -i -r 1 -n 20000 Util/bench/delegate-shapes.rb \ +# "base=env IR_CONFIG=Release Util/perf/callgrind/count.sh ../ironruby" "new=env IR_CONFIG=Release Util/perf/callgrind/count.sh ." +# +# Every line prints the sum of its results next to its time; it must be CRuby's. +$stdout.sync = true +require 'delegate' +require 'forwardable' + +class DgTarget + def zero = 1 + def two(a, b) = a + def blk = yield +end +class DgMM + def initialize(t) = @target = t + def method_missing(name, *args, &block) = @target.public_send(name, *args, &block) + def respond_to_missing?(name, priv = false) = @target.respond_to?(name, priv) || super +end +class DgFw + extend Forwardable + def_delegators :@target, :zero, :two, :blk + def initialize(t) = @target = t +end +DgDC = DelegateClass(DgTarget) + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +T = DgTarget.new +D = { "direct" => T, "sd" => SimpleDelegator.new(T), "dc" => DgDC.new(T), "fw" => DgFw.new(T), "mm" => DgMM.new(T) } +N = (ENV["N"] || 200_000).to_i +D.each do |k, o| + t("#{k}_zero", N) { |n| i = 0; r = 0; while i < n; r += o.zero; i += 1; end; r } + t("#{k}_two", N) { |n| i = 0; r = 0; while i < n; r += o.two(1, 2); i += 1; end; r } + t("#{k}_blk", N) { |n| i = 0; r = 0; while i < n; r += o.blk { 1 }; i += 1; end; r } +end diff --git a/Util/bench/forward-shapes.rb b/Util/bench/forward-shapes.rb new file mode 100644 index 000000000..e8b0945a6 --- /dev/null +++ b/Util/bench/forward-shapes.rb @@ -0,0 +1,42 @@ +# What a forwarding wrapper pays on top of a fixed-argument call, part by part: a `&k` parameter left unused, a block +# argument passed on (`&k`, `&nil`), a rest parameter splatted on, `...`, and `(*, &)`; the callee `two(a, b)` uses no block. +# ruby Util/perf/ab.rb -i -r 1 -n 20000 Util/bench/forward-shapes.rb "base=env IR_CONFIG=Release Util/perf/callgrind/count.sh ." +# Every line prints the sum of its results next to its time; it must be CRuby's. +$stdout.sync = true +class FT; def two(a, b) = a; end +class FW + def initialize(t) = @t = t + def fixed(a, b) = @t.two(a, b) + def fixed_blk(a, b, &k) = @t.two(a, b, &k) + def rest(*a) = @t.two(*a) + def rest_blk(*a, &k) = @t.two(*a, &k) + def dots(...) = @t.two(...) + def anon(*, &) = @t.two(*, &) + def param_only(a, b, &k) = @t.two(a, b) + def pass_nil(a, b) = @t.two(a, b, &nil) +end +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the +# seven sections as the time is. See Util/perf/instructions.rb. +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end +o = FW.new(FT.new) +N = (ENV["N"] || 200_000).to_i +t("fixed", N) { |n| i = 0; r = 0; while i < n; r += o.fixed(1, 2); i += 1; end; r } +t("fixed_blk", N) { |n| i = 0; r = 0; while i < n; r += o.fixed_blk(1, 2); i += 1; end; r } +t("rest", N) { |n| i = 0; r = 0; while i < n; r += o.rest(1, 2); i += 1; end; r } +t("rest_blk", N) { |n| i = 0; r = 0; while i < n; r += o.rest_blk(1, 2); i += 1; end; r } +t("dots", N) { |n| i = 0; r = 0; while i < n; r += o.dots(1, 2); i += 1; end; r } +t("param_only", N) { |n| i = 0; r = 0; while i < n; r += o.param_only(1, 2); i += 1; end; r } +t("pass_nil", N) { |n| i = 0; r = 0; while i < n; r += o.pass_nil(1, 2); i += 1; end; r } +t("anon", N) { |n| i = 0; r = 0; while i < n; r += o.anon(1, 2); i += 1; end; r } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index b9d45558e..addda911d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -5470,6 +5470,31 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/delegate (2026-11-27) - Ruby's delegation patterns against CRuby: measured, nothing built - a + delegation layer costs what its calls cost.** A call through each to a trivial method, ns, IronRuby + / CRuby (`Util/bench/delegate-shapes.rb`, new; CRuby by process CPU, since its thread clock here + reads in 40 ns steps): direct 37 / 25, 38 / 30, 79 / 42 (zero arguments, two, a block); + SimpleDelegator 411 / 379, 440 / 398, 477 / 396 (1.1-1.2); DelegateClass 120 / 73, 120 / 77, + 190 / 84 (1.6, 1.6, 2.3); Forwardable 108 / 75, 150 / 78, 160 / 90 (1.4, 1.9, 1.8); a + method_missing with public_send 158 / 185, 240 / 203, 267 / 206 (0.9-1.3). By instructions a + DelegateClass or Forwardable layer adds about 2,900 to a direct call's 1,250-1,330: about 83 ns + against CRuby's 48, the 1.5-1.7 of IronRuby's calls in general, not something of delegation's. + What a forwarding layer pays over a call with fixed arguments (`Util/bench/forward-shapes.rb`, + new, instructions a call into `two(a, b)`): fixed 1,701; `&k` passed on with no block 2,304; + `*a` 2,870; `*a, &k` 3,207; `...` 3,078; `*, &` 3,205. Taken apart: the rest Array 1,170; an + unused `&k` parameter alone (light frame, no block given) 438; a block argument alone (`&nil`) + 584 - the two together only 603, so mostly one cost; Forwardable's `defined?(_.m)` before each + forward about 30 ns (CRuby 12). A call passing a block to a Ruby method that uses none gets a rule + rather than a precompiled dispatcher (`BindPrecompiled` refuses it for `WarnUnusedBlock`, the + 3.4 unused-block warning, which only the rule emits; `IR_BIND_TRACE=1` shows `two(L,2&)` as + `rule`): a probe that let the dispatcher through counted the same (within the counter's +-70), + so that is not where the block's cost is. + Left for a step: the ~440-600 instructions of a block parameter or argument that is nil (in the + light frame's entry or in `MethodCall`'s block-argument path - the hoisting, the retry frame, + the block's conversion), which every `...`, `&block` and DelegateClass forward pays; and the rest + Array of `...` (a calling convention that passes the caller's arguments on without one, as + CRuby's VM does - larger than a step). + - **perf/passensure (2026-11-27) - running a pending ensure clause from the filter of a rescue frame above it: designed, found unsound, not built** (stage 1 of the brief; `Docs/rescue-above-ensure.md`). The idea (perf/rescuefilter): a rescue above a passed ensure catches and throws again (~20 us for the From f70e597cff166c9541fc8da50d1f85c2f834f506 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:22:17 +0000 Subject: [PATCH 158/439] LEDGER: perf/json landed (not gated): case over String literals dispatched once; gap 7 measured again Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7iJNHYWSjfa8yzFSQ --- Util/perf/LEDGER.md | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 5906b5a4f..7e7e32cb9 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -809,6 +809,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `@current != '"'` and `case @current when` in `read`, `read_value` and `read_string_internal`, which the JIT declines for their `raise` and their calls, so the compiled comparison of round seven does not reach them. + Round perf/json (2026-11-27, see Landed): profiled again (perf, 12 s at steady state), the + one-character comparisons are some 11% of self time (EqualsAsciiLiteral 4.8, Equals 3.0, + CaseString 2.3, StringEqualsString 1.2), the Range of `@input[a..b]` under 1%, and the String + per character escapes into `@current` and the capture buffer, so it cannot be skipped. Per call, + `x == '"'`, `x != '"'`, `'"' == x` and the four-way `is_white_space` chain were already at or + under CRuby's time with or without the method JIT; `case x when 'a', ...` was not (146.5 ns + without the JIT against 56): `case` over String literals now looks its subject up once. Still + open: the method JIT's own `case` over String literals (94-99 ns, a CaseString call per + literal), and what the calls between Json's small methods cost (CallSite.Target 9.4%, the + method JIT's entry stubs about 10%), which is gap 16's and /perf-frame's, not String work. 8. **`TakeBfcForBlockYield` 2.3% of DeltaBlue** is not the atomic exchange of 94dc9169: with a plain read and write in its place (an upper bound, not a correct change), SOM's `Vector#each` over 4 elements ran at 0.98-1.05 of before and over 100 at @@ -1626,6 +1636,44 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/json (2026-11-27) - `case` over String literals looks its subject up once while String#=== + is the library's (gap 7)** - not gated. Commit 0a78877 on `claude/perf-strsearch`, based on + claude/happy-gauss-95wm2j 15285eb with 0518f08 merged in. Measured first: a perf profile of AWFY + Json at steady state put the one-character String comparisons at about 11% of self time and the + Range of `@input[a..b]` under 1%; `@current = @input[@index]` escapes, so its String has to be + made. Per call (`Util/bench/strcmp-shapes.rb`, ns, CRuby / base / base -X:NoJIT): `x == '"'` + 71.6 / 46.8 / 81.1, `'"' == x` 67.3 / 43.3 / 73.8, the `is_white_space` chain 190.2 / 63.8 / + 170.6, `case x when` five clauses 56.0 / 98.9 / 146.5 (a method around it alone 30.1 / 42.8 / + 49.9). So the `case` was the piece: each `when 'x'` made a String and a `===` call through a site. + Json's read_value is such a `case` (eleven literals) in a method the JIT declines (it calls + methods the screen refuses for a String literal argument or a Range), so the generic code ran it. + Now a `case value` whose `when`s are all ASCII String literals gets a CaseStringSite: each + literal's clause in a 128-entry table (one character) or a dictionary; RubyOps.CaseStringDispatch + answers the clause for a String subject MutableString.FindAsciiLiteral can read in place (as + EqualsAsciiLiteral reads it) while String#=== resolves to MutableStringOps' own method under the + current global method version and the runtime has no refinements (as ArrayExtremeSite checks); + otherwise NotHandled, and each `when` makes its calls as written (`clause == NotHandled ? + : clause == i`; no body emitted twice). A light frame passes its declaring scope + (ScopeOperandIndex); the AOT compiler re-creates the site; ReflectionCache.Generated.cs + regenerated; `IR_CASE_DISPATCH=0` turns it off. `kase` without the JIT 146.5 -> 64.0 ns (CRuby + 56.0); with the JIT unchanged (94-99: the JIT's own CaseString chain, not touched). AWFY Json, ten + processes of `awfy.rb 10` per arm, alternating, ms per iteration (median, min-max): base 58.6 + (55.0-60.7), new 55.1 (53.7-58.8), off 57.9 (52.9-61.1): 0.942 of base, 0.952 of off, new below base + in 9 of 10 paired runs, but the ranges overlap; CD (no such `case`) 424.0 / 435.8 / 454.5 with + spreads of 10-12% on every arm, the noise of this machine. Census: 0 of 28,376 methods moved. + Checked: `Util/case-string-matrix.rb` (new, 786 rows: thirty subjects - one-character reads, + words, empty, UTF-8, BINARY, broken, US-ASCII, UTF-16LE, EUC-JP, frozen, a subclass, nil, a Symbol, + numbers, a #to_str object - through six `case`s in methods the JIT compiles and one it declines, + with frozen_string_literal, a refined, a prepended and a redefined String#===, with the calls each + makes counted): CRuby's output on base, new, IR_CASE_DISPATCH=0 and -X:NoJIT. string-search, + hot-shapes, jit, jit-calls and light-entry matrices: new, off and -X:NoJIT print what the base + prints (the base's own differences from CRuby, 115 / 3 / 0 / 0 / 1 rows, unchanged). + spec/core/string (3,963 examples; element_reference, slice, equal_value and eql run alone too) + and spec/language/case_spec.rb: the same on base, new and off, 0 failures (the one + `String.try_convert` error on all three). There is no spec/library/json at SPEC_REF and no json + matrix; JSON.parse/generate of escapes, non-ASCII, nesting and five malformed documents prints + CRuby's output on base and new. + - **perf/strsearch4 (2026-11-27) - the ASCII scan's cost of round three found and mostly removed; `#byteindex`/`#byterindex` from an offset other than 0 walk from the last search, through a map shared with StringScanner (gap 21, round four)** - not gated. Commits 8d030d1, 103c741 on From a984ac7477ddfd80125b1b2f623292a5941ddae2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:23:39 +0000 Subject: [PATCH 159/439] Time#strftime: a colon not before z ends the directive, and the error names the format MRI's strftime accepts colons only before z and E or O only before the conversions they modify; otherwise the directive is "unknown" at the colon (or the E or O): that much is copied through and the rest of the format is read afresh. So "%:%Y" is "%:2020" and "%E%Y" is "%E2020", while "%:%" and "%::3%" end in a lone %, which is an ArgumentError naming the whole format ("invalid format: %:%"). IronRuby read the colons and the next character as one directive, so "%:%" came out as "%:%" and "%:3%" as an error naming only the final "%". Util/strftime-matrix.rb: 108 rows differed from CRuby 4.0, 36 do (all %Z with a width on a zoneless time, a separate cause). spec/core/time, library/date and library/datetime strftime specs pass; Time_StrftimeColon1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 29 ++++++++++++++++++++++ Src/Libraries/Builtins/Strftime.cs | 32 ++++++++++++++++++++----- 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index aeb8b542d..977fdd149 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -984,6 +984,7 @@ public Tests(Driver/*!*/ driver) { Time_LoadZone1, Time_DumpLoadedZone1, Time_MachineZone1, + Time_StrftimeColon1, Time_OlsonZone1, Zlib_Streams1, Process_SpawnKill1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 77a069afa..fcd0cd0f1 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -948,6 +948,35 @@ puts ArrayList }, @"System::Collections::ArrayList"); } + /// + /// Colons go only with z, and E and O only with the conversions they modify: otherwise MRI's + /// strftime makes the directive unknown at the colon (or the E or O), copies it through and + /// reads the rest afresh, so "%:%Y" is "%:2020" and "%:%" ends in a lone %. That error names + /// the whole format. + /// + public void Time_StrftimeColon1() { + TestOutput(@" +t = Time.utc(2020, 1, 2, 3, 4, 5) +%w[%:%Y %::y %:: %::::z %:::z %E%Y %O%d %E: %-:%m %10:%Y].each { |f| p t.strftime(f) } +%w[%:% %::3% %E% x%].each { |f| begin; t.strftime(f); rescue ArgumentError => e; puts e.message; end } +", @" +""%:2020"" +""%::y"" +""%::"" +""%::::z"" +""+00"" +""%E2020"" +""%O02"" +""%E:"" +""%-:01"" +""%10:2020"" +invalid format: %:% +invalid format: %::3% +invalid format: %E% +invalid format: x% +"); + } + /// /// With TZ unset the zone is the machine's, daylight saving time included. Windows has no /etc/localtime, /// and the zone used to be TimeZoneInfo.Local's base offset alone, so Time.now, Time.local and File.mtime diff --git a/Src/Libraries/Builtins/Strftime.cs b/Src/Libraries/Builtins/Strftime.cs index 236385cb1..974eee280 100644 --- a/Src/Libraries/Builtins/Strftime.cs +++ b/Src/Libraries/Builtins/Strftime.cs @@ -71,8 +71,9 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, int start = i; i++; if (i >= format.Length) { - // MRI: a lone % at the end, or one followed only by flags or a width, is an error - throw RubyExceptions.CreateArgumentError("invalid format: " + format.Substring(start)); + // MRI: a lone % at the end, or one followed only by flags or a width, is an + // error that names the whole format + throw RubyExceptions.CreateArgumentError("invalid format: " + format); } Modifiers modifiers = new Modifiers(); @@ -107,17 +108,36 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, } if (i >= format.Length) { - throw RubyExceptions.CreateArgumentError("invalid format: " + format.Substring(start)); + throw RubyExceptions.CreateArgumentError("invalid format: " + format); } if (format[i] == 'E' || format[i] == 'O') { modifiers.Alt = format[i]; i++; + // MRI goes to "unknown" at the E or O itself when the next character is not + // a conversion it modifies: "%E" is copied through and the rest is read + // afresh, so "%E%Y" is "%E2020". + if (i < format.Length && (modifiers.Alt == 'E' ? "cCxXyY" : "deHImMSuUVwWy").IndexOf(format[i]) < 0) { + result.Append(format, start, i - start); + continue; + } } - while (i < format.Length && format[i] == ':' && modifiers.Colons < 3) { - modifiers.Colons++; - i++; + if (i < format.Length && format[i] == ':') { + int colons = 1; + while (i + colons < format.Length && format[i + colons] == ':') { + colons++; + } + if (colons > 3 || i + colons >= format.Length || format[i + colons] != 'z') { + // MRI: colons go only with z; otherwise the directive is unknown at the + // first colon, which is copied through, and the rest is read afresh, so + // "%:%Y" is "%:2020" and "%:%" ends in a lone %. + i++; + result.Append(format, start, i - start); + continue; + } + modifiers.Colons = colons; + i += colons; } if (i >= format.Length) { From 54c67eac9203b3efb89275d3ae722b46b13e56a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:27:34 +0000 Subject: [PATCH 160/439] Time#strftime: %Z of a zoneless time writes nothing, padding included A time made with a fixed offset (Time.new(..., 3660)) has no zone name. MRI's strftime then sets the piece's length to 0 and skips the copy and its padding together, so "%10Z" is "" and "%2000000000Z" neither pads nor raises ERANGE. IronRuby padded the empty name to the width. Util/strftime-matrix.rb now agrees with CRuby 4.0 (36 rows differed after the colon fix, none do); Time_StrftimeNoZone1 holds CRuby's output, and the time strftime and zone specs pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 22 ++++++++++++++++++++++ Src/Libraries/Builtins/Strftime.cs | 13 ++++++++++--- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 977fdd149..724d67a6e 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -985,6 +985,7 @@ public Tests(Driver/*!*/ driver) { Time_DumpLoadedZone1, Time_MachineZone1, Time_StrftimeColon1, + Time_StrftimeNoZone1, Time_OlsonZone1, Zlib_Streams1, Process_SpawnKill1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index fcd0cd0f1..abe68f754 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -977,6 +977,28 @@ public void Time_StrftimeColon1() { "); } + /// + /// A time with a fixed offset has no zone name, and MRI's %Z then writes nothing at all, not + /// even the padding of a width (nor does a huge width raise ERANGE). + /// + public void Time_StrftimeNoZone1() { + TestOutput(@" +t = Time.new(2012, 1, 1, 0, 0, 0, 3660) +%w[%10Z %-10Z %010Z %^5Z %Z| %2000000000Z].each { |f| p t.strftime(f) } +u = Time.utc(2020) +p u.strftime(""%6Z|""), u.localtime(""+01:00"").strftime(""%_5Z|"") +", @" +"""" +"""" +"""" +"""" +""|"" +"""" +"" UTC|"" +""|"" +"); + } + /// /// With TZ unset the zone is the machine's, daylight saving time included. Windows has no /etc/localtime, /// and the zone used to be TimeZoneInfo.Local's base offset alone, so Time.now, Time.local and File.mtime diff --git a/Src/Libraries/Builtins/Strftime.cs b/Src/Libraries/Builtins/Strftime.cs index 974eee280..fa6aeb377 100644 --- a/Src/Libraries/Builtins/Strftime.cs +++ b/Src/Libraries/Builtins/Strftime.cs @@ -154,10 +154,12 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, } if (modifiers.Width > 0 && PadsToWidth(directive, modifiers) && - result.Length + 2L * modifiers.Width > SizeLimit(format.Length)) { + result.Length + 2L * modifiers.Width > SizeLimit(format.Length) && + !(directive == 'Z' && String.IsNullOrEmpty(RubyTimeOps.GetZoneAbbreviation(context, time)))) { // MRI's strftime grows its buffer to at most strftime_size_limit and raises // ERANGE, naming the format, rather than going on: "%2147483647d" would - // otherwise ask for a 4 GB string. + // otherwise ask for a 4 GB string. A %Z with no zone name writes nothing, + // so it asks for no room. throw RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ERANGE"), format); } @@ -253,7 +255,12 @@ private static string FormatDirective(RubyContext/*!*/ context, RubyTime/*!*/ ti case 'Z': { string name = RubyTimeOps.GetZoneAbbreviation(context, time); - return Text(name ?? "", modifiers, width); + if (String.IsNullOrEmpty(name)) { + // MRI writes nothing for a time with no zone name (a fixed offset), + // not even the padding of a width: "%10Z" is "". + return ""; + } + return Text(name, modifiers, width); } case 'c': return Compound(context, time, "%a %b %e %H:%M:%S %Y", modifiers, depth); From 317d7661e455c85581d45d2dcc022e4e1c03e645 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:29:14 +0000 Subject: [PATCH 161/439] Date._strptime/_parse: a "UT" prefix before an offset is no zone MRI's date_zone_to_diff strips a "gmt" or "utc" before the sign of a numeric zone, never "ut", so Date._strptime("UT-3", "%Z") has offset: nil (while "ut" on its own is UTC, from the zone table). IronRuby's zone_to_diff accepted "ut" too and gave -10800. Util/strptime-matrix.rb: the "UT-3" row now agrees with CRuby 4.0. library/date and library/datetime specs pass; Date_ZoneToDiffUt1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 26 +++++++++++++++++++++++++ Src/StdLib/ironruby/date/format.rb | 4 +++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 724d67a6e..f83d78acd 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -986,6 +986,7 @@ public Tests(Driver/*!*/ driver) { Time_MachineZone1, Time_StrftimeColon1, Time_StrftimeNoZone1, + Date_ZoneToDiffUt1, Time_OlsonZone1, Zlib_Streams1, Process_SpawnKill1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index abe68f754..5be3ded3b 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -999,6 +999,32 @@ p u.strftime(""%6Z|""), u.localtime(""+01:00"").strftime(""%_5Z|"") "); } + /// + /// MRI's date_zone_to_diff strips only "gmt" or "utc" before a zone's sign, so "UT-3" has no + /// offset, though "ut" on its own is UTC. + /// + public void Date_ZoneToDiffUt1() { + TestOutput(@" +require 'ruby4' +require 'date' +[""UT-3"", ""UT+0930"", ""UTC-3"", ""GMT+3"", ""+3"", ""ut"", ""Ut-03:00"", ""utc+9"", ""gmt-3.5""].each { |z| p [z, Date._strptime(z, ""%Z"")] } +p Date._parse(""2026-01-02 10:00 UT-3"") +p DateTime.strptime(""2026 UTC-3"", ""%Y %Z"").offset +", @" +[""UT-3"", {zone: ""UT-3"", offset: nil}] +[""UT+0930"", {zone: ""UT+0930"", offset: nil}] +[""UTC-3"", {zone: ""UTC-3"", offset: -10800}] +[""GMT+3"", {zone: ""GMT+3"", offset: 10800}] +[""+3"", {zone: ""+3"", offset: 10800}] +[""ut"", {zone: ""ut"", offset: 0}] +[""Ut-03:00"", {zone: ""Ut-03:00"", offset: nil}] +[""utc+9"", {zone: ""utc+9"", offset: 32400}] +[""gmt-3.5"", {zone: ""gmt-3.5"", offset: -12600}] +{zone: ""UT-3"", hour: 10, min: 0, year: 2026, mon: 1, mday: 2, offset: nil} +(-1/8) +"); + } + /// /// With TZ unset the zone is the machine's, daylight saving time included. Windows has no /etc/localtime, /// and the zone used to be TimeZoneInfo.Local's base offset alone, so Time.now, Time.local and File.mtime diff --git a/Src/StdLib/ironruby/date/format.rb b/Src/StdLib/ironruby/date/format.rb index 92945cf9c..f7f770684 100644 --- a/Src/StdLib/ironruby/date/format.rb +++ b/Src/StdLib/ironruby/date/format.rb @@ -1073,7 +1073,9 @@ def zone_to_diff(zone) # :nodoc: if Format::ZONES.include?(zone) offset = Format::ZONES[zone] offset += 3600 if dst - elsif zone.sub!(/\A(?:gmt|utc?)?([-+])/, '') + # MRI's date_zone_to_diff strips only a "gmt" or "utc" before the sign: "ut-3" is no + # offset, though "ut" alone is a zone. + elsif zone.sub!(/\A(?:gmt|utc)?([-+])/, '') sign = $1 if zone.include?(':') hour, min, sec, = zone.split(':') From ae3360babc60f2869df0977df22460137fc8c9bc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:31:31 +0000 Subject: [PATCH 162/439] Date._strptime/_parse: refuse a string that is not ASCII-compatible date_s__strptime_internal and date_s__parse raise ArgumentError ("string should have ASCII compatible encoding", or "format should ..." for the format) before matching anything. IronRuby went on and failed in the first regexp match with Encoding::CompatibilityError. Date.strptime and DateTime._strptime reach the same check. Util/strptime-matrix.rb: the utf-16 row now agrees with CRuby 4.0. Date_StrptimeEncoding1 holds CRuby's output; library/date, datetime and time specs pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 23 +++++++++++++++++++++++ Src/StdLib/ironruby/date/format.rb | 5 +++++ 3 files changed, 29 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f83d78acd..e66081722 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -987,6 +987,7 @@ public Tests(Driver/*!*/ driver) { Time_StrftimeColon1, Time_StrftimeNoZone1, Date_ZoneToDiffUt1, + Date_StrptimeEncoding1, Time_OlsonZone1, Zlib_Streams1, Process_SpawnKill1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 5be3ded3b..691400da8 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -1025,6 +1025,29 @@ p DateTime.strptime(""2026 UTC-3"", ""%Y %Z"").offset "); } + /// + /// Date._strptime and Date._parse refuse a string (or format) whose encoding is not ASCII-compatible + /// with MRI's ArgumentError, before any regexp sees it. + /// + public void Date_StrptimeEncoding1() { + TestOutput(@" +require 'ruby4' +require 'date' +u = ""2026"".encode(""UTF-16LE"") +p((Date._strptime(u, ""%Y"") rescue $!)) +p((Date._strptime(""2026"", ""%Y"".encode(""UTF-16LE"")) rescue $!)) +p((Date._parse(u) rescue $!)) +p((Date.strptime(u, ""%Y"") rescue $!)) +p((DateTime._strptime(u, ""%Y"") rescue $!)) +", @" +# +# +# +# +# +"); + } + /// /// With TZ unset the zone is the machine's, daylight saving time included. Windows has no /etc/localtime, /// and the zone used to be TimeZoneInfo.Local's base offset alone, so Time.now, Time.local and File.mtime diff --git a/Src/StdLib/ironruby/date/format.rb b/Src/StdLib/ironruby/date/format.rb index f7f770684..3ffff05d6 100644 --- a/Src/StdLib/ironruby/date/format.rb +++ b/Src/StdLib/ironruby/date/format.rb @@ -386,7 +386,11 @@ def self._strptime(str, fmt='%F') # StringValue, as date_s__strptime takes both (String#+ converts with #to_str, or raises # MRI's TypeError: "no implicit conversion of nil into String") str = '' + str unless String === str + # date_s__strptime_internal: each argument must have an ASCII-compatible encoding, the + # string's checked before the format is converted + raise ArgumentError, 'string should have ASCII compatible encoding' unless str.encoding.ascii_compatible? fmt = '' + fmt unless String === fmt + raise ArgumentError, 'format should have ASCII compatible encoding' unless fmt.encoding.ascii_compatible? # ASCII-only Strings go to the C# walk (Src/Libraries/Date/DateStrptime.cs), which answers # false for what it leaves to the Ruby below. It hands back the Rationals as [n, d] and the # offset as a place after the zone, so that the Hash keeps the Bag's order. @@ -856,6 +860,7 @@ def self._parse_ddd(str, e) # :nodoc: :_parse_year, :_parse_mon, :_parse_mday, :_parse_ddd def self._parse(str, comp=true) + raise ArgumentError, 'string should have ASCII compatible encoding' unless str.encoding.ascii_compatible? str = str.dup e = Format::Bag.new From a765d0890efb982fc0a33189e3967ca9ddfa06a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:32:55 +0000 Subject: [PATCH 163/439] Date._strptime: the leftover is a plain String for a subclass's string MRI builds the :leftover (and the other captured strings) as new Strings, so a String subclass passed to Date._strptime does not come back in the hash. IronRuby's Ruby walk worked on str.dup, which keeps the subclass; it now copies with String.new. ASCII-only plain Strings take the C# walk and are not affected. Util/strptime-matrix.rb: the subclass row now agrees with CRuby 4.0. Date_StrptimeSubclass1 holds CRuby's output; library/date, datetime and time specs pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 17 +++++++++++++++++ Src/StdLib/ironruby/date/format.rb | 3 ++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e66081722..e3f293354 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -988,6 +988,7 @@ public Tests(Driver/*!*/ driver) { Time_StrftimeNoZone1, Date_ZoneToDiffUt1, Date_StrptimeEncoding1, + Date_StrptimeSubclass1, Time_OlsonZone1, Zlib_Streams1, Process_SpawnKill1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 691400da8..3f0bcee52 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -1048,6 +1048,23 @@ public void Date_StrptimeEncoding1() { "); } + /// + /// Date._strptime's leftover is a plain String even when the string passed in is a subclass's, + /// as MRI's is. + /// + public void Date_StrptimeSubclass1() { + TestOutput(@" +require 'ruby4' +require 'date' +class S < String; end +h = Date._strptime(S.new(""2026 x""), ""%Y""); p [h, h[:leftover].class] +h = Date._strptime(S.new(""2026 \xC3\xA9""), ""%Y""); p [h[:leftover].bytes, h[:leftover].class] +", @" +[{year: 2026, leftover: "" x""}, String] +[[32, 195, 169], String] +"); + } + /// /// With TZ unset the zone is the machine's, daylight saving time included. Windows has no /etc/localtime, /// and the zone used to be TimeZoneInfo.Local's base offset alone, so Time.now, Time.local and File.mtime diff --git a/Src/StdLib/ironruby/date/format.rb b/Src/StdLib/ironruby/date/format.rb index 3ffff05d6..54307ba24 100644 --- a/Src/StdLib/ironruby/date/format.rb +++ b/Src/StdLib/ironruby/date/format.rb @@ -404,7 +404,8 @@ def self._strptime(str, fmt='%F') return h end end - str = str.dup + # A copy that is a plain String, as MRI's leftover is, whatever subclass came in + str = String.new(str) e = Format::Bag.new return unless _strptime_i(str, fmt, e) From d532e821a03315cee81be6fa291244c1ef3d3e8f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:34:27 +0000 Subject: [PATCH 164/439] Date._parse: take the day name out before the time date__parse runs parse_day before parse_time. IronRuby ran them the other way round, so in "10:00 sat" the time's zone alternative ([[:alpha:]]+) took "sat" as a zone (zone: "sat", offset: nil) and the weekday was lost; where both were found, :wday came after the time's keys instead of first. Util/strptime-matrix.rb: the four _parse rows now agree with CRuby 4.0 (one row differs, Time.strptime with a bignum year, which needs a year beyond long in RubyTime). Date_ParseDayFirst1 holds CRuby's output; library/date, datetime and time specs pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 18 ++++++++++++++++++ Src/StdLib/ironruby/date/format.rb | 4 +++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e3f293354..899e33639 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -989,6 +989,7 @@ public Tests(Driver/*!*/ driver) { Date_ZoneToDiffUt1, Date_StrptimeEncoding1, Date_StrptimeSubclass1, + Date_ParseDayFirst1, Time_OlsonZone1, Zlib_Streams1, Process_SpawnKill1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 3f0bcee52..51f1c2341 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -1065,6 +1065,24 @@ class S < String; end "); } + /// + /// date__parse takes the day name out before the time, so the time's zone cannot read a day name + /// after the time as a zone, and :wday leads the hash. + /// + public void Date_ParseDayFirst1() { + TestOutput(@" +require 'ruby4' +require 'date' +[""Sat Aug 28 02:55:50 2021"", ""10:00 sat"", ""Sat, 28 Aug 2021 02:55:50 GMT"", ""monday 3pm"", ""2021-08-28 sun""].each { |s| p Date._parse(s) } +", @" +{wday: 6, hour: 2, min: 55, sec: 50, year: 2021, mon: 8, mday: 28} +{wday: 6, hour: 10, min: 0} +{wday: 6, zone: ""GMT"", hour: 2, min: 55, sec: 50, year: 2021, mon: 8, mday: 28, offset: 0} +{wday: 1, hour: 15} +{wday: 0, year: 2021, mon: 8, mday: 28} +"); + } + /// /// With TZ unset the zone is the machine's, daylight saving time included. Windows has no /etc/localtime, /// and the zone used to be TimeZoneInfo.Local's base offset alone, so Time.now, Time.local and File.mtime diff --git a/Src/StdLib/ironruby/date/format.rb b/Src/StdLib/ironruby/date/format.rb index 54307ba24..49eb07335 100644 --- a/Src/StdLib/ironruby/date/format.rb +++ b/Src/StdLib/ironruby/date/format.rb @@ -870,8 +870,10 @@ def self._parse(str, comp=true) str.gsub!(/[^-+',.\/:@[:alnum:]\[\]]+/, ' ') - _parse_time(str, e) # || _parse_beat(str, e) + # date__parse takes the day name out first, so that the time's zone cannot read + # "10:00 sat" as a zone named "sat" (and :wday leads the hash) _parse_day(str, e) + _parse_time(str, e) # || _parse_beat(str, e) _parse_eu(str, e) || _parse_us(str, e) || From fa6fa4e8e2db9d0fda464d169524a43ec6c3fcf4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:40:32 +0000 Subject: [PATCH 165/439] Encoding errors from a conversion have binary messages MRI's transcoder builds the messages of UndefinedConversionError, InvalidByteSequenceError and ConverterNotFoundError with rb_sprintf, so they are ASCII-8BIT strings ("U+65E5 from UTF-8 to US-ASCII", "\"\xFF\" on UTF-8", "code converter not found (x to y)"). IronRuby turned the CLR message into a UTF-8 string. An error made from Ruby with a message of its own still keeps that string. Util/converter-matrix.rb: the message cells of the LAST_ERROR rows now agree with CRuby 4.0, as does the one differing row of Util/encode-matrix.rb; core/encoding and String#encode specs pass, and Encoding_ErrorMessageBinary1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 26 +++++++++++++++++++++++++ Src/Ruby/Runtime/RubyExceptionData.cs | 9 ++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 899e33639..4359bb241 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1064,6 +1064,7 @@ public Tests(Driver/*!*/ driver) { Encoding_InvalidBytes1, Encoding_Converter1, Encoding_Converter2, + Encoding_ErrorMessageBinary1, Encoding_StatelessIso2022Jp1, Encoding_AsciiIncompatible1, Encoding_AsciiIncompatibleLines1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 51f1c2341..7740276ae 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -3275,6 +3275,32 @@ puts r.inspect "); } + /// + /// MRI builds the transcoders' error messages with rb_sprintf, so an UndefinedConversionError, + /// InvalidByteSequenceError or ConverterNotFoundError raised by a conversion has a binary message; + /// one made with a message of its own keeps that string. + /// + public void Encoding_ErrorMessageBinary1() { + TestOutput(@" +ec = Encoding::Converter.new(""UTF-8"", ""US-ASCII"") +ec.primitive_convert(""\xE6\x97\xA5"".dup.force_encoding(""UTF-8""), """".b) +p ec.last_error.message.encoding +[""\xE6\x97\xA5"", ""\xFF""].each { |s| begin; s.dup.force_encoding(""UTF-8"").encode(""US-ASCII""); rescue => x; p [x.class, x.message, x.message.encoding]; end } +begin; ""\xFF"".b.encode(""UTF-8""); rescue => x; p [x.message, x.message.encoding]; end +begin; Encoding::Converter.new(""x"", ""y""); rescue => x; p [x.message, x.message.encoding]; end +p Encoding::UndefinedConversionError.new(""m"").message.encoding +p Encoding::UndefinedConversionError.new.message +", @" +# +[Encoding::UndefinedConversionError, ""U+65E5 from UTF-8 to US-ASCII"", #] +[Encoding::InvalidByteSequenceError, ""\""\\xFF\"" on UTF-8"", #] +[""\""\\xFF\"" from ASCII-8BIT to UTF-8"", #] +[""code converter not found (x to y)"", #] +# +""Encoding::UndefinedConversionError"" +"); + } + public void Encoding_Converter1() { TestOutput(@" def t diff --git a/Src/Ruby/Runtime/RubyExceptionData.cs b/Src/Ruby/Runtime/RubyExceptionData.cs index d4da51a28..e5c295569 100644 --- a/Src/Ruby/Runtime/RubyExceptionData.cs +++ b/Src/Ruby/Runtime/RubyExceptionData.cs @@ -778,7 +778,14 @@ public object Message { // "Attempted to divide by zero."; MRI says "divided by 0". clrMessage = "divided by 0"; } - _message = MutableString.Create(clrMessage, RubyEncoding.UTF8); + if (_exception is UndefinedConversionError || _exception is InvalidByteSequenceError || + _exception is ConverterNotFoundError) { + // MRI builds the transcoders' messages with rb_sprintf into binary strings + // ("\"\xFF\" on UTF-8", "code converter not found (x to y)"). + _message = MutableString.CreateBinary(System.Text.Encoding.UTF8.GetBytes(clrMessage)); + } else { + _message = MutableString.Create(clrMessage, RubyEncoding.UTF8); + } } return _message; } From 0ae2117dc6c914e0d45b1ec54fc49a767780f462 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:41:14 +0000 Subject: [PATCH 166/439] Encoding::Converter#convpath: decorator names are binary strings MRI's convpath and search_convpath list a decorator by the name its transcoder table holds, a binary string ("universal_newline" is ASCII-8BIT). IronRuby made them US-ASCII. Util/converter-matrix.rb: the "NEW decorator" row now agrees with CRuby 4.0; core/encoding specs pass and Encoding_ConvPathDecoratorBinary1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 20 ++++++++++++++++++++ Src/Libraries/Builtins/EncodingConverter.cs | 6 +++--- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 4359bb241..b1254c44c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1065,6 +1065,7 @@ public Tests(Driver/*!*/ driver) { Encoding_Converter1, Encoding_Converter2, Encoding_ErrorMessageBinary1, + Encoding_ConvPathDecoratorBinary1, Encoding_StatelessIso2022Jp1, Encoding_AsciiIncompatible1, Encoding_AsciiIncompatibleLines1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 7740276ae..d4b190b16 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -3301,6 +3301,26 @@ p ec.last_error.message.encoding "); } + /// + /// A decorator's name in Encoding::Converter#convpath (and search_convpath) is a binary string, + /// as MRI's transcoder table holds it. + /// + public void Encoding_ConvPathDecoratorBinary1() { + TestOutput(@" +p Encoding::Converter.new("""", """", universal_newline: true).convpath.map(&:encoding) +p Encoding::Converter.new("""", ""universal_newline"").convpath.map(&:encoding) +p Encoding::Converter.new([[""UTF-8"", ""EUC-JP""], ""crlf_newline""]).convpath.last.encoding +p Encoding::Converter.search_convpath(""UTF-8"", ""EUC-JP"", crlf_newline: true).last.encoding +p Encoding::Converter.new(""UTF-8"", ""UTF-16BE"", xml: :text).convpath[0].encoding +", @" +[#] +[#] +# +# +# +"); + } + public void Encoding_Converter1() { TestOutput(@" def t diff --git a/Src/Libraries/Builtins/EncodingConverter.cs b/Src/Libraries/Builtins/EncodingConverter.cs index bb7b2c83a..0b9a70e2c 100644 --- a/Src/Libraries/Builtins/EncodingConverter.cs +++ b/Src/Libraries/Builtins/EncodingConverter.cs @@ -379,7 +379,7 @@ private static RubyEncoding FindEncoding(RubyContext/*!*/ context, object obj, s // universal_newline is ["universal_newline", [UTF-8, UTF-16BE]]. int at = (path != null && !path[path.Length - 1].IsAsciiIdentity) ? result.Count - 1 : result.Count; foreach (string name in DecoratorPathNames(flags)) { - result.Insert(at++, MutableString.CreateAscii(name).Freeze()); + result.Insert(at++, MutableString.CreateBinary(Encoding.ASCII.GetBytes(name)).Freeze()); } return result; } @@ -1650,7 +1650,7 @@ private static int ParseOptions(ConversionStorage>/* TryGetDecoratorFlag(destinationString.ToString(), out decorator)) { var named = new RubyConverter(null, flags | decorator); string name = destinationString.ToString(); - named._explicitConvPath = new RubyArray { MutableString.CreateAscii(name).Freeze() }; + named._explicitConvPath = new RubyArray { MutableString.CreateBinary(Encoding.ASCII.GetBytes(name)).Freeze() }; named._explicitDescription = name; return named; } @@ -1722,7 +1722,7 @@ private static bool TryGetDecoratorFlag(string/*!*/ name, out int flag) { throw RubyExceptions.CreateArgumentError("decoration failed: {0}", name); } flags |= decorator; - reported.Add(MutableString.CreateAscii(name).Freeze()); + reported.Add(MutableString.CreateBinary(Encoding.ASCII.GetBytes(name)).Freeze()); } var result = new RubyConverter(path.Count != 0 ? path.ToArray() : null, flags); From 72925c05867f0844dae4e0909242c6ca2ff97454 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:47:00 +0000 Subject: [PATCH 167/439] Leave $! alone in a begin/rescue/ensure that raises nothing (IR_LAZY_ERRINFO) A method with a rescue or an ensure clause paid for $! on every call, raising or not: the rescue's finally wrote it back, the ensure clause read it and wrote it back, and every ensure asked IsReclaimingFiber. All three are [ThreadStatic]s, a call into the runtime from a compiled body (gap 22: ensure 112 ns against CRuby's 27, rescue 106 against 24). - The rescue's finally restores $! only if an exception was taken or the statements were left otherwise (a jump, an exception going through): run to their end, they left $! as it was. The save at entry stays: by the time a handler runs, an inner frame that threw the exception on may have changed $!. - The ensure clause reads and restores $! only for an exception it runs for; with none it leaves $! as it found it. - IsReclaimingFiber asks the thread-static only while some thread has a safe point requested, which a thread reclaiming a fiber always has. Timed (ab.rb, eight rounds, -X:NoJIT; switch off -> on): ensure 60.8 -> 52.0 ns (CRuby 31.6), else 62.7 -> 56.0, begin/rescue 62.2 -> 56.0, rescue 52.9 -> 52.3, the plain control 46.5 -> 45.3. errinfo-matrix and nine other matrices in five modes print the baseline's output; ruby/spec language/rescue, ensure, retry, core/exception and library/timeout pass as on the baseline. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/Ruby/Compiler/Ast/Body.cs | 53 +++++++++++++++++++++++++++++------ Src/Ruby/Runtime/RubyUtils.cs | 10 ++++++- 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Body.cs b/Src/Ruby/Compiler/Ast/Body.cs index 005b22f89..1224589f7 100644 --- a/Src/Ruby/Compiler/Ast/Body.cs +++ b/Src/Ruby/Compiler/Ast/Body.cs @@ -146,6 +146,14 @@ internal bool HasRescue { /// internal bool SafePointFirst { get; set; } + /// + /// IR_LAZY_ERRINFO=0 saves and restores $! around a begin/rescue/ensure on every run, as it used to. Otherwise a run in + /// which nothing is raised leaves $! alone: the rescue's finally restores it only if an exception was taken or the body + /// was left otherwise (a jump, an exception going through), and the ensure clause reads and restores it only for an + /// exception it runs for. Each access is a [ThreadStatic], a call into the runtime from compiled code (gap 22). + /// + internal static readonly bool LazyErrinfo = Environment.GetEnvironmentVariable("IR_LAZY_ERRINFO") != "0"; + private bool HasExceptionHandling { get { return (_statements.Count > 0 && _rescueClauses != null) || _elseStatements != null || _ensureStatements != null; @@ -217,8 +225,17 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem transformedEnsure = Ast.Block( // ensure (an exception to be thrown on gets its backtrace completed first: a jump out of the clause ends it): - Ast.Assign(oldExceptionVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), - AstUtils.IfThen(exceptionRethrowVariable, Ast.Call(_ExposeException, oldExceptionVariable)), + // $! is read only for an exception the clause runs for (LazyErrinfo): with none, the clause leaves $! as it + // found it when it completes, and restoring it would store what is there. + LazyErrinfo + ? AstUtils.IfThen(exceptionRethrowVariable, + Ast.Assign(oldExceptionVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), + Ast.Call(_ExposeException, oldExceptionVariable) + ) + : Ast.Block( + Ast.Assign(oldExceptionVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), + AstUtils.IfThen(exceptionRethrowVariable, Ast.Call(_ExposeException, oldExceptionVariable)) + ), Ast.Assign(ensureDoneVariable, AstUtils.Constant(false)), AstUtils.Try( // An exception the clause raises has the exception the clause runs for as its cause, which the @@ -240,7 +257,9 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, entryExceptionVariable) ) ), - Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable), + LazyErrinfo + ? AstUtils.IfThen(exceptionRethrowVariable, Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable)) + : Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable), // rethrow: AstUtils.IfThen( @@ -290,6 +309,22 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem MSA.Expression handledVariable = (_rescueClauses != null) ? gen.CurrentScope.DefineHiddenVariable("#handled-exception", typeof(Exception)) : null; + // Whether the statements ran to their end with nothing taken by the handler: $! is then what it was before, and the + // finally below has nothing to restore (LazyErrinfo). Left by a jump or an exception, they did not. + MSA.Expression completedVariable = (_rescueClauses != null && LazyErrinfo) ? + gen.CurrentScope.DefineHiddenVariable("#body-completed", typeof(bool)) : null; + Func restoreHandled = () => (completedVariable != null) + ? AstUtils.IfThen( + Ast.AndAlso(Ast.Not(exceptionRethrowVariable), Ast.OrElse(exceptionThrownVariable, Ast.Not(completedVariable))), + Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable) + ) + : AstUtils.Unless(exceptionRethrowVariable, + Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable) + ); + Func markCompleted = () => (completedVariable != null) + ? (MSA.Expression)Ast.Assign(completedVariable, AstUtils.Constant(true)) + : AstUtils.Empty(); + // make rescue clause: MSA.Expression transformedRescue; if (_rescueClauses != null) { @@ -376,6 +411,7 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem ) ), Ast.Assign(passingVariable, AstUtils.Constant(null, typeof(Exception))), + markCompleted(), AstUtils.IfThen(exceptionThrownVariable, Ast.Block( Ast.Assign(handledVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), transformedRescue, @@ -384,9 +420,7 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem AstUtils.Empty() ).Finally( // restore previous exception if the current one has been handled: - AstUtils.Unless(exceptionRethrowVariable, - Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable) - ), + restoreHandled(), leaveRescue ); } else if (_rescueClauses != null) { @@ -399,6 +433,7 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem Ast.Assign(exceptionThrownVariable, AstUtils.Constant(true)), AstUtils.Empty() ), + markCompleted(), AstUtils.IfThen(exceptionThrownVariable, Ast.Block( Ast.Assign(handledVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), transformedRescue, @@ -407,9 +442,7 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem AstUtils.Empty() ).Finally( // restore previous exception if the current one has been handled: - AstUtils.Unless(exceptionRethrowVariable, - Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable) - ), + restoreHandled(), leaveRescue ); } else if (_elseStatements == null) { @@ -443,6 +476,8 @@ public Body(Statements/*!*/ statements, List rescueClauses, Statem // no rescue clause has run yet, also after a retry: the else clause's exceptions have $! as their cause (_rescueClauses == null) ? (MSA.Expression)AstUtils.Empty() : Ast.Assign(handledVariable, AstUtils.Constant(null, typeof(Exception))), + (completedVariable == null) ? (MSA.Expression)AstUtils.Empty() : + Ast.Assign(completedVariable, AstUtils.Constant(false)), guarded, diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index aca28d882..b42c91ae4 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1846,7 +1846,15 @@ public FiberReclaimSignal() : base(null) { } [ThreadStatic] private static bool _reclaimingFiber; - public static bool IsReclaimingFiber { get { return _reclaimingFiber; } } + // Every ensure clause asks, on every run (Body.TransformExceptionHandling), and the [ThreadStatic] is a call into the + // runtime from a compiled body. A thread reclaiming a fiber has a safe point requested for as long as it does + // (BeginFiberReclamation, EndFiberReclamation): while no thread has, the count says no without the thread-static. + // IR_LAZY_ERRINFO=0 reads the thread-static every time. + private static readonly bool ReclaimingTestsCount = Environment.GetEnvironmentVariable("IR_LAZY_ERRINFO") != "0"; + + public static bool IsReclaimingFiber { + get { return (!ReclaimingTestsCount || Volatile.Read(ref Requests) != 0) && _reclaimingFiber; } + } public static void BeginFiberReclamation() { if (!_reclaimingFiber) { From 0f83fd93272efe04376eb17aab5e2cf4f55b28a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:54:37 +0000 Subject: [PATCH 168/439] Share the `!=' rule of plain objects between their classes (gaps 10 and 12) `a != b' on a plain object is bound as `!a.equal?(b)' when the receiver's `==' is BasicObject's (DispatchIntrinsics.TryBuildNotEquals, #215), and MaySpecialize kept those rules out of the shared rules, so a site got a rule per receiver class: over two to eight classes it missed its target on every other call into the DLR's UpdateAndExecute, whose speed the CLR's dynamic PGO decided from one process to the next, and over sixty it built a rule per class. The rule is now shared when the receiver is a plain RubyObject (BasicObject subclasses included), the call has the intrinsic's shape, and the class resolves `==' - public, without refinements, as BasicObject#!= calls it - to BasicObject#== (IsSharableNotEquals). ResolveShared asks that for the first bind and for every class version TryShareVersion adds, so a class whose `==' or `!=' is anything else is never in the set, and defining either re-versions the class. nil, booleans, Integers and Strings keep their rules. IR_SHARED_NEQ=0 turns it off. Checked: twospeed-shapes in ten processes per build: two classes 83-114 -> 39-43 ns, four 65-80 -> 41-51, eight 89-102 -> 44-48, sixty 542-571 -> 42-44; one class, `==' and calls level; callgrind controls 1.000. AWFY Richards, Json, Permute, DeltaBlue and Bounce in ten processes each: level. The new Util/neq-share-matrix.rb (== and != defined, included, on singletons, private, protected, on Object; method_missing; refinements; Comparable; Struct; BasicObject subclasses; Integer against Float; threads), shared-rule-light, jit, jit-calls, dmeth-jit and refinement matrices print CRuby's output in all seven gate modes and with the switch off; hot-shapes prints the base's. ruby/spec core/basicobject, core/comparable and language/send_spec as the base; 338 named IronRuby.Tests pass. Not gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs | 32 +++- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 2 +- Util/neq-share-matrix.rb | 157 +++++++++++++++++++ Util/perf/LEDGER.md | 38 +++++ 4 files changed, 226 insertions(+), 3 deletions(-) create mode 100644 Util/neq-share-matrix.rb diff --git a/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs b/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs index 696d55507..3410d1d81 100644 --- a/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs +++ b/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs @@ -324,12 +324,40 @@ internal static bool IsLightBlockGivenSite(string/*!*/ methodName, RubyCallSigna /// class has one instance, so its folded rule would serve one object - OpenStruct's `respond_to?(:total)' met a new one with /// every OpenStruct, and built and compiled a rule for each. The ordinary call is shared between such classes instead. /// - internal static bool MaySpecialize(RubyMemberInfo/*!*/ method, RubyCallSignature signature, RubyClass/*!*/ targetClass) { + /// + /// A `!=' rule for a plain Ruby object (IsSharableNotEquals) is the exception: its answer, `a.equal?(b)' negated, is the same + /// for every class that resolves `==' to BasicObject#==, so it is shared like an ordinary call (gap 10). + internal static bool MaySpecialize(RubyMemberInfo/*!*/ method, RubyCallSignature signature, RubyClass/*!*/ targetClass, object target) { if (IsKernelMethod(method, ref _respondTo, "RespondTo")) { return signature.ArgumentCount == 1 && !signature.HasBlock && !signature.HasSplattedArgument && !signature.HasRhsArgument && !IsObjectSingleton(targetClass); } - return IsSendMethod(method) || IsNotEqualsMethod(method); + return IsSendMethod(method) || IsNotEqualsMethod(method) && !IsSharableNotEquals(targetClass, target, signature); + } + + internal static readonly bool ShareNotEqualsEnabled = System.Environment.GetEnvironmentVariable("IR_SHARED_NEQ") != "0"; + + /// + /// `a != b' on a plain Ruby object - a RubyObject, BasicObject subclasses included - whose class resolves `==' (public, + /// without refinements, as BasicObject#!= calls it) to BasicObject#==: TryBuildNotEquals binds it as `!a.equal?(b)', + /// which depends on nothing else about the class. One rule then serves every such class, its receiver test the set of + /// class versions found to resolve both names so (RubyCallAction.BindShared, TryShareVersion - each of which comes + /// here for the class it is about to add): a site over two to eight classes no longer misses its target on every + /// other call into the DLR's update, whose speed was the CLR's dynamic PGO's to decide (gap 12, perf/twospeed2). + /// Defining `==' or `!=' anywhere in the class's ancestry re-versions it, and the new version is checked again here; + /// a class whose `==' is another method (Comparable's, a Struct's, a user's, a refinement-free override) is not taken + /// and gets the rule of its own it got before. IR_SHARED_NEQ=0 turns this off. + /// + internal static bool IsSharableNotEquals(RubyClass/*!*/ targetClass, object target, RubyCallSignature signature) { + if (!ShareNotEqualsEnabled || target == null || target.GetType() != typeof(RubyObject) || + signature.HasBlock || signature.HasSplattedArgument || signature.HasRhsArgument || signature.ResolveOnly || + signature.IsVirtualCall || signature.IsSuperCall || signature.IsInteropCall || signature.ArgumentCount != 1) { + return false; + } + int version; + var lookup = targetClass.GetMethodLookup("==", out version); + return version >= 0 && lookup.Found && lookup.Visibility == RubyMethodVisibility.Public && + IsLibraryMethod(lookup.Info, "IronRuby.Builtins.BasicObjectOps", "ValueEquals"); } // the singleton class of an object that is not a module: its only instance is that object diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index dc8cb4682..8e561d773 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -445,7 +445,7 @@ private bool ResolveShared(RubyContext/*!*/ context, RubyScope/*!*/ scope, objec } // respond_to?(:sym) and send(:sym) rules are specialized on the receiver's class (DispatchIntrinsics): - if (!isMissing && DispatchIntrinsics.MaySpecialize(member, Signature, targetClass)) { + if (!isMissing && DispatchIntrinsics.MaySpecialize(member, Signature, targetClass, target)) { return false; } diff --git a/Util/neq-share-matrix.rb b/Util/neq-share-matrix.rb new file mode 100644 index 000000000..04263c9a8 --- /dev/null +++ b/Util/neq-share-matrix.rb @@ -0,0 +1,157 @@ +# Differential matrix for `a != b' bound as one rule shared by receivers of several classes (gap 10, +# DispatchIntrinsics.IsSharableNotEquals, IR_SHARED_NEQ). Each row runs one `!=' site hot over objects of +# several plain classes, then changes what `!=' or `==' means for one of them - `==' defined on a class, on a +# module included later, on a singleton class; `!=' defined; method_missing; refinements; BasicObject +# subclasses; Comparable; Integer against Float; Struct - and runs the site again. Run under CRuby and ./ir.sh +# (JIT on and off, light frames off, the switch off) and diff: +# +# ruby Util/neq-share-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/neq-share-matrix.rb > /tmp/ir.txt && diff /tmp/mri.txt /tmp/ir.txt +# IR_SHARED_NEQ=0 ./ir.sh Util/neq-share-matrix.rb > /tmp/off.txt && diff /tmp/mri.txt /tmp/off.txt +# +# Every row must match, and the last line be `end'. + +$stdout.sync = true +N = 3000 + +def row(name, value) + puts "#{name}: #{value.inspect}" +end + +def err + yield +rescue Exception => e + [e.class, e.message] +end + +# one `!=' site, called over objs against other; the count of true answers +def neq_site(objs, other, n = N) + c = 0 + n.times { |i| c += 1 if objs[i % objs.size] != other } + c +end + +# a second site, so that a rule shared between sites is exercised too +def neq_site2(objs, other, n = N) + c = 0 + i = 0 + while i < n + c += 1 if objs[i % objs.size] != other + i += 1 + end + c +end + +def fresh(k) = (1..k).map { Class.new } + +cs = fresh(8) +objs = cs.map(&:new) +row "1. plain, 1..8 classes", [1, 2, 3, 4, 8].map { |k| [neq_site(objs.first(k), objs[0]), neq_site2(objs.first(k), objs[1])] } + +cs = fresh(4); objs = cs.map(&:new) +r = [neq_site(objs, objs[2])] +cs[2].class_eval { def ==(o) = true } +r << neq_site(objs, objs[3]) << neq_site2(objs, objs[0]) +row "2. == defined on one class after the site bound", r + +cs = fresh(4); objs = cs.map(&:new) +r = [neq_site(objs, objs[1])] +cs[1].class_eval { def !=(o) = :custom } +r << neq_site(objs, objs[1]) << (objs[1] != 5) +row "3. != defined on one class", r + +cs = fresh(4); objs = cs.map(&:new) +r = [neq_site(objs, objs[0])] +m = Module.new { def ==(o) = o.is_a?(Integer) } +cs[0].include(m); cs[3].include(m) +r << neq_site(objs, 1) << neq_site(objs, objs[0]) << neq_site2(objs, 2) +row "4. == from a module included later", r + +cs = fresh(4); objs = cs.map(&:new) +r = [neq_site(objs, objs[0])] +m = Module.new { def !=(o) = false } +cs[2].include(m) +r << neq_site(objs, objs[0]) << neq_site2(objs, objs[2]) +row "5. != from a module included later", r + +cs = fresh(3); objs = cs.map(&:new) +r = [neq_site(objs, objs[1])] +def (objs[1]).==(o) = true +r << neq_site(objs, :x) << neq_site2(objs, objs[0]) +row "6. == on a singleton class", r + +cs = fresh(3); objs = cs.map(&:new) +r = [neq_site(objs, objs[0])] +objs[0].singleton_class +r << neq_site(objs, objs[0]) +row "6a. a singleton class without ==", r + +class MM + def method_missing(name, *args) = [:mm, name, args] + def respond_to_missing?(*) = true +end +class MMU < MM + undef_method :!= +end +cs = fresh(2); objs = cs.map(&:new) + [MMU.new, MM.new] +row "7. method_missing (undef !=)", [neq_site(objs.first(2), objs[0]), err { objs[2] != 1 }, neq_site(objs.values_at(0, 1, 3), objs[3])] + +module RefEq + refine(Object) { def ==(o) = true } +end +module RefNeq + refine(Object) { def !=(o) = :refined } +end +class UsesRef + using RefEq + def self.neq(objs, other) = (c = 0; N.times { |i| c += 1 if objs[i % objs.size] != other }; c) +end +class UsesRefNeq + using RefNeq + def self.neq(objs, other) = (r = nil; N.times { |i| r = (objs[i % objs.size] != other) }; r) +end +cs = fresh(3); objs = cs.map(&:new) +row "8. refinements of == and !=", [UsesRef.neq(objs, objs[0]), UsesRefNeq.neq(objs, objs[0]), neq_site(objs, objs[0])] + +b1 = Class.new(BasicObject); b2 = Class.new(BasicObject) +bo = [b1.new, b2.new] +row "9. BasicObject subclasses", [neq_site(bo, bo[0]), neq_site2(bo, bo[1])] +b1.class_eval { def ==(o) = true } +row "9a. == on a BasicObject subclass", [neq_site(bo, bo[1])] + +row "10. Integer against Float", [neq_site([1, 2, 3], 1.0), neq_site([1.0, 2, 3.5], 1), neq_site2([1, 2**70, 3], 2**70)] + +cmp = Class.new { include Comparable; attr_reader :v; def initialize(v) = (@v = v); def <=>(o) = v <=> o.v } +c1, c2 = cmp.new(1), cmp.new(1) +p1 = Class.new.new +row "11. Comparable's ==", [neq_site([c1, c2, p1], c1), neq_site2([p1, c2], c2)] + +S = Struct.new(:a) +row "12. Struct and plain", [neq_site([S.new(1), S.new(1), Object.new], S.new(1))] + +row "13. nil, true, String, Symbol and plain", [neq_site([nil, true, false, "a", :a, Object.new], nil), neq_site2(["a", "a".dup, Object.new], "a")] + +cs = fresh(4); objs = cs.map(&:new) +r = [neq_site(objs, objs[0])] +cs[1].class_eval { private def ==(o) = true } +r << neq_site(objs, objs[1]) +cs[3].class_eval { protected def ==(o) = true } +r << neq_site(objs, objs[3]) +row "14. private and protected ==", r + +cs = fresh(4); objs = cs.map(&:new) +r = [neq_site(objs, objs[0])] +cs[0].class_eval { def ==(o) = true } +cs[0].class_eval { remove_method :== } +r << neq_site(objs, objs[0]) +Object.class_eval { def ==(o) = equal?(o) || o == :eq_anything } +r << neq_site(objs, :eq_anything) << neq_site2(objs, objs[1]) +Object.class_eval { remove_method :== } +r << neq_site(objs, :eq_anything) +row "15. == defined then removed, and on Object", r + +cs = fresh(6); objs = cs.map(&:new) +ths = 4.times.map { |t| Thread.new { neq_site(objs, objs[t]) + neq_site2(objs, objs[t + 1]) } } +row "16. threads", ths.map(&:value) + +puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a0a7a8da1..49b4b261b 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -879,6 +879,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has objects, two Integers and two Strings (05a31f0a, merged into this branch after round nine): the cases this session's perf/neq1 found faster, without the Integer-against- Float one it found slower. + Round of 2026-11-27 (see Landed, perf/neqrule, not gated): the negated-builtin rule for plain objects is + shared by every class whose `==` is BasicObject's: a site over 2-60 classes no longer has a rule per class. 11. **The method JIT refuses a constant whose value is nil** ("constant without a value": it cannot tell nil from an autoload that has not run). Richards' `NO_WORK = nil` and `NO_TASK = nil` keep three methods out. See Rejected for why fixing only that is not @@ -1639,6 +1641,42 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/neqrule (2026-11-27) - `a != b` on plain objects is one rule for every class (gaps 10 and 12)** - + not gated. `DispatchIntrinsics.TryBuildNotEquals` (#215) binds `a != b` as `!a.equal?(b)` when the + receiver's `==` is BasicObject's, and `MaySpecialize` kept such rules out of IronRuby's shared rules, so a + site saw a rule per receiver class: over two to eight classes it missed its target on every other call into + the DLR's `UpdateAndExecute`, whose speed the CLR's dynamic PGO decided (gap 12, perf/twospeed2), and over + 60 it built a rule per class. Now `MaySpecialize` lets the rule be shared when the receiver is a plain + `RubyObject` (BasicObject subclasses included), the call has the intrinsic's shape, and the class resolves + `==` - public, without refinements, as BasicObject#!= calls it - to BasicObject#== (`IsSharableNotEquals`). + `ResolveShared` asks that both for the first bind and for every version `TryShareVersion` adds, so a class + whose `==` is another method (its own, a module's, a singleton's, Comparable's, a private or protected one, + one on Object) or whose `!=` is (defined, or undefined into method_missing) is never in the set, and + defining either re-versions the class. nil, booleans, Integers and Strings keep their rules per class. + `IR_SHARED_NEQ=0` turns it off. + - Ten processes each (`Util/bench/twospeed-shapes.rb`, ns, base / new): `neq2` 83-114 / 39-43, `neq3` 63-69 + / 41-45, `neq4` 65-80 / 41-51, `neq8` 89-102 / 44-48, `neq60` 542-571 / 42-44; level: `neq1`, `==` at + every count, calls at every count (`call60` 561-605 / 562-608). Instructions (callgrind, N=20000): + `neq2` 0.924, `neq4` 0.856, `neq8` 0.770, `neq60` 0.230; `neq1`, `eq1`, `eq2`, `eq4`, `call1`, `call2` + 1.000; `call60` 1.219 in one round after `neq60`, 1.138 alone, 1.005 (overlap) over two rounds - + a megamorphic site's binding, which the change does not reach (its method is a define_method one). + - AWFY, ten processes each, median of each process's last 8 of 15 iterations, ms, base / new: Richards + 2363 / 2357, Json 488 / 494, Permute 1195 / 1196, DeltaBlue 542 / 545, Bounce 396 / 392 - inside their + spreads. None of them has such a site: Richards' `NO_TASK != @current_task` has a nil receiver, Json's + `!=` are on Strings, which keep their rules. + - Matrices (`Util/perf/gate-matrices.rb`, base 99c1d2f against new, as built, NoJIT, NoJITCalls, + IR_LIGHT_FRAMES=0, IR_PARKED_SCOPES=0, the ReadyToRun host and IR_SHARED_NEQ=0): `Util/neq-share-matrix.rb` + (new: 1-8 classes over two sites; `==` defined on a class after the site bound, from a module included + later, on a singleton class, on a BasicObject subclass, private, protected, on Object and removed again; + `!=` defined and from a module; undef `!=` into method_missing; refinements of `==` and `!=`; Comparable; + Struct; nil, true, String, Symbol; Integer against Float; threads), shared-rule-light, jit, jit-calls, + dmeth-jit, refinement: same as CRuby in all seven modes; hot-shapes: the base's one row. ruby/spec + core/basicobject, core/comparable and language/send_spec: as the base (the known `into`/`to` errors). + IronRuby.Tests: 338 named (equality, Comparable, refinements, rules, sites, dispatch, Method*, Super*, + Alias*, BasicObject, singleton, send, define_method, the JIT) pass. + - For the gate: the shared rule's set now decides `!=` for every plain-object class a program has; the + cases above are the ones that must leave a class out. + - **perf/twospeed (2026-11-27) - an interpreted rule stuck before its compiled one runs compiled (gap 12, DLR patch 0111)** - not gated. What decides the speed: `recv != other` over four or eight plain classes is served by IronRuby's shared rule (one rule whose test is a set of class versions, handed to From 0b88dd07bd87dc42a538b0d8413b87cf2356ef8f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:56:19 +0000 Subject: [PATCH 169/439] Module#name and #to_s: US-ASCII for an ASCII name, binary when anonymous A module's name is a symbol's string in MRI, so Object.name and Object.to_s are US-ASCII, as is a singleton class's "#"; an anonymous module's "#" comes from rb_sprintf and is binary. A non-ASCII name stays UTF-8, and a temporary name keeps the encoding it was given. IronRuby made all of them UTF-8, so for example [Object.name, "a"].join was UTF-8 where CRuby's is US-ASCII. Util/converter-matrix.rb now agrees with CRuby 4.0 (the class-name cells of its LAST_ERROR rows were the last difference). The name-, inspect-, encoding-, interpolation- and marshal-related matrices are unchanged; spec/core/module, core/class, core/kernel, core/string, core/marshal and language show only the known into/to errors; 225 IronRuby.Tests about modules, classes, encodings, inspect and names pass, and Module_NameEncoding1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 30 +++++++++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 26 ++++++++++++++++----- 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index b1254c44c..4a587d52c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1066,6 +1066,7 @@ public Tests(Driver/*!*/ driver) { Encoding_Converter2, Encoding_ErrorMessageBinary1, Encoding_ConvPathDecoratorBinary1, + Module_NameEncoding1, Encoding_StatelessIso2022Jp1, Encoding_AsciiIncompatible1, Encoding_AsciiIncompatibleLines1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index d4b190b16..c609710f9 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -3321,6 +3321,36 @@ public void Encoding_ConvPathDecoratorBinary1() { "); } + /// + /// A module's name is a symbol's string in MRI, US-ASCII when it is ASCII, and so is the + /// description of a singleton class; an anonymous module's "#" is a binary string. + /// A temporary name keeps its own encoding. + /// + public void Module_NameEncoding1() { + TestOutput(@" +module M; class K; end; end +p Object.name.encoding, Object.to_s.encoding, M::K.name.encoding, M::K.inspect.encoding +p Object.singleton_class.to_s.encoding, Object.new.singleton_class.to_s.encoding +p Class.new.to_s.encoding, Module.new.inspect.encoding +p [Object.name, ""a""].join.encoding, ""#{Object}"".encoding +c = Class.new +c.set_temporary_name(""fake"") +p c.name.encoding +", @" +# +# +# +# +# +# +# +# +# +# +# +"); + } + public void Encoding_Converter1() { TestOutput(@" def t diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index f88eb0fd5..d40fa910e 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -4344,16 +4344,25 @@ public MutableString GetNameString(RubyContext/*!*/ context) { // another runtime sees the name decorated with the runtime id; not worth caching if (context != _context) { - return MutableString.CreateMutable(GetName(context), context.GetIdentifierEncoding()).FreezeInterned(); + string name = GetName(context); + return MutableString.CreateMutable(name, NameEncoding(context, name)).FreezeInterned(); } var result = _nameString; if (result == null) { - _nameString = result = MutableString.CreateMutable(_name, context.GetIdentifierEncoding()).FreezeInterned(); + _nameString = result = MutableString.CreateMutable(_name, NameEncoding(context, _name)).FreezeInterned(); } return result; } + /// + /// MRI's module names are symbols' strings: US-ASCII when the name is ASCII ("Object"), + /// UTF-8 otherwise. A temporary name keeps the encoding it was given, which here is UTF-8. + /// + private RubyEncoding/*!*/ NameEncoding(RubyContext/*!*/ context, string/*!*/ name) { + return !_isTemporaryName && name.IsAscii() ? RubyEncoding.Ascii : context.GetIdentifierEncoding(); + } + public MutableString GetDisplayName(RubyContext/*!*/ context, bool showEmptyName) { if (IsSingletonClass) { RubyClass c = (RubyClass)this; @@ -4400,12 +4409,18 @@ public MutableString GetDisplayName(RubyContext/*!*/ context, bool showEmptyName c = (RubyClass)module; } - return result.Append('>', nestings); + result.Append('>', nestings); + if (result.IsAscii()) { + // MRI: "#" is US-ASCII, as the name inside it is + result.ForceEncoding(RubyEncoding.Ascii); + } + return result; } else if (_name == null) { if (showEmptyName) { return null; } else { - MutableString result = MutableString.CreateMutable(context.GetIdentifierEncoding()); + // MRI makes "#" with rb_sprintf, a binary string + MutableString result = MutableString.CreateMutable(RubyEncoding.Binary); result.Append("#<"); result.Append(_context.GetClassOf(this).GetName(context)); result.Append(':'); @@ -4414,7 +4429,8 @@ public MutableString GetDisplayName(RubyContext/*!*/ context, bool showEmptyName return result; } } else { - return MutableString.CreateMutable(GetName(context), context.GetIdentifierEncoding()); + string name = GetName(context); + return MutableString.CreateMutable(name, NameEncoding(context, name)); } } From 9d05ecac2d8bf825fa4f3114eeb01c4643db6ee4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:03:45 +0000 Subject: [PATCH 170/439] Let an eval'd text with defined? share its compiled code perf/erb36's screen kept an eval'd text's compiled code only when nothing in it keeps state of one eval, and refused any defined?. Of the 80 ERB templates of the standard library (rdoc's .rhtml, bundler's .tt) and erb-shapes' page, 5 have a defined? - all of a local (defined?(current), defined?(klass)) - and 3 nothing else; a refused template pays the transformation and the light compile on every render, 2.7 times a shared one. defined? keeps only what its operand's code keeps: of a local, the answer the compile found in the locals the cache key holds; of a call, a call site; of a constant, a constant's cache, which an allowed constant read keeps too; of an instance, global or class variable, a runtime call. The screen walks into the operand, so defined?(yield) and defined?(super) stay refused by their own nodes. IR_EVAL_SHARE_DEFINED=0 refuses it again. Instructions a render (Util/perf/callgrind/count.sh, switch off -> on): the page with a defined?(title) 3,399,985 -> 1,251,786 (0.368); the plain page, the page with a regexp (still refused) and eval('1 + 1') unchanged. Timed alone 639 -> 235 us. Templates of the stdlib shared: 69 -> 72 of 80. Util/eval-defined-matrix.rb (new) evaluates one text while what its answer depends on changes in between - a method, a constant, self, the binding's locals, a global - plus defined?(yield)/(super), __FILE__/__LINE__, a method's frame and the top level, and threads; it prints CRuby 4.0's output on the unchanged build and on this one in every mode. eval-locals, erb-escape, lexical-light, block-scope-reuse, hot-shapes and eval-matrix print what they did. Specs core/kernel/eval, core/binding, core/basicobject/instance_eval and library/erb give the same results on both builds. Eval_SharedDefined1 is new. erb-shapes.rb gains erb_eval_regexp and erb_eval_defined. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 36 ++++++++++ Src/Ruby/Runtime/EvalCodeCache.cs | 16 ++++- Util/bench/erb-shapes.rb | 5 ++ Util/eval-defined-matrix.rb | 95 +++++++++++++++++++++++++ 5 files changed, 150 insertions(+), 3 deletions(-) create mode 100644 Util/eval-defined-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 6259729f4..28711ce6e 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1297,6 +1297,7 @@ public Tests(Driver/*!*/ driver) { TopLevelBinding_RubyProgram, EvalWithProcBinding1, Eval_LocalVariableSites1, + Eval_SharedDefined1, ModuleEvalProc1, ModuleEvalProc2, ModuleEvalProc3, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 9dcfa5484..addfc687b 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8054,6 +8054,42 @@ def b_with(**h) = binding.tap { |b| h.each { |k, v| b.local_variable_set(k, v) } "); } + /// + /// IR_EVAL_SHARE_DEFINED: a text with `defined?' shares its compiled code between evals (EvalCodeCache), and the + /// answers follow what changed in between - the binding's locals, a method and a constant defined and removed, + /// self's instance variables; `defined?(yield)' stays refused (Util/eval-defined-matrix.rb). + /// + public void Eval_SharedDefined1() { + TestOutput(@" +require 'ruby4' +def b_with(**h) = binding.tap { |b| h.each { |k, v| b.local_variable_set(k, v) } } +T = ""[defined?(cur) ? cur : :none, defined?(dm_t), defined?(DC_T), defined?(@iv)]"" +class P; def initialize(n) = (@iv = n if n); def b = binding; end +r = [] +r << eval(T, b_with(cur: 1)) +r << eval(T, b_with) +Object.send(:define_method, :dm_t) { 1 } +Object.const_set(:DC_T, 1) +r << eval(T, b_with(cur: 2)) +Object.send(:remove_method, :dm_t) +Object.send(:remove_const, :DC_T) +r << eval(T, b_with) +r << eval(T, P.new(5).b) << eval(T, P.new(nil).b) +def blk(&b) = eval(""defined?(yield) ? yield : :noblock"", binding) +r << blk << blk { 1 } +r.each { |x| p x } +", @" +[1, nil, nil, nil] +[:none, nil, nil, nil] +[2, ""method"", ""constant"", nil] +[:none, nil, nil, nil] +[:none, nil, nil, ""instance-variable""] +[:none, nil, nil, nil] +:noblock +1 +"); + } + /// /// A method that reads or writes a global is a light frame too (MethodDefinition.IsLightGlobal): every global but $~ and /// $_ is the runtime's, and the frame reads and writes it through the declaring scope. A name that comes to denote $~ or $_ diff --git a/Src/Ruby/Runtime/EvalCodeCache.cs b/Src/Ruby/Runtime/EvalCodeCache.cs index dafa2c6cd..cf7195c45 100644 --- a/Src/Ruby/Runtime/EvalCodeCache.cs +++ b/Src/Ruby/Runtime/EvalCodeCache.cs @@ -22,8 +22,9 @@ namespace IronRuby.Runtime { /// ones - a /o regexp, a regexp or range literal (one object per eval), END {}, and the same one /// level down in a `def' or a block compiled at its first call. So a text is kept only when its /// whole tree, blocks included, holds none of the nodes whose code keeps such a value - /// (): no regexp, range, flip-flop, END, defined?, super, yield, and no - /// def, class or module body (whose code would also be one for two evals). What is left - calls, + /// (): no regexp, range, flip-flop, END, super, yield, and no + /// def, class or module body (whose code would also be one for two evals). A `defined?' is let in + /// (perf/evalscreen): it keeps what its operand's code keeps. What is left - calls, /// locals, string, symbol and number literals, blocks, constants, conditionals, loops - keeps /// only call-site caches, which a method body run again shares too; a frozen string literal is /// interned, the same object for every eval, as MRI's is. @@ -82,6 +83,11 @@ internal static bool IsShareable(SourceUnitTree/*!*/ ast) { return screen.Shareable; } + /// + /// IR_EVAL_SHARE_DEFINED=0 refuses a text with a `defined?' again, as perf/erb36's screen did (see Screen). + /// + private static readonly bool ShareDefinedEnabled = Environment.GetEnvironmentVariable("IR_EVAL_SHARE_DEFINED") != "0"; + private sealed class Screen : Walker { internal bool Shareable = true; @@ -99,7 +105,11 @@ private bool Refuse() { public override bool Enter(RegularExpression/*!*/ node) => Refuse(); public override bool Enter(RegularExpressionCondition/*!*/ node) => Refuse(); public override bool Enter(ShutdownHandlerStatement/*!*/ node) => Refuse(); - public override bool Enter(IsDefinedExpression/*!*/ node) => Refuse(); + // `defined?' keeps what the code of its operand keeps and nothing more (IR_EVAL_SHARE_DEFINED): of a local, the + // answer the compile found in the locals the key holds; of a call, a call site; of a constant, a constant's cache, + // which a constant read keeps too; of an instance, global or class variable, a runtime call. The walk goes on into + // the operand, so `defined?(yield)' and `defined?(super)' are refused as their YieldCall and SuperCall are. + public override bool Enter(IsDefinedExpression/*!*/ node) => ShareDefinedEnabled || Refuse(); public override bool Enter(SuperCall/*!*/ node) => Refuse(); public override bool Enter(YieldCall/*!*/ node) => Refuse(); diff --git a/Util/bench/erb-shapes.rb b/Util/bench/erb-shapes.rb index cb052209e..47c4b22d9 100644 --- a/Util/bench/erb-shapes.rb +++ b/Util/bench/erb-shapes.rb @@ -71,3 +71,8 @@ def fresh_v = (b = binding; b.local_variable_set(:v, 1); b) LOOP_S = "-> { i = 0; s = 0; w = v; while i < 1000; s += w; i += 1; end; s }.()" t("eval_reads_v", n(30)) { |n| s = 0; n.times { s += eval(LOOP_V, fresh_v, '(reads)', 0) }; s } t("eval_reads_static", n(30)) { |n| s = 0; n.times { s += eval(LOOP_S, fresh_v, '(reads)', 0) }; s } +# the template with what perf/erb36's screen refuses (EvalCodeCache.IsShareable): a regexp literal, a defined? of a local +SRC_RE = ERB.new(PAGE.sub("<%= title %>", "<%= title.sub(/T/, 't') %>"), trim_mode: '-').src +SRC_DEF = ERB.new(PAGE.sub("<%= title %>", "<%= defined?(title) ? title : '' %>"), trim_mode: '-').src +t("erb_eval_regexp", n(300)) { |n| s = 0; n.times { |i| s += crc(eval(SRC_RE, fresh_top("T#{i & 3}"), '(erb)', 0)) }; s } +t("erb_eval_defined", n(300)) { |n| s = 0; n.times { |i| s += crc(eval(SRC_DEF, fresh_top("T#{i & 3}"), '(erb)', 0)) }; s } diff --git a/Util/eval-defined-matrix.rb b/Util/eval-defined-matrix.rb new file mode 100644 index 000000000..78ba58e20 --- /dev/null +++ b/Util/eval-defined-matrix.rb @@ -0,0 +1,95 @@ +# Differential matrix for `defined?' in an eval'd text whose compiled code is kept and shared by every eval of the +# same text (EvalCodeCache; IR_EVAL_SHARE_DEFINED lets such a text in). Each probe evaluates one text many times +# while what its answer depends on changes between the evals: a method defined, made private, removed; a constant +# defined and removed; another self; a binding with the local and one without; a global, an instance and a class +# variable set and unset. And what the key has to tell apart: __FILE__ and __LINE__, a method's frame and the top +# level, threads. Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/eval-defined-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/eval-defined-matrix.rb > /tmp/on.txt 2>&1 +# IR_EVAL_SHARE_DEFINED=0 ./ir.sh Util/eval-defined-matrix.rb > /tmp/off.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt + +N = 3000 + +def t(label) + print label.ljust(52), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def b_with(**h) + b = binding + h.each { |k, v| b.local_variable_set(k, v) } + b +end + +# ---------------------------------------------------------------- 1. what the answer depends on changes + +class Probe + def initialize(n) = (@iv = n if n) + def b = binding +end +t('defined?(local) with and without the local') { |i| eval("defined?(cur) ? cur : :none", i.even? ? b_with(cur: i % 3) : b_with) } +t('defined?(method), defined and removed') do |i| + Object.send(:define_method, :dm_probe) { 1 } if i == 1000 + Object.send(:remove_method, :dm_probe) if i == 2000 + eval("defined?(dm_probe)", b_with) +end +class Vis; def pub = 1; end +t('defined?(o.m), made private and public') do |i| + Vis.send(:private, :pub) if i == 1000 + Vis.send(:public, :pub) if i == 2000 + eval("defined?(o.pub)", b_with(o: Vis.new)) +end +t('defined?(Const), defined and removed') do |i| + Object.const_set(:DC_PROBE, 1) if i == 1000 + Object.send(:remove_const, :DC_PROBE) if i == 2000 + eval("defined?(DC_PROBE)", b_with) +end +t('defined?(A::B)') do |i| + Object.const_set(:DCA, Module.new) if i == 500 + DCA.const_set(:B, 1) if i == 1500 + DCA.send(:remove_const, :B) if i == 2500 + eval("defined?(DCA::B)", b_with) +end +t('defined?(@iv) with another self') { |i| eval("defined?(@iv)", Probe.new(i.even? ? i : nil).b) } +t('defined?($g) set and unset') do |i| + $dg_probe = 1 if i == 1000 + $dg_probe = nil if i == 2000 + eval("defined?($dg_probe)", b_with) +end +class CV; @@cv = 1; def self.b = binding; end +t('defined?(@@cv) in a class\'s frame') { |i| eval("defined?(@@cv)", CV.b) } +t('defined?(String), defined?(::Kernel)') { |i| eval("[defined?(String), defined?(::Kernel)]", b_with) } +t('defined?(x = 1), defined?(1 + 1), defined?(nil)') { |i| eval("[defined?(x = 1), defined?(1 + 1), defined?(nil)]", b_with) } +t('defined?(puts), defined?(self)') { |i| eval("[defined?(puts), defined?(self)]", b_with) } + +# ---------------------------------------------------------------- 2. what stays refused, and what the key tells apart + +def with_block = eval("defined?(yield) ? yield : :noblock", binding) +t('defined?(yield), with and without a block') { |i| i.even? ? with_block { i % 2 } : with_block } +class SupBase; def m = :base; end +class SupSub < SupBase; def m = eval("defined?(super) ? super : :nosuper", binding); def n = eval("defined?(super) ? 1 : :nosuper", binding); end +t('defined?(super)') { [SupSub.new.m, SupSub.new.n] } +t('__FILE__ and __LINE__ with the file and line given') { |i| eval("[defined?(x), __FILE__, __LINE__]", b_with, "f#{i % 2}.rb", i % 3) } +def in_method(cur) = eval("defined?(cur) ? cur : :none", binding) +t('in a method and at the top level') { |i| i.even? ? in_method(i % 3) : eval("defined?(cur) ? cur : :none", b_with) } +t('a cached text in four threads') do |i| + next nil unless i % 500 == 0 + 4.times.map { |k| Thread.new { 100.times.map { eval("defined?(cur) ? cur : :none", k.even? ? b_with(cur: k) : b_with) }.uniq } }.map(&:value) +end + +# ---------------------------------------------------------------- 3. templates + +require 'erb' +T = ERB.new("<%= defined?(current) ? current : 'none' %>:<%= defined?(klass) ? 1 : 0 %>") +t('ERB with defined?') { |i| i.even? ? T.result_with_hash(current: i % 3) : T.result_with_hash(klass: 1) } From 779d87cfb0469a884a87c494c8a95ab78a711160 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:03:45 +0000 Subject: [PATCH 171/439] Ledger: perf/evalscreen landed (instructions only, not gated); gap 31: what templates hit, and why the regexp literal is left Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 4bf8070bc..6231849e4 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1564,6 +1564,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (`LocalVariableSite`); a render 0.86-0.88 of its instructions, a loop of eval'd reads 0.37. Left: the first access of each site per render (a fresh binding defines `_erbout`, which invalidates every site), and the cost of the eval itself. + perf/evalscreen (Landed): of the 80 ERB templates of the standard library (rdoc's 40 + `.rhtml`, bundler's 39 `.tt`) and erb-shapes' page, 69 were shared and 11 refused - a regexp + literal in 6, `defined?` in 5 (all of a local), a range in 2 (bundler's, run once); a refused + template costs 2.7 times a shared one (3.40M instructions a render against 1.27M). `defined?` + is let in now: 72 of 80. Left: the regexp literal. CRuby makes a new Regexp per eval of the + same text (`eval("/a/").equal?(eval("/a/"))` is false; one eval's block gets the same one on + every call), so sharing the code needs the literal's cache box per eval - and a block of the + text reaches nothing per eval: it is compiled apart (BlockDispatcher) and sees only the + scope, which for `eval(s, binding)` is the binding's own. Untried: carrying an eval's literal + boxes on the Procs its code instantiates. 32. **A singleton class, and a method defined at run time, cost 25 to 60 times CRuby's** (`Object.new.singleton_class` 17 us, `def o.x` 18, `define_singleton_method` 46, `Class.new` 12, with a `def` 37), and `OpenStruct.new(h)` of three keys, which @@ -1778,6 +1788,49 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/evalscreen (/perf-step, 2026-11-27, on 4320d4a + perf/lexical b45360c) - an eval'd + text with `defined?` shares its compiled code (`IR_EVAL_SHARE_DEFINED`, gap 31)** - + instructions only, not gated. Measured first, which refusals of perf/erb36's screen real + templates hit (ERB.new(...).src of every `.erb`, `.rhtml` and `.tt` of Src/StdLib and + erb-shapes' page, parsed with Prism under CRuby): 80 templates, 69 shared, 11 refused - a + regexp literal in 6 (4 alone: `/^\w+\./m`, `%r{\A[^/]+(?=/)}`), `defined?` in 5 (3 alone, all + of a local: `defined?(current)`, `defined?(klass)`), a range in 2 (bundler's `0..1`, run once + per `bundle gem`); no `yield`, `super` or definitions. A refused render costs 2.7 times a + shared one: `erb_eval_regexp` 3,399,071 and `erb_eval_defined` 3,399,985 instructions against + `erb_eval_top` 1,271,530 (the page with one regexp, or one `defined?(title)`). + - The regexp, the most common, was not taken: CRuby makes a new Regexp per eval of the same + text (three evals, three objects; one eval's block, the same object on every call), so a + shared Regexp is observable through `equal?` and `object_id`, and making the cache box per + eval needs state a block of the text can reach - it cannot: a block is compiled apart + (BlockDispatcher) and sees only its scope, the binding's own (see gap 31). + - `defined?` keeps only what its operand's code keeps: of a local, the answer the compile + found in the locals the cache key holds; of a call, a call site; of a constant, a constant's + cache (which an allowed constant read keeps too); of an instance, global or class variable, + a runtime call. The screen walks into the operand, so `defined?(yield)` and `defined?(super)` + stay refused by their YieldCall and SuperCall. One line in `EvalCodeCache.Screen`, under the + switch. Templates shared: 69 -> 72 of 80 (darkfish's and aliki's `_head` and darkfish's + `index`; `_sidebar_pages` also has a regexp). + - Instructions a render (`Util/perf/callgrind/count.sh`, N=1000, switch off -> on): + `erb_eval_defined` 3,399,985 -> 1,251,786 (0.368); `erb_eval_top` 1,271,530 -> 1,270,311, + `erb_eval_regexp` 3,399,071 -> 3,394,511, `eval_small` 55,414 -> 55,414. Timed alone, + `erb_eval_defined` 639 -> 235 us. (Several callgrind processes of the switch-off arm died + with exit 1 and no output after a few shapes - every eval of a refused text compiles new + code under valgrind; run shape by shape they finish.) + - `Util/eval-defined-matrix.rb` (new: `defined?` of a local with and without it in the + binding, a method defined and removed, `o.m` made private and public, a constant and + `A::B` defined and removed, `@iv` under another self, `$g`, `@@cv`, String and ::Kernel, + an assignment, an expression, nil, `puts`, self; `defined?(yield)` and `defined?(super)`, + `__FILE__`/`__LINE__` with the file and line given, a method's frame and the top level, + four threads on one cached text, ERB) prints CRuby 4.0's output on the unchanged build, and + on the change with the switch on and off, `IR_EVAL_LOCAL_CACHE=0`, `IR_LIGHT_FRAMES=0`, + `-X:NoJIT -X:NoOSR` and `-X:NoJITCalls`; so do eval-locals, erb-escape, lexical-light, + block-scope-reuse and hot-shapes, and eval-matrix prints the unchanged build's. ruby/spec + `core/kernel/eval_spec.rb` 57 / 0, `core/binding` 98 / 0, `library/erb` 53 / 0, + `core/basicobject/instance_eval_spec.rb` 41 with the 3 known into/to errors - the same on + both builds. IronRuby.Tests `Eval_SharedDefined1` (new; passes with the switch off too) and + 29 named eval, binding and defined? tests pass. The round's base needed DLR patches 0111 and + 0112 applied to the DLR checkouts. + - **perf/evallocals (/perf-step, 2026-11-27, on b887bc1 + perf/lexical a87b5dc) - a site of eval'd code remembers where a local it knows by name resolved (`IR_EVAL_LOCAL_CACHE`, gap 31)** - instructions only, not gated. Eval'd code reads a local the text does not declare From 2b924094d4011bee2d62565aad20919c59fe3df8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:07:30 +0000 Subject: [PATCH 172/439] Marshal: write a raised exception's "bt_locations", and its cause last Since 3.4 MRI keeps the backtrace of a raise in the exception's "bt_locations" internal ivar as well, and Marshal.dump writes it: as a link to the "bt" array while that is still the raise's, as the raise's strings once #set_backtrace replaced it, and not at all for an exception never raised, raised with #raise's backtrace argument, or loaded from a dump. It and "cause" are set at the raise, so they follow the ivars #initialize set (KeyError's receiver and key, the user's own). IronRuby wrote neither "bt_locations" nor that order, so a raised exception's dump differed from CRuby's byte for byte (one ivar fewer). The prelude's #set_backtrace now keeps the raise's strings for it. Util/marshal-matrix.rb now agrees with CRuby 4.0; core/marshal and core/exception specs pass, and Marshal_ExceptionBtLocations1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 32 +++++++++++++++++++++ Src/Libraries/Builtins/Marshal.cs | 37 +++++++++++++++++++------ Src/StdLib/ironruby/ruby4.rb | 3 ++ 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 4a587d52c..f35a0bcc2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1076,6 +1076,7 @@ public Tests(Driver/*!*/ driver) { Marshal_LoadFloat1, Marshal_SetIVars1, Marshal_NameError1, + Marshal_ExceptionBtLocations1, Marshal_LoadChecks1, Integer_SqrtPowDigits1, Prelude_DataStructErrors1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index c609710f9..f411619a6 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -4000,6 +4000,38 @@ class MySet < Set; end "); } + /// + /// MRI keeps the backtrace of a raise in "bt_locations" and Marshal writes it: as a link to "bt" + /// while that is still the raise's, as the raise's strings once #set_backtrace replaced it, and not + /// at all for an exception never raised or raised with a backtrace of #raise's argument. It and the + /// cause come after the instance variables set before the raise. + /// + public void Marshal_ExceptionBtLocations1() { + TestOutput(@" +require 'ruby4' +def ivars(e) = Marshal.dump(e).scan(/:[\x06-\x16]([a-z_@?]+)(.)/).map(&:join) +e = RuntimeError.new(""x""); p ivars(e) +e.set_backtrace([""a""]); p ivars(e) +begin; raise ""y""; rescue => f; end +p ivars(f) +f.set_backtrace([""b""]); p ivars(f) +p Marshal.load(Marshal.dump(f)).backtrace == [""b""] +begin; raise RuntimeError, ""z"", [""s1""]; rescue => g; end +p ivars(g), ivars(Marshal.load(Marshal.dump(g))) +begin; begin; raise ""in""; rescue; e2 = KeyError.new(""o"", receiver: 1, key: 2); e2.instance_variable_set(:@u, 1); raise e2; end; rescue => c; end +p ivars(c) +", @" +[""mesgI"", ""bt0""] +[""mesgI"", ""bt[""] +[""mesgI"", ""bt["", ""bt_locations@\a""] +[""mesgI"", ""bt["", ""bt_locations[""] +true +[""mesgI"", ""bt[""] +[""mesgI"", ""bt[""] +[""mesgI"", ""bt["", ""receiveri\x06"", ""keyi\a"", ""@ui\x06"", ""causeo:"", ""bt_locations@\v""] +"); + } + /// /// An exception MRI dumped loads as MRI loads it: "bt_locations" is not an instance variable of the result, which /// has no Locations; a NoMethodError's message dumped as a NameError::message is its string, and NameError's name, diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index b4d0b5eca..e0dddf740 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -730,8 +730,23 @@ private void WriteException(Exception/*!*/ exception, string[]/*!*/ instanceName } } + // MRI keeps the backtrace of the raise in "bt_locations" as well and writes it out: + // the very array of "bt" (a link) while the exception still has the backtrace it + // was raised with, the raise's strings once #set_backtrace replaced it, and nothing + // for an exception that was never raised (or got its backtrace from #raise's + // argument, or from Marshal). + object locations = null; + if (data.HasBacktrace) { + object value; + if (!_context.TryGetInstanceVariable(exception, RubyUtils.GetCoreStateInstanceVariableName("@__backtrace_from_strings__"), out value)) { + locations = data.Backtrace; + } else if (_context.TryGetInstanceVariable(exception, RubyUtils.GetCoreStateInstanceVariableName("@__raise_backtrace_strings__"), out value)) { + locations = value; + } + } + WriteObject(exception); - WriteInt32(2 + (isNameError ? 1 : 0) + (isNoMethodError ? 2 : 0) + (cause != null ? 1 : 0) + internalNames.Count + instanceNames.Length); + WriteInt32(2 + (locations != null ? 1 : 0) + (isNameError ? 1 : 0) + (isNoMethodError ? 2 : 0) + (cause != null ? 1 : 0) + internalNames.Count + instanceNames.Length); WriteSymbol("mesg", RubyEncoding.Binary); object message = data.Message; var messageString = message as MutableString; @@ -757,13 +772,6 @@ private void WriteException(Exception/*!*/ exception, string[]/*!*/ instanceName WriteAnObject(data.PrivateCall); } - // MRI writes the cause as another pseudo instance variable, and only when the - // exception has one - an exception that was never raised inside a rescue has not. - if (cause != null) { - WriteSymbol("cause", RubyEncoding.Binary); - WriteAnObject(cause); - } - foreach (string name in internalNames) { object value; _context.TryGetInstanceVariable(exception, HiddenIVarName(name), out value); @@ -772,6 +780,19 @@ private void WriteException(Exception/*!*/ exception, string[]/*!*/ instanceName } WriteIVarPairs(exception, instanceNames); + + // MRI writes the cause as another pseudo instance variable, and only when the + // exception has one - an exception that was never raised inside a rescue has not. + // It and "bt_locations" are set when the exception is raised, so they come after + // the instance variables #initialize set. + if (cause != null) { + WriteSymbol("cause", RubyEncoding.Binary); + WriteAnObject(cause); + } + if (locations != null) { + WriteSymbol("bt_locations", RubyEncoding.Binary); + WriteAnObject(locations); + } } private void WriteUsingDump(object/*!*/ obj) { diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 1f9bac817..3cda6ac2c 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -12550,6 +12550,9 @@ def set_backtrace(value) # was raised keeps the ones it was raised with, and one that never was gets none, # however many strings it is given. @__backtrace_locations__ = backtrace_locations + # Marshal writes the raise's backtrace as "bt_locations" beside the new "bt", as MRI + # does, so the strings it was raised with are kept for it + @__raise_backtrace_strings__ ||= backtrace if @__backtrace_locations__ @__backtrace_from_strings__ = true __core_set_backtrace__(value) end From 3f0ebccba362765f1d4055e1a21084db60aafb1d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:09:33 +0000 Subject: [PATCH 173/439] IO#write: text bound for UTF-16/32 goes through UTF-8 first MRI's do_writeconv takes text written to an IO whose external encoding is not ASCII-compatible to that encoding's ASCII-compatible partner first (writeconv_asciicompat, UTF-8 for UTF-16BE), and only then into the external encoding. A binary "\xFF" written to a "w:utf-16be" IO therefore fails on that leg alone: "\"\xFF\" from ASCII-8BIT to UTF-8", where String#encode("UTF-16BE") reports the whole path. IronRuby encoded straight to the external encoding and gave the String#encode message. The same options (invalid:/undef: replace) apply to both legs, which writes the same bytes as before. Util/io-conversion-matrix.rb now agrees with CRuby 4.0; io-encoding and io-transcode matrices are unchanged, the IO write/print/puts/ set_encoding/syswrite/binwrite and File.open specs pass, and Io_WriteViaAsciiCompat1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IoTests.cs | 39 +++++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 4 +++ 3 files changed, 44 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f35a0bcc2..8d5a3f1f3 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1124,6 +1124,7 @@ public Tests(Driver/*!*/ driver) { Io_LineReaders2, Io_LineReaders3, Io_UngetcConverted1, + Io_WriteViaAsciiCompat1, Io_GetsLongLineFromPipe1, Io_UnreadPushedBack1, Io_WideLineReaders1, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index 2a03b3cc5..fd5469fd0 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -839,6 +839,45 @@ puts 42 Assert(actual == expected, actual); } + /// + /// Text written to an IO whose external encoding is not ASCII-compatible goes to that encoding's + /// ASCII-compatible one (UTF-8) first, as in MRI's do_writeconv, so a byte that cannot get there is + /// reported on that leg alone. + /// + public void Io_WriteViaAsciiCompat1() { + TestOutput(@" +require 'ruby4' +p((""\xFF"".b.encode(""UTF-16BE"") rescue $!)) +p((""\xFF"".b.encode(""EUC-JP"") rescue $!)) +p((""\xFF"".b.encode(""UTF-8"") rescue $!)) +_r, w = IO.pipe +w.set_encoding(""UTF-16BE"") +p((w.write(""\xFF"".b) rescue $!)) +p((w.write(""\xFF"".dup.force_encoding(""ISO-8859-1"")) rescue $!)) +w.set_encoding(""EUC-JP"") +p((w.write(""\xFF"".b) rescue $!)) +r, w = IO.pipe +w.set_encoding(""UTF-16LE"") +w.write(""ab"", ""\u00e9"".encode(""ISO-8859-1""), ""\xA4\xA2"".dup.force_encoding(""EUC-JP"")) +w.close +p r.read.b +r, w = IO.pipe +w.set_encoding(""UTF-16BE"", invalid: :replace, undef: :replace) +w.write(""\xFF"".b, ""a\xFFb"".dup.force_encoding(""UTF-8"")) +w.close +p r.read.b +", @" +# +# +# +# +2 +# +""a\x00b\x00\xE9\x00B0"" +""\xFF\xFD\x00a\xFF\xFD\x00b"" +"); + } + /// /// IO#ungetc on a stream that converts what it reads - text mode, or an internal encoding - puts the text in /// a buffer of characters already converted, as MRI's rb_io_ungetc puts it in fptr->cbuf: the readers of diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 3cda6ac2c..8d145c73e 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -11377,6 +11377,10 @@ def __encode_for_write__(text) end return ec.convert(text.encode(::Encoding::UTF_8, **options)) end + # MRI's do_writeconv takes text bound for an encoding that is not ASCII-compatible + # (UTF-16BE) to that encoding's ASCII-compatible one first (UTF-8), so a byte that + # fails is reported on that leg: "\xFF" from ASCII-8BIT to UTF-8. + text = text.encode(::Encoding::UTF_8, **options) unless target.ascii_compatible? || text.encoding == ::Encoding::UTF_8 text.encode(target, **options) end private :__encode_for_write__ From 6f0a9fbd4ba0031ff2c3fb987dab22a6c7021143 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:14:44 +0000 Subject: [PATCH 174/439] JIT: attribute reads and writes on an unsampled local; nested classes as candidates An attribute read or write on a local of the method the profile has no sample of (`top = @piles[pile]; top.next = nil` in AWFY Towers' pop_disk_from, `x.right` in CD) bailed. UnsampledAttrVariable now names the variable: the one the classes a call on the local was inlined for agree on, or else the one every class whose own method of the name is written in Ruby names, each a public accessor of the same variable. The read and the write go through the sampled path's sites, which check the class they meet and deopt (a write before storing); the effect rule is unchanged. JitStub.ClassesDefining walks Object's subclasses instead of its constants for the candidates of an unsampled call (IR_JIT_NESTED=0 turns it off): 82% of the stdlib's leaf-shaped instance methods are in nested classes, and a nested receiver whose method's name a top-level class also defines was inlined for that class alone and deopted on every call. The screen's leaf hint keeps Object's constants (with every class it wrapped a method only to decline it on app-shapes). Towers' pop_disk_from and CD's RedBlackTree#get specialize; Havlak's split_bucket now declines at the effect rule (and is called 459 times an iteration). Census: one method up (Rake::Scope#trim), none down; app-shapes and gem list make the same decisions. Callgrind new/base: ns_at_chain 0.617, towers_pop 0.814, chain_len 0.532, controls 1.000; Havlak, Towers and CD times within their spread. unsampled-matrix grows to 32 cases (nested classes; writes with a frozen receiver, a private writer, one private in a subclass, method_missing, a reading thread) and prints CRuby's output on both builds in every mode; the jit, jit-calls, jit-const, ivar, deadconst, hot-shapes and inline matrices are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5NtGd2eCVJ7fCeWbG --- Src/Ruby/Builtins/RubyModule.cs | 8 + Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs | 26 +-- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 63 ++++-- Src/Ruby/Runtime/Jit/JitRuntime.cs | 8 + Src/Ruby/Runtime/Jit/JitStub.cs | 60 ++++-- Util/bench/havlak-shapes.rb | 56 ++++++ Util/perf/LEDGER.md | 56 ++++++ Util/unsampled-matrix.rb | 210 +++++++++++++++++++- 8 files changed, 442 insertions(+), 45 deletions(-) diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 05b7c1eb4..3cc38ffe6 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -1045,6 +1045,14 @@ internal WeakList/*!*/ DependentClasses { } } + /// The dependent classes (DependentClasses) without making the list: null if there are none. + internal WeakList DependentClassesOrNull { + get { + Context.RequiresClassHierarchyLock(); + return _dependentClasses; + } + } + /// /// The classes that name this one as their direct superclass, excluding singleton /// classes -- Ruby 3.1's Class#subclasses. The dependent-class list exists to diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs index abfe8f547..a8de344bd 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs @@ -40,9 +40,9 @@ internal sealed partial class JitCompiler { private RubyClass _inlinedSelfClass; // A call was inlined on a parameter under a check of the one class the profile saw it hold (JitCode). private bool _inlinedOnArgumentClass; - // The locals nothing samples that a call was inlined on (UnsampledCallees), with the first class it was inlined - // for: what names the instance variable of an attribute read of the local (EmitMethodAttrRead). - private System.Collections.Generic.Dictionary _unsampledClasses; + // The locals nothing samples that a call was inlined on (UnsampledCallees), with the classes it was inlined for: + // what names the instance variable of an attribute read or write of the local (UnsampledAttrVariable). + private System.Collections.Generic.Dictionary _unsampledClasses; /// /// The call inlined (see the file header), or null if it is not a call of an inlinable @@ -73,7 +73,8 @@ private MSA.Expression TryInlineCall(MethodCall/*!*/ node, out JT type) { !JitRuntime.InlineUnsampled || !UnsampledCallees(node.MethodName, args.Length, out cls, out code, out otherCls, out otherCode)) { return null; } - (_unsampledClasses ?? (_unsampledClasses = new System.Collections.Generic.Dictionary()))[receiverLocal.Name] = cls; + (_unsampledClasses ?? (_unsampledClasses = new System.Collections.Generic.Dictionary()))[receiverLocal.Name] = + (otherCls != null) ? new[] { cls, otherCls } : new[] { cls }; } else { cls = JitRuntime.ClassOf(_context, sample); if (cls.Context != _context) { return null; } @@ -187,8 +188,8 @@ private JitCode InlinableCallee(RubyClass/*!*/ cls, string/*!*/ name, bool selfR } /// - /// The callees of a call on a local the profile has no sample of (TryInlineCall): the classes, constants of - /// Object, that define a method of the name themselves whose typed body may be inlined now (InlinableCallee), + /// The callees of a call on a local the profile has no sample of (TryInlineCall): the classes that define a + /// method of the name themselves (JitStub.ClassesDefining: any subclass of Object, nested in a module or not) whose typed body may be inlined now (InlinableCallee), /// one or two of them, two only if their bodies take and give the same types. Each is called under a check of /// its exact class, which deopts on any other (a subclass, a singleton class, a class whose method of the name /// has no such body, one with method_missing), and the entry's method version check covers a redefinition. @@ -197,18 +198,7 @@ private JitCode InlinableCallee(RubyClass/*!*/ cls, string/*!*/ name, bool selfR private bool UnsampledCallees(string/*!*/ name, int argc, out RubyClass cls, out JitCode code, out RubyClass otherCls, out JitCode otherCode) { cls = otherCls = null; code = otherCode = null; - var classes = new System.Collections.Generic.List(); - using (_context.ClassHierarchyLocker()) { - _context.ObjectClass.EnumerateConstants((module, constantName, value) => { - var c = value as RubyClass; - RubyMemberInfo method; - if (c != null && c.Context == _context && !c.IsSingletonClass && !classes.Contains(c) && c.TryGetDefinedMethod(name, out method) && - method is RubyMethodInfo) { - classes.Add(c); - } - return false; - }); - } + var classes = JitStub.ClassesDefining(_context, name); bool notReady = _hints.CalleeNotReady; int ready = 0; foreach (var c in classes) { diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 578fcc626..991fd2f94 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1752,16 +1752,9 @@ private MSA.Expression EmitMethodAttrRead(MethodCall/*!*/ node, out JT type) { var target = node.Target; object sample; if (!TrySample(target, out sample) || !(sample is RubyObject)) { - // A local nothing samples that a call was inlined on for a class (UnsampledCallees): the reader of that - // class names the variable; ReadSelfAttr binds to whatever class the object has and deopts unless the - // name is the same variable's reader there. Its value is an object. - var local = target as LocalVariable; - RubyClass inlinedFor; - if (local == null || local.DefinitionLexicalDepth != _scopeDepth || _unsampledClasses == null || - !_unsampledClasses.TryGetValue(local.Name, out inlinedFor)) { - return null; - } - string name = JitRuntime.SelfAttrSite.ReaderVariable(inlinedFor, node.MethodName, true); + // A local nothing samples (UnsampledAttrVariable): ReadSelfAttr binds to whatever class the object has + // and deopts unless the name is the same variable's reader there. Its value is an object. + string name = UnsampledAttrVariable(target as LocalVariable, node.MethodName, false); if (name == null || CanFallBack(target)) { return null; } JT lt; var localReceiver = Coerce(Emit(target, out lt), lt, JT.Obj); @@ -1801,6 +1794,44 @@ private MSA.Expression EmitMethodAttrRead(MethodCall/*!*/ node, out JT type) { return GuardIVarRead(guard, read); } + /// + /// The instance variable an attribute reader (: writer) of the name reads (writes) on a + /// local of the method nothing samples: the one the class a call on the local was inlined for names + /// (UnsampledCallees), or else the one every class names whose own method of the name is written in Ruby - each must + /// be a public attr_reader/attr_writer or a method that is one (SelfAttrSite), all of the same variable, and there + /// must be one (AgreedAccessorVariable). Null otherwise. Only the name is decided here: the read or write checks the class of the object it + /// meets, and deopts where the accessor is not that variable's (a private one, method_missing, another class's). + /// + private string UnsampledAttrVariable(LocalVariable local, string/*!*/ name, bool writer) { + if (!JitRuntime.InlineUnsampled || local == null || local.DefinitionLexicalDepth != _scopeDepth || !_refinements.IsEmpty) { return null; } + RubyClass[] inlinedFor; + if (_unsampledClasses != null && _unsampledClasses.TryGetValue(local.Name, out inlinedFor)) { + string agreed = AgreedAccessorVariable(inlinedFor, name, writer, false); + if (agreed != null) { return agreed; } + } + return AgreedAccessorVariable(JitStub.ClassesDefining(_context, name, true, true), name, writer, true); + } + + // The one variable the accessors of the name on these classes read (write); null if there is none or two differ. + // strict: every class whose own method of the name is written in Ruby (an accessor, a def) must be such an accessor - + // a name some class defines as a real method (`to_s', `name') is no evidence of what an object nothing samples + // holds; only methods of the core library (Integer#next) are left out, as their classes' objects deopt where met. + // Not strict: a class that is no such accessor is skipped (the classes a call on the local was inlined for). + private static string AgreedAccessorVariable(IEnumerable/*!*/ classes, string/*!*/ name, bool writer, bool strict) { + string found = null; + foreach (var cls in classes) { + string v = writer ? JitRuntime.SelfAttrSite.WriterVariable(cls, name, true) : JitRuntime.SelfAttrSite.ReaderVariable(cls, name, true); + if (v == null) { + RubyMemberInfo own; + if (strict && cls.TryGetDefinedMethod(name, out own) && !(own is RubyLibraryMethodInfo)) { return null; } + continue; + } + if (found != null && found != v) { return null; } + found = v; + } + return found; + } + /// /// `@o.x = v', `o.x = v', `self.x = v' in a method, where the profiled receiver's x= is an attr_writer /// (or a method that is one): the store (JitRuntime.WriteAttr), under ReadSelfAttr's checks, which @@ -1813,9 +1844,17 @@ private MSA.Expression EmitMethodAttrRead(MethodCall/*!*/ node, out JT type) { if (op != null || node.IsSafeNavigation || !_refinements.IsEmpty) { throw Bail("attribute assignment " + node.Name); } var target = node.Qualifier; object sample; - if (!TrySample(target, out sample) || !(sample is RubyObject)) { throw Bail("attribute assignment " + node.Name + " on an unprofiled receiver"); } bool explicitReceiver = !(target is SelfReference); - string variableName = JitRuntime.SelfAttrSite.WriterVariable(JitRuntime.ClassOf(_context, sample), node.Name, explicitReceiver); + string variableName; + if (!TrySample(target, out sample) || !(sample is RubyObject)) { + // A local nothing samples: the variable the writers of the name write (UnsampledAttrVariable). The store + // below is the sampled one's: WriteAttr checks the class it meets, and deopts before writing anything. + sample = null; + variableName = UnsampledAttrVariable(target as LocalVariable, node.Name, true); + if (variableName == null) { throw Bail("attribute assignment " + node.Name + " on an unprofiled receiver"); } + } else { + variableName = JitRuntime.SelfAttrSite.WriterVariable(JitRuntime.ClassOf(_context, sample), node.Name, explicitReceiver); + } if (variableName == null && sample is RubyStruct) { int member = JitRuntime.StructMemberSite.Member(JitRuntime.ClassOf(_context, sample), node.Name, explicitReceiver, true); if (member >= 0) { return EmitStructMemberWrite(node, right, member, explicitReceiver, out type); } diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index e09b0f742..e16194dd3 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -53,6 +53,14 @@ public static partial class JitRuntime { /// internal static readonly bool InlineUnsampled = Environment.GetEnvironmentVariable("IR_JIT_UNSAMPLED") != "0"; + /// + /// IR_JIT_NESTED (on unless =0): the candidates of an unsampled call (JitStub.ClassesDefining, JitCompiler.UnsampledCallees) + /// are every subclass of Object that defines the method, not only those that are constants of Object: most classes of + /// real code are nested in a module, and a nested receiver whose method's name a top-level class also defines was + /// inlined for the top-level class alone and deopted on every call. + /// + internal static readonly bool NestedClasses = Environment.GetEnvironmentVariable("IR_JIT_NESTED") != "0"; + /// /// Statistics, printed by -X:JITStats. /// diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 9f8a4172c..7be5baee9 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -1844,22 +1844,56 @@ internal static bool IsLeafShape(MethodDeclaration/*!*/ ast, Func /// A class that is a constant of Object defines a Ruby method of this name that may be inlined. internal static bool IsLeafMethodOfSomeClass(RubyContext/*!*/ context, string/*!*/ name) { - var candidates = new List(); + // Only the classes that are constants of Object: with every class (ClassesDefining's walk) the hint is more often + // yes for a receiver that is an Array or a Hash (some nested class has a leaf `push'), and such a caller is + // wrapped to be declined (app-shapes: CSV::Parser::Scanner#keep_start), with nothing more specialized. + foreach (var cls in ClassesDefining(context, name, false)) { + RubyMemberInfo method; + if (cls.TryGetDefinedMethod(name, out method) && IsLeafMethod(method as RubyMethodInfo, true)) { return true; } + } + return false; + } + + /// + /// The classes that define a Ruby method of the name themselves (not singleton classes): with IR_JIT_NESTED + /// (on unless =0) and every subclass of Object, found down the subclass lists (RubyModule.DependentClasses, which + /// a class joins in its superclass's), so a class nested in a module (`Foo::Entry`) is one; without it the + /// classes that are constants of Object, as it was. Under the class hierarchy lock. + /// + internal static List/*!*/ ClassesDefining(RubyContext/*!*/ context, string/*!*/ name, bool nested = true, bool anyMember = false) { + var result = new List(); using (context.ClassHierarchyLocker()) { - context.ObjectClass.EnumerateConstants((module, constantName, value) => { - var cls = value as RubyClass; - RubyMemberInfo method; - if (cls != null && cls.Context == context && !cls.IsSingletonClass && cls.TryGetDefinedMethod(name, out method)) { - var info = method as RubyMethodInfo; - if (info != null) { candidates.Add(info); } + if (!nested || !JitRuntime.NestedClasses) { + context.ObjectClass.EnumerateConstants((module, constantName, value) => { + var cls = value as RubyClass; + if (cls != null && !result.Contains(cls) && Defines(context, cls, name, anyMember)) { result.Add(cls); } + return false; + }); + return result; + } + var seen = new HashSet(); + var work = new Stack(); + work.Push(context.ObjectClass); + while (work.Count > 0) { + var cls = work.Pop(); + if (!seen.Add(cls)) { continue; } + if (Defines(context, cls, name, anyMember)) { result.Add(cls); } + var subs = cls.DependentClassesOrNull; + if (subs == null) { continue; } + foreach (var sub in subs) { + // a class's list holds its subclasses (and, through them, nothing else: a mixin's holds its includers) + if (sub != null && !sub.IsSingletonClass && ReferenceEquals(sub.SuperClass, cls)) { work.Push(sub); } } - return false; - }); - } - foreach (var info in candidates) { - if (IsLeafMethod(info, true)) { return true; } + } } - return false; + return result; + } + + // anyMember: an attr_reader or attr_writer counts too, not only a Ruby method + private static bool Defines(RubyContext/*!*/ context, RubyClass/*!*/ cls, string/*!*/ name, bool anyMember) { + RubyMemberInfo method; + return cls.Context == context && !cls.IsSingletonClass && cls.TryGetDefinedMethod(name, out method) && + (anyMember ? !method.IsUndefined && !method.IsHidden : method is RubyMethodInfo); } /// diff --git a/Util/bench/havlak-shapes.rb b/Util/bench/havlak-shapes.rb index f68e15d5c..f3d55fc49 100644 --- a/Util/bench/havlak-shapes.rb +++ b/Util/bench/havlak-shapes.rb @@ -54,6 +54,56 @@ def chain_length(key) end end +# The same in a module, beside the top-level HsEntry, which defines a `match' too: a candidate search that sees only +# Object's constants finds HsEntry alone, inlines for it, and deopts on every HsNs::Entry (JitStub.ClassesDefining). +module HsNs + class Entry + attr_reader :hash, :key, :value + attr_accessor :next + def initialize(hash, key, value, nxt); @hash = hash; @key = key; @value = value; @next = nxt; end + def match(hash, key); @hash == hash && @key == key; end + end + class Dict + def initialize(size = 16); @buckets = Array.new(size); end + def get_bucket(hash); @buckets[(@buckets.size - 1) & hash]; end + def at(key) + hash = key.custom_hash + e = get_bucket(hash) + while e + return e.value if e.match(hash, key) + e = e.next + end + nil + end + def at_put(key, value) + hash = key.custom_hash + i = (@buckets.size - 1) & hash + @buckets[i] = Entry.new(hash, key, value, @buckets[i]) + end + end +end + +# AWFY Towers' pop_disk_from and push_disk: a disk read from an Array, then an attribute read and write on it +class HsDisk + attr_accessor :next + attr_reader :size + def initialize(size); @size = size; @next = nil; end +end +class HsPiles + def initialize; @piles = Array.new(3); end + def pop_disk_from(pile) + top = @piles[pile] + raise 'Attempting to remove a disk from an empty pile' unless top + @piles[pile] = top.next + top.next = nil + top + end + def push_disk(disk, pile) + disk.next = @piles[pile] + @piles[pile] = disk + end +end + def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) def t(name, n) @@ -78,4 +128,10 @@ def t(name, n) t("at_first", N) { |n| i = 0; s = 0; while i < n; s += d.at(first); i += 1; end; s } t("at_chain", N) { |n| i = 0; s = 0; while i < n; s += d.at(deep); i += 1; end; s } t("at_miss", N) { |n| i = 0; s = 0; while i < n; s += 1 if d.at(missing).nil?; i += 1; end; s } +nd = HsNs::Dict.new +keys.each_with_index { |k, i| nd.at_put(k, i) } +t("ns_at_chain", N) { |n| i = 0; s = 0; while i < n; s += nd.at(deep); i += 1; end; s } +hp = HsPiles.new +3.times { |p| [3, 2, 1].each { |sz| hp.push_disk(HsDisk.new(sz + p * 10), p) } } +t("towers_pop", N / 3 * 3) { |n| i = 0; s = 0; while i < n; dk = hp.pop_disk_from(i % 3); hp.push_disk(dk, (i + 2) % 3); s += dk.size; i += 1; end; s } t("chain_len", N) { |n| i = 0; s = 0; while i < n; s += d.chain_length(deep); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index d84b1928c..e556b59da 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1202,6 +1202,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has on a receiver nothing samples - the same kind of local, `current` walking a chain; the write would need what the read now has, a name from a class the call was inlined for or from the classes that define the writer). + perf/havlak2 (see Landed) gave the write its name; `split_bucket` now declines at the + effect rule ("a deopt after an effect (call next)": the next iteration's read can deopt + after this one's write), and it is called 459 times an iteration against `at`'s 799,304, + so it is not worth a body that could take that. 26. **Start-up: `gem` and `irb` answer in 0.7 to 2.2 s, CRuby in 0.1 to 0.2** (the one thing that has to stay fast while the tiers stay on by default, and it is not fast). 2026-11-18, a7060a27, the ReadyToRun host (`IR_CONFIG=R2R`, what `ir.sh` runs when @@ -1509,6 +1513,58 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/havlak2 (/perf-step, 2026-11-27, on e68ac13) - an attribute read or write on a local nothing + samples, and the candidates of an unsampled call found in classes nested in modules (gaps 25, 1)** - + not gated. Two parts. (1) `UnsampledAttrVariable`: `x.a` and `x.a = v`, x a local of the method the + profile has no sample of, read and write the variable through the sampled path's sites + (`ReadSelfAttr`, `WriteAttr`: each checks the class it meets and deopts where the accessor is not that + variable's, a write before storing anything); the name is the one the classes a call on x was inlined + for agree on, or else the one every class names whose own method of the name is written in Ruby - all + of them must be public accessors of the same variable (`AgreedAccessorVariable`, strict); core library + methods (`Integer#next`) are left out. A looser first version (any class that has such an accessor) + moved 30 census methods to `compiles` at `x.to_s` and `x.name`, which a String receiver would deopt on + every call; strict, one moves (`Rake::Scope#trim`, `tail` of a linked list). The effect rule is the + compiler's as for a sampled receiver: a write is an effect, and a read or guard after it that can + deopt declines the body. (2) `JitStub.ClassesDefining` walks Object's subclasses (the subclass lists, + `RubyModule.DependentClassesOrNull`) instead of Object's constants, for the candidates of an unsampled + call (`IR_JIT_NESTED=0` turns it off). Counted with Prism over the census corpus: of the instance + methods of leaf shape, 4,269 of 5,206 in Src/StdLib are in classes nested in a module, 0 of 117 in + AWFY. And e68ac13 has a fault this fixes: a nested receiver whose method's name a top-level class + also defines was inlined for the top-level class alone and deopted on every call, the stub retiring + and retrying it (`Ns::Dict#at` in unsampled-matrix, `ns_at_chain` below). The screen's leaf hint + (`IsLeafMethodOfSomeClass`) keeps Object's constants: with every class it said yes to `push` for + receivers that are Arrays, and on app-shapes `CSV::Parser::Scanner#keep_start` was wrapped and + declined with nothing more specialized. + Census (Src/StdLib + AWFY): maybe 2,981 -> 2,980, compiles 3,370 -> 3,371 (`Rake::Scope#trim`), none + down. AWFY traced (3 x 1, CD 3 x 100): Towers `pop_disk_from` specialized (was declined at + `call: next/0`), CD `RedBlackTree#get` specialized (direct calls), Havlak `split_bucket` and Richards + `release` declined at the effect rule instead of the unsampled access; every other decision the same, + all fourteen verify. CD's `Node#successor` now passes `x.right` and stops at "== on a receiver of + unknown type" (`x == y.right`, an identity comparison of an unsampled local) and then at + `call: tree_minimum/1`; `find_node` was already specialized and deopts on most calls on both builds, + which is not the read. app-shapes (N=20000) and `gem list` traced: the same counts on both builds + (115/30/566 and 11/5/265 specialized/declined/screened), the same checksums; start-up (`-e 1`, `gem + list`) the same within noise. + `Util/bench/havlak-shapes.rb` gains `ns_at_chain`, `towers_pop` (instructions a call, callgrind, + new/base, two rounds): `ns_at_chain` 0.617, `towers_pop` 0.814, `chain_len` (a bare read of the local + in a loop) 0.532, controls `at_first`, `at_chain`, `at_miss` 1.000 (one earlier process counted + `at_chain` at 4.3 times and did not again in two rounds and two runs of it alone: a state of that + process). Time, three pairs in separate processes, the order turned in the second: Havlak 6 1 base + 21.94/20.93/20.80 s, new 21.64/22.46/20.77; Towers 40 100 7.61/7.03/7.40, 7.28/7.02/7.36; CD 15 100 + 7.63/7.39/8.10, 7.91/7.24/8.19 - all within the runs' spread. + Checked: `Util/unsampled-matrix.rb` 16 -> 32 cases (nested classes, nested redefinition and singleton, + a second nested class; writes in a loop: plain, a frozen receiver, `private :mark=`, private in a + subclass, method_missing for the writer, another thread reading the field; Towers' pop/push: the same + five and a thread) prints CRuby's output on the unchanged build and on the new one with the JIT on, + `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, `IR_JIT_NESTED=0` and `IR_JIT_UNSAMPLED=0`; the pop cases + specialize `Piles#pop` (a frozen disk deopts once and the element write is taken back). jit, jit-calls, + jit-const, ivar, deadconst matrices print CRuby's in all modes, hot-shapes and inline the baseline's. + IronRuby.Tests Jit*, Loop*, Inline* (21) pass. + For the gate: the subclass walk runs under the hierarchy lock at each compile of an unsampled call; + a receiver of a core class whose method shares an accessor's name (an Integer's `next`) deopts where + met, and the stub retires a body that does so too often; the strict rule rests on Ruby-written + definitions only. + - **perf/havlak (/perf-step, 2026-11-26, on 819a368) - a call on a local the profile has no sample of is inlined for the classes that define the method, under checks of their class (gap 25)** - not gated. som.rb's `Dictionary#at` (Havlak's `IdentityDictionary`) declined at `call: match/2`: `e` diff --git a/Util/unsampled-matrix.rb b/Util/unsampled-matrix.rb index bfce19305..d8f205001 100644 --- a/Util/unsampled-matrix.rb +++ b/Util/unsampled-matrix.rb @@ -7,11 +7,17 @@ # # One case per process, since one case's event would change what the next compiles: # for c in $(ruby Util/unsampled-matrix.rb list); do echo "== $c"; ruby Util/unsampled-matrix.rb $c 2>&1; done > cruby.txt -# (the same with IR_CONFIG=Release ./ir.sh, with -X:NoJIT -X:NoOSR, with -X:NoJITCalls and with IR_JIT_UNSAMPLED=0) +# (the same with IR_CONFIG=Release ./ir.sh, with -X:NoJIT -X:NoOSR, with -X:NoJITCalls, with IR_JIT_UNSAMPLED=0 and with +# IR_JIT_NESTED=0). The nested_ cases put the classes in a module (JitStub.ClassesDefining); the write_ cases write an +# attribute of the local in a loop (declined by the effect rule: a read after the write can deopt), the pop_ cases in +# AWFY Towers' straight-line pop_disk_from (compiled: the write is the last effect). # IR_JIT_VERBOSE=1 shows `inlined Ent#match into at' and `specialized Dict/at': the path is reached. CASES = %w[plain class_change two_classes redefine redefine_value singleton singleton_value method_missing - subclass subclass_private private_value private_match protected_match remove_match frozen nil_entry] + subclass subclass_private private_value private_match protected_match remove_match frozen nil_entry + nested nested_redefine nested_other nested_singleton + write write_frozen write_private write_subclass_private write_missing write_thread + pop pop_frozen pop_private pop_subclass_private pop_missing pop_thread] if ARGV[0] == 'list' puts CASES @@ -22,6 +28,7 @@ class Ent attr_reader :hash, :key, :value, :next attr_writer :next + attr_accessor :mark def initialize(hash, key, value, nxt); @hash = hash; @key = key; @value = value; @next = nxt; end def match(hash, key); @hash == hash && @key == key; end end @@ -50,12 +57,91 @@ def at(key) end nil end + + # an attribute write on the same kind of local (split_bucket's `lo_tail.next = current') + def touch(key, m) + hash = hash_of(key) + e = get_bucket(hash) + while e + e.mark = m if e.match(hash, key) + e = e.next + end + m + end +end + +# AWFY Towers' pop_disk_from and push_disk: a disk read from an Array, an element write, then an attribute write on +# the disk - a local nothing samples, and a straight-line body the JIT compiles (the write is its last effect) +class Disk + attr_accessor :next + attr_reader :size + def initialize(size); @size = size; @next = nil; end +end + +class Piles + def initialize; @piles = Array.new(3); end + def pop(pile) + top = @piles[pile] + raise 'empty pile' unless top + @piles[pile] = top.next + top.next = nil + top + end + def push(disk, pile) + disk.next = @piles[pile] + @piles[pile] = disk + end + def sizes(pile); a = []; d = @piles[pile]; while d; a << d.size; d = d.next; end; a; end +end + +# moves `n' disks one at a time from pile i % 3 to pile (i + 2) % 3, so that every pile's top moves in turn, the event +# at the half; then the sum of the sizes moved, each pile's sizes, and the first odd answer +def run_pop(pl, n, event) + odd = nil + moved = 0 + n.times do |i| + event.call if i == n / 2 + v = answer { d = pl.pop(i % 3); pl.push(d, (i + 2) % 3); d.size } + v.is_a?(Integer) ? moved += v : odd ||= v + end + [moved, pl.sizes(0), pl.sizes(1), pl.sizes(2), odd] +end + +# the same in a module: classes nested in one are candidates too (JitStub.ClassesDefining) +module Ns + class Ent + attr_reader :hash, :key, :value, :next + def initialize(hash, key, value, nxt); @hash = hash; @key = key; @value = value; @next = nxt; end + def match(hash, key); @hash == hash && @key == key; end + end + class Dict + def initialize; @buckets = Array.new(16); end + def hash_of(key); key * 7; end + def get_bucket(hash); @buckets[hash & 15]; end + def put(key, value, cls = Ent) + h = hash_of(key) + @buckets[h & 15] = cls.new(h, key, value, @buckets[h & 15]) + end + def at(key) + hash = hash_of(key) + e = get_bucket(hash) + while e + return e.value if e.match(hash, key) + e = e.next + end + nil + end + end end def answer yield rescue NoMethodError, NameError => e [e.class, e.message[/\A[^(]*/].strip] +rescue FrozenError => e + [e.class, e.message[/\A[^:]*/]] +rescue RuntimeError => e + [e.class, e.message] end d = Dict.new @@ -82,6 +168,27 @@ def run(d, n, event) end 3000.times { |i| d.at(i % 40) } +nd = Ns::Dict.new +40.times { |k| nd.put(k, k * 10) } +3000.times { |i| nd.at(i % 40) } +3000.times { |i| d.touch(i % 40, 0) } +pl = Piles.new +[5, 4, 3, 2, 1].each { |sz| pl.push(Disk.new(sz), 0) } +[15, 14, 13, 12, 11].each { |sz| pl.push(Disk.new(sz), 1) } +[25, 24, 23, 22, 21].each { |sz| pl.push(Disk.new(sz), 2) } +3000.times { |i| pl.push(pl.pop(i % 3), (i + 2) % 3) } + +# writes: touch every key, with the event at the half; what the entries' marks are then, or the first error +def run_touch(d, n, event) + odd = nil + n.times do |i| + event.call if i == n / 2 + v = answer { d.touch(i % 40, i) } + odd ||= v unless v.is_a?(Integer) + end + marks = (0...40).map { |k| e = d.get_bucket(d.hash_of(k)); e = e.next until e.nil? || e.key == k; e && e.mark } + [marks.compact.sum, marks.count(nil), odd] +end case c when 'plain' @@ -153,4 +260,103 @@ def respond_to_missing?(name, priv = false); [:match, :value, :next].include?(na p run(d, N, -> { d.instance_variable_get(:@buckets).each { |e| while e; e.freeze; e = e.next; end } }) when 'nil_entry' p run(d, N, -> { d.instance_variable_get(:@buckets).map! { nil } }) +when 'nested' + p run(nd, N, -> {}) +when 'nested_redefine' + p run(nd, N, -> { Ns::Ent.class_eval { def match(hash, key); @key == key + 1; end } }) +when 'nested_other' + # a second nested class with a match of its own, at the head of each chain + p run(nd, N, -> { + Ns.const_set(:Other, Class.new do + attr_reader :value, :next + def initialize(hash, key, value, nxt); @hash = hash; @value = value; @next = nxt; end + def match(hash, key); @hash == hash; end + end) + 40.times { |k| nd.put(k, -k, Ns::Other) } + }) +when 'nested_singleton' + p run(nd, N, -> { + e = nd.get_bucket(nd.hash_of(5)) + e = e.next until e.key == 5 + def e.match(hash, key); false; end + }) +when 'write' + p run_touch(d, N, -> {}) +when 'write_frozen' + p run_touch(d, N, -> { e = d.get_bucket(d.hash_of(6)); e = e.next until e.key == 6; e.freeze }) +when 'write_private' + p run_touch(d, N, -> { Ent.send(:private, :mark=) }) +when 'write_subclass_private' + Object.const_set(:SubPrivateWriter, Class.new(Ent) { private :mark= }) + p run_touch(d, N, -> { d.put(11, 1, SubPrivateWriter) }) +when 'write_missing' + Object.const_set(:GhostWriter, Class.new do + attr_reader :hash, :key, :value, :next + def initialize(hash, key, value, nxt); @hash = hash; @key = key; @value = value; @next = nxt; @marks = []; end + def match(hash, key); @hash == hash && @key == key; end + def mark; @marks.size; end + def method_missing(name, *args) + name == :mark= ? (@marks << args[0]; args[0]) : super + end + def respond_to_missing?(name, priv = false); name == :mark= || super; end + end) + p run_touch(d, N, -> { d.put(12, 1, GhostWriter) }) +when 'pop' + p run_pop(pl, N, -> {}) +when 'pop_frozen' + p run_pop(pl, N, -> { pl.instance_variable_get(:@piles).each { |top| top.freeze if top } }) +when 'pop_private' + p run_pop(pl, N, -> { Disk.send(:private, :next=) }) +when 'pop_subclass_private' + Object.const_set(:PrivateDisk, Class.new(Disk) { private :next= }) + p run_pop(pl, N, -> { + pd = PrivateDisk.new(99) + piles = pl.instance_variable_get(:@piles) + pd.instance_variable_set(:@next, piles[2]) + piles[2] = pd + }) +when 'pop_missing' + Object.const_set(:GhostDisk, Class.new do + attr_reader :size + def initialize(size); @size = size; @link = nil; end + def method_missing(name, *args) + case name + when :next then @link + when :next= then @link = args[0] + else super + end + end + def respond_to_missing?(name, priv = false); name == :next || name == :next= || super; end + end) + p run_pop(pl, N, -> { pl.push(GhostDisk.new(77), 0) }) +when 'pop_thread' + # another thread reads each pile's top disk's next while the moves go on: it must only see nil or a Disk + stop_pt = false + bad_pt = 0 + piles_pt = pl.instance_variable_get(:@piles) + reader_pt = Thread.new do + until stop_pt + piles_pt.each { |top_pt| n_pt = top_pt && top_pt.next; bad_pt += 1 unless n_pt.nil? || n_pt.is_a?(Disk) } + end + end + r_pt = run_pop(pl, N, -> {}) + stop_pt = true + reader_pt.join + p [r_pt, bad_pt] +when 'write_thread' + # another thread reads the mark of key 3 while the writes go on; it must only ever see a value some touch wrote + e3 = d.get_bucket(d.hash_of(3)) + e3 = e3.next until e3.key == 3 + stop_wt = false + bad_wt = 0 + reader_wt = Thread.new do + until stop_wt + m_wt = e3.mark + bad_wt += 1 unless m_wt.is_a?(Integer) && m_wt >= 0 && m_wt < N && (m_wt == 0 || m_wt % 40 == 3) + end + end + r_wt = run_touch(d, N, -> {}) + stop_wt = true + reader_wt.join + p [r_wt, bad_wt] end From d206f90f11fd1bad231f4a14651a94e282a7e917 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:22:13 +0000 Subject: [PATCH 175/439] perf/rescuelight: errinfo matrix and ledger entry Util/errinfo-matrix.rb probes $! around begin/rescue/else/ensure on the runs that raise nothing and on those that do: nested and callee rescues, an exception through a rescue that does not match, jumps and throw through ensure, an exception raised in ensure and its cause, retry, else/ensure order, binding and caller in a rescue clause, TracePoint :raise/:rescue, Timeout and Thread#raise mid-body, and a million-deep recursion through ensure. The ledger records the change as landed, timed but not gated, and what gap 22 is now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/errinfo-matrix.rb | 165 +++++++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 51 +++++++++++++ 2 files changed, 216 insertions(+) create mode 100644 Util/errinfo-matrix.rb diff --git a/Util/errinfo-matrix.rb b/Util/errinfo-matrix.rb new file mode 100644 index 000000000..5a11adc84 --- /dev/null +++ b/Util/errinfo-matrix.rb @@ -0,0 +1,165 @@ +# Differential matrix for $! around begin/rescue/else/ensure when nothing is raised and when something is (Body. +# TransformExceptionHandling; IR_LAZY_ERRINFO leaves $! alone on the runs that raise nothing). Run it under CRuby and +# under ./ir.sh in every mode, and diff: +# +# ruby Util/errinfo-matrix.rb > mri.txt +# ./ir.sh Util/errinfo-matrix.rb > on.txt +# IR_LAZY_ERRINFO=0 ./ir.sh Util/errinfo-matrix.rb > off.txt +# IR_LIGHT_FRAMES=0 ./ir.sh Util/errinfo-matrix.rb > scoped.txt +# diff mri.txt on.txt && diff mri.txt off.txt && diff mri.txt scoped.txt +# +# Each probe runs 3000 times (interpreted, then compiled) and prints every distinct answer once: $! in and after a +# rescue, a begin that raises nothing inside a rescue clause, a rescue in a callee, an exception going through a rescue +# that does not match, return/break/next/throw through ensure, an exception raised in ensure and its cause, retry, +# else/ensure order, binding and local_variables in a rescue clause, caller from it, TracePoint :raise/:rescue, +# Timeout and Thread#raise arriving mid-body, and recursion a million deep through an ensure. + +N = 3000 + +def t(label) + print label.ljust(52), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def errinfo = $!&.message + +def quiet_rescue(x) + begin + x + 1 + rescue StandardError + 0 + end +end + +def quiet_ensure(x) + begin + x + 1 + ensure + @seen = errinfo + end +end + +def callee_rescues + raise TypeError, "inner" +rescue TypeError + errinfo +end + +def passes_through + begin + raise ArgumentError, "pass" + rescue TypeError + :no + end +end + +def ensure_return + begin + return errinfo + ensure + @in_ensure = errinfo + end +end + +def ensure_raises + begin + raise "first" + ensure + raise "second" + end +end + +def retrying + n = 0 + begin + n += 1 + raise "r#{n}" if n < 3 + [n, errinfo] + rescue + retry + end +end + +def else_ensure(log) + begin + log << errinfo + rescue + log << :rescue + else + log << :else << errinfo + ensure + log << :ensure << errinfo + end + log +end + +def in_clause + begin + raise "b" + rescue => err + [err.message == binding.local_variable_get(:err).message, local_variables.include?(:err), caller(0, 1)[0][/in .*/]] + end +end + +def deep_ensure(n) + return 0 if n == 0 + begin + deep_ensure(n - 1) + 1 + ensure + @d = n + end +end + +t("nothing raised: $! after rescue, after ensure") { |i| [quiet_rescue(i % 2), quiet_ensure(i % 2), errinfo, @seen] } +t("nothing raised inside a rescue clause") do |i| + begin + raise "outer#{i % 2}" + rescue + [quiet_rescue(i % 2), quiet_ensure(i % 2), errinfo, @seen] + end +end +t("$! after the rescue clause ends") { |i| begin; raise "x#{i % 2}"; rescue; errinfo; end; errinfo } +t("a callee's rescue, then $! here") { |i| begin; raise "o"; rescue; [callee_rescues, errinfo]; end } +t("through a rescue that does not match") { |i| r = begin; passes_through; rescue => e; [e.message, errinfo]; end; [r, errinfo] } +t("return through ensure, inside a rescue") { |i| begin; raise "y"; rescue; [ensure_return, @in_ensure, errinfo]; end } +t("an exception raised in ensure and its cause") { |i| begin; ensure_raises; rescue => e; [e.message, e.cause&.message, errinfo]; end } +t("retry") { |i| [retrying, errinfo] } +t("else and ensure order, $! in each") { |i| else_ensure([]) } +t("else and ensure inside a rescue clause") { |i| begin; raise "z"; rescue; else_ensure([]); end } +t("next and break through ensure") { |i| [1, 2, 3].each { |k| begin; next if k == 1; break k * 10; ensure; @last = [k, errinfo]; end } } +t("throw through ensure") { |i| [catch(:t) { begin; throw :t, 5; ensure; @thrown = errinfo; end }, @thrown, errinfo] } +t("binding, local_variables, caller in a rescue clause") { |i| in_clause } + +tp_events = [] +tp = TracePoint.new(:raise, :rescue) { |tp| tp_events << [tp.event, tp.raised_exception.message] } +t("TracePoint :raise and :rescue") do |i| + tp_events.clear + tp.enable { begin; raise "tp"; rescue; end; quiet_rescue(i % 2); quiet_ensure(i % 2) } + tp_events.dup +end + +require 'timeout' +t("Timeout in a body with a rescue that does not match") do |i| + next nil unless i % 500 == 0 + r = (Timeout.timeout(0.01) { begin; sleep 1; rescue ArgumentError; :no; end } rescue $!.class) + [r, errinfo] +end +t("Thread#raise in a body with rescue and ensure") do |i| + next nil unless i % 500 == 0 + th = Thread.new { begin; sleep; rescue => e; [e.message, errinfo]; ensure; @th_ensure = errinfo; end } + sleep 0.01 until th.status == "sleep" + th.raise("tr") + [th.value, errinfo] +end + +puts "recursion a million deep through ensure: " + (begin; deep_ensure(1_000_000).to_s; rescue SystemStackError; "SystemStackError"; end) +puts "and $! after: #{errinfo.inspect}" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 0b6271a07..8c05ba24f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1193,6 +1193,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has is raised**: `def r(x) begin; x + 1; rescue StandardError; 0; end end` 106 ns against CRuby's 24, the same with `ensure` 112 against 27 (`Util/bench/zjit-post-shapes.rb`, one loaded run: factors). Gap 9 seen from the caller: no light frame, no typed body. + Since then (perf/rescuelight, 2026-11-27, see Landed): such methods are light frames + (b72da7b), and with `$!` left alone on a run that raises nothing, `ensure` is 52 ns and + `rescue` 52 against a plain light frame's 45 and CRuby's 29-32 (`-X:NoJIT`); what is left + is the typed body the method JIT refuses (`Body`: 27 against 35 ns for `x + 1`) and the + read of `$!` at a rescue's entry. A .NET `try` costs nothing on the path that does not throw, so the experiment is to find what the method does around the handler (the scope, the saving of `$!`, the frame) and let a body whose handler is not entered run as light as one without. @@ -1774,6 +1779,52 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/rescuelight (/perf-frame, 2026-11-27) - `$!` left alone in a begin/rescue/ensure that + raises nothing** (switch `IR_LAZY_ERRINFO`, on unless `=0`) - timed, not gated. Built on + 4320d4a with claude/perf-lsite merged (d83116b). + - **What gap 22 is now.** Its 80 ns predate b72da7b: `resc` and `ens` of zjit-post-shapes are + light frames (`IR_LIGHT_FRAMES=why`), and the method JIT refuses them (`screen rejected + B/resc: Body`). `ab.rb -r 8` (ns; CRuby / IronRuby / `-X:NoJIT`): `x + 1` 21.1 / 27.0 / + 35.0, rescue 20.4 / 39.0 / 40.0, ensure 24.2 / 50.5 / 50.1. So two parts: no typed body + (~8 ns, 27 against 35), and the handler in the light frame (rescue ~5 ns, ensure ~15). + - **What the handler pays** (callgrind, calls only - its code is MinOpts, see perf/castcheck): + `$!` - `GetCurrentException` and `SetCurrentException`, each a `[ThreadStatic]` read or + write, a call into the runtime from a compiled body (`__tls_get_addr`). Per call with + nothing raised: a rescue read it at entry and wrote it back in its finally; an ensure read + it at entry, read it again in the clause and wrote it back after, and asked + `RubyUtils.IsReclaimingFiber`, a third thread-static. + - **What changed.** The rescue's finally restores `$!` only if an exception was taken or the + statements were left otherwise (a jump, an exception going through): run to their end they + left `$!` as they found it (nested handlers and callees restore their own). The save at the + rescue's entry stays: when the handler runs, an inner frame that threw the exception on may + already have set `$!` to it, so a save there would restore the wrong value. The ensure + clause reads and restores `$!` only for an exception it runs for. `IsReclaimingFiber` asks + the thread-static only while some thread has a safe point requested (a thread reclaiming a + fiber does for as long as it is, `BeginFiberReclamation`). + - **Timed** (`Util/bench/rescue-shapes.rb`, `ab.rb -r 8`, `-X:NoJIT`, ns; CRuby / off / on): + ensure 31.6 / 60.8 / 52.0 (0.86), else_ 35.7 / 62.7 / 56.0, begin_r 39.0 / 62.2 / 56.0, + modifier 30.2 / 48.0 / 45.1, rescue 29.3 / 52.9 / 52.3, rescue_e 30.4 / 48.0 / 47.7; the + plain control 28.7 / 46.5 / 45.3 (all but ensure overlap). AWFY, ten processes each + (median, base / candidate / switch off): Json 45,741 / 45,650 / 45,598 us, CD 337,463 / + 329,373 / 331,432, Havlak 2,604,039 / 2,595,776 / 2,554,229 - no change beyond the noise. + - **Checked.** `Util/errinfo-matrix.rb` (new: `$!` after a rescue and an ensure that raised + nothing, also inside a rescue clause; after a rescue clause ends; a callee's rescue; an + exception through a rescue that does not match; return through ensure inside a rescue; an + exception raised in ensure and its cause; retry; else/ensure order and `$!` in each; next + and break through ensure; throw through ensure; binding, local_variables and caller in a + rescue clause; TracePoint `:raise`/`:rescue`; Timeout and Thread#raise mid-body; a + million-deep recursion through ensure: SystemStackError) prints CRuby's output on the + baseline and the candidate, switch on and off. With it, rescue-light, jit-raise, + jit-rescue, raise, light-entry, block-pass, parked-scope, jit and hot-shapes in five modes + (as built, `IR_LAZY_ERRINFO=0`, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`): + 50 runs, the candidate's output the baseline's in every one (raise-matrix differs from + CRuby on both alike). ruby/spec language/rescue (60 examples), language/ensure (31), + language/retry (3), core/exception (250), library/timeout (7): 0 failures on both trees. + IronRuby.Tests: the 79 registered tests named Exception/Rescue/Ensure/Retry/Raise: PASSED. + Not run: the whole suite, a sweep, the census (no verdict moves). + - Left: the typed body (`Body` refused: a handler in the typed body, gap 22's last line); + the read of `$!` at a rescue's entry. + - **Gate of 2026-11-27 for round 4 of round thirty-seven** (perf/strdup, perf/strsearch2, perf/extiter2 and 3, perf/lframe, perf/lexical2 and 3, perf/kwrest, perf/jitscreen and 2, perf/deadconst2, perf/permute, perf/havlak, perf/dmethjit2, perf/jitsettle; the rejected From 0cf16c33f5c0f3c8e603e48afaf946894c9c0a79 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:33:55 +0000 Subject: [PATCH 176/439] perf/nilblock: a nil block costs nothing by clock; record it, and what does perf/delegate counted a nil block parameter or argument at 440-600 instructions a call with the callgrind counter. Timed natively with the method JIT off, the wrappers with an unused &k, &nil and a nil &k passed on are within noise of the fixed call; what the counter saw is its MinOpts code and the typed body the method JIT gives the fixed wrapper and refuses the others. `...` is what does cost: 2.4 times CRuby's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/perf/LEDGER.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8c05ba24f..ad4c51507 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -6485,6 +6485,27 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/nilblock (/perf-frame, 2026-11-27) - a nil block parameter or argument: measured by + clock, no cost to remove** (no code; built on d206f90, which is 4320d4a with claude/perf-lsite). + perf/delegate (3ea2ea5) counted a nil `&k` parameter or `&nil` argument at 440-600 instructions + a call into `two(a, b)` with the callgrind counter (`Util/bench/forward-shapes.rb`). + - **By clock it is not there.** `ab.rb -r 12 -n 2000000`, `-X:NoJIT` so that every wrapper is + the same kind of frame (ns; CRuby / IronRuby): fixed 37.3 / 51.9, an unused `&k` 46.0 / 50.0, + `&nil` 37.9 / 52.0, `&k` passed on (nil) 47.9 / 53.3 - the four within IronRuby's spread + (7-20%) of each other, where CRuby pays 9-10 ns for a block parameter. With the method JIT + (`ab.rb -r 8`): fixed 40.0, `&k` unused 44.0, `&nil` 46.3, `&k` passed 51.7 (CRuby 35.7, + 44.0, 35.9, 46.3). + - **What the counter saw.** Its code is MinOpts (perf/castcheck), and the wrappers differ in + the typed body: `fixed` is specialized (`FW/fixed arity 2 -> Int`), a method with a block + parameter is never wrapped (`JitStub.ParameterShape`: "block parameter"), and one that + passes `&nil` is refused by the screen (`MethodCall two`). That refusal is the 4-6 ns left + with the JIT on; it is the method JIT's to take, a typed body that takes a block and hands + it on (gap 9), not a frame's. + - **What the clock does show:** `...` 111.7 ns against fixed 51.9 (CRuby 45.7: 2.44), and + `(*, &)` 117.9 (CRuby 83.6) - the rest Array a forwarding layer builds and splats (gap 16's + second part; perf/delegate's 1,170 instructions). That is the forwarding cost worth a + step, not the block. + - **perf/castcheck (/perf-frame, 2026-11-27) - why the JIT expands no cast in Ruby's compiled bodies, and a fix that was not worth keeping** (switch `IR_UNWIND_RETURN`, reverted; built on 15285eb with claude/perf-lsite merged, 054d132). perf/lconst found every `castclass` in a Ruby From 288cc13fea0c78aafa93370d5826d0812a1c0183 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:39:24 +0000 Subject: [PATCH 177/439] perf/dotsfwd: the values `...' forwards are reachable after the call; stop On CRuby 4.0 nothing names the values of `...' or an anonymous `*', `**' or `&', but the method's own body can forward them again after a call - a second forward, eval, binding.eval, instance_eval, send(:eval), eval through an alias, a TracePoint :return hook's binding.eval - and must pass what it was given even after a callee changed its rest. So handing the callee the caller's Array is not sound, and no static guard can see every eval. IronRuby already behaves as CRuby on all of it. Util/anon-forward-matrix.rb keeps the probes; the ledger says where the 60 ns of `...' are instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Util/anon-forward-matrix.rb | 67 +++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 26 ++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 Util/anon-forward-matrix.rb diff --git a/Util/anon-forward-matrix.rb b/Util/anon-forward-matrix.rb new file mode 100644 index 000000000..08396d607 --- /dev/null +++ b/Util/anon-forward-matrix.rb @@ -0,0 +1,67 @@ +# What can reach the values a method forwards with `...' or an anonymous `*', `**' or `&' (Ruby 3.2+), after the call +# that forwarded them - what a forward that hands the callee the caller's own Array (no copy) would have to keep right. +# CRuby 4.0: nothing names them (local_variables, binding.local_variables and a TracePoint binding see none, +# binding.local_variable_get(:"...") raises), but the method's own body can forward them again - a second `raw(...)', +# eval("raw(...)"), binding.eval, instance_eval, send(:eval), eval through an alias, and a TracePoint :return hook's +# binding.eval - and must then see what the caller was given, whatever an earlier callee did to its rest or kwrest. +# +# ruby Util/anon-forward-matrix.rb > mri.txt && ./ir.sh Util/anon-forward-matrix.rb > ir.txt && diff mri.txt ir.txt +# +# (perf/dotsfwd, Util/perf/LEDGER.md: why `...' forwarding cannot share the caller's Array.) +def raw(*a, **k, &b) = [a, k, b&.call] +def try_(label) + r = begin; yield; rescue Exception => e; "#{e.class}: #{e.message.lines.first.strip[0, 80].gsub(/0x[0-9a-f]+/, "0x")}"; end + puts "#{label.ljust(44)} => #{r.inspect}" +end +def d_eval(...) = eval("raw(...)") +def d_eval_star(*) = eval("raw(*)") +def d_eval_dstar(**) = eval("raw(**)") +def d_eval_amp(&) = eval("raw(&)") +def d_lvars(...) = local_variables +def d_lvars_anon(*, **, &) = local_variables +def d_binding_lvars(...) = binding.local_variables +def d_binding_get(...) = binding.local_variable_get(:"...") +def d_binding_get_star(*) = binding.local_variable_get(:*) +def d_binding_eval(...) = binding.eval("raw(...)") +def d_instance_eval(...) = instance_eval("raw(...)") +def d_send_eval(...) = send(:eval, "raw(...)") +def d_eval_star_in_dots(...) = eval("raw(*)") +try_("eval('raw(...)') in def(...)") { d_eval(1, 2, k: 3) { :blk } } +try_("eval('raw(*)') in def(*)") { d_eval_star(1, 2) } +try_("eval('raw(**)') in def(**)") { d_eval_dstar(k: 1) } +try_("eval('raw(&)') in def(&)") { d_eval_amp { :blk } } +try_("local_variables in def(...)") { d_lvars(1, 2) } +try_("local_variables in def(*, **, &)") { d_lvars_anon(1, k: 2) { } } +try_("binding.local_variables in def(...)") { d_binding_lvars(1) } +try_("binding.local_variable_get(:'...')") { d_binding_get(1) } +try_("binding.local_variable_get(:*)") { d_binding_get_star(1) } +try_("binding.eval('raw(...)')") { d_binding_eval(1, 2) } +try_("instance_eval('raw(...)')") { d_instance_eval(1, 2) } +try_("send(:eval, 'raw(...)')") { d_send_eval(1, 2) } +try_("eval('raw(*)') in def(...)") { d_eval_star_in_dots(1, 2) } +seen = [] +tp = TracePoint.new(:return) { |t| seen << (t.binding.local_variables rescue $!.class) if t.method_id == :fwd_tp } +def fwd_tp(...) = raw(...) +tp.enable { fwd_tp(1, 2) } +try_("TracePoint :return binding.local_variables") { seen } +def keeps(*a) = (a << :mutated; a) +def fwd_keep(...) = keeps(...) +try_("callee mutates its rest; caller's view") { arr = [1, 2]; [fwd_keep(*arr), arr] } +def keeps2(*a) = (a << :m; a.size) +def twice(...) = [keeps2(...), raw(...)] +try_("callee mutates rest, then raw(...) again") { twice(1, 2) } +def twice_eval(...) = [keeps2(...), eval("raw(...)")] +try_("callee mutates rest, then eval('raw(...)')") { twice_eval(1, 2) } +def twice_anon(*) = [keeps2(*), raw(*)] +try_("callee mutates rest, then raw(*) again") { twice_anon(1, 2) } +def kwkeep(**k) = (k[:x] = 1; k.size) +def twice_kw(**) = [kwkeep(**), raw(**)] +try_("callee mutates kwrest, then raw(**) again") { twice_kw(a: 1) } +def fwd_tp2(...) = keeps2(...) +seen = [] +tp = TracePoint.new(:return) { |t| seen << t.binding.eval("raw(...)") if t.method_id == :fwd_tp2 } +tp.enable { fwd_tp2(1, 2) } +try_("TracePoint :return binding.eval('raw(...)')") { seen } +class Object; alias_method :e2, :eval; end +def via_alias(...) = [keeps2(...), e2("raw(...)")] +try_("eval through an alias after a mutating callee") { via_alias(1, 2) } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 95e310e43..ec795cece 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -6485,6 +6485,32 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/dotsfwd (/perf-frame, 2026-11-27) - `...` forwarding without the rest Array: stopped + before building, the forwarded values are reachable after the call** (no code; on bbe4b1a, + 4320d4a with claude/perf-lsite and perf/delegate's shape files). The target was the callee's + rest taking the caller's anonymous Array, sound only if nothing can name it (the gate turned + off perf/forward's ForwardedRest for a named rest that eval and a TracePoint binding could read). + - **What CRuby 4.0 does** (`Util/anon-forward-matrix.rb`, new). Nothing *names* them: + `local_variables`, `binding.local_variables` and a TracePoint `:return` binding's + `local_variables` are empty, `binding.local_variable_get(:"...")` and `(:*)` raise NameError. + But the method's own body can forward them again after the call, and must then pass what it + was given: a second `raw(...)`, `raw(*)` and `raw(**)` after a callee that grew its rest or + added to its kwrest see the original values; so do `eval("raw(...)")`, `binding.eval`, + `instance_eval`, `send(:eval, ...)`, `eval` through an alias (`alias_method :e2, :eval`) and a + TracePoint `:return` hook's `binding.eval("raw(...)")`; `eval("raw(*)")`, `("raw(**)")`, + `("raw(&)")` re-forward the anonymous ones. IronRuby prints the same in all of these (as built, + `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`), so there is no difference to fix. + - **So sharing is not sound.** A callee that keeps or mutates its rest would change what a later + forward sees, and a static guard ("forwards once, no eval in the body") cannot see an eval + reached through `send`, an alias or a TracePoint hook. Per the brief, stopped here. + - **What the 60 ns are not.** `...` costs IronRuby 111.7 ns against fixed 51.9 (perf/nilblock), + CRuby 45.7 against 37.3: CRuby's forward costs ~8 ns, IronRuby's ~60. The copy a sound forward + keeps is one Array; most of the 60 is the rest Array built at the wrapper's entry (which an + eval may reach, so it stays) and the splat call's own dispatch (the rule unpacking it, the + callee's entry) - machinery that can be made cheaper without sharing anything: for a callee + that takes the elements positionally (`two(a, b)`) no second Array is made at all, so the + question there is only what the splat site costs. That is the next step for `...`. + - **perf/nilblock (/perf-frame, 2026-11-27) - a nil block parameter or argument: measured by clock, no cost to remove** (no code; built on d206f90, which is 4320d4a with claude/perf-lsite). perf/delegate (3ea2ea5) counted a nil `&k` parameter or `&nil` argument at 440-600 instructions From d136ef2b45744cd3a4b8b37e3ef2d32343e42f81 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:42:30 +0000 Subject: [PATCH 178/439] Thread#backtrace: a thread blocked in a core method shows that method MRI puts the C method a thread is blocked in on top of its backtrace: 'Thread::Mutex#lock', 'Thread::Queue#pop' (or SizedQueue's), 'Thread::SizedQueue#push', 'Thread#join', 'Thread#value', 'Thread::ConditionVariable#wait', 'Thread.stop'. IronRuby's library methods have no frame in another thread's recorded stack, so the backtrace began at the Ruby caller, or said 'Kernel#sleep' for the waits that sleep. Each of these now names itself in the thread's BlockedLabel (which sockets already used) for the time it may block, unless an outer one did (Thread#value around its join), and the label wins over Kernel#sleep. Only the blocking paths set it. Util/thread-backtrace-matrix.rb: the mutex row now agrees with CRuby 4.0. The "main, seen by child" row still differs: without a GVL the child reads main's stack before main reaches Queue#pop. core/thread, mutex, conditionvariable, queue, sizedqueue, library/monitor and timeout specs show only the known into/to error, the thread, fiber, mutex and queue IronRuby.Tests pass, and Thread_BlockedMethodFrame1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/FiberTests.cs | 28 +++++++++++ Src/Libraries/Builtins/ThreadOps.cs | 46 +++++++++++++++++-- Src/Libraries/Thread/RubyConditionVariable.cs | 7 ++- Src/Libraries/Thread/RubyMutex.cs | 2 + Src/Libraries/Thread/RubyQueue.cs | 3 ++ Src/Libraries/Thread/SizedQueue.cs | 3 ++ 7 files changed, 86 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 8d5a3f1f3..d19a00bb7 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1218,6 +1218,7 @@ public Tests(Driver/*!*/ driver) { WeakMap_NoBlock1, Fiber_ThreadRaiseReachesRunningFiber1, Thread_HandleInterruptOtherRuntime1, + Thread_BlockedMethodFrame1, Thread_HandleInterruptInherited1, Thread_HandleInterruptIoWrite1, Thread_RaiseBetweenBlockCallsMeetsRescue1, diff --git a/Src/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index 72e8b2969..a0f7de3da 100644 --- a/Src/IronRuby.Tests/Runtime/FiberTests.cs +++ b/Src/IronRuby.Tests/Runtime/FiberTests.cs @@ -121,6 +121,34 @@ sleep 0.01 ", "[0, 0, 0, 2]"); } + /// + /// Thread#backtrace of a thread blocked in a core method shows that method on top, as MRI's does: + /// Mutex#lock, Queue#pop, SizedQueue#push, Thread#join and #value, ConditionVariable#wait, + /// Thread.stop. + /// + public void Thread_BlockedMethodFrame1() { + TestOutput(@" +require 'ruby4' +def lbl(t) = (sleep 0.1 until t.status == ""sleep""; t.backtrace.map { |l| l[/'.*'/] }) +m = Mutex.new; m.lock +t = Thread.new { m.lock }; p lbl(t); m.unlock; t.join +q = Queue.new; t = Thread.new { q.pop }; p lbl(t); q << 1; t.join +sq = SizedQueue.new(1); sq << 1; t = Thread.new { sq.push(2) }; p lbl(t); sq.pop; t.join +zq = Queue.new; z = Thread.new { zq.pop }; t = Thread.new { z.join }; p lbl(t); zq << 1; t.join +zq = Queue.new; z = Thread.new { zq.pop }; t = Thread.new { z.value }; p lbl(t); zq << 1; t.join +cv = ConditionVariable.new; m2 = Mutex.new; t = Thread.new { m2.lock; cv.wait(m2); m2.unlock }; p lbl(t); m2.synchronize { cv.signal }; t.join +t = Thread.new { Thread.stop }; p lbl(t); t.wakeup; t.join +", @" +[""'Thread::Mutex#lock'"", ""'block in
'""] +[""'Thread::Queue#pop'"", ""'block in
'""] +[""'Thread::SizedQueue#push'"", ""'block in
'""] +[""'Thread#join'"", ""'block in
'""] +[""'Thread#value'"", ""'block in
'""] +[""'Thread::ConditionVariable#wait'"", ""'block in
'""] +[""'Thread.stop'"", ""'block in
'""] +"); + } + /// /// Thread.handle_interrupt holds a Thread#raise back in every runtime of the process. The /// exception's class used to be looked up in the first runtime created, whatever runtime the diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 33209830b..2cc06088e 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -808,7 +808,9 @@ public static object NativeBacktrace(RubyContext/*!*/ context, Thread/*!*/ self) } RubyArray trace = RubyExceptionData.CreateBacktrace(context, self); RubyThreadInfo info = RubyThreadInfo.FromThread(self); - string blockedIn = info.IsSleeping ? "Kernel#sleep" : info.BlockedLabel; + // the core method it is blocked in, which has no frame of its own: Mutex#lock, Queue#pop... or, + // for a plain sleep, Kernel#sleep + string blockedIn = info.BlockedLabel ?? (info.IsSleeping ? "Kernel#sleep" : null); if (trace != null && trace.Count > 0 && blockedIn != null) { string caller = trace[0].ToString(); int label = caller.LastIndexOf(":in ", StringComparison.Ordinal); @@ -898,6 +900,15 @@ public static ThreadGroup Group(Thread/*!*/ self) { /// Answers whether the thread finished within . /// private static bool JoinWithSafePoints(Thread/*!*/ self, int timeout) { + string previous = EnterBlockingMethod("Thread#join"); + try { + return JoinWithSafePointsCore(self, timeout); + } finally { + ExitBlockingMethod(previous); + } + } + + private static bool JoinWithSafePointsCore(Thread/*!*/ self, int timeout) { long deadline = (timeout == Timeout.Infinite) ? Int64.MaxValue : Environment.TickCount64 + timeout; while (true) { try { @@ -1294,10 +1305,34 @@ public static object Status(Thread/*!*/ self) { [RubyMethod("value")] public static object Value(RubyContext/*!*/ context, Thread/*!*/ self) { - Join(context, self); + string previous = EnterBlockingMethod("Thread#value"); + try { + Join(context, self); + } finally { + ExitBlockingMethod(previous); + } return RubyThreadInfo.FromThread(self).Result; } + /// + /// Names the core method the current thread is in and may block in ("Thread::Mutex#lock") for + /// Thread#backtrace, which MRI shows on top of a blocked thread's stack and IronRuby has no frame + /// for - unless an outer one (Thread#value around its join) has named it already. Pass the answer + /// to . + /// + internal static string EnterBlockingMethod(string/*!*/ label) { + RubyThreadInfo info = RubyThreadInfo.Current; + string previous = info.BlockedLabel; + if (previous == null) { + info.BlockedLabel = label; + } + return previous; + } + + internal static void ExitBlockingMethod(string previous) { + RubyThreadInfo.Current.BlockedLabel = previous; + } + // stop? // declared singleton methods @@ -1714,7 +1749,12 @@ public static void Stop(RubyContext/*!*/ context, object self) { if (RubyThreadInfo.GetRactorThreads(context).Length <= 1) { throw new ThreadError("stopping only thread\n\tnote: use sleep to stop forever"); } - DoSleep(); + string previous = EnterBlockingMethod("Thread.stop"); + try { + DoSleep(); + } finally { + ExitBlockingMethod(previous); + } } internal static void DoSleep() { diff --git a/Src/Libraries/Thread/RubyConditionVariable.cs b/Src/Libraries/Thread/RubyConditionVariable.cs index 297a9cfc9..d3b7093e0 100644 --- a/Src/Libraries/Thread/RubyConditionVariable.cs +++ b/Src/Libraries/Thread/RubyConditionVariable.cs @@ -123,6 +123,7 @@ private static object DoWait(RubyConditionVariable/*!*/ self, RubyMutex/*!*/ mut RubyMutex.Unlock(mutex); node = self._waiters.AddLast(info); } + string previousLabel = IronRuby.Builtins.ThreadOps.EnterBlockingMethod("Thread::ConditionVariable#wait"); try { if (ms < 0) { info.Sleep(); @@ -149,7 +150,11 @@ private static object DoWait(RubyConditionVariable/*!*/ self, RubyMutex/*!*/ mut } // Uninterruptibly: MRI promises the mutex is held again when #wait returns, even // if the thread was killed while it was waiting to get it back. - RubyMutex.DoLock(mutex, false); + try { + RubyMutex.DoLock(mutex, false); + } finally { + IronRuby.Builtins.ThreadOps.ExitBlockingMethod(previousLabel); + } } return result; } diff --git a/Src/Libraries/Thread/RubyMutex.cs b/Src/Libraries/Thread/RubyMutex.cs index c5f1e3870..11fcea372 100644 --- a/Src/Libraries/Thread/RubyMutex.cs +++ b/Src/Libraries/Thread/RubyMutex.cs @@ -166,6 +166,7 @@ private void LockContended(Thread/*!*/ me, bool interruptible) { if (!RubyUtils.PrepareNudgeableWait()) { interrupted = true; } else { + string previous = IronRuby.Builtins.ThreadOps.EnterBlockingMethod("Thread::Mutex#lock"); try { using (RubyUtils.BlockingWait.Enter()) { Monitor.Wait(_syncRoot); @@ -173,6 +174,7 @@ private void LockContended(Thread/*!*/ me, bool interruptible) { } catch (ThreadInterruptedException) { interrupted = true; } finally { + IronRuby.Builtins.ThreadOps.ExitBlockingMethod(previous); RubyUtils.NudgeableWaitDone(); } } diff --git a/Src/Libraries/Thread/RubyQueue.cs b/Src/Libraries/Thread/RubyQueue.cs index 17649a40b..bd7da688a 100644 --- a/Src/Libraries/Thread/RubyQueue.cs +++ b/Src/Libraries/Thread/RubyQueue.cs @@ -109,6 +109,7 @@ protected object Dequeue(int timeoutMilliseconds) { } private bool WaitOnQueue(int milliseconds) { + string previous = IronRuby.Builtins.ThreadOps.EnterBlockingMethod(this is SizedQueue ? "Thread::SizedQueue#pop" : "Thread::Queue#pop"); try { using (RubyUtils.BlockingWait.Enter()) { return milliseconds == Timeout.Infinite ? Monitor.Wait(_queue) : Monitor.Wait(_queue, milliseconds); @@ -116,6 +117,8 @@ private bool WaitOnQueue(int milliseconds) { } catch (ThreadInterruptedException) { RubyUtils.TranslateThreadInterrupt(); return true; + } finally { + IronRuby.Builtins.ThreadOps.ExitBlockingMethod(previous); } } diff --git a/Src/Libraries/Thread/SizedQueue.cs b/Src/Libraries/Thread/SizedQueue.cs index f8b3fc961..d5de6a68f 100644 --- a/Src/Libraries/Thread/SizedQueue.cs +++ b/Src/Libraries/Thread/SizedQueue.cs @@ -55,6 +55,7 @@ private bool Enqueue(object value, int timeoutMilliseconds) { try { while (_queue.Count >= _limit) { bool signalled; + string previous = IronRuby.Builtins.ThreadOps.EnterBlockingMethod("Thread::SizedQueue#push"); try { using (RubyUtils.BlockingWait.Enter()) { if (timeoutMilliseconds < 0) { @@ -67,6 +68,8 @@ private bool Enqueue(object value, int timeoutMilliseconds) { } catch (ThreadInterruptedException) { RubyUtils.TranslateThreadInterrupt(); continue; + } finally { + IronRuby.Builtins.ThreadOps.ExitBlockingMethod(previous); } CheckOpen(); if (!signalled) { From e34d236cdf87ded7d442248ba50aa4105d90a8e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:46:24 +0000 Subject: [PATCH 179/439] Ask the `!=' sharing question in TryShareVersionFromLookup too The gate branch's TryShareVersionFromLookup adds a class version to a shared rule's set from the method lookup cache, and calls DispatchIntrinsics.MaySpecialize, which since perf/neqrule takes the receiver: a `!=' rule is shared only for a plain object whose class resolves `==' to BasicObject's. Passing the receiver keeps that check on this path, so a class with an `==' of its own is not added to the set here either. Util/neq-share-matrix.rb prints CRuby's output with the JIT on and off and with IR_SHARED_NEQ=0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 0b92088d4..ad04cec5b 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -522,7 +522,7 @@ private bool TryShareVersionFromLookup(RubyContext/*!*/ context, object/*!*/ tar if (visibility == RubyMethodVisibility.Protected || !allVisible && visibility != RubyMethodVisibility.Public) { return false; } - if (DispatchIntrinsics.MaySpecialize(lookup.Info, Signature, targetClass)) { + if (DispatchIntrinsics.MaySpecialize(lookup.Info, Signature, targetClass, target)) { return false; } From 81944370746af70f4ac3e4296d812184c385f8bb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:48:03 +0000 Subject: [PATCH 180/439] Enumerator::Lazy: record #inspect without a prepended module The chain methods that record themselves for Lazy#inspect (reject, take, with_index, each_slice...) were wrapped in a module prepended to Enumerator::Lazy, so Lazy.ancestors began with Enumerator::LazyInspect where MRI's has nothing prepended. The wrappers are now defined in Lazy itself, each around the method it replaces (bound and called where the module called super), and the module is gone. Util/enum-matrix.rb now agrees with CRuby 4.0; core/enumerator specs and the enumerator IronRuby.Tests pass, and Enumerator_LazyAncestors1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/EnumeratorTests.cs | 31 +++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 27 ++++++++-------- 3 files changed, 45 insertions(+), 14 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index d19a00bb7..350c8408a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1057,6 +1057,7 @@ public Tests(Driver/*!*/ driver) { Enumerator_ExternalCursor1, Enumerator_ExternalFiber1, Enumerator_LazyEachResult1, + Enumerator_LazyAncestors1, Enumerator_ChainNoNext1, Io_Messages1, Encoding_Misc1, diff --git a/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs b/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs index ca1f38584..de084ffe5 100644 --- a/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs +++ b/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs @@ -171,6 +171,37 @@ class Array // A lazy operation's #each answers nil (lazy_add_method), and so StopIteration#result is nil // at the end of its #next; the source's own lazy answers what the source's #each does. + /// + /// Enumerator::Lazy has nothing prepended, as in MRI: the chain methods that record themselves for + /// #inspect are wrapped in Lazy itself. + /// + public void Enumerator_LazyAncestors1() { + TestOutput(@" +require 'ruby4' +p Enumerator::Lazy.ancestors +p (1..3).lazy.singleton_class.ancestors[1, 2] +l = (1..Float::INFINITY).lazy +p l.reject(&:even?).take(3), l.reject(&:even?).take(3).to_a +p l.with_index.map { |x, i| x * i }.first(3), l.each_slice(2).first(2), l.zip(l).first(2) +p l.filter_map { |x| x * 2 if x.odd? }.uniq.take_while { |x| x < 10 } +p (1..3).lazy.cycle.take(5).to_a, (1..3).lazy.compact.drop(1).to_a, (1..5).lazy.chunk_while { |a, b| b == a + 1 }.first(1) +p Enumerator::Lazy.instance_method(:take).owner +", @" +[Enumerator::Lazy, Enumerator, Enumerable, Object, Kernel, BasicObject] +[Enumerator::Lazy, Enumerator] +#:reject>:take(3)> +[1, 3, 5] +[0, 2, 6] +[[1, 2], [3, 4]] +[[1, 1], [2, 2]] +#:filter_map>:uniq>:take_while> +[1, 2, 3, 1, 2] +[2, 3] +[[1, 2, 3, 4, 5]] +Enumerator::Lazy +"); + } + public void Enumerator_LazyEachResult1() { TestOutput(@" require 'ruby4' diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 8d145c73e..d5b952047 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -6570,23 +6570,22 @@ def __to_int__(value) # Each lazy chain method records itself for #inspect: # #:map>. grep and grep_v, which # need the caller's frame, record themselves in __ir_lazy_grep_impl__. - module LazyInspect - # map, flat_map and select record themselves: their aliases (collect, filter, ...) - # have to stay the very same method. - [:reject, :filter_map, :compact, :uniq, :take, :take_while, :drop, :drop_while, :with_index, - :each_with_index, :with_object, :zip, :chunk, :chunk_while, - :slice_when, :slice_before, :slice_after, :each_slice, :each_cons, :cycle].each do |name| - define_method(name) do |*args, &block| - result = super(*args, &block) - if result.is_a?(::Enumerator::Lazy) && !result.equal?(self) - result.__set_inspect__(self, name, name == :with_index && args.empty? ? [0] : args) - end - result + # map, flat_map and select record themselves: their aliases (collect, filter, ...) + # have to stay the very same method. The others are wrapped here, in Lazy itself + # around the method each replaces, not in a prepended module: MRI's Lazy has nothing + # prepended, and Lazy.ancestors would show it. + [:reject, :filter_map, :compact, :uniq, :take, :take_while, :drop, :drop_while, :with_index, + :each_with_index, :with_object, :zip, :chunk, :chunk_while, + :slice_when, :slice_before, :slice_after, :each_slice, :each_cons, :cycle].each do |name| + original = Lazy.instance_method(name) + Lazy.send(:define_method, name) do |*args, &block| + result = original.bind_call(self, *args, &block) + if result.is_a?(::Enumerator::Lazy) && !result.equal?(self) + result.__set_inspect__(self, name, name == :with_index && args.empty? ? [0] : args) end + result end end - __hide_constant__ :LazyInspect - Lazy.prepend(LazyInspect) # --- Enumerator::Chain ------------------------------------------------- class Chain < Enumerator From 3e3fa33130875e0346cf7bf8dde6ac3bbc83859a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:50:21 +0000 Subject: [PATCH 181/439] Share an eval'd text's code when it has regexp or range literals, their objects kept per eval perf/evalscreen left the regexp literal as the commonest reason an eval'd text's compiled code is not shared (6 of the 11 refused templates of the standard library; such a render costs 2.7 times a shared one). The screen refused it because the literal's object was a constant of the code, while CRuby makes a new Regexp per eval of the same text - the same one for every pass and every block call within one eval, and an escaped Proc keeps its eval's - and the same for an Integer range literal. A plain string eval whose tree has a regexp or a range now keeps its literals' objects in an EvalLiterals, one slot per literal site, which its top level makes at entry in a hidden variable. A literal of the top level reads its slot from there; every Proc the text instantiates carries it (RubyOps.AttachEvalLiterals, Proc.EvalLiterals in the Proc's rare state, kept by its copies), and a literal in a block reads it through the block's BlockParam - not the binding's scope, which every eval through the binding shares. Eval'd code replaces no loops, so a block body always has its BlockParam. A literal in a def or class body of the text keeps its object in the code as before (the screen still refuses those). The screen lets in regexp literals, regexp conditions and ranges; a flip-flop stays out. IR_EVAL_LITERALS=0 turns all of it off. Instructions a render (Util/perf/callgrind/count.sh, switch off -> on): the page with a regexp 3,399,928 -> 1,283,572 (0.378); the plain page, the page with defined? and eval('1 + 1') unchanged. Timed 613 -> 223 us. All 80 ERB templates of the standard library now share their code. Util/eval-literals-matrix.rb (new) checks literal identity across and within evals, escaped Procs, Proc copies, /o, interpolation, ranges, $~, threads and ERB; it prints CRuby 4.0's output on the unchanged build and on this one by default, with the switch off, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. The eval, regexp, erb-escape, lexical-light, block-scope-reuse and hot-shapes matrices print what they did. Specs core/kernel/eval, core/binding, language/regexp, core/regexp and library/erb give the same results on both builds. Eval_SharedLiterals1 is new. ReflectionCache.Generated.cs is ClassInitGenerator's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 38 +++++++++ Src/Ruby/Builtins/Proc.cs | 13 +++ Src/Ruby/Compiler/Ast/BlockDefinition.cs | 5 ++ .../Ast/Expressions/RangeExpression.cs | 6 ++ .../Ast/Expressions/RegularExpression.cs | 10 +-- Src/Ruby/Compiler/Ast/SourceUnitTree.cs | 11 +++ Src/Ruby/Compiler/AstGenerator.cs | 26 ++++++ .../Compiler/ReflectionCache.Generated.cs | 10 +++ Src/Ruby/Runtime/EvalCodeCache.cs | 47 ++++++++++- Src/Ruby/Runtime/EvalLiterals.cs | 47 +++++++++++ Src/Ruby/Runtime/RubyOps.cs | 34 ++++++++ Util/eval-literals-matrix.rb | 81 +++++++++++++++++++ 13 files changed, 321 insertions(+), 8 deletions(-) create mode 100644 Src/Ruby/Runtime/EvalLiterals.cs create mode 100644 Util/eval-literals-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 28711ce6e..93e6660cf 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1298,6 +1298,7 @@ public Tests(Driver/*!*/ driver) { EvalWithProcBinding1, Eval_LocalVariableSites1, Eval_SharedDefined1, + Eval_SharedLiterals1, ModuleEvalProc1, ModuleEvalProc2, ModuleEvalProc3, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index addfc687b..8d3af250f 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8090,6 +8090,44 @@ def blk(&b) = eval(""defined?(yield) ? yield : :noblock"", binding) "); } + /// + /// IR_EVAL_LITERALS: a text with regexp and range literals shares its compiled code between evals, its literals' objects + /// kept per eval (EvalLiterals): a new one per eval, the same one for every pass and block call of one eval and for a + /// Proc that escaped it, /o once per eval, threads each with their own (Util/eval-literals-matrix.rb). + /// + public void Eval_SharedLiterals1() { + TestOutput(@" +require 'ruby4' +B = binding +def distinct(a) = a.map(&:object_id).uniq.size +p distinct(3.times.map { eval(""/a\\w/"", B) }), distinct(eval(""4.times.map { /a\\w/ }"", B)), eval(""[/s/, /s/]"", B).then { |r| r[0].equal?(r[1]) } +pr = eval(""proc { /esc/ }"", B); first = pr.call; other = eval(""proc { /esc/ }"", B).call +p pr.call.equal?(first), first.equal?(other), pr.dup.call.equal?(first) +V = binding.tap { |b| b.local_variable_set(:v, ""z"") } +p distinct(3.times.map { eval('/#{v}/o', V) }), distinct(eval('3.times.map { /#{v}/o }', V)), distinct(eval('3.times.map { /#{v}/ }', V)) +p eval(""(1..2)"", B).frozen?, distinct(3.times.map { eval(""(1..2)"", B) }), distinct(eval(""3.times.map { (1...4) }"", B)) +eval('""xab"" =~ /a(b)/', binding); p $~[1] +rs = 4.times.map { Thread.new { 20.times.map { eval(""2.times.map { /th/ }"", B) } } }.map(&:value).flatten(1) +p rs.all? { |pair| pair[0].equal?(pair[1]) }, distinct(rs.map(&:first)) == rs.size +", @" +3 +1 +false +true +false +true +3 +1 +3 +true +3 +1 +""b"" +true +true +"); + } + /// /// A method that reads or writes a global is a light frame too (MethodDefinition.IsLightGlobal): every global but $~ and /// $_ is the runtime's, and the frame reads and writes it through the declaring scope. A name that comes to denote $~ or $_ diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index c9a012f9f..ba80774af 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -84,6 +84,8 @@ private sealed class RareState { public string SymbolName; public bool IsIsolated; public string CalleeName; + // the literals of the eval whose text this Proc's block is written in (IronRuby.Runtime.EvalLiterals) + public EvalLiterals EvalLiterals; } private RareState _rare; @@ -270,6 +272,15 @@ public bool IsIsolated { set { if (value || _rare != null) { Rare.IsIsolated = value; } } } + /// + /// The literals of the eval whose text this Proc's block is written in, which its block's code reads its regexp and + /// range literals from (RubyOps.GetBlockEvalLiterals); null for any other block. A copy of the Proc keeps them. + /// + internal EvalLiterals EvalLiterals { + get { var r = _rare; return (r != null) ? r.EvalLiterals : null; } + set { if (value != null || _rare != null) { Rare.EvalLiterals = value; } } + } + public string SourcePath { get { return _dispatcher.SourcePath; } } @@ -297,6 +308,7 @@ protected Proc(Proc/*!*/ proc) Converter = proc.Converter; IsIsolated = proc.IsIsolated; SymbolName = proc.SymbolName; + EvalLiterals = proc.EvalLiterals; } /// @@ -308,6 +320,7 @@ protected Proc(Proc/*!*/ proc) result.Converter = Converter; result.SymbolName = SymbolName; result.IsIsolated = true; + result.EvalLiterals = EvalLiterals; return result; } diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index 3e4a2168b..d9815f0bd 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -523,6 +523,11 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St // a literal nested in a block whose Proc may be reused (see reusesProc above): its Proc reaches that one instance = Methods.KeepEnclosingProcs.OpCall(instance, gen.CurrentScopeVariable); } + // a block of an eval'd text whose literals are kept per eval takes the eval's with it (AstGenerator.GetEvalLiterals) + var evalLiterals = gen.GetEvalLiterals(); + if (evalLiterals != null) { + instance = Methods.AttachEvalLiterals.OpCall(instance, evalLiterals); + } return reusesProc ? Ast.Assign(previousProc, instance) : instance; } diff --git a/Src/Ruby/Compiler/Ast/Expressions/RangeExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/RangeExpression.cs index 86f422ddc..82469be07 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/RangeExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/RangeExpression.cs @@ -68,6 +68,12 @@ private bool IsIntegerRange(out int intBegin, out int intEnd) { // a Range is frozen, and MRI makes a literal one of integers a single object, which // the expression evaluates to every time gen.HasLiteralState = true; + // one per eval of a text whose code is shared (AstGenerator.GetEvalLiterals) + var literals = gen.GetEvalLiterals(); + if (literals != null) { + return Methods.GetEvalIntegerRange.OpCall(literals, AstUtils.Constant(gen.EvalLiteralCount++), + AstUtils.Constant(intBegin), AstUtils.Constant(intEnd), AstUtils.Constant(_isExclusive)); + } return AstUtils.Constant(new IronRuby.Builtins.Range(intBegin, intEnd, _isExclusive)); } else { return (_isExclusive ? Methods.CreateExclusiveRange : Methods.CreateInclusiveRange).OpCall( diff --git a/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs index 57a31237d..aa3ef0b45 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs @@ -60,7 +60,7 @@ public RegularExpression(List/*!*/ pattern, RubyRegexOptions options // TODO: create the regex here, not at runtime: gen.HasLiteralState = true; return Methods.CreateRegexL.OpCall( - Ast.Constant(literal), encoding.Expression, AstUtils.Constant(_options), AstUtils.Constant(new StrongBox(null)) + Ast.Constant(literal), encoding.Expression, AstUtils.Constant(_options), gen.RegexCacheBox() ); } @@ -68,7 +68,7 @@ public RegularExpression(List/*!*/ pattern, RubyRegexOptions options // TODO: create the regex here, not at runtime: gen.HasLiteralState = true; return Methods.CreateRegexB.OpCall( - Ast.Constant(literal), encoding.Expression, AstUtils.Constant(_options), AstUtils.Constant(new StrongBox(null)) + Ast.Constant(literal), encoding.Expression, AstUtils.Constant(_options), gen.RegexCacheBox() ); } @@ -78,7 +78,7 @@ public RegularExpression(List/*!*/ pattern, RubyRegexOptions options return Methods.CreateRegex("N").OpCall( Ast.NewArrayInit(typeof(MutableString), args), AstUtils.Constant(_options), - AstUtils.Constant(new StrongBox(null)) + gen.RegexCacheBox() ); } @@ -94,14 +94,14 @@ public RegularExpression(List/*!*/ pattern, RubyRegexOptions options encoding = sourceEncoding; } return Methods.CreateRegexB.OpCall( - Ast.Constant(literal.ToByteArray()), encoding.Expression, AstUtils.Constant(_options), AstUtils.Constant(new StrongBox(null)) + Ast.Constant(literal.ToByteArray()), encoding.Expression, AstUtils.Constant(_options), gen.RegexCacheBox() ); } string suffix = new String('M', args.Count); args.Add(gen.Encoding.Expression); args.Add(AstUtils.Constant(_options)); - args.Add(AstUtils.Constant(new StrongBox(null))); + args.Add(gen.RegexCacheBox()); return Methods.CreateRegex(suffix).OpCall(args); } diff --git a/Src/Ruby/Compiler/Ast/SourceUnitTree.cs b/Src/Ruby/Compiler/Ast/SourceUnitTree.cs index 602671887..0f99de067 100644 --- a/Src/Ruby/Compiler/Ast/SourceUnitTree.cs +++ b/Src/Ruby/Compiler/Ast/SourceUnitTree.cs @@ -115,6 +115,12 @@ public SourceUnitTree(LexicalScope/*!*/ definedScope, Statements/*!*/ statements ); gen.CurrentMethod.HasOwnCompiledFrame = true; + // a plain string eval's regexp and Integer range literals are kept per eval, so that its code can be shared + // (EvalCodeCache, IronRuby.Runtime.EvalLiterals) + if (gen.CompilerOptions.FactoryKind == TopScopeFactoryKind.None && EvalCodeCache.KeepsLiteralsPerEval(this)) { + gen.EvalLiteralsVariable = scope.DefineHiddenVariable("#evalLiterals", typeof(EvalLiterals)); + } + MSA.Expression body; if (_statements.Count > 0) { @@ -201,6 +207,11 @@ public SourceUnitTree(LexicalScope/*!*/ definedScope, Statements/*!*/ statements throw Assert.Unreachable; } + if (gen.EvalLiteralsVariable != null) { + prologue = Ast.Block(prologue, + Ast.Assign(gen.EvalLiteralsVariable, Methods.CreateEvalLiterals.OpCall(AstUtils.Constant(gen.EvalLiteralCount)))); + } + body = Ast.Block(prologue, body); body = gen.AddReturnTarget(scope.CreateScope(body)); diff --git a/Src/Ruby/Compiler/AstGenerator.cs b/Src/Ruby/Compiler/AstGenerator.cs index ddb64d8d1..fb842a6dd 100644 --- a/Src/Ruby/Compiler/AstGenerator.cs +++ b/Src/Ruby/Compiler/AstGenerator.cs @@ -76,6 +76,32 @@ internal AstGenerator(RubyContext/*!*/ context, RubyCompilerOptions/*!*/ options // keeps (a Regexp literal, `/.../o', an Integer Range literal): two compilations of it answer two objects. internal bool HasLiteralState { get; set; } + // A plain string eval whose text has a regexp or Integer range literal (IR_EVAL_LITERALS): the top level's hidden + // variable that holds the eval's literals (IronRuby.Runtime.EvalLiterals), and how many slots the code takes. + internal MSA.ParameterExpression EvalLiteralsVariable { get; set; } + internal int EvalLiteralCount { get; set; } + + /// + /// The eval's literals as the code being transformed reaches them: the top level's variable, or in a block of the text + /// the Proc its BlockParam belongs to; null outside such a text, in a def or a class body in it (which the eval cache + /// refuses), where a literal keeps its object in the compiled code as before. + /// + internal MSA.Expression GetEvalLiterals() { + if (EvalLiteralsVariable == null || CurrentMethod != TopLevelScope || GetEnclosingModuleFrame() != null) { + return null; + } + return (CurrentBlock == null) ? (MSA.Expression)EvalLiteralsVariable : Methods.GetBlockEvalLiterals.OpCall(CurrentBlock.BfcVariable); + } + + /// The cache box of a regexp literal: one per eval of a shared text (), else one of the code. + internal MSA.Expression/*!*/ RegexCacheBox() { + var literals = GetEvalLiterals(); + if (literals != null) { + return Methods.GetEvalRegexBox.OpCall(literals, AstUtils.Constant(EvalLiteralCount++)); + } + return AstUtils.Constant(new StrongBox(null)); + } + public RubyCompilerOptions/*!*/ CompilerOptions { get { return _compilerOptions; } } diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 9e41faeac..27ec1a058 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -44,6 +44,8 @@ public static partial class Methods { private static MethodInfo _AllocateStructInstance; public static MethodInfo/*!*/ ArrayLiteralExtreme { get { return _ArrayLiteralExtreme ?? (_ArrayLiteralExtreme = CallInstruction.CacheFunc(RubyOps.ArrayLiteralExtreme)); } } private static MethodInfo _ArrayLiteralExtreme; + public static MethodInfo/*!*/ AttachEvalLiterals { get { return _AttachEvalLiterals ?? (_AttachEvalLiterals = CallInstruction.CacheFunc(RubyOps.AttachEvalLiterals)); } } + private static MethodInfo _AttachEvalLiterals; public static MethodInfo/*!*/ AutoSplatArgument { get { return _AutoSplatArgument ?? (_AutoSplatArgument = CallInstruction.CacheFunc(RubyOps.AutoSplatArgument)); } } private static MethodInfo _AutoSplatArgument; public static MethodInfo/*!*/ BeginPark { get { return _BeginPark ?? (_BeginPark = CallInstruction.CacheFunc(RubyOps.BeginPark)); } } @@ -124,6 +126,8 @@ public static partial class Methods { private static MethodInfo _CreateDelegateFromProc; public static MethodInfo/*!*/ CreateEncoding { get { return _CreateEncoding ?? (_CreateEncoding = CallInstruction.CacheFunc(RubyOps.CreateEncoding)); } } private static MethodInfo _CreateEncoding; + public static MethodInfo/*!*/ CreateEvalLiterals { get { return _CreateEvalLiterals ?? (_CreateEvalLiterals = CallInstruction.CacheFunc(RubyOps.CreateEvalLiterals)); } } + private static MethodInfo _CreateEvalLiterals; public static MethodInfo/*!*/ CreateEvent { get { return _CreateEvent ?? (_CreateEvent = CallInstruction.CacheFunc(RubyOps.CreateEvent)); } } private static MethodInfo _CreateEvent; public static MethodInfo/*!*/ CreateExclusiveRange { get { return _CreateExclusiveRange ?? (_CreateExclusiveRange = CallInstruction.CacheFunc(RubyOps.CreateExclusiveRange)); } } @@ -260,6 +264,8 @@ public static partial class Methods { private static MethodInfo _GetArrayItem; public static MethodInfo/*!*/ GetArrayRange { get { return _GetArrayRange ?? (_GetArrayRange = CallInstruction.CacheFunc(RubyOps.GetArrayRange)); } } private static MethodInfo _GetArrayRange; + public static MethodInfo/*!*/ GetBlockEvalLiterals { get { return _GetBlockEvalLiterals ?? (_GetBlockEvalLiterals = CallInstruction.CacheFunc(RubyOps.GetBlockEvalLiterals)); } } + private static MethodInfo _GetBlockEvalLiterals; public static MethodInfo/*!*/ GetCachedGlobalVariable { get { return _GetCachedGlobalVariable ?? (_GetCachedGlobalVariable = CallInstruction.CacheFunc(RubyOps.GetCachedGlobalVariable)); } } private static MethodInfo _GetCachedGlobalVariable; public static MethodInfo/*!*/ GetClassVariable { get { return _GetClassVariable ?? (_GetClassVariable = CallInstruction.CacheFunc(RubyOps.GetClassVariable)); } } @@ -290,6 +296,10 @@ public static partial class Methods { private static MethodInfo _GetCurrentPreMatch; public static MethodInfo/*!*/ GetDefaultExceptionMessage { get { return _GetDefaultExceptionMessage ?? (_GetDefaultExceptionMessage = CallInstruction.CacheFunc(RubyOps.GetDefaultExceptionMessage)); } } private static MethodInfo _GetDefaultExceptionMessage; + public static MethodInfo/*!*/ GetEvalIntegerRange { get { return _GetEvalIntegerRange ?? (_GetEvalIntegerRange = CallInstruction.CacheFunc(RubyOps.GetEvalIntegerRange)); } } + private static MethodInfo _GetEvalIntegerRange; + public static MethodInfo/*!*/ GetEvalRegexBox { get { return _GetEvalRegexBox ?? (_GetEvalRegexBox = CallInstruction.CacheFunc>(RubyOps.GetEvalRegexBox)); } } + private static MethodInfo _GetEvalRegexBox; public static MethodInfo/*!*/ GetExpressionQualifiedConstant { get { return _GetExpressionQualifiedConstant ?? (_GetExpressionQualifiedConstant = CallInstruction.CacheFunc(RubyOps.GetExpressionQualifiedConstant)); } } private static MethodInfo _GetExpressionQualifiedConstant; public static MethodInfo/*!*/ GetGlobalMissingConstant { get { return _GetGlobalMissingConstant ?? (_GetGlobalMissingConstant = CallInstruction.CacheFunc(RubyOps.GetGlobalMissingConstant)); } } diff --git a/Src/Ruby/Runtime/EvalCodeCache.cs b/Src/Ruby/Runtime/EvalCodeCache.cs index cf7195c45..1e5298eaa 100644 --- a/Src/Ruby/Runtime/EvalCodeCache.cs +++ b/Src/Ruby/Runtime/EvalCodeCache.cs @@ -88,6 +88,45 @@ internal static bool IsShareable(SourceUnitTree/*!*/ ast) { /// private static readonly bool ShareDefinedEnabled = Environment.GetEnvironmentVariable("IR_EVAL_SHARE_DEFINED") != "0"; + /// + /// IR_EVAL_LITERALS=0 refuses a text with a regexp or range literal again, and compiles its literals' objects into its + /// code as before (see KeepsLiteralsPerEval). + /// + internal static readonly bool EvalLiteralsEnabled = Environment.GetEnvironmentVariable("IR_EVAL_LITERALS") != "0"; + + /// + /// Whether a plain string eval of the tree keeps its literals' objects per eval (IronRuby.Runtime.EvalLiterals): it + /// has a regexp literal or a range, whose objects CRuby makes once per eval of the text. + /// + internal static bool KeepsLiteralsPerEval(SourceUnitTree/*!*/ ast) { + if (!EvalLiteralsEnabled) { + return false; + } + var finder = new LiteralFinder(); + finder.Walk(ast); + return finder.Found; + } + + private sealed class LiteralFinder : Walker { + internal bool Found; + public override bool Enter(RegularExpression/*!*/ node) { Found = true; return false; } + public override bool Enter(RangeExpression/*!*/ node) { Found = true; return false; } + + protected internal override void Walk(MethodCall/*!*/ node) { + base.Walk(node); + if (node.Block != null) { + node.Block.Walk(this); + } + } + + protected internal override void Walk(ParallelAssignmentExpression/*!*/ node) { + base.Walk(node); + foreach (var value in node.Right) { + value.Walk(this); + } + } + } + private sealed class Screen : Walker { internal bool Shareable = true; @@ -100,10 +139,12 @@ private bool Refuse() { public override bool Enter(ModuleDefinition/*!*/ node) => Refuse(); public override bool Enter(SingletonDefinition/*!*/ node) => Refuse(); public override bool Enter(MethodDefinition/*!*/ node) => Refuse(); - public override bool Enter(RangeExpression/*!*/ node) => Refuse(); + // A regexp literal and an Integer range literal keep their object per eval (KeepsLiteralsPerEval); any other range + // makes its object every time, with a call site for <=> (IR_EVAL_LITERALS). + public override bool Enter(RangeExpression/*!*/ node) => EvalLiteralsEnabled || Refuse(); public override bool Enter(RangeCondition/*!*/ node) => Refuse(); - public override bool Enter(RegularExpression/*!*/ node) => Refuse(); - public override bool Enter(RegularExpressionCondition/*!*/ node) => Refuse(); + public override bool Enter(RegularExpression/*!*/ node) => EvalLiteralsEnabled || Refuse(); + public override bool Enter(RegularExpressionCondition/*!*/ node) => EvalLiteralsEnabled || Refuse(); public override bool Enter(ShutdownHandlerStatement/*!*/ node) => Refuse(); // `defined?' keeps what the code of its operand keeps and nothing more (IR_EVAL_SHARE_DEFINED): of a local, the // answer the compile found in the locals the key holds; of a call, a call site; of a constant, a constant's cache, diff --git a/Src/Ruby/Runtime/EvalLiterals.cs b/Src/Ruby/Runtime/EvalLiterals.cs new file mode 100644 index 000000000..2a1bc49bc --- /dev/null +++ b/Src/Ruby/Runtime/EvalLiterals.cs @@ -0,0 +1,47 @@ +/* **************************************************************************** + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. + * + * ***************************************************************************/ + +using System.Runtime.CompilerServices; +using System.Threading; +using IronRuby.Builtins; + +namespace IronRuby.Runtime { + /// + /// The objects the literals of one eval of a text make - a regexp literal's Regexp, an Integer range literal's Range - + /// which CRuby makes anew for every eval of the same text and once for all the passes and block calls of one eval. The + /// compiled code of such a text is shared by every eval of it (EvalCodeCache, IR_EVAL_LITERALS), so the objects cannot + /// be constants of that code: the eval's top level makes one of these at entry (RubyOps.CreateEvalLiterals) and every + /// Proc its code instantiates carries it (Proc.EvalLiterals), so that a block of the text, compiled apart and seeing + /// only its scope - the binding's own, shared by every eval through it - still finds its eval's objects. A slot is + /// filled once, by whichever thread gets there first. + /// + public sealed class EvalLiterals { + private readonly object[]/*!*/ _slots; + + internal EvalLiterals(int count) { + _slots = new object[count]; + } + + internal StrongBox/*!*/ GetRegexBox(int index) { + var box = Volatile.Read(ref _slots[index]) as StrongBox; + if (box != null) { + return box; + } + var created = new StrongBox(null); + return Interlocked.CompareExchange(ref _slots[index], created, null) as StrongBox ?? created; + } + + internal Range/*!*/ GetIntegerRange(int index, int begin, int end, bool exclusive) { + var range = Volatile.Read(ref _slots[index]) as Range; + if (range != null) { + return range; + } + var created = new Range(begin, end, exclusive); + return Interlocked.CompareExchange(ref _slots[index], created, null) as Range ?? created; + } + } +} diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index e120e654e..43d9c35ef 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -899,6 +899,40 @@ public static object SetLocalVariable(object value, RubyScope/*!*/ scope, string /// read of the slot or cell, without the lookup by name and its lock, while the scope and the runtime's /// dynamic locals are what they were. /// + /// The literals of one eval of a text whose code may be shared (see ). + [Emitted] + public static EvalLiterals/*!*/ CreateEvalLiterals(int count) { + return new EvalLiterals(count); + } + + /// The eval's literals a block of its text reads, from the Proc the text instantiated it as. + [Emitted] + public static EvalLiterals GetBlockEvalLiterals(BlockParam/*!*/ bfc) { + return bfc.Proc.EvalLiterals; + } + + /// A Proc the eval'd text instantiated takes the eval's literals with it. + [Emitted] + public static Proc/*!*/ AttachEvalLiterals(Proc/*!*/ proc, EvalLiterals literals) { + proc.EvalLiterals = literals; + return proc; + } + + /// + /// The cache of a regexp literal of an eval'd text, one per eval. Without the eval's literals - a Proc that lost them, + /// which no path is known to - a fresh one: the regexp is right, only made again. + /// + [Emitted] + public static StrongBox/*!*/ GetEvalRegexBox(EvalLiterals literals, int index) { + return (literals != null) ? literals.GetRegexBox(index) : new StrongBox(null); + } + + /// An Integer range literal of an eval'd text: frozen, one object per eval (see ). + [Emitted] + public static Range/*!*/ GetEvalIntegerRange(EvalLiterals literals, int index, int begin, int end, bool exclusive) { + return (literals != null) ? literals.GetIntegerRange(index, begin, end, exclusive) : new Range(begin, end, exclusive); + } + [Emitted] public static object GetLocalVariableAtSite(RubyScope/*!*/ scope, LocalVariableSite/*!*/ site) { var resolution = site.Resolve(scope); diff --git a/Util/eval-literals-matrix.rb b/Util/eval-literals-matrix.rb new file mode 100644 index 000000000..5d3010adf --- /dev/null +++ b/Util/eval-literals-matrix.rb @@ -0,0 +1,81 @@ +# Differential matrix for the identity of the literals an eval'd text makes - a regexp literal, `/#{x}/o`, an +# interpolated regexp, an Integer range literal - when the text's compiled code is shared by every eval of it +# (EvalCodeCache; IR_EVAL_LITERALS lets texts with such literals in, the literals' caches kept per eval). CRuby makes +# a new object per eval of the same text, and the same one for every pass and every call of a block within one eval; +# a Proc that escapes keeps its eval's object. Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/eval-literals-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/eval-literals-matrix.rb > /tmp/on.txt 2>&1 +# IR_EVAL_LITERALS=0 ./ir.sh Util/eval-literals-matrix.rb > /tmp/off.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt + +N = 1000 + +def t(label) + print label.ljust(56), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +B = binding +def distinct(list) = list.map(&:object_id).uniq.size + +# ---------------------------------------------------------------- 1. across evals and within one + +t('top level: 3 evals') { distinct(3.times.map { eval("/a\\w/", B) }) } +t('top level: a while loop in one eval') { distinct(eval("r = []; i = 0; while i < 4; r << /a\\w/; i += 1; end; r", B)) } +t('a block, 4 calls in one eval') { distinct(eval("4.times.map { /a\\w/ }", B)) } +t('nested blocks') { distinct(eval("2.times.flat_map { [1, 2].map { /n\\w/ } }", B)) } +t('two sites with the same text') { r = eval("[/s/, /s/]", B); r[0].equal?(r[1]) } +t('a block, across evals') { distinct(3.times.flat_map { eval("2.times.map { /a\\w/ }", B) }) } +t('the top level and a block of one eval') { eval("x = /t/; [x, 2.times.map { /t/ }]", B).flatten.then { |a| distinct(a) } } +t('a lambda and a proc of one eval') { eval("l = -> { /l/ }; pr = proc { /l/ }; [l.(), l.(), pr.(), pr.()]", B).then { |a| [a[0].equal?(a[1]), a[2].equal?(a[3]), a[0].equal?(a[2])] } } +t('frozen, source, options') { r = eval("/a\\w/mi", B); [r.frozen?, r.source, r.options] } + +# ---------------------------------------------------------------- 2. Procs that escape + +t('an escaped Proc after another eval') do + pr = eval("proc { /esc/ }", B) + first = pr.call + other = eval("proc { /esc/ }", B).call + [pr.call.equal?(first), first.equal?(other)] +end +t('two Procs of one eval, kept') { ps = eval("[proc { /k/ }, proc { /k/ }]", B); [ps[0].().equal?(ps[0].()), ps[0].().equal?(ps[1].())] } +t('a Proc made into a method') do + o = Object.new + o.define_singleton_method(:m, &eval("proc { /dm/ }", B)) + [o.m.equal?(o.m), o.m.source] +end +t('copies of the Proc: dup, curry') { pr = eval("proc { /lc/ }", B); [pr.dup.().equal?(pr.()), pr.curry.().equal?(pr.())] } +t('Method#to_proc and a block passed on') { eval("def_pr = proc { /bp/ }; [1, 2].map(&def_pr)", B).then { |a| a[0].equal?(a[1]) } } + +# ---------------------------------------------------------------- 3. /o, interpolation, ranges, $~ + +v = "z" +t('/#{v}/o: 3 evals, and a loop of one') { [distinct(3.times.map { eval('/#{v}/o', binding) }), distinct(eval('3.times.map { /#{v}/o }', binding))] } +t('/#{v}/: a loop of one eval') { distinct(eval('3.times.map { /#{v}/ }', binding)) } +t('/o keeps the first value within an eval') { w = "a"; eval('2.times.map { |i| w = "b" if i == 1; /#{w}/o.source }', binding) } +t('an Integer range literal: frozen, per eval, a loop') { [eval("(1..2)", B).frozen?, distinct(3.times.map { eval("(1..2)", B) }), distinct(eval("3.times.map { (1...4) }", B))] } +t('a range of variables') { a = 1; distinct(eval("2.times.map { (a..3) }", binding)) } +t('$~ of a match in the text, in the binding\'s frame') { $~ = nil; eval('"xab" =~ /a(b)/', binding); [$~ && $~[1], $~ && $~.pre_match] } +t('$~ in a block of the text') { eval('["q1", "q2"].map { |s| s =~ /q(\\d)/; $1 }', B) } +t('a regexp as a condition (the last line)') { $_ = "hay"; quiet = $VERBOSE; $VERBOSE = nil; r = eval('/a/ ? 1 : 0', binding); $VERBOSE = quiet; r } + +# ---------------------------------------------------------------- 4. threads and templates + +t('four threads, one text') do |i| + next nil unless i % 200 == 0 + rs = 4.times.map { Thread.new { 50.times.map { eval("2.times.map { /th/ }", B) } } }.map(&:value).flatten(1) + [rs.all? { |pair| pair[0].equal?(pair[1]) }, distinct(rs.map(&:first)) == rs.size] +end +require 'erb' +T = ERB.new("<%= items.map { |s| s.sub(/^x/, 'y') }.join(',') %>|<%= (1..2).to_a.size %>") +t('ERB with a regexp and a range') { |i| T.result_with_hash(items: ["x#{i % 3}", "zx"]) } From 5472a50acd8c7c8d0a0f93b8c37853336484fb21 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:50:21 +0000 Subject: [PATCH 182/439] Ledger: perf/evalboxes landed (instructions only, not gated); gap 31 updated Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 51 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 6231849e4..30a4c214e 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1572,8 +1572,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has same text (`eval("/a/").equal?(eval("/a/"))` is false; one eval's block gets the same one on every call), so sharing the code needs the literal's cache box per eval - and a block of the text reaches nothing per eval: it is compiled apart (BlockDispatcher) and sees only the - scope, which for `eval(s, binding)` is the binding's own. Untried: carrying an eval's literal - boxes on the Procs its code instantiates. + scope, which for `eval(s, binding)` is the binding's own. + perf/evalboxes (Landed) carries an eval's literal objects on the Procs its code + instantiates: regexp and Integer range literals are let in, and all 80 templates share + their code. Left: a text with `def`, `class`, `module`, `super`, `yield`, a flip-flop or END + (none of the 80 has one), and the eval's own cost when it is shared. 32. **A singleton class, and a method defined at run time, cost 25 to 60 times CRuby's** (`Object.new.singleton_class` 17 us, `def o.x` 18, `define_singleton_method` 46, `Class.new` 12, with a `def` 37), and `OpenStruct.new(h)` of three keys, which @@ -1788,6 +1791,50 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/evalboxes (/perf-step, 2026-11-27, on 4320d4a + perf/lexical 779d87c) - an eval'd + text with regexp or range literals shares its compiled code, the literals' objects kept per + eval (`IR_EVAL_LITERALS`, gap 31)** - instructions only, not gated. The commonest refusal left + by perf/evalscreen (6 of the 11 refused stdlib templates; 2.7 times a shared render). + - What CRuby does, checked first (CRuby 4.0): a regexp literal of the text's top level is a new + object per eval and the same one for every pass of one eval's `while`; one in a block, the + same on every call of the block within the eval, and a Proc that escapes keeps its eval's + after another eval of the text; two sites with the same text are two objects; `/#{x}/o` once + per eval; an interpolated one without `o` new every time; an Integer range literal frozen, + per eval, the same within one; regexps frozen; `$~` set in the binding's frame. + - Where the state lives: a plain string eval (`TopScopeFactoryKind.None`) whose tree has a + regexp or a range gets a hidden variable of its top level that its prologue sets to a new + `EvalLiterals` (one slot per literal site, filled once by whichever thread gets there + first). A literal of the top level reads its slot from it; every Proc the text instantiates + takes it along (`RubyOps.AttachEvalLiterals`, `Proc.EvalLiterals` in the Proc's rare state, + kept by its copies - `dup`, `curry`, a method made of it), and a literal in a block reads it + from the block's BlockParam's Proc (`GetBlockEvalLiterals`) - the binding's scope, shared by + every eval through it, is not used. A literal in a `def` or class body of the text keeps its + object in the code as before (the screen refuses those texts). Eval'd code replaces no loops + (`CanReplaceLoops` is false for eval), so a block body always runs with its BlockParam. The + screen lets in `RegularExpression`, `RegularExpressionCondition` and `RangeExpression` + (a flip-flop's `RangeCondition` stays refused). Five new emitted helpers; + `ReflectionCache.Generated.cs` is ClassInitGenerator's, identical to the entries written by + hand. + - Instructions a render (`Util/perf/callgrind/count.sh`, N=1000, one shape per process, switch + off -> on): `erb_eval_regexp` 3,399,928 -> 1,283,572 (0.378); `erb_eval_top` 1,272,648 -> + 1,272,650, `erb_eval_defined` 1,271,525 -> 1,270,361, `eval_small` 55,159 -> 55,159. Timed: + `erb_eval_regexp` 613 -> 223 us, `erb_eval_top` 235 -> 239. Standard-library templates + shared: 72 -> 80 of 80. + - `Util/eval-literals-matrix.rb` (new: the cases above, nested blocks, a lambda and a proc of + one eval, frozen/source/options, an escaped Proc after another eval, two Procs of one eval, + a Proc made into a method, `dup` and `curry`, a Proc passed as a block, `/o` keeping its + first value, a range of variables, `$~` at the top level and in a block, a regexp as a + condition, four threads on one text, ERB) prints CRuby 4.0's output on the unchanged build, + and on the change by default, with `IR_EVAL_LITERALS=0`, `IR_LIGHT_FRAMES=0`, `-X:NoJIT + -X:NoOSR`, `-X:NoJITCalls` and R2R. eval-defined, eval-locals, erb-escape, regex-light, + regexp-escaped-byte, regexp-inspect, regexp-property, lexical-light, block-scope-reuse and + hot-shapes print CRuby's output, eval-matrix, regex-property and regexp-binary-ctype the + unchanged build's, in those five modes; the three eval matrices CRuby's under R2R. + ruby/spec `core/kernel/eval_spec.rb` 57 / 0, `core/binding` 98 / 0, `language/regexp` 258 / + 0, `core/regexp` 256 with 3 errors, `library/erb` 53 / 0 - the same on both builds. + IronRuby.Tests `Eval_SharedLiterals1` (new; passes with the switch off too) and 93 named + eval, binding, defined?, regexp, range, proc and block tests pass. + - **perf/evalscreen (/perf-step, 2026-11-27, on 4320d4a + perf/lexical b45360c) - an eval'd text with `defined?` shares its compiled code (`IR_EVAL_SHARE_DEFINED`, gap 31)** - instructions only, not gated. Measured first, which refusals of perf/erb36's screen real From 8c31db5c8d589cc3238e96bfb677cbd6a607b4ad Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:53:45 +0000 Subject: [PATCH 183/439] LEDGER: gap 39, what closing the String reader races would take Per-call content holds stop torn reads within one call but not the wrong answers of methods that make several content calls; matching CRuby needs each String method atomic (a per-string lock in the dispatch layer and the JIT's inlined String operations), estimated at +15-40% on short String operations. Recorded as undecided, like gap 20. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Util/perf/LEDGER.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a89d2cac5..a3ce41330 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1653,6 +1653,18 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has perf/strswitch (see Landed) took cause 2: no write is lost to a reader's switch and no writer fails on one (21 and 25 rows of 252 on master, 0 and 0 now, 20 runs). Causes 1 and 3 remain: 89 rows of readers that answer wrongly or raise. + What closing them takes (2026-11-27, analysis, not tried): holding the content inside each + content call stops a single call's torn read (the IndexOutOfRange and RangeError rows) for a + compare-exchange per call, about +1-2% instructions and +5-8% time on a short operation (the + cost perf/strcow measured for a held slice), but not the wrong answers: most String methods make + several content calls - end_with? reads the byte count, then compares the tail - and a writer + runs between them, so the answer mixes two states. Matching CRuby needs each whole String method + atomic: a lock per string (a Monitor on the MutableString, no new field) around every String + library method, in the call and dispatch layer and in the method JIT's inlined String + operations, with methods that take a block left out (CRuby lets other threads run between + yields too, and holding a lock across user code can deadlock). Estimated 10-20 ns a call, + +15-40% on a short String operation - not measured. Two-string operations take both locks in a + fixed order. Undecided: a matter of what IronRuby promises under threads, as gap 20 is. ## Landed From 77330379820c3517f65f1dc4f48219f1ffdbcc2f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:55:39 +0000 Subject: [PATCH 184/439] String#<<: a frozen receiver raises FrozenError whatever the argument MRI's rb_str_concat checks the receiver before it looks at the argument, so "a".freeze << Object.new (or nil, 1.5, :sym) is a FrozenError. The earlier fix covered what reaches a method body; an argument the binder could not convert to a String for the [DefaultProtocol] overload raised the TypeError before any body ran. #<< gets an overload for any other object, which checks the receiver and then converts with to_str as before; a String or an Integer still binds to its own overload. String_AppendFrozenAnyArgument1 holds CRuby's output; String#<<, #concat and #+ specs pass and the String IronRuby.Tests pass. A loop of s << "x" << 65 runs as fast as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 38 ++++++++++++++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 11 +++++++ 3 files changed, 50 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 350c8408a..993b3e899 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -170,6 +170,7 @@ public Tests(Driver/*!*/ driver) { String_NonCharacter1, String_SuccSeparators1, String_AppendFrozenFirst1, + String_AppendFrozenAnyArgument1, String_CountDeleteSqueeze1, String_CountDeleteSqueeze2, String_CountDeleteSqueeze3, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index 78c3cfb50..f3d570e71 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -351,6 +351,44 @@ p t.chars.map(&:ord) "); } + /// + /// A frozen String raises FrozenError from #<< whatever it is given, before any conversion of the + /// argument: an object with no #to_str, nil, a Float, a Symbol. + /// + public void String_AppendFrozenAnyArgument1() { + TestOutput(@" +require 'ruby4' +s = ""a"".freeze +[Object.new, nil, 1.5, :sym, [1]].each { |x| begin; s << x; rescue => e; p [e.class, e.message]; end } +begin; s.concat(Object.new); rescue => e; p [e.class, e.message]; end +begin; s.prepend(Object.new); rescue => e; p [e.class, e.message]; end +begin; s.replace(Object.new); rescue => e; p [e.class, e.message]; end +begin; s.insert(0, Object.new); rescue => e; p [e.class, e.message]; end +t = +""a"" +o = Object.new; def o.to_str = ""Z"" +[o, ""b"", 99, 2**40 % 0x110000].each { |x| t << x } +p t.bytes +[Object.new, nil, 1.5].each { |x| begin; t << x; rescue => e; p [e.class, e.message]; end } +class S < String; end +p((+""q"") << S.new(""r"")) +", @" +[FrozenError, ""can't modify frozen String: \""a\""""] +[FrozenError, ""can't modify frozen String: \""a\""""] +[FrozenError, ""can't modify frozen String: \""a\""""] +[FrozenError, ""can't modify frozen String: \""a\""""] +[FrozenError, ""can't modify frozen String: \""a\""""] +[FrozenError, ""can't modify frozen String: \""a\""""] +[FrozenError, ""can't modify frozen String: \""a\""""] +[FrozenError, ""can't modify frozen String: \""a\""""] +[TypeError, ""no implicit conversion of Object into String""] +[97, 90, 98, 99, 240, 144, 128, 128] +[TypeError, ""no implicit conversion of Object into String""] +[TypeError, ""no implicit conversion of nil into String""] +[TypeError, ""no implicit conversion of Float into String""] +""qr"" +"); + } + /// /// #count, #delete and #squeeze answer an ASCII character from a bitmask CharacterSelector /// computes when it is parsed, negation and intersection included; anything else goes diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index e8702d78f..995c21478 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -867,6 +867,17 @@ private static void RequireByteCode(MutableString/*!*/ self, uint c) { throw RubyExceptions.CreateRangeError("bignum out of char range"); } + /// + /// Anything else: MRI's rb_str_concat checks the receiver before it converts the argument, + /// so a frozen string raises FrozenError whatever it is given ("a".freeze << Object.new), + /// where the binder's conversion of a [DefaultProtocol] parameter would raise the TypeError first. + /// + [RubyMethod("<<")] + public static MutableString/*!*/ Append(ConversionStorage/*!*/ stringCast, MutableString/*!*/ self, object other) { + self.RequireNotFrozen(); + return self.Append(Protocols.CastToString(stringCast, other)); + } + // Ruby 1.9 gave #concat - but not #<< - any number of arguments. Each one is an // Integer codepoint or something String-convertible, and they are appended in order, // so "s.concat(s, s)" triples s rather than looping. From 857fff83bed0b31a56160698725e00da5cda7dc0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:01:15 +0000 Subject: [PATCH 185/439] LEDGER: perf/crubydiff's third round The causes fixed (gaps 27 and 28 closed), the matrices they turned, what is left with the reason, and the behaviour that changed outside a message for the gate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 55 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index b0c347e2c..786d59097 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1394,11 +1394,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has RubyGems' own Ruby (binds ~100 ms inclusive in `-e 1`, the running of precompiled code), the files `gem list` requires, and the JIT, which the release image already halves. A next attempt should measure on the release image, or say why the R2R host stands in for it. -27. **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby +27. **Closed (perf/crubydiff, third round): `send` frames are hidden.** Was: **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a speed gap. -28. **`-w` warns of an unused block where CRuby does not**: `def given; block_given?; end` +28. **Closed (perf/crubydiff, third round): CRuby registers block-using names per file at compile time, and so does the bridge now.** Was: **`-w` warns of an unused block where CRuby does not**: `def given; block_given?; end` called as `given(&b)` from a method that received `b` prints "the block passed to 'Object#given' ... may be ignored" under `ir -w` on master too; CRuby 4.0 `-w` printed it for a three-line file but not inside a longer one. Found while writing @@ -1728,6 +1728,57 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (method(:puts).to_proc.source_location; CRuby says nil on both); Kernel#Integer(String) now takes the context (one more argument on that fast path); the binder's conversion rule for an overridden respond_to? resolves to_xxx and method_missing at build time. + Third round (2026-11-27, on claude/happy-gauss-95wm2j + the second): the causes left above, gaps + 27 and 28. One commit per cause, each with CRuby 4.0's output as a registered IronRuby.Tests case; + touched matrices now same: strftime (108 -> 0), converter, io-conversion, marshal, enum (Lazy), + encode; regexp-binary-ctype 25 -> 9, strptime 8 -> 1, thread-backtrace 2 -> 1. + - `send`/`__send__` frames hidden from backtraces ([RubyStackTraceHidden]; public_send keeps its + frame, as in CRuby). Gap 27. Backtrace_SendHidden1. + - `-w`'s unused-block warning: CRuby registers every method that uses a block when the file is + compiled (iseq_set_use_block), so a later definition of the name silences it; the bridge now + does the same (RubyContext.NoteMethodUsingBlock at Def). Gap 28. UnusedBlock_LaterDefinition1. + - An ISO-8859-1 subject (not ASCII-only) is matched with Onigmo's ISO-8859-1 ctype table: a + Latin1Ctype mode of the translator beside the ASCII one, a third cached translation in RubyRegex. + Regex_Latin1Ctype1. + - strftime: a colon not before z (and E/O not before what they modify) ends the directive there + and the rest is read afresh; a lone % names the whole format. Time_StrftimeColon1. `%Z` of a + zoneless time writes nothing, padding included. Time_StrftimeNoZone1. + - Date: "UT-3" is no offset (zone_to_diff strips only gmt/utc); _strptime/_parse refuse a + non-ASCII-compatible string; _strptime's leftover is a plain String for a subclass; _parse takes + the day name before the time ("10:00 sat" was zone "sat"). Four tests. + - Transcoding errors (UndefinedConversion, InvalidByteSequence, ConverterNotFound) have binary + messages; convpath's decorator names are binary; Module#name/#to_s are US-ASCII for an ASCII + name and binary for "#" (a temporary name keeps its own). Three tests. + - Marshal writes a raised exception's "bt_locations" (a link to "bt", or the raise's strings + after #set_backtrace), and "cause" after the ivars #initialize set. Marshal_ExceptionBtLocations1. + - IO#write into a UTF-16/32 external encoding goes through UTF-8 first (do_writeconv), so a bad + byte is reported on that leg. Io_WriteViaAsciiCompat1. + - Thread#backtrace of a thread blocked in Mutex#lock, Queue#pop, SizedQueue#push/#pop, + Thread#join/#value, ConditionVariable#wait or Thread.stop shows that method on top (the + thread's BlockedLabel, set on the blocking paths only). Thread_BlockedMethodFrame1. + - Enumerator::Lazy's #inspect recorders are defined in Lazy around the methods they replace, not + in a prepended module. Enumerator_LazyAncestors1. + - `frozen << Object.new` (nil, a Float, a Symbol) is FrozenError: an object overload of #<< + checks the receiver before converting. String_AppendFrozenAnyArgument1. + Left, with the reason: UTF-8's \b/\B without U+00B2 U+00B3 U+00B9 U+00BC-U+00BE and + [[:upper:]]/i without U+00B5 (the UTF-8 path's word class, a cost on every \b); Time with a + year beyond long (RubyTime keeps it in a long); Method#call / Method#[] frames (a rule dispatches + straight to the target; a frame means a trampoline on every call); sort_by/inject's 'Array#each' + frame (IronRuby's iterate without #each); library frames in another thread's backtrace + (Mutex#synchronize, Array#each: only Ruby frames are recorded, and recording library ones costs + every block-taking call); calls on a later line of a multi-line statement report the statement's + first line (eval's "(eval at f:41)" for 42, caller, binding: line tracking is per statement); + the heredoc part's frame line (needs a node with the part's span and JIT walker support); + thread-backtrace's "main, seen by child" row (no GVL: the child reads main before main reaches + Queue#pop); a non-ASCII class's singleton "#", US-ASCII in CRuby, UTF-8 here. + For the gate, behaviour that changed outside a message: send frames gone from backtraces; + unused-block names registered at parse time (a file's later definitions count); ISO-8859-1 + regexp matching (new translation, chosen per subject); strftime output for "%:..." and "%E%..." + and padded %Z; Date._parse hash order and "10:00 sat"; Date._strptime leftover class and + encoding errors; Module#name/#to_s/#inspect encodings (so [Object.name, "a"].join is US-ASCII); + transcoding error message encodings; convpath element encodings; Marshal bytes of raised + exceptions; IO#write into UTF-16/32 (the same bytes, a different error); Thread#backtrace + contents; Lazy.ancestors and Lazy#take & co. owner; String#<< has an object overload. - **perf/kwrest (/perf-step, 2026-11-26, on 79a2c30 + perf/lexical3) - a rest parameter that takes a call's keyword hash unmarks the call's own instead of storing a copy From ebd42abbcd353a749c4a10bf5e51f1bfa0e72d2c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:02:15 +0000 Subject: [PATCH 186/439] Measure gap 17 before building it: a prelude primitive cannot pay The gap counted every private __x__ call in the prelude as a call to a C# helper, which a name the compiler turns into a direct static call would make cheaper. Measured first, 1,156 of the 1,604 __x__ calls in ruby4.rb call a Ruby method the prelude defines itself, which no primitive can replace. The 225 calls that reach a C#-only helper are dominated by start-up registrations that run once. What those 225 cost: about 10 ns a call in the steady state (3% of filter_map), and 59 binds and 9.6 ms of a 1.4 s `-e 1` start on the in-place build, less on R2R. That is less than the compiler, the startup library, R2R and the method JIT would have to take on to emit and type such a call. The 56 prelude methods the JIT's screen refuses for helper calls alone are refused mostly by Ruby helpers, so the census would not move either. Util/bench/helper-call-cost.rb (new) times a helper call against a constant and, with --census, counts the prelude's __x__ calls by where they go. The ledger's gap 17 now says what was measured; the entry under Rejected says what would pay instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6tJMpWBUoryxBaN6Q --- Util/bench/helper-call-cost.rb | 43 ++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 33 ++++++++++++++++++++++++-- 2 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 Util/bench/helper-call-cost.rb diff --git a/Util/bench/helper-call-cost.rb b/Util/bench/helper-call-cost.rb new file mode 100644 index 000000000..285b89a6d --- /dev/null +++ b/Util/bench/helper-call-cost.rb @@ -0,0 +1,43 @@ +# What a prelude helper call costs (LEDGER gap 17): a method that calls a C# method on self through a +# call site, against the same method answering a constant. Prints ns per call (process CPU). +# +# ./ir.sh Util/bench/helper-call-cost.rb +# +# And which of the prelude's `__x__` calls a "primitive" could replace at all - the C# ones - against +# the ones that call a Ruby method the prelude defines itself: +# +# ruby Util/bench/helper-call-cost.rb --census +if ARGV[0] == "--census" + root = File.expand_path("../..", __dir__) + src = File.read(File.join(root, "Src/StdLib/ironruby/ruby4.rb"), encoding: "UTF-8") + calls = Hash.new(0) + src.scan(/(? 436, `erb.result_with_has 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per site at start-up, 0.2-0.4 ms). TruffleRuby's `Primitive.x` is replaced at parse time. - Untried: a name the compiler turns into a direct static call in prelude files only - (lessons, section 4, item 4). + Measured in round thirty-eight (perf/primitive, see Rejected) before building it: most of + those calls are not to C#. Of 1,604 `__x__` calls in `ruby4.rb` (489 names), 1,156 call a + Ruby method the prelude defines itself (`__flt__` 31, `__check__` 28, `__err__` 24, + `__chain__` 22...) and 225 (110 names) a C#-only helper, the most frequent of which run once + at start-up (`__hide_constant__` 23, `__iter_cursor_method__` 10); + `ruby Util/bench/helper-call-cost.rb --census`. A primitive could take only those 225: about + 10 ns a call (a C# method on self from a Ruby method 42-44 ns against 28-31 for a constant) + and, at `-e 1` (in-place build), 59 binds and 9.6 ms of a 1.4 s start. Of the 56 prelude + methods the method JIT's screen refuses for helper calls alone, the helpers are mostly Ruby + (`__check__` 15, `__ir_try_convert__`, `__hash_operand__`, `__hash_subset__` 4 each): what would + let those through is the screen taking a self call to a private prelude method, not a primitive. 18. **A `while ... yield` in Ruby runs at ~100 ns per element** against 9 for a C# iterator compiled with its block, and at twice CRuby's time for the same source: the loop compiler gives up on `yield` (see the Rejected entry "A block whose body is @@ -6471,6 +6480,26 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/primitive (2026-11-27) - a direct static call for the prelude's C# helpers (gap 17), + not built: measured first, it cannot pay for itself.** Base 4708492 (the round-38 branch at + 4320d4a with perf/fiberbound). The gap counted every `__x__` call as a call to C#; 72% of + them (1,156 of 1,604 in `ruby4.rb`) call a Ruby method the prelude defines, which a primitive + cannot replace, and the 225 that reach a C#-only helper are dominated by start-up registrations + run once. What the 225 cost: about 10 ns a call in the steady state (`Util/bench/helper-call-cost.rb`, + new: a method calling `size` or `frozen?` on self 42-44 ns, answering a constant 28-31; + `__plain_list__?` 79 ns, most of it the helper's own method lookups, which a direct call keeps), + so 3% of `filter_map` (344 ns) and less of the other core methods that call one; at start-up + (`IR_BIND_TRACE=1 IR_PHASE_TIMES=1 ./ir.sh -e 1`, in-place build): 1,050 binds, 333 ms + inclusive, of which 59 binds and 9.6 ms are C# helpers' (13 and 11.5 ms the Ruby helpers'), + so at most about 0.7% of the start, less on the R2R host, and not the 4-5% round four left. The + cost of building it - the compiler resolving a library method's overloads and parameter + conventions (storages, BlockParam, RubyContext, conversions) at compile time, the startup library + and R2R emitting the same, and the JIT taking the call - is larger than any of that. The + census's helper refusals (56 prelude methods refused at the JIT screen by helper calls alone) + are mostly Ruby helpers, so a primitive would not move the census either. What would: the screen + taking a self call to a private prelude method (`__check__`, `__flt__`, `__err__`), or, for the + start, the binds that are not helpers' (965 of 1,050). + - **perf/passensure (2026-11-27) - running a pending ensure clause from the filter of a rescue frame above it: designed, found unsound, not built** (stage 1 of the brief; `Docs/rescue-above-ensure.md`). The idea (perf/rescuefilter): a rescue above a passed ensure catches and throws again (~20 us for the From c1045a052318e091ab7b8db5d6b34cef69711e61 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:08:16 +0000 Subject: [PATCH 187/439] Let `recv.m op= v' run in a light frame (gap 9) `o.x += 1', `o.x ||= v', `self.x &&= v' (a MemberAssignmentExpression) kept their method's scope only because IsScopeFree had no case for the node and refused it by default. The node is the call of m on the receiver, kept in a hidden CLR variable of the lambda, the operator's call or `||'/`&&', and the call of m= with the right-hand side as its value: sites like those of `o.x = o.x + 1', which a light frame already takes. A rule that needs the caller's scope answers LightScopeRequired as for any light call. IR_LIGHT_MEMBER_OPASSIGN=0 turns it off. Census of Src/StdLib and AWFY: 39 more methods are light frames, none fewer. ab.rb -r 6, ns, switch off -> on: `o.x += 1' 78.0 -> 41.7, `o.y ||= v' 73.9 -> 35.8, `self.x += 1' 73.5 -> 42.0 (CRuby 32-33); the written-out forms and three controls level. The new Util/light-member-opassign-matrix.rb (operators, &., the value being the right-hand side, private accessors, redefinition after binding, singleton, method_missing, BasicObject, refinements, errors, binding/eval/local_variables, raise, send and define_method, TracePoint, threads) and the light-entry, hot-shapes, block-pass, jit, block-given, light-rest and super-light matrices print CRuby's output in all seven gate modes and with the switch off. ruby/spec language optional_assignments, assignments and safe_navigator pass; Method_LightFrameMemberOpAssign1 and 42 other light-frame and assignment tests pass. Not gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 42 ++++ .../Ast/Definitions/MethodDefinition.cs | 18 ++ Util/bench/prelude-cost.rb | 18 ++ Util/light-member-opassign-matrix.rb | 184 ++++++++++++++++++ Util/perf/LEDGER.md | 32 +++ 6 files changed, 295 insertions(+) create mode 100644 Util/light-member-opassign-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f8c62603e..650c644d6 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1157,6 +1157,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGuard1, Method_LightFrameBlockGiven1, Method_LightFrameRest1, + Method_LightFrameMemberOpAssign1, Method_LightFrameKeywordRest1, Method_KeywordHashIntoRest1, Method_KeywordPrologue1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index bd0d7cde9..6b71ca3f2 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7887,6 +7887,48 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters "); } + /// + /// `recv.m op= v' in a light frame (IR_LIGHT_MEMBER_OPASSIGN): the read of m, the operator and the write of m= are calls of + /// the frame's light sites; the value is the right-hand side whatever m= returns; a private accessor on self; `&.'; binding. + /// + public void Method_LightFrameMemberOpAssign1() { + TestOutput(@" +require 'ruby4' +class Box; attr_accessor :x, :y; def initialize(x = 0) = (@x = x); end +class Odd; def x = 5; def x=(v); @s = v; :ignored; end; attr_reader :s; end +class Priv; def initialize = (@x = 1); def bump = (self.x += 1); private; attr_accessor :x; end +def plus(o) = (o.x += 1) +def ored(o, v) = (o.y ||= v) +def anded(o, v) = (o.y &&= v) +def safe(o) = (o&.x += 1) +def seen(o) = (o.x += 1; _w = 3; binding.local_variable_get(:_w) + o.x) +def boom(o) + o.x += 1 + raise ""boom"" +end +p plus(Box.new), ored(Box.new, 2), anded(Box.new, 2), safe(nil), safe(Box.new(4)), seen(Box.new) +o = Odd.new +p plus(o), o.s, Priv.new.bump +p 40.times.map { |i| plus(Box.new(i % 3)) }.uniq, 40.times.map { |i| ored(Box.new, i) }.sum +begin; plus(Object.new); rescue NoMethodError => e; p e.message; end +begin; boom(Box.new); rescue => e; p e.backtrace[0][/in .*/]; end +", @" +1 +2 +nil +nil +5 +4 +6 +6 +2 +[1, 2, 3] +780 +""undefined method 'x' for an instance of Object"" +""in 'Object#boom'"" +"); + } + /// /// IR_LIGHT_KEYWORD_REST and IR_LIGHT_KEYWORD_SPLAT: keywords beside a rest or post parameter, bound out of one splat /// (PrismAstBridge.LowerGeneralParameters), and a hash passed on as keywords, in a light frame diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 6e5c75da8..d805014b8 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -610,6 +610,13 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// internal static readonly bool LightKeywordSplatEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_KEYWORD_SPLAT") != "0"; + /// + /// IR_LIGHT_MEMBER_OPASSIGN=0 keeps a method with `recv.m op= v' (`o.x += 1', `o.x ||= v', `self.x &&= v'; a + /// MemberAssignmentExpression) out of light frames, as it was: it is a read of m, the operator and a write of m=, three + /// calls like those of `o.x = o.x + 1', which a light frame takes, and a hidden CLR variable for the receiver. + /// + internal static readonly bool LightMemberOpAssignEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_MEMBER_OPASSIGN") != "0"; + // The built-in methods that store the caller's $~ when given a Regexp, and so take the caller's scope: a light frame // that calls one makes its scope on the call (RubyOps.LightScopeRequired) and calls again, which costs more than the // scope made at entry (gap 16 of Util/perf/LEDGER.md). A name only says which method is likely, not which is called, @@ -1178,6 +1185,17 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong } return IsScopeFree(item.Array, blockLiterals, why) && AreScopeFree(item.Arguments, blockLiterals, why); } + // `o.x op= v' (MemberAssignmentExpression.TransformReadCore): the call of x on the receiver, kept in a hidden variable + // of the lambda, the operator's call (or `||'/`&&') and the call of x= - sites like those of `o.x = o.x + 1', with + // nothing that takes the frame's scope. `o&.x op= v' is a nil test around one (PrismAstBridge.MemberOpAssign). + var memberAssignment = node as MemberAssignmentExpression; + if (memberAssignment != null) { + if (!LightCallsEnabled || !LightMemberOpAssignEnabled) { + return Refuse(why, LightCallsEnabled ? "MemberAssignmentExpression (IR_LIGHT_MEMBER_OPASSIGN=0)" : + "MemberAssignmentExpression (IR_LIGHT_CALLS=0)"); + } + return IsScopeFree(memberAssignment.LeftTarget, blockLiterals, why) && IsScopeFree(memberAssignment.Right, blockLiterals, why); + } // a String literal is a constant, or a copy of one; a Symbol literal is a constant if (node is StringLiteral) { return true; diff --git a/Util/bench/prelude-cost.rb b/Util/bench/prelude-cost.rb index da83cd4e2..0dac3e1d6 100644 --- a/Util/bench/prelude-cost.rb +++ b/Util/bench/prelude-cost.rb @@ -531,3 +531,21 @@ def t(name, n) t("d_one", N) { |n| i = 0; s = 0; while i < n; s += kr.d_one(i); i += 1; end; s } t("d_two", N) { |n| i = 0; s = 0; while i < n; s += kr.d_two(i); i += 1; end; s } t("d_cond", N) { |n| i = 0; s = 0; while i < n; s += kr.d_cond(i); i += 1; end; s } +# `o.x += 1' (a MemberAssignmentExpression, IR_LIGHT_MEMBER_OPASSIGN) against the same written out as `o.x = o.x + 1', +# which a light frame already takes; `||=' on an attribute against its written-out form; and a method that does only that +class MOp + attr_accessor :x, :y + def initialize = (@x = 0; @y = nil) + def opa(o) = (o.x += 1) + def opa_out(o) = (o.x = o.x + 1) + def ora(o, v) = (o.y ||= v) + def ora_out(o, v) = (o.y || (o.y = v)) + def self_opa = (self.x += 1) +end +mo = MOp.new +mt = MOp.new +t("m_opassign", N) { |n| i = 0; while i < n; mo.opa(mt); i += 1; end; mt.x } +t("m_opassign_out", N) { |n| i = 0; while i < n; mo.opa_out(mt); i += 1; end; mt.x } +t("m_orassign", N) { |n| i = 0; s = 0; while i < n; s += mo.ora(mt, i); i += 1; end; s } +t("m_orassign_out", N) { |n| i = 0; s = 0; while i < n; s += mo.ora_out(mt, i); i += 1; end; s } +t("m_self_opassign", N) { |n| i = 0; while i < n; mo.self_opa; i += 1; end; mo.x } diff --git a/Util/light-member-opassign-matrix.rb b/Util/light-member-opassign-matrix.rb new file mode 100644 index 000000000..28007858c --- /dev/null +++ b/Util/light-member-opassign-matrix.rb @@ -0,0 +1,184 @@ +# Differential matrix for `recv.m op= v' (a MemberAssignmentExpression: `o.x += 1', `o.x ||= v', `self.x &&= v', +# `o&.x += 1') in a method that runs without a scope (a light frame, MethodDefinition.IsScopeFree, +# IR_LIGHT_MEMBER_OPASSIGN): the read of m, the operator and the write of m= are three call sites with a light scope, +# as `o.x = v' and `@x += v' are. Run it under CRuby and under ./ir.sh with the switch on and off, and diff: +# +# ruby Util/light-member-opassign-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/light-member-opassign-matrix.rb > /tmp/on.txt +# IR_LIGHT_MEMBER_OPASSIGN=0 ./ir.sh Util/light-member-opassign-matrix.rb > /tmp/off.txt +# IR_LIGHT_FRAMES=0 ./ir.sh Util/light-member-opassign-matrix.rb > /tmp/noframes.txt +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt && diff /tmp/mri.txt /tmp/noframes.txt +# +# Every probe runs N times and reports each distinct answer once, in the order they first appear, so the +# interpreted body, the compiled one and a site whose rule is already bound all meet the case. +# +# IR_LIGHT_FRAMES=why ./ir.sh Util/light-member-opassign-matrix.rb 2>&1 >/dev/null | grep -a '^\[light\]' +# +# says which of the methods below are light frames. + +N = 3000 + +def t(label) + print label.ljust(58), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 60]}" + end +end + +class Box + attr_accessor :x, :list + def initialize(x = 0) = (@x = x; @list = []) +end + +# ---------------------------------------------------------------- 1. the operators + +def plus(o) = (o.x += 1) +def minus(o, v) = (o.x -= v) +def ored(o, v) = (o.x ||= v) +def anded(o, v) = (o.x &&= v) +def shifted(o, v) = (o.list << v; o.list.size) +def append_op(o, v) = (o.list += [v]; o.list.size) +def safe(o) = (o&.x += 1) +def safe_or(o, v) = (o&.x ||= v) + + +t("o.x += 1") { |i| plus(Box.new(i % 3)) } +t("o.x -= v") { |i| minus(Box.new(10), i % 3) } +t("o.x ||= v on nil and on a value") { |i| ored(Box.new(i.odd? ? nil : :set), :v) } +t("o.x &&= v on nil and on a value") { |i| anded(Box.new(i.odd? ? nil : :set), :v) } +t("o.list << v, o.list += [v]") { |i| bx = Box.new; [shifted(bx, i), append_op(bx, i)] } +t("o&.x += 1, on nil and on an object") { |i| safe(i.odd? ? nil : Box.new(i % 3)) } +t("o&.x ||= v, on nil and on an object") { |i| safe_or(i.odd? ? nil : Box.new(nil), :w) } + +# ---------------------------------------------------------------- 2. the value of the expression + +class Odd + def x = 5 + def x=(v) + @stored = v + :ignored + end + attr_reader :stored +end +def value_of(o) = (o.x += 2) +t("the value is the rhs, not what x= returns") { |i| o = Odd.new; [value_of(o), o.stored] } + +# ---------------------------------------------------------------- 3. private setter on self, and on another object + +class Priv + def initialize = (@x = 1) + def bump = (self.x += 1) + def bump_other(o) = (o.x += 1) + private + attr_accessor :x +end +t("self.x += 1 with a private accessor") { |i| Priv.new.bump } +t("o.x += 1 with a private accessor") { |i| Priv.new.bump_other(Priv.new) } + +# ---------------------------------------------------------------- 4. who is asked, redefined after the site bound + +class Re + attr_accessor :x +end +def re_plus(o) = (o.x += 1) +t("x= redefined and removed after binding") do |i| + o = Re.new; o.x = 0 + Re.class_eval { define_method(:x=) { |val| @x = val * 10 } } if i == 1000 + Re.class_eval { remove_method :x=; attr_writer :x } if i == 2000 + [re_plus(o), o.x] +end +t("x on a singleton class") do |i| + o = Re.new; o.x = 1 + def o.x = 100 if i % 3 == 0 + re_plus(o) +end + +class MM + def method_missing(name, *args) = name.to_s.end_with?("=") ? (@last = [name, *args]) : 7 + def respond_to_missing?(*) = true + attr_reader :last +end +t("method_missing for x and x=") { |i| o = MM.new; [re_plus(o), o.last] } + +class BO < BasicObject + def x = 1 + def x=(v) + @v = v + end + def v = @v +end +t("a BasicObject receiver") { |i| o = BO.new; [re_plus(o), o.v] } + +module RefX + refine(Re) { def x = 1000 } +end +class UsingRef + using RefX + def self.plus(o) = (o.x += 1) +end +t("a refinement of x in force") { |i| o = Re.new; o.x = 0; UsingRef.plus(o) } +t("the same object outside it") { |i| o = Re.new; o.x = 0; re_plus(o) } + +t("errors: no x=, nil receiver, frozen") do |i| + r = [] + r << (begin; re_plus(Object.new); rescue NoMethodError => e; e.message; end) + r << (begin; re_plus(nil); rescue NoMethodError => e; e.message; end) + r << (begin; o = Re.new; o.x = 1; o.freeze; re_plus(o); rescue => e; e.class; end) + r +end + +# ---------------------------------------------------------------- 5. what the frame still does afterwards + +def with_binding(o) = (o.x += 1; _v = 5; binding.local_variable_get(:_v) + o.x) +def with_locals(o) = (o.x += 1; _w = 2; local_variables) +def with_eval(o) = (o.x += 1; eval("o.x * 2")) +def with_block(o) = (o.x += 1; [1, 2].map { |k| o.x += k; o.x }) +def with_raise(o) + o.x += 1 + raise ArgumentError, "boom" +end +def recursive(o, n) = n.zero? ? o.x : (o.x += 1; recursive(o, n - 1)) +def with_method_name(o) = (o.x += 1; __method__) +def with_block_given(o) = (o.x += 1; block_given?) + +t("binding after") { |i| with_binding(Box.new(i % 2)) } +t("local_variables after") { |i| with_locals(Box.new) } +t("eval after") { |i| with_eval(Box.new(i % 3)) } +t("a block that op-assigns too") { |i| with_block(Box.new) } +t("raise: the label in the backtrace") { |i| begin; with_raise(Box.new); rescue => e; e.backtrace_locations[0].label; end } +t("recursion") { |i| recursive(Box.new, 5) } +t("__method__ and block_given?") { |i| [with_method_name(Box.new), with_block_given(Box.new)] } + +# ---------------------------------------------------------------- 6. other ways in + +class Via + attr_accessor :x + def initialize = (@x = 0) + def inc = (self.x += 1) + define_method(:dinc) { self.x += 1 } +end +v = Via.new +t("send, public_send, Method#call, define_method") { |i| [v.send(:inc), v.public_send(:inc), v.method(:inc).call, v.dinc].size } +t("value after the above") { |i| v.x > 0 } + +# ---------------------------------------------------------------- 7. tracing and threads + +def traced(o) = (o.x += 1) +calls = [] +# (only the method's own :call: IronRuby's TracePoint does not report attr_accessor's x and x= as :c_call, on the base too) +tp = TracePoint.new(:call, :c_call) { |tr| calls << [tr.event, tr.method_id] if tr.method_id == :traced } +tp.enable { traced(Box.new) } +t("TracePoint :call and :c_call saw") { |i| calls.uniq } +t("after the TracePoint is disabled") { |i| traced(Box.new(i % 2)) } + +ths = 4.times.map { Thread.new { 5000.times { plus(Box.new) }; :done } } +t("threads") { |i| ths.map(&:value) } + +puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 925d7c8b0..20ae73e78 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1776,6 +1776,38 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lightmember (2026-11-27) - `recv.m op= v` in a light frame (gap 9)** - not gated. Chosen by the census of + 4320d4a + perf/neqrule: what keeps methods out of light frames is now mostly a regular expression whose method sets the + caller's `$~` (gsub 273, `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54 - about 880 methods, which + perf/regexlight found need a cheaper late scope or second call, not a filter change), a Range in a body with literal + blocks (158, kept out on purpose: measured slower), lambdas (73), and then `o.x op= v` (38) - which nothing in it + needs the scope for. Keyword parameters, which gap 9 named, are no longer on the list. + - Why the construct had the scope: no reason but the filter's - `IsScopeFree` had no case for a + MemberAssignmentExpression and refused it by default. What the frame must answer instead: nothing. The node is the + call of m on the receiver (kept in a hidden CLR variable of the lambda, not a scope local), the operator's call or + `||`/`&&`, and the call of m= with the right-hand side as its value (MemberAssignmentExpression.TransformReadCore), + sites like those of `o.x = o.x + 1`, which a light frame takes; `o&.x op= v` is a nil test around one + (PrismAstBridge.MemberOpAssign). What forces the scope at run time when something reaches for it: the same as for + any light call - a rule that needs the caller's scope answers LightScopeRequired, and binding, eval and + local_variables make it then (all in the matrix). Switch: `IR_LIGHT_MEMBER_OPASSIGN=0`. + - Census (Src/StdLib + AWFY, 28,377 methods): light frames 26,693 -> 26,732 (+39, 94.1% -> 94.2%), none down; the + JIT's counts unchanged. In app-shapes' run one method of the kind. + - Time (`Util/bench/prelude-cost.rb`, `ab.rb -r 6`, ns; CRuby / base / switch off / new): `m_opassign` (`o.x += 1`) + 33.2 / 78.0 / 78.0 / 41.7 (0.53), `m_orassign` (`o.y ||= v`) 32.0 / 73.6 / 73.9 / 35.8 (0.48), `m_self_opassign` + 31.6 / 75.8 / 73.5 / 42.0 (0.57); their written-out forms and the controls `d_one`, `kr_rest`, `p_plain_opt` level. + - Checks: the new `Util/light-member-opassign-matrix.rb` (`+=`, `-=`, `||=`, `&&=`, `<<` and `+=` on a list, `&.`; + the value is the right-hand side whatever m= returns; a private accessor on self and on another object; x= + redefined and removed after binding; a singleton x; method_missing; a BasicObject receiver; a refinement in + force and not; NoMethodError on nil and an Object, FrozenError; binding, local_variables, eval, a block that + op-assigns, raise and its label, recursion, `__method__`, block_given?; send, public_send, Method#call, + define_method; a TracePoint; threads), light-entry, hot-shapes, block-pass, jit, block-given, light-rest and + super-light: CRuby's output in all seven gate modes (as built, NoJIT, NoJITCalls, IR_LIGHT_FRAMES=0, + IR_PARKED_SCOPES=0, the ReadyToRun host, the switch off) on both trees, 56 of 56. ruby/spec language + optional_assignments, assignments and safe_navigator: no failures on either. IronRuby.Tests: the new + Method_LightFrameMemberOpAssign1 and the 42 other tests named for light frames and assignments pass. + - Found on the base, left: IronRuby's TracePoint does not report attr_accessor's reader and writer as `:c_call` + (CRuby does); the matrix traces only the method's own `:call`. + - **perf/neqrule (2026-11-27) - `a != b` on plain objects is one rule for every class (gaps 10 and 12)** - not gated. `DispatchIntrinsics.TryBuildNotEquals` (#215) binds `a != b` as `!a.equal?(b)` when the receiver's `==` is BasicObject's, and `MaySpecialize` kept such rules out of IronRuby's shared rules, so a From d20bca786e5c8281cccf94fa929f18e64866a1db Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:09:45 +0000 Subject: [PATCH 188/439] Ledger: perf/yieldloop, a yield in an outlined loop measured (gap 18) Not built. Util/bench/yield-shapes.rb (new) takes a `while ... yield` apart per element: the yield itself costs about what CRuby's and C#'s do (11 ns), and the gap is the loop around it, which runs generic because the loop compiler bails at the YieldCall. Taking the yield into the typed loop needs a resume point after it (a deopt replays the iteration) and a self-guarded tail (the block may redefine what follows), which is JITResume's stage 2 for bodies with locals; the ledger says so under gap 18 and in the Rejected list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Util/bench/yield-shapes.rb | 82 ++++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 38 ++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 Util/bench/yield-shapes.rb diff --git a/Util/bench/yield-shapes.rb b/Util/bench/yield-shapes.rb new file mode 100644 index 000000000..9ee8b5b23 --- /dev/null +++ b/Util/bench/yield-shapes.rb @@ -0,0 +1,82 @@ +# A `while ... yield` written in Ruby (gap 18, perf/yieldloop): a user-written #each over an Array and the prelude's +# methods made of such a loop, against Array#each in C#. ns per ELEMENT (each shape divides by the elements it yields): +# +# ruby Util/perf/ab.rb -i Util/bench/yield-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# +# ueachK: `def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; end` over K elements with `{ |x| s += x }`; +# ueach4n: the same with a block that does nothing; cyield4: Array#each over 4, the C# iterator (control); +# take_while, sum_blk, uniq_blk, to_h_blk: the prelude's `while ... yield` methods over 100 elements; +# loop100 is the same loop with the yield taken out and the element read kept, and ueach100e yields to an empty block: +# their difference is what the yield costs, and loop100 with the tiers on (-X:NoJIT -X:NoOSR off) what the loop around a +# yield loses, the typed copy that the loop compiler gives up on at a YieldCall (round thirty-seven, see the ledger). +$stdout.sync = true + +class L + def initialize(a) = @a = a + def each + i = 0 + while i < @a.size + yield @a[i] + i += 1 + end + self + end + + def loop + i = 0 + while i < @a.size + @a[i] + i += 1 + end + self + end +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the seven sections as the +# time is. See Util/perf/instructions.rb. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-12s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +N = (ENV['N'] || 400_000).to_i +a1 = [1]; a4 = [1, 2, 3, 4]; a100 = (1..100).to_a +l1 = L.new(a1); l4 = L.new(a4); l100 = L.new(a100) + +t("ueach1", N) { |n| s = 0; i = 0; while i < n; l1.each { |x| s += x }; i += 1; end; s } +t("ueach4", N) { |n| s = 0; i = 0; while i < n; l4.each { |x| s += x }; i += 4; end; s } +t("ueach100", N) { |n| s = 0; i = 0; while i < n; l100.each { |x| s += x }; i += 100; end; s } +t("ueach100e", N) { |n| s = 0; i = 0; while i < n; l100.each { |x| }; s += 1; i += 100; end; s } +t("loop100", N) { |n| s = 0; i = 0; while i < n; l100.loop; s += 1; i += 100; end; s } +t("ueach4n", N) { |n| s = 0; i = 0; while i < n; l4.each { |x| }; s += 1; i += 4; end; s } +t("cyield4", N) { |n| s = 0; i = 0; while i < n; a4.each { |x| s += x }; i += 4; end; s } +t("take_while", N) { |n| s = 0; i = 0; while i < n; s += a100.take_while { |x| x < 1000 }.size; i += 100; end; s } +t("sum_blk", N) { |n| s = 0; i = 0; while i < n; s += a100.sum { |x| x }; i += 100; end; s } +t("uniq_blk", N) { |n| s = 0; i = 0; while i < n; s += a100.uniq { |x| x }.size; i += 100; end; s } +t("to_h_blk", N) { |n| s = 0; i = 0; while i < n; s += a100.to_h { |x| [x, x] }.size; i += 100; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 2a0cb4f5d..66bd06b40 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1127,6 +1127,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has iterator compiled with its block, and at twice CRuby's time for the same source: the loop compiler gives up on `yield` (see the Rejected entry "A block whose body is `yield `"). This is what keeps per-element loops in C#. + Round thirty-seven (perf/yieldloop, measured, not built; see Rejected) took it apart with + `Util/bench/yield-shapes.rb`, per element over 100: the loop alone (`loop100`) 10 ns with + the tiers on, 28 with them off, CRuby 18; the same loop yielding to an empty block + (`ueach100e`) 39-40 either way, CRuby 28; to `{ |x| s += x }` (`ueach100`) 55-57, CRuby + 30. So the `yield` itself is about 11 ns - CRuby's is about 10, C#'s `Array#each` yielding + the same empty block without its compiled copy 12 - and the rest is the loop around it + running generic: the loop compiler bails at the YieldCall (`[osr] emitter: node: + YieldCall`) and the light frame's `while` keeps its four dynamic sites. A typed loop + with the `yield` as a call in it would be about 23 ns against CRuby's 28. What stands in + the way is not the yield's cost but the iteration it would sit in (see Rejected). 19. **`Object.new.extend(M)` is 200 to 300 times CRuby's time and grows with the number of objects extended**: 20,000 in a `while` loop take 4.5 s, 40,000 11.0 s, 200,000 72 s, with and without the JIT and OSR; CRuby takes 0.23 s for 200,000 (1.1 us each). @@ -6489,6 +6499,34 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/yieldloop (round thirty-seven, 2026-11-27) - a `yield` in an outlined `while` loop: measured, + not built** (gap 18). What a `while ... yield` pays per element is the loop, not the yield (gap 18's + numbers): IronRuby's `yield` is about 11 ns, CRuby's about 10, and the loop around it is 28 ns generic + against 10 typed and CRuby's 18, generic because the loop compiler bails at the YieldCall. So of the + three candidates the brief named, the method's block resolved once per call of the iterator and a + cheaper `Yield1` for a scope-free block act on the 11 ns that is already CRuby's (round ten's + perf/veach, the yield in a block reading the method's Proc once, found the walk cheap too), and only + the third - the loop tier taking a `yield` - acts on the 15 ns that is not. That one needs what the + tier does not have: + - **A resume point after the yield.** A deopt restores the locals of the top of the iteration and runs + it again generically (JitLoopCompiler's header): one after the yield runs the block twice. Every + loop of this kind has an `i += 1` after its yield, whose add deopts on an overflow out of Int64, and + `@a[i]`, `i < @a.size` whose guards deopt. The emitter declines a deopt after an effect + (`_deoptAfterEffect`), so the yield would decline the loop, unless the iteration can be resumed + after the yield - JITResume's stage 2, for a body with locals (stage 1 takes none). + - **Nothing typed after the yield.** The block is any Ruby code: it may redefine Integer#+ or Array#[], + freeze, enable a TracePoint, and in this thread that is ordered before the `i += 1` that follows, + which a typed add would not see until the next safe point (JITResume's "self-guarded tail": every + node after a fallback re-checks or speculates on nothing). + - **The block's own frame and protocol.** Kept, if the yield is a call (`JitRuntime` calling + `RubyOps.Yield1` with the method's Proc and its reused BlockParam, then `MethodYield`'s break test): + a `break` leaves the loop with the block's value as the method's, `next` is the block's, a raise + leaves through the typed loop with the tuple brought up to date first. + What it would win: `ueach100` 55 -> about 23 ns per element (CRuby 30), and the prelude's `take_while`, + `sum`, `uniq` and `to_h` with a block (48, 100, 225 and 273 ns against CRuby's 28, 28, 57 and 94 per + element). The next attempt starts from JITResume's stage 2 (`Docs/jit-resume-deopt.md`), with the + yield as its first fallback that is not an attribute operation, not from the yield. + - **perf/passensure (2026-11-27) - running a pending ensure clause from the filter of a rescue frame above it: designed, found unsound, not built** (stage 1 of the brief; `Docs/rescue-above-ensure.md`). The idea (perf/rescuefilter): a rescue above a passed ensure catches and throws again (~20 us for the From 7b276098a7f7cf8e00a594135c97f07e5cc080b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:10:51 +0000 Subject: [PATCH 189/439] A running loop sees a nearer constant appear; a module's own constants before its prepends A compiled loop that folded a constant (an outlined loop, or a typed method body's) went on answering it after another thread made a constant of that name nearer to the lookup - lexically, in a superclass, through an included or prepended module - until the call returned; CRuby's next read answers the new one. A new constant moves ConstantAccessVersion only, which a running loop's safe point does not read. rminor's fix (moving the code epoch for any new constant whose name some code folded) was taken back for firing on every constant of that name anywhere. Now JitFoldedConstant.Resolve, when it folds, notes the name on every module the lookup searched (the lexical scopes' modules, the innermost one's ancestors, Object's from a module, a qualifier's ancestors), in the lookup's own hold of the class hierarchy lock. A constant new to such a module, or a mixin bringing one into it, is then a reassignment (RubyContext.ConstantReassigned): the code epoch moves and running loops look again at their next safe point - a typed body revalidates and deopts, an outlined copy hands itself back. A constant of that name in any other module is a new constant as before. IR_LOOP_NEAR=0 turns it off. Nothing changes on a loop's path when no such event happens. And a constant lookup from a module with prepended modules searched them ahead of the module's own table: `Q::X' after Q.prepend(m with X) answered m's X in every mode, CRuby 4.0 Q's own (the constant table stays with the class, not its origin). Only the module the lookup starts from: a superclass's or an included module's prepended constant still wins, as in CRuby. IR_CONST_OWN_FIRST=0 restores the old order. Util/loop-const-matrix.rb gains running loops that must stop when a nearer constant appears (lexical, superclass, include, prepend, a qualifier's include; body and outlined) and the prepend order rows; it prints CRuby's output on the new build in each mode, and with either switch off its own rows go wrong. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Src/Ruby/Builtins/RubyModule.cs | 83 +++++++++++++++++++-- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 38 +++++++++- Util/loop-const-matrix.rb | 67 ++++++++++++++++- 3 files changed, 176 insertions(+), 12 deletions(-) diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index f4f9d0d25..fb977a10d 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -1675,7 +1675,7 @@ internal RubyModule GetConstantOwnerNoLock(string/*!*/ name) { Context.RequiresClassHierarchyLock(); RubyModule owner = null; - ForEachAncestor(true, (module) => { + ForEachConstantAncestor(true, (module) => { ConstantStorage storage; if (module.TryGetConstantNoAutoloadCheck(name, out storage)) { owner = module; @@ -1790,6 +1790,51 @@ internal void Publish(string/*!*/ name) { RubyOps.ScopeSetMember(_context.TopGlobalScope, name, this); } + // IR_LOOP_NEAR=0: a constant new to a module on a folded lookup's path moves ConstantAccessVersion only, as any new one. + private static readonly bool _FoldedPaths = Environment.GetEnvironmentVariable("IR_LOOP_NEAR") != "0"; + + // The names of the constants compiled code folded through this module: lookups that searched it, or would have + // searched it ahead of where they found the constant (JitFoldedConstant.Resolve). Under the class hierarchy lock. + private HashSet _foldedConstantNames; + + internal void NoteFoldedConstantNoLock(string/*!*/ name) { + Context.RequiresClassHierarchyLock(); + if (_FoldedPaths) { + (_foldedConstantNames ??= new HashSet()).Add(name); + } + } + + private bool IsOnFoldedPathNoLock(string/*!*/ name) { + return _foldedConstantNames != null && _foldedConstantNames.Contains(name); + } + + /// + /// A module was included in or prepended to this one. A new constant moves ConstantAccessVersion, which a running + /// compiled loop does not read; one a folded lookup would now find nearer than what it folded is a change that loop + /// must see at its next iteration, as CRuby's next read does, as a reassignment is (RubyContext.ConstantReassigned). + /// So if a mixin of this module now has a constant of a name folded through this module, the code epoch moves: + /// keyed on the lookups' paths, a constant of that name anywhere else (rminor's epoch move fired for those) does not. + /// + private void MixinsChangedConstantsNoLock() { + if (_foldedConstantNames != null && (BringsFoldedConstantNoLock(_prepends) || BringsFoldedConstantNoLock(_mixins))) { + _context.ConstantReassigned(); + } else { + _context.ConstantsChanged(); + } + } + + private bool BringsFoldedConstantNoLock(RubyModule/*!*/[]/*!*/ modules) { + foreach (var module in modules) { + foreach (var name in _foldedConstantNames) { + ConstantStorage storage; + if (module.TryGetConstantNoAutoloadCheck(name, out storage)) { + return true; + } + } + } + return false; + } + private void SetConstantNoLock(string/*!*/ name, object value) { Mutate(); SetConstantNoMutateNoLock(name, value); @@ -1804,6 +1849,9 @@ internal void SetConstantNoMutateNoLock(string/*!*/ name, object value) { // assigned again: a running loop that folded it must see the new value (none has folded an // autoload that has not run: the file it loads assigning the constant is no reassignment) _context.ConstantReassigned(); + } else if (IsOnFoldedPathNoLock(name)) { + // new here, where a folded lookup of the name searched: nearer than what it found, so the same + _context.ConstantReassigned(); } else { _context.ConstantsChanged(); } @@ -1877,7 +1925,7 @@ public MutableString GetAutoloadedConstantPath(string/*!*/ name) { public MutableString GetAutoloadedConstantPath(string/*!*/ name, bool inherit) { using (Context.ClassHierarchyLocker()) { MutableString result = null; - ForEachAncestor(inherit, (module) => { + ForEachConstantAncestor(inherit, (module) => { ConstantStorage storage; AutoloadedConstant autoloaded; if (module.TryGetConstantNoAutoloadCheck(name, out storage)) { @@ -2078,12 +2126,33 @@ private ConstantLookupResult TryLookupConstantNoLock(bool included, bool inherit } // Returns the owner of the constant or null if the constant is not found. + // IR_CONST_OWN_FIRST=0: a constant is looked up in ancestor order, the modules prepended to the receiver first. + private static readonly bool _ConstantsOwnFirst = Environment.GetEnvironmentVariable("IR_CONST_OWN_FIRST") != "0"; + + /// + /// The modules a constant lookup from this one searches, in order: this module's own table first, and then its + /// ancestors as ForEachAncestor visits them, without it. CRuby keeps a module's constants in the module itself, + /// which comes before the modules prepended to it (rb_prepend_module moves the method table to the origin, not + /// the constant table), so `Q::X' finds Q's own X ahead of a prepended module's. Only the module the lookup + /// starts from: a superclass or an included module is reached through its prepended modules first, and theirs + /// win (`C::X' for C < S finds what S's prepended module has). + /// + private bool ForEachConstantAncestor(bool inherited, Func/*!*/ action) { + if (!_ConstantsOwnFirst || _prepends.Length == 0) { + return ForEachAncestor(inherited, action); + } + if (action(this)) { + return true; + } + return ForEachAncestor(inherited, (module) => module != this && action(module)); + } + private RubyModule TryResolveConstantNoAutoloadCheck(bool inherited, string/*!*/ name, out ConstantStorage value) { Context.RequiresClassHierarchyLock(); var storage = default(ConstantStorage); RubyModule owner = null; - if (ForEachAncestor(inherited, (module) => (owner = module).TryGetConstantNoAutoloadCheck(name, out storage))) { + if (ForEachConstantAncestor(inherited, (module) => (owner = module).TryGetConstantNoAutoloadCheck(name, out storage))) { value = storage; return owner; } else { @@ -3955,7 +4024,7 @@ internal void PrependModulesNoLock(RubyModule[]/*!*/ modules) { PrependsUpdated(oldPrepends, _prepends = expanded); _inheritedLookups = null; - _context.ConstantsChanged(); + MixinsChangedConstantsNoLock(); } /// @@ -4054,7 +4123,7 @@ internal void SpliceAncestorUpdate(RubyModule/*!*/ owner, RubyModule/*!*/[]/*!*/ } } - _context.ConstantsChanged(); + MixinsChangedConstantsNoLock(); } private static RubyModule[]/*!*/ SpliceBefore(RubyModule/*!*/[]/*!*/ list, int index, RubyModule/*!*/[]/*!*/ added) { @@ -4105,7 +4174,7 @@ internal void IncludeModulesNoLock(RubyModule[]/*!*/ modules) { MixinsUpdated(_mixins, _mixins = expanded); _inheritedLookups = null; - _context.ConstantsChanged(); + MixinsChangedConstantsNoLock(); if (!IsClass) { PropagateMixinsToDependentsNoLock(); @@ -4152,7 +4221,7 @@ private void ReexpandMixinNoLock(RubyModule/*!*/ mixin) { MixinsUpdated(_mixins, _mixins = expanded); _inheritedLookups = null; - _context.ConstantsChanged(); + MixinsChangedConstantsNoLock(); if (!IsClass) { PropagateMixinsToDependentsNoLock(); diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 9867f280d..dd8634bf3 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -171,7 +171,7 @@ private object ResolveConstant(ConstantVariable/*!*/ node) { if (scope == null) { throw Bail("constant without a scope: " + node.Name); } object value; RubyModule owner; - string failure = JitFoldedConstant.Resolve(_context, scope, node, out value, out owner); + string failure = JitFoldedConstant.Resolve(_context, scope, node, out value, out owner, true); if (failure != null) { throw Bail(failure); } _resolvedConstantOwner = owner; (_foldedConstants ?? (_foldedConstants = new List())).Add(new JitFoldedConstant(scope, node, value, owner)); @@ -2273,8 +2273,13 @@ internal bool StillHolds(RubyContext/*!*/ context) { /// an autoload pending or running, a deprecated or private constant, a missing one, or a scope lexically /// inside an object's singleton class (whose generic sites do not cache either). Null when it is one. /// + /// + /// : the lookup is being folded - every module it searched, or would search ahead of where it + /// found the constant, notes the name (RubyModule.NoteFoldedConstantNoLock), in the same hold of the class hierarchy + /// lock as the lookup: a constant of that name made in one of them later, or brought into one by a mixin, is then a + /// change a running loop that folded this must see (RubyModule.ConstantAddedNoLock). internal static string Resolve(RubyContext/*!*/ context, RubyScope/*!*/ scope, ConstantVariable/*!*/ node, - out object value, out RubyModule resolvedOwner) { + out object value, out RubyModule resolvedOwner, bool notePath = false) { string name = node.Name; value = null; resolvedOwner = null; @@ -2285,7 +2290,7 @@ internal static string Resolve(RubyContext/*!*/ context, RubyScope/*!*/ scope, C if (qualifier == null) { return "constant qualified by an expression: " + name; } object qualifierValue; RubyModule qualifierOwner; - failure = Resolve(context, scope, qualifier, out qualifierValue, out qualifierOwner); + failure = Resolve(context, scope, qualifier, out qualifierValue, out qualifierOwner, notePath); if (failure != null) { return failure; } var module = qualifierValue as RubyModule; if (module == null) { return "constant qualified by a non-module: " + name; } @@ -2297,6 +2302,7 @@ internal static string Resolve(RubyContext/*!*/ context, RubyScope/*!*/ scope, C if (!module.TryResolveConstantNoLock(null, name, out storage) || module.IsPrivateConstantInAncestors(name)) { return "qualified constant not found: " + name; } + if (notePath) { NoteAncestors(module, name); } if ((failure = NotDeprecated(context, module.GetConstantOwnerNoLock(name), name)) != null) { return failure; } resolvedOwner = module.GetConstantOwnerNoLock(name) ?? module; value = storage.Value; @@ -2311,6 +2317,7 @@ internal static string Resolve(RubyContext/*!*/ context, RubyScope/*!*/ scope, C if (!obj.TryResolveConstantNoLock(null, name, out storage) || obj.IsPrivateConstant(name)) { return "constant not found: ::" + name; } + if (notePath) { NoteAncestors(obj, name); } if ((failure = NotDeprecated(context, obj.GetConstantOwnerNoLock(name), name)) != null) { return failure; } resolvedOwner = obj.GetConstantOwnerNoLock(name) ?? obj; } else { @@ -2318,6 +2325,7 @@ internal static string Resolve(RubyContext/*!*/ context, RubyScope/*!*/ scope, C if (scope.TryResolveConstantNoLock(null, name, out storage, out owner) != null) { return "constant not found: " + name; } + if (notePath) { NoteLexicalPath(context, scope, name); } // the owner is only reported once some constant has been deprecated if ((failure = NotDeprecated(context, owner, name)) != null) { return failure; } resolvedOwner = owner; @@ -2335,6 +2343,30 @@ internal static string Resolve(RubyContext/*!*/ context, RubyScope/*!*/ scope, C return null; } + // The modules a lookup of `name' from the module searches (its ancestors), each noting the name. + private static void NoteAncestors(RubyModule/*!*/ module, string/*!*/ name) { + module.ForEachAncestor(true, (m) => { m.NoteFoldedConstantNoLock(name); return false; }); + } + + // The modules an unqualified lookup from the scope searches (RubyScope.TryResolveConstantNoLock): the lexical + // scopes' modules, the innermost one's ancestors, and Object's when that is a module or there is none. All of + // them, not only those ahead of where the constant was found: one after it costs a needless hand-back at most. + private static void NoteLexicalPath(RubyContext/*!*/ context, RubyScope/*!*/ scope, string/*!*/ name) { + RubyModule innerMost = null; + for (RubyScope s = scope; s != null; s = s.Parent) { + if (s.Module != null) { + s.LexicalConstantModule.NoteFoldedConstantNoLock(name); + innerMost ??= s.Module; + } + } + if (innerMost != null) { + NoteAncestors(innerMost, name); + } + if (innerMost == null || !innerMost.IsClass) { + NoteAncestors(context.ObjectClass, name); + } + } + /// A deprecated constant warns on every read, which the generic code does. private static string NotDeprecated(RubyContext/*!*/ context, RubyModule owner, string/*!*/ name) { if (context.HasDeprecatedConstants && (owner == null || owner.GetDeprecatedConstantOwnerNoLock(name) != null)) { diff --git a/Util/loop-const-matrix.rb b/Util/loop-const-matrix.rb index 5b48a90db..d1ae6a247 100644 --- a/Util/loop-const-matrix.rb +++ b/Util/loop-const-matrix.rb @@ -72,7 +72,7 @@ def self.go = run { i = 0; s = 0; while i < N; s += X7; i += 1; end; s } module Q8; X = 1; end module R8; end loop8 = -> { run { i = 0; s = 0; while i < N; s += Q8::X; i += 1; end; s } } -# (not `Q8.prepend(Module.new { const_set(:X, 40) })`: IronRuby finds the prepended X in every mode, CRuby Q8's own) +row "qualifier's module gets a prepend", entries(10, ->(k) { Q8.prepend(Module.new { const_set(:X, 40) }) if k == 5 }) { loop8.() } row "qualified, its path replaced", entries(10, ->(k) { Object.const_set(:Q8, Module.new { const_set(:X, 50) }) if k == 5 }) { loop8.() } # an autoload registered nearer between entries, and a loop entered while an autoload of that name is in flight @@ -108,6 +108,69 @@ def self.go = run { i = 0; s = 0; while i < N; s += X12; i += 1; end; s } sleep 0.01 until seen.size > 50 L12.const_set(:X12, 100) t.join -row "nearer defined on another thread (between entries)", [seen.first, seen.last, seen.uniq.size <= 2, seen.drop_while { |v| v == N }.uniq] +# (an entry running when the constant appears may add some of each: a running loop sees it at its next read) +row "nearer defined on another thread", [seen.first, seen.last, seen.all? { |v| v.between?(N, 100 * N) }] + +# ---------------------------------------------------------------- 4. a running loop, and a nearer constant another thread defines +# Each loop runs while the constant it reads is still the one it started with, up to a limit far beyond what it needs: a +# loop that does not see the nearer constant appear (CRuby's next read does) runs to the limit and says so. The methods are +# warmed with short runs first, so that the method JIT has typed them. +LIMIT = 1_000_000_000 +def nearer(define) + t = Thread.new { sleep 0.05; define.() } + r = yield + t.join + r +end +R1 = 1 +module RL1 + def self.body(n = LIMIT) = (i = 0; while R1 == 1 && i < n; i += 1; end; i < n) +end +200.times { RL1.body(20) } +row "running body, nearer lexical", nearer(-> { RL1.const_set(:R1, 2) }) { RL1.body } +R2 = 1 +module RL2 + def self.outlined(n = LIMIT) = run { i = 0; while R2 == 1 && i < n; i += 1; end; i < n } +end +row "running outlined, nearer lexical", nearer(-> { RL2.const_set(:R2, 2) }) { RL2.outlined } +R3 = 1 +class RB3; end +class RC3 < RB3 + def self.body(n = LIMIT) = (i = 0; while R3 == 1 && i < n; i += 1; end; i < n) +end +200.times { RC3.body(20) } +row "running body, nearer in a superclass", nearer(-> { RB3.const_set(:R3, 2) }) { RC3.body } +R4 = 1 +class RC4 + def self.outlined(n = LIMIT) = run { i = 0; while R4 == 1 && i < n; i += 1; end; i < n } +end +row "running outlined, nearer by include", nearer(-> { RC4.include(Module.new { const_set(:R4, 2) }) }) { RC4.outlined } +R5 = 1 +module RL5 + def self.body(n = LIMIT) = (i = 0; while R5 == 1 && i < n; i += 1; end; i < n) +end +200.times { RL5.body(20) } +row "running body, nearer by prepend", nearer(-> { RL5.prepend(Module.new { const_set(:R5, 2) }) }) { RL5.body } +class RB6; Y = 1; end +class RQ6 < RB6; end +def rq6(n = LIMIT) = run { i = 0; while RQ6::Y == 1 && i < n; i += 1; end; i < n } +row "running outlined, qualified, nearer by the qualifier's include", nearer(-> { RQ6.include(Module.new { const_set(:Y, 9) }) }) { rq6 } + +# ---------------------------------------------------------------- 5. the order a constant lookup searches a module with prepends +class S13; X = :s_own; end +S13.prepend(Module.new { const_set(:X, :s_pre) }) +class C13 < S13; end +module M13; Y = :m_own; end +M13.prepend(Module.new { const_set(:Y, :m_pre) }) +class D13; include M13; end +class F13; W = :own; end +F13.prepend(Module.new { const_set(:W, :pre) }) +module N13; V = :n; end +module N13b; V = :n2; end +class G13; include N13; prepend N13b; end +row "own table before prepends", [S13::X, S13.const_get(:X), M13::Y, F13::W, F13.const_get(:W), F13.const_defined?(:W)] +row "superclass's and mixin's prepends win", [C13::X, C13.const_get(:X), D13::Y, D13.const_get(:Y), G13::V] +loop13 = -> { run { i = 0; s = 0; while i < N; s += (F13::W == :own ? 1 : 0); i += 1; end; s } } +row "a loop over it", entries(6, nil) { loop13.() } puts "end" From 4e4266549e308ee8c169a5bdb169505974d7ad86 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:14:02 +0000 Subject: [PATCH 190/439] Ledger: perf/loopnear (round thirty-nine, gap 29) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Util/perf/LEDGER.md | 51 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e0c83ce3b..c48a2dfc5 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1523,13 +1523,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and a method body with an effect that only a method redefinition makes stale, which goes on with the old method until it returns (`MethodLoopSafePointSlow`'s impure branch). Done for outlined loops in round thirty-eight (see Landed, perf/loopconst): an outlined loop's - entry looks its folded constants up again rather than comparing a baked version. Still open: a - running loop (outlined or a method body's) does not see a nearer constant appear (only the - constant version moves, which its safe point does not read; the fix keys on the folded lookups' - paths and is untried); an outlined loop's safe point still hands the loop back on any reassignment - (the code epoch, compared as an immediate), which rebuilds the copy. Found on the way, in every - mode on master: `Q8::X` after `Q8.prepend(Module.new { const_set(:X, 40) })` answers the prepended - module's X; CRuby 4.0 answers Q8's own (`Util/loop-const-matrix.rb` notes it). + entry looks its folded constants up again rather than comparing a baked version. And the running + loop's fault (rminor's case) in perf/loopnear (see Landed): a nearer constant that appears on a + folded lookup's path moves the code epoch. Still open: an outlined loop's safe point hands the + loop back on any reassignment (the code epoch, compared as an immediate), which rebuilds the copy; + a typed body that deopts there finishes its call in the generic body (`near.rb`: 0.45 s typed, + 14.6 s once deopted, CRuby 6.6 s). 30. **`Binding#local_variable_get`, `_set`, `_defined?` and `local_variables` are an `eval` of source text each** (the prelude, `class Binding`): 436 us for a set against 0.1 on CRuby. `ERB#result_with_hash` sets one per key (237 times CRuby), irb sets `_` @@ -1782,6 +1781,44 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/loopnear (round thirty-nine, 2026-11-27) - a running loop sees a nearer constant appear; a + module's own constants before its prepends (gap 29)** - not gated. A compiled loop that folded a + constant (an outlined loop, or a typed method body's) went on answering it after another thread made + a constant of that name nearer to the lookup (lexically, in a superclass, through an include or a + prepend): a new constant moves `ConstantAccessVersion` only, which a running loop's safe point does + not read. rminor's epoch move, keyed on the name, fired for every constant of that name anywhere and + was taken back. Now `JitFoldedConstant.Resolve`, when it folds, notes the name on each module the + lookup searched (`RubyModule.NoteFoldedConstantNoLock`: the lexical scopes' modules, the innermost + one's ancestors, Object's from a module, a qualifier's ancestors - all of them, not only those ahead + of the owner, which costs a needless hand-back at most), in the lookup's own hold of the class + hierarchy lock. A constant new to such a module, or a mixin bringing one into it + (`MixinsChangedConstantsNoLock`), is a reassignment (`ConstantReassigned`): the code epoch moves, a + typed body's safe point revalidates and deopts, an outlined copy hands itself back. `IR_LOOP_NEAR=0` + turns it off. Nothing on a loop's own path changed. + The probe (`near.rb`: `X` folded in `module L`, 300M iterations, a thread starting 0.2 s in): + defining `X` on fresh classes and modules every millisecond - no deopt, base / new 0.45 / 0.45 s + (body), 0.39 / 0.44 (outlined); `L.const_set(:X, 100)` - base answers the old value to the end, new + sees the new one (one deopt or hand-back; the deopted body finishes in the generic body, 14.6 s + against CRuby's 6.6). A loop with no such event: instructions (`deadconst-shapes.rb`, count.sh, + N=20,000) identical to the instruction on all nine shapes; time over 10 alternating processes, + base / new mean (min): body 0.447 (0.39) / 0.426 (0.38), outlined 0.399 (0.38) / 0.414 (0.38). + Also fixed, the difference perf/loopconst recorded: a constant lookup from a module with prepended + modules searched them ahead of the module's own table (`Q::X` after `Q.prepend(m)` with `m::X` + answered m's in every mode; CRuby 4.0 answers Q's own, the constant table staying with the class, + not its origin). `RubyModule.ForEachConstantAncestor` searches the module the lookup starts from + first, then its ancestors: only that one (CRuby: `C::X` for `C < S` finds S's prepended module's X + ahead of S's own, and an included module's prepend wins too). Used by resolution, the owner lookup + and `autoload?`. `IR_CONST_OWN_FIRST=0` restores the old order. + `Util/loop-const-matrix.rb` gains running loops that must stop when a nearer constant appears + (lexical, superclass, include, prepend, a qualifier's include; bodies and outlined), the prepend + order rows, and the prepend row it had left out; CRuby 4.0's output on the new build in every mode, + and with `IR_LOOP_NEAR=0` or `IR_CONST_OWN_FIRST=0` exactly its own rows go wrong (base: those and + the prepend rows). `gate-matrices.rb` on hot-shapes, jit, osr-array, deadconst, jit-const, + loop-const, sdef, prepend and prepend2 in eight modes (the gate's six, `IR_LOOP_CONSTANTS=0`, + `IR_SINGLETON_LOOKUP=0`): PASS, 72 same. ruby/spec language/constants, core/module const_set, + const_get, const_defined, const_source_location, remove_const, prepend, autoload: no failures on + either build. The census cannot see this. + - **perf/loopconst (round thirty-eight, 2026-11-27) - an outlined loop looks its folded constants up again at its entry (gap 29)** - not gated. A loop outlined by OSR (`JitLoopCompiler`) that folded a constant guarded its entry on the runtime's constant version as it was when the copy was compiled, From 8a9c997fbf6af195eca8afd33f1bddec1e4ab885 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:14:55 +0000 Subject: [PATCH 191/439] Design: a yield in an outlined loop (JITResume stage 3a, gap 18) Not built: the narrowest sound slice needs four mechanisms the OSR tier lacks. A typed copy of `while i < @a.size; yield @a[i]; i += 1; end` has to make the method return on the block's break, write its locals back when an exception leaves through the yield, see an Integer#+ the block redefined in the same iteration, and fire the generic :line for `i += 1` when the block enabled a TracePoint. Handing back before the tail would skip `i += 1`; running it typed would miss the redefinition and the hook. Docs/jit-resume-deopt.md gets "Stage 3a": the shape, the four ways out of an iteration after the yield (a guarded typed tail, a generic tail compiled from the loop body's statements after the yield, a MethodReturned answer for break, the write-back on an exception), what the copy's state must hold, the matrix rows and an order of work. Util/yield-loop-matrix.rb (new, 31 rows) prints CRuby's output on the unchanged build in all six gate modes. The ledger records it under gap 18 and in the Rejected list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Docs/jit-resume-deopt.md | 128 +++++++++++++++++++++++++++- Util/yield-loop-matrix.rb | 175 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 302 insertions(+), 1 deletion(-) create mode 100644 Util/yield-loop-matrix.rb diff --git a/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md index fddd4cd43..33891b2fe 100644 --- a/Docs/jit-resume-deopt.md +++ b/Docs/jit-resume-deopt.md @@ -2,7 +2,8 @@ Status: stage 1 is implemented behind `-X:JITResume` (off by default; `Src/Ruby/Runtime/Jit/JitResume.cs`, `JitCompiler.Resume.cs`, matrix section 11 of `Util/jit-matrix.rb`), narrowed as its section says; the rest -is design only. It answers gap 1 of `Util/perf/LEDGER.md` +is design only, including stage 3a at the end (a yield in an outlined loop, gap 18), whose matrix is +`Util/yield-loop-matrix.rb`. It answers gap 1 of `Util/perf/LEDGER.md` ("Calls of other methods from hot bodies"): `CallSite.Target` is 24-32% of every benchmark, and Richards, Towers, DeltaBlue, Bounce and CD's `tree_insert` all wait on one rule of the method JIT. @@ -377,3 +378,128 @@ the `while` statement with `#resume` clear, and the generic code evaluates the c the first's index, which would run an iteration whose condition nobody evaluated. Then `-X:JITResume` on by default, after a full sweep and the benchmark suite, if stages 1-4 measured as faster. + +## Stage 3a: a yield in an outlined loop (gap 18) + +Status: design, with its matrix (`Util/yield-loop-matrix.rb`, which CRuby and the unchanged build print +alike). Written in round thirty-seven (perf/yieldresume) after perf/yieldloop measured the gap: +`def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; self; end` costs about 40 ns per element +yielding to an empty block, CRuby 28. Of that the yield itself is about 11 ns (CRuby's about 10), and the +rest is the loop running generic, because the loop compiler bails at the YieldCall (`[osr] emitter: node: +YieldCall`). A typed copy of the loop with the yield as a call in it would be about 23 ns. + +This is a narrower problem than stage 3, and the OSR tier is the place for it, not the method JIT: + +- The method JIT never wraps a method that uses its block (the screen), and a yielding iterator is the + whole point. The OSR copy of a loop runs **inside the generic body** (a light frame's or a full one): + that body is the method's frame - its backtrace line, its `ensure`, its flow-control frame, its lazily + made scope - and the copy is entered at the top of an iteration and leaves at the top of one. +- The yield stays a call: the block runs its own compiled code, so its frame (`block in ...`), its + `next`/`redo`, its TracePoint `:b_call` and its backtraces are the generic ones. Nothing is inlined. +- The copy already leaves only at an iteration boundary: a deopt restores the snapshot taken at the top of + the iteration and answers `Retry`, and the generic loop runs that iteration again. That is sound up to + the yield - nothing observable has happened in the iteration - and it is the stage-1 rule applied per + iteration. So the only new question is the **tail**: the statements of the iteration after the yield. + +### The shape + +`while C; S1 ... Sk; yield E1, ..., En; T1 ... Tm; end`, with exactly one yield, in statement position, +directly in the loop body (not in an `if`, a `begin`, a nested loop or the condition), the arguments +plain (no splat, no block pass), and `C`, the `S` and the `E` what the copy compiles today. Anything else +keeps today's answer (the loop bails). The method's block and its yield BlockParam are new inputs of the +copy: the block is read once on entry, as the generic yield reads it (`MakeMethodBlockParameterRead`: +the light frame's block parameter, or the scope's); the BlockParam is the copy's local, reused across +iterations by `ReuseBfcForYield` as the generic loop reuses it. + +### The four ways out of an iteration after the yield + +Each of them ends either at the **next** iteration boundary, with the end-of-iteration state in the +tuple, or by leaving the method; none restarts the iteration. + +1. **Normal.** Right after the yield the copy tests one guard, G: the global method version and the + constant version are the ones its prologue checked, `TracePoint.ActiveEvents` is 0, and the yield did + not break (`MethodYield`'s test). With G, the tail runs typed. A tail operation that would deopt + today must not: `i += 1` on an Int or Lng local that overflows has, with G (Integer#+ is still the + library's), a known result, the Bignum, which `JitRuntime` makes without calling Ruby; the local then + holds an `Obj` for the rest of the iteration. An operation whose guard fails for another reason + (an `Array#[]` on a receiver whose class moved, an attribute read) takes the same path: its result is + computed by its generic operation on the operands already evaluated, as stage 1's fallbacks are, and + is `Obj` from there. Once a tail operation has gone `Obj`, every later tail operation is emitted on + `Obj` (the self-guarded tail: stage 2's rule, applied to a tail only), and at the end of the iteration + the copy writes its locals into the tuple and answers **Handback**: a new answer of the site (next to + `Retry`) that the generic loop takes as "continue at the head, evaluating `C` yourself", the snapshot + not restored. A tail that went typed to the end goes on to the next iteration in the copy. +2. **The world changed, or tracing came on** (G fails). The block may have redefined `Integer#+` + (`redefine +` in the matrix: CRuby calls the new `+` for the very `i += 1` that follows), reassigned + a constant, or enabled a TracePoint whose `:line` for `i += 1`, with a binding that sees `i`, CRuby + fires (`trace line`, `trace binding`). Neither can be had from typed code. The copy writes its locals + into the tuple and runs the **generic tail**: `T1 ... Tm` compiled by the AstGenerator exactly as the + generic body compiles them (the same sites, the same TraceLineExpressions), as a lambda over the + method's scope, built the first time it is needed and cached on the site (cold code). In a light frame + the scope is made as a TracePoint would make it (`LightFrame.MakeScopeIfTraced`), which needs the + frame's `#rfc`, self and block as copy inputs too, and is then the frame's for the rest of the call + (the light frame's `#scope` variable, so that the generic loop that follows uses the same one). Then + Handback. This is stage 3's resumable body for one resume point - after the yield - and without its + dispatch problem: the tail is a straight-line suffix of the loop body, inside no try region the + generic body would have to jump into, which is why the shape takes the yield only directly in the + loop body. +3. **Break.** The block's `break v` makes the iterator return `v` (`MethodYield` answers true and the + generic yield returns from the method). The copy writes its locals into the tuple and answers + **MethodReturned(v)**, a new answer the generic loop's glue (`WhileLoopExpression`, the `osrResult` + test) turns into the method's own `return v` (`gen.Return`), so the method's `ensure`, the light + frame's finally and TracePoint's `:return` run as they do for the generic yield (`break ensure`). + `next` and `redo` are the block's own and need nothing. +4. **An exception through the yield.** A `raise` or `throw` in the block, a `return` from it (a + MethodUnwinder aimed at the caller), Thread#raise or #kill: the copy's locals are written into the + tuple on the way out (a fault handler around the yield, or a finally keyed on a flag), so a `rescue` + or `ensure` of the method sees the loop's own counter (`raise rescue`: `["at 42", 41]`). + +Everything before the yield is as today: a deopt in `C`, the `S` or the `E` restores the snapshot and +the iteration runs again generically, since nothing observable has happened in it. A redefinition by +the block is seen by the next iteration's `C` through the prologue's version check moved to the +iteration's safe point (it is there already: the copy's safe point checks the code epoch). + +### What else the state must hold + +- **Representation in the tuple.** A local that went `Obj` in the tail is written as the object; a typed + one through the representation funnel (`NarrowLong`), as the copy's exits do now. +- **Threads and re-entrancy.** All of it is per invocation: the block, the BlockParam, the locals are + locals of the copy's delegate. The generic tail lambda is shared and stateless. A re-entrant call of the + iterator from the block (`re-entrant`, `recursion`) runs its own generic body and its own copy. +- **The undo log.** The copy logs no element writes of its own in this shape; a tail with an element + write (`r << yield(x)` is a call, not a write) is declined until it is needed. +- **The yield's arity and protocol.** `Yield0` ... `YieldN` by the argument count, as the generic yield + chooses; the yield's value is `Obj`. + +### The matrix's rows (`Util/yield-loop-matrix.rb`) and what each one checks + +| Rows | Checks | +|---|---| +| `hot`, `sizes`, `returns self`, `enumerator`, `each2` | the typed copy with a yield computes what the generic loop does, empty to 100 elements, two yielded values | +| `break`, `break ensure`, `break each2`, `throw` | way 3: the block's break value is the method's, its `ensure` sees the loop's counter; a throw leaves through way 4 | +| `next`, `redo`, `symbol`, `lambda`, `method`, `kept block` | the block's own protocol and the forms a block comes in, untouched by the copy | +| `raise rescue`, `raise ensure`, `raise outside` | way 4: the counter is written back before a rescue or ensure of the method reads it | +| `redefine +`, `redefine []` | way 2: the tail's `i += 1` calls the `+` the block defined, in the same iteration; the next `@a[i]` the `[]` | +| `trace line`, `trace binding` | way 2: `:line` for the tail's statement, in the iteration that enabled it, with a binding that sees `i` | +| `grow`, `shrink`, `freeze`, `ivar swap` | the next iteration's condition and element read see what the block did to the array or to `@a` (a deopt there replays nothing) | +| `re-entrant`, `recursion`, `fiber`, `threads` | per-invocation state: the copy's block, BlockParam and locals are its own | +| `big counter` | way 1: an `i += 2**61` past Int64 in the tail is the Bignum, handed back at the end of the iteration | + +### Order of work, each step gated by the matrix + +1. The two answers, Handback and MethodReturned, in `OsrLoopSite` and the glue, with a C# test that a + copy can hand back after a typed tail and that `MethodReturned` runs the method's ensure. +2. The yield in the copy, with ways 2, 3 and 4: the block and BlockParam inputs, `Yield0`-`YieldN`, the + write-back on an exception, MethodReturned on a break, and the generic tail lambda run whenever G + fails. With G the tail runs typed only if it cannot fail - in this step a tail of `local += literal` on + Int/Lng locals, whose overflow makes the Bignum (way 1's first case) and hands back at the end of the + iteration - and any other tail always runs generic. No step may hand back *before* the tail: the + generic loop starts at the head, so a tail skipped there is a statement lost (`i += 1` never run), and + a tail run without its hooks is a `:line` lost (`trace line`, `trace binding`). +3. The typed tail with its `Obj` continuation (way 1) for tails of more than local increments. + +Each step's rows: `Util/yield-loop-matrix.rb` in every mode and with the switch off; block-loop, osr, +jit, jit-calls, parked-iterator and hot-shapes matrices; ruby/spec language/yield, break, while; +`IR_OSR_VERBOSE=1` showing the iterator's loop specialized (the probe reaches the path). The measure is +`Util/bench/yield-shapes.rb` (`ueach100`, `ueach100e` against CRuby) and the prelude's `take_while`, +`sum`, `uniq` and `to_h` with a block, by clock. diff --git a/Util/yield-loop-matrix.rb b/Util/yield-loop-matrix.rb new file mode 100644 index 000000000..accf9e544 --- /dev/null +++ b/Util/yield-loop-matrix.rb @@ -0,0 +1,175 @@ +# Differential checks for a `while ... yield` loop in a method (gap 18; the rows a typed copy of such a loop must pass, +# Docs/jit-resume-deopt.md, "Stage 3a: a yield in an outlined loop"). Every iterator below runs hot - several hundred +# calls over a hundred elements - so that the loop tier sees it, and each row then makes the block do what the copy +# would have to get right after the yield: break, next, redo, raise, redefine Integer#+ or Array#[], freeze or change +# the array, enable a TracePoint, re-enter the iterator, run on four threads. The output must match CRuby's: +# +# ruby Util/yield-loop-matrix.rb > /tmp/cruby.txt +# ./ir.sh Util/yield-loop-matrix.rb > /tmp/ir.txt +# diff /tmp/cruby.txt /tmp/ir.txt +# +# (also with -X:NoJIT -X:NoOSR, IR_LIGHT_FRAMES=0, IR_PARKED_SCOPES=0 and the change's own switch) +$stdout.sync = true + +def rows(name) = puts("#{name}: #{yield.inspect}") + +class L + attr_reader :log + def initialize(a) = (@a = a; @log = []) + def each + return to_enum(:each) unless block_given? + i = 0 + while i < @a.size + yield @a[i] + i += 1 + end + self + end + def each_ensure + i = 0 + begin + while i < @a.size + yield @a[i] + i += 1 + end + ensure + @log << [:ensure, i] + end + end + def each_rescue + i = 0 + begin + while i < @a.size + yield @a[i] + i += 1 + end + :done + rescue => e + [e.message, i] + end + end + def map_like + r = [] + i = 0 + while i < @a.size + r << yield(@a[i]) + i += 1 + end + r + end + def each2 + i = 0 + while i < @a.size + yield @a[i], i + i += 1 + end + i + end + def each_block(&b) + i = 0 + while i < @a.size + yield @a[i] + i += 1 + end + b + end + def each_last + i = 0 + x = nil + while i < @a.size + x = @a[i] + yield x + i += 1 + end + [i, x] + end +end + +A100 = (1..100).to_a.freeze +l = L.new(A100.dup) +hot = 0 +400.times { l.each { |x| hot += x } } +rows("hot") { hot } +rows("sizes") { [[], [7], [1, 2, 3, 4], A100].map { |a| s = 0; L.new(a).each { |x| s += x }; s } } +rows("returns self") { l.each { }.equal?(l) } +rows("enumerator") { l.each.first(3) } + +# break, next and redo from the block +rows("break") { 3.times.map { |k| l.each { |x| break [:broke, x] if x == 50 + k } } } +rows("break ensure") { e = L.new(A100.dup); r = e.each_ensure { |x| break x * 2 if x == 37 }; [r, e.log] } +rows("next") { l.map_like { |x| next -x if x.odd?; x }.first(6) } +rows("redo") { seen = []; tries = 0; l.map_like { |x| tries += 1; redo if x == 3 && tries < 5; seen << x; x }.size.then { [seen.first(5), tries] } } +rows("break each2") { l.each2 { |x, i| break [x, i] if i == 99 } } +rows("each2") { l.each2 { |x, i| } } + +# a raise in the block: the iterator's rescue and ensure see the loop's own counter +rows("raise rescue") { L.new(A100.dup).each_rescue { |x| raise "at #{x}" if x == 42 } } +rows("raise ensure") { e = L.new(A100.dup); r = (e.each_ensure { |x| raise ArgumentError if x == 64 } rescue $!.class); [r, e.log] } +rows("raise outside") { s = 0; r = (l.each { |x| s += x; raise IndexError, "#{x}" if x == 99 } rescue $!.message); [r, s] } +rows("throw") { catch(:t) { l.each { |x| throw :t, x if x == 77 }; :none } } + +# the block changes the world under the loop: Integer#+, Array#[], the array, a freeze +rows("redefine +") { + calls = [] + r = l.each_last { |x| + if x == 10 + Integer.class_eval { alias_method :__ylm_plus, :+; define_method(:+) { |o| calls << [self, o] if o == 1 && calls.size < 3; __ylm_plus(o) } } + elsif x == 12 + Integer.class_eval { alias_method :+, :__ylm_plus; remove_method :__ylm_plus } + end + } + [r, calls] +} +rows("redefine []") { + reads = [] + e = L.new(A100.dup) + r = e.each_last { |x| + if x == 20 + Array.class_eval { alias_method :__ylm_at, :[]; define_method(:[]) { |*a| reads << a if reads.size < 3; __ylm_at(*a) } } + elsif x == 22 + Array.class_eval { alias_method :[], :__ylm_at; remove_method :__ylm_at } + end + } + [r, reads] +} +rows("grow") { a = [1, 2, 3]; s = []; L.new(a).each { |x| s << x; a << x + 10 if a.size < 8 }; s } +rows("shrink") { a = (1..10).to_a; s = []; L.new(a).each { |x| s << x; a.pop }; s } +rows("freeze") { a = (1..5).to_a; s = []; L.new(a).each { |x| s << x; a.freeze if x == 2 }; [s, a.frozen?] } +rows("ivar swap") { e = L.new([1, 2, 3]); s = []; e.each { |x| s << x; e.instance_variable_set(:@a, [7, 8, 9, 10]) if x == 1 }; s } + +# a TracePoint enabled from the block sees the rest of the iteration +rows("trace line") { + ev = [] + tp = TracePoint.new(:line, :return) { |t| ev << [t.event, t.lineno - L.instance_method(:each).source_location[1], t.method_id] if t.path == __FILE__ && t.method_id == :each } + L.new((1..6).to_a).each { |x| tp.enable if x == 3; tp.disable if x == 5 } + ev.first(12) +} +rows("trace binding") { + vals = [] + tp = TracePoint.new(:line) { |t| vals << t.binding.local_variable_get(:i) if t.path == __FILE__ && t.method_id == :each } + L.new((1..4).to_a).each { |x| tp.enable if x == 2; tp.disable if x == 3 } + vals +} + +# the block passed in other forms, re-entrancy, a fiber, threads, an iterator that keeps its block +rows("lambda") { s = 0; l.each(&->(x) { s += x }); s } +rows("method") { $ylm = 0; def ylm_add(x) = $ylm += x; l.each(&method(:ylm_add)); $ylm } +rows("symbol") { L.new(%w[a b]).map_like(&:upcase) } +rows("kept block") { b = l.each_block { |x| x }; [b.class, b.call(5)] } +rows("re-entrant") { s = 0; small = L.new([1, 2, 3]); small.each { |x| small.each { |y| s += x * y } }; s } +rows("recursion") { r = []; t = nil; t = ->(n) { L.new((1..n).to_a).each { |x| r << [n, x]; t.(x - 1) if x == n && n > 1 } }; t.(3); r } +rows("fiber") { f = Fiber.new { l.each { |x| Fiber.yield x if x % 40 == 0 }; :end }; [f.resume, f.resume, f.resume] } +rows("threads") { 4.times.map { |t| Thread.new { ylm_s = 0; 50.times { l.each { |x| ylm_s += x * t } }; ylm_s } }.map(&:value) } +rows("big counter") { + big = Class.new { + def each + i = 2**62 + while i < 2**64 + yield i + i += 2**61 + end + i + end + }.new + r = []; e = big.each { |x| r << x }; [r.size, e, e.class] +} From 992cfcc2f86d7015a7fa7cd606503fb94c3b9279 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:15:15 +0000 Subject: [PATCH 192/439] Ledger: perf/yieldresume, the design of a yield in an outlined loop (gap 18) The commit before this one said the ledger records the design; its edit had not applied. Gap 18 gets what stage 3a of Docs/jit-resume-deopt.md designs, and the Rejected list why no smaller slice than its four mechanisms is sound. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Util/perf/LEDGER.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 66bd06b40..3ac58bd80 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1137,6 +1137,22 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has YieldCall`) and the light frame's `while` keeps its four dynamic sites. A typed loop with the `yield` as a call in it would be about 23 ns against CRuby's 28. What stands in the way is not the yield's cost but the iteration it would sit in (see Rejected). + The second step of round thirty-seven (perf/yieldresume, design only) wrote that down: + `Docs/jit-resume-deopt.md`, "Stage 3a: a yield in an outlined loop", with its matrix + `Util/yield-loop-matrix.rb` (31 rows; CRuby's output on the unchanged build in all six + modes). The OSR copy is the place, not the method JIT: it runs inside the generic body, + which stays the method's frame, and it already leaves only at iteration boundaries, so + everything before the yield is sound as it is. What is new is the iteration's tail after + the yield, which must end at the next boundary and never restart: four ways out - a typed + tail under one guard taken after the yield (method and constant versions, tracing, no + break), with an overflow making the Bignum; a generic tail, the loop body's statements + after the yield compiled as the generic body compiles them, when that guard fails (the + block redefined `Integer#+`, or enabled a TracePoint whose `:line` for `i += 1` CRuby fires + in the same iteration with `i` in its binding); a new site answer, MethodReturned, for the + block's break, turned into the method's own return; and the locals written back when an + exception leaves through the yield. Two new answers of `OsrLoopSite` (Handback, + MethodReturned) and the generic tail lambda are the work; the doc orders it in three steps, + none of which may hand back before the tail. 19. **`Object.new.extend(M)` is 200 to 300 times CRuby's time and grows with the number of objects extended**: 20,000 in a `while` loop take 4.5 s, 40,000 11.0 s, 200,000 72 s, with and without the JIT and OSR; CRuby takes 0.23 s for 200,000 (1.1 us each). @@ -6499,6 +6515,20 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/yieldresume (round thirty-seven, 2026-11-27) - a typed loop that resumes after a yield: + designed, not built** (gap 18; `Docs/jit-resume-deopt.md`, "Stage 3a"). The brief's narrowest slice - + `def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; end` typed and sound - needs four + mechanisms the OSR tier does not have: a way for the copy to make the method return (a `return` in an + outlined loop bails today: "the outlined copy has no way to return from the method"), for the block's + `break`; a write-back of the typed locals when an exception leaves through the yield, for the + iterator's own `rescue`/`ensure`; a typed `i += 1` after the yield that sees an `Integer#+` the block + redefined in the same iteration; and the generic `:line` hook for that `i += 1` when the block enabled + a TracePoint, with a binding that sees `i`, which needs the light frame's lazily made scope in the + copy. The last two are why no smaller slice is sound: a copy that hands back to the generic loop + before the tail skips `i += 1` (the generic loop starts at the head), and one that runs the tail + without its hooks loses CRuby's `:line`. `Util/yield-loop-matrix.rb` pins each of them (`redefine +` + calls the new `+` for the very `i += 1` after the yield; `trace line` fires `:line` for it first; + `trace binding` sees `i`). Nothing in the runtime changed; the design is the result. - **perf/yieldloop (round thirty-seven, 2026-11-27) - a `yield` in an outlined `while` loop: measured, not built** (gap 18). What a `while ... yield` pays per element is the loop, not the yield (gap 18's numbers): IronRuby's `yield` is about 11 ns, CRuby's about 10, and the loop around it is 28 ns generic From 16300b204406261e57dec2a7c5c58d67c9230962 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:17:46 +0000 Subject: [PATCH 193/439] A parked method scope keeps its locals tuple for the next call A method whose block literals park its scope with their Procs (RubyOps.CreateMethodScopeParked) still made a new locals tuple on every call: the entry makes the tuple before it knows whether it will take the parked scope (MakeLocalsStorage), and a light frame that keeps its locals in CLR variables makes it with the scope (MaterializeLocals). That tuple was all NBody's `advance' still allocated (24 bytes per call); DeltaBlue's `satisfy', `execute' and `incremental_remove', som.rb's `each', `append' and `remove', and Queens' `place_queen' park too. Now EndPark, when it parks the scope, clears the scope's tuple (up to 16 slots, a flat tuple) and keeps it with the scope (ParkedProcs.Locals), and the next call takes it (RubyOps.TakeParkedLocals, [Emitted]) with an atomic exchange: from the slot at the entry, or from the parked scope the call took when the tuple is made with the scope. A tuple is handed to one call; the scope and its tuple may go to different calls. Nothing else can hold the tuple when it is parked: parking already requires a scope that nothing captured and Procs that are reusable and inactive. A tuple of another type (another compilation of the body) is not taken. IR_PARKED_LOCALS=0 makes a new one as before. Util/parked-tuple-matrix.rb (new): a local set on some calls only, nil on the others; local_variables and defined?; bindings and Procs of the scope kept in the middle; an exception after the locals are set; more locals than a kept tuple holds; recursion; a light frame that makes its scope on some calls; threads calling one method and taking bindings; a call suspended in a fiber; eval; a TracePoint :return binding. It prints what CRuby 4.0 prints with the switch on and off, IR_PARKED_SCOPES=0, -X:NoJIT -X:NoOSR and on the base; with the clear at park left out, three rows go wrong. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- .../Ast/Definitions/MethodDefinition.cs | 18 +- Src/Ruby/Compiler/Ast/ScopeBuilder.cs | 27 ++- .../Compiler/ReflectionCache.Generated.cs | 2 + Src/Ruby/Runtime/RubyOps.cs | 48 +++++ Src/Ruby/Runtime/RubyScope.cs | 6 + Util/parked-tuple-matrix.rb | 176 ++++++++++++++++++ 6 files changed, 268 insertions(+), 9 deletions(-) create mode 100644 Util/parked-tuple-matrix.rb diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 6e5c75da8..dd4b4159d 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -394,13 +394,15 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin // A light frame keeps its locals in CLR variables if it can and makes few calls (MaxRegisterLocalsCalls): // `def one(x); yield x; end' would otherwise allocate their tuple on every call. MSA.Expression enter = null; + scope.ReusedLocals = ParkedLocals(parkSlot, null); + scope.ReusedLocalsWithScope = ParkedLocals(parkSlot, currentMethod.ParkedVariable); if (light != null) { var registerBody = (CountCalls() <= MaxRegisterLocalsCalls) ? scope.TryUseRegisterLocals(body) : null; if (registerBody != null) { body = registerBody; enter = light.EnterWithRegisterLocals(scope); } else { - enter = light.Enter(scope); + enter = light.Enter(scope, scope.ReusedLocals); } } @@ -409,7 +411,7 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin var locals = scope.LocalsTupleVariable; var parked = currentMethod.ParkedVariable; enter = Ast.Block( - scope.MakeLocalsStorage(), + scope.MakeLocalsStorage(scope.ReusedLocals), Ast.Assign(parked, Methods.TakeParkedScope.OpCall(Ast.Constant(parkSlot), declaringScope, declaringModule)), Ast.Condition(Ast.NotEqual(parked, AstUtils.Constant(null, typeof(ParkedProcs))), Methods.ReuseParkedScope.OpCall(parked, locals, selfParameter, blockParameter, EnterInterpretedFrameExpression.Instance), @@ -471,6 +473,14 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin /// internal static readonly bool LightBlocksEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_BLOCKS") != "0"; + // The tuple the entry of a body with a parking slot takes from the scope its last call parked (RubyOps.TakeParkedLocals), + // or null for a body without one. + private static MSA.Expression ParkedLocals(ParkedScopeSlot parkSlot, MSA.Expression taken) { + return (parkSlot != null && RubyOps.ParkedLocalsEnabled) + ? Methods.TakeParkedLocals.OpCall(Ast.Constant(parkSlot), taken ?? AstUtils.Constant(null, typeof(ParkedProcs))) + : null; + } + /// /// IR_PARKED_SCOPES=0 makes a new scope on every call of a method whose literal blocks reuse their Procs (see /// RubyOps.CreateMethodScopeParked); IR_PARKED_SCOPES=verbose names each method compiled with a parking slot. @@ -653,10 +663,10 @@ private sealed class LightFrame { /// Replaces CreateMethodScope: the locals, the safe point and the call's flow-control frame, the alias /// the method was called by, and a scope only if a TracePoint listens for calls. /// - internal MSA.Expression/*!*/ Enter(ScopeBuilder/*!*/ scope) { + internal MSA.Expression/*!*/ Enter(ScopeBuilder/*!*/ scope, MSA.Expression reusedLocals) { return Ast.Block( StackCheck, - scope.MakeLocalsStorage(), + scope.MakeLocalsStorage(reusedLocals), Ast.Assign(Rfc, EnterMethod), Ast.Assign(Callee, Methods.TakePendingCallee.OpCall(Name)), // the test inline, as in EnterWithRegisterLocals: a call of CreateMethodScopeIfTraced, with its nine diff --git a/Src/Ruby/Compiler/Ast/ScopeBuilder.cs b/Src/Ruby/Compiler/Ast/ScopeBuilder.cs index ada21ff64..5234537ad 100644 --- a/Src/Ruby/Compiler/Ast/ScopeBuilder.cs +++ b/Src/Ruby/Compiler/Ast/ScopeBuilder.cs @@ -255,11 +255,26 @@ private int LiftedVisibleVariableCount { } public MSA.Expression/*!*/ MakeLocalsStorage() { + return MakeLocalsStorage(null); + } + + /// + /// Where a method body with a parking slot takes a tuple of nils before it makes one (RubyOps.TakeParkedLocals): at its + /// entry (MakeLocalsStorage), and when it makes its scope from register locals (MaterializeLocals, after the parked + /// scope is taken). Null for any other body. + /// + internal MSA.Expression ReusedLocals, ReusedLocalsWithScope; + + /// + /// MakeLocalsStorage that takes the tuple gives, if it is one of this scope's type, before it + /// makes one: a tuple whose every slot is nil (RubyOps.TakeParkedLocals). + /// + public MSA.Expression/*!*/ MakeLocalsStorage(MSA.Expression reused) { // TODO: use a factory instead of Ast.New to improve interpreter perf: - MSA.Expression result = Ast.Assign( - _localsTuple, - LiftedVisibleVariableCount == 0 ? (MSA.Expression)Ast.Constant(null, _localsTuple.Type) : NewTuple(_localsTuple.Type) - ); + MSA.Expression tuple = (LiftedVisibleVariableCount == 0) ? (MSA.Expression)Ast.Constant(null, _localsTuple.Type) : + (reused != null) ? Ast.Coalesce(Ast.TypeAs(reused, _localsTuple.Type), NewTuple(_localsTuple.Type)) : + NewTuple(_localsTuple.Type); + MSA.Expression result = Ast.Assign(_localsTuple, tuple); if (_parameters != null) { var initializers = new AstExpressions(); @@ -395,7 +410,9 @@ internal MSA.Expression TryUseRegisterLocals(MSA.Expression/*!*/ body) { internal MSA.Expression/*!*/ MaterializeLocals() { Debug.Assert(_registers != null); var result = new AstExpressions(); - result.Add(Ast.Assign(_localsTuple, NewTuple(_localsTuple.Type))); + result.Add(Ast.Assign(_localsTuple, (ReusedLocalsWithScope != null) + ? Ast.Coalesce(Ast.TypeAs(ReusedLocalsWithScope, _localsTuple.Type), NewTuple(_localsTuple.Type)) + : NewTuple(_localsTuple.Type))); for (int i = 0; i < _registers.Length; i++) { result.Add(Ast.Assign(GetVariableAccessor(_localsTuple, i), _registers[i])); } diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index c43d8230e..9b726ab05 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -664,6 +664,8 @@ public static partial class Methods { private static MethodInfo _TakeBfcForBlockYield; public static MethodInfo/*!*/ TakeFreshSplat { get { return _TakeFreshSplat ?? (_TakeFreshSplat = CallInstruction.CacheFunc(RubyOps.TakeFreshSplat)); } } private static MethodInfo _TakeFreshSplat; + public static MethodInfo/*!*/ TakeParkedLocals { get { return _TakeParkedLocals ?? (_TakeParkedLocals = CallInstruction.CacheFunc(RubyOps.TakeParkedLocals)); } } + private static MethodInfo _TakeParkedLocals; public static MethodInfo/*!*/ TakeParkedScope { get { return _TakeParkedScope ?? (_TakeParkedScope = CallInstruction.CacheFunc(RubyOps.TakeParkedScope)); } } private static MethodInfo _TakeParkedScope; public static MethodInfo/*!*/ TakePendingCallee { get { return _TakePendingCallee ?? (_TakePendingCallee = CallInstruction.CacheFunc(RubyOps.TakePendingCallee)); } } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 730427f3a..40c1ff14a 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -402,6 +402,7 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R proc?.ClearForPark(); } var methodScope = (RubyMethodScope)scope; + parked.Locals = ParkedLocalsEnabled ? ClearForPark(methodScope._locals) : null; methodScope.ClearCallState(); parked.Scope = methodScope; parked.ThreadId = Environment.CurrentManagedThreadId; @@ -415,6 +416,53 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R Volatile.Write(ref slot.Spare, parked); } + /// + /// IR_PARKED_LOCALS=0: a call of a method that parks its scope makes a new locals tuple, as it did, rather than take the + /// tuple of the parked scope's last call (TakeParkedLocals). + /// + internal static readonly bool ParkedLocalsEnabled = Environment.GetEnvironmentVariable("IR_PARKED_LOCALS") != "0"; + + // The most slots of a locals tuple that is cleared and parked: a flat tuple (up to 128 slots is one) and a short clear. + private const int MaxParkedLocals = 16; + + /// + /// The locals tuple of a call whose scope is being parked, every slot cleared to nil, for the next call to take; null if it + /// is not one to keep. Nothing else holds it: the scope is not captured (BeginPark), and every Proc of the call that could + /// reach it is reusable and inactive (StageParkedProc), so nothing outlives the call that could read it - and the values it + /// held go with the call, as they would with a tuple that is dropped. + /// + private static MutableTuple ClearForPark(MutableTuple locals) { + if (locals == null) { + return null; + } + int capacity = locals.Capacity; + if (capacity > MaxParkedLocals) { + return null; + } + for (int i = 0; i < capacity; i++) { + locals.SetValue(i, null); + } + return locals; + } + + /// + /// The locals tuple a method with a parking slot makes, if it can be the one parked with the scope, cleared (the caller + /// checks its type, and makes a new one otherwise): of , the parked scope this call took, when the + /// tuple is made with the scope (ScopeBuilder.MaterializeLocals); of the one parked in the slot, when it is made at the + /// entry, before the call knows whether it will take the scope. Taken with an atomic exchange, apart from the scope, so + /// that each tuple belongs to one call: a call that takes the parked scope gives it this call's tuple (Reinitialize), and + /// one that does not leaves the scope parked without one. + /// + [Emitted] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static MutableTuple TakeParkedLocals(ParkedScopeSlot/*!*/ slot, ParkedProcs taken) { + var parked = taken ?? Volatile.Read(ref slot.Parked); + if (parked == null || parked.Locals == null) { + return null; + } + return Interlocked.Exchange(ref parked.Locals, null); + } + #endregion #region Light method frames diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index e59ef6b0d..a708935ad 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1408,12 +1408,18 @@ public sealed class ParkedProcs { internal readonly Proc[]/*!*/ Procs; internal int ThreadId; + // The locals tuple of the parked scope's last call, cleared, for the next call's entry to take (RubyOps.TakeParkedLocals): + // the entry makes the tuple before it knows whether it will take the scope, so the two are taken apart, each by one + // call. Null when there is none to take. + internal MutableTuple Locals; + internal ParkedProcs(int count) { Procs = new Proc[count]; } internal void Clear() { Scope = null; + Locals = null; Array.Clear(Procs, 0, Procs.Length); } } diff --git a/Util/parked-tuple-matrix.rb b/Util/parked-tuple-matrix.rb new file mode 100644 index 000000000..265bf19d8 --- /dev/null +++ b/Util/parked-tuple-matrix.rb @@ -0,0 +1,176 @@ +# Differential matrix for the locals tuple a method that parks its scope keeps for its next call (IR_PARKED_LOCALS: +# RubyOps.EndPark, TakeParkedLocals; ScopeBuilder.MakeLocalsStorage, MaterializeLocals). The tuple is cleared when the scope +# is parked and taken by the next call's entry, or with the scope by a light frame that keeps its locals in CLR variables. +# Run it under CRuby and under ./ir.sh with the switch on and off and with parked scopes and the tiers off, and diff: +# +# ruby Util/parked-tuple-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/parked-tuple-matrix.rb > /tmp/on.txt +# IR_PARKED_LOCALS=0 ./ir.sh Util/parked-tuple-matrix.rb > /tmp/off.txt +# IR_PARKED_SCOPES=0 ./ir.sh Util/parked-tuple-matrix.rb > /tmp/noparked.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/parked-tuple-matrix.rb > /tmp/notiers.txt +# +# Every method runs thousands of times, parking its scope, around the case it probes. Their block literals are given to +# core iterators that do not keep them (each, map, times), which is what lets them park. + +def t(label) + print label.ljust(64), ' => ' + begin + v = yield + puts "#{v.inspect} (#{v.class})" + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +N = 3000 + +class P + def initialize; @a = [1, 2, 3]; @kept = []; end + attr_reader :kept + + # a local assigned on some calls only: nil on the others + def maybe(set) + x = 41 if set + @a.each { |e| x = x.to_i + e if set } + [x, defined?(x), local_variables.sort] + end + + # a binding taken on some calls: it keeps its own locals + def bind(v) + w = v * 2 + @a.each { |e| w += e } + (v % 1000 == 7) ? binding : w + end + + # a Proc of the method's own scope kept on some calls (`proc' keeps the block it is given) + def keep(v) + u = v + 1 + @a.map { |e| e + u } + @kept << proc { [u, v] } if v % 1000 == 3 + u + end + + # an exception leaving after its locals are set + def raising(v) + q = v + @a.each { |e| q += e } + raise ArgumentError, "boom #{q}" if v % 700 == 5 + q + end + + # many locals: more than the tuple that is kept may hold + def many(v) + a1 = v; a2 = a1 + 1; a3 = a2 + 1; a4 = a3 + 1; a5 = a4 + 1; a6 = a5 + 1; a7 = a6 + 1; a8 = a7 + 1; a9 = a8 + 1 + b1 = a9 + 1; b2 = b1 + 1; b3 = b2 + 1; b4 = b3 + 1; b5 = b4 + 1; b6 = b5 + 1; b7 = b6 + 1; b8 = b7 + 1; b9 = b8 + 1 + c = nil + @a.each { |e| c = b9 + e } if v.odd? + [a1, b9, c] + end + + # recursion: each level has its own locals + def rec(d, acc) + here = d * 10 + @a.each { |e| here += e } + inner = (d > 0) ? rec(d - 1, acc) : acc + [here, inner] + end + + # many calls a light frame makes: its locals in CLR variables until the scope is made + def light(v, make) + k = v + j = nil + @a.each { |e| j = (j || 0) + e + k } if make + [k, j] + end +end + +t('a local set on some calls is nil on the others') { + o = P.new + r = [] + N.times { |n| v = o.maybe(n.even?); r << v if n > N - 4 } + r +} +t('local_variables and defined? after reuse') { o = P.new; N.times { |n| o.maybe(n % 3 == 0) }; [o.maybe(false), o.maybe(true)] } +t('a binding taken in the middle keeps its own locals') { + o = P.new + bs = [] + N.times { |n| r = o.bind(n); bs << r if r.is_a?(Binding) } + bs.map { |b| [b.local_variable_get(:v), b.local_variable_get(:w), b.local_variables.sort] } +} +t('a binding written after later calls') { + o = P.new + b = nil + N.times { |n| r = o.bind(n); b = r if r.is_a?(Binding) && b.nil? } + b.local_variable_set(:w, :changed) + N.times { |n| o.bind(n + 1) } + [b.local_variable_get(:w), b.local_variable_get(:v)] +} +t('a Proc of the scope kept in the middle') { + o = P.new + N.times { |n| o.keep(n) } + o.kept.map(&:call) +} +t('an exception after the locals are set') { + o = P.new + errs = [] + s = 0 + N.times do |n| + begin + s += o.raising(n) + rescue ArgumentError => e + errs << e.message + end + end + [s, errs] +} +t('more locals than a kept tuple holds') { o = P.new; r = []; N.times { |n| r << o.many(n) if n > N - 3 }; r } +t('recursion') { o = P.new; r = nil; 500.times { |n| r = o.rec(4, n) }; r } +t('a light frame that makes its scope on some calls') { + o = P.new + r = [] + N.times { |n| v = o.light(n, n % 3 != 0); r << v if n > N - 4 } + r +} +t('threads calling one method') { + o = P.new + ths = Array.new(4) { |ti| Thread.new { s = 0; nils = 0; 2000.times { |n| x, = o.maybe((n + ti).even?); x.nil? ? nils += 1 : s += x }; [s, nils] } } + ths.map(&:value) +} +t('threads: bindings taken while others call') { + o = P.new + ths = Array.new(4) { |ti| Thread.new { bs = []; 3000.times { |n| r = o.bind(n * 4 + ti); bs << r if r.is_a?(Binding) }; bs.map { |b| [b.local_variable_get(:v), b.local_variable_get(:w)] } } } + ths.map(&:value).flatten(1).sort +} + +class Fib + def initialize; @a = [1, 2]; end + def gen(y, v) + loc = v + @a.each { |e| y << (loc + e) } + loc + end +end + +t('a call suspended in a fiber while the method runs again') { + f = Fib.new + N.times { |n| f.gen([], n) } + e = Enumerator.new { |y| f.gen(y, 100) } + first = e.next + mid = Array.new(50) { |n| f.gen([], n) }.last + second = e.next + [first, mid, second, (e.next rescue :done)] +} +t('eval in the method sees its own locals') { + k = Class.new { def m(v); z = v; [1].each { |e| z += e }; eval('z'); end }.new + r = nil + N.times { |n| r = k.m(n) } + r +} +t('TracePoint :return binding') { + o = P.new + N.times { |n| o.maybe(n.odd?) } + seen = [] + tp = TracePoint.new(:return) { |tpp| seen << tpp.binding.local_variable_get(:x) if tpp.method_id == :maybe } + tp.enable { o.maybe(true); o.maybe(false) } + [seen, o.maybe(false)] +} From fadeeda29fffa3d09b262bedc8c5a6a27be3675b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:24:27 +0000 Subject: [PATCH 194/439] sort_by of a Hash, a Range or an Enumerator sorts through the C# merge sort Enumerable#sort_by, and min_by(n)/max_by(n), of anything but a plain Array gathered [key, index, element] triples, sorted them with a Ruby comparison block and took the elements out again: {a: 1, b: 2, c: 3, d: 4}.sort_by { |k, v| -v } took 2158 ns against CRuby's 905. An Array already went to the C# stable merge sort (Array#sort_by, under the private alias __list_sort_by__) with the keys its #each walk made. Now every receiver does: the generic walk is unchanged (the |*values| block, the same block calls, Hash#each still the frame under sort_by in a backtrace), and the elements it gathered go to the same sort, which takes their keys by position. Equal keys keep their input order, as before. The merge compared the later key with the earlier one, so keys that do not compare were named the wrong way round: [1, 2].sort_by { |x| x == 1 ? 1 : "a" } said "comparison of String with 1 failed" where CRuby says "comparison of Integer with String failed" (its sort_by_cmp sends #<=> to the earlier key). It now compares the earlier with the later, which gives CRuby's messages for Arrays and for everything else, and CRuby's order for ties under a redefined Integer#<=>. Clock (Util/perf/ab.rb, four rounds, ns, CRuby / unchanged / this): hash_sort_by 905 / 2158 / 1753 (0.81), hash_sort_by_pair 852 / 2166 / 1757 (0.81), range_sort_by 681 / 1953 / 1547 (0.79), hash_max_by_n 776 / 2415 / 2024 (0.84); the Array rows sort_by, min_by_n and max_by_n within the noise (1.00, 1.01, 0.99). Three rows are new in core-small.rb. Util/sort-by-matrix.rb (new: Hashes with every block shape, a Range, a Struct, Enumerators, yields of several values, keys that do not compare, NaN, <=> answering a Float, a Bignum or a String, break/raise/throw, backtrace frames, redefined Array#sort_by, Array#<< and Integer#<=>, min_by(n)/max_by(n), the method's arity and parameters) prints what the unchanged build printed, but for the Integer#<=> line, now CRuby's, in the default mode, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. callable-parameters, caller, light-entry and hot-shapes print what they did in those modes. ruby/spec core/enumerable, hash, array, range, struct and enumerator: the same examples on both builds (three errors on both). IronRuby.Tests Backtrace_LibraryFrames1 and six more that use sort_by, min_by or max_by pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/Libraries/Extensions/IListOps.cs | 4 +- Src/StdLib/ironruby/ruby4.rb | 30 +++--- Util/bench/core-small.rb | 6 ++ Util/sort-by-matrix.rb | 151 +++++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 17 deletions(-) create mode 100644 Util/sort-by-matrix.rb diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index ac3f42196..952acab4d 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -3210,7 +3210,9 @@ private static void MergeSortByKey(object[]/*!*/ keys, object[]/*!*/ items, obje int left = start, right = start + half, target = start; int leftEnd = start + half, rightEnd = start + length; while (left < leftEnd && right < rightEnd) { - if (fixnumKeys ? (int)keys[right] < (int)keys[left] : Protocols.Compare(comparisonStorage, keys[right], keys[left]) < 0) { + // the earlier key is the receiver of #<=>, as in MRI's sort_by_cmp: keys that do not + // compare are named in that order ("comparison of Integer with String failed") + if (fixnumKeys ? (int)keys[left] > (int)keys[right] : Protocols.Compare(comparisonStorage, keys[left], keys[right]) > 0) { keyBuffer[target] = keys[right]; itemBuffer[target++] = items[right++]; } else { diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 19cd99ee7..31f38d28b 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -601,29 +601,27 @@ def __count_arg__(n) # Sorts by the block's key, keeping input order for equal keys so that # `min_by(n)` and `max_by(n)` agree with MRI on ties. # - # An Array whose #each is the built-in one is sorted by the C# Array#sort_by, taken under a - # private name when the prelude loads (a program's own Array#sort_by does not change - # min_by): it is a stable merge sort, so equal keys keep their input order as here. The - # Ruby comparison block below cost more than everything else for a short Array. + # Every receiver is sorted by the C# Array#sort_by, taken under a private name when the + # prelude loads (a program's own Array#sort_by does not change min_by): it is a stable merge + # sort, so equal keys keep their input order. An Array whose #each is the built-in one is + # walked with a one-value block (__list_sort_by_key__); anything else - a Hash, a Range, an + # Enumerator - with the generic `|*values|` block, and the elements it gathered go to the + # same sort, which takes their keys by position. Sorting [key, index, element] triples with + # a Ruby comparison block and taking the elements out again was more than half of + # {a: 1, b: 2, c: 3, d: 4}.sort_by { |k, v| -v }. def __sort_by_key__(block) return __list_sort_by_key__(&block) if __plain_list__? - decorated = [] - index = 0 + items = [] + keys = [] each do |*values| item = __enum_item__(values) - decorated << [values.size == 1 ? block.call(item) : __enum_yield__(values, &block), index, item] - index += 1 + keys << (values.size == 1 ? block.call(item) : __enum_yield__(values, &block)) + items << item # the block #each was given answers nil, as MRI's does, should #each keep it and call it nil end - decorated.sort do |a, b| - c = (a[0] <=> b[0]) - # the keys that will not compare are named, not the triples carrying them - if c.nil? - raise ArgumentError, "comparison of #{a[0].class} with #{::Comparable.__cmp_operand__(b[0])} failed" - end - c == 0 ? (a[1] <=> b[1]) : c - end.map { |triple| triple[2] } + i = -1 + items.__send__(:__list_sort_by__) { keys[i = i.succ] } end private :__sort_by_key__ diff --git a/Util/bench/core-small.rb b/Util/bench/core-small.rb index 9ec13f7e4..688282e25 100644 --- a/Util/bench/core-small.rb +++ b/Util/bench/core-small.rb @@ -99,6 +99,9 @@ def m83; @a.uniq { |x| x & 1 }.size; end def m84; @sp.strip.size; end def m85; @sp.lstrip.size; end def m86; @sp.rstrip.size; end + def m87; (1..4).sort_by { |x| -x }.size; end + def m88; @h.max_by(2) { |k, v| v }.size; end + def m89; @h.sort_by { |pair| pair[1] }.size; end end def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end # INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the @@ -203,3 +206,6 @@ def t(name, n) t("strip", N) { |n| i = 0; s = 0; while i < n; s += h.m84; i += 1; end; s } t("lstrip", N) { |n| i = 0; s = 0; while i < n; s += h.m85; i += 1; end; s } t("rstrip", N) { |n| i = 0; s = 0; while i < n; s += h.m86; i += 1; end; s } +t("range_sort_by", N) { |n| i = 0; s = 0; while i < n; s += h.m87; i += 1; end; s } +t("hash_max_by_n", N) { |n| i = 0; s = 0; while i < n; s += h.m88; i += 1; end; s } +t("hash_sort_by_pair", N) { |n| i = 0; s = 0; while i < n; s += h.m89; i += 1; end; s } diff --git a/Util/sort-by-matrix.rb b/Util/sort-by-matrix.rb new file mode 100644 index 000000000..f4e7f3720 --- /dev/null +++ b/Util/sort-by-matrix.rb @@ -0,0 +1,151 @@ +# Differential matrix for Enumerable#sort_by and the count forms of min_by and max_by on a receiver +# that is not a plain Array (a Hash, a Range, a Struct, an Enumerator, a class of its own that +# includes Enumerable), where the keys come from a walk with #each and the elements are sorted by +# them. Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/sort-by-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/sort-by-matrix.rb > /tmp/ir.txt 2>&1 +# diff /tmp/mri.txt /tmp/ir.txt + +def t(label) + print label.ljust(46), ' => ' + begin + puts yield.inspect + rescue Exception => e + puts "#{e.class}: #{e.message.sub(/0x\h+/, '0x')}" + end +end + +H = { a: 3, b: 1, c: 2, d: 1 } + +class Multi + include Enumerable + def each + yield 1, :x + yield 3 + yield + yield [2, :y] + yield 0, :z, :w + end +end + +class Pairs + include Enumerable + def initialize(*a) = @a = a + def each(&b) = @a.each(&b) +end + +class OddKey + attr_reader :v + def initialize(v) = @v = v + def <=>(o) = (v <=> o.v).to_f + def inspect = "K#{v}" +end + +class BigCmp + attr_reader :v + def initialize(v) = @v = v + def <=>(o) = (v <=> o.v) * 2**70 +end + +class StrCmp + def <=>(_) = "x" +end + +S = Struct.new(:a, :b, :c) + +# ---------------------------------------------------------------- 1. the forms +t('hash |k, v|') { H.sort_by { |k, v| -v } } +t('hash |pair|') { H.sort_by { |pair| pair[1] } } +t('hash |k|') { H.sort_by { |k| k.to_s } } +t('hash ties keep order') { H.sort_by { |_k, v| v } } +t('hash lambda (k, v)') { H.sort_by(&->(k, v) { v }) } +t('hash lambda (pair)') { H.sort_by(&->(pair) { pair[1] }) } +t('hash &:last') { H.sort_by(&:last) } +t('hash proc (*a)') { H.sort_by(&proc { |*a| a.inspect }) } +t('hash empty') { {}.sort_by { |k, v| v } } +t('hash one') { { z: 1 }.sort_by { |k, v| v } } +t('hash frozen') { H.dup.freeze.sort_by { |k, v| v } } +t('hash no block') { e = H.sort_by; [e.class, e.size, e.each { |k, v| v }] } +t('range') { (1..6).sort_by { |x| [x % 3, -x] } } +t('range endless, break') { (1..).sort_by { |x| break x if x > 3 } } +t('struct') { S.new(3, 1, 2).sort_by { |x| x } } +t('enumerator with index') { %w[b c a].each_with_index.sort_by { |s, i| s } } +t('enumerator with_index |pair|') { %w[b c a].each_with_index.sort_by { |pair| -pair[1] } } +t('several values per yield |*a|') { Multi.new.sort_by { |*a| a.size } } +t('several values per yield |a|') { Multi.new.sort_by { |a| a.inspect } } +t('several values per yield |a, b|') { Multi.new.sort_by { |a, b| b.to_s } } +t('own Enumerable') { Pairs.new(3, 1, 2).sort_by { |x| -x } } +t('own Enumerable, 40 elements') { Pairs.new(*(1..40).to_a.shuffle(random: Random.new(1))).sort_by { |x| x % 7 } } +t('a Set') { require 'set'; Set[3, 1, 2].sort_by { |x| x } } +t('the result is a new Array') { r = H.sort_by { |k, v| v }; [r.class, r.frozen?] } + +# ---------------------------------------------------------------- 2. the keys +t('keys that do not compare') { Pairs.new(1, 2).sort_by { |x| x == 1 ? 1 : "a" } } +t('keys that do not compare, 3') { Pairs.new(1, 2, 3).sort_by { |x| x == 2 ? :s : x } } +t('nil keys') { Pairs.new(1, 2).sort_by { nil } } +t('one nil key') { Pairs.new(1).sort_by { nil } } +t('Float keys, NaN') { Pairs.new(1, 2, 3).sort_by { |x| x == 2 ? Float::NAN : x.to_f } } +t('<=> answering a Float') { Pairs.new(3, 1, 2).sort_by { |x| OddKey.new(x) } } +t('<=> answering a Bignum') { Pairs.new(3, 1, 2).sort_by { |x| BigCmp.new(x) }.map(&:itself) } +t('<=> answering a String') { Pairs.new(3, 1).sort_by { |x| StrCmp.new } } +t('Array keys') { H.sort_by { |k, v| [v, k] } } +t('String keys') { H.sort_by { |k, v| k.to_s * v } } +t('mixed Integer and Float keys') { Pairs.new(1, 2, 3, 4).sort_by { |x| x.odd? ? x : x - 0.5 } } +t('Bignum keys') { Pairs.new(1, 2, 3).sort_by { |x| -x * 2**80 } } + +# ---------------------------------------------------------------- 3. the block +t('break') { H.sort_by { |k, v| break :out if v == 1 } } +t('next') { H.sort_by { |k, v| next -v } } +t('raise') { H.sort_by { |k, v| raise "boom #{k}" } } +t('throw') { catch(:t) { H.sort_by { |k, v| throw :t, k } } } +t('the block sees the walk in order') { seen = []; Pairs.new(3, 1, 2).sort_by { |x| seen << x; x }; seen } +t('the hash grows under the block') { h = { a: 1 }; begin; h.sort_by { |k, v| h[:"x#{v}"] = v + 1; v }; rescue => e; e.class; end } +t('backtrace frames') do + H.sort_by { |k, v| raise "x" } +rescue => e + e.backtrace_locations.first(4).map(&:label) +end +t('backtrace frames, own Enumerable') do + Pairs.new(1, 2).sort_by { raise "x" } +rescue => e + e.backtrace_locations.first(4).map(&:label) +end +t('a redefined Array#sort_by does not count') do + class Array; alias __saved_sort_by__ sort_by; def sort_by = :redefined; end + begin + [H.sort_by { |k, v| v }, Pairs.new(2, 1).sort_by { |x| x }, H.min_by(2) { |k, v| v }] + ensure + class Array; alias sort_by __saved_sort_by__; remove_method :__saved_sort_by__; end + end +end +t('a redefined Array#<< does not count') do + class Array; alias __saved_push__ <<; def <<(x) = raise("no"); end + begin + H.sort_by { |k, v| v } + ensure + class Array; alias << __saved_push__; remove_method :__saved_push__; end + end +end +t('a redefined Integer#<=>') do + class Integer; alias __saved_cmp__ <=>; def <=>(o) = -(__saved_cmp__(o) || 0); end + begin + [H.sort_by { |k, v| v }, Pairs.new(1, 3, 2).sort_by { |x| x }] + ensure + class Integer; alias <=> __saved_cmp__; remove_method :__saved_cmp__; end + end +end + +# ---------------------------------------------------------------- 4. min_by(n), max_by(n) +t('hash min_by(2)') { H.min_by(2) { |k, v| v } } +t('hash max_by(2)') { H.max_by(2) { |k, v| v } } +t('hash min_by(0), max_by(9)') { [H.min_by(0) { |k, v| v }, H.max_by(9) { |k, v| v }] } +t('range min_by(2)') { (1..5).min_by(2) { |x| -x } } +t('own max_by(2), ties') { Pairs.new(1, 2, 3, 4).max_by(2) { |x| x % 2 } } +t('min_by(-1)') { H.min_by(-1) { |k, v| v } } +t('max_by(2) keys that do not compare') { Pairs.new(1, 2).max_by(2) { |x| x == 1 ? 1 : "a" } } + +# ---------------------------------------------------------------- 5. the method +m = Enumerable.instance_method(:sort_by) +t('arity, parameters, owner') { [m.arity, m.parameters, m.owner, H.method(:sort_by).owner] } +t('min_by arity, parameters') { [Enumerable.instance_method(:min_by).arity, Enumerable.instance_method(:min_by).parameters] } From ed49c523bd17a3e6e2b61e65e4dccf55a61620e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:24:42 +0000 Subject: [PATCH 195/439] Ledger: perf/hsortby landed (not gated); gap 15: the 2026-11-27 survey Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 30a4c214e..a5d3a0018 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1036,6 +1036,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has in `Kernel#__ir_string__`, which asks whether #respond_to? is Kernel's (`method(:respond_to?).owner`) and calls #to_s through `bind_call`; CRuby decides that in C (rb_check_funcall). Probably needs a C# helper, which is /perf-step's, not /perf-core's. + `Hash#sort_by` (2.4 -> 1.9), `Range#sort_by` (2.9 -> 2.3) and `Hash#max_by(2)` (3.1 -> 2.6) + are done too (perf/hsortby, see Landed). Survey of 2026-11-27 (one round): the Ruby rows + above 4x CRuby are `Array#dig` into a Hash (9.2), `String(nil)`/`String(5)` (8.8, 6.7), + `Array#sum` (8.0) and with a block over Floats (7.1) or Integers (4.4); `Array#min` (6.0) + and `Array#take` (4.1, Enumerable's C# take: CRuby's is Array's own) are C#, /perf-step's. `Array#to_h { }` is done too (4.7 -> 2.3), and `min_by`/`max_by` (3.1 -> 2.2), and their count form (`min_by(2)` 3.8 -> 2.9 after the review fix below). Open beside speed: `min_by(n)`'s tie order is input order, MRI's nmin selection orders ties its own way. `take_while`/`drop_while` done (2.6 -> 2.2, @@ -1791,6 +1796,29 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/hsortby (/perf-core, 2026-11-27, on 5472a50) - `sort_by`, `min_by(n)` and + `max_by(n)` of a Hash, a Range or an Enumerator through the C# merge sort** (the gap 15 survey's + largest Ruby row in nanoseconds over CRuby: `Hash#sort_by` +1250 ns). The generic walk made + [key, index, element] triples and sorted them with a Ruby comparison block; now the elements it + gathers go to `__list_sort_by__` (the C# stable merge sort, as an Array's already did) with + their keys by position. The walk itself is unchanged, so are block calls and the `Hash#each` + frame. The merge now sends #<=> to the earlier key, as MRI's sort_by_cmp: keys that do not + compare are named in CRuby's order, for Arrays too ("comparison of Integer with String + failed"; it said "String with 1"). + - Clock (`ab.rb`, four rounds, ns, CRuby / unchanged / this): `hash_sort_by` 905 / 2158 / + 1753 (0.81), `hash_sort_by_pair` 852 / 2166 / 1757 (0.81), `range_sort_by` 681 / 1953 / + 1547 (0.79), `hash_max_by_n` 776 / 2415 / 2024 (0.84); `sort_by`, `min_by_n`, `max_by_n` + of an Array 1.00, 1.01, 0.99 (noise). + - `Util/sort-by-matrix.rb` (new) prints the unchanged build's output but for one line now + CRuby's (ties under a redefined Integer#<=>), in five modes and R2R; callable-parameters, + caller, light-entry, hot-shapes unchanged in four modes; ruby/spec core/enumerable, hash, + array, range, struct, enumerator the same examples on both builds; IronRuby.Tests + `Backtrace_LibraryFrames1` and six more pass. Not gated. + - Left from CRuby (as before): tie order (CRuby's sort_by is not stable; this is), the NaN + key's message, and a redefined `Array#<<` reaching the walk. Next lever: the walk - a + `|*values|` block and `__enum_item__` per element; a Hash whose #each is the built-in one + could be walked with a one-value block, as `__plain_list__?` does for an Array. + - **perf/evalboxes (/perf-step, 2026-11-27, on 4320d4a + perf/lexical 779d87c) - an eval'd text with regexp or range literals shares its compiled code, the literals' objects kept per eval (`IR_EVAL_LITERALS`, gap 31)** - instructions only, not gated. The commonest refusal left From f7ae738be62a906c203ffccb17a1c2a131d3baef Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:28:57 +0000 Subject: [PATCH 196/439] Pass a trailing splat uncopied when the block argument is a variable or literal A call with a block argument (`f(*a, &b)', `f(x, *a, &b)', `...', `(*, &)') evaluated its receiver and arguments into temporaries before the block argument and copied a trailing splat into a fresh array there: an allocation and a copy on every call of every forwarder. CRuby 4.0 copies only when the block argument could run code before its #to_proc (`splatarray true' for `&G.new(a)', `&method(:m)'); for a variable, a constant or a literal it passes the list itself (`splatarray false', pm_setup_args_dup_rest_p), and the call expands it after #to_proc. That is observable: with a local `g' whose #to_proc appends to `a', `f(*a, &g)' gets the new item and `two(*a, &g)' raises ArgumentError (given 3, expected 2). IronRuby copied always, so it differed there. MethodCall.TransformRead now keeps the list (after #to_a) for such a block argument (IsSideEffectFree), not marked fresh, so a rest parameter of the callee copies it as for any other splat. IR_SPLAT_BY_REFERENCE=0 restores the copy. Checked: new Util/splat-blockarg-matrix.rb same as CRuby by default, with IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR and -X:NoJITCalls; the splat-pass, kwrest-call, block-pass, anon-forward, light-entry, hot-shapes, jit and jit-calls matrices unchanged in every mode; language/send and def specs as before; IronRuby.Tests passed. By clock (ab.rb, Release): `(*a, &b)' and `(...)' forwarders into a fixed-arity callee 104 -> 75 ns, delegate-shapes' forwarders 0.67-0.79 of before, nothing slower. Util/perf/LEDGER.md has the numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Compiler/Ast/Expressions/MethodCall.cs | 45 +++++++- Util/perf/LEDGER.md | 43 +++++++ Util/splat-blockarg-matrix.rb | 106 ++++++++++++++++++ 3 files changed, 193 insertions(+), 1 deletion(-) create mode 100644 Util/splat-blockarg-matrix.rb diff --git a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs index 2a2ce3ef3..b6e52098b 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs @@ -31,6 +31,13 @@ namespace IronRuby.Compiler.Ast { /// target.method_id(args) ///
public partial class MethodCall : CallExpression { + /// + /// IR_SPLAT_BY_REFERENCE=0: a call with a block argument copies its trailing splat before the block argument is evaluated, + /// as it used to (see TransformRead). CRuby 4.0 passes the list itself when the block argument is a variable, a constant + /// or a literal (IsSideEffectFree). + /// + internal static readonly bool SplatByReference = System.Environment.GetEnvironmentVariable("IR_SPLAT_BY_REFERENCE") != "0"; + private string/*!*/ _methodName; private readonly Expression _target; @@ -183,7 +190,21 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { assignments.Add(Ast.Assign(temp, argument)); ordered.Add(temp); } - if (scratch.SplattedArgument != null) { + if (scratch.SplattedArgument != null && !scratch.SplattedArgumentIsFresh && SplatByReference && + IsSideEffectFree(((BlockReference)block).Expression)) { + // A trailing splat of a list the arguments did not make (`f(*a, &b)', `f(x, *a, &b)', and `...'), with a block + // argument that cannot run code before its #to_proc (a variable, a constant, a literal: IsSideEffectFree): CRuby 4.0 + // passes the list itself there (`splatarray false', prism_compile.c's pm_setup_args_dup_rest_p), which the call + // expands once the block argument has been converted - a #to_proc that changes `a' shows in the arguments + // (`f(*a, &o)' with `o.to_proc' appending to `a': the callee gets the item). Any other block argument + // (`f(*a, &G.new(a))', `&method(:m)') gets the copy below, as in CRuby, where neither it nor its #to_proc sees `a' change. + // So the list (after its #to_a, which comes before the block argument's #to_proc) is kept here, not copied, and + // is not fresh: a rest parameter of the callee copies it as for any splat. IR_SPLAT_BY_REFERENCE=0 copies it. + var temp = gen.CurrentScope.DefineHiddenVariable("#splat", typeof(System.Collections.IList)); + assignments.Add(Ast.Assign(temp, AstUtils.Convert(scratch.SplattedArgument, typeof(System.Collections.IList)))); + ordered.SplattedArgument = temp; + ordered.SplattedArgumentIsFresh = false; + } else if (scratch.SplattedArgument != null) { // The splat is expanded into an array here, before the block argument is evaluated: a copy, which nothing else // refers to, and so fresh for the call (RubyCallFlags.HasFreshSplat): a rest parameter of the callee takes it // rather than copying it again. A splat that is fresh already - an array the arguments made, or a rest parameter @@ -232,6 +253,28 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { return result; } + /// + /// A block argument whose evaluation runs no Ruby code, so that a splatted list cannot change before its #to_proc: + /// CRuby 4.0 passes such a call's trailing splat uncopied (prism_compile.c, pm_setup_args_dup_rest_p, which also counts + /// a few more shapes, such as `[]', that no #to_proc could tell apart). + /// + private static bool IsSideEffectFree(Expression/*!*/ expression) { + switch (expression) { + case LocalVariable _: + case InstanceVariable _: + case GlobalVariable _: + case ClassVariable _: + case SelfReference _: + case Literal _: + case SymbolLiteral _: + return true; + case ConstantVariable constant: + return constant.Qualifier == null || IsSideEffectFree(constant.Qualifier); + default: + return false; + } + } + internal static MSA.Expression/*!*/ MakeCallWithBlockRetryable(AstGenerator/*!*/ gen, MSA.Expression/*!*/ invoke, MSA.Expression blockArgVariable, MSA.Expression transformedBlock, bool isBlockDefinition) { return MakeCallWithBlockRetryable(gen, invoke, blockArgVariable, transformedBlock, isBlockDefinition, null); diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index ec795cece..f8d041b72 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1779,6 +1779,49 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/splatpos (/perf-step, 2026-11-27) - `f(*a, &b)' passes `a' itself, not a copy, when + `b' is a variable, a constant or a literal** (switch `IR_SPLAT_BY_REFERENCE`, on unless `=0`). + Built on 288cc13 (claude/perf-lsite, which has 4320d4a). + - **What the round asked, and where the cost was.** A splat into a fixed-arity Ruby callee + already costs what the call written out does (`two(*a)` 46 ns, `two(a[0], a[1])` 51, + CRuby 40 and 40). The slow ones were the splats that also pass a block: `rest_blk` (`(*a, + &b) = two(*a, &b)`) 103, `dots` 104, `lead_dots` 104 (CRuby 82, 44, 90). A call with a + block argument evaluates its receiver and arguments into temporaries first (the block is + computed first for a literal block's retry), and a trailing splat was copied there into a + fresh RubyArray: an allocation and a copy per call, for every forwarder. + - **What CRuby 4.0 does.** `splatarray false` - the list itself, expanded by the call after + the block argument's #to_proc - when the block argument is a variable, a constant or a + literal (prism_compile.c, pm_setup_args_dup_rest_p; `--dump=insns`); `splatarray true`, a + copy made before the block argument, for anything else (`&G.new(a)`, `&method(:m)`, + `&(g.x)`). So it is observable: with `g = o` whose #to_proc appends to `a`, `f(*a, &g)` + gets the new item and `two(*a, &g)` raises `given 3, expected 2`; `f(*a, &Grow.new(a))` + does not. IronRuby copied always, which was wrong for the first kind. + - **What changed.** MethodCall.TransformRead keeps the list (after #to_a) in the temporary, + not fresh, when the block argument is a local, instance, global or class variable, self, + a literal, a symbol or an unqualified (or constant-qualified) constant + (MethodCall.IsSideEffectFree; a subset of CRuby's set - the shapes it leaves out, `[]`, + `{}`, `1..2`, have no #to_proc that could change a list). A rest parameter of the callee + copies it as for any splat. `...` and `(*, &)` forward a local, so they take it. + - **Checks.** New `Util/splat-blockarg-matrix.rb` (order of receiver/args/to_a/to_proc, the + list growing and shrinking under to_proc with `&local`, `&@ivar`, `&$gvar`, `&CONST` and + with a call, length mismatches, to_a and nil splats, optional/keyword/block callees, + ruby2_keywords, frozen list, forwarders, callee redefined after bind, method_missing, + break, super): same as CRuby in default, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls`; `=0` shows the old difference. splat-pass, kwrest-call, block-pass, + anon-forward, light-entry, hot-shapes, jit, jit-calls matrices same as CRuby in every mode + and with the switch off; forward-rest's two `binding` lines differ from CRuby the same way + on the unchanged build. language/send and def specs as before (send's one error is the + known `into`/`to` wording). IronRuby.Tests in full: PASSED. + - **Clock** (`ab.rb -r 6`, Release net10.0, ns; CRuby / off / on): splat-shapes `dots` 44.0 / + 103.8 / 75.6, `rest_blk` 82.4 / 103.3 / 74.9, `lead_dots` 90.0 / 103.7 / 71.7, the rest + unchanged (`splat` 39.9 / 47.9 / 46.0, `rest_kw_blk` 117.7 / 187.8 / 182.9, `anon` 89.7 / + 259.1 / 259.5). forward-shapes `rest` 116 / 78, `rest_blk` 102 / 68, `dots` 99 / 76, `anon` + 98 / 60 (off / on; wide spreads). delegate-shapes `dc_two` 137 / 100, `fw_two` 120 / 80, + `fw_blk` 156 / 120, `mm_two` 238 / 198, `sd_two` 375 / 334; `direct_*` unchanged. + - **Left.** `anon` of splat-shapes (`(*, **, &)`, 259 against CRuby's 90) and `rest_kw_blk` + pass a keyword splat too and go another way (KeywordSplatMerge); `f(*a, k: g, &g)` still + copies where CRuby does not (the splat is not trailing there; pre-existing). + - **perf/rescuelight (/perf-frame, 2026-11-27) - `$!` left alone in a begin/rescue/ensure that raises nothing** (switch `IR_LAZY_ERRINFO`, on unless `=0`) - timed, not gated. Built on 4320d4a with claude/perf-lsite merged (d83116b). diff --git a/Util/splat-blockarg-matrix.rb b/Util/splat-blockarg-matrix.rb new file mode 100644 index 000000000..e6d122ee6 --- /dev/null +++ b/Util/splat-blockarg-matrix.rb @@ -0,0 +1,106 @@ +# Differential matrix for a call that splats and passes a block argument (`f(*a, &b)', `f(x, *a, &b)', `...'): the +# order CRuby 4.0 evaluates them in, and when it passes a trailing splat's list itself, expanded after the block +# argument's #to_proc - a block argument that is a variable, a constant or a literal - and when it copies it first - any +# other block argument, a method call say (MethodCall.TransformRead; IR_SPLAT_BY_REFERENCE=0 always copies, as IronRuby +# used to). +# +# ruby Util/splat-blockarg-matrix.rb > mri.txt +# ./ir.sh Util/splat-blockarg-matrix.rb > on.txt +# IR_LIGHT_FRAMES=0 ./ir.sh Util/splat-blockarg-matrix.rb > scoped.txt +# diff mri.txt on.txt && diff mri.txt scoped.txt +# +# Each probe runs 3000 times (interpreted, then compiled) and prints every distinct answer once. + +N = 3000 + +def t(label) + print label.ljust(56), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def f(*x, &b) = [x, b && b.call] +def two(a, b) = [a, b] +def opt(a, b = :d) = [a, b] +def kw(a, b, k: :k) = [a, b, k] +def blk(a, b, &k) = [a, b, k && k.call] +def keeps(*x) = (x << :kept; x) + +class Grow; def initialize(a) = @a = a; def to_proc = (a = @a; a << 3; proc { :g }); end +class Shrink; def initialize(a) = @a = a; def to_proc = (a = @a; a.pop; proc { :s }); end +class ToA; def initialize(log) = @log = log; def to_a = (@log << :to_a; [7, 8]); end +class LogProc; def initialize(log) = @log = log; def to_proc = (@log << :to_proc; proc { :p }); end + +# ---------------------------------------------------------------- 1. order, and the list passed itself +t("receiver, args, to_a, to_proc order") do |i| + log = [] + r = send(:f, (log << :arg; 1), *ToA.new(log), &LogProc.new(log)) + [r, log] +end +t("&local: to_proc grows the list, callee sees it") { |i| a = [1, 2]; g = Grow.new(a); [f(*a, &g), a] } +t("&local, a leading argument") { |i| a = [1, 2]; g = Grow.new(a); f(0, *a, &g) } +t("&local, an item after the splat") { |i| a = [1, 2]; g = Grow.new(a); f(*a, 9, &g) } +t("&local shrinks it") { |i| a = [1, 2, 3]; g = Shrink.new(a); f(*a, &g) } +t("&@ivar, fixed-arity callee: grown list too long") { |i| a = [1, 2]; @g = Grow.new(a); (two(*a, &@g) rescue [$!.class, $!.message]) } +t("&$gvar, fixed-arity callee: shrunk list too short") { |i| a = [1, 2]; $g = Shrink.new(a); (two(*a, &$g) rescue [$!.class, $!.message]) } +GROW = []; class << GROW; def to_proc = (self << 3; proc { :c }); end +t("&CONST that is the splatted list") { |i| GROW.clear.push(1, 2); f(*GROW, &GROW) } +t("&(expr): a call copies; to_proc grows it unseen") { |i| a = [1, 2]; [f(*a, &Grow.new(a)), a] } +t("to_proc grows it, with a leading argument") { |i| a = [1, 2]; f(0, *a, &Grow.new(a)) } +t("to_proc grows it, an item after the splat") { |i| a = [1, 2]; f(*a, 9, &Grow.new(a)) } +t("to_proc shrinks it") { |i| a = [1, 2, 3]; f(*a, &Shrink.new(a)) } +t("fixed-arity callee: grown list is too long") { |i| a = [1, 2]; (two(*a, &Grow.new(a)) rescue [$!.class, $!.message]) } +t("fixed-arity callee: shrunk list is too short") { |i| a = [1, 2]; (two(*a, &Shrink.new(a)) rescue [$!.class, $!.message]) } +t("a Proc block argument, no to_proc") { |i| a = [1, 2]; pr = proc { :pr }; [f(*a, &pr), a] } +t("&nil") { |i| a = [1, 2]; f(*a, &nil) } +t("&:sym") { |i| a = ["x", "y"]; f(*a, &:upcase) } +t("&method(:m)") { |i| a = [1, 2]; f(*a, &method(:keeps)) } + +# ---------------------------------------------------------------- 2. what the callee gets +t("callee's rest is a copy: mutating it leaves the list") { |i| a = [1, 2]; pr = proc { }; [keeps(*a, &pr), a] } +t("length that does not match") { |i| a = [1, 2, 3]; (two(*a, &nil) rescue [$!.class, $!.message]) } +t("list changing length between calls") { |i| a = (i.even? ? [1, 2] : [1]); (two(*a, &nil) rescue [$!.class, $!.message]) } +t("non-Array splat: to_a") { |i| (two(*ToA.new([]), &nil)) } +t("nil splat") { |i| (f(*nil, &nil)) } +t("optional-parameter callee") { |i| a = (i.even? ? [1] : [1, 2]); opt(*a, &nil) } +t("keyword callee") { |i| a = [1, 2]; kw(*a, &nil) } +t("block callee, block given") { |i| a = [1, 2]; pr = proc { :given }; blk(*a, &pr) } +t("ruby2_keywords hash as last element") do |i| + h = Hash.ruby2_keywords_hash({k: :r2k}) + a = [1, 2, h] + kw(*a, &nil) +end +t("frozen list") { |i| a = [1, 2].freeze; two(*a, &nil) } + +# ---------------------------------------------------------------- 3. forwarders +def fwd_rest_blk(*a, &b) = f(*a, &b) +def fwd_dots(...) = f(...) +def fwd_lead(x, ...) = f(x, ...) +def fwd_anon(*, &) = f(*, &) +def fwd_two(...) = fwd_dots(...) +t("(*a, &b) forward, with and without a block") { |i| i.even? ? fwd_rest_blk(1, 2) { :b } : fwd_rest_blk(1, 2) } +t("(...) forward") { |i| i.even? ? fwd_dots(1, 2) { :b } : fwd_dots(1, 2) } +t("(x, ...) forward") { |i| fwd_lead(1, 2) } +t("(*, &) forward") { |i| fwd_anon(1, 2) { :anon } } +t("two layers of ...") { |i| fwd_two(1, 2) { :two } } + +class Redef; def m(a, b) = :first; def call(a) = m(*a, &nil); end +t("callee redefined after the site bound") do |i| + o = Redef.new + Redef.class_eval { def m(a, b) = :second } if i == 1500 + o.call([1, 2]) +end +class MM; def method_missing(n, *a, &b) = [n, a, b && b.call]; def respond_to_missing?(*) = true; def go(a) = ghost(*a, &proc { :mm }); end +t("method_missing callee") { |i| MM.new.go([1, 2]) } +t("break through a passed block") { |i| a = [1, 2]; [1].each { |_| blk(*a, &proc { break :broke }) } } +class Sup; def m(a, b, &k) = [a, b, k && k.call]; end +class Sub < Sup; def m(*a, &k) = super(*a, &k); end +t("super(*a, &k)") { |i| Sub.new.m(1, 2) { :sup } } From 885c67a1474e2b322474da2bbf47567f25749606 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:33:34 +0000 Subject: [PATCH 197/439] StringScanner: match from inside a character as MRI does, on the rest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Without fixed_anchor, MRI's strscan matches the rest of the subject as a string of its own, so from a scan pointer inside a character (#pos= or a byte-wise scan put it there) the split character's bytes are characters of their own: StringScanner.new("héllo").tap { _1.pos = 2 } .scan(/\S+/) is "\xA9llo". IronRuby mapped the byte position to an index into the whole subject's characters, which landed on the wrong one, and answered nil (or matched later than CRuby, as exist?(/ /) did). Such a match now runs on the rest cut out as its own string, which RubyRegex.MatchWindow may match although it is broken (allowBroken, for this one caller); a subject broken as a whole still raises, as in MRI. The check costs nothing where the UTF-8 map answers it; elsewhere it looks back to the last ASCII byte (EUC encodings) or to the start (an EUC-JP scan of 26 KB timed as before). Util/string-search-matrix.rb: 115 lines differing from CRuby 4.0 -> 90. Left: /./ and \A. do not match a lone split byte (the translator's '.' excludes the lone surrogate an invalid byte decodes to), which is the regexp translator's, not the scanner's. library/stringscanner specs pass; StringScanner_InsideCharacter1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 41 +++++++++++++++ Src/Libraries/StringScanner/StringScanner.cs | 52 ++++++++++++++++++++ Src/Ruby/Builtins/RubyRegex.cs | 19 +++++-- 4 files changed, 108 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 23e3304e0..30088d835 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -214,6 +214,7 @@ public Tests(Driver/*!*/ driver) { Regex_PropertyEncoding1, Regex_BinaryCtype1, Regex_Latin1Ctype1, + StringScanner_InsideCharacter1, Regex_InspectResultEncoding1, Regex_EscapedByteEncoding1, Regex_EscapedByteEncoding2, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 4dc5c078f..29e9d4c30 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -895,6 +895,47 @@ def t(l) "); } + /// + /// From a scan pointer inside a character of a valid subject, MRI's strscan matches the rest as a + /// string of its own: the split character's bytes are characters there ("\xA9llo"). A subject that + /// is broken as a whole still raises. + /// + public void StringScanner_InsideCharacter1() { + TestOutput(@" +require 'strscan' +s = StringScanner.new(""h\u00e9llo w, x"") +s.pos = 2 +p s.scan(/\S+/), s.pos, s.matched, s.pre_match.bytes, s[0] +s.pos = 2 +p s.skip(/\s+/), s.exist?(/ /), s.match?(/\w+/), s.scan_until(/,/), s.pos +e = StringScanner.new(""\xA4\xA2a b"".dup.force_encoding(""EUC-JP"")) +e.pos = 1 +p e.scan(/\S+/), e.pos, e.rest +e.pos = 1 +p e.scan_until(/ /), e.charpos +b = StringScanner.new(""ab\xE9c d"".dup.force_encoding(""UTF-8"")) +b.pos = 2 +p((b.scan(/\S+/) rescue $!)) +", @" +""\xA9llo"" +6 +""\xA9llo"" +[104, 195] +""\xA9llo"" +nil +5 +nil +""\xA9llo w,"" +9 +""\xA2a"" +3 +"" b"" +""\xA2a "" +3 +# +"); + } + /// /// A BINARY subject is matched with Onigmo's ASCII-8BIT ctype table (MRI's /// rb_reg_prepare_enc compiles a regexp that is not fixed-encoding for the subject's diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index b9896a691..066962b6b 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -458,6 +458,13 @@ private bool MatchRegex(RubyRegex/*!*/ pattern, bool anchored, bool advance, boo if (mapped >= 0) { return mapped != 0; } + if (!_fixedAnchor) { + return MatchRest(pattern, anchored, advance); + } + } else if (!_fixedAnchor && !_scanString.DetectSingleByteCharacters() && !_scanString.ContainsInvalidCharacters() && + IsInsideCharacter()) { + // (a broken subject raises in the match below, as it does in MRI) + return MatchRest(pattern, anchored, advance); } if (lazyGroups && !_fixedAnchor) { @@ -507,6 +514,51 @@ private bool MatchRegex(RubyRegex/*!*/ pattern, bool anchored, bool advance, boo return Matched(start, matchBase + matchEnd, advance); } + /// + /// Whether the scan pointer is inside a character of a valid subject with multibyte characters + /// and no UTF-8 map (EUC-JP, say): the bytes before it, from a point known to start a + /// character, end in an incomplete one. In the EUC encodings, as in UTF-8, a byte below 0x80 + /// is a character of its own, so the bytes after the last such byte are enough; in the others + /// (Shift_JIS, Big5, whose second bytes can be ASCII) only the start of the subject is known. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private bool IsInsideCharacter() { + if (_position <= 0 || _position >= ByteLength) { + return false; + } + var encoding = _scanString.Encoding; + int from = 0; + if (encoding == RubyEncoding.UTF8 || encoding.Name.StartsWith("EUC", StringComparison.OrdinalIgnoreCase)) { + from = _position; + while (from > 0 && _scanString.GetByte(from - 1) >= 0x80) { + from--; + } + if (from == _position) { + return false; + } + } + return MutableString.CreateBinary(_scanString.GetBinarySlice(from, _position - from), encoding).ContainsInvalidCharacters(); + } + + /// + /// A match from a scan pointer inside a character (#pos= set it there, or a byte-wise scan + /// left it there). MRI's strscan matches the rest of the subject as a string of its own, so + /// the bytes of the split character there are broken characters, one each, which /./, /\S+/ + /// and \A match; the subject's own characters say nothing about them. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private bool MatchRest(RubyRegex/*!*/ pattern, bool anchored, bool advance) { + MutableString rest = MutableString.CreateBinary(_scanString.GetBinarySlice(_position, ByteLength - _position), _scanString.Encoding); + MatchData match = pattern.MatchWindow(rest, 0, anchored, false, true); + int matchStart, matchEnd; + if (match == null || !match.TryGetGroupByteOffsets(0, out matchStart, out matchEnd) || (anchored && matchStart != 0)) { + return false; + } + _match = match; + _matchBase = _position; + return Matched(_position + matchStart, _position + matchEnd, advance); + } + private bool MatchLiteral(MutableString/*!*/ pattern, bool anchored, bool advance) { ClearMatch(); diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 0fa8c26ed..c700f59a1 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -346,14 +346,14 @@ object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers /// This is a regexp-versus-string rule, distinct from the string-versus-string /// compatibility MutableString.RequireCompatibleEncoding applies. /// - private void RequireMatchableEncoding(MutableString/*!*/ input) { + private void RequireMatchableEncoding(MutableString/*!*/ input, bool allowBroken = false) { if ((_flags & LiteralPatternFlag) != 0) { // a String pattern (#sub, #gsub, #scan): MRI's rb_enc_check, receiver first input.RequireCompatibleEncoding(_pattern); return; } - if (input.ContainsInvalidCharacters()) { + if (!allowBroken && input.ContainsInvalidCharacters()) { throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", input.Encoding.Name); } @@ -432,10 +432,10 @@ private bool IsRecompiledCached(RubyEncoding/*!*/ encoding) { /// regex it gets back (MatchWindow, which derives an anchored one from it), so that only /// the regex that actually runs works its way up to being compiled. ///
- private Regex/*!*/ Transform(MutableString/*!*/ input, out string strInput, out bool astral, bool countUse) { + private Regex/*!*/ Transform(MutableString/*!*/ input, out string strInput, out bool astral, bool countUse, bool allowBroken = false) { ContractUtils.RequiresNotNull(input, "input"); - RequireMatchableEncoding(input); + RequireMatchableEncoding(input, allowBroken); input.PrepareForCharacterRead(); strInput = input.ConvertToString(); // O(1): matching has just validated the input, which works the flags out @@ -1672,12 +1672,21 @@ public MatchData Match(MutableString/*!*/ input, int start, bool freezeInput) { /// Start is a CLR index into the input's characters. ///
public MatchData MatchWindow(MutableString/*!*/ input, int start, bool anchored, bool freezeInput) { + return MatchWindow(input, start, anchored, freezeInput, false); + } + + /// + /// Match a string with broken characters rather than raise: StringScanner's rest from a scan + /// pointer inside a character of a subject that is itself valid, which MRI's Onigmo matches + /// from there with the split character's bytes as characters of their own. + /// + public MatchData MatchWindow(MutableString/*!*/ input, int start, bool anchored, bool freezeInput, bool allowBroken) { // Convert the whole input, not the part from "start" on: the conversion is the // expensive half of a match on a long subject, and converting only the tail means // paying for the tail again at every position the scanner stops at. string str; bool astral; - Regex regex = Transform(input, out str, out astral, !anchored); + Regex regex = Transform(input, out str, out astral, !anchored, allowBroken); if (start < 0) { start += str.Length; From 1cae85ae8259c987afe2f9edbca0058313b5040b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:34:21 +0000 Subject: [PATCH 198/439] StringScanner: a subject shorter than the scan pointer answers as MRI's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the subject is replaced by a shorter string (or cut) while the scan pointer is beyond its new end, MRI's strscan_do_scan clears the match and answers nil (S_RESTLEN < 0), #rest is "", #bol? is nil, and #charpos counts the bytes past the end as characters (rb_enc_strlen runs on). IronRuby raised ArgumentError ("Invalid argument value (Parameter 'count')") from the first scan, and IndexOutOfRangeException from #bol?. Util/string-search-matrix.rb: the four "replace('ö o') between scans" rows now agree with CRuby 4.0. library/stringscanner specs pass; StringScanner_ShorterSubject1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 19 +++++++++++++++++++ Src/Libraries/StringScanner/StringScanner.cs | 18 +++++++++++++++++- 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 30088d835..505e7f112 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -215,6 +215,7 @@ public Tests(Driver/*!*/ driver) { Regex_BinaryCtype1, Regex_Latin1Ctype1, StringScanner_InsideCharacter1, + StringScanner_ShorterSubject1, Regex_InspectResultEncoding1, Regex_EscapedByteEncoding1, Regex_EscapedByteEncoding2, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 29e9d4c30..2d3b5eeb9 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -936,6 +936,25 @@ p e.scan_until(/ /), e.charpos "); } + /// + /// A subject replaced by a shorter one under the scan pointer: MRI's scans answer nil, #rest is + /// empty, #bol? is nil and #charpos counts the bytes beyond the end as characters. + /// + public void StringScanner_ShorterSubject1() { + TestOutput(@" +require 'strscan' +s = +""hello world"" +ss = StringScanner.new(s) +ss.scan(/\S+/); ss.skip(/\s+/) +s.replace(""a b"") +p [ss.scan(/\S+/), ss[0], ss.pos, ss.matched, ss.pre_match, ss.rest, ss.charpos, ss.getch, ss.bol?, ss.eos?] +p [ss.peek(2), ss.rest_size, ss.check(/x/), ss.skip(""a""), ss.exist?(/a/), ss.rest?, ss.inspect] +", @" +[nil, nil, 6, nil, nil, """", 6, nil, nil, true] +["""", 0, nil, nil, nil, false, ""#""] +"); + } + /// /// A BINARY subject is matched with Onigmo's ASCII-8BIT ctype table (MRI's /// rb_reg_prepare_enc compiles a regexp that is not fixed-encoding for the subject's diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index 066962b6b..dde51663d 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -391,6 +391,12 @@ private bool Match(object/*!*/ pattern, bool anchored, bool advance) { /// The caller answers a length or a position, not text: the /// MatchData can wait until something asks for a group. private bool Match(object/*!*/ pattern, bool anchored, bool advance, bool lazyGroups) { + if (_position > ByteLength) { + // The subject was replaced by a shorter one under the scan pointer: MRI's + // strscan_do_scan clears the match and answers nil (S_RESTLEN < 0). + ClearMatch(); + return false; + } var regex = pattern as RubyRegex; return (regex != null) ? MatchRegex(regex, anchored, advance, lazyGroups) @@ -756,10 +762,14 @@ public static bool IsFixedAnchor(StringScanner/*!*/ self) { [RubyMethod("beginning_of_line?")] [RubyMethod("bol?")] - public static bool BeginningOfLine(StringScanner/*!*/ self) { + public static bool? BeginningOfLine(StringScanner/*!*/ self) { if (self._position == 0) { return true; } + if (self._position > self.ByteLength) { + // MRI: nil once the subject got shorter than the scan pointer + return null; + } Utf8OffsetMap map = self.Map; int clr = (map != null) ? map.ClrOf(self._position) : -1; if (clr > 0) { @@ -889,6 +899,12 @@ public static int GetCurrentPosition(StringScanner/*!*/ self) { [RubyMethod("charpos")] public static int GetCharPosition(StringScanner/*!*/ self) { + int length = self.ByteLength; + if (self._position > length) { + // MRI's rb_enc_strlen runs past the end of a subject that got shorter than the scan + // pointer, and counts each byte beyond it as a character + return self.CharacterCountOf(length) + (self._position - length); + } return self.CharacterCountOf(self._position); } From ed21b1ad2519f31da26f66057b5aa9bb9c3aad42 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:35:09 +0000 Subject: [PATCH 199/439] StringScanner: a String pattern of an incompatible encoding raises MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MRI's strscan checks a String pattern against the subject with rb_enc_check, so scanning a binary or EUC-JP subject for "é" (UTF-8) raises Encoding::CompatibilityError ("incompatible character encodings: BINARY (ASCII-8BIT) and UTF-8"); an ASCII pattern or an ASCII-only subject is compatible. IronRuby compared bytes and answered nil. The check runs only when the two encodings differ. Util/string-search-matrix.rb: the 23 scan('é') rows of the binary and EUC-JP subjects now agree with CRuby 4.0 (63 lines left, all /./ on a split byte). library/stringscanner specs pass; StringScanner_LiteralEncoding1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 27 ++++++++++++++++++++ Src/Libraries/StringScanner/StringScanner.cs | 5 ++++ 3 files changed, 33 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 505e7f112..99db70d78 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -216,6 +216,7 @@ public Tests(Driver/*!*/ driver) { Regex_Latin1Ctype1, StringScanner_InsideCharacter1, StringScanner_ShorterSubject1, + StringScanner_LiteralEncoding1, Regex_InspectResultEncoding1, Regex_EscapedByteEncoding1, Regex_EscapedByteEncoding2, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 2d3b5eeb9..db14dbdcc 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -955,6 +955,33 @@ p [ss.peek(2), ss.rest_size, ss.check(/x/), ss.skip(""a""), ss.exist?(/a/), ss.r "); } + /// + /// A String pattern whose encoding is incompatible with the subject's is an error to MRI's strscan + /// (rb_enc_check), not a miss; an ASCII pattern, or an ASCII-only subject, is compatible. + /// + public void StringScanner_LiteralEncoding1() { + TestOutput(@" +require 'strscan' +b = StringScanner.new(""ab\xE9c"".b) +p((b.scan(""\u00e9"") rescue $!), (b.scan(""a"") rescue $!), (b.skip_until(""\u00e9"") rescue $!)) +e = StringScanner.new(""\xA4\xA2a"".dup.force_encoding(""EUC-JP"")) +e.pos = 3 +p((e.scan(""\u00e9"") rescue $!), (e.check("""") rescue $!)) +a = StringScanner.new(""abc"") +p((a.scan(""\u00e9"") rescue $!)) +u = StringScanner.new(""h\u00e9"") +p((u.scan(""\xE9"".b) rescue $!)) +", @" +# +""a"" +# +# +"""" +nil +# +"); + } + /// /// A BINARY subject is matched with Onigmo's ASCII-8BIT ctype table (MRI's /// rb_reg_prepare_enc compiles a regexp that is not fixed-encoding for the subject's diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index dde51663d..7372eaf84 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -568,6 +568,11 @@ private bool MatchRest(RubyRegex/*!*/ pattern, bool anchored, bool advance) { private bool MatchLiteral(MutableString/*!*/ pattern, bool anchored, bool advance) { ClearMatch(); + if (pattern.Encoding != _scanString.Encoding) { + // MRI's rb_enc_check(subject, pattern): an incompatible pattern is an error, not a miss + _scanString.RequireCompatibleEncoding(pattern); + } + if (anchored && pattern.IsAscii()) { // The usual #skip("{"): an ASCII pattern's characters are its bytes, so it can be // compared where it stands instead of being copied out to a byte array first. From 9b588fc2f774bd8fd04c8097a6a376c6b2f73fee Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:38:49 +0000 Subject: [PATCH 200/439] Outline a block whose local is first assigned inside an if branch AWFY Sieve allocated 100 MB per iteration, nearly all of it in `(2..size).each`: the block-loop screen (BlockLoopSite.Screen) admits a block-local only when a statement of the body itself first assigns it, and Sieve's `k = i + i` sits under `if flags[i - 1]`. So the block was never run in place: 4,999 yields per call, each boxing an `i` past the Integer cache, and an entry per prime into the OSR copy of the inner `while`. The screen now walks the statement lists of if/elsif/else branches and while bodies as it walks the body (WalkScoped): a local first mentioned by a statement of such a list that assigns it is admitted for the rest of the list, so it is never read before it is written in an iteration, and refused anywhere after the list, where the block would see nil on an iteration that skipped it while a loop slot would carry an earlier value. IR_BLOCK_LOOP_SCOPED=0 keeps the old screen. Sieve 100.3 -> 12.1 MB per iteration (alloc.rb; the flags Arrays are what is left), the other benchmarks as before. AWFY, 10 alternating rounds, medians: Sieve 136.4 -> 63.6 ms; Bounce, Permute and Queens overlapping, with the same OSR traces on both builds. Util/block-loop-matrix.rb's new section of scoped locals prints CRuby's output; the block-loop, osr-array, array2, array-step, ivar, hot-shapes, jit, jit-calls, strcow and dup matrices pass in every mode and switched off; spec/core/array as on the base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Ruby/Runtime/Osr/BlockLoopSite.cs | 61 ++++++++++++++++++++++- Util/block-loop-matrix.rb | 72 +++++++++++++++++++++++++++ Util/perf/LEDGER.md | 27 ++++++++++ 3 files changed, 159 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs index e85b77da2..91ac96764 100644 --- a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs @@ -248,6 +248,65 @@ private bool AcceptsNested(MethodCall/*!*/ call) { return true; } + // Locals first assigned by a statement of a nested list - an `if' branch, a `while' body - whose scope, that list, + // has ended (WalkScoped): any later mention is outside it. + private HashSet _outOfScope; + + /// + /// IR_BLOCK_LOOP_SCOPED=0: a block-local must be first assigned by a statement of the body itself, as before. + /// + internal static readonly bool ScopedLocals = Environment.GetEnvironmentVariable("IR_BLOCK_LOOP_SCOPED") != "0"; + + // A list of statements of an `if' branch or a `while' body: a local of the block's own first mentioned by a statement + // of the list that assigns it (`k = i + i' in Sieve's `if flags[i - 1]') is admitted for the rest of the list - every + // mention of it is then after that assignment in the same iteration, so the slot it keeps across iterations of the + // copy is never read before it is written, as a fresh block-local is not - and refused anywhere after the list, where + // the block would see nil on an iteration that did not run the list. + private void WalkScoped(Statements list) { + if (list == null) { return; } + List scoped = null; + foreach (var statement in list) { + var assignment = statement as SimpleAssignmentExpression; + var target = (ScopedLocals && assignment != null && assignment.Operation == null) ? assignment.Left as LocalVariable : null; + if (target != null && target.DefinitionLexicalDepth == _depth && !IsKnown(target) && + (_outOfScope == null || !_outOfScope.Contains(target.Name))) { + assignment.Right.Walk(this); + _locals.Add(target); + (scoped ?? (scoped = new List())).Add(target.Name); + } else { + statement.Walk(this); + } + if (_rejected) { return; } + } + if (scoped != null) { + var outOfScope = _outOfScope ?? (_outOfScope = new HashSet()); + foreach (var name in scoped) { outOfScope.Add(name); } + } + } + + internal protected override void Walk(IfExpression/*!*/ node) { + if (Enter(node)) { + node.Condition.Walk(this); + WalkScoped(node.Body); + if (node.ElseIfClauses != null) { + foreach (var clause in node.ElseIfClauses) { + if (_rejected) { break; } + if (clause.Condition != null) { clause.Condition.Walk(this); } + WalkScoped(clause.Statements); + } + } + } + Exit(node); + } + + internal protected override void Walk(WhileLoopExpression/*!*/ node) { + if (Enter(node)) { + if (node.Condition != null) { node.Condition.Walk(this); } + WalkScoped(node.Statements); + } + Exit(node); + } + private bool IsKnown(LocalVariable/*!*/ local) { if (_parameter != null && local.Name == _parameter.Name) { return true; } foreach (var known in _locals) { @@ -294,7 +353,7 @@ public override bool Enter(LocalVariable/*!*/ node) { private bool Admits(LocalVariable/*!*/ node) { int d = node.DefinitionLexicalDepth; if (d < 0 || d > _depth) { return false; } - if (d == _depth) { return IsKnown(node); } + if (d == _depth) { return IsKnown(node) && (_outOfScope == null || !_outOfScope.Contains(node.Name)); } return _parent == null || _parent.Admits(node); } } diff --git a/Util/block-loop-matrix.rb b/Util/block-loop-matrix.rb index 1ee2bb9ed..613d91f72 100644 --- a/Util/block-loop-matrix.rb +++ b/Util/block-loop-matrix.rb @@ -632,3 +632,75 @@ def run(n, at, &event) r = o.run(3000, 1500) { |me| def me.swap(i, j); @log << :single if @log.size < 2; end } [r, o.log, p2.run(3000, -1)] end + +# ---------------------------------------------------------------- block-locals first assigned in a nested list +# (perf/sieve) A local first assigned by a statement of an `if' branch or a `while' body is admitted for the rest of that +# list (Sieve's `k = i + i' under `if flags[i - 1]'), and any mention of it after the list keeps the block from being +# outlined: there the block sees nil on an iteration that did not run the list, where a loop slot would carry the value +# of an earlier one. Each runs hot, then probes. +def bl_sieve(size) + flags = Array.new(size, true) + count = 0 + (2..size).each do |i| + if flags[i - 1] + count += 1 + k = i + i + while k <= size + flags[k - 1] = false + k += i + end + end + end + [count, flags.count(true)] +end +t('scoped: Sieve, hot') { 30.times { bl_sieve(N) }; bl_sieve(N) } +t('scoped: Sieve with 2.upto') do + f = Array.new(N, true); c = 0 + 2.upto(N) { |i| if f[i - 1]; c += 1; k = i * 2; while k <= N; f[k - 1] = false; k += i; end; end } + c +end +t('scoped: read after the if is nil on iterations that skip it') do + r = []; (1..N).each { |i| if i.even?; k = i; end; r << k if i > N - 4 }; r +end +t('scoped: assigned in then and else') do + s = 0; (1..N).each { |i| if i.even?; k = i; s += k; else; k = -1; s += k; end }; s +end +t('scoped: assigned in elsif only, read after') do + r = []; (1..N).each { |i| if i % 3 == 0; s = 1; elsif i % 3 == 1; k = i; end; r << k if i > N - 3 }; r +end +t('scoped: while body, read in the condition (do-while)') do + c = 0; (1..N).each { |i| begin; x = (x || 0) + 1; c += 1; end while x < 2 if i.odd? }; c +end +t('scoped: while body, read after the loop') do + r = []; (1..N).each { |i| j = 0; while j < 2; m = i + j; j += 1; end; r << m if i > N - 3 }; r +end +t('scoped: read before the assignment in the same list') do + r = []; (1..N).each { |i| if i > 0; r << z if i > N - 2; z = i; end }; r +end +t('scoped: a deopt after the assignment (Float)') do + s = 0; (1..N).each { |i| if i.odd?; k = i * 2; k = k * 1.5 if i > N - 10; s += k; end }; s +end +t('scoped: an Integer leaving Int32 after the assignment') do + s = 0; (1..N).each { |i| if i.odd?; k = i * (1 << 30); s += k; end }; s +end +t('scoped: binding sees the block-local') do + r = nil; (1..N).each { |i| if i.even?; k = i; end; r = binding.local_variable_defined?(:k) if i == N }; r +end +t('scoped: map with a scoped local') do + (1..N).to_a.map { |i| if i.even?; k = i * 3; k + 1; else; i; end }.sum +end +t('scoped: select with a scoped local') do + (1..N).to_a.select { |i| if i % 3 == 0; k = i / 3; k.odd?; else; false; end }.size +end +t('scoped: times with a scoped local, Array grown under the loop') do + a = []; N.times { |i| if i % 7 == 0; k = i; a << k; a << a.size; end }; [a.size, a.last] +end +t('scoped: next inside the list') do + s = 0; (1..N).each { |i| if i.even?; k = i; next if k % 4 == 0; s += k; end }; s +end +t('scoped: break inside a while in the list') do + s = 0; (1..N).each { |i| if i.odd?; k = i; while k > 0; k -= 7; break if k < 3; end; s += k; end }; s +end +t('scoped: a nested block reads it') do + s = 0; (1..N).each { |i| if i.odd?; k = i; [1, 2].each { |x| s += k * x }; end }; s +end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 33b34f224..1f61e4598 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1786,6 +1786,33 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/sieve (2026-11-27, not gated) - a block-local first assigned inside an `if` branch or a + `while` body no longer keeps the block from being outlined** (switch `IR_BLOCK_LOOP_SCOPED`). AWFY + Sieve allocated 100.3 MB per iteration (alloc.rb). Bytes per `sieve` call, by variants: the + `while` loops alone 1 KB beyond the 40 KB flags Array; `(2..size).each` with the real block 296 KB, + with an empty block 98 KB (a boxed Integer per yield above the 1,023 cache), with only + `flags[i - 1]` in it 2.7 KB - that one is run in place (BlockLoopSite). Sieve's is not: the + block-loop screen admits a block-local only if a statement of the body itself first assigns it, + and `k = i + i` sits under `if flags[i - 1]`, so all 4,999 iterations were yields, each boxing `i` + and entering the OSR copy of the inner `while` with boxed locals. The screen now walks the + statement lists of `if`/`elsif`/`else` branches and `while` bodies as it walks the body + (`Screen.WalkScoped`): a local first mentioned by a statement of such a list that assigns it is + admitted for the rest of that list and refused anywhere after it, where the block would see nil + on an iteration that skipped the list while a loop slot would keep an earlier value. Sieve 100.3 + -> 12.1 MB per iteration (the 300 flags Arrays are what is left); the other thirteen as before + (DeltaBlue, Richards and Towers moved by up to 7% between runs of the same build). AWFY, 10 + alternating rounds of 8 s, medians: Sieve 136,442 -> 63,559 us (0.466), Permute 0.955, Bounce + 1.009, Queens 1.029, all three within each other's ranges, and their OSR traces are the same on + both builds. `Util/block-loop-matrix.rb` gains a section (Sieve hot and with upto; a read after + the `if`; then and else; elsif; a do-while; a read after a `while`; a read before the assignment; + a Float deopt and an Integer leaving Int32 after it; binding; map, select, times; next; break; a + nested block): CRuby's output on both builds. Those the screen now admits but the loop compiler + cannot take (Float or overflowing arithmetic, binding, map's value) cost one attempt, 0.2-0.4 ms, + and are retired. Checks: block-loop, osr-array, array2, array-step, ivar, hot-shapes, jit, + jit-calls, strcow and dup matrices in every mode and switched off: PASS (array2 and block-loop's + R2R row as the base); spec/core/array 2,898 examples, the one known error on both. Base 9c4f953 + (4320d4a with 8c31db5); the base needed DLR patches 0111 and 0112 applied by hand. + - **Gate of 2026-11-27 for round 4 of round thirty-seven** (perf/strdup, perf/strsearch2, perf/extiter2 and 3, perf/lframe, perf/lexical2 and 3, perf/kwrest, perf/jitscreen and 2, perf/deadconst2, perf/permute, perf/havlak, perf/dmethjit2, perf/jitsettle; the rejected From 238d99434d4fe25e16f9a7a45e53653482e77bc1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:44:15 +0000 Subject: [PATCH 201/439] Method JIT: typed bodies for calls without a block A method whose block parameter is only passed on (`def w(a, b, &k) = @t.two(a, b, &k)`) was never wrapped by the method JIT, and one that passed `&nil` was refused by the screen, so a forwarding layer cost about 550 instructions more than the same method without the block. JitStub.BlockParameterOnlyPassed now accepts such a method: the parameter is never read except as `&k`, never assigned, there is no yield or super, and every parameter is mandatory. Its typed body is compiled for a call without a block. There `&k` passes no block, as `&nil` always does, and the screen, EmitCall and TryInlineCall treat the call as one without a block. `block_given?` in a method body compiles to false on the same terms, when Kernel's method answers it. Such a body sets JitCode.AssumesNoBlock, and the entry tests that the block is null, so a call with a block runs the generic body. A method the profile saw called with a block is declined. IR_JIT_BLOCK_PARAM=0 turns this off. Instructions per call on Util/bench/forward-shapes.rb: fixed_blk 2,254 -> 1,703, param_only 2,094 -> 1,699, pass_nil 2,232 -> 1,697, the same as the fixed forwarder. Census: 62 methods up, none down. Util/jit-blockparam-matrix.rb prints CRuby's output in every JIT mode; the jit, block-pass, block-given and forwarding matrices, ruby/spec language block/send/yield/super/def/proc and IronRuby.Tests are the same as on the base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs | 2 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 67 +++++++- Src/Ruby/Runtime/Jit/JitStub.cs | 81 +++++++++- Util/jit-blockparam-matrix.rb | 176 +++++++++++++++++++++ Util/perf/LEDGER.md | 35 ++++ 5 files changed, 355 insertions(+), 6 deletions(-) create mode 100644 Util/jit-blockparam-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs index abfe8f547..7d2ee8911 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs @@ -50,7 +50,7 @@ internal sealed partial class JitCompiler { /// private MSA.Expression TryInlineCall(MethodCall/*!*/ node, out JT type) { type = JT.None; - if (_ast == null || _loop != null || _supplied >= 0 || _hints == null || !_refinements.IsEmpty || node.Block != null) { return null; } + if (_ast == null || _loop != null || _supplied >= 0 || _hints == null || !_refinements.IsEmpty || node.Block != null && !PassesNoBlock(node)) { return null; } var args = (node.Arguments != null) ? node.Arguments.Expressions : new RExpr[0]; foreach (var arg in args) { if (arg is SplattedArgument) { return null; } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 179d05fc8..b82e9d5b8 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -94,6 +94,10 @@ internal sealed class JitCode { // block after its parameters and makes its frame (JitResume.cs); null when it has none. internal JitResumeInfo Resume; internal int FallbackSites; + // The body was compiled for a call without a block: its block parameter is nil, which `&k' passes on as no block + // (JitStub.BlockParameterOnlyPassed), or it answered `block_given?' with false. The entry takes it only when the + // block is null. + internal bool AssumesNoBlock; } /// @@ -111,6 +115,12 @@ internal sealed partial class JitCompiler { private readonly MethodDeclaration _ast; private readonly RubyContext/*!*/ _context; + + // The method's block parameter, when it only passes it on (JitStub.BlockParameterOnlyPassed): the body is compiled + // for a call without a block, where `&k' passes none (JitScreen.PassesNoBlock). Null otherwise. + private readonly LocalVariable _passedBlock; + // The body answered `block_given?' with false, for a call without a block (EmitBlockGiven). + private bool _blockGivenFalse; private readonly int _scopeDepth; // The refinements active where the code being compiled was written: the calls it binds itself @@ -222,6 +232,7 @@ private JitCompiler(MethodDeclaration/*!*/ ast, RubyContext/*!*/ context, JT[]/* _ast = ast; _context = context; _constantScope = constantScope; + if (JitStub.BlockParameterOnlyPassed(ast)) { _passedBlock = ast.Parameters.Block; } _paramTypes = paramTypes; _keywords = keywords; _supplied = (keywords == null) ? supplied : -1; @@ -795,6 +806,7 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ InlinedOnArgumentClass = c._inlinedOnArgumentClass, Resume = (c._fallbackSites > 0) ? c._resume : null, FallbackSites = c._fallbackSites, + AssumesNoBlock = c._passedBlock != null || c._blockGivenFalse, }; } return Declined("the return type did not settle"); @@ -2270,8 +2282,39 @@ internal static bool IsRaiseCall(MethodCall/*!*/ node) { return Ast.Call(JitRuntime.M("RaiseDeopt")); } + /// + /// A call whose block is `&nil', or `&k' of the method's block parameter k when the method only passes it on and + /// the body is compiled for a call without a block (_passedBlock): it passes no block, and is the call without one. + /// + private bool PassesNoBlock(MethodCall/*!*/ node) { + return _refinements.IsEmpty && JitScreen.PassesNoBlock(node, _passedBlock); + } + + // `block_given?' in a method (not an outlined loop, which runs in a frame that may have a block) + private bool IsBlockGiven(MethodCall/*!*/ node) { + return node.Target == null && node.MethodName == "block_given?" && (node.Arguments == null || node.Arguments.IsEmpty) && + node.Block == null && _ast != null && _loop == null; + } + + /// + /// `block_given?' as false, for a body the entry takes only when the call has no block (JitCode.AssumesNoBlock) - and + /// which a body that inlines it or calls it directly calls without one. Kernel#block_given? is what self's class + /// resolves the name to now; the entry's method version guard covers a later definition. + /// + private MSA.Expression/*!*/ EmitBlockGiven(out JT type) { + object sample = (_hints != null) ? _hints.SelfSample : null; + // (only BuildEntry tests the block: not a keyword method's direct entry, nor a per-count body's) + if (_keywords != null || _supplied >= 0) { throw Bail("block_given? with optional parameters"); } + if (sample == null || !_refinements.IsEmpty || !IsBuiltinMethod(JitRuntime.ClassOf(_context, sample), "block_given?")) { + throw Bail("block_given? is not Kernel's"); + } + _blockGivenFalse = true; + type = JT.Bool; + return Ast.Constant(false); + } + private MSA.Expression/*!*/ EmitCall(MethodCall/*!*/ node, out JT type) { - if (node.Block != null) { + if (node.Block != null && !PassesNoBlock(node)) { // an iterator with a literal block inside a core iterator's outlined loop: run in place (JitCompiler.Nest.cs) if (_loop != null && WritesReceivers) { return EmitNestedBlockLoop(node, out type); } throw Bail("call with a block: " + node.MethodName); @@ -2284,6 +2327,8 @@ internal static bool IsRaiseCall(MethodCall/*!*/ node) { return EmitNot(node.Target, out type); } + if (IsBlockGiven(node)) { return EmitBlockGiven(out type); } + // `raise ...' or `fail ...' (EmitRaise): a deopt, and the generic body raises. if (IsRaiseCall(node)) { return EmitRaise(node, out type); } @@ -3315,6 +3360,24 @@ private JitScreen(MethodDeclaration/*!*/ ast, JitKeywords keywords) { // a method with keywords is never called directly from its typed body (EmitCall) _arity = (keywords != null) ? -1 : ast.Parameters.Mandatory.Length + ast.Parameters.Optional.Length; _tailConstruction = (keywords != null) ? null : JitCompiler.TailConstruction(ast); + if (JitStub.BlockParameterOnlyPassed(ast)) { _passedBlock = ast.Parameters.Block; } + } + + // the method's block parameter, when it only passes it on (JitCompiler._passedBlock) + private readonly LocalVariable _passedBlock; + + /// + /// `&nil', or `&k' of , the block parameter of a method that only passes it on and + /// whose body is entered only without a block: no block is passed (JitCompiler.PassesNoBlock). + /// + internal static bool PassesNoBlock(MethodCall/*!*/ node, LocalVariable passedBlock) { + var reference = node.Block as BlockReference; + if (reference == null) { return false; } + var literal = reference.Expression as Literal; + if (literal != null && literal.GetType() == typeof(Literal) && literal.Value == null) { return true; } + var local = reference.Expression as LocalVariable; + return local != null && passedBlock != null && local.Name == passedBlock.Name && + local.DefinitionLexicalDepth == passedBlock.DefinitionLexicalDepth; } // the `C.new(a, b)' the method ends with, if it does (JitCompiler.TailConstruction) @@ -3955,7 +4018,7 @@ private static bool IsRangeBound(RExpr/*!*/ node) { /// Mirrors JitCompiler.EmitCall: a self-recursive call, a binary operator, an element read or a Hash query. private bool WalkCall(MethodCall/*!*/ node) { - if (node.Block != null) { return No(node); } + if (node.Block != null && !PassesNoBlock(node, _passedBlock)) { return No(node); } // `raise ...': a deopt, whose arguments are never emitted (JitCompiler.EmitRaise) if (JitCompiler.IsRaiseCall(node)) { return true; } var args = node.Arguments; diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index cf33887ed..df171d9ac 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -153,6 +153,8 @@ internal abstract class JitStub { // body (it is profiling or cooling down, or its entry is stale). The method then goes on // profiling, as for a callee it would inline (ReceiverHints.CalleeNotReady, MaxInlineWaits). private bool _calleeNotReady; + // A call the stub profiled had a block: a body compiled for calls without one is declined (JitCode.AssumesNoBlock). + protected bool _calledWithBlock; protected JitStub(MethodDeclaration/*!*/ ast, RubyContext/*!*/ context, RubyModule/*!*/ declaringModule, Delegate/*!*/ generic, int arity, JitKeywords keywords) { @@ -363,7 +365,8 @@ protected void Profile(object self, object[] args) { if (_receiverClass == null) { _receiverClass = cls; } else if (_receiverClass != cls) { _polymorphicReceiver = true; } ObserveType(ref _selfClrType, self); - if (++_calls < Threshold) { return; } + // a method that passes its block parameter on and was called with a block declines now (TrySpecialize) + if (++_calls < Threshold && !(_calledWithBlock && _ast.Parameters.Block != null)) { return; } _calls = 0; if (Interlocked.CompareExchange(ref _compiling, 1, 0) != 0) { return; } @@ -886,6 +889,12 @@ private bool TrySpecialize() { } if (_perCountMandatory >= 0) { return TrySpecializePerCount(refinements); } + // a body for calls without a block (BlockParameterOnlyPassed) is not compiled for a method called with one + if (_calledWithBlock && _ast.Parameters.Block != null) { + _declineReason = "called with a block"; + return false; + } + var types = ProfiledTypes(_typedCount); // The method version the entry guards on is read before compiling, so that it is never @@ -902,6 +911,11 @@ private bool TrySpecialize() { var hints = Hints(); var code = Named(JitCompiler.TryCompile(_ast, _context, types, _keywords, refinements, -1, _declaringScope, hints, Callees(refinements, version, constantVersion), epoch), epoch, version, constantVersion); + if (code != null && code.AssumesNoBlock && _calledWithBlock) { + // the entry would send each call that has a block to the generic body, past its guards + _declineReason = "called with a block"; + return false; + } if (code == null) { // A call the body could inline - or, with -X:JITCalls, bind - is of a method that has not been // specialized yet: a caller called once per call of its callee turns hot first. Profile on, a @@ -1332,6 +1346,10 @@ private bool SelfCallResolvesHere(RubyClass/*!*/ cls, RefinementActivation/*!*/ Ast.Call(JitRuntime.M("ClassOf"), Ast.Constant(_context), self), Ast.Constant(pinnedClass, typeof(RubyClass)))); } + // a body compiled for a call without a block (BlockParameterOnlyPassed, JitCompiler.EmitBlockGiven) + if (code.AssumesNoBlock) { + test = And(test, Ast.ReferenceEqual(blk, Ast.Constant(null, typeof(Proc)))); + } MSA.ParameterExpression[] keywordValues = null; if (_keywords != null) { @@ -1741,8 +1759,11 @@ internal static bool CensusScreen(MethodDeclaration/*!*/ ast, RubyContext/*!*/ c internal static string ParameterShape(MethodDeclaration/*!*/ ast) { var ps = ast.Parameters; if (ps.Unsplat != null) { return "rest parameter"; } - if (ps.Block != null) { return "block parameter"; } - if (ast.UsesBlock) { return "uses its block"; } + if (ps.Block != null) { + if (!BlockParameterOnlyPassed(ast)) { return "block parameter"; } + } else if (ast.UsesBlock) { + return "uses its block"; + } if (ps.Mandatory.Length + ps.Optional.Length > MaxArity) { return "more than " + MaxArity + " parameters"; } for (int i = 0; i < ps.Mandatory.Length; i++) { if (!(ps.Mandatory[i] is LocalVariable)) { return "destructuring parameter"; } @@ -1750,6 +1771,53 @@ internal static string ParameterShape(MethodDeclaration/*!*/ ast) { return null; } + // IR_JIT_BLOCK_PARAM=0 turns it off + private static readonly bool _blockParameters = Environment.GetEnvironmentVariable("IR_JIT_BLOCK_PARAM") != "0"; + + /// + /// A method with a block parameter that does nothing with it but pass it on, `def w(a, b, &k) = @t.m(a, b, &k)': the + /// parameter is never read otherwise nor assigned, the method does not yield or call super (which passes it on too), and + /// it has only mandatory parameters. Called without a block, k is nil and `&k' passes no block, as `&nil' does; the + /// typed body is made for that call (JitCode.AssumesNoBlock: the entry takes it only when the block is null, and a method + /// the profile saw called with one is declined), and compiles `&k' as no block at all (JitScreen.PassesNoBlock). + /// A call with a block runs the generic body, which passes it on. + /// + internal static bool BlockParameterOnlyPassed(MethodDeclaration/*!*/ ast) { + var ps = ast.Parameters; + if (!_blockParameters || ps.Block == null || ps.Optional.Length > 0 || ps.Unsplat != null || ast.Body == null) { return false; } + var finder = new BlockPassFinder(ps.Block); + ast.Body.Walk(finder); + return !finder.Refused; + } + + private sealed class BlockPassFinder : Walker { + private readonly string/*!*/ _name; + private readonly int _depth; + internal bool Refused; + + internal BlockPassFinder(LocalVariable/*!*/ parameter) { + _name = parameter.Name; + _depth = parameter.DefinitionLexicalDepth; + } + + private bool IsParameter(Expression node) { + var local = node as LocalVariable; + return local != null && local.Name == _name && local.DefinitionLexicalDepth == _depth; + } + + public override bool Enter(BlockReference/*!*/ node) { + // `&k': the parameter passed on, and not otherwise read + return !IsParameter(node.Expression); + } + + // any other read, or an assignment + public override bool Enter(LocalVariable/*!*/ node) { if (IsParameter(node)) { Refused = true; } return true; } + public override bool Enter(YieldCall/*!*/ node) { Refused = true; return true; } + public override bool Enter(SuperCall/*!*/ node) { Refused = true; return true; } + // a method defined inside has variables of its own + public override bool Enter(MethodDefinition/*!*/ node) { return false; } + } + // The static part of Wrap's decision; rejectedBy is set when the screen (not the parameter list) refused the body. // isLeafCallee: the census's answer in place of the declaring module's (CensusScreen). // constantTruth: what a constant guarding a statement is now (JitScreen.CanEverCompile); null where it is not known. @@ -2081,6 +2149,7 @@ private object Cool(object self, Proc block) { private object Call(object self, Proc block) { var f = _fast; if (f != null) { return f(self, block); } + if (block != null) { _calledWithBlock = true; } Profile(self, Args0); f = _fast; return (f != null) ? f(self, block) : _gen(self, block); @@ -2121,6 +2190,7 @@ private object Cool(object self, Proc block, object a0) { private object Call(object self, Proc block, object a0) { var f = _fast; if (f != null) { return f(self, block, a0); } + if (block != null) { _calledWithBlock = true; } Profile(self, new[] { a0 }); f = _fast; return (f != null) ? f(self, block, a0) : _gen(self, block, a0); @@ -2161,6 +2231,7 @@ private object Cool(object self, Proc block, object a0, object a1) { private object Call(object self, Proc block, object a0, object a1) { var f = _fast; if (f != null) { return f(self, block, a0, a1); } + if (block != null) { _calledWithBlock = true; } Profile(self, new[] { a0, a1 }); f = _fast; return (f != null) ? f(self, block, a0, a1) : _gen(self, block, a0, a1); @@ -2201,6 +2272,7 @@ private object Cool(object self, Proc block, object a0, object a1, object a2) { private object Call(object self, Proc block, object a0, object a1, object a2) { var f = _fast; if (f != null) { return f(self, block, a0, a1, a2); } + if (block != null) { _calledWithBlock = true; } Profile(self, new[] { a0, a1, a2 }); f = _fast; return (f != null) ? f(self, block, a0, a1, a2) : _gen(self, block, a0, a1, a2); @@ -2241,6 +2313,7 @@ private object Cool(object self, Proc block, object a0, object a1, object a2, ob private object Call(object self, Proc block, object a0, object a1, object a2, object a3) { var f = _fast; if (f != null) { return f(self, block, a0, a1, a2, a3); } + if (block != null) { _calledWithBlock = true; } Profile(self, new[] { a0, a1, a2, a3 }); f = _fast; return (f != null) ? f(self, block, a0, a1, a2, a3) : _gen(self, block, a0, a1, a2, a3); @@ -2281,6 +2354,7 @@ private object Cool(object self, Proc block, object a0, object a1, object a2, ob private object Call(object self, Proc block, object a0, object a1, object a2, object a3, object a4) { var f = _fast; if (f != null) { return f(self, block, a0, a1, a2, a3, a4); } + if (block != null) { _calledWithBlock = true; } Profile(self, new[] { a0, a1, a2, a3, a4 }); f = _fast; return (f != null) ? f(self, block, a0, a1, a2, a3, a4) : _gen(self, block, a0, a1, a2, a3, a4); @@ -2321,6 +2395,7 @@ private object Cool(object self, Proc block, object a0, object a1, object a2, ob private object Call(object self, Proc block, object a0, object a1, object a2, object a3, object a4, object a5) { var f = _fast; if (f != null) { return f(self, block, a0, a1, a2, a3, a4, a5); } + if (block != null) { _calledWithBlock = true; } Profile(self, new[] { a0, a1, a2, a3, a4, a5 }); f = _fast; return (f != null) ? f(self, block, a0, a1, a2, a3, a4, a5) : _gen(self, block, a0, a1, a2, a3, a4, a5); diff --git a/Util/jit-blockparam-matrix.rb b/Util/jit-blockparam-matrix.rb new file mode 100644 index 000000000..d9b734326 --- /dev/null +++ b/Util/jit-blockparam-matrix.rb @@ -0,0 +1,176 @@ +# Differential matrix for methods the method JIT compiles for a call without a block (JitCode.AssumesNoBlock): a +# block parameter only passed on (`def w(a, &k) = @t.m(a, &k)', JitStub.BlockParameterOnlyPassed), `&nil', and +# `block_given?' (JitCompiler.EmitBlockGiven). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-blockparam-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-blockparam-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-blockparam-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-blockparam-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep BP +# The traps: a call with a block after the body is hot (the entry's block test), a method the profile saw called with +# a block, `break' through the passed block, `&obj' with to_proc (called once, by the outer call), a Symbol and a lambda +# passed on, block_given? in the callee, super with the implicit block, the parameter read, assigned or reached through +# a binding, a deopt with a block in flight, block_given? redefined, refined or in a loop, `&nil' with a block given. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 60]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class Callee + def two(a, b) = a + b + def two_y(a, b) = block_given? ? yield(a, b) : a + b + def given? = block_given? + def kind(&b) = b.nil? ? :none : (b.lambda? ? :lambda : :proc) + def leaf(a) = block_given? ? a * -1 : a +end + +class BPBase + def sup(a, &k) = block_given? ? yield(a) : a * 10 +end + +class BP < BPBase + def initialize; @t = Callee.new; end + def fwd(a, b, &k) = @t.two(a, b, &k) + def fwd_y(a, b, &k) = @t.two_y(a, b, &k) + def fwd_given(&k) = @t.given?(&k) + def fwd_kind(&k) = @t.kind(&k) + def fwd2(a, b, &k) = fwd_y(a, b, &k) + def anon(a, b, &) = @t.two_y(a, b, &) + def nil_pass(a, b) = @t.two_y(a, b, &nil) + def given(a) = block_given? ? a * -1 : a + 1 + def given_self(a) = block_given? ? a : leaf2(a) + def leaf2(a) = a * 2 + def inl(a, &k) = leaf(a, &k) + def leaf(a) = block_given? ? a * -1 : a + def read_k(a, &k) = k ? -a : a + def assign_k(a, &k) + k = proc { |x, y| x * y } if a > 1000 + @t.two_y(a, 1, &k) + end + def sup(a, &k) = super + def sup_explicit(a, &k) = @t.two_y(a, 1, &k) + def bind_k(a, &k) = binding.local_variable_get(:k) ? -a : a + def deopt(a, b, &k) = @t.two_y(a, b, &k) + 1 + def missing(a, &k) = @t.nosuch(a, &k) +end + +o = BP.new +t("fwd, no block") { warm { |i| o.fwd(i, 1) } } +t("fwd, then a block (two ignores it)") { o.fwd(1, 2) { :x } } +t("fwd_y, no block") { warm { |i| o.fwd_y(i, 1) } } +t("fwd_y, then a block") { o.fwd_y(3, 4) { |a, b| a * b } } +t("fwd_y, block then none") { [o.fwd_y(3, 4) { |a, b| a - b }, o.fwd_y(3, 4)] } +t("fwd_y: break through the block") { o.fwd_y(1, 2) { break :broke } } +t("fwd_y: break in a loop") { r = []; [1, 2, 3].each { |i| r << o.fwd_y(i, 0) { |a, _| break a * 100 if a == 2; a } }; r } +t("fwd_y: next in the block") { o.fwd_y(5, 6) { next :nexted } } +t("fwd_y: return from a lambda block") { l = ->(a, b) { return a + b + 100 }; o.fwd_y(1, 2, &l) } +t("fwd_y: &obj to_proc, called once") { n = 0; ob = Object.new; ob.define_singleton_method(:to_proc) { n += 1; proc { |a, b| a * b * 10 } }; [o.fwd_y(2, 3, &ob), n] } +t("fwd_y: &obj to_proc returns nil") { ob = Object.new; def ob.to_proc = nil; o.fwd_y(2, 3, &ob) } +t("fwd_y: &:sym") { o.fwd_y(2, 3, &:+) } +t("fwd_y: &nil") { o.fwd_y(2, 3, &nil) } +t("fwd_y: via send with a block") { o.send(:fwd_y, 2, 3) { |a, b| [a, b] } } +t("fwd_y: via Method#call") { m = o.method(:fwd_y); [m.call(2, 3), m.call(2, 3) { |a, b| a - b }] } +t("fwd_y: via Method#to_proc") { m = o.method(:fwd_y).to_proc; m.call(4, 5) } +t("fwd_given, no block") { warm { o.fwd_given } } +t("fwd_given, a block") { o.fwd_given { } } +t("fwd_kind") { warm { o.fwd_kind }; [o.fwd_kind, o.fwd_kind { }, o.fwd_kind(&-> { })] } +t("fwd2, two layers") { warm { |i| o.fwd2(i, 1) }; [o.fwd2(1, 1), o.fwd2(2, 3) { |a, b| a * b }] } +t("anon &") { warm { |i| o.anon(i, 1) }; [o.anon(1, 1), o.anon(2, 3) { |a, b| a * b }] } +t("nil_pass") { warm { |i| o.nil_pass(i, 1) } } +t("nil_pass with a block") { o.nil_pass(2, 3) { :never } } +t("given") { warm { |i| o.given(i) } } +t("given, then a block") { [o.given(5) { }, o.given(5)] } +t("given_self") { warm { |i| o.given_self(i) }; [o.given_self(3) { }, o.given_self(3)] } +t("inl: inlined callee's block_given?") { warm { |i| o.inl(i) }; [o.inl(4), o.inl(4) { }] } +t("read_k") { warm { |i| o.read_k(i) }; [o.read_k(4), o.read_k(4) { }] } +t("assign_k") { warm { |i| o.assign_k(i) }; [o.assign_k(5), o.assign_k(2000), o.assign_k(5) { |a, b| a - b }] } +t("super with the implicit block") { warm { |i| o.sup(i) }; [o.sup(3), o.sup(3) { |a| a + 1 }] } +t("sup_explicit") { warm { |i| o.sup_explicit(i) }; [o.sup_explicit(3), o.sup_explicit(3) { |a, b| a * b }] } +t("bind_k") { warm { |i| o.bind_k(i) }; [o.bind_k(3), o.bind_k(3) { }] } +t("deopt: no block") { warm { |i| o.deopt(i, 1) }; o.deopt(2**62, 2**62) } +t("deopt: a block in flight") { o.deopt(2**62, 2**62) { |a, b| (a + b).to_s.size } } +t("deopt: Float") { [o.deopt(1.5, 1), o.deopt(1.5, 1) { |a, b| a * b }] } +t("missing") { o.missing(1) } +t("missing with a block") { o.missing(1) { } } + +# called with a block from the start: the profile saw one +p2 = BP.new +t("always a block") { warm { |i| p2.fwd_y(i, 1) { |a, b| a - b } } } +t("always a block, then none") { [p2.fwd_y(7, 1), p2.fwd_y(7, 1) { |a, b| a * b }] } +t("given, always a block") { warm { |i| p2.given(i) { } } } +t("given, always a block, then none") { p2.given(7) } + +# a block sometimes +p3 = BP.new +t("a block every third call") { s = 0; warm { |i| s += (i % 3 == 0) ? p3.fwd_y(i, 1) { |a, b| a * b } : p3.fwd_y(i, 1) }; s } + +# block_given? redefined in the class after the body is hot +class GivenRedef + def g(a) = block_given? ? :yes : a +end +gr = GivenRedef.new +t("block_given? before") { warm { |i| gr.g(i) } } +class GivenRedef + def block_given? = true +end +t("block_given? redefined") { [gr.g(1), gr.g(1) { }] } + +# Kernel#block_given? refined where the method is written +module GivenRefinement + refine Object do + def block_given? = :refined + end +end +class GivenRefined + using GivenRefinement + def g(a) = block_given? ? a : -a +end +gref = GivenRefined.new +t("block_given? refined") { warm { |i| gref.g(i) } } + +# block_given? in a while loop (an outlined loop runs in the generic frame) +class GivenLoop + def g(n) + i = 0 + s = 0 + while i < n + s += block_given? ? 2 : 1 + i += 1 + end + s + end +end +gl = GivenLoop.new +t("block_given? in a loop") { warm(50) { gl.g(2000) } } +t("block_given? in a loop, a block") { gl.g(2000) { } } + +# a singleton method on the receiver, and another class +t("singleton fwd_y") { s = BP.new; def s.fwd_y(a, b, &k) = :single; [s.fwd_y(1, 2), o.fwd_y(1, 2)] } +class BP2 < BP; def two_y(*) = :sub; end +t("subclass") { b2 = BP2.new; warm { |i| b2.fwd_y(i, 1) }; [b2.fwd_y(1, 1), b2.fwd_y(1, 1) { |a, b| a * b }] } + +# the callee redefined after the forwarding body is hot +class Callee + def two_y(a, b) = block_given? ? [:redef, yield(a, b)] : [:redef, a] +end +t("callee redefined") { [o.fwd_y(1, 2), o.fwd_y(1, 2) { |a, b| a + b }] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index d1ea398dd..25f191a53 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1774,6 +1774,41 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitblockparam (2026-11-27, census and timed, not gated) - a typed body for a call without a block** + (switch `IR_JIT_BLOCK_PARAM`). A method whose block parameter is only passed on, `def w(a, b, &k) = + @t.two(a, b, &k)`, was never wrapped (`JitStub.ParameterShape`: "block parameter"), and one passing `&nil` + was refused at the screen (a call with a block). Now `JitStub.BlockParameterOnlyPassed` takes a method whose + block parameter is never read except as `&k`, never assigned, with no yield and no super, and only + mandatory parameters. Its typed body is compiled for a call without a block: there k is nil and `&k` + passes none, as `&nil` always does (`JitScreen.PassesNoBlock`; the screen, `EmitCall` and `TryInlineCall` + take such a call as one without a block). `block_given?` in a method body (not in an outlined loop, not + with optional or keyword parameters, Kernel's and unrefined) compiles to false on the same terms + (`EmitBlockGiven`). Such a body sets `JitCode.AssumesNoBlock`, and the entry adds `block == null` to its + test, so a call with a block runs the generic body, which passes it on. A method the profile saw called + with a block is declined ("called with a block"), at that call if it has a block parameter, before + anything is compiled. Inlined and directly called bodies are only ever called without a block. + Census (Src/StdLib, Util/bench, AWFY): 62 methods up, none down. 61 left "never (block parameter)" + (2 now compile, the rest are maybe), and `FW#pass_nil` left "never (MethodCall two)". Compiles 3,579 -> + 3,583, maybe 3,180 -> 3,238. Traced runs: forward-shapes specialized 4 -> 7, declines 1 -> 1; + delegate-shapes 3 -> 3, 1 -> 1; app-shapes 120 -> 120 specialized, declines 28 -> 29. The new decline, + `CSV::FieldsConverter#each` (`@converters.each(&block)`), is always called with a block; it declines at + its first call. Most of the methods let through pass `&k` to an iterator, so they win nothing: the gain + is a forwarder to a leaf called without a block. Instructions per call (`callgrind/count.sh`, + `Util/bench/forward-shapes.rb`): fixed_blk 2,254 -> 1,703, param_only 2,094 -> 1,699, pass_nil + 2,232 -> 1,697, the same as fixed (1,701). rest, rest_blk, dots and anon are unchanged (rest and dots + read +69 once and 0 on a rerun). Delegate-shapes is unchanged, row for row (its forwarders take a rest + or a block). Clock (ab.rb -r 3, noisy): param_only 54 -> 38 ns against the switch off; the other rows + overlap. `Util/jit-blockparam-matrix.rb` (new: `&k`, `&nil`, block_given? in the caller and callee, + break and next through the passed block, a lambda's return, `&obj` with to_proc once, `&:sym`, send and + Method#call with a block, two layers, anonymous `&`, an inlined callee's block_given?, k read, assigned, + through a binding, super with the implicit block, a deopt with a block in flight, a method always + called with a block, a block every third call, block_given? redefined, refined and in a loop, a + singleton, the callee redefined): CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, + IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, dmeth-jit, block-pass, block-given, forward-rest + and hot-shapes in the same five modes: the same as the base (forward-rest's six bind_call-of-binding rows + differ from CRuby on both). ruby/spec language block, send, yield, super, def and proc: the same as the + base (send's one error is the known `into`). IronRuby.Tests, all 1,377: PASSED. + - **Gate of 2026-11-27 for round 4 of round thirty-seven** (perf/strdup, perf/strsearch2, perf/extiter2 and 3, perf/lframe, perf/lexical2 and 3, perf/kwrest, perf/jitscreen and 2, perf/deadconst2, perf/permute, perf/havlak, perf/dmethjit2, perf/jitsettle; the rejected From 1b4603949e857e6eb5db94df3e89069f83701cff Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:44:35 +0000 Subject: [PATCH 202/439] Array#take is Array's own, as MRI's rb_ary_take Array inherited Enumerable#take, which walks #each through a Proc and its BlockParam: [1, 2, 3, 4].take(2) took 248 ns against CRuby's 71, where first(2), the same work read from the storage, took 80. It also differed from CRuby wherever that walk shows: Array.instance_method(:take).owner was Enumerable, a backtrace named Enumerable#first, a subclass's own #each (or a redefined Array#each) was called, a redefined Enumerable#take reached Arrays, and take(2**40) was a RangeError where NUM2LONG takes it. IListOps now has #take, next to #first(n): the count through the same [DefaultProtocol]int conversion as before, "attempt to take negative size" for a negative one, then a new plain Array of the first elements; a Bignum count that fits a long takes the whole Array (a negative one is the ArgumentError) and one past a long is "bignum too big to convert into 'long'", as in MRI. Clock (Util/perf/ab.rb, four rounds, ns, CRuby / unchanged / this): take 71.5 / 248.0 / 83.1 (0.34); first_n, min, max, minmax within the noise (six rounds for min, max, minmax: 0.98, 1.02, 0.98). Util/array-take-matrix.rb (new: counts of every kind, to_int, Bignums, Floats, NaN, Infinity, arity errors, a block, frozen receivers, subclasses with their own #each, #size and #[], owner/arity/parameters, the backtrace label, Enumerable#take of a Range and a Hash, redefined Enumerable#take and Array#each): six lines move to CRuby's output and none away; the two left (nil's and Infinity's message) are the conversion protocol's, as before. The same in the default mode, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. array-step, array2, enum, enum-next, enumerable2, osr-array and hot-shapes print what they did in those four modes. ruby/spec core/array and core/enumerable: the same examples on both builds. IronRuby.Tests: the eight tests that call take and Backtrace_LibraryFrames1 pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/Libraries/Extensions/IListOps.cs | 24 ++++++++ Util/array-take-matrix.rb | 85 ++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 Util/array-take-matrix.rb diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index 952acab4d..6a25fbc84 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -1712,6 +1712,30 @@ public static object First(IList/*!*/ self) { return new RubyArray(self, 0, count); } + // Array's own #take, as MRI's rb_ary_take: a new plain Array of the first count elements, read + // from the storage. Enumerable's walked #each through a Proc, three times as long, and so + // called a subclass's own #each, which MRI's does not. + [RubyMethod("take")] + public static RubyArray/*!*/ Take(IList/*!*/ self, [DefaultProtocol]int count) { + if (count < 0) { + throw RubyExceptions.CreateArgumentError("attempt to take negative size"); + } + return new RubyArray(self, 0, Math.Min(count, self.Count)); + } + + // The count is a long in MRI (NUM2LONG): past an int it takes the whole Array, past a long it + // is a RangeError. + [RubyMethod("take")] + public static RubyArray/*!*/ Take(IList/*!*/ self, [NotNull]System.Numerics.BigInteger count) { + if (count < Int64.MinValue || count > Int64.MaxValue) { + throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + } + if (count.Sign < 0) { + throw RubyExceptions.CreateArgumentError("attempt to take negative size"); + } + return new RubyArray(self, 0, self.Count); + } + [RubyMethod("last")] public static object Last(IList/*!*/ self) { return self.Count == 0 ? null : self[self.Count - 1]; diff --git a/Util/array-take-matrix.rb b/Util/array-take-matrix.rb new file mode 100644 index 000000000..efcfc7873 --- /dev/null +++ b/Util/array-take-matrix.rb @@ -0,0 +1,85 @@ +# Differential matrix for Array#take, which is Array's own in CRuby (rb_ary_take: the count through +# NUM2LONG, a negative one refused, then rb_ary_subseq) rather than Enumerable's walk with #each. +# Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/array-take-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/array-take-matrix.rb > /tmp/ir.txt 2>&1 +# diff /tmp/mri.txt /tmp/ir.txt + +def t(label) + print label.ljust(46), ' => ' + begin + puts yield.inspect + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +A = [1, 2, 3, 4] + +class Sub < Array; end +class OwnEach < Array + def each = raise("each called") +end +class OwnSize < Array + def size = 99 + def length = 99 + def [](*) = :own +end +class ToInt + def to_int = 2 +end +class BadToInt + def to_int = "2" +end + +t('take(2)') { A.take(2) } +t('take(0)') { A.take(0) } +t('take(4), take(9)') { [A.take(4), A.take(9)] } +t('empty take(3)') { [].take(3) } +t('take(-1)') { A.take(-1) } +t('take(-1) of an empty one') { [].take(-1) } +t('take(2.9)') { A.take(2.9) } +t('take(-0.5)') { A.take(-0.5) } +t('take(nil)') { A.take(nil) } +t('take("2")') { A.take("2") } +t('take(:a)') { A.take(:a) } +t('take(to_int)') { A.take(ToInt.new) } +t('take(bad to_int)') { A.take(BadToInt.new) } +t('take(BasicObject)') { A.take(BasicObject.new) } +t('take(2**40)') { A.take(2**40) } +t('take(2**64)') { A.take(2**64) } +t('take(-2**64)') { A.take(-2**64) } +t('take(Float::INFINITY)') { A.take(Float::INFINITY) } +t('take(Float::NAN)') { A.take(Float::NAN) } +t('take(2r)') { A.take(2r) } +t('take()') { A.take } +t('take(1, 2)') { A.take(1, 2) } +t('take with a block') { A.take(2) { :ignored } } +t('a new Array') { r = A.take(4); [r.equal?(A), r.class] } +t('a change to it stays its own') { r = A.take(2); r << 9; [r, A] } +t('a frozen one') { f = [1, 2, 3].freeze; r = f.take(2); [r, r.frozen?] } +t('a subclass') { r = Sub[1, 2, 3].take(2); [r, r.class] } +t('a subclass with its own #each') { OwnEach[1, 2, 3].take(2) } +t('a subclass with its own #size, #[]') { OwnSize[1, 2, 3].take(2) } +t('nil elements') { [nil, nil, 1].take(2) } +t('owner, arity, parameters') { m = A.method(:take); [m.owner, m.arity, m.parameters] } +t('backtrace label') { A.take(-1) rescue $!.backtrace_locations.first(2).map(&:label) } +t('Enumerable#take of a Range') { (1..9).take(3) } +t('Enumerable#take of a Hash') { { a: 1, b: 2 }.take(1) } +t('a redefined Enumerable#take') do + module Enumerable; alias __saved_take__ take; def take(n) = :enum; end + begin + [A.take(1), (1..3).take(1)] + ensure + module Enumerable; alias take __saved_take__; remove_method :__saved_take__; end + end +end +t('a redefined Array#each') do + class Array; alias __saved_each__ each; def each = raise("each"); end + begin + A.take(2) + ensure + class Array; alias each __saved_each__; remove_method :__saved_each__; end + end +end From 52f4f22e52f8b73a3f43149dfc620b2d36ad1edd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:44:35 +0000 Subject: [PATCH 203/439] Ledger: perf/arymin landed (clock only, not gated); gap 15: Array#min's 6x was the survey's noise Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a5d3a0018..e09249ccc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1039,8 +1039,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Hash#sort_by` (2.4 -> 1.9), `Range#sort_by` (2.9 -> 2.3) and `Hash#max_by(2)` (3.1 -> 2.6) are done too (perf/hsortby, see Landed). Survey of 2026-11-27 (one round): the Ruby rows above 4x CRuby are `Array#dig` into a Hash (9.2), `String(nil)`/`String(5)` (8.8, 6.7), - `Array#sum` (8.0) and with a block over Floats (7.1) or Integers (4.4); `Array#min` (6.0) - and `Array#take` (4.1, Enumerable's C# take: CRuby's is Array's own) are C#, /perf-step's. + `Array#sum` (8.0) and with a block over Floats (7.1) or Integers (4.4). Of the C# rows, + `Array#min` (6.0 in that one round) is 2.0x measured (72 ns against 36, as `max`): the + survey's noise, not a slow path; `Array#take` (4.1) is done (perf/arymin, see Landed). `Array#to_h { }` is done too (4.7 -> 2.3), and `min_by`/`max_by` (3.1 -> 2.2), and their count form (`min_by(2)` 3.8 -> 2.9 after the review fix below). Open beside speed: `min_by(n)`'s tie order is input order, MRI's nmin selection orders ties its own way. `take_while`/`drop_while` done (2.6 -> 2.2, @@ -1796,6 +1797,18 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/arymin (/perf-step, 2026-11-27, on ed49c52) - `Array#take` is Array's own, as MRI's + `rb_ary_take`** - clock only, not gated. Array inherited Enumerable's C# take, a walk of + #each through a Proc: `[1, 2, 3, 4].take(2)` 248.0 -> 83.1 ns (CRuby 71.5), `first_n`, `min`, + `max`, `minmax` within the noise. Six cases of `Util/array-take-matrix.rb` (new) now print + CRuby's output: the owner, the backtrace label, a subclass's own #each and a redefined + Array#each not called, a redefined Enumerable#take not reaching Arrays, `take(2**40)`. Left: + nil's and Infinity's conversion messages (the protocol's, as for `first`). The same in four + modes and R2R; array-step, array2, enum, enum-next, enumerable2, osr-array and hot-shapes + unchanged; ruby/spec core/array and core/enumerable the same examples on both builds. + `Array#min`, the other row the survey put far from CRuby, measured 2.0x CRuby, not 6.0x, and + was left: its Fixnum path is there, what remains is the call. + - **perf/hsortby (/perf-core, 2026-11-27, on 5472a50) - `sort_by`, `min_by(n)` and `max_by(n)` of a Hash, a Range or an Enumerator through the C# merge sort** (the gap 15 survey's largest Ruby row in nanoseconds over CRuby: `Hash#sort_by` +1250 ns). The generic walk made From 9ebaaf67c0b9f3bb1793b31b3b498887005ede55 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:45:47 +0000 Subject: [PATCH 204/439] Kernel#binding through a Method object raises, as in MRI MRI's Kernel#binding needs a Ruby caller: called through a Method object (method(:binding).call, Kernel.instance_method(:binding).bind_call(self), #bind(self).call, #to_proc.call) the caller is Method#call, and MRI raises RuntimeError "Cannot create Binding object for non-Ruby caller". IronRuby handed the Method#call site's scope to it and returned a Binding of the code that made the call. send, __send__ and an alias still bind the caller, in MRI and here. A library method can now say so with [RequiresRubyCaller]; Method#call's rule (RubyMethod.BuildInvoke) raises for one, and the method-object fast dispatcher leaves it to that rule. Both are decided when the rule or the dispatcher is built; nothing is added to a call. Util/forward-rest-matrix.rb now agrees with CRuby 4.0 (binding-lvar and refinement-binding matrices unchanged); core/method, unboundmethod, binding, proc and Kernel#binding specs pass, as do the 201 method, proc, binding, eval and send IronRuby.Tests; Method_BindingNonRubyCaller1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 47 +++++++++++++++++++++ Src/Libraries/Builtins/KernelOps.cs | 1 + Src/Ruby/Builtins/RubyMethod.cs | 27 ++++++++++++ Src/Ruby/Runtime/Attributes.cs | 10 +++++ Src/Ruby/Runtime/Calls/LibraryDispatcher.cs | 3 +- 6 files changed, 88 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 99db70d78..27296b13b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1150,6 +1150,7 @@ public Tests(Driver/*!*/ driver) { Kernel_ConversionsInjectZip1, Kernel_ConversionsRoundingStep1, Method_OptionalAndKeywordParameters1, + Method_BindingNonRubyCaller1, Method_OptionalAndKeywordParameters2, Range_MinMaxInclude1, Integer_StepMatchString1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index f6de03606..b50682eab 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -6429,6 +6429,53 @@ public void Range_MinMaxInclude1() { "); } + /// + /// Kernel#binding called through a Method object (Method#call, bind, bind_call, to_proc) has no + /// Ruby caller to bind, and MRI raises RuntimeError; send and an alias still bind the caller. + /// + public void Method_BindingNonRubyCaller1() { + TestOutput(@" +require 'ruby4' +def t(l) + r = yield + p [l, r.class, (r.local_variable_get(:x) rescue $!.class)] +rescue => e + p [l, e.class, e.message] +end +x = 1 +p x +t(:send) { send(:binding) } +t(:__send__) { __send__(:binding) } +t(:public_send) { public_send(:binding) } +t(:method_call) { method(:binding).call } +t(:bind_call) { Kernel.instance_method(:binding).bind_call(self) } +t(:to_proc) { method(:binding).to_proc.call } +t(:unbound_bind) { Kernel.instance_method(:binding).bind(self).call } +t(:instance_eval) { instance_eval { binding } } +t(:tap) { [1].map(&method(:binding)) rescue $! } +class Object; alias bnd binding; end +t(:alias) { bnd } +t(:alias_method) { method(:bnd).call } +t(:singleton) { Kernel.method(:binding).call } +t(:caught) { begin; method(:binding).call; rescue RuntimeError => e; e.class.ancestors.include?(StandardError); end } +", @" +1 +[:send, Binding, 1] +[:__send__, Binding, 1] +[:public_send, NoMethodError, ""private method 'binding' called for main""] +[:method_call, RuntimeError, ""Cannot create Binding object for non-Ruby caller""] +[:bind_call, RuntimeError, ""Cannot create Binding object for non-Ruby caller""] +[:to_proc, RuntimeError, ""Cannot create Binding object for non-Ruby caller""] +[:unbound_bind, RuntimeError, ""Cannot create Binding object for non-Ruby caller""] +[:instance_eval, Binding, 1] +[:tap, ArgumentError, NoMethodError] +[:alias, Binding, 1] +[:alias_method, RuntimeError, ""Cannot create Binding object for non-Ruby caller""] +[:singleton, RuntimeError, ""Cannot create Binding object for non-Ruby caller""] +[:caught, TrueClass, NoMethodError] +"); + } + /// /// A method with optional positional parameters and keywords (`def m(a, b = 2, k: 3)') keeps its /// optionals as optional parameters; a keyword call that leaves one out has its keyword hash moved diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index 2182b6a1d..c2b23af81 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -935,6 +935,7 @@ internal static object CreateCanonicalRational(RubyContext/*!*/ context, BigInte [RubyMethod("binding", RubyMethodAttributes.PrivateInstance)] [RubyMethod("binding", RubyMethodAttributes.PublicSingleton)] + [RequiresRubyCaller] public static Binding/*!*/ GetLocalScope(RubyScope/*!*/ scope, object self) { var result = Binding.Create(scope, scope.SelfObject); diff --git a/Src/Ruby/Builtins/RubyMethod.cs b/Src/Ruby/Builtins/RubyMethod.cs index bb1ba09d3..bb54df486 100644 --- a/Src/Ruby/Builtins/RubyMethod.cs +++ b/Src/Ruby/Builtins/RubyMethod.cs @@ -183,6 +183,19 @@ internal void BuildInvoke(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ Assert.NotNull(metaBuilder, args); Debug.Assert(args.Target == this); + if (_methodMissingName == null && RequiresRubyCaller(_info)) { + // MRI: a method object's call is not a Ruby caller, and Kernel#binding has nothing to bind + metaBuilder.AddRestriction(Ast.AndAlso( + Ast.TypeIs(args.TargetExpression, typeof(RubyMethod)), + Ast.Equal(Ast.Property(Ast.Convert(args.TargetExpression, typeof(RubyMethod)), InfoProperty), AstUtils.Constant(_info, typeof(RubyMemberInfo))) + )); + metaBuilder.SetError(Ast.New( + typeof(RuntimeError).GetConstructor(new[] { typeof(string) }), + AstUtils.Constant("Cannot create Binding object for non-Ruby caller") + )); + return; + } + // A call to these methods depends on the method, the name it is called by and the arguments (self included), not on // which Method object holds them. Each `instance_method(:m).bind(obj).call` makes a new Method, so a rule that took // the Method and its receiver as constants was bound and compiled anew for every call of such a site. @@ -235,6 +248,20 @@ internal void BuildInvoke(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ } } + internal static bool RequiresRubyCaller(RubyMemberInfo/*!*/ info) { + var library = info as RubyLibraryMethodInfo; + if (library == null) { + return false; + } + foreach (var overload in library.MethodBases) { + var method = overload.ReflectionInfo; + if (method != null && method.IsDefined(typeof(RequiresRubyCallerAttribute), false)) { + return true; + } + } + return false; + } + private static bool IsReceiverIndependent(RubyMemberInfo/*!*/ info) { Type type = info.GetType(); return type == typeof(RubyLibraryMethodInfo) || type == typeof(RubyMethodInfo) || type == typeof(RubyLambdaMethodInfo); diff --git a/Src/Ruby/Runtime/Attributes.cs b/Src/Ruby/Runtime/Attributes.cs index 3aadfdc88..4412799d1 100644 --- a/Src/Ruby/Runtime/Attributes.cs +++ b/Src/Ruby/Runtime/Attributes.cs @@ -342,6 +342,16 @@ public AliasMethodAttribute(string/*!*/ newName, string/*!*/ oldName) { public sealed class RubyStackTraceHiddenAttribute : Attribute { } + /// + /// Marks a library method that needs a Ruby caller's frame and that MRI refuses to run for a + /// caller that is not Ruby code: Kernel#binding called through a Method object + /// (Method#call, UnboundMethod#bind_call, Method#to_proc) raises RuntimeError "Cannot create + /// Binding object for non-Ruby caller". Checked when the Method's call rule is built. + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public sealed class RequiresRubyCallerAttribute : Attribute { + } + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public class DefaultProtocolAttribute : Attribute { } diff --git a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs index 9332c50a9..c6615504b 100644 --- a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs @@ -1154,7 +1154,8 @@ internal static object TryCreateMethodObjectCall(RubyCallAction/*!*/ binder, Typ if (infoType == typeof(RubyLibraryMethodInfo)) { var libraryMethod = (RubyLibraryMethodInfo)info; - if (TracePoint.CCallTracing || DispatchIntrinsics.IsSend(libraryMethod)) { + if (TracePoint.CCallTracing || DispatchIntrinsics.IsSend(libraryMethod) || RubyMethod.RequiresRubyCaller(libraryMethod)) { + // (Kernel#binding through a Method object is an error the rule raises: RubyMethod.BuildInvoke) return null; } return TryCreate(binder, delegateType, signature, libraryMethod, receiverClass, receiver, RubyCallAction.ClrReceiverTest.Plain, From 374584c586b326807b20cbc69f7d845a890506df Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:47:44 +0000 Subject: [PATCH 205/439] LEDGER: perf/crubydiff's fourth round The causes fixed, what is left with the reason, and the behaviour that changed outside a message for the gate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 0d7661d2a..cc34270e8 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2355,6 +2355,34 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has transcoding error message encodings; convpath element encodings; Marshal bytes of raised exceptions; IO#write into UTF-16/32 (the same bytes, a different error); Thread#backtrace contents; Lazy.ancestors and Lazy#take & co. owner; String#<< has an object overload. + Fourth round (2026-11-27, on claude/happy-gauss-95wm2j 4320d4a + the third): the rows round 5's + gate still saw. string-search 115 -> 63 lines, forward-rest -> same. + - StringScanner from a scan pointer inside a character matches the rest as a string of its own, + as MRI's strscan does (RubyRegex.MatchWindow's allowBroken, for this caller only; a subject + broken as a whole still raises). StringScanner_InsideCharacter1. + - StringScanner over a subject made shorter than the scan pointer: nil scans, "" rest, nil bol?, + charpos past the end. StringScanner_ShorterSubject1. + - StringScanner with a String pattern of an incompatible encoding raises (rb_enc_check). + StringScanner_LiteralEncoding1. + - Kernel#binding through a Method object raises RuntimeError "Cannot create Binding object for + non-Ruby caller" ([RequiresRubyCaller], checked when Method#call's rule is built). + Method_BindingNonRubyCaller1. + Left, with the reason: string-search's last 63 lines are /./ and \A. on a lone split byte (an + invalid byte decodes to a lone surrogate, which the translator's '.' excludes: the regexp + translator's, not the scanner's); int-matrix's hash values (CRuby seeds them per process), its + Integer.instance_methods(false) (#hash, #step, #to_c are C# fast paths defined on Integer, owned by + Kernel and Numeric in CRuby) and (2**100).equal? (a Bignum is a boxed BigInteger, compared and + identified by value); caller-matrix as in the third round; stdre's URI names (the vendored + uri/rfc3986_parser.rb inlines SEG, since .NET has no \g, so CRuby's (?...){0} is not + there); eval-matrix's "character class has duplicated range" (Onigmo's CC_DUP warning is not + implemented; a rule that is not exactly Onigmo's would warn where CRuby does not); glob-matrix + (the row lists the runtime's own clr-debug-pipe files in /tmp); fiddle's Handle::NEXT (the + matrix's own expected difference, and CRuby answers an address); numeric-conversion's "gives + NilClass" (pinned wording). + For the gate, behaviour that changed outside a message: StringScanner's matches from inside a + character, its answers over a shortened subject, and an error for an incompatible String pattern; + Kernel#binding through Method#call/bind_call/to_proc raises; RubyRegex.MatchWindow has an + allowBroken overload. - **perf/strsearch4 (2026-11-27) - the ASCII scan's cost of round three found and mostly removed; `#byteindex`/`#byterindex` from an offset other than 0 walk from the last search, through a map From a5fec1d8d8cc7625dab507945ba39ba570afd1ce Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:49:28 +0000 Subject: [PATCH 206/439] Ledger: perf/iter3, where gap 13's fixed cost stands now Measured, nothing kept. Util/bench/iter-shapes.rb (new) times an iterator call over 1, 2 and 4 elements against CRuby, and splits the fixed part: per element IronRuby is now cheaper than CRuby, and the ~57 ns left per call is what a literal block costs its caller (the light frame's scope made or taken parked, and the Proc over it), which a stored Proc does not and CRuby's literal does not either. Publishing the parked scope with a release write instead of a compare-exchange was tried and moved nothing; the ledger says what would take the cost (a Proc that needs no method scope until it escapes, gap 16's design). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Util/bench/iter-shapes.rb | 80 +++++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 21 ++++++++++ 2 files changed, 101 insertions(+) create mode 100644 Util/bench/iter-shapes.rb diff --git a/Util/bench/iter-shapes.rb b/Util/bench/iter-shapes.rb new file mode 100644 index 000000000..1c4fccb65 --- /dev/null +++ b/Util/bench/iter-shapes.rb @@ -0,0 +1,80 @@ +# The fixed cost of calling an iterator with a literal block (gap 13, round thirty-seven, perf/iter3): ns per call of a +# method that calls the iterator once over 1, 2 or 4 elements; the caller is a `while' loop. +# +# ruby Util/perf/ab.rb Util/bench/iter-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# +# each/times/map: Array#each, Integer#times, Array#map with `{ |x| s += x }' (map: `{ |x| x + 1 }'); call: the same +# method with no iterator (`s += a[0]'), the floor a method call costs; empty: each with `{ }'. +# nb0, nbp, nbl: a light method that ignores its block called with none, with a stored Proc (`&P') and with a literal +# `{ }'; eachp, eachl: Array#each over one element with `&P' and with `{ }'. A literal costs its caller what a stored +# Proc does not: the method's scope made (or taken parked) and the Proc made over it (round thirty-seven, perf/iter3). +$stdout.sync = true + +P = proc { } +class O + def nb; 1; end + def nb0(a) = nb + def nbp(a) = nb(&P) + def nbl(a) = nb { } + def eachp(a) = a.each(&P).size + def eachl(a) = a.each { }.size + def each(a); s = 0; a.each { |x| s += x }; s; end + def times(k); s = 0; k.times { |j| s += j }; s; end + def map(a) = a.map { |x| x + 1 }.size + def empty(a); a.each { }; 1; end + def call(a); s = 0; s += a[0]; s; end +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the seven sections as the +# time is. See Util/perf/instructions.rb. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-12s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +o = O.new +N = (ENV['N'] || 1_000_000).to_i +a1 = [1]; a2 = [1, 2]; a4 = [1, 2, 3, 4] + +t("call", N) { |n| i = 0; s = 0; while i < n; s += o.call(a1); i += 1; end; s } +t("empty1", N) { |n| i = 0; s = 0; while i < n; s += o.empty(a1); i += 1; end; s } +t("each1", N) { |n| i = 0; s = 0; while i < n; s += o.each(a1); i += 1; end; s } +t("each2", N) { |n| i = 0; s = 0; while i < n; s += o.each(a2); i += 1; end; s } +t("each4", N) { |n| i = 0; s = 0; while i < n; s += o.each(a4); i += 1; end; s } +t("times1", N) { |n| i = 0; s = 0; while i < n; s += o.times(1); i += 1; end; s } +t("times2", N) { |n| i = 0; s = 0; while i < n; s += o.times(2); i += 1; end; s } +t("times4", N) { |n| i = 0; s = 0; while i < n; s += o.times(4); i += 1; end; s } +t("map1", N) { |n| i = 0; s = 0; while i < n; s += o.map(a1); i += 1; end; s } +t("map2", N) { |n| i = 0; s = 0; while i < n; s += o.map(a2); i += 1; end; s } +t("map4", N) { |n| i = 0; s = 0; while i < n; s += o.map(a4); i += 1; end; s } +t("nb0", N) { |n| i = 0; s = 0; while i < n; s += o.nb0(a1); i += 1; end; s } +t("nbp", N) { |n| i = 0; s = 0; while i < n; s += o.nbp(a1); i += 1; end; s } +t("nbl", N) { |n| i = 0; s = 0; while i < n; s += o.nbl(a1); i += 1; end; s } +t("eachp", N) { |n| i = 0; s = 0; while i < n; s += o.eachp(a1); i += 1; end; s } +t("eachl", N) { |n| i = 0; s = 0; while i < n; s += o.eachl(a1); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 3ac58bd80..6c90d2383 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1010,6 +1010,27 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has takes Permute from 124.5 to 53.9 MB per iteration and costs 3.8% more instructions, its time level (1.00 over six rounds), as perf/deadconst found. Left: `each_with_index` (the prelude's, `*args, &block`), `inject`, and `upto`/`downto`'s entry, which is not their bytes. + perf/iter3 (round thirty-seven, measured, nothing kept; `Util/bench/iter-shapes.rb`) put + the gap where it stands now, ns per call of a method that calls the iterator, alternating + rounds: `each` over 1, 2, 4 elements 128, 159, 184 against CRuby's 78, 108, 176 (1.64, + 1.47, 1.05), `times` 1.40, 1.27, 1.05, `map` 1.42, 1.16, 0.88. Per element IronRuby is now + cheaper than CRuby (about 13 ns against 30); what is left is the fixed part, and it is + not the iterator, the yield or the BlockParam: a light method that ignores its block, + called with a literal `{ }` (`nbl`), is 116 ns against 59 with a stored Proc (`nbp`) and 39 + with none, where CRuby's literal costs nothing (36, 36, 32); `a.each { }` 120 against + `a.each(&P)` 84. With every light frame off (`IR_LIGHT_FRAMES=0`) the stored Proc costs + 98 and the literal 107: once the method has a scope the literal adds almost nothing. So + the ~57 ns is the caller's scope, which a light frame makes (or takes parked) because the + literal's Proc is over it, and the Proc made over it. Not the parking protocol's atomics: + publishing the parked scope with a release write instead of a compare-exchange + (`EndPark`) moved nothing in eight rounds (1.03, 0.92, 1.02 overlapping), and with parking + off (allocating scope and Proc) the time is the same. What would take it is a Proc that + needs no method scope until something can see one - a literal whose body reads and writes + only its own locals and the method's through the frame, given to a callee that does not + keep it - with the scope made, from the frame's live locals, when it escapes (`&b`, + `binding`, a `return` from the block, a TracePoint). That is the light frame's lazy scope + reached from a Proc instead of from the frame's own code: gap 16's design, not one step. + 14. **DeltaBlue: `Vector#each`** (`(@first_idx..(@last_idx - 1)).each { |i| yield @storage[i] }`) is about 20% of its samples by nearest Ruby frame (8.9% the method, 11.3% its block), and no call site owns more than 1.2% of the 24% in From cf81c90af818537bd83d01260cee7565e51174a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 21:45:14 +0000 Subject: [PATCH 207/439] Ledger: round 5's gate passes (4320d4a against master) IronRuby.Tests, the matrices in 13 modes, the probes, all five ruby/spec suites, the timing and start-up pass on 4320d4a, after the three fixes the gate itself made (ForwardedRest off by default, the constants rewriter's stack guard, Format_Char2's expectation). The matrix run hit its time limit in its last stage; its runs were classified with the script's own verdicts and the unfinished matrices run again, and the string race matrix, which differs from run to run by design, was compared over five runs of each tree. Two micro-table rows slower in both orders on a loaded run were level in eight pinned alternating rounds. Start-up wins back round 4's -e 1 loss. Round 5's entries are marked gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 102 +++++++++++++++++++++++++++++++++----------- 1 file changed, 76 insertions(+), 26 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 660f96919..fca12495b 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -930,7 +930,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the next idea. A light caller's call of a JIT-typed method with a Float argument (`selfcall` of micro-table) is 3% slower by median through the dispatcher than through the rule, with the same bytes. - Round of 2026-11-27 (see Landed, perf/twospeed, not gated): found and fixed - an interpreted shared rule + Round of 2026-11-27 (see Landed, perf/twospeed): found and fixed - an interpreted shared rule left ahead of its compiled one in a site's rules, run on every call to fail (DLR patch 0111). `neq2` still varies 59-102 ns on both builds, which is something else. Round of 2026-11-27, second (perf/twospeed2, a finding, no code): `neq2`'s spread is the CLR's dynamic PGO, @@ -994,7 +994,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the walk about 12% faster and a megamorphic call without a block 2.2 times slower: reverted. A per-site table from class to dispatcher is worth at most about 10% of the walk. `Prism.parse` itself (not in the shape) is 8 times CRuby's. - Round thirty-seven (perf/iter, see Landed, not gated) measured the four parts on one + Round thirty-seven (perf/iter, see Landed) measured the four parts on one element against CRuby: a literal inside a block 111 ns and 302 B against 44 (`n.times { o.e { |c| s += c } }`), `each1` 131/77 B against 72, a Ruby-level iterator 125/77 B against 55, `upto1` 151/389 B against 70, `any1` 149/374 B against 52, `find1` 292/885 B @@ -1453,13 +1453,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has RubyGems' own Ruby (binds ~100 ms inclusive in `-e 1`, the running of precompiled code), the files `gem list` requires, and the JIT, which the release image already halves. A next attempt should measure on the release image, or say why the R2R host stands in for it. - 2026-11-27, perf/startup3 (Landed, not gated): measured on the release image as perf/startup2 + 2026-11-27, perf/startup3 (Landed): measured on the release image as perf/startup2 asks. FindCopyingClasses' type scan is now generated attributes, and the default-spec cache is validated without a glob or a File::Stat per gemspec. Main-thread instructions -2.0% / -2.0% / -1.8% on `gem list` / `require "irb"` / irb, and -2.8% on `-e 1` (release image). What is left of RubyGems' boot is its own class bodies (specification, requirement, platform: ~40 ms of `-e 1`) and rbconfig (~12 ms). - 2026-11-27, perf/startup4 (Landed, not gated): RubyGems' boot files are all in the startup + 2026-11-27, perf/startup4 (Landed): RubyGems' boot files are all in the startup library. Their self time is first binds, two `super` rules, specification.rb's string `eval` and the R2R host's JIT. rbconfig.rb no longer uses CLR interop: -0.3 to -0.9% main-thread instructions on all five commands. Next leads: the 4,989 CLR member lookups of ruby4.rb in `-e 1` @@ -1596,7 +1596,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has two ConditionalWeakTable entries onto the Proc measured nothing. Next idea: a lock-free test for a singleton class with no mixins that does not define the name itself (it resolves as its superclass), at most about 10%. - Round thirty-seven (see Landed, perf/singleton, not gated): that idea, taken further - a + Round thirty-seven (see Landed, perf/singleton): that idea, taken further - a singleton class with no modules of its own answers every name it has no entry for from its superclass's lookup cache, lock-free, and the shared rule's test reads that cache. The profile behind it (callgrind with the CLR's perf map, 300 steady-state `os_app` objects, @@ -1774,6 +1774,56 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, + perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, + perf/twospeed and its note, perf/extiter4 and 5, perf/fiberstart, perf/iter, perf/strsearch3 and 4, + perf/nbody, perf/lconst, perf/startup3 and 4, perf/singleton; the rejected perf/kwprologue and + perf/regexlight, ledger only): the branch `claude/happy-gauss-95wm2j` at 4320d4a against master f81fc19, + Release net10.0, four cores: **PASS, after three fixes the gate made** (1eb1194 is the merge): + - 4320d4a: perf/forward's ForwardedRest is off by default (`IR_FORWARD_REST=1`): the gate's probes read + the rest parameter after the call through `instance_eval("args")`, `send(:eval, ...)`, an alias of + eval and a TracePoint's `:return` binding, and saw the callee's change (see "Caught by the gate (round + thirty-seven, round 5)"; `Util/forward-rest-matrix.rb`). + - b493c0b: perf/lconst's CompiledConstantsRewriter overflowed the stack on DeepNesting1 (begin/rescue + 500 deep, compiled up front), which killed its test process; a tree too deep is now compiled as it is. + - 6369856: Format_Char2 expected the RangeError that perf/crubydiff had rightly made CRuby 4.0's + ArgumentError "invalid character" (`%c` of 0x100 in ISO-8859-1). + The merge itself: perf/iter's parked nested Procs and perf/nbody's reused Procs of outlinable blocks + meet in BlockDefinition (resolved by hand: nbody's ParkSlot in the InstantiateParkedBlock branch, iter's + branches after it, every nested Proc through KeepEnclosingProcs); a probe file of escaping, kept, bound + and threaded nested Procs under hot outlined blocks prints CRuby's output with the JIT on and off, on + the R2R host and with `IR_NESTED_PROCS=0`, `IR_PARKED_BLOCK_SCOPES=0` and `IR_LIGHT_FRAMES=0`. + perf/lsite's DLR patch was renumbered 0112 (twospeed's is 0111); all 21 apply in order to a clean DLR. + ReflectionCache.Generated.cs as merged is what ClassInitGenerator writes. + IronRuby.Tests (`parallel-tests.sh`): 1,377 tests, every one executed, none failed (INCOMPLETE is the + driver's `Current culture: ` banner, as before). + `gate-matrices.rb --all`, 180 units in 13 modes (the six default ones, and `IR_NESTED_PROCS`, + `IR_PARKED_BLOCK_SCOPES`, `IR_SINGLETON_LOOKUP`, `IR_SHARE_TAIL`, `IR_SEALED_CONSTANTS`, `IR_SAFE_SWITCH`, + `IR_COPIED_TABLE` off). The run reached its time limit in its last stage, so its 5,017 runs were classified + with the script's own verdict code (2,015 same, 273 baseline) and the six matrices it had not finished or + confirmed were run again in all 13 modes: keyword-light, keyword-rest-light and kw-prologue same in all; + thread-backtrace baseline and one flaky (master's output alone); callable-parameters the prelude line of + `Kernel#puts` again (ruby4.rb:13578; CRuby says nil). string-race-matrix races its writers on purpose + and differs between runs, so it was compared over five runs of each tree: rows not always ok 108 -> 86, + not-ok results 501 -> 420, lost writes 104 -> 0, no writer raising; one new kind, `inspect` racing + `force_encoding` raising System.Text.EncoderFallbackException in 5 of 5 (master's writer raised there + instead), one of gap 39's readers that still read unheld. + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against master (Src/StdLib, Util/bench, AWFY): light frames 91.7% -> 94.1% (668 up, one down: + Math.__ir_log__, which perf/crubydiff's rb_math_log grew past the multiple-assignment limit for a large + light body), method JIT compiles 11.7% -> 12.2% (183 up, none down). + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.958 and 0.964 + (Richards 0.88 / 0.85, DeltaBlue 0.89 / 0.94, CD 0.97 / 0.86); none more than 5% slower in both (Sieve + 1.026 / 1.039, which perf/sieve of round 6 takes to 0.47). Alone, five rounds in each order, medians + new/base: NBody 1.002 / 0.965, List 1.005 / 1.052, Bounce 0.978 / 0.967, Richards 0.963 / 0.905. + micro-table in both orders: `cmp` 1.19 / 1.20 and `ivar_rw` 1.22 / 1.10 slower in both on a loaded run; + eight alternating rounds of `ab.rb` on a quiet machine, pinned: 0.98 and 1.03 (`empty` 1.10), all + overlapping, so the load's. + Start-up on the R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 501 -> 483 and + 477 -> 467, `gem --version` 532 -> 547 and 552 -> 551, `gem list` 935 -> 921 and 950 -> 955, + `require "irb"` 953 -> 958 and 974 -> 932, irb 1+1 1063 -> 1037 and 1091 -> 1047: round 4's `-e 1` + loss is won back (perf/startup3 and 4). + - **Gate of 2026-11-27 for round 4 of round thirty-seven** (perf/strdup, perf/strsearch2, perf/extiter2 and 3, perf/lframe, perf/lexical2 and 3, perf/kwrest, perf/jitscreen and 2, perf/deadconst2, perf/permute, perf/havlak, perf/dmethjit2, perf/jitsettle; the rejected @@ -1811,7 +1861,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 1180 -> 1169. None more than 5% slower in both runs, but `-e 1` is 4-5% (20-28 ms) slower in both: open, for perf/startup3 and 4 (round 5) to win back, and measured again at round 5's gate. -- **perf/strswitch (2026-11-27, not gated) - a String's representation switch cannot lose a write** +- **perf/strswitch (2026-11-27, gated 2026-11-27 (round 5's gate entry)) - a String's representation switch cannot lose a write** (gap 39's cause 2; switch `IR_SAFE_SWITCH`). A switch between characters and bytes (a reader's getbyte, bytes, index, unpack... or a writer's) now converts holding the content it switches from and publishes the new one only by compare-exchange on `_rawContent` against it @@ -1837,7 +1887,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has unheld (`Replace`, the end of `Transcode`) is safe against a reader's switch only because its last store is unconditional. -- **perf/strcow (2026-11-27, not gated) - a String slice copied while the content is held; a +- **perf/strcow (2026-11-27, gated 2026-11-27 (round 5's gate entry)) - a String slice copied while the content is held; a long tail slice shares the array, as MRI's** (gap 24's dup note). Asked for: copy-on-write content for dup, `+` and slices. Found: it is there already - CharArrayContent and BinaryContent share their array on Clone and on a long slice and copy on the first write (ContentState, the @@ -1861,7 +1911,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has MutableString and String IronRuby.Tests: PASSED. Left: other readers of a content (index, each char, the byte views) still read it unheld. -- **perf/dupcost (2026-11-26, not gated) - `String#dup` of a bare string: one look for instance +- **perf/dupcost (2026-11-26, gated 2026-11-27 (round 5's gate entry)) - `String#dup` of a bare string: one look for instance data, and the copy constructor** (gap 24's dup note). Where the time went, by callgrind with the CLR's perf map over one `str_dup` section of `dup-shapes.rb` (instructions per call, the shape's driver included; the scratch profiler kept the section's files and named JIT frames @@ -1910,7 +1960,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has MRI's FL_EXIVAR may stay set after the removal, which would send it through rb_obj_dup. - **perf/forward (2026-11-27) - a rest parameter passed on where nothing can see it again is the callee's rest parameter; a block-passing call's hoisted splat is fresh** (gap 36 and gap 16's second part; - `IR_FORWARD_REST=0` turned the first off) - timed, not gated. **The first part is off by default since round 5's + `IR_FORWARD_REST=0` turned the first off) - timed, gated 2026-11-27 (round 5's gate entry, its first part off by default). **The first part is off by default since round 5's gate (2026-11-27), behind `IR_FORWARD_REST=1`**: `Util/forward-rest-matrix.rb` (new, from the gate's probes) reads the rest parameter again after the call by names ForwardedRest's walk cannot see - `instance_eval("args")`, `send(:eval, "args")`, an alias of `eval` (any call may ask for the frame's scope), a TracePoint's binding at @@ -1952,7 +2002,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/timeout (2026-11-27) - `Timeout.timeout` wakes its watcher thread only when it has to** (`Src/StdLib/ironruby/timeout.rb`, an override that loads CRuby's file as it is and redefines two - methods of `Timeout::State`) - timed, not gated. A raise rescued through `Timeout.timeout` cost + methods of `Timeout::State`) - timed, gated 2026-11-27 (round 5's gate entry). A raise rescued through `Timeout.timeout` cost 152-164 us against CRuby's 3.1 (perf/ensure's finding). Taken apart with copies of timeout.rb (each with one thing left out; no profiler: this container refuses perf_event_open and the sampler could not be installed): without the `ensure request.finished` 21 us, without the @@ -1992,7 +2042,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the stdlib copy). - **perf/jitaref (2026-11-26) - `a[i]` in a typed body after some Array has a singleton `[]`** - - trace only, not gated (the census cannot see it: it loads no library). The side finding of + - trace only, gated 2026-11-27 (round 5's gate entry) (the census cannot see it: it loads no library). The side finding of perf/jitconst: app-shapes declined `OptionParser.top` (`@stack[-1]`) and `.base`, and rejected `Gem::Requirement#none?`, all at "[] on a RubyArray". The typed body takes `recv[i]` with any Integer index already (negative from the end, out of range nil: `JitRuntime.IndexInt`); in @@ -2031,7 +2081,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has anywhere - the cost the generic site pays in the same state; the other element methods (`[]=`, `fetch`, `size`...) still use the class-wide test. - **perf/twospeed (2026-11-27) - an interpreted rule stuck before its compiled one runs compiled - (gap 12, DLR patch 0111)** - not gated. What decides the speed: `recv != other` over four or eight plain + (gap 12, DLR patch 0111)** - gated 2026-11-27 (round 5's gate entry). What decides the speed: `recv != other` over four or eight plain classes is served by IronRuby's shared rule (one rule whose test is a set of class versions, handed to every site that calls the method on another class, RubyCallAction). `DynamicUtils.LightBind` makes it interpreted; past its count it compiles in the background and then fails its test once compiled, so that @@ -2066,7 +2116,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ../dlr apply Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch`); every interpreted rule in every program is affected. AWFY was not timed; Bounce was once seen bimodal (gap 12's note). -- **perf/jitprobe (2026-11-26) - the stub's generic cost is not the interpreter's** - not gated. A probe +- **perf/jitprobe (2026-11-26) - the stub's generic cost is not the interpreter's** - gated 2026-11-27 (round 5's gate entry). A probe (`JitStub.Probe`) times the generic body to decide whether an entry that deopts pays its way. It waited for the generic body's compile for at most 8 deopt windows, which go by in microseconds when every other call deopts, and then timed the interpreter: 4 us a call where the compiled body takes 0.16. Its @@ -2100,7 +2150,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has probes of 32 timed calls each in its first 100 ms after the compile); `GenericCompiled` now takes the stub's lock on the light compiler's thread. - **perf/fiberstart (2026-11-27) - what a fiber's start costs, found; the end of an iteration on a - fiber raised from C# and its stack walk deferred, as a cursor's is (gap 35)** - not gated. Base + fiber raised from C# and its stack walk deferred, as a cursor's is (gap 35)** - gated 2026-11-27 (round 5's gate entry). Base 8d7efda (the round-38 branch with perf/extiter5). Measured first (`Util/bench/fiber-start.rb`, new: one kind per process, blocks of 500, wall and process CPU, threads), on this four-core container: a raw CLR thread started and joined is 120-150 us whatever its stack (0, 256 KB, 1 MB, @@ -2139,7 +2189,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has in five plain runs on base and five on new (no abort, no failure). - **perf/extiter5 (2026-11-27) - Hash#select / #filter / #reject, `filter_map`, `flat_map` and - `each_with_object` take `next` on a cursor (gap 35)** - not gated. Base 1fca3c7 (the round-38 + `each_with_object` take `next` on a cursor (gap 35)** - gated 2026-11-27 (round 5's gate entry). Base 1fca3c7 (the round-38 branch at b887bc1 with perf/extiter4). Hash's own #select, #filter and #reject copy the receiver when the iteration starts, as IDictionaryOps.Filter and MRI's rb_hash_select do (a plain Hash with its compare_by_identity, the entries with their hash codes), walk the copy with @@ -2179,7 +2229,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has runs). - **perf/extiter4 (2026-11-26) - an abandoned lazy enumerator's fiber is reclaimed: its #next walks - a copy (gap 35)** - not gated. Base 3bf570d (the round-37 branch at 79a2c30 with + a copy (gap 35)** - gated 2026-11-27 (round 5's gate entry). Base 3bf570d (the round-37 branch at 79a2c30 with perf/extiter3). Measured first (`Util/bench/extiter-abandoned.rb`, new: 10,000 enumerators abandoned after one `next`, threads and RSS after three `GC.start`s): every lazy kind kept its thread for good on the base - 10,018 threads, 634-715 MB - where a generator Enumerator made in @@ -2213,7 +2263,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated; one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope @@ -2307,7 +2357,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/strsearch4 (2026-11-27) - the ASCII scan's cost of round three found and mostly removed; `#byteindex`/`#byterindex` from an offset other than 0 walk from the last search, through a map - shared with StringScanner (gap 21, round four)** - not gated. Commits 8d030d1, 103c741 on + shared with StringScanner (gap 21, round four)** - gated 2026-11-27 (round 5's gate entry). Commits 8d030d1, 103c741 on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j b887bc1 with d3b8844 merged in. 1. Round three cost an ASCII scan word by word over 10 KB (`ss_words_a`) 2.6 to 3.4% more instructions, most of it also with `IR_FAST_SEARCH=0`. Found with a per-function count: @@ -2350,7 +2400,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has failures (the one `String.try_convert` error on all three). - **perf/startup4 (2026-11-27) - RubyGems' boot files are precompiled already; rbconfig asks the host - instead of CLR interop (gap 26)** - not gated. Base c7cb16e (15285eb with perf/startup3). + instead of CLR interop (gap 26)** - gated 2026-11-27 (round 5's gate entry). Base c7cb16e (15285eb with perf/startup3). Asked: are specification.rb, requirement.rb, platform.rb, specification_record.rb and rbconfig.rb compiled at every boot? No. The startup library (`Util/aot/startup-files.txt`, written by `Util/aot/startup-files.rb` from what `-e 1`, the gem commands and irb load; built by @@ -2586,7 +2636,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has enclosing local). - **perf/jitstr (2026-11-26) - `s + "lit"` and `s << "lit"` in a body the method JIT compiles** - - census only, not gated. Behind the String literal line (101 alone) are call arguments (44, gap 1's + census only, gated 2026-11-27 (round 5's gate entry). Behind the String literal line (101 alone) are call arguments (44, gap 1's wall, perf/strlit's rejected first build) and operands of String operators: `+` 12 (about 15 with mixed forms), `<<` 11 (16 with `*` or `%` beside it), `"fmt" % x` 8, `"-" * n` 5, comparisons a few (`s == "lit"` is perf/t3's intrinsic already). Taken: `+` and `<<` with a String literal @@ -2637,7 +2687,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has For the gate: no IronRuby.Tests or spec run. A String given a singleton `+` anywhere makes every later compile of `+` bail for the life of the process (`HasPlainInstances`, as for `==`). - **perf/strsearch3 (2026-11-27) - StringScanner on a UTF-8 subject maps bytes to characters - incrementally, without switching the subject to bytes (gap 21, round three)** - not gated. + incrementally, without switching the subject to bytes (gap 21, round three)** - gated 2026-11-27 (round 5's gate entry). Commits 0c41d0f, 8822aad on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j 79a2c30 with a7b9a12 merged in. Chosen by measured size among the three items left under gap 21: a loop over 10 KB and 100 KB of UTF-8 text (CRuby / base, ms) - StringScanner word by word @@ -2684,7 +2734,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/lconst (/perf-frame, 2026-11-27) - a compiled body's constants without a cast helper** (switch `IR_SEALED_CONSTANTS`, on unless `=0`; a DLR patch, `0112-compile-rewriter`) - - instructions only, not gated. Built on 79a2c30 with claude/perf-lsite merged (980e36c). + instructions only, gated 2026-11-27 (round 5's gate entry). Built on 79a2c30 with claude/perf-lsite merged (980e36c). - **Counted first** (callgrind with `DOTNET_ReadyToRun=0`, so that CoreLib's cast helpers have names, and a caller walk of the perf map): `CastHelpers.ChkCastClass` and `ChkCastClassSpecial` are 9.2% of `fc`'s instructions (frame-cost, `-X:NoJIT`), 11.7% of @@ -2804,7 +2854,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/startup3 (2026-11-27) - start-up on the release image: a copied module's backtrace name from generated attributes; the default-spec cache validated in one pass over the directory (gap - 26)** - not gated. Base 79a2c30 (with the round's ledger, 973314a). Two commits: + 26)** - gated 2026-11-27 (round 5's gate entry). Base 79a2c30 (with the round's ledger, 973314a). Two commits: - 86e85c0: `RubyStackTraceBuilder.FindCopyingClasses` read the `Includes(Copy = true)` attributes of every type in IronRuby.Libraries the first time a backtrace named a copied module's method. That cost ~9 ms once per process (`gem list`, `require "irb"` and irb, through optparse's rescued @@ -3191,7 +3241,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has TypeError if it's not a kind of String`, run as a directory). - **perf/iter (round thirty-seven, 2026-11-26) - a block that holds a block literal reuses its scope - and the literal's Proc (gaps 13 and 6)** - instructions and bytes, not gated. A block whose + and the literal's Proc (gaps 13 and 6)** - instructions and bytes, gated 2026-11-27 (round 5's gate entry). A block whose body has a block literal (`a.each { |x| o.e { |c| s += c } }`, Richards' worker block with `DATA_SIZE.times { }`, prism's `each_child_node` walks) made a scope, a Proc and a BlockParam on every call: the literal's Proc is over the block's scope, so `BlockDefinition` never let such a @@ -3251,7 +3301,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has way a literal's Proc reaches Ruby without clearing its reusable flag. - **perf/nbody b3c20a5 55be4d2 (round thirty-eight, 2026-11-27) - a block literal with a literal - nested in it reuses its Proc when it can be outlined (gap 2)** - not gated. NBody allocated 152 MB + nested in it reuses its Proc when it can be outlined (gap 2)** - gated 2026-11-27 (round 5's gate entry). NBody allocated 152 MB per iteration, 608 bytes per `advance`; an in-process GC allocation-tick listener (EventListener on GCAllocationTick) gave RubyMethodScope 26%, Proc 26%, BlockParam 16%, Int32 16%, Double 12% of them. `advance` is a light frame whose literal blocks could park its scope with their Procs @@ -3292,7 +3342,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has wrong (NullReferenceException, a kept Proc reading another call's locals), so it does probe the rule. - **perf/singleton (round thirty-seven, 2026-11-26) - lookups on a re-versioned singleton class - answered from its superclass's cache (gaps 32, 19)** - not gated. Each definition on an object + answered from its superclass's cache (gaps 32, 19)** - gated 2026-11-27 (round 5's gate entry). Each definition on an object that gets methods of its own (OpenStruct's `define_singleton_method!` of every member) re-versions its singleton class and so empties the class's method lookup cache; every name asked again - the `singleton_method_added` hook check, `respond_to?`, the shared rules' version test - From 635862aa4c6f1f331f391e0636b0e4842bb70795 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 21:46:12 +0000 Subject: [PATCH 208/439] Ledger: drop the entries the merge of claude/perf-nbody doubled Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 55 --------------------------------------------- 1 file changed, 55 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index fc7197ccc..fe1c6481a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -3811,61 +3811,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and its Procs move between threads through `CallBlockParam` (the thread check in `InstantiateNestedParkedBlockSlow`, and the Proc[] cleared when another thread keeps); and any way a literal's Proc reaches Ruby without clearing its reusable flag. -- **perf/lframe (/perf-frame, 2026-11-26) - a cheaper method entry: the alias name and the - traced test** (switch `IR_LIGHT_ENTRY`, on unless `=0`) - instructions only, not gated. - Built on 2f8c31c. What gap 16's profiles left on every light frame, looked at on its own - with `Util/bench/frame-cost.rb` (new: a method that does nothing, one, three calls, a yield, - `block_given?`, and `String#bytesplice`), `-X:NoJIT` so that the generic bodies run. - - **Not the prologue.** perf/lsite2 put the light lambda's +158 down to zeroing its locals; - `DOTNET_JitDisasm` of the light `H#gsub` says otherwise: two 64-byte stores. What the - lambda pays up front is its closure constants (each load a bounds check and a - `CHKCASTCLASS` helper call), the frame record (`PrecompiledFrames.Enter`) and the - entry's helpers. So no `SkipLocalsInit` (the runtime compiles with the BCL's - `LambdaExpression.Compile`, which has no such switch, and the DLR patch set has nothing - to patch) and no DLR patch. - - **The alias name.** A call through an alias leaves the name it was called by in a - thread-static for the method's entry to take (`MarkAliasCall`, `TakePendingCallee`, - `CreateMethodScope`). Every entry tested a flag first, `_aliasCallSeen`, which start-up - sets for good (RubyGems and the prelude call aliases), so every entry of every method, - light or scoped, read the thread-static - a call into the runtime from a DynamicMethod: - `TakePendingCallee` 26 + `TakePendingCalleeSlow` 34 instructions a call in the `fc` - profile. The flag is now a count of the threads that have a name pending: raised by the - alias call when its thread had none, lowered by the entry that takes one, so an entry - reads the thread-static only while some thread has a name pending. A thread that dies - with one pending leaves the count up, which only costs the reads it costs today. - - **The traced test.** A light frame without register locals called - `CreateMethodScopeIfTraced` (nine arguments) on every entry to learn that no TracePoint - listens; the test is now inline, as `EnterWithRegisterLocals` has it. - - Left as they were: `EnterLightMethod` and `LeaveLightMethodFrame` already inline their - fast paths (the slow exit only for a block or a scope), and the frame record is every - compiled frame's, tuned before (#168). - - **Numbers** (instructions a call, `Util/perf/callgrind/count.sh`, N=20,000; switch off -> - on). frame-cost, light frames: `f0` 1,572 -> 1,435 (0.913), `f1` 1,656 -> 1,591 (0.961), - `fc` 2,553 -> 2,314 (0.906), `fc3` 4,280 -> 3,693 (0.863), `fy` 2,412 -> 2,347 (0.973), - `fbg` 1,932 -> 1,795 (0.929), `bytesplice` 27,120 -> 26,907 (0.992); the same with - `IR_LIGHT_FRAMES=0` (the alias count only): 0.945-0.974, `bytesplice` 0.991. Default mode, - regex-shapes: 0.977-0.993, `size` 1.000; core-small: `tap` 0.931, `then` 0.945, `minmax` - 0.969, `inject_sym` 0.973, `inject` 0.975, `sum_blk` 0.980, `zip` 0.985, `max_by` 0.984, - `each`/`each_with_index` 0.991. No shape counts more. No timing run (the counter is the - measure here; the gate owes the clock). - - Checked: `Util/light-entry-matrix.rb` (new: `__callee__` and `__method__` through `alias` - and `alias_method` into light and scoped methods, `define_method`, `send`, `public_send`, - `Method#call`, `bind_call`, method_missing; an alias call that raises ArgumentError before - its method is entered and then ordinary calls; alias calls as arguments of alias calls; - recursion through an alias; four threads calling aliases and names; TracePoint `:call`'s - `method_id`/`callee_id`; a million-deep recursion through a light frame, and through an - alias: SystemStackError, and the process goes on) and light-rest, block-given, - global-light, lexical-light, keyword-light, regex-light, rescue-light, super-light, - parked-scope, caller, light-remember and hot-shapes: the candidate prints what the - baseline prints in all 78 runs (each as built, `IR_LIGHT_ENTRY=0`, `IR_LIGHT_FRAMES=0`, - `IR_LIGHT_REGEX=all`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`), and CRuby's but where the - baseline differs too: caller's library frames, hot-shapes' FrozenError, and - light-entry's `define_method` body called through an alias, whose `__callee__` is the - definition's name on both builds (CRuby: the alias's) - a fault of master, not of this. - IronRuby.Tests: the 11 of AliasTests, `Backtrace_ArityCalleeFrame1` and the ten - `Method_LightFrame*`: PASSED. The census cannot see this (no method changes verdict). - Not run: `IR_CONFIG=R2R` start-up, the suite, a sweep, AWFY (owed to the gate). - - **perf/nbody2 7621c60 (round thirty-nine, 2026-11-27) - an OSR loop's exits box Integers through the cache and store back only what the copy changed and someone reads (gap 2)** - not gated. What perf/nbody left of NBody (48 MB, 192 bytes per `advance`) was traced by variants of `advance` From 904f0733779545bc507b3271630cb01b438bb562 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:40:06 +0000 Subject: [PATCH 209/439] Random: find the Mersenne Twister's class at the first Random made, not at every boot Random's class body resolved IronRuby.Builtins.MersenneTwister at load time through CLR interop: System::Type.get_type(...).to_class. ruby4.rb loads in every process, so every boot paid for reflection over System::Type, RuntimeType and TypeInfo. Those were the only CLR member lookup of `ir -e 1' that found anything, plus the call sites' rules (~3 ms on the R2R host). Nothing at boot makes a Random. Random.__mt_class__ now finds the class on first use and keeps it in the same hidden ivar. Two threads that race there get the same class (to_class answers one RubyClass per type). Checked: Random.new(seed)#rand, #bytes, #seed, ==, Marshal, dup, Random.rand, srand/rand, and a Random made on another thread print what CRuby 4.0 prints, as before. Random.instance_variables is still []. Main-thread instructions: `-e 1' -9.4 M (-0.47%), `gem list' -26 M (-0.76%), R2R host. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/StdLib/ironruby/ruby4.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 19cd99ee7..b26432ada 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9786,8 +9786,12 @@ def signo class Random # MRI's generator is MT19937 (see MersenneTwister.cs), seeded and consumed exactly as # random.c does, so a given seed produces the same numbers, bytes and marshal data here. - @__mt_class__ = System::Type.get_type("IronRuby.Builtins.MersenneTwister, IronRuby.Libraries").to_class - def self.__mt_class__ = @__mt_class__ + # Found at the first Random made, not at every boot: through CLR interop it cost every + # process the reflection of System::Type and its Ruby class (~3 ms of `ir -e 1'). Two threads + # that race here find the same class. + def self.__mt_class__ + @__mt_class__ ||= System::Type.get_type("IronRuby.Builtins.MersenneTwister, IronRuby.Libraries").to_class + end private_class_method :__mt_class__ def initialize(seed = Random.new_seed) From 3abbbee666a701d26df6c1f9be3b1017e91cf5bf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:40:07 +0000 Subject: [PATCH 210/439] CLR member lookups: field and event names from metadata, and a class key for the failure cache A Ruby method name missing from a class is looked up as a CLR member of each CLR-backed class up the hierarchy: ~7,200 lookups in `ir -e 1', ~690 of them past the cache of failed lookups. Two costs in them could go. - Before asking reflection for a field or event, MayDeclareFieldOrEvent built each type's set of declared names with GetFields and GetEvents. That fills the type's reflection cache with an object per member: ~2 ms over the 42 types `ir -e 1' asks about (Int32 and Double 0.2-0.3 ms each). The names now come from the assembly's metadata tables, as DeclaredMemberNames.MayDeclareMethod's method names already do. Types with no TypeDef to read (arrays, generic parameters, types of dynamic assemblies such as generated Ruby classes) still use reflection. - The failure cache was keyed by a ValueTuple. A CoreLib Dictionary over a struct of ours has its code JIT-compiled at first use: ~0.8 ms on the ReadyToRun host, at the process's first lookup. The key is now a small class, which uses the shared precompiled code. Checked: ClrFieldAndEventNamesFromMetadata1 compares the metadata names with reflection's for every type of IronRuby, IronRuby.Libraries, Microsoft.Dynamic, System.Private.CoreLib and System.Collections, plus constructed generic and nested types (over 5,000 types), and finds them equal. The 207 Clr* tests and the hosting tests pass. An interop probe prints the same as the base on the R2R host and the Release build: fields, constants, events, nested enums, generic types, indexers, mangled names, respond_to? on CLR objects, extension methods, and the inherited and method_added hooks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/LibraryInitializerTests.cs | 28 ++++++ Src/Ruby/Builtins/RubyClass.cs | 94 +++++++++++++++++-- 3 files changed, 114 insertions(+), 9 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f8c62603e..186e3523d 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -597,6 +597,7 @@ public Tests(Driver/*!*/ driver) { ClrOverloadInheritance1, LibraryInitializerOverloadAttributes1, LibraryCopiedModuleAttributes1, + ClrFieldAndEventNamesFromMetadata1, ClrOverloadInheritance2, ClrOverloadInheritance3, ClrOverloadInheritance4, diff --git a/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs b/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs index 9b75292e9..29e800f4b 100644 --- a/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs +++ b/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs @@ -106,5 +106,33 @@ public void LibraryCopiedModuleAttributes1() { } Assert(RubyStackTraceBuilder.ReadCopyingClasses(typeof(IronRuby.Builtins.ArrayOps).Assembly).Count >= 6); } + + /// + /// A CLR member lookup asks whether a type declares a field or event of the name (RubyClass.MayDeclareFieldOrEvent), + /// and the answer comes from the assembly's metadata. A name the metadata misses would hide a member, so the names + /// must be exactly those reflection lists, for every type the metadata answers for. + /// + public void ClrFieldAndEventNamesFromMetadata1() { + int compared = 0; + foreach (var assembly in new[] { typeof(RubyClass).Assembly, typeof(IronRuby.Builtins.ArrayOps).Assembly, typeof(object).Assembly, + typeof(Microsoft.Scripting.Utils.ReflectionUtils).Assembly, typeof(System.Collections.Generic.LinkedList<>).Assembly }) { + foreach (var type in assembly.GetTypes()) { + var read = RubyClass.ReadFieldAndEventNames(type); + if (read == null) { + continue; + } + var reflected = RubyClass.ReflectFieldAndEventNames(type); + Assert(read.SetEquals(reflected), type.FullName + ": metadata " + String.Join(",", read) + " / reflection " + String.Join(",", reflected)); + compared++; + } + } + // constructed generic types and nested types answer from their definitions' rows + foreach (var type in new[] { typeof(List), typeof(Dictionary), typeof(KeyValuePair), typeof(Environment.SpecialFolder) }) { + var read = RubyClass.ReadFieldAndEventNames(type); + Assert(read != null && read.SetEquals(RubyClass.ReflectFieldAndEventNames(type)), type.FullName); + } + Assert(compared > 5000, "only " + compared + " types compared"); + Assert(RubyClass.ReadFieldAndEventNames(typeof(int[])) == null); + } } } diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index 7cc4c7563..eec562fd2 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -958,7 +958,36 @@ internal RubyMemberInfo ResolveMethodMissingForSite(string/*!*/ name, RubyMethod /// The cache is shared by all runtimes in the process, and a member that is missing without PrivateBinding /// (a private field, say) exists with it, so the key includes that setting. /// - private static Dictionary<(Type, string, bool, bool), int> _clrFailedMemberLookupCache = new Dictionary<(Type, string, bool, bool), int>(); + private static Dictionary _clrFailedMemberLookupCache = new Dictionary(); + + // The key of a failed lookup. A class, not a ValueTuple: a CoreLib collection over a struct of IronRuby's has its code + // JIT-compiled at its first use (~0.8 ms of every start on the ReadyToRun host, at the first CLR member lookup), + // where one over a class shares the precompiled code of every reference type. + private sealed class FailedLookup : IEquatable { + private readonly Type/*!*/ _type; + private readonly string/*!*/ _name; + private readonly bool _isStatic, _privateBinding; + + internal FailedLookup(Type/*!*/ type, string/*!*/ name, bool isStatic, bool privateBinding) { + _type = type; + _name = name; + _isStatic = isStatic; + _privateBinding = privateBinding; + } + + public bool Equals(FailedLookup other) { + return other != null && _type == other._type && _name == other._name && _isStatic == other._isStatic && + _privateBinding == other._privateBinding; + } + + public override bool Equals(object obj) { + return Equals(obj as FailedLookup); + } + + public override int GetHashCode() { + return _type.GetHashCode() ^ _name.GetHashCode() ^ (_isStatic ? 1 : 0) ^ (_privateBinding ? 2 : 0); + } + } /// /// GetRuntimeMethods includes @@ -976,7 +1005,7 @@ internal RubyMemberInfo ResolveMethodMissingForSite(string/*!*/ name, RubyMethod private static bool IsFailureCached(Type/*!*/ type, string/*!*/ methodName, bool isStatic, bool privateBinding, int extensionVersion) { // check for cached lookup failure (if the cache is available): bool result = false; - var key = (type, methodName, isStatic, privateBinding); + var key = new FailedLookup(type, methodName, isStatic, privateBinding); var cache = Interlocked.Exchange(ref _clrFailedMemberLookupCache, null); if (cache != null) { @@ -1006,7 +1035,7 @@ private static void CacheFailure(Type/*!*/ type, string/*!*/ methodName, bool is // store failure to the cache if the cache is not owned by another thread: var cache = Interlocked.Exchange(ref _clrFailedMemberLookupCache, null); if (cache != null) { - cache[(type, methodName, isStatic, privateBinding)] = extensionVersion; + cache[new FailedLookup(type, methodName, isStatic, privateBinding)] = extensionVersion; Interlocked.Exchange(ref _clrFailedMemberLookupCache, cache); } } @@ -1602,16 +1631,63 @@ private bool TryGetClrField(Type/*!*/ type, BindingFlags bindingFlags, bool inhe /// asked for at all. /// private static bool MayDeclareFieldOrEvent(Type/*!*/ type, string/*!*/ name) { - return _declaredFieldAndEventNames.GetValue(type, static t => { + return _declaredFieldAndEventNames.GetValue(type, static t => ReadFieldAndEventNames(t) ?? ReflectFieldAndEventNames(t)).Contains(name); + } + + // The names from the assembly's metadata tables, as DeclaredMemberNames.MayDeclareMethod reads a type's method names: + // GetFields and GetEvents populate the type's reflection cache with an object per member (Int32 and Double: 0.2-0.3 ms + // each, ~2 ms over the 42 types `ir -e 1' asks about). Null where there is no TypeDef to read (an array, a generic + // parameter, a type of a dynamic assembly such as a generated Ruby class): reflection answers those. + internal static HashSet ReadFieldAndEventNames(Type/*!*/ type) { + try { + if (type.HasElementType || type.IsGenericParameter || type.Module != type.Assembly.ManifestModule) { + return null; + } + int token = type.MetadataToken; + if ((token >> 24) != 0x02) { // not a TypeDef + return null; + } + var reader = _metadataReaders.GetValue(type.Assembly, static a => new MetadataReaderBox(CreateMetadataReader(a))).Reader; + if (reader == null) { + return null; + } + var definition = reader.GetTypeDefinition(System.Reflection.Metadata.Ecma335.MetadataTokens.TypeDefinitionHandle(token & 0xFFFFFF)); var names = new HashSet(StringComparer.Ordinal); - foreach (var field in t.GetFields(BindingFlags.DeclaredOnly | ReflectionUtils.AllMembers)) { - names.Add(field.Name); + foreach (var handle in definition.GetFields()) { + names.Add(reader.GetString(reader.GetFieldDefinition(handle).Name)); } - foreach (var e in t.GetEvents(BindingFlags.DeclaredOnly | ReflectionUtils.AllMembers)) { - names.Add(e.Name); + foreach (var handle in definition.GetEvents()) { + names.Add(reader.GetString(reader.GetEventDefinition(handle).Name)); } return names; - }).Contains(name); + } catch (Exception) { + return null; + } + } + + private sealed class MetadataReaderBox { + internal readonly System.Reflection.Metadata.MetadataReader Reader; // null: no metadata to read + internal MetadataReaderBox(System.Reflection.Metadata.MetadataReader reader) { Reader = reader; } + } + + private static readonly ConditionalWeakTable _metadataReaders = new ConditionalWeakTable(); + + private static unsafe System.Reflection.Metadata.MetadataReader CreateMetadataReader(Assembly/*!*/ assembly) { + if (assembly.IsDynamic || !System.Reflection.Metadata.AssemblyExtensions.TryGetRawMetadata(assembly, out byte* blob, out int length)) { + return null; + } + return new System.Reflection.Metadata.MetadataReader(blob, length); + } + + internal static HashSet/*!*/ ReflectFieldAndEventNames(Type/*!*/ t) { + var names = new HashSet(StringComparer.Ordinal); + foreach (var field in t.GetFields(BindingFlags.DeclaredOnly | ReflectionUtils.AllMembers)) { + names.Add(field.Name); + } + foreach (var e in t.GetEvents(BindingFlags.DeclaredOnly | ReflectionUtils.AllMembers)) { + names.Add(e.Name); + } + return names; } private static readonly ConditionalWeakTable> _declaredFieldAndEventNames = new ConditionalWeakTable>(); From f67ac44fdcc2aa87e6d7793fc01e806f170166cf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:40:54 +0000 Subject: [PATCH 211/439] JIT: read the method tables of the unsampled-call candidates under the class hierarchy lock perf/havlak2 (6f0a9fb) moved IsLeafMethodOfSomeClass onto ClassesDefining, which takes the class hierarchy lock and lets it go before it returns, and then read each class's method table (TryGetDefinedMethod) outside it; its AgreedAccessorVariable's strict test did the same. In the Release build that is an unlocked Dictionary read beside a thread defining a method; the Debug build's RequiresClassHierarchyLock assertion aborted 11 IronRuby.Tests processes in round 6's gate (the TLS, socket and Integer_FDivCoerced1 tests, among others). The candidates are now collected under the lock and tested for leafness outside it, as the method did before, and the strict test reads under the lock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 11 +++++++++-- Src/Ruby/Runtime/Jit/JitStub.cs | 15 ++++++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 18c6ca6c4..26c39724c 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1892,8 +1892,15 @@ private static string AgreedAccessorVariable(IEnumerable/*!*/ classes foreach (var cls in classes) { string v = writer ? JitRuntime.SelfAttrSite.WriterVariable(cls, name, true) : JitRuntime.SelfAttrSite.ReaderVariable(cls, name, true); if (v == null) { - RubyMemberInfo own; - if (strict && cls.TryGetDefinedMethod(name, out own) && !(own is RubyLibraryMethodInfo)) { return null; } + if (strict) { + RubyMemberInfo own; + bool defined; + // the method table under the class hierarchy lock, as everywhere else it is read + using (cls.Context.ClassHierarchyLocker()) { + defined = cls.TryGetDefinedMethod(name, out own); + } + if (defined && !(own is RubyLibraryMethodInfo)) { return null; } + } continue; } if (found != null && found != v) { return null; } diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 2c4a7ff01..acb6ce4de 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -2003,9 +2003,18 @@ internal static bool IsLeafMethodOfSomeClass(RubyContext/*!*/ context, string/*! // Only the classes that are constants of Object: with every class (ClassesDefining's walk) the hint is more often // yes for a receiver that is an Array or a Hash (some nested class has a leaf `push'), and such a caller is // wrapped to be declined (app-shapes: CSV::Parser::Scanner#keep_start), with nothing more specialized. - foreach (var cls in ClassesDefining(context, name, false)) { - RubyMemberInfo method; - if (cls.TryGetDefinedMethod(name, out method) && IsLeafMethod(method as RubyMethodInfo, true)) { return true; } + // The method tables are read under the class hierarchy lock (another thread may be defining a method), the + // leaf test of what they hold outside it, as before ClassesDefining (round 6's gate: the Debug build's + // RequiresClassHierarchyLock aborted the TLS tests here). + var candidates = new List(); + using (context.ClassHierarchyLocker()) { + foreach (var cls in ClassesDefining(context, name, false)) { + RubyMemberInfo method; + if (cls.TryGetDefinedMethod(name, out method) && method is RubyMethodInfo info) { candidates.Add(info); } + } + } + foreach (var info in candidates) { + if (IsLeafMethod(info, true)) { return true; } } return false; } From b36f01bbfdbd50bf3ca243923977b71fca159c37 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:42:21 +0000 Subject: [PATCH 212/439] StringScanner: '.' matches a byte of a split character, as Onigmo's does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From a scan pointer inside a character, strscan matches the rest of the subject as a string of its own, whose leading bytes are undecodable; to Onigmo each is a character, so /./, \A. and (?m:.) match it ("\xA9" from byte 2 of "héllo"). Such a byte reaches .NET as a lone U+DC00-U+DCFF (EscapingEncoding), which the astral-safe translation of '.' excludes, so these scans answered nil. A subject with undecodable bytes is matched only on StringScanner's allowBroken path (any other match of a broken string raises first), so that path gets a translation of its own (RegexpTransformer. TransformForEscapedBytes, cached beside the astral one) in which '.' also takes such a byte. No other match changes. Util/string-search-matrix.rb now agrees with CRuby 4.0 (63 lines differed). jit-scan, regex-light, regexp-escaped-byte and stdre matrices are unchanged; library/stringscanner, core/regexp (the known into/to errors only), language/regexp and core/matchdata specs pass, as do the Regex and StringScanner IronRuby.Tests; StringScanner_DotOnSplitByte1 holds CRuby's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 28 +++++++++++++++++++ Src/Ruby/Builtins/RegexpTransformer.cs | 34 ++++++++++++++++++++---- Src/Ruby/Builtins/RubyRegex.cs | 31 +++++++++++++++++++++ 4 files changed, 89 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 27296b13b..8dffe7c2a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -217,6 +217,7 @@ public Tests(Driver/*!*/ driver) { StringScanner_InsideCharacter1, StringScanner_ShorterSubject1, StringScanner_LiteralEncoding1, + StringScanner_DotOnSplitByte1, Regex_InspectResultEncoding1, Regex_EscapedByteEncoding1, Regex_EscapedByteEncoding2, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index db14dbdcc..029a0d003 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -982,6 +982,34 @@ public void StringScanner_LiteralEncoding1() { "); } + /// + /// From a scan pointer inside a character, '.' (and \A., (?m:.)) matches a byte of the split character + /// as a character of its own, as Onigmo does: such a byte reaches .NET as a lone U+DC00-U+DCFF. + /// + public void StringScanner_DotOnSplitByte1() { + TestOutput(@" +require 'ruby4' +require 'strscan' +def at(s, pos) = StringScanner.new(s).tap { |x| x.pos = pos } +p at(""h\u00e9llo"", 2).check(/./), at(""h\u00e9llo"", 2).scan(/\A./), at(""h\u00e9llo"", 2).scan_full(/./, false, true) +p at(""a\u{1F600}b"", 2).scan(/./), at(""a\u{1F600}b"", 3).scan(/(?m:.)/), at(""a\u{1F600}b"", 4).scan(/./) +e = at(""\xA4\xA2a"".dup.force_encoding(""EUC-JP""), 1) +p e.check(/./), e.scan(/\A.a/) +p at(""h\u00e9llo"", 2).scan(/.l/), at(""h\u00e9llo"", 2).scan(/..+/) +", @" +""\xA9"" +""\xA9"" +""\xA9"" +""\x9F"" +""\x98"" +""\x80"" +""\xA2"" +""\xA2a"" +""\xA9l"" +""\xA9llo"" +"); + } + /// /// A BINARY subject is matched with Onigmo's ASCII-8BIT ctype table (MRI's /// rb_reg_prepare_enc compiles a regexp that is not fixed-encoding for the subject's diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index d59da1aeb..04d986bfa 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -117,6 +117,8 @@ private sealed class SharedState { public bool AsciiCtype; // see Transform(..., latin1Ctype) public bool Latin1Ctype; + // see TransformForEscapedBytes + public bool EscapedBytes; // Whether /i or an inline (?i) may be in effect anywhere in the pattern (AsciiCtype only). public bool MayIgnoreCase; // Whether AsciiCtype made the translation differ from the plain one. @@ -279,6 +281,22 @@ internal static string Transform(string/*!*/ rubyPattern, RubyRegexOptions optio return result; } + /// + /// The astral-safe translation for a subject that holds undecodable bytes, which reach .NET as lone low + /// surrogates U+DC00-U+DCFF (EscapingEncoding): '.' takes such a byte as a character of its own, as Onigmo + /// does. Only StringScanner matches such a subject (the rest from a scan pointer inside a character of a + /// valid subject: RubyRegex.MatchWindow's allowBroken); any other match of a broken string raises first. + /// + internal static string TransformForEscapedBytes(string/*!*/ rubyPattern, RubyRegexOptions options, out bool hasGAnchor) { + RegexpTransformer transformer = new RegexpTransformer(rubyPattern); + transformer._clrOptions = RubyRegex.ToClrOptions(options); + transformer._state.AstralSafe = true; + transformer._state.EscapedBytes = true; + var result = transformer.Transform(); + hasGAnchor = transformer._hasGAnchor; + return result; + } + private RegexpTransformer(string/*!*/ rubyPattern) { _rubyPattern = rubyPattern; _groupNameCounts = CountGroupNames(rubyPattern); @@ -711,7 +729,9 @@ private static bool HasInlineIgnoreCase(string/*!*/ pattern) { bool astralSafe = _state.AstralSafe; bool asciiCtype = _state.AsciiCtype; bool latin1Ctype = _state.Latin1Ctype; + bool escapedBytes = _state.EscapedBytes; _state = new SharedState(); + _state.EscapedBytes = escapedBytes; _state.AstralSafe = astralSafe; _state.AsciiCtype = asciiCtype; _state.Latin1Ctype = latin1Ctype; @@ -2281,6 +2301,10 @@ private void AppendAnyCharacter() { if (next == '*' || next == '+') { Append('.'); _loopGuardPending = true; + } else if (_state.EscapedBytes) { + // an undecodable byte (a lone U+DC00-U+DCFF) is a character too + string other = (_dotAll == true) ? "[^\\ud800-\\udfff]" : (_dotAll == false) ? "[^\\n\\ud800-\\udfff]" : "(?![\\ud800-\\udfff])."; + _sb.Append("(?:[\\ud800-\\udbff][\\udc00-\\udfff]|" + other + "|[\\udc00-\\udcff])"); } else if (_dotAll == true) { _sb.Append("(?:[\\ud800-\\udbff][\\udc00-\\udfff]|[^\\ud800-\\udfff])"); } else if (_dotAll == false) { @@ -3013,11 +3037,11 @@ private CharacterSet ParseCharacterGroupUnion() { // A range reaching past U+FFFF has non-BMP members, which CharacterSet emits // as surrogate pairs. ActionView's token pattern is one of these: // [0-9A-Za-z_\u0080-\u{10ffff}-]. - // A '-' bound is spelled as a code unit: .NET reads [\--0] as '-', '-' and '0' - // rather than as the range from '-' to '0' Onigmo makes of [--0]. - set = CharacterSet.MakeRange(low, high, (high >= 0x10000) ? null : - (low == '-' || high == '-') ? - "\\u" + low.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) + "-\\u" + high.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) : + // A '-' bound is spelled as a code unit: .NET reads [\--0] as '-', '-' and '0' + // rather than as the range from '-' to '0' Onigmo makes of [--0]. + set = CharacterSet.MakeRange(low, high, (high >= 0x10000) ? null : + (low == '-' || high == '-') ? + "\\u" + low.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) + "-\\u" + high.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) : set.Text + "-" + rangeEnd.Text); } diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index c700f59a1..83c8e068e 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -48,6 +48,8 @@ public partial class RubyRegex : IEquatable, IDuplicable, IRubyObject // pairs - nearly all of them - never pays for that and matches with _cachedRegex. private Regex _cachedAstralRegex; private TimeSpan _cachedAstralTimeout; + // the translation for a subject with undecodable bytes (StringScanner's allowBroken only) + private Tuple _cachedEscapedBytes; // The same pattern translated for a match Onigmo makes with its ASCII-8BIT or US-ASCII // ctype table (UsesAsciiCtype) - above all a BINARY subject with bytes above 0x7F, which @@ -176,6 +178,7 @@ public void Set(MutableString/*!*/ pattern, RubyRegexOptions options) { _options = options & ~RubyRegexOptions.Once; _cachedRegex = null; _cachedAstralRegex = null; + _cachedEscapedBytes = null; _cachedBinary = null; _binaryIsPlain = false; _nonAsciiEscape = -1; @@ -442,6 +445,10 @@ private bool IsRecompiledCached(RubyEncoding/*!*/ encoding) { astral = input.HasSurrogatePairs(); RubyRegex target = RecompiledFor(input); + if (allowBroken && input.ContainsInvalidCharacters()) { + astral = true; + return target.TransformEscapedBytesPattern(); + } if (astral) { return target.TransformAstralPattern(); } @@ -531,6 +538,30 @@ private bool UsesAsciiCtype(MutableString/*!*/ input) { return result; } + /// + /// The astral-safe translation in which an undecodable byte is a character ('.' matches it), for the one + /// caller that matches a broken subject (RegexpTransformer.TransformForEscapedBytes). + /// + private Regex/*!*/ TransformEscapedBytesPattern() { + TimeSpan timeout = EffectiveTimeout; + var cached = _cachedEscapedBytes; + if (cached != null && cached.Item1 == timeout) { + return cached.Item2; + } + + Regex astral = TransformAstralPattern(); + Regex result; + try { + bool hasGAnchor; + result = new Regex(RegexpTransformer.TransformForEscapedBytes(GetClrPatternSource(), _options, out hasGAnchor), astral.Options, timeout); + } catch (Exception) { + result = astral; + } + + _cachedEscapedBytes = Tuple.Create(timeout, result); + return result; + } + private Regex/*!*/ TransformAstralPattern() { TimeSpan timeout = EffectiveTimeout; if (_cachedAstralRegex != null && timeout == _cachedAstralTimeout) { From 740cc5ec8c1a11794d56d61e48164f2efb113b7e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:42:21 +0000 Subject: [PATCH 213/439] LEDGER: perf/crubydiff's fifth round The cause fixed, and what the other candidate (a call's own line in a multi-line statement) would take. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index cc34270e8..84a762327 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2383,6 +2383,19 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has character, its answers over a shortened subject, and an error for an incompatible String pattern; Kernel#binding through Method#call/bind_call/to_proc raises; RubyRegex.MatchWindow has an allowBroken overload. + Fifth round (2026-11-27, on 374584c): string-search's last 63 lines. '.' (\A., (?m:.)) on a byte of a + split character: such a byte reaches .NET as a lone U+DC00-U+DCFF, which the astral-safe '.' excluded; + StringScanner's allowBroken path, the only one that matches a broken subject, now has a translation of its + own in which '.' takes it. string-search -> same. StringScanner_DotOnSplitByte1. Left: \S and [^x] on such + a byte (CRuby matches; not in the matrix). For the gate: only StringScanner matches from inside a + character change. + Not taken this round, the other candidate: a call on a later line of a multi-line statement reports the + statement's line. The line is a SourceLineMarker per statement (AstGenerator.AddDebugInfo): free in the + interpreter, which maps instructions to sequence points, but a store into the compiled frame's record + (PrecompiledFrames) in compiled code, and the method JIT and light frames keep lines their own way. Carrying + a call's own line means a marker before each call whose line differs from the last one emitted on that path + (and after it, for a later call back on the statement's line): free in the interpreter, a store per such + call in compiled code, and support in the JIT's and light frames' line records - multi-line statements only. - **perf/strsearch4 (2026-11-27) - the ASCII scan's cost of round three found and mostly removed; `#byteindex`/`#byterindex` from an offset other than 0 walk from the last search, through a map From 011dadcfa872512b20e689046009cb8f8aaf7bdd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:43:09 +0000 Subject: [PATCH 214/439] Design: a literal block in a light frame without the full call (gaps 13 and 16) Measured and designed, not built. A literal costs its light caller about 60 ns over a stored Proc: about 15 is the Proc, and about 45 is that a body with a literal sends its calls with a block through the full site with the scope made on demand - the same `nb(&P)` is 108 ns in such a body and 62 in one without. Without a profiler on this host the 45 ns cannot be divided between the site, the scope's publication and the object, and that division decides what to build. Docs/light-frame-literal-blocks.md (new) has the numbers, how a literal reaches its method's locals today, which uses of its Proc need a real scope, the narrowest sound shape, the two changes (the light site for such a call; the Proc's scope made but not published as the frame's) with their invariants, and the matrix to write first. Util/bench/iter-shapes.rb gains the nbx, nby and nbz shapes; the ledger records it under gap 16. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Docs/light-frame-literal-blocks.md | 127 +++++++++++++++++++++++++++++ Util/bench/iter-shapes.rb | 9 ++ Util/perf/LEDGER.md | 15 ++++ 3 files changed, 151 insertions(+) create mode 100644 Docs/light-frame-literal-blocks.md diff --git a/Docs/light-frame-literal-blocks.md b/Docs/light-frame-literal-blocks.md new file mode 100644 index 000000000..ce8092cbe --- /dev/null +++ b/Docs/light-frame-literal-blocks.md @@ -0,0 +1,127 @@ +# A literal block in a light frame: what it costs, and a Proc without a method scope + +Status: measured and designed in round thirty-seven (perf/lazyproc), not built. It is the remainder of +gap 13 of `Util/perf/LEDGER.md` (the fixed cost of calling an iterator) and a case of gap 16 (a light +frame that ends up making its scope). + +## What it costs + +`Util/bench/iter-shapes.rb`, ns per call of a light method, the callee `def nb; 1; end` ignoring its +block, alternating rounds against CRuby 4.0 (round thirty-seven, this host): + +| shape | IronRuby | CRuby | what it is | +|---|---|---|---| +| `nb0`: `nb` | 39-43 | 32-36 | a light frame calling a light frame | +| `nbp`: `nb(&P)` | 52-62 | 36-44 | a stored Proc passed on through the light site (`LightBlockPassEnabled`) | +| `nby`: `return nb if a; nb { }` | 56 | 36 | a body with a literal; the hot path calls without a block | +| `nbx`: `return nb(&P) if a; nb { }` | 108 | 48 | the same, the hot path passing a stored Proc | +| `nbl`: `nb { }` | 116-123 | 35-40 | the literal itself | +| `eachp` / `eachl`: `a.each(&P)` / `a.each { }` | 84 / 120 | 68 / 64 | the same through Array#each | + +So the literal's ~60 ns over a stored Proc is in two parts: + +- **About 15 ns is the Proc** (`nbl` against `nbx`): made, or made again from the parked scope + (`InstantiateParkedBlock`), and converted by the callee. +- **About 45 ns is the call with a block in a body that has a literal** (`nbx` against `nbp`): the same + `nb(&P)` costs 108 in such a body and 62 in one without. In a light body with literal blocks + (`LightFrameRewriter.BlockLiterals`) a call with a block does not take the light site + (`blockPass = ... && !BlockLiterals`): it goes through the full site with the scope made on demand + (`light.LazyScope`: `TakeParkedScope` + `ReuseParkedScopeLazy`, or `CreateMethodScopeLazy`), and the + method then leaves through `LeaveLightMethodFrameSlow` and parks (`BeginPark`/`EndPark`). A call without + a block in the same body keeps the light site and costs 56 (`nby`). + +How the 45 ns divides between the scope, the parking around it, the frame's exit with a scope and the +full site is **not measured**: Linux perf cannot run where this was done, and callgrind could not name the +JIT's code. The pieces read cheap (the scope's constructor is a dozen field writes; publishing the parked +scope with a release write instead of a compare-exchange moved nothing, perf/iter3; allocating instead of +parking, `IR_PARKED_SCOPES=0`, costs the same). The first job of an attempt is that attribution - a +profile on a host with perf, or the sequence the body emits timed piece by piece in C# - because it +decides which of the two steps below is worth building. + +## How a literal reaches its method today + +- **The method's locals.** A light body's locals are in the tuple the scope made on demand wraps + (`scope.LocalsTupleVariable`) whenever a block reads them through that scope; a body that can keep them in + CLR registers (`ScopeBuilder.TryUseRegisterLocals`) materializes the tuple when the scope is made + (`MaterializeLocals`). Which of the two a body with a literal of the narrow shape gets is to be read from + `TransformLightFrame` before B is built: B needs the tuple to be the frame's own storage. A block reaches an enclosing local through its Proc: + `Proc.LocalScope` is the method's scope, and the block's lambda takes the parent tuples from it + (`BlockDefinition`: `CreateScopeWithParent(..., bfc.Proc.LocalScope, ...)`, and the closure variables + `#closure` of `ScopeBuilder`). A scope-free block body (`IsLightCallBody`) runs without a scope of its + own and reads the enclosing locals from the same parent. +- **The literal's Proc** is `new Proc(ProcKind.Block, self, scope, dispatcher)` with `scope` the method's + scope (`InstantiateBlock`/`InstantiateReusableBlock`/`InstantiateParkedBlock` all take + `gen.CurrentScopeVariable`, which the rewriter turns into `light.LazyScope`): the literal forces the + scope whether or not its body reads anything of it. +- **Callees.** A call from a light frame without a literal block goes through a site flagged + `HasLightScope`, given the declaring scope; a rule that needs the caller's scope answers + `RubyOps.LightScopeRequired`, and the frame makes its scope and calls again through the full site + (`LightFrameRewriter.LightScopeCall`). In a body with literals, calls with a block are left on the full + site, so the literal forces the scope a second time over, at the call. + +## What needs a real method scope behind a literal's Proc + +Everything that reads `Proc.LocalScope`, or reaches the method's frame through it: + +| use | how it reaches the scope | detectable | +|---|---|---| +| the block reads or writes an enclosing local | the parent tuples from `Proc.LocalScope` | at compile time (the block's outer variables, `BlockDispatcher.OuterVariableNames`) | +| `return` in the block | the MethodUnwinder's target is the method's frame | at compile time | +| `binding`, `eval`, `local_variables`, `__method__` in the block, a nested literal | the block's scope, made with the method's as its parent | written in the block: at compile time; through `send`, `method`, `instance_exec`: only at run time, as LightScopeRequired from the block's own call sites | +| `$~`, `$_` set or read by the block or a method it calls | `GetInnerMostClosureScope` walks from the block's scope to the method's | at run time (a callee that takes the scope answers LightScopeRequired) | +| a TracePoint `:b_call`/`:line` in the block | the block's scope made for the hook, its parent the method's; `binding.local_variables` lists the method's locals | at run time (`TracePoint.ActiveEvents`) | +| the Proc escapes: the callee names it (`&b`, `Proc.new`, `define_method`), keeps it, calls `#binding` on it | the Proc object outlives the call and carries `LocalScope` | at run time: the callee's conversion (`ConvertAsMethodFrame`, not `ConvertAsLightFrame`/[BlockNotKept]) | +| `break` from the block | the Proc's converter (the callee's frame), and `LocalScope.IsEmpty` in `BlockParam.Break` | at run time, but needs only something non-empty | +| constants and `def` in the block | the lexical chain from `Proc.LocalScope`, which passes through the method's scope to the declaring scope | the declaring scope gives the same lexical answers | + +## The design + +The narrowest shape that can be sound: a literal whose body **reads and writes no enclosing local, has no +`return`, no nested literal, and none of `binding`, `eval`, `local_variables`, `__method__` written in it**, +in a light body whose literals are all of that kind (`nb { }`, `a.each { |x| f(x) }`). Its Proc needs the +method's scope for nothing it does itself; only the run-time reaches of the table remain. Two changes +follow from the numbers, each worth building only if the attribution says so: + +**A. The call with such a literal through the light site.** In a body with literals, a call with a block +takes the full site with the scope made on demand (`blockPass = ... && !BlockLiterals`). For a literal of +the narrow shape the call needs the caller's scope no more than `nb(&P)` does: it can take the +`HasLightScope` site, with LightScopeRequired (then the full site with the scope, as today) when its rule +reads the caller's scope. What it saves is the full site's share of the 45 ns; on its own it still makes +the scope, because the Proc does. + +**B. The Proc's scope made, but not as the frame's.** The light frame makes the scope object the Proc +needs (a dozen field writes) without making it the frame's published scope: `#scope` stays null, so the +frame leaves through the inlined `LeaveLightMethodFrame` fast path, does not park, and its own calls keep +the light site. The Proc holds a complete method scope (the frame's tuple, self, block, rfc, declaring +scope and module), so every run-time reach of the table finds a real scope: a block that calls `binding` +through `send` gets a block scope whose parent is it; `$~` set by a callee lands in it; a Proc kept by the +callee and asked for `#binding` after the method returned sees the method's locals, because the tuple is +the frame's own. Two things change against today and are what its matrix must pin: + +- **One scope per invocation.** If the frame later needs a scope of its own (a call that answered + LightScopeRequired, `__method__`, a TracePoint), it must take the one the Proc holds, not make a second: + `$~` set in the block and read by the method after, `local_variable_set` through one binding and read + through the other. So the frame keeps the made scope in a variable of its own (`#proc-scope`), and + `light.LazyScope` becomes `#scope ?? (#scope = #proc-scope ?? make())`, publishing it then. +- **Leaving.** A scope the frame never published still had a Proc over it, which a callee may have kept: + its flow-control frame must say the method is gone (`LeaveMethod`) when the method returns, so that a + `break` or a `binding.eval("return")` through it after that raises LocalJumpError as today. That is the + slow path of `LeaveLightMethodFrame`; B keeps it only when `#proc-scope` is non-null and the Proc is no + longer reusable (it escaped), and otherwise resets the scope for the next call as parking does. + +**Which first.** If the 45 ns is mostly the full site, A alone takes it. If it is mostly the scope's +publication (the frame's exit with a scope, the parking around it), B takes it and A adds the rest. If it +is the object itself, neither does much, and the literal's cost is what a heap Proc over a heap scope is +in .NET: CRuby's literal is a stack frame field, and only escape analysis of the kind TruffleRuby does +would remove it. + +## The matrix it needs first + +`Util/literal-block-light-matrix.rb`, before any code, printing CRuby's output on the unchanged build: +the narrow literal passed to a light Ruby method, Array#each and Integer#times, called hot; the callee +naming the block (`&b`) and keeping it, calling `b.binding.local_variables` after the method returned, and +`define_method(:x, &b)`; the block calling `binding` and `local_variables` through `send`; the block +calling `"a" =~ /a/` through `send` and the method reading `$~` after; a TracePoint `:b_call` reading +`binding.local_variables` in the block; `break` with a value and the method's `ensure`; an exception +through the block; a re-entrant call of the method from its block; four threads; `IR_LIGHT_BLOCKS=0`, +`IR_PARKED_SCOPES=0` and the change's switch. diff --git a/Util/bench/iter-shapes.rb b/Util/bench/iter-shapes.rb index 1c4fccb65..e047e7583 100644 --- a/Util/bench/iter-shapes.rb +++ b/Util/bench/iter-shapes.rb @@ -9,6 +9,9 @@ # nb0, nbp, nbl: a light method that ignores its block called with none, with a stored Proc (`&P') and with a literal # `{ }'; eachp, eachl: Array#each over one element with `&P' and with `{ }'. A literal costs its caller what a stored # Proc does not: the method's scope made (or taken parked) and the Proc made over it (round thirty-seven, perf/iter3). +# nbx, nby, nbz: a body that has a literal (never evaluated here) calling with a stored Proc, without a block, and not at +# all: in such a body a call with a block takes the full site with the scope made on demand (perf/lazyproc, +# Docs/light-frame-literal-blocks.md). $stdout.sync = true P = proc { } @@ -19,6 +22,9 @@ def nbp(a) = nb(&P) def nbl(a) = nb { } def eachp(a) = a.each(&P).size def eachl(a) = a.each { }.size + def nbx(a); return nb(&P) if a; nb { }; end + def nby(a); return nb if a; nb { }; end + def nbz(a); return 1 if a; nb { }; end def each(a); s = 0; a.each { |x| s += x }; s; end def times(k); s = 0; k.times { |j| s += j }; s; end def map(a) = a.map { |x| x + 1 }.size @@ -78,3 +84,6 @@ def t(name, n) t("nbl", N) { |n| i = 0; s = 0; while i < n; s += o.nbl(a1); i += 1; end; s } t("eachp", N) { |n| i = 0; s = 0; while i < n; s += o.eachp(a1); i += 1; end; s } t("eachl", N) { |n| i = 0; s = 0; while i < n; s += o.eachl(a1); i += 1; end; s } +t("nbx", N) { |n| i = 0; s = 0; while i < n; s += o.nbx(a1); i += 1; end; s } +t("nby", N) { |n| i = 0; s = 0; while i < n; s += o.nby(a1); i += 1; end; s } +t("nbz", N) { |n| i = 0; s = 0; while i < n; s += o.nbz(a1); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 6c90d2383..fe9a68a92 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1139,6 +1139,21 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has made twice cost. Nothing was built; the about 800 methods of the census's regex lines stay out. A step on them has to make the second call or the late scope cheaper (perf/lsite and perf/lsite2 tried the second and were rejected), not the light entry. + Round thirty-seven (perf/lazyproc, measured and designed, not built; + `Docs/light-frame-literal-blocks.md`): a literal block is this gap's commonest case. A light + method calling `nb { }` is 116-123 ns against `nb(&P)`'s 52-62 and CRuby's 35-40. About 15 ns + of the difference is the Proc (`nbl` against `nbx`); about 45 is that, in a body with a + literal, a call with a block leaves the light site for the full one with the scope made on + demand (`blockPass = ... && !BlockLiterals`): the same `nb(&P)` is 108 in a body that also has + a literal (`nbx`) and 62 in one without, while a call without a block there stays at 56 + (`nby`). How those 45 ns divide between the full site, the scope's publication (the frame's + exit with a scope, the parking around it) and the object is not measured - no profiler on + this host - and decides which of the doc's two changes to build: A, a literal that reads no + enclosing local and has no `return`, `binding` or nested literal called through the light + site; B, its Proc's scope made but not published as the frame's (no slow exit, no parking, + the frame's calls still light), with one scope per invocation and the frame's exit marking it + left when the Proc escaped. + 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per site at start-up, 0.2-0.4 ms). TruffleRuby's `Primitive.x` is replaced at parse time. From d7d8492938e2033985ff115f2b438a1b12f175be Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:46:39 +0000 Subject: [PATCH 215/439] Ledger: perf/clrlookup landed, not gated (gap 26) What makes the CLR member lookups of start-up and what they cost. Records the three changes and their numbers: main-thread instructions -0.75 to -1.97% on the R2R host, -0.10 to -1.13% on the release image, across the five start-up commands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Util/perf/LEDGER.md | 70 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 660f96919..325af5e07 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1464,6 +1464,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and the R2R host's JIT. rbconfig.rb no longer uses CLR interop: -0.3 to -0.9% main-thread instructions on all five commands. Next leads: the 4,989 CLR member lookups of ruby4.rb in `-e 1` (5.9 ms), and eval'd strings in the startup library. + 2026-11-27, perf/clrlookup (Landed, not gated): the 7,230 CLR member lookups of `-e 1` are + method resolution falling back to the CLR types of Object, Class, Module and their singleton + classes; the hooks of the prelude's definitions (`const_added`, `method_added`...) are most of them. + They cost little: failures are cached and names checked against metadata. The time is the first + lookup on each of ~67 types. Taken: Random's interop call made lazy, field and event names read + from metadata, and the failure cache keyed by a class. -0.75 to -1.97% main-thread instructions on + the R2R host, -0.10 to -1.13% on the release image. 27. **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a @@ -1774,6 +1781,69 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/clrlookup (2026-11-27) - what makes the CLR member lookups of start-up; Random's class found on + first use; field and event names from metadata; a class key for the lookup failure cache (gap 26)** + - not gated. Base 4320d4a. + The finding (a throwaway build that logged each lookup with its module, name, result, caller and + time; `ir -e 1`, R2R host): a Ruby method name a module lacks is looked up as a CLR member of each + CLR-backed module up the hierarchy (`RubyModule.TryGetClrMember`). That covers Object + (System.Object), Kernel, Class, Module, Comparable and the singleton classes of CLR-backed classes, + under the mangled name too (`method_added` -> `MethodAdded`). + - 7,230 lookups, 4,989 of them while ruby4.rb loads; one hit (`System::Type.get_type`). + - Who asks: binding call sites (`BindPrecompiled`) 2,461; the hooks of the prelude's definitions: + `const_added` 1,090 (SetConstant), `method_added` / `singleton_method_added` 1,388 (DefineMethod), + `inherited` 148; `private` and friends 718; `respond_to?` 501. + - `RubyClass` already caches failures (keyed by type, name, static, private binding, extension + version), and `DeclaredMemberNames.MayDeclareMethod` answers method names from metadata. So + 6,799 lookups cost under 5 us (3.5 ms in all). 684 reach reflection, 15 ms with tracing: 11.7 ms of + it the first lookup on each of 67 types, and the process's first lookup alone ~4.9 ms (the failure + cache's JIT, then the first metadata reader and reflection, over RubyStruct's statics while + Process::Tms is defined). + - Per-type name sets, built once: methods from metadata 2.7 ms (15 types; 2 ms of it opening the + first metadata reader), fields and events by reflection 1.9 ms (42 types), irregularly mangled + names 1.0 ms (3 types: Double, Int32, IronRuby). + - A set of member names built by reflection would pay the same first-time cost per type, so it saves + only repeat misses, which the failure cache already answers. What could go was the reflection + those sets still made, the cache's JIT, and the one interop call. + Taken: + - 904f073: `Random.__mt_class__` resolves `IronRuby.Builtins.MersenneTwister` on first use. It + used to be at Random's class body in ruby4.rb, through `System::Type.get_type(...).to_class` + (reflection over System::Type, RuntimeType and TypeInfo, ~3.3 ms). Random's results match CRuby, + `Random.instance_variables` is still `[]`, and racing threads find the same class. + - 3abbbee: `MayDeclareFieldOrEvent` reads field and event names from the assembly's metadata (as + MayDeclareMethod does), with reflection only for arrays, generic parameters and dynamic + assemblies. The failure cache is keyed by a class (`FailedLookup`), so CoreLib's shared + Dictionary code serves it. ClrFieldAndEventNamesFromMetadata1 compares metadata with reflection + for over 5,000 types. `-e 1` JITs 663 methods instead of 687. + Main-thread instructions (callgrind, TieredCompilation=0, base and new side by side), M: + | command | release image | R2R host | + |---|---|---| + | `-e 1` | 1,155.7 -> 1,142.7 (-1.13%) | 2,008.5 -> 1,968.9 (-1.97%) | + | `gem --version` | 1,332.1 -> 1,318.1 (-1.05%) | 2,271.5 -> 2,232.4 (-1.72%) | + | `gem list` | 2,239.7 -> 2,225.9 (-0.62%) | 3,376.1 -> 3,340.1 (-1.07%) | + | `require "irb"` | 2,353.9 -> 2,340.1 (-0.59%) | 3,421.1 -> 3,381.9 (-1.15%) | + | irb 1+1 | 2,522.5 -> 2,520.0 (-0.10%) | 3,680.2 -> 3,652.5 (-0.75%) | + The R2R host gains more, because it also pays the JIT the change removes. + Wall, best of N alternating, base / new, ms: + - R2R host (10): `-e 1` 531 / 481, `gem --version` 576 / 554, `gem list` 979 / 907, `require + "irb"` 969 / 955, irb 1112 / 1107. + - Release image (20): 360 / 351, 407 / 403, 814 / 784, 810 / 819, 897 / 924. With new run first + (base / new): 360 / 357, 455 / 432, 804 / 768, 845 / 822, 952 / 912. + - Release image (10) went either way: `-e 1` 341 / 377 in one order, 360 / 344 in the other. + The machine is shared and noisy: compare the instruction counts. + Checked: an interop probe prints the same on both trees, on the R2R host and the Release build: + fields and constants (Int32::MaxValue, Math::PI, String::Empty, DBNull.value), an event + (AppDomain#assembly_load), a nested enum, TimeSpan, generic List and Dictionary (indexers), + KeyValuePair, Version#major, mangled names, respond_to? on CLR objects, extension methods, and the + `inherited` and `method_added` hooks. IronRuby.Tests: 211 Clr*, hosting and extension tests pass, + including the test assembly's own C# types and extension methods, and the new metadata test. + AWFY verifying: at 3 s, base's Richards was killed at the deadline and new's CD and Json ran 2-3x + slow, right after a container restart. At 8 s in both orders DeltaBlue, Richards, Json, CD and Towers + verify, and none is slower in both (geomean 0.960 and 0.988 new/base). + Left: the cold start of reflection and metadata (~4-5 ms at the process's first lookup, which only + moves); the irregularly mangled names map (GetMembers with FlattenHierarchy, 1 ms for Double and + Int32); and the per-type sets of the ~60 types `-e 1` touches. + - **Gate of 2026-11-27 for round 4 of round thirty-seven** (perf/strdup, perf/strsearch2, perf/extiter2 and 3, perf/lframe, perf/lexical2 and 3, perf/kwrest, perf/jitscreen and 2, perf/deadconst2, perf/permute, perf/havlak, perf/dmethjit2, perf/jitsettle; the rejected From 49699fa05e5987dcf1d38609b182f682b45dc507 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:48:43 +0000 Subject: [PATCH 216/439] Let a light frame's String and Regexp calls store $~ in no frame (gap 16) The census's largest refusal was a regex literal passed to a method that stores the caller's $~ (gsub, =~, sub, when, scan, split, match: about 880 methods): such a light frame made its scope on the call and called again, which costs more than the scope at entry (perf/regexlight). In CRuby $~ is frame-local: a method's match never reaches its caller. A method with no $~ reference, no block or lambda, no binding, eval, send or method call, and no global but the runtime's own cannot observe its $~ either, so it need not be stored in any frame. MethodDefinition.IsMatchSink finds those methods; their regex literals no longer keep them out of light frames, and their light sites of the String/Regexp matching methods get RubyCallFlags.HasMatchSink. The rule of such a site, once it has resolved a library method of String, Symbol or Regexp, gives it the runtime's EmptyScope (CallArguments.MatchSink) instead of answering LightScopeRequired. Not while c_call is traced; and the rule takes the scope while any TracePoint is enabled. Switch: IR_LIGHT_MATCH_SINK=0. Known difference: a TracePoint enabled by a callee after the match reads nil for the method's $~ through its binding (matrix row 10, MID=1). Census: light frames 26,732 -> 27,291, none lost. Instructions (callgrind): gsub 0.971, split 0.964, kase 0.965, eqt 0.929, controls 1.000. New matrix Util/light-match-sink-matrix.rb plus regex-light, light-entry, hot-shapes, block-pass and jit match CRuby in all seven gate modes; specs language/predefined, core/regexp and the String matching methods unchanged; new test Method_LightFrameMatchSink1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 42 +++ .../Ast/Definitions/MethodDefinition.cs | 103 ++++++- Src/Ruby/Runtime/Calls/CallArguments.cs | 15 ++ Src/Ruby/Runtime/Calls/RubyCallAction.cs | 33 ++- Src/Ruby/Runtime/Calls/RubyCallSignature.cs | 11 +- Util/light-match-sink-matrix.rb | 255 ++++++++++++++++++ Util/perf/LEDGER.md | 45 ++++ 8 files changed, 491 insertions(+), 14 deletions(-) create mode 100644 Util/light-match-sink-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 650c644d6..74fee27e9 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1158,6 +1158,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGiven1, Method_LightFrameRest1, Method_LightFrameMemberOpAssign1, + Method_LightFrameMatchSink1, Method_LightFrameKeywordRest1, Method_KeywordHashIntoRest1, Method_KeywordPrologue1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 6b71ca3f2..52f795620 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -7887,6 +7887,48 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters "); } + /// + /// IR_LIGHT_MATCH_SINK: a light frame whose regex literals go to String and Regexp methods that store $~, in a method + /// that reads no $~ of its own (MethodDefinition.IsMatchSink): the caller's $~ is left as it was, in its thread too; a + /// method that reads its $~ ($~, Regexp.last_match, binding) sees its match. + /// + public void Method_LightFrameMatchSink1() { + TestOutput(@" +require 'ruby4' +def g(s) = s.gsub(/b/, ""x"") +def sp(s) = s.split(/,/) +def k(s) + case s + when /z/ then 1 + when /b/ then 2 + end +end +def e(s) = (s =~ /c/) || -1 +def t(s); s =~ /b+/; $~[0]; end +def l(s); s.sub(/a/, """"); Regexp.last_match(0); end +def b(s); s.index(/c/); binding.eval(""$~[0]""); end +def caller_sees(s) + ""zz"" =~ /z/ + r = [g(s), sp(s), k(s), e(s)] + [r, $~[0]] +end +p caller_sees(""abc,b""), 40.times.map { caller_sees(""ab"") }.uniq +p t(""abbc""), l(""abc""), b(""abc"") +$~ = nil +p [g(""b""), e(""c""), $~] +th = Thread.new { ""q"" =~ /q/; 30.times { g(""bb""); k(""b"") }; $~[0] } +p th.value +", @" +[[""axc,x"", [""abc"", ""b""], 2, 2], ""z""] +[[[""ax"", [""ab""], 2, -1], ""z""]] +""bb"" +""a"" +""c"" +[""x"", 0, nil] +""q"" +"); + } + /// /// `recv.m op= v' in a light frame (IR_LIGHT_MEMBER_OPASSIGN): the read of m, the operator and the write of m= are calls of /// the frame's light sites; the value is the right-hand side whatever m= returns; a private accessor on self; `&.'; binding. diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index d805014b8..708287395 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -626,6 +626,69 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { "byterindex", "[]", "[]=", "slice", "slice!", "start_with?", "partition", "rpartition", "grep", "grep_v", }; + /// + /// IR_LIGHT_MATCH_SINK=0 keeps a method whose regex literal goes to a method that stores $~ out of light frames, as before + /// (see IsMatchSink). + /// + internal static readonly bool LightMatchSinkEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_MATCH_SINK") != "0"; + + // The names of RegexScopeMethods that String, Symbol and Regexp define (RubyCallAction.IsMatchSinkMethod): a light site + // of one in a method that is a match sink stores $~ in no frame (RubyCallFlags.HasMatchSink). + private static readonly HashSet/*!*/ MatchSinkMethods = new HashSet { + "=~", "===", "match", "gsub", "gsub!", "sub", "sub!", "scan", "split", "index", "rindex", "byteindex", + "byterindex", "[]", "[]=", "slice", "slice!", "start_with?", "partition", "rpartition", + }; + + // Set while the body of a method that is a match sink is checked (IsBodyScopeFree): a regex literal given to one of + // MatchSinkMethods, or in a when clause, does not then keep it out of light frames. + [ThreadStatic] + private static bool t_matchSink; + + // The names of the methods through which a frame's $~ is read other than by `$~', `$1'... and Regexp.last_match: a + // binding or a string eval in the frame, a call made by name (send, method), and a TracePoint the frame enables itself. + private static readonly HashSet/*!*/ MatchObserverMethods = new HashSet { + "binding", "eval", "instance_eval", "class_eval", "module_eval", "send", "__send__", "public_send", "method", + "public_method", "singleton_method", "last_match", "enable", "set_trace_func", "trace", + }; + + // The globals a match sink may read or write: none of them is the frame's $~ or an alias of it. + private static readonly HashSet/*!*/ MatchSinkGlobals = new HashSet { + "stdout", "stderr", "stdin", "VERBOSE", "DEBUG", "0", "PROGRAM_NAME", "LOAD_PATH", "LOADED_FEATURES", ":", "\"", + ";", ",", "/", "\\", "!", "@", "$", "*", "FILENAME", "-w", "-v", "-d", "-0", "-F", "-i", "-l", "-p", "-a", "-I", + }; + + /// + /// Whether nothing reads the $~ of a frame of the method (CRuby: $~ is frame-local, and a block's is its method's): no + /// `$~', `$&', `$1', Regexp.last_match or other reference to it, no block or lambda (whose binding a callee may be given), + /// no binding, string eval or call made by name (MatchObserverMethods), no global but the runtime's own + /// (MatchSinkGlobals: `alias $m $~' makes `$m' the frame's $~). Such a method's light frame lets the String, Symbol and + /// Regexp methods it calls store $~ in no frame at all (RubyCallFlags.HasMatchSink), where it would otherwise make its + /// scope for them on every call and call them again (gap 16 of Util/perf/LEDGER.md). $~ after the method returns is + /// its caller's, as in CRuby. + /// + private bool IsMatchSink() { + if (!LightMatchSinkEnabled || !LightRegexEnabled) { + return false; + } + var finder = new MatchObserverFinder(); + foreach (var optional in _parameters.Optional) { + optional.Walk(finder); + } + Body.Walk(finder); + return !finder.Found; + } + + private sealed class MatchObserverFinder : Walker { + internal bool Found; + + public override bool Enter(RegexMatchReference/*!*/ node) { Found = true; return false; } + public override bool Enter(GlobalVariable/*!*/ node) { Found |= !MatchSinkGlobals.Contains(node.Name); return !Found; } + public override bool Enter(BlockDefinition/*!*/ node) { Found = true; return false; } + public override bool Enter(LambdaDefinition/*!*/ node) { Found = true; return false; } + public override bool Enter(MethodDefinition/*!*/ node) { return false; } + public override bool Enter(MethodCall/*!*/ node) { Found |= MatchObserverMethods.Contains(node.MethodName); return !Found; } + } + private static bool HasRegexLiteral(Expression target, Arguments arguments) { if (target is RegularExpression) { return true; @@ -780,7 +843,13 @@ private static bool HasHandling(Body/*!*/ body) { // The body's statements and its rescue, else and ensure clauses are scope-free (blockLiterals: with literal blocks). private bool IsBodyScopeFree(bool blockLiterals) { - return FirstNotScopeFree(blockLiterals) == null && AreClausesScopeFree(Body, blockLiterals, null); + bool saved = t_matchSink; + t_matchSink = !blockLiterals && IsMatchSink(); + try { + return FirstNotScopeFree(blockLiterals) == null && AreClausesScopeFree(Body, blockLiterals, null); + } finally { + t_matchSink = saved; + } } // The most calls a body with a multiple assignment may make and still be a light frame. A light frame's lambda grows @@ -1034,7 +1103,13 @@ private bool HasBlockGuard { // A statement of a block's body (BlockDefinition.IsLightCallBody): not one with exception handling, which the rewriter // takes only in a method's frame (LightFrameRewriter.Handling). internal static bool IsScopeFree(Expression/*!*/ node) { - return IsScopeFree(node, false, null) && !HandlingFinder.Has(node); + bool saved = t_matchSink; + t_matchSink = false; + try { + return IsScopeFree(node, false, null) && !HandlingFinder.Has(node); + } finally { + t_matchSink = saved; + } } // Finds a `begin' with rescue, else or ensure, a rescue modifier or a `retry' in a node, outside its blocks and definitions. @@ -1179,8 +1254,8 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong return why != null && Refuse(why, item == null ? "assignment to " + assignment.Left.GetType().Name : LightCallsEnabled ? "assignment to an element with a block" : "assignment to an element (IR_LIGHT_CALLS=0)"); } - // `s[/x/] = v' is String#[]=, which stores $~ (RegexScopeMethods) - if (!LightRegexAll && HasRegexLiteral(null, item.Arguments)) { + // `s[/x/] = v' is String#[]=, which stores $~ (RegexScopeMethods), in no frame in a match sink (IsMatchSink) + if (!LightRegexAll && !t_matchSink && HasRegexLiteral(null, item.Arguments)) { return why != null && Refuse(why, "RegularExpression passed to []= (it sets $~)"); } return IsScopeFree(item.Array, blockLiterals, why) && AreScopeFree(item.Arguments, blockLiterals, why); @@ -1308,7 +1383,7 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong } foreach (var clause in caseExpression.WhenClauses) { foreach (var comparison in clause.Comparisons) { - if (comparison is RegularExpression && !LightRegexAll) { + if (comparison is RegularExpression && !LightRegexAll && !t_matchSink) { return Refuse(why, "RegularExpression in a when clause (Regexp#=== sets $~)"); } if (!IsScopeFree(comparison, blockLiterals, why)) { @@ -1364,7 +1439,8 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong // scope, and the call passes it as an argument (LightFrameRewriter.LightScopeCall) var call = node as MethodCall; if (call != null) { - if (!LightRegexAll && HasRegexLiteral(call.Target, call.Arguments) && RegexScopeMethods.Contains(call.MethodName)) { + if (!LightRegexAll && HasRegexLiteral(call.Target, call.Arguments) && RegexScopeMethods.Contains(call.MethodName) && + !(t_matchSink && MatchSinkMethods.Contains(call.MethodName))) { return why != null && Refuse(why, "RegularExpression passed to " + call.MethodName + " (it sets $~)"); } var blockReference = call.Block as BlockReference; @@ -1495,7 +1571,7 @@ private static bool IsScopeFreeTarget(LeftValue/*!*/ target, bool blockLiterals, } var item = target as ArrayItemAccess; if (item != null && item.Block == null) { - if (!LightRegexAll && HasRegexLiteral(null, item.Arguments)) { + if (!LightRegexAll && !t_matchSink && HasRegexLiteral(null, item.Arguments)) { return why != null && Refuse(why, "RegularExpression passed to []= (it sets $~)"); } return IsScopeFree(item.Array, blockLiterals, why) && AreScopeFree(item.Arguments, blockLiterals, why); @@ -1599,8 +1675,10 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ var inLoop = scope.DefineHiddenVariable("#in-loop", typeof(bool)); light.LazyScope = Ast.Coalesce(scopeVariable, Ast.Assign(scopeVariable, Ast.Call(_LightScopeInLoop, light.MakeScope, inLoop))); + bool blockLiterals = LightBlocksEnabled && HasLightBlockLiteral(); var rewriter = new LightFrameRewriter(scopeVariable, light.LazyScope, light.Rfc, declaringScope, inLoop, HasBlockGuard) { - BlockLiterals = LightBlocksEnabled && HasLightBlockLiteral(), + BlockLiterals = blockLiterals, + MatchSink = !blockLiterals && IsMatchSink(), BlockParameter = LightBlockGivenEnabled ? blockParameter : null, SuperModule = LightSuperEnabled ? ConstantValue(declaringModule) as RubyModule : null, SuperName = _name, @@ -1662,6 +1740,8 @@ internal sealed class LightFrameRewriter : MSA.ExpressionVisitor { // makes none. The scope made on demand has the frame's locals (its tuple, made from the register locals if those are // used), self, block and flow-control frame, which is all the block and the call read from it. internal bool BlockLiterals; + // Nothing reads the frame's $~ (IsMatchSink): a light site of one of MatchSinkMethods has RubyCallFlags.HasMatchSink. + internal bool MatchSink; // see LightFrame.MakesCalls internal bool MakesCalls; @@ -2134,8 +2214,11 @@ private MSA.Expression LightScopeCall(Microsoft.Scripting.Ast.LightDynamicExpres return null; } - var lightAction = RubyCallAction.Make(action.Context, action.MethodName, - new RubyCallSignature(signature.ArgumentCount, signature.Flags | RubyCallFlags.HasLightScope)); + var lightFlags = signature.Flags | RubyCallFlags.HasLightScope; + if (MatchSink && MatchSinkMethods.Contains(action.MethodName)) { + lightFlags |= RubyCallFlags.HasMatchSink; + } + var lightAction = RubyCallAction.Make(action.Context, action.MethodName, new RubyCallSignature(signature.ArgumentCount, lightFlags)); return MakeLightCall(reduced, action, lightAction, DispatchIntrinsics.IsLightBlockGivenSite(action.MethodName, lightAction.Signature)); } diff --git a/Src/Ruby/Runtime/Calls/CallArguments.cs b/Src/Ruby/Runtime/Calls/CallArguments.cs index 35455dce5..af554d32c 100644 --- a/Src/Ruby/Runtime/Calls/CallArguments.cs +++ b/Src/Ruby/Runtime/Calls/CallArguments.cs @@ -89,6 +89,14 @@ public int SimpleArgumentCount { /// internal bool ScopeRead; + /// + /// Set by RubyCallAction.BuildCall at a site with RubyCallFlags.HasMatchSink once the method is resolved and is one that + /// takes the scope only to store $~ (RubyCallAction.IsMatchSinkMethod): the scope the rule gives it is then the runtime's + /// empty scope, which nothing reads $~ of, and reading it is not reading the frame's. + /// + internal bool MatchSink; + private DynamicMetaObject _sinkScope; + /// /// The scope argument's expression, for a helper that takes the scope only for its runtime (GetInstanceVariable, /// SetAttribute): the scope a light-scope site passes has the same runtime, so this does not count as reading it. @@ -99,6 +107,13 @@ internal Expression/*!*/ ContextScopeExpression { public DynamicMetaObject/*!*/ MetaScope { get { + if (MatchSink) { + if (_sinkScope == null) { + var sink = ((RubyContext)_context.Value).EmptyScope; + _sinkScope = new DynamicMetaObject(Ast.Constant(sink, typeof(RubyScope)), BindingRestrictions.Empty, sink); + } + return _sinkScope; + } if (_signature.HasLightScope) { ScopeRead = true; } diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index ad04cec5b..87aa6605d 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -121,7 +121,7 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // binder. Leaving it out of the mask sent every bare `foo` to a rule of its own. if (Context == null || Signature.ResolveOnly || - (Signature.Flags & ~(RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasScope | RubyCallFlags.HasBlock | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasSourceBlock | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasLightScope)) != 0 || + (Signature.Flags & ~(RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasScope | RubyCallFlags.HasBlock | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasSourceBlock | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasLightScope | RubyCallFlags.HasMatchSink)) != 0 || Signature.HasSplattedArgument && Signature.HasRhsArgument) { return null; } @@ -372,7 +372,7 @@ internal SharedRule(RubyMemberInfo/*!*/ member, bool isMissing, Type/*!*/ target private const RubyCallFlags SharableCallFlags = RubyCallFlags.HasScope | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasBlock | RubyCallFlags.HasImplicitSelf | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSourceBlock | - RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat; + RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasMatchSink; private static readonly object _SharedRulesLock = new object(); private SharedRule[] _sharedRules; @@ -772,8 +772,21 @@ private static bool BuildCall(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ me return BuildCall(metaBuilder, sentName, args, defaultFallback, callClrMethods, false); } + if (args.Signature.HasMatchSink && !args.ScopeRead && IsMatchSinkMethod(args.RubyContext, method.Info)) { + args.MatchSink = true; + } method.Info.BuildCall(metaBuilder, args, methodName); + // While a TracePoint is enabled its hooks may read the frame's $~ through their binding (a :line or :return + // event): the call then stores $~ in the frame's scope, made for it (RubyOps.LightScopeRequired). + if (args.MatchSink && !metaBuilder.Error && metaBuilder.Result != null) { + metaBuilder.Result = Ast.Condition( + Ast.Equal(Ast.Field(null, typeof(TracePoint).GetField("ActiveEvents")), AstUtils.Constant(0)), + AstUtils.Convert(metaBuilder.Result, typeof(object)), + AstUtils.Constant(RubyOps.LightScopeRequired, typeof(object)) + ); + } + // MRI 3.4+: a block passed to a method that never uses it may be ignored if (args.Signature.HasSourceBlock && RequiresUnusedBlockCheck(method.Info) && !metaBuilder.Error && metaBuilder.Result != null) { metaBuilder.Result = Ast.Block( @@ -967,6 +980,22 @@ private static MethodResolutionResult ResolveOwnClrMember(MetaObjectBuilder/*!*/ return notFound; } + /// + /// A library method of String, Symbol or Regexp (MutableStringOps, SymbolOps, RubyRegexOps): one that takes its caller's + /// scope to store $~ in it and for the runtime, and for nothing else - not to resolve a call it makes, which goes through + /// a site of its own without the caller's refinements, as CRuby's rb_funcall does. A site with RubyCallFlags.HasMatchSink + /// gives it the runtime's empty scope (CallArguments.MatchSink). Not while c_call is traced: the rule then reports the + /// call with the caller's scope (RubyLibraryMethodInfo.AddCallTracing), and switching tracing rebinds every rule. + /// + internal static bool IsMatchSinkMethod(RubyContext/*!*/ context, RubyMemberInfo/*!*/ method) { + if (!(method is RubyLibraryMethodInfo) || TracePoint.CCallTracing) { + return false; + } + var owner = method.DeclaringModule; + return owner == context.GetClass(typeof(MutableString)) || owner == context.GetClass(typeof(RubySymbol)) || + owner == context.GetClass(typeof(RubyRegex)); + } + internal static MethodResolutionResult Resolve(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ methodName, CallArguments/*!*/ args, out RubyMemberInfo methodMissing) { diff --git a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs index 0d880a199..165a67ee3 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs @@ -77,13 +77,19 @@ public enum RubyCallFlags { // (ArgsBuilder.AddCallArguments). Not a site that splats an array of the program's own (`f(*a)'), which the callee // must not share. HasFreshSplat = 2048, + + // CallAction only, with HasLightScope: a call in a method that runs without its scope and that nothing in its body + // reads $~ of (MethodDefinition.IsMatchSink). A library method of String, Symbol or Regexp, which takes the scope only to + // store $~ in it and for its runtime, is then given the runtime's empty scope instead of reading the frame's + // (CallArguments.MatchSink), and the frame makes no scope for it. + HasMatchSink = 4096, } /// /// RubyScope/RubyContext, (self), (argument){ArgumentCount}, (splatted-argument)?, (block)? /// public struct RubyCallSignature : IEquatable { - private const int FlagsCount = 12; + private const int FlagsCount = 13; private const int ResolveOnlyArgumentCount = (int)(UInt32.MaxValue >> FlagsCount); private const int MaxArgumentCount = ResolveOnlyArgumentCount - 1; @@ -104,6 +110,7 @@ public struct RubyCallSignature : IEquatable { public bool HasSourceBlock { get { return (_countAndFlags & (uint)RubyCallFlags.HasSourceBlock) != 0; } } public bool HasLightScope { get { return (_countAndFlags & (uint)RubyCallFlags.HasLightScope) != 0; } } public bool HasFreshSplat { get { return (_countAndFlags & (uint)RubyCallFlags.HasFreshSplat) != 0; } } + public bool HasMatchSink { get { return (_countAndFlags & (uint)RubyCallFlags.HasMatchSink) != 0; } } // defined? ignores arguments hence we can use one argument number (max) to represent resolve only sites: public bool ResolveOnly { get { return ArgumentCount == ResolveOnlyArgumentCount; } } @@ -191,7 +198,7 @@ public bool Equals(RubyCallSignature other) { (HasImplicitSelf ? "." : "") + (HasImplicitArguments ? "^" : "") + (IsVirtualCall ? "V" : "") + - (HasLightScope ? "L" : HasScope ? "S" : "C") + + (HasLightScope ? (HasMatchSink ? "M" : "L") : HasScope ? "S" : "C") + (ResolveOnly ? "?" : "," + ArgumentCount.ToString()) + (HasSplattedArgument ? (HasFreshSplat ? "*+" : "*") : "") + (HasBlock ? "&" : "") + diff --git a/Util/light-match-sink-matrix.rb b/Util/light-match-sink-matrix.rb new file mode 100644 index 000000000..e6fd02bff --- /dev/null +++ b/Util/light-match-sink-matrix.rb @@ -0,0 +1,255 @@ +# Differential matrix for the frame-local $~ of a method that runs in a light frame and gives a regex to a String, +# Symbol or Regexp method that stores $~ (MethodDefinition.IsMatchSink, RubyCallFlags.HasMatchSink, +# IR_LIGHT_MATCH_SINK). CRuby's rules, which each row checks: +# +# - $~ is the frame's own: a method's match does not set its caller's $~, and leaves it as it was (nil or a match); +# - a block sees its method's $~ (and sets it), a lambda too; +# - $~ is per thread as well as per frame; +# - $1..$9, $&, $`, $', $+ and Regexp.last_match read $~; `$~ = nil' and `$~ = md' set it, any other value raises; +# - binding, eval and a string instance_eval read the frame's $~, and so does a TracePoint's binding; +# - each of =~, ===, `when', match, gsub, sub, scan, split, index, rindex, [], slice, start_with?, partition, +# rpartition, byteindex and their bang forms sets $~ (or clears it on no match); +# - a method calling String#=~ with an object of its own: that object's =~ runs in its own frame. +# +# Every method is called hot (N times) so that its sites are bound and compiled, then once more for the row. +# Run under CRuby and ./ir.sh (JIT on and off, light frames off, the switch off) and diff: +# +# ruby Util/light-match-sink-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/light-match-sink-matrix.rb > /tmp/ir.txt && diff /tmp/mri.txt /tmp/ir.txt +# IR_LIGHT_MATCH_SINK=0 ./ir.sh Util/light-match-sink-matrix.rb > /tmp/off.txt && diff /tmp/mri.txt /tmp/off.txt +# +# Every row must match, and the last line be `end'. + +$stdout.sync = true +N = 2000 + +def row(name, value) + puts "#{name}: #{value.inspect}" +end + + + +def hot(n = N) + r = nil + n.times { r = yield } + r +end + +class Sinks + def eqt(s) = s =~ /b+/ + def eqt_r(s, r) = s =~ r + def treq(s) = /b+/ === s + def kase(s) + case s + when /z/ then :z + when /b+/ then :b + else :none + end + end + def match(s) = s.match(/b+/) ? 1 : 0 + def gsub(s) = s.gsub(/b/, "x") + def gsub_hash(s) = s.gsub(/b/, "b" => "y") + def sub(s) = s.sub(/b/, "x") + def gsubb(s) = s.dup.gsub!(/b/, "x") + def subb(s) = s.dup.sub!(/b/, "x") + def scan(s) = s.scan(/b/) + def split(s) = s.split(/b/) + def index(s) = s.index(/b/) + def rindex(s) = s.rindex(/b/) + def aref(s) = s[/b+/] + def slice(s) = s.slice(/b+/) + def sliceb(s) = s.dup.slice!(/b+/) + def aset(s) = (t = s.dup; t[/b+/] = "Q"; t) + def startw(s) = s.start_with?(/a/) + def part(s) = s.partition(/b+/) + def rpart(s) = s.rpartition(/b/) + def bindex(s) = s.byteindex(/b/) + def sym(s) = s.to_sym =~ /b/ + def sym_match(s) = s.to_sym.match(/b/) ? 1 : 0 + def notm(s) = s !~ /b/ + def grep(a) = a.grep(/b/) +end + +S = Sinks.new +STR = "abbc" +NAMES = %i[eqt treq kase match gsub gsub_hash sub gsubb subb scan split index rindex aref slice sliceb aset startw part rpart bindex sym sym_match notm] + +# 1. the caller's $~ after each method, when the caller had none and when it had one of its own +def caller_nil(name) + $~ = nil + r = S.send(name, STR) + [r, $~ && $~[0]] +end +def caller_set(name) + "zz" =~ /z/ + r = S.send(name, STR) + [r, $~ && $~[0]] +end +NAMES.each do |name| + hot { caller_nil(name) } + row "1. #{name}", [caller_nil(name), caller_set(name), hot { caller_set(name) }] +end +row "1a. grep", [hot { S.grep(%w[ab cd]) }, ($~ = nil; S.grep(%w[ab]); $~ && $~[0])] +row "1b. =~ with a Regexp in a variable", [hot { S.eqt_r(STR, /c/) }, ("zz" =~ /z/; S.eqt_r(STR, /c/); $~ && $~[0])] +row "1c. no match", [hot { S.eqt("xyz") }, ("zz" =~ /z/; S.eqt("xyz"); $~ && $~[0]), S.gsub("xyz"), S.split("xyz")] + +# 2. methods that read their own $~ after the match: these must see it +class Observers + def tilde(s); s =~ /b+/; $~ && $~[0]; end + def amp(s); s.sub(/b+/, ""); $&; end + def num(s); s.match(/(b)(c)/); [$1, $2, $3]; end + def pre_post(s); s =~ /b+/; [$`, $']; end + def plus(s); s =~ /(a)|(b)/; $+; end + def last(s); s.index(/b+/); Regexp.last_match && Regexp.last_match(0); end + def bind(s); s.scan(/b/); binding.eval("$~ && $~[0]"); end + def ev(s); s =~ /bc/; eval("$~[0]"); end + # not instance_eval("$~"): IronRuby's string instance_eval does not see its caller's $~ (with or without the switch) + def ieval(s); s =~ /bc/; instance_eval("$~[0]"); end + def blk(s); s =~ /b+/; [1].map { $~ && $~[0] }; end + def blk_sets(s); [s].each { |x| x =~ /c/ }; $~ && $~[0]; end + def lam(s); s =~ /b+/; l = -> { $~ && $~[0] }; l.call; end + def assign_nil(s); s =~ /b+/; $~ = nil; [$~, $&]; end + def assign_md(s, md); s =~ /b+/; $~ = md; [$~[0], $&]; end + def assign_bad(s); s =~ /b+/; $~ = 1; end + def defined_q(s); s =~ /b+/; [defined?($~), defined?($1), defined?($&)]; end + def kase(s) + case s + when /(b+)/ then $1 + end + end + def send_last(s); s.split(/b/); Regexp.send(:last_match, 0); end + def meth(s); s =~ /c/; method(:md0_here).call; end + def md0_here = $~ && $~[0] + def callee_does_not_see(s); s =~ /c/; md0_here; end + def when_then_tilde(s) + r = case s + when /z/ then 1 + when /bb/ then 2 + end + [r, $~ && $~[0]] + end + def gsub_block(s) = s.gsub(/b/) { $~[0].upcase } + def scan_block(s); r = []; s.scan(/b(.)/) { r << $1 }; r; end +end +O = Observers.new +md = /(x)/.match("x") +%i[tilde amp num pre_post plus last bind ev blk blk_sets lam assign_nil defined_q kase send_last meth callee_does_not_see when_then_tilde gsub_block scan_block].each do |name| + row "2. #{name}", [hot { O.send(name, STR) }, ("zz" =~ /z/; O.send(name, STR); $~ && $~[0])] +end +row "2. assign_md", [hot { O.assign_md(STR, md) }, ("zz" =~ /z/; O.assign_md(STR, md); $~ && $~[0])] +row "2. assign_bad", [(O.assign_bad(STR) rescue [$!.class, $!.message])] + +# 3. a global alias of $~ read in the method +alias $mm $~ +class AliasReader + def read(s); s =~ /b+/; $mm && $mm[0]; end +end +row "3. alias $mm $~", [hot { AliasReader.new.read(STR) }] + +# 4. threads: each thread's $~ is its own, and a method's match sets no thread's +ths = 4.times.map do |t| + Thread.new do + "t#{t}" =~ /t(\d)/ + r = hot(500) { S.gsub(STR) + S.split(STR).join + S.kase(STR).to_s } + [r, $1] + end +end +row "4. threads", ths.map(&:value) + +# 5. refinements of a sink name in a method that is otherwise a sink +module RefGsub + refine(String) { def gsub(*) = :refined } +end +class UsesRefGsub + using RefGsub + def g(s) = s.gsub(/b/, "x") +end +row "5. refined gsub", [hot { UsesRefGsub.new.g(STR) }, ("zz" =~ /z/; UsesRefGsub.new.g(STR); $~ && $~[0])] + +# 6. String#=~ with an object of the program's own; a String subclass with a Ruby gsub +class MyMatcher + def =~(s) = (s =~ /c/; [:mine, $~ && $~[0]]) +end +class Sinks + def eqt_obj(s, o) = s =~ o +end +class MyString < String + def gsub(*) = [:sub, super] +end +row "6. String#=~ with an object", [hot { S.eqt_obj(STR, MyMatcher.new) }, ("zz" =~ /z/; S.eqt_obj(STR, MyMatcher.new); $~ && $~[0])] +row "6a. String subclass", [hot { S.gsub(MyString.new(STR)) }, ("zz" =~ /z/; S.gsub(MyString.new(STR)); $~ && $~[0])] +row "6b. Symbol receiver", [hot { S.eqt(:abbc) }, ("zz" =~ /z/; S.eqt(:abbc); $~ && $~[0])] + +# 7. gsub, sub and =~ redefined on String after the sites are bound, and removed again +row "7. before", [hot { S.gsub(STR) }, hot { S.eqt(STR) }] +class String + alias_method :__orig_gsub, :gsub + remove_method :gsub + def gsub(*a) = [:redefined, $~] +end +row "7. redefined", [S.gsub(STR), hot { S.gsub(STR) }, ("zz" =~ /z/; S.gsub(STR); $~ && $~[0])] +class String + remove_method :gsub + alias_method :gsub, :__orig_gsub + remove_method :__orig_gsub +end +row "7. restored", [S.gsub(STR), hot { S.gsub(STR) }, ("zz" =~ /z/; S.gsub(STR); $~ && $~[0])] + +# 8. TracePoint: enabled before the call, its :return binding sees the method's $~ +def traced(s) + s =~ /b+/ + 1 +end +seen = [] +tp = TracePoint.new(:return) { |t| seen << t.binding.eval("$~ && $~[0]") if t.method_id == :traced } +hot { traced(STR) } +tp.enable { traced(STR) } +row "8. TracePoint :return enabled before", seen +seen = [] +tp2 = TracePoint.new(:c_return) { |t| seen << [t.method_id, t.return_value] if t.method_id == :=~ } +tp2.enable { traced(STR) } +row "8a. TracePoint :c_return", seen +row "8b. after tracing", [hot { traced(STR) }, ("zz" =~ /z/; traced(STR); $~ && $~[0])] + +# 9. a method that both makes its scope for another call (respond_to?, block_given?) and matches +class Mixed + def rt(s); s =~ /b/; respond_to?(:rt) ? s.gsub(/c/, "") : nil; end + def bg(s); s.sub(/a/, "") + (block_given? ? "y" : "n"); end + def kw(s, x: 1) = s.split(/b/).size + x + def opt(s, n = s.index(/c/)) = n + def rescue_m(s) + Integer(s) + rescue ArgumentError + s.gsub(/b/, "") + end +end +mx = Mixed.new +row "9. scope made late", [hot { [mx.rt(STR), mx.bg(STR), mx.kw(STR), mx.opt(STR), mx.rescue_m(STR)] }, ("zz" =~ /z/; mx.rt(STR); mx.opt(STR); mx.rescue_m(STR); $~ && $~[0])] + +# 10. TracePoint enabled by a callee after the method's match: its :line and :return bindings see the match in CRuby. +# The one row the switch changes: a match sink stored the match in no frame, and a scope made for the hooks after the +# match has no $~ (`[[:line, nil], [:return, nil]]'). Not run unless MID=1, so that the matrix diffs clean; the light +# frame's sites take the scope while a TracePoint is enabled (RubyCallAction.BuildCall), which covers every TracePoint +# enabled before the method was entered. +if ENV['MID'] +def mid_enabler + $mid_tp = TracePoint.new(:line, :return) { |t| $mid_seen << [t.event, t.binding.eval("$~ && $~[0]")] if t.method_id == :mid } + $mid_tp.enable +end +def mid(s) + s =~ /b+/ + mid_enabler + 1 +end +def mid_plain(s) + s =~ /b+/ + 1 +end +hot { mid_plain(STR) } +$mid_seen = [] +mid(STR) +$mid_tp.disable +row "10. TracePoint enabled mid-frame", $mid_seen +end + +puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 20ae73e78..0fa3b9668 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1114,6 +1114,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has made twice cost. Nothing was built; the about 800 methods of the census's regex lines stay out. A step on them has to make the second call or the late scope cheaper (perf/lsite and perf/lsite2 tried the second and were rejected), not the light entry. + **perf/lightmatch** took the methods that cannot observe their `$~` (no reference, block, binding or eval): + there the call stores it in no frame and makes neither (+559 light frames, 0.93-0.97 of the instructions); the + methods that read their `$~` or have blocks are what is left. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per site at start-up, 0.2-0.4 ms). TruffleRuby's `Primitive.x` is replaced at parse time. @@ -1776,6 +1779,48 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lightmatch (2026-11-27) - a light frame lets String and Regexp methods store `$~` in no frame (gap 16, the + `$~` family)** - not gated. Chosen by the census of c1045a0: the regex lines were its largest refusal (gsub 273, + `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54). + - CRuby's rules, the matrix's rows: `$~` is the frame's own - a method's match never sets its caller's, which keeps + what it had (nil or a match); a block and a lambda see and set their method's; per thread too; `$1`..`$9`, `$&`, + `` $` ``, `$'`, `$+`, Regexp.last_match read it, `$~ = nil` and `$~ = md` set it (anything else is a TypeError); + binding, eval and a TracePoint's binding read the frame's; `alias $m $~` makes `$m` read it. + - So a method that cannot observe its `$~` needs it stored nowhere. `MethodDefinition.IsMatchSink`: no `$~`/`$1`... + reference, no block or lambda (a callee given one may ask for its binding), none of binding, eval, instance_eval, + class_eval, module_eval, send, `__send__`, public_send, method, public_method, singleton_method, last_match, + enable, set_trace_func, trace, and no global but the runtime's own. In such a method a regex literal given to + `=~ === match gsub(!) sub(!) scan split index rindex byteindex byterindex [] []= slice(!) start_with? partition + rpartition` or in a `when` no longer keeps it out of light frames, and those light sites get + `RubyCallFlags.HasMatchSink`. Their rule, once it has resolved a library method of String, Symbol or Regexp (which + take the scope to store `$~` and for the runtime only - not for a call they make, as rb_funcall), gives it the + runtime's EmptyScope (`CallArguments.MatchSink`) instead of answering LightScopeRequired - no late scope, no second + call. Not with c_call traced, and the rule tests `TracePoint.ActiveEvents` and takes the scope while any TracePoint + is on. Refinements, a Ruby `gsub` on String or a subclass, `!~` (Kernel's) and Enumerable#grep still read the + scope as before. Switch: `IR_LIGHT_MATCH_SINK=0`. + - **Known difference from CRuby:** a TracePoint enabled by a callee after the method's match, whose :line or + :return binding then reads the method's `$~`, sees nil (CRuby: the match). Matrix row 10, run with `MID=1`. The + sound form is a `$~` slot per light frame copied into a late scope; not built (it would pay a thread-local read + and write a call). Every TracePoint enabled before the method's entry is covered. + - Census (Src/StdLib + AWFY, 28,377 methods): light frames 26,732 -> 27,291 (+559, 94.2% -> 96.2%), none down; the + JIT's counts unchanged. The regex lines left: `=~` 138, gsub 82, `when` 45, split 31, match 29, scan 27, sub 27 - + methods that read their `$~` or have blocks. + - Instructions (`Util/perf/callgrind/count.sh`, regex-shapes, N=20000; base / switch off / new): gsub 12,610 / + 12,608 / 12,238 (0.971), split 10,769 / 10,769 / 10,378 (0.964), kase 8,426 / 8,426 / 8,133 (0.965), eqt 5,691 / + 5,690 / 5,289 (0.929); size, tilde 1.000, matchp level with off. Time (`ab.rb -r 5`, off / new, ns, load 12-14): + gsub 395 / 356 (0.90), split 326 / 306 (0.94), kase 253 / 213 (0.84), eqt 198 / 173 (0.87); size, matchp, tilde + overlap. (`ab.rb -i` over count.sh failed under ab.rb's CPU pinning here; each arm was run by hand.) + - Checks: the new `Util/light-match-sink-matrix.rb` (every method above, the caller's `$~` nil and set, no match, a + Regexp in a variable, grep; 21 methods that read their `$~`; `alias $mm $~`; threads; a refined gsub; String#=~ + with an object of the program's; a String subclass; a Symbol receiver; gsub redefined and restored after binding; + TracePoint :return and :c_return; a scope made late by respond_to?, block_given?, keywords, defaults, rescue), + regex-light, light-entry, hot-shapes, block-pass and jit: CRuby's output in all seven gate modes on both trees, 41 + same and regex-light under R2R as on base. ruby/spec language/predefined, core/regexp, core/string + gsub/sub/scan/split/match: 673 examples, the same three conversion-message errors on both. IronRuby.Tests: the new + Method_LightFrameMatchSink1 and 36 light-frame and regex tests pass (the new one with the switch off too). + - Found on the way, not fixed: `instance_eval("$~")` does not see its caller's `$~` (CRuby does), with or without the + switch. + - **perf/lightmember (2026-11-27) - `recv.m op= v` in a light frame (gap 9)** - not gated. Chosen by the census of 4320d4a + perf/neqrule: what keeps methods out of light frames is now mostly a regular expression whose method sets the caller's `$~` (gsub 273, `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54 - about 880 methods, which From ae0f0c692d00d26accd58b04599620a208ff8619 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:58:21 +0000 Subject: [PATCH 217/439] Park the scope of a method that calls Integer#downto, one per level of recursion AWFY Permute allocated 124.5 MB per iteration, 168 bytes per `permute` call, for an algorithm that needs a 6-element Array. permute is a light frame whose literal block reuses its Proc, but downto was in MethodDefinition.NeverParkedIterators, as it lacked [BlockNotKept], so every call made a scope, a Proc and a BlockParam. And a method's ParkedScopeSlot parks one scope, which a recursion six deep can use on one level only. - Both Integer#downto overloads are [BlockNotKept]: they only yield, as #times does, and the generic one's `<` and `-` never see the block. downto leaves the list (IR_PARK_DOWNTO=0 puts it back). - ParkedScopeSlot.Deeper holds the parked scopes of recursive calls: up to 7 more, made on the first overflow, each entry taken and filled by compare-exchange as Parked is (IR_PARKED_DEPTH, default 8, 1 as before). permute(6) 1,453 -> 411 KB. alloc.rb: Permute 124.5 -> 20.3 MB per iteration, Queens 30.5 -> 8.7, Havlak 1,774 -> 1,674, the others as before. AWFY, 10 alternating rounds, medians: Permute 0.933, Queens 0.969, Towers 1.000. Util/parked-scope-matrix.rb's new section 7 prints CRuby's output; the parked-scope, block-scope-reuse, block-nest-reuse, block-loop, osr-array, hot-shapes, jit, jit-calls and ivar matrices pass in every mode and with each switch off; spec/core/integer, core/proc and language block, yield and break as on the base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Libraries/Builtins/Integer.cs | 4 ++ .../Ast/Definitions/MethodDefinition.cs | 7 +++ Src/Ruby/Runtime/RubyOps.cs | 39 +++++++++++- Src/Ruby/Runtime/RubyScope.cs | 12 ++++ Util/parked-scope-matrix.rb | 59 +++++++++++++++++++ Util/perf/LEDGER.md | 26 ++++++++ 6 files changed, 145 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/Integer.cs b/Src/Libraries/Builtins/Integer.cs index 233fd0688..033bf9900 100644 --- a/Src/Libraries/Builtins/Integer.cs +++ b/Src/Libraries/Builtins/Integer.cs @@ -1149,7 +1149,10 @@ private static object UpToImpl(BinaryOpStorage/*!*/ greaterThanStorage, BinaryOp /// /// Since both self and other are Fixnum then this algorithm doesn't need to worry about overflowing into Bignum. /// + // Only yields to its block: a literal block's Proc, and the method's scope with it, can be made again for the next + // call ([BlockNotKept], as Integer#times; MethodDefinition.NeverParkedIterators). [RubyMethod("downto")] + [BlockNotKept] public static object DownTo(BlockParam block, int self, int other) { return (block != null) ? DownToImpl(block, self, other) : new Enumerator(self, "downto", other); } @@ -1185,6 +1188,7 @@ private static object DownToImpl(BlockParam/*!*/ block, int self, int other) { /// This approach automatically deals with Floats and overflow/underflow between Fixnum and Bignum. /// [RubyMethod("downto")] + [BlockNotKept] public static object DownTo(BinaryOpStorage/*!*/ lessThanStorage, BinaryOpStorage/*!*/ subtractStorage, BlockParam block, object/*!*/ self, object other) { diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 6e5c75da8..9cfdcb011 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -491,9 +491,16 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin }; internal static bool IsNeverParkedIterator(string/*!*/ name) { + // Integer#downto only yields ([BlockNotKept], as #times): a method that calls it with a literal (Permute's recursive + // `permute') may park its scope. IR_PARK_DOWNTO=0 counts it among the iterators above, as before. + if (name == "downto" && ParkDownTo) { + return false; + } return NeverParkedIterators.Contains(name); } + private static readonly bool ParkDownTo = Environment.GetEnvironmentVariable("IR_PARK_DOWNTO") != "0"; + /// /// IR_LIGHT_BLOCK_GIVEN=0 makes `block_given?' in a light-frame method the call it was before: the frame makes its /// scope and Kernel#block_given? reads the block from it (see LightFrameRewriter.LightScopeCall). diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 730427f3a..fd25702c8 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -247,7 +247,7 @@ internal static void ThrowStackLevelTooDeep() { public static ParkedProcs TakeParkedScope(ParkedScopeSlot/*!*/ slot, RubyScope/*!*/ parentScope, RubyModule/*!*/ declaringModule) { var parked = slot.Parked; if (parked == null) { - return null; + return (slot.Deeper == null) ? null : TakeDeeperParkedScope(slot, parentScope, declaringModule); } return TakeParkedScopeSlow(slot, parked, parentScope, declaringModule); } @@ -258,6 +258,23 @@ private static ParkedProcs TakeParkedScopeSlow(ParkedScopeSlot/*!*/ slot, Parked if (Interlocked.CompareExchange(ref slot.Parked, null, parked) != parked) { return null; } + return CheckTakenParkedScope(slot, parked, parentScope, declaringModule); + } + + // A recursive call, whose caller took Parked: one of the scopes its own recursive calls parked (ParkedScopeSlot.Deeper). + private static ParkedProcs TakeDeeperParkedScope(ParkedScopeSlot/*!*/ slot, RubyScope/*!*/ parentScope, RubyModule/*!*/ declaringModule) { + var deeper = slot.Deeper; + for (int i = 0; i < deeper.Length; i++) { + var parked = deeper[i]; + if (parked != null && Interlocked.CompareExchange(ref deeper[i], null, parked) == parked) { + return CheckTakenParkedScope(slot, parked, parentScope, declaringModule); + } + } + return null; + } + + private static ParkedProcs CheckTakenParkedScope(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, RubyScope/*!*/ parentScope, + RubyModule/*!*/ declaringModule) { // the same body may be defined in more than one module or runtime: a scope is only reused for the definition it was // made for (one parked for another goes back, or is dropped if a call parked meanwhile) var scope = parked.Scope; @@ -405,7 +422,7 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R methodScope.ClearCallState(); parked.Scope = methodScope; parked.ThreadId = Environment.CurrentManagedThreadId; - if (Interlocked.CompareExchange(ref slot.Parked, parked, null) == null) { + if (Interlocked.CompareExchange(ref slot.Parked, parked, null) == null || TryParkDeeper(slot, parked)) { return; } } else { @@ -415,6 +432,24 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R Volatile.Write(ref slot.Spare, parked); } + // Parked is full - this call's caller, or another thread, parked first: a free entry of Deeper. + private static bool TryParkDeeper(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked) { + if (ParkedScopeSlot.Depth <= 1) { + return false; + } + var deeper = slot.Deeper; + if (deeper == null) { + Interlocked.CompareExchange(ref slot.Deeper, new ParkedProcs[ParkedScopeSlot.Depth - 1], null); + deeper = slot.Deeper; + } + for (int i = 0; i < deeper.Length; i++) { + if (deeper[i] == null && Interlocked.CompareExchange(ref deeper[i], parked, null) == null) { + return true; + } + } + return false; + } + #endregion #region Light method frames diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index e59ef6b0d..9cd8c9e35 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1376,6 +1376,18 @@ public sealed class ParkedScopeSlot { internal ParkedProcs Parked; internal ParkedProcs Spare; + // The scopes of recursive calls: Parked serves one call at a time, so a method that calls itself (Permute's `permute', + // six deep) made a scope and Procs for every call below the first. A call that finds Parked taken takes one of these, + // and one that ends while Parked is full parks here; each entry is taken and filled with a compare-exchange, as Parked + // is. Made on the first such park; Deeper.Length + 1 calls deep are served. IR_PARKED_DEPTH (default 8, 1: Parked only). + internal ParkedProcs[] Deeper; + internal static readonly int Depth = GetDepth(); + + private static int GetDepth() { + int depth; + return Int32.TryParse(Environment.GetEnvironmentVariable("IR_PARKED_DEPTH"), out depth) && depth >= 1 ? Math.Min(depth, 64) : 8; + } + // The number of block literals of the body, the name it is defined under. internal int ProcCount; internal readonly string/*!*/ DefinitionName; diff --git a/Util/parked-scope-matrix.rb b/Util/parked-scope-matrix.rb index 3f1a0a3e1..ca6b03773 100644 --- a/Util/parked-scope-matrix.rb +++ b/Util/parked-scope-matrix.rb @@ -149,4 +149,63 @@ class P2 < P1; def run; [0].each { |z| z }; super; end; end class P3; def run; [0].each { |z| z }; yield 2; end; end t('super hands the block on, kept, break called later') { |i| P2.new.run { |x| break x }; P2.new.run { }; begin; $kb.call; rescue LocalJumpError => e; e.reason; end } t('a kept caller block after another call of the body') { |i| pr = nil; P3.new.run { |x| pr = proc { break x } }; P3.new.run { }; begin; pr.call; rescue LocalJumpError => e; e.reason; end } + +# ---------------------------------------------------------------- 7. downto, and recursion deeper than one parked scope +# (perf/permute) Integer#downto only yields ([BlockNotKept]), so a method calling it with a literal is parked; and a +# recursive method parks one scope per level (ParkedScopeSlot.Deeper, IR_PARKED_DEPTH) instead of one in all. Every row +# below is a way a scope of one level could be seen by another, or a scope that must not be parked could be. + +class PsPerm + attr_reader :count, :v + def initialize; @count = 0; @v = Array.new(6) { |k| k }; end + def permute(n) + @count += 1 + if n != 0 + n1 = n - 1 + permute(n1) + n1.downto(0) do |i| + swap(n1, i) + permute(n1) + swap(n1, i) + end + end + end + def swap(i, j); tmp = @v[i]; @v[i] = @v[j]; @v[j] = tmp; end +end +t('Permute: count and the array after permute(5)') { |i| o = PsPerm.new; o.permute(5); [o.count, o.v] } + +class PsDeep + def r(n, acc) + x = n * 10 + n.downto(1) { |i| acc << [x, i] if i == n || i == 1; r(n - 1, acc) if i == n } + acc + end + def boom(n, at) + x = n + n.downto(1) { |i| raise "at #{x}" if n == at; boom(n - 1, at) if i == n } + x + end +end +pd = PsDeep.new +t('each level sees its own locals, 4 deep') { |i| pd.r(4, []) } +t('each level sees its own locals, 12 deep (past the slots)') { |i| pd.r(12, []).size } +t('an exception 3 levels down, then a normal call') { |i| e = (pd.boom(6, 3) rescue $!.message); [e, pd.boom(5, -1)] } + +class PsDownto + def keep_binding(n); y = n; n.downto(0) { |i| $ps_b = binding if i == 0 }; y; end + def keep_proc(n); n.downto(0) { |i| $ps_p = proc { [n, i] } if i == 0 }; n; end + def brk(n) = n.downto(0) { |i| break i * 100 if i == 2 } + def nxt(n); s = 0; n.downto(0) { |i| next if i.odd?; s += i }; s; end + def float(n); s = []; n.downto(1.5) { |i| s << i }; s; end + def big(n); s = 0; (2**64 + n).downto(2**64) { |i| s += 1 }; s; end +end +pdt = PsDownto.new +t('a binding kept from a downto block, then another call') { |i| pdt.keep_binding(i % 5); b = $ps_b; pdt.keep_binding(7); b.local_variable_get(:y) == i % 5 } +t('a Proc made in a downto block, then another call') { |i| pdt.keep_proc(i % 4); pr = $ps_p; pdt.keep_proc(9); pr.call == [i % 4, 0] } +t('break out of downto') { |i| pdt.brk(5) } +t('next in downto') { |i| pdt.nxt(9) } +t('downto a Float') { |i| pdt.float(4) } +t('downto over Bignums') { |i| pdt.big(3) } +t('two threads recurse in the same method') { |i| a = PsPerm.new; b = PsPerm.new; [Thread.new { a.permute(4); a.count }, Thread.new { b.permute(4); b.count }].map(&:value) } +t('downto without a block') { |i| 3.downto(1).to_a } puts 'end' diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1f61e4598..d107f92e7 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1786,6 +1786,32 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/permute (2026-11-27, not gated) - Integer#downto parks its caller's scope, and a recursive + method parks one scope per level** (switches `IR_PARK_DOWNTO`, `IR_PARKED_DEPTH`). alloc.rb on 9b588fc: + Permute 124.5 MB per iteration, 1.45 MB per `permute(6)` (8,660 calls), for an algorithm that needs + a 6-element Array. Variants: with `while` in place of `downto` 208 KB (`@count += 1` boxes an Integer + on every call, the cached ones below 1,024 included); so about 144 bytes per call came from the block. + `permute` is a light frame whose literal block reuses its Proc, but `downto` was in + `MethodDefinition.NeverParkedIterators` (it lacked `[BlockNotKept]`, which `times` has), so the + method had no parking slot and made a scope, a Proc and a BlockParam on every call; and a slot parks + one scope, which a recursion six deep could use on one level only. Now both Integer#downto overloads + are `[BlockNotKept]` (they only yield; the generic one's `<` and `-` never see the block) and + `downto` leaves the list; and `ParkedScopeSlot.Deeper` (up to 7 more, made on the first overflow, + each taken and filled by compare-exchange as `Parked` is) holds the scopes of recursive calls. + `permute(6)` 1,453 -> 746 KB (downto) -> 411 KB (depth). An in-process GC allocation-tick listener + (an IronRuby subclass of EventListener) sampled what is left: boxed Int32 5,470, the scoped calls' + `MutableTuple` locals 2,234, the rest small. alloc.rb: Permute 124.5 -> 20.3 MB, + Queens 30.5 -> 8.7 MB, Havlak 1,774 -> 1,674 MB, the others as before. AWFY, 10 alternating rounds, + medians: Permute 112,970 -> 105,378 us (0.933, no overlap), Queens 0.969, Towers 1.000. + `Util/parked-scope-matrix.rb` gains section 7 (Permute; each level's locals, 4 and 12 deep; an + exception three levels down; a binding and a Proc kept from a downto block; break, next, a Float + and Bignum bounds, no block; two threads in the same recursive method): CRuby's output on both builds. + Checks: parked-scope, block-scope-reuse, block-scope-reuse-blockpass, block-nest-reuse, block-loop, + osr-array, hot-shapes, jit, jit-calls and ivar matrices in every mode and with each switch off: + PASS; block-scope-reuse-race 10 of 10 as CRuby; spec/core/integer, core/proc and language + block/yield/break as on the base. Left: the `@count` boxes (an Integer instance variable is held + boxed, raw only for Floats) and the locals tuple per scoped call. + - **perf/sieve (2026-11-27, not gated) - a block-local first assigned inside an `if` branch or a `while` body no longer keeps the block from being outlined** (switch `IR_BLOCK_LOOP_SCOPED`). AWFY Sieve allocated 100.3 MB per iteration (alloc.rb). Bytes per `sieve` call, by variants: the From ae730f625b31ff3f0adcc6125bce92afd16d1a29 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:01:33 +0000 Subject: [PATCH 218/439] TracePoint: attr_reader and attr_writer calls report :c_call and :c_return CRuby's attr_reader/attr_writer/attr_accessor methods are C methods, so a TracePoint on :c_call/:c_return sees each call (with the value read or written as the return value). IronRuby reported nothing: the attribute rule and its fast dispatchers had no tracing, and the method JIT and compiled loops read and write the instance variable directly. While c_call is traced (TracePoint.CCallTracing, which already rebinds every rule and bumps the global method version when it changes), the attribute rule gets the library methods' TraceLibraryCall/Return around it (RubyLibraryMethodInfo.AddCallTracing, now shared), the attribute dispatchers stand aside, and the JIT's attribute sites do not bind (they rebind on the method version, so code compiled earlier falls back to the call). All of it is decided when a site binds; an untraced call runs the same code as before. TracePoint_AttrAccessorCCall1 holds CRuby's output (direct, send, public_send, Method#call, a JIT-compiled method and loop before, during and after tracing, with and without -X:NoJIT). spec/core/tracepoint and Module#attr* specs pass; the light, member and backtrace matrices print CRuby's output; the TracePoint, attribute, light-frame, JIT and loop IronRuby.Tests pass. Util/bench/frame-cost.rb and app-shapes' invoice, render, rules and ostruct against the same merge without the change, by clock with ab.rb: every shape within the noise (new/base 0.84-1.08, spreads overlapping). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 44 +++++++++++++++++++ Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs | 14 +++++- .../Runtime/Calls/RubyLibraryMethodInfo.cs | 11 +++-- Src/Ruby/Runtime/Jit/JitRuntime.cs | 11 ++++- 5 files changed, 74 insertions(+), 7 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 6d9a2544c..c47939208 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1166,6 +1166,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrame2, Block_RegisterLocals1, TracePoint_EndlessDefLine1, + TracePoint_AttrAccessorCCall1, Defined_ConditionNoFreeze1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 5c960c00e..4a9f601b1 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -9225,6 +9225,50 @@ comparison of Integer with nil failed "); } + /// + /// attr_reader and attr_writer methods are C methods to CRuby's TracePoint: :c_call and :c_return, through + /// every kind of call, in a method the JIT compiled before the TracePoint was enabled too, and nothing once it is off. + /// + public void TracePoint_AttrAccessorCCall1() { + TestOutput(@" +require 'ruby4' +class C; attr_accessor :x; attr_reader :r; attr_writer :w; def initialize; @r = 1; end; end +c = C.new +ev = [] +tp = TracePoint.new(:c_call, :c_return, :call, :return) { |t| ev << [t.event, t.method_id, t.defined_class, (t.return_value if t.event.to_s.end_with?(""return""))] if t.defined_class == C } +tp.enable { c.x = 5; c.x; c.r; c.w = 2; c.send(:x); c.public_send(:x=, 3); c.method(:x).call } +ev.each { |e| p e } +class D; attr_accessor :x; def initialize; @x = 0; end; def bump; self.x = x + 1; end; def loop_read(n) = (s = 0; i = 0; while i < n; s += x; i += 1; end; s); end +c = D.new +5000.times { c.bump; c.loop_read(3) } +ev2 = [] +tp2 = TracePoint.new(:c_call, :c_return) { |t| ev2 << [t.event, t.method_id] if t.defined_class == D } +tp2.enable { c.bump; c.loop_read(2) } +p ev2 +ev2.clear +3000.times { c.bump; c.loop_read(3) } +p ev2, c.x +", @" +[:c_call, :x=, C, nil] +[:c_return, :x=, C, 5] +[:c_call, :x, C, nil] +[:c_return, :x, C, 5] +[:c_call, :r, C, nil] +[:c_return, :r, C, 1] +[:c_call, :w=, C, nil] +[:c_return, :w=, C, 2] +[:c_call, :x, C, nil] +[:c_return, :x, C, 5] +[:c_call, :x=, C, nil] +[:c_return, :x=, C, 3] +[:c_call, :x, C, nil] +[:c_return, :x, C, 3] +[[:c_call, :x], [:c_return, :x], [:c_call, :x=], [:c_return, :x=], [:c_call, :x], [:c_return, :x], [:c_call, :x], [:c_return, :x]] +[] +8001 +"); + } + /// /// The expression of an endless def is not a line to TracePoint :line (prism gives it no newline flag): CRuby reports /// no event for it, with or without a rescue modifier, but does for statements in parentheses in it and in a block. diff --git a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs index ff7be0ccc..d1830281f 100644 --- a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs @@ -84,7 +84,9 @@ public RubyAttributeReaderInfo(RubyMemberFlags flags, RubyModule/*!*/ declaringM } internal override MemberDispatcher GetDispatcher(Type/*!*/ delegateType, RubyCallSignature signature, object target, int version) { - if (!(target is IRubyObject)) { + // CRuby's attr methods are C methods, reported as :c_call/:c_return; the dispatcher reports nothing, + // so a site bound while c_call is traced takes the rule (switching tracing rebinds every site) + if (!(target is IRubyObject) || TracePoint.CCallTracing) { return null; } @@ -105,6 +107,9 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA AstUtils.Box(args.TargetExpression), AstUtils.Constant(new InstanceVariableSite(InstanceVariableName)) )); + if (TracePoint.CCallTracing) { + metaBuilder.Result = RubyLibraryMethodInfo.AddCallTracing(this, metaBuilder.Result, args, name); + } } } @@ -123,7 +128,9 @@ public RubyAttributeWriterInfo(RubyMemberFlags flags, RubyModule/*!*/ declaringM } internal override MemberDispatcher GetDispatcher(Type/*!*/ delegateType, RubyCallSignature signature, object target, int version) { - if (!(target is IRubyObject)) { + // CRuby's attr methods are C methods, reported as :c_call/:c_return; the dispatcher reports nothing, + // so a site bound while c_call is traced takes the rule (switching tracing rebinds every site) + if (!(target is IRubyObject) || TracePoint.CCallTracing) { return null; } @@ -144,6 +151,9 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA AstUtils.Convert(args.ContextScopeExpression, typeof(RubyScope)), AstUtils.Constant(new InstanceVariableSite(InstanceVariableName)) )); + if (TracePoint.CCallTracing) { + metaBuilder.Result = RubyLibraryMethodInfo.AddCallTracing(this, metaBuilder.Result, args, name); + } } } diff --git a/Src/Ruby/Runtime/Calls/RubyLibraryMethodInfo.cs b/Src/Ruby/Runtime/Calls/RubyLibraryMethodInfo.cs index 9b66e1640..8dbea7d1c 100644 --- a/Src/Ruby/Runtime/Calls/RubyLibraryMethodInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyLibraryMethodInfo.cs @@ -246,14 +246,19 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA // Rules are rebound when c_call tracing is switched on or off, so a rule bound without it costs nothing. if (TracePoint.CCallTracing && !metaBuilder.Error && metaBuilder.Result != null) { - metaBuilder.Result = AddCallTracing(metaBuilder.Result, args, name); + metaBuilder.Result = AddCallTracing(this, metaBuilder.Result, args, name); } } - private Expression/*!*/ AddCallTracing(Expression/*!*/ call, CallArguments/*!*/ args, string/*!*/ name) { + /// + /// :c_call before and :c_return after , the body of a rule for , a + /// method CRuby implements in C (a library method, an attr_reader or attr_writer). Only for a rule bound while + /// c_call is traced: switching it on or off rebinds every rule. + /// + internal static Expression/*!*/ AddCallTracing(RubyMemberInfo/*!*/ info, Expression/*!*/ call, CallArguments/*!*/ args, string/*!*/ name) { Expression scope = AstUtils.Convert(args.MetaScope.Expression, typeof(RubyScope)); Expression target = AstUtils.Convert(args.TargetExpression, typeof(object)); - Expression method = AstUtils.Constant(this, typeof(RubyMemberInfo)); + Expression method = AstUtils.Constant(info, typeof(RubyMemberInfo)); Expression methodName = AstUtils.Constant(name); Expression before = Methods.TraceLibraryCall.OpCall(scope, target, method, methodName); diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 29e31fd20..cb6af48f9 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -616,7 +616,11 @@ internal static string ReaderVariable(RubyClass/*!*/ cls, string/*!*/ name, bool var resolved = Resolve(cls, name, publicOnly); if (!resolved.Found) { return null; } var reader = resolved.Info as IronRuby.Runtime.Calls.RubyAttributeReaderInfo; - return (reader != null) ? reader.InstanceVariableName : TrivialAccessorVariable(cls, resolved.Info, false); + if (reader != null) { + // an attr_reader is a C method to TracePoint's :c_call, which a read of the variable would not report + return TracePoint.CCallTracing ? null : reader.InstanceVariableName; + } + return TrivialAccessorVariable(cls, resolved.Info, false); } /// @@ -627,7 +631,10 @@ internal static string WriterVariable(RubyClass/*!*/ cls, string/*!*/ name, bool var resolved = Resolve(cls, name, publicOnly); if (!resolved.Found) { return null; } var writer = resolved.Info as IronRuby.Runtime.Calls.RubyAttributeWriterInfo; - return (writer != null) ? writer.InstanceVariableName : TrivialAccessorVariable(cls, resolved.Info, true); + if (writer != null) { + return TracePoint.CCallTracing ? null : writer.InstanceVariableName; + } + return TrivialAccessorVariable(cls, resolved.Info, true); } /// From ced768eb6979c11da12689d13942df41f90dc2c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:04:22 +0000 Subject: [PATCH 219/439] Pass `f(*a, **h)' the list itself and no array for an empty h A call that splats a list and then a keyword hash - the forward of every `(*a, **k)' and `(*, **)' method - went through UnsplatArguments: a copy of the list, a one-or-zero element array of the hash (SplatKeywordHash), and an AddRange of one into the other. Three arrays per call, for the common case of a forward that passes no keywords: `(*a, **k) = two(*a, **k)' took 174 ns against 71 for `(*a) = two(*a)' (CRuby 109 and 84). CRuby 4.0 compiles it to `splatarray false' when h is a variable: the list itself, and an empty or nil h passes nothing. A #to_hash that appends to the list shows in the arguments there, where IronRuby's copy hid it. When the keyword splat is the lone `**h' of a variable, constant or literal (KeywordArgumentSplat.IsLoneSideEffectFree), the splatted argument is now the list when the hash passes nothing, and `[*a, h]' (RubyOps.SplatAppendItem, one array) when it passes one. It is not fresh, so a rest parameter of the callee copies it as for `f(*a)'. IR_KWSPLAT_BY_REFERENCE=0 restores UnsplatArguments. Checked with the new Util/kwsplat-forward-matrix.rb (next commit) and the splat, keyword and forward matrices in every mode; specs and IronRuby.Tests as recorded in Util/perf/LEDGER.md. By clock (ab.rb, Release): rest_kw 174 -> 124 ns, rest_kw_blk 184 -> 128. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/Ruby/Compiler/Ast/Arguments.cs | 28 +++++++++++++++++++ .../Compiler/Ast/Expressions/MethodCall.cs | 2 +- Src/Ruby/Compiler/Ast/KeywordArgumentSplat.cs | 11 ++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Compiler/Ast/Arguments.cs b/Src/Ruby/Compiler/Ast/Arguments.cs index d9e818c26..70c767458 100644 --- a/Src/Ruby/Compiler/Ast/Arguments.cs +++ b/Src/Ruby/Compiler/Ast/Arguments.cs @@ -19,6 +19,7 @@ using System.Collections; using System.Collections.Generic; using Microsoft.Scripting.Utils; +using IronRuby.Builtins; using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronRuby.Compiler.Ast { @@ -26,6 +27,12 @@ namespace IronRuby.Compiler.Ast { public class Arguments { internal static readonly Arguments Empty = new Arguments(); + /// + /// IR_KWSPLAT_BY_REFERENCE=0: `f(*a, **h)' copies a and appends h's one-or-zero element array to the copy, as it + /// used to (see TransformToCallInternal). + /// + internal static readonly bool KeywordSplatByReference = System.Environment.GetEnvironmentVariable("IR_KWSPLAT_BY_REFERENCE") != "0"; + private readonly Expression/*!*/[]/*!*/ _expressions; public bool IsEmpty { @@ -92,6 +99,27 @@ private MSA.Expression TransformToCallInternal(AstGenerator/*!*/ gen, ICollectio var method = gen.CurrentMethod; fresh = method != null && gen.CurrentBlock == null && ReferenceEquals(_expressions[firstSplatted], method.ForwardedRestSplat); return _expressions[firstSplatted].TransformRead(gen); + } else if (splattedCount == 2 && firstSplatted == _expressions.Length - 2 && KeywordSplatByReference && + !(_expressions[firstSplatted] is KeywordArgumentSplat) && + _expressions[firstSplatted + 1] is KeywordArgumentSplat keywords && keywords.IsLoneSideEffectFree) { + // `f(*a, **h)', the forward of `(*a, **h)' and `(*, **)': CRuby 4.0 passes the list itself (`splatarray false' + // when the keyword splat is a variable) and an empty or nil h as no argument at all. So the list is not copied: + // it is what the call splats when h passes nothing, and `[*a, h]' - one array, of the size it ends up - when + // it passes a hash. UnsplatArguments copied the list, made a one-or-zero element array of the hash and appended + // that, three arrays for a call that passed none. Not fresh: a rest parameter of the callee copies the list as + // for `f(*a)'. IR_KWSPLAT_BY_REFERENCE=0 goes through UnsplatArguments. + var list = gen.CurrentScope.DefineHiddenVariable("#splat", typeof(IList)); + var hash = gen.CurrentScope.DefineHiddenVariable("#kwsplat", typeof(Hash)); + return MSA.Expression.Block( + MSA.Expression.Assign(list, AstUtils.Convert(_expressions[firstSplatted].TransformRead(gen), typeof(IList))), + MSA.Expression.Assign(hash, keywords.TransformToArgument(gen)), + MSA.Expression.Condition( + MSA.Expression.ReferenceEqual(hash, AstUtils.Constant(null)), + list, + AstUtils.Convert(Methods.SplatAppendItem.OpCall(list, hash), typeof(IList)), + typeof(IList) + ) + ); } else if (splattedCount >= 1) { fresh = true; return UnsplatArguments(gen, firstSplatted); diff --git a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs index b6e52098b..e414457cc 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs @@ -258,7 +258,7 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { /// CRuby 4.0 passes such a call's trailing splat uncopied (prism_compile.c, pm_setup_args_dup_rest_p, which also counts /// a few more shapes, such as `[]', that no #to_proc could tell apart). /// - private static bool IsSideEffectFree(Expression/*!*/ expression) { + internal static bool IsSideEffectFree(Expression/*!*/ expression) { switch (expression) { case LocalVariable _: case InstanceVariable _: diff --git a/Src/Ruby/Compiler/Ast/KeywordArgumentSplat.cs b/Src/Ruby/Compiler/Ast/KeywordArgumentSplat.cs index aa91ad020..d5aca962e 100644 --- a/Src/Ruby/Compiler/Ast/KeywordArgumentSplat.cs +++ b/Src/Ruby/Compiler/Ast/KeywordArgumentSplat.cs @@ -79,6 +79,17 @@ private KeywordArgumentSplat(Expression/*!*/ hash, Expression/*!*/ converted, Lo return new KeywordArgumentSplat(hash, converted, keywords); } + /// + /// `f(..., **h)` with h a variable, a constant or a literal (MethodCall.IsSideEffectFree): reading it runs no Ruby code, + /// so a positional splat before it need not be copied before it is read (Arguments.TransformToCallInternal). + /// + internal bool IsLoneSideEffectFree { + get { + return _converted != null && _keywords == null && + Argument is SimpleAssignmentExpression assignment && MethodCall.IsSideEffectFree(assignment.Right); + } + } + internal override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { if (_converted != null) { return MSA.Expression.Coalesce( From acbf96619f3384595a5b179f12cc33621cc9c9d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:04:23 +0000 Subject: [PATCH 220/439] Read an anonymous `*' back for `super' instead of copying the arguments A method whose signature mixes keywords with a rest (`def m(*, **)', `def m(a, *, d:)') is lowered to one splat that its prologue takes apart, and kept `?superargs?', a copy of the whole argument list, on every call for a parameterless `super' - unless every positional could be read back by name, which CanReadBackPositionals said an anonymous `*' could not. The copy also kept the method out of light frames ("optional, splat or post parameters"). So `def w(*, **, &) = two(*, **, &)' took 264 ns against CRuby's 88. The prologue binds an anonymous `*' of a method to the hidden local `?rest?' (Symbols.RestArgsLocal), which `f(*)' reads and nothing can assign. `super' now reads it back from there, as it does a named rest, and eval('super') (SuperCall.EvalImplicitArguments) reads it there too rather than by its signature name `*' - IronRuby.Tests' SuperParameterlessEval2 caught that case. Checked: new Util/kwsplat-forward-matrix.rb (empty and nil `**', arity errors, optional, keyword and mutating callees, positional Hashes, to_hash, to_a, ruby2_keywords, forwarders, redefinition, method_missing, super(*, **, &), zsuper and eval('super') from anonymous signatures) same as CRuby in every mode, but for three probes that differ on the base build as well (listed in its header); splat-blockarg, splat-pass, kwrest-call, keyword-light, keyword-rest-light, anon-forward, block-pass, light-entry and hot-shapes matrices unchanged; language/keyword_arguments, send, def, super and method specs as before; IronRuby.Tests passed. By clock: anon 264 -> 132 ns. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/Prism/PrismAstBridge.cs | 11 +- .../Compiler/Ast/Expressions/SuperCall.cs | 7 +- Util/kwsplat-forward-matrix.rb | 137 ++++++++++++++++++ Util/perf/LEDGER.md | 47 ++++++ 4 files changed, 197 insertions(+), 5 deletions(-) create mode 100644 Util/kwsplat-forward-matrix.rb diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 4b9e6b120..2ae924d7b 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -2409,13 +2409,16 @@ private bool IsYieldAllowed() { /// /// Whether every positional parameter has a name can - /// read it back by: no destructuring, no anonymous `*`. + /// read it back by: no destructuring. An anonymous `*` of a method is read back from the hidden local the prologue + /// binds it to (Symbols.RestArgsLocal, which `f(*)` reads too and nothing can assign): `def m(*, **)' did not, and + /// kept a copy of its whole argument list on every call for a `super' it had not got (LowerGeneralParameters's + /// ?superargs?), which also kept it out of light frames. Only methods ask (blocks have no parameterless `super'). /// private static bool CanReadBackPositionals(Pm.ParametersNode/*!*/ node) { foreach (var required in node.Requireds) { if (!(required is Pm.RequiredParameterNode)) return false; } - if (node.Rest != null && !(node.Rest is Pm.RestParameterNode rest && rest.Name != null)) return false; + if (node.Rest != null && !(node.Rest is Pm.RestParameterNode)) return false; foreach (var post in node.Posts) { if (!(post is Pm.RequiredParameterNode)) return false; } @@ -2442,8 +2445,8 @@ private List ZSuperPositionalArguments(Pm.ParametersNode/*!*/ node) } if (node.Rest != null) { - if (!(node.Rest is Pm.RestParameterNode rest) || rest.Name == null) return null; - result.Add(new SplattedArgument(CurrentScope.ResolveOrAddVariable(rest.Name, Span(node.Rest)))); + if (!(node.Rest is Pm.RestParameterNode rest)) return null; + result.Add(new SplattedArgument(CurrentScope.ResolveOrAddVariable(rest.Name ?? Symbols.RestArgsLocal, Span(node.Rest)))); } foreach (var post in node.Posts) { diff --git a/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs b/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs index beacc51d7..350e6167d 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs @@ -256,7 +256,12 @@ private Arguments EvalImplicitArguments(AstGenerator/*!*/ gen) { } break; case "rest": - arguments.Add(new SplattedArgument(ReadLocal(parameter.Name, span))); + // an anonymous `*' is read back from the hidden local the prologue binds it to, as a `super' in the + // method itself reads it (PrismAstBridge.CanReadBackPositionals), which no longer keeps ?superargs? + // for it + arguments.Add(new SplattedArgument(ReadLocal( + parameter.Name == "*" && gen.CompilerOptions.LocalNames != null && + gen.CompilerOptions.LocalNames.Contains(Symbols.RestArgsLocal) ? Symbols.RestArgsLocal : parameter.Name, span))); break; case "keyreq": case "key": diff --git a/Util/kwsplat-forward-matrix.rb b/Util/kwsplat-forward-matrix.rb new file mode 100644 index 000000000..aedfae468 --- /dev/null +++ b/Util/kwsplat-forward-matrix.rb @@ -0,0 +1,137 @@ +# Differential matrix for a call that splats a list and then a keyword hash (`f(*a, **h)', the forwards of `(*a, **h)' +# and `(*, **)'), which passes the list itself and, for an empty or nil h, no keyword argument at all +# (Arguments.TransformToCallInternal; IR_KWSPLAT_BY_REFERENCE=0 copied the list and appended h's one-or-zero element +# array); and a parameterless `super' in a method with an anonymous `*' (PrismAstBridge.CanReadBackPositionals). +# +# ruby Util/kwsplat-forward-matrix.rb > mri.txt +# ./ir.sh Util/kwsplat-forward-matrix.rb > on.txt +# IR_LIGHT_FRAMES=0 ./ir.sh Util/kwsplat-forward-matrix.rb > scoped.txt +# diff mri.txt on.txt && diff mri.txt scoped.txt +# +# Three probes differ from CRuby 4.0 on builds before and after this change and are kept to show it: a `**' copy loses +# the hash's default proc, and a ruby2_keywords hash ends the list before an explicit empty `**' (CRuby passes it +# positionally, flag and all; IronRuby's call sites take it as keywords whenever it is the last item splatted). +# +# Each probe runs 3000 times (interpreted, then compiled) and prints every distinct answer once. + +N = 3000 + +def t(label) + print label.ljust(56), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 70]}" + end +end + +def two(a, b) = [a, b] +def opt(a, b = :d) = [a, b] +def kw(a, k: :k) = [a, k] +def kwr(*a, **k) = [a, k] +def any(*a, **k, &b) = [a, k, b && b.call] +def mut(*a, **k) = (k[:added] = 1; a << :added; [a, k]) +def pos(a, b) = [a, b.class] + +class ToHash; def initialize(log, h) = (@log = log; @h = h); def to_hash = (@log << :to_hash; @h); end +class Grow; def initialize(a) = @a = a; def to_hash = (@a << 3; {}); end +class BadHash; def to_hash = 1; end + +def fwd(*a, **k) = any(*a, **k) +def fwd_anon(*, **) = any(*, **) +def fwd_anon_blk(*, **, &) = any(*, **, &) +def fwd_two(*, **) = two(*, **) +def fwd_opt(*, **) = opt(*, **) +def fwd_kw(*, **) = kw(*, **) +def fwd_mut(*, **) = mut(*, **) +def fwd_pos(*, **) = pos(*, **) + +# ---------------------------------------------------------------- 1. empty and nil keyword splats pass nothing +t("f(*a, **{}) to a fixed-arity callee") { |i| a = [1, 2]; h = {}; two(*a, **h) } +t("f(*a, **nil)") { |i| a = [1, 2]; h = nil; two(*a, **h) } +t("f(*a, **h), h empty then not") { |i| a = [1]; h = i.even? ? {} : {k: i % 3}; (kw(*a, **h) rescue [$!.class, $!.message]) } +t("too many: f(*a, **h) with h given to two(a, b)") { |i| a = [1, 2]; h = {k: 1}; (two(*a, **h) rescue [$!.class, $!.message]) } +t("too few") { |i| a = [1]; h = {}; (two(*a, **h) rescue [$!.class, $!.message]) } +t("list changing length between calls") { |i| a = i.even? ? [1, 2] : [1, 2, 3]; h = {}; (two(*a, **h) rescue [$!.class, $!.message]) } +t("optional-parameter callee") { |i| a = i.even? ? [1] : [1, 2]; h = {}; opt(*a, **h) } +t("optional-parameter callee, keywords as positional") { |i| a = [1]; h = {k: 1}; opt(*a, **h) } +t("keywords and a positional Hash") { |i| a = [1, {p: 1}]; h = {k: 2}; kwr(*a, **h) } +t("positional Hash, empty keywords") { |i| a = [1, {p: 1}]; h = {}; kwr(*a, **h) } +t("positional Hash to a keyword callee, empty keywords") { |i| a = [{p: 1}]; h = {}; (kw(*a, **h) rescue [$!.class, $!.message]) } +t("nil splat and nil keywords") { |i| a = nil; h = nil; kwr(*a, **h) } + +# ---------------------------------------------------------------- 2. the callee's arguments are its own +t("callee mutates its **k and *a") { |i| a = [1]; h = {k: 1}; r = mut(*a, **h); [r, a, h] } +t("callee mutates them, empty keywords") { |i| a = [1]; h = {}; r = mut(*a, **h); [r, a, h] } +t("frozen list and hash") { |i| a = [1, 2].freeze; h = {}.freeze; two(*a, **h) } +t("frozen hash given") { |i| a = [1].freeze; h = {k: 3}.freeze; r = mut(*a, **h); [r, h.frozen?] } +t("compare_by_identity hash") { |i| a = [1]; h = {}.compare_by_identity; h[:k] = 1; kwr(*a, **h) } +t("hash with a default proc") { |i| a = [1]; h = Hash.new { 0 }; h[:k] = 1; r = kwr(*a, **h); [r, r[1].default_proc.nil?] } + +# ---------------------------------------------------------------- 3. conversions +t("non-Hash **obj: to_hash, order") { |i| log = []; a = [1]; o = ToHash.new(log, {k: 1}); [kwr(*a, **o), log] } +t("non-Hash **obj returning empty") { |i| log = []; a = [1, 2]; o = ToHash.new(log, {}); [two(*a, **o), log] } +t("to_hash that grows the splatted list") { |i| a = [1, 2]; o = Grow.new(a); [kwr(*a, **o), a] } +t("to_hash returning a non-Hash") { |i| a = [1]; o = BadHash.new; (kwr(*a, **o) rescue [$!.class, $!.message]) } +t("**obj with no to_hash") { |i| a = [1]; o = Object.new; (kwr(*a, **o) rescue [$!.class]) } +t("non-Array *obj: to_a") { |i| a = 1..2; h = {}; two(*a, **h) } +t("keyword hash from a call: evaluated after the list") { |i| a = [1, 2]; r = kwr(*a, **(a << 9; {k: 1})); [r, a] } +t("non-Symbol keys") { |i| a = [1]; h = {"s" => 1, 2 => 3}; kwr(*a, **h) } + +# ---------------------------------------------------------------- 4. ruby2_keywords +ruby2_keywords def r2k_fwd(*a) = kwr(*a) +ruby2_keywords def r2k_fwd_kw(*a) = (h = {}; kwr(*a, **h)) +t("ruby2_keywords hash passed on") { |i| r2k_fwd(1, k: 2) } +t("ruby2_keywords hash with **{} after it") { |i| r2k_fwd_kw(1, k: 2) } +t("ruby2_keywords hash flag after **{}") do |i| + h = Hash.ruby2_keywords_hash({k: 1}) + a = [1, h]; e = {} + r = kwr(*a, **e) + [r[0].last.equal?(h), r[1]] +end + +# ---------------------------------------------------------------- 5. forwarders +t("(*a, **k) forward") { |i| i.even? ? fwd(1, 2, k: 3) : fwd(1, 2) } +t("(*, **) forward") { |i| i.even? ? fwd_anon(1, 2, k: 3) : fwd_anon(1) } +t("(*, **, &) forward, with and without a block") { |i| i.even? ? fwd_anon_blk(1, k: 3) { :b } : fwd_anon_blk(1) } +t("(*, **) to a fixed-arity callee") { |i| (fwd_two(*[1, 2][0, 1 + i % 2]) rescue [$!.class, $!.message]) } +t("(*, **) to a fixed-arity callee, keywords given") { |i| (fwd_two(1, k: 1) rescue [$!.class, $!.message]) } +t("(*, **) to an optional-parameter callee") { |i| i.even? ? fwd_opt(1) : fwd_opt(1, k: 2) } +t("(*, **) to a keyword callee") { |i| (i.even? ? fwd_kw(1) : fwd_kw(1, k: 2)) rescue [$!.class, $!.message] } +t("(*, **) to a callee that mutates") { |i| a = [1]; h = {k: 1}; r = fwd_mut(*a, **h); [r, a, h] } +t("(*, **) positional Hash stays positional") { |i| fwd_pos(1, {p: 1}) } +t("(*, **) positional Hash and keywords") { |i| (fwd_pos(1, {p: 1}, k: 2) rescue [$!.class, $!.message]) } + +class Redef; def m(a, b) = :first; def call(*, **) = m(*, **); end +t("callee redefined after the site bound") do |i| + o = Redef.new + Redef.class_eval { def m(a, b, **k) = [:second, k] } if i == 1500 + o.call(1, 2) +end +class MM; def method_missing(n, *a, **k, &b) = [n, a, k, b && b.call]; def respond_to_missing?(*) = true + def go(*, **) = ghost(*, **); end +t("method_missing callee") { |i| i.even? ? MM.new.go(1, 2) : MM.new.go(1, k: 2) } + +# ---------------------------------------------------------------- 6. super with an anonymous rest +class SupP; def m(*a, **k, &b) = [a, k, b && b.call]; def o(a, b = :d, k: :k) = [a, b, k]; end +class SupA < SupP; def m(*, **, &) = super(*, **, &); end +class SupZ < SupP; def m(*, **) = super; end +class SupZK < SupP; def m(x, *, y, k: 1, **) = super; end +class SupZO < SupP; def o(*, k: 0) = super; end +class SupZG < SupP; def m(*, **) = (g(*); super); def g(*r) = (r.clear; r << :g); end +t("super(*, **, &)") { |i| i.even? ? SupA.new.m(1, 2, k: 3) { :blk } : SupA.new.m } +t("zsuper from (*, **)") { |i| i.even? ? SupZ.new.m(1, 2, k: 3) { :blk } : SupZ.new.m } +t("zsuper from (x, *, y, k: 1, **)") { |i| i.even? ? SupZK.new.m(1, 2, 3, 4, k: 5, q: 6) : SupZK.new.m(1, 2) } +t("zsuper from (*, k: 0) to an optional-parameter parent") { |i| i.even? ? SupZO.new.o(1) : SupZO.new.o(1, 2, k: 3) } +t("zsuper after the rest was passed on and mutated") { |i| SupZG.new.m(7, 8, k: 1) } +class SupE < SupP; def m(a, *, d:) = eval('super'); end +class SupE2 < SupP; def m(*, **) = eval('super'); end +class SupE3 < SupP; def m(*, **) = [1].map { eval('super') }.first; end +t("eval('super') from (a, *, d:)") { |i| SupE.new.m(1, 2, 3, d: 4) } +t("eval('super') from (*, **)") { |i| i.even? ? SupE2.new.m(1, 2, k: 3) : SupE2.new.m } +t("eval('super') in a block from (*, **)") { |i| SupE3.new.m(1, k: 2) } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f8d041b72..ade59bff5 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1779,6 +1779,53 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kwfwd (/perf-step, 2026-11-27) - `f(*a, **h)` passes `a` itself and no array for an + empty `h`; `def m(*, **)` keeps no copy of its arguments for a `super`** (switch + `IR_KWSPLAT_BY_REFERENCE` for the first, on unless `=0`). Built on f7ae738b (claude/perf-lsite, + which has 4320d4a). + - **Where the cost was.** `rest_kw` (`(*a, **k) = two(*a, **k)`) 174 ns against `rest_fwd`'s + 71 (CRuby 109, 84), `anon` (`(*, **, &)`) 264 (CRuby 88). Splitting it: binding `**k` costs + almost nothing (`kw_recv` = `rest_only`); passing an empty one on costs ~55 ns. Arguments. + UnsplatArguments made three arrays for it - a copy of `a`, a one-or-zero element array of + the keyword hash (SplatKeywordHash), and the AddRange - for a call that passes no keywords. + `anon` paid ~80 ns more: LowerGeneralParameters kept `?superargs?`, a copy of the whole + argument list for a parameterless `super`, because CanReadBackPositionals counted an + anonymous `*` as unreadable; and a method with `?superargs?` is no light frame + (`IR_LIGHT_FRAMES=why`: "optional, splat or post parameters"). + - **What CRuby 4.0 does.** `splatarray false` for `f(*a, **h)` with h a variable (the list + itself; a `#to_hash` that appends to `a` shows in the arguments), and an empty or nil `**` + passes nothing. A parameterless `super` in `def m(*, **)` reads the anonymous rest. + - **What changed.** (1) Arguments.TransformToCallInternal: a positional splat followed by a + lone `**h` whose operand is a variable, constant or literal (KeywordArgumentSplat. + IsLoneSideEffectFree, MethodCall.IsSideEffectFree) passes the list when + KeywordArgumentSplat.TransformToArgument gives null, and `[*a, h]` (RubyOps.SplatAppendItem, + one array) otherwise; not fresh, so a callee's rest copies as for `f(*a)`. (2) + PrismAstBridge.CanReadBackPositionals takes an anonymous `*` of a method, which `super` reads + back from Symbols.RestArgsLocal - the local `f(*)` reads, which nothing can assign; and + `eval('super')` (SuperCall.EvalImplicitArguments) reads it there too. IronRuby.Tests' + SuperParameterlessEval2 caught that one: without `?superargs?` the eval'd `super` of + `def m(a, *, d:)` read the rest by its signature name, `*`, and passed none of it. + - **Checks.** New `Util/kwsplat-forward-matrix.rb` (empty/nil `**`, arity errors, optional, + keyword and mutating callees, keywords plus a positional Hash, frozen and + compare_by_identity hashes, to_hash order and errors, to_a, ruby2_keywords, the forwarders, + redefinition after bind, method_missing, `super(*, **, &)` and zsuper from anonymous + signatures): same as CRuby in default, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` except three probes that differ on the base build too (a `**` copy loses the + default proc; a ruby2_keywords hash before an explicit empty `**` is taken as keywords, where + CRuby keeps it positional - IronRuby's dispatchers convert a marked last item of any splat). + `=0` also differs on "to_hash that grows the splatted list", which this fixes. + splat-blockarg, splat-pass, kwrest-call, keyword-light, keyword-rest-light, anon-forward, + block-pass, light-entry, hot-shapes same as CRuby in every mode and with the switch off. + Specs language/keyword_arguments, send, def, super, method as before. IronRuby.Tests in full: + PASSED. + - **Clock** (`ab.rb -r 6`, Release net10.0, ns; CRuby / base / new): splat-shapes `rest_kw` + 108.6 / 173.5 / 123.7, `rest_kw_blk` 115.1 / 184.0 / 128.0, `anon` 88.1 / 263.9 / 131.8; the + rest unchanged. forward-shapes and delegate-shapes unchanged (two rows that read 1.18 and + 1.29 were 1.04 and 1.00 rerun alone with `-r 10`). + - **Left.** `anon` and `rest_kw` are still ~40 ns over CRuby. The ruby2_keywords case above + needs a call-site flag ("keywords given explicitly") that every dispatcher reads. + `f(*a, k: 1, &g)` (named keywords, not a `**`) still copies. + - **perf/splatpos (/perf-step, 2026-11-27) - `f(*a, &b)' passes `a' itself, not a copy, when `b' is a variable, a constant or a literal** (switch `IR_SPLAT_BY_REFERENCE`, on unless `=0`). Built on 288cc13 (claude/perf-lsite, which has 4320d4a). From 14b9f885ba8f6faeedd988c680cd813e783bf80e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:10:18 +0000 Subject: [PATCH 221/439] StringScanner: \S, [^x] and \X match a byte of a split character, as in Onigmo The rest of a subject cut from a scan pointer inside a character starts with undecodable bytes. Onigmo matches such a byte with a negated escape (\S \D \W \H), a class negated at its top ([^l], [^\s], (?i)[^l]) and \X, but not with a positive class ([\S], [\W], \w, \p{Any}) - the shape the previous commit gave '.'. IronRuby's translation for that subject (TransformForEscapedBytes, used by StringScanner's allowBroken path only) left these sets as they were, which exclude the lone U+DC00-U+DCFF such a byte decodes to, so they answered nil. In that translation only, those sets also take an escaped byte; every other translation emits what it did. StringScanner_NegatedClassOnSplitByte1 holds CRuby's output for 26 patterns. string-search (0 lines from CRuby), regex-light, regexp-escaped-byte, regexp-binary-ctype, stdre and jit-scan matrices are unchanged; library/stringscanner, language/regexp and core/regexp (the known into/to errors only) specs pass, as do the Regex and StringScanner IronRuby.Tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 65 ++++++++++++++++++++++++ Src/Ruby/Builtins/RegexpTransformer.cs | 24 +++++++-- 3 files changed, 86 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index c47939208..63f802751 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -218,6 +218,7 @@ public Tests(Driver/*!*/ driver) { StringScanner_ShorterSubject1, StringScanner_LiteralEncoding1, StringScanner_DotOnSplitByte1, + StringScanner_NegatedClassOnSplitByte1, Regex_InspectResultEncoding1, Regex_EscapedByteEncoding1, Regex_EscapedByteEncoding2, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 029a0d003..7eb6f5d51 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -1010,6 +1010,71 @@ p at(""h\u00e9llo"", 2).scan(/.l/), at(""h\u00e9llo"", 2).scan(/..+/) "); } + /// + /// From a scan pointer inside a character, Onigmo matches a byte of the split character with a negated escape + /// (\S \D \W \H), a class negated at its top ([^l]) and \X, but not with a positive class ([\S], \w, \p{Any}). + /// + public void StringScanner_NegatedClassOnSplitByte1() { + TestOutput(@" +require 'ruby4' +require 'strscan' +def at(s, pos) = StringScanner.new(s).tap { |x| x.pos = pos } +p ['.', (at(""h\u00e9llo"", 2).scan(Regexp.new('.')) rescue $!.class)] +p ['\\S', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\S')) rescue $!.class)] +p ['[^l]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^l]')) rescue $!.class)] +p ['[^a-z]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^a-z]')) rescue $!.class)] +p ['\\D', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\D')) rescue $!.class)] +p ['\\W', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\W')) rescue $!.class)] +p ['\\H', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\H')) rescue $!.class)] +p ['[[:^space:]]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[[:^space:]]')) rescue $!.class)] +p ['[^\\s]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^\\s]')) rescue $!.class)] +p ['P{Space}', (at(""h\u00e9llo"", 2).scan(Regexp.new('P{Space}')) rescue $!.class)] +p ['[\\s\\S]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[\\s\\S]')) rescue $!.class)] +p ['[\\S]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[\\S]')) rescue $!.class)] +p ['\\w', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\w')) rescue $!.class)] +p ['\\s', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\s')) rescue $!.class)] +p ['[^\\w]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^\\w]')) rescue $!.class)] +p ['[\\W]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[\\W]')) rescue $!.class)] +p ['[^l]+', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^l]+')) rescue $!.class)] +p ['\\S+', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\S+')) rescue $!.class)] +p ['\\X', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\X')) rescue $!.class)] +p ['\\R', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\R')) rescue $!.class)] +p ['[^\\n]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^\\n]')) rescue $!.class)] +p ['(?i)[^l]', (at(""h\u00e9llo"", 2).scan(Regexp.new('(?i)[^l]')) rescue $!.class)] +p ['[^\\u00e9]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^\\u00e9]')) rescue $!.class)] +p ['\\p{Any}', (at(""h\u00e9llo"", 2).scan(Regexp.new('\\p{Any}')) rescue $!.class)] +p ['[\\x80-\\xff]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[\\x80-\\xff]')) rescue $!.class)] +p ['[^l\\u3042]', (at(""h\u00e9llo"", 2).scan(Regexp.new('[^l\\u3042]')) rescue $!.class)] +", @" +[""."", ""\xA9""] +[""\\S"", ""\xA9""] +[""[^l]"", ""\xA9""] +[""[^a-z]"", ""\xA9""] +[""\\D"", ""\xA9""] +[""\\W"", ""\xA9""] +[""\\H"", ""\xA9""] +[""[[:^space:]]"", nil] +[""[^\\s]"", ""\xA9""] +[""P{Space}"", nil] +[""[\\s\\S]"", nil] +[""[\\S]"", nil] +[""\\w"", nil] +[""\\s"", nil] +[""[^\\w]"", ""\xA9""] +[""[\\W]"", nil] +[""[^l]+"", ""\xA9""] +[""\\S+"", ""\xA9llo""] +[""\\X"", ""\xA9""] +[""\\R"", nil] +[""[^\\n]"", ""\xA9""] +[""(?i)[^l]"", ""\xA9""] +[""[^\\u00e9]"", ""\xA9""] +[""\\p{Any}"", nil] +[""[\\x80-\\xff]"", RegexpError] +[""[^l\\u3042]"", ""\xA9""] +"); + } + /// /// A BINARY subject is matched with Onigmo's ASCII-8BIT ctype table (MRI's /// rb_reg_prepare_enc compiles a regexp that is not fixed-encoding for the subject's diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index 04d986bfa..57f5b9089 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -937,7 +937,9 @@ private void Parse(bool isSubexpression) { lastWasQuantifier = false; lastEntity = null; bool topLevelPosixClass; - AppendCharacterSet(ParseCharacterGroup(false, out topLevelPosixClass), true); + // Onigmo takes an undecodable byte for a character a class negated at its top ([^l]) matches + bool negatedGroup = Peek() == '^'; + AppendCharacterSet(ParseCharacterGroup(false, out topLevelPosixClass), true, negatedGroup); break; case '.': @@ -1712,7 +1714,9 @@ private void ParseEscape(int escape) { "(?>\\r\\n|\\uD83C[\\uDDE6-\\uDDFF]\\uD83C[\\uDDE6-\\uDDFF]|" + "(?:[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[^\\uD800-\\uDFFF])" + "(?:\\p{M}|[\\uFE00-\\uFE0F\\u200C]|\\uD83C[\\uDFFB-\\uDFFF]|\\uDB40[\\uDC20-\\uDC7F]|" + - "\\u200D(?:[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[^\\uD800-\\uDFFF]))*)" + "\\u200D(?:[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[^\\uD800-\\uDFFF]))*" + + // an undecodable byte is a cluster of its own to Onigmo (TransformForEscapedBytes) + (_state.EscapedBytes ? "|[\\uDC00-\\uDCFF])" : ")") ); break; @@ -1775,7 +1779,8 @@ private void ParseEscape(int escape) { var latin1Word = CharacterSet.MakeSet(_latin1WordQuirk, null); set = (escape == 'w') ? set.Union(latin1Word) : set.Subtract(latin1Word); } - AppendCharacterSet(set, false); + // \S \D \W \H match an undecodable byte in Onigmo, as a negated class does + AppendCharacterSet(set, false, escape == 'S' || escape == 'D' || escape == 'W' || escape == 'H'); break; } } @@ -2318,7 +2323,18 @@ private void AppendAnyCharacter() { /// Emits a character set as a pattern entity. A set holding every non-BMP character that /// a * or + follows is emitted as one class (CharacterSet.AppendLoopBodyTo), for speed. /// - private void AppendCharacterSet(CharacterSet/*!*/ set, bool parenthesize) { + /// + /// The set is a negated escape (\S) or a class negated at its top ([^x]), which Onigmo matches against an + /// undecodable byte (a positive class, [\S] included, does not): in the translation for such a subject + /// (TransformForEscapedBytes) it takes the lone U+DC00-U+DCFF the byte decodes to. + /// + private void AppendCharacterSet(CharacterSet/*!*/ set, bool parenthesize, bool takesEscapedByte) { + if (takesEscapedByte && _state.EscapedBytes) { + _sb.Append("(?:"); + set.AppendTo(_sb, true); + _sb.Append("|[\\udc00-\\udcff])"); + return; + } if (_state.MayIgnoreCase) { if (set.IsSingleCharacter && IsUnfoldedLatin1Letter(set.SingleCodepoint)) { // \xE9: the letter itself, spelled as a literal one is From b0a33d4af7840e292f8b8e92f7295b596b964ab7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:19:23 +0000 Subject: [PATCH 222/439] Parked locals: clear the tuple's slots directly, not through SetValue Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Runtime/RubyOps.cs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 40c1ff14a..9d2c59a77 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -432,15 +432,25 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R /// held go with the call, as they would with a tuple that is dropped. /// private static MutableTuple ClearForPark(MutableTuple locals) { - if (locals == null) { + // A locals tuple is MutableTuple of 1, 2, 4, 8 or 16 slots (MakeObjectTupleType), each deriving from the + // one half its size: its slots are set directly, without SetValue's virtual call and switch per slot. + if (!(locals is MutableTuple t1) || locals.Capacity > MaxParkedLocals) { return null; } - int capacity = locals.Capacity; - if (capacity > MaxParkedLocals) { - return null; - } - for (int i = 0; i < capacity; i++) { - locals.SetValue(i, null); + t1.Item000 = null; + if (locals is MutableTuple t2) { + t2.Item001 = null; + if (locals is MutableTuple t4) { + t4.Item002 = null; t4.Item003 = null; + if (locals is MutableTuple t8) { + t8.Item004 = null; t8.Item005 = null; t8.Item006 = null; t8.Item007 = null; + if (locals is MutableTuple t16) { + t16.Item008 = null; t16.Item009 = null; t16.Item010 = null; t16.Item011 = null; + t16.Item012 = null; t16.Item013 = null; t16.Item014 = null; t16.Item015 = null; + } + } + } } return locals; } From ccad78e452aa288a6938123a8731ea0439145222 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:19:31 +0000 Subject: [PATCH 223/439] Revert the parked locals tuple (rejected) Reverts 16300b2 and b0a33d4. A parked method scope that kept its locals tuple for the next call saved the allocation (NBody 18.0 -> 12.0 MB per iteration, the fourteen benchmarks' bytes 0.892), but not the time: in callgrind a parked light frame with register locals (`sum_with', two locals read by an `each' block) took 2.2-2.9% more instructions in every pair of processes, NBody's `advance' -3.0% in one build and +0.4% in the next, and ten alternating AWFY processes had DeltaBlue 1.041, Richards 1.020 and Havlak 1.083 of the base (overlapping ranges) against NBody 0.982. The take (an atomic exchange) and the clear cost about what the 24-byte allocation did. See the ledger, Rejected, perf/parkedtuple. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- .../Ast/Definitions/MethodDefinition.cs | 18 +- Src/Ruby/Compiler/Ast/ScopeBuilder.cs | 27 +-- .../Compiler/ReflectionCache.Generated.cs | 2 - Src/Ruby/Runtime/RubyOps.cs | 58 ------ Src/Ruby/Runtime/RubyScope.cs | 6 - Util/parked-tuple-matrix.rb | 176 ------------------ 6 files changed, 9 insertions(+), 278 deletions(-) delete mode 100644 Util/parked-tuple-matrix.rb diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index dd4b4159d..6e5c75da8 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -394,15 +394,13 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin // A light frame keeps its locals in CLR variables if it can and makes few calls (MaxRegisterLocalsCalls): // `def one(x); yield x; end' would otherwise allocate their tuple on every call. MSA.Expression enter = null; - scope.ReusedLocals = ParkedLocals(parkSlot, null); - scope.ReusedLocalsWithScope = ParkedLocals(parkSlot, currentMethod.ParkedVariable); if (light != null) { var registerBody = (CountCalls() <= MaxRegisterLocalsCalls) ? scope.TryUseRegisterLocals(body) : null; if (registerBody != null) { body = registerBody; enter = light.EnterWithRegisterLocals(scope); } else { - enter = light.Enter(scope, scope.ReusedLocals); + enter = light.Enter(scope); } } @@ -411,7 +409,7 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin var locals = scope.LocalsTupleVariable; var parked = currentMethod.ParkedVariable; enter = Ast.Block( - scope.MakeLocalsStorage(scope.ReusedLocals), + scope.MakeLocalsStorage(), Ast.Assign(parked, Methods.TakeParkedScope.OpCall(Ast.Constant(parkSlot), declaringScope, declaringModule)), Ast.Condition(Ast.NotEqual(parked, AstUtils.Constant(null, typeof(ParkedProcs))), Methods.ReuseParkedScope.OpCall(parked, locals, selfParameter, blockParameter, EnterInterpretedFrameExpression.Instance), @@ -473,14 +471,6 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin /// internal static readonly bool LightBlocksEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_BLOCKS") != "0"; - // The tuple the entry of a body with a parking slot takes from the scope its last call parked (RubyOps.TakeParkedLocals), - // or null for a body without one. - private static MSA.Expression ParkedLocals(ParkedScopeSlot parkSlot, MSA.Expression taken) { - return (parkSlot != null && RubyOps.ParkedLocalsEnabled) - ? Methods.TakeParkedLocals.OpCall(Ast.Constant(parkSlot), taken ?? AstUtils.Constant(null, typeof(ParkedProcs))) - : null; - } - /// /// IR_PARKED_SCOPES=0 makes a new scope on every call of a method whose literal blocks reuse their Procs (see /// RubyOps.CreateMethodScopeParked); IR_PARKED_SCOPES=verbose names each method compiled with a parking slot. @@ -663,10 +653,10 @@ private sealed class LightFrame { /// Replaces CreateMethodScope: the locals, the safe point and the call's flow-control frame, the alias /// the method was called by, and a scope only if a TracePoint listens for calls. /// - internal MSA.Expression/*!*/ Enter(ScopeBuilder/*!*/ scope, MSA.Expression reusedLocals) { + internal MSA.Expression/*!*/ Enter(ScopeBuilder/*!*/ scope) { return Ast.Block( StackCheck, - scope.MakeLocalsStorage(reusedLocals), + scope.MakeLocalsStorage(), Ast.Assign(Rfc, EnterMethod), Ast.Assign(Callee, Methods.TakePendingCallee.OpCall(Name)), // the test inline, as in EnterWithRegisterLocals: a call of CreateMethodScopeIfTraced, with its nine diff --git a/Src/Ruby/Compiler/Ast/ScopeBuilder.cs b/Src/Ruby/Compiler/Ast/ScopeBuilder.cs index 5234537ad..ada21ff64 100644 --- a/Src/Ruby/Compiler/Ast/ScopeBuilder.cs +++ b/Src/Ruby/Compiler/Ast/ScopeBuilder.cs @@ -255,26 +255,11 @@ private int LiftedVisibleVariableCount { } public MSA.Expression/*!*/ MakeLocalsStorage() { - return MakeLocalsStorage(null); - } - - /// - /// Where a method body with a parking slot takes a tuple of nils before it makes one (RubyOps.TakeParkedLocals): at its - /// entry (MakeLocalsStorage), and when it makes its scope from register locals (MaterializeLocals, after the parked - /// scope is taken). Null for any other body. - /// - internal MSA.Expression ReusedLocals, ReusedLocalsWithScope; - - /// - /// MakeLocalsStorage that takes the tuple gives, if it is one of this scope's type, before it - /// makes one: a tuple whose every slot is nil (RubyOps.TakeParkedLocals). - /// - public MSA.Expression/*!*/ MakeLocalsStorage(MSA.Expression reused) { // TODO: use a factory instead of Ast.New to improve interpreter perf: - MSA.Expression tuple = (LiftedVisibleVariableCount == 0) ? (MSA.Expression)Ast.Constant(null, _localsTuple.Type) : - (reused != null) ? Ast.Coalesce(Ast.TypeAs(reused, _localsTuple.Type), NewTuple(_localsTuple.Type)) : - NewTuple(_localsTuple.Type); - MSA.Expression result = Ast.Assign(_localsTuple, tuple); + MSA.Expression result = Ast.Assign( + _localsTuple, + LiftedVisibleVariableCount == 0 ? (MSA.Expression)Ast.Constant(null, _localsTuple.Type) : NewTuple(_localsTuple.Type) + ); if (_parameters != null) { var initializers = new AstExpressions(); @@ -410,9 +395,7 @@ internal MSA.Expression TryUseRegisterLocals(MSA.Expression/*!*/ body) { internal MSA.Expression/*!*/ MaterializeLocals() { Debug.Assert(_registers != null); var result = new AstExpressions(); - result.Add(Ast.Assign(_localsTuple, (ReusedLocalsWithScope != null) - ? Ast.Coalesce(Ast.TypeAs(ReusedLocalsWithScope, _localsTuple.Type), NewTuple(_localsTuple.Type)) - : NewTuple(_localsTuple.Type))); + result.Add(Ast.Assign(_localsTuple, NewTuple(_localsTuple.Type))); for (int i = 0; i < _registers.Length; i++) { result.Add(Ast.Assign(GetVariableAccessor(_localsTuple, i), _registers[i])); } diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 9b726ab05..c43d8230e 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -664,8 +664,6 @@ public static partial class Methods { private static MethodInfo _TakeBfcForBlockYield; public static MethodInfo/*!*/ TakeFreshSplat { get { return _TakeFreshSplat ?? (_TakeFreshSplat = CallInstruction.CacheFunc(RubyOps.TakeFreshSplat)); } } private static MethodInfo _TakeFreshSplat; - public static MethodInfo/*!*/ TakeParkedLocals { get { return _TakeParkedLocals ?? (_TakeParkedLocals = CallInstruction.CacheFunc(RubyOps.TakeParkedLocals)); } } - private static MethodInfo _TakeParkedLocals; public static MethodInfo/*!*/ TakeParkedScope { get { return _TakeParkedScope ?? (_TakeParkedScope = CallInstruction.CacheFunc(RubyOps.TakeParkedScope)); } } private static MethodInfo _TakeParkedScope; public static MethodInfo/*!*/ TakePendingCallee { get { return _TakePendingCallee ?? (_TakePendingCallee = CallInstruction.CacheFunc(RubyOps.TakePendingCallee)); } } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 9d2c59a77..730427f3a 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -402,7 +402,6 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R proc?.ClearForPark(); } var methodScope = (RubyMethodScope)scope; - parked.Locals = ParkedLocalsEnabled ? ClearForPark(methodScope._locals) : null; methodScope.ClearCallState(); parked.Scope = methodScope; parked.ThreadId = Environment.CurrentManagedThreadId; @@ -416,63 +415,6 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R Volatile.Write(ref slot.Spare, parked); } - /// - /// IR_PARKED_LOCALS=0: a call of a method that parks its scope makes a new locals tuple, as it did, rather than take the - /// tuple of the parked scope's last call (TakeParkedLocals). - /// - internal static readonly bool ParkedLocalsEnabled = Environment.GetEnvironmentVariable("IR_PARKED_LOCALS") != "0"; - - // The most slots of a locals tuple that is cleared and parked: a flat tuple (up to 128 slots is one) and a short clear. - private const int MaxParkedLocals = 16; - - /// - /// The locals tuple of a call whose scope is being parked, every slot cleared to nil, for the next call to take; null if it - /// is not one to keep. Nothing else holds it: the scope is not captured (BeginPark), and every Proc of the call that could - /// reach it is reusable and inactive (StageParkedProc), so nothing outlives the call that could read it - and the values it - /// held go with the call, as they would with a tuple that is dropped. - /// - private static MutableTuple ClearForPark(MutableTuple locals) { - // A locals tuple is MutableTuple of 1, 2, 4, 8 or 16 slots (MakeObjectTupleType), each deriving from the - // one half its size: its slots are set directly, without SetValue's virtual call and switch per slot. - if (!(locals is MutableTuple t1) || locals.Capacity > MaxParkedLocals) { - return null; - } - t1.Item000 = null; - if (locals is MutableTuple t2) { - t2.Item001 = null; - if (locals is MutableTuple t4) { - t4.Item002 = null; t4.Item003 = null; - if (locals is MutableTuple t8) { - t8.Item004 = null; t8.Item005 = null; t8.Item006 = null; t8.Item007 = null; - if (locals is MutableTuple t16) { - t16.Item008 = null; t16.Item009 = null; t16.Item010 = null; t16.Item011 = null; - t16.Item012 = null; t16.Item013 = null; t16.Item014 = null; t16.Item015 = null; - } - } - } - } - return locals; - } - - /// - /// The locals tuple a method with a parking slot makes, if it can be the one parked with the scope, cleared (the caller - /// checks its type, and makes a new one otherwise): of , the parked scope this call took, when the - /// tuple is made with the scope (ScopeBuilder.MaterializeLocals); of the one parked in the slot, when it is made at the - /// entry, before the call knows whether it will take the scope. Taken with an atomic exchange, apart from the scope, so - /// that each tuple belongs to one call: a call that takes the parked scope gives it this call's tuple (Reinitialize), and - /// one that does not leaves the scope parked without one. - /// - [Emitted] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MutableTuple TakeParkedLocals(ParkedScopeSlot/*!*/ slot, ParkedProcs taken) { - var parked = taken ?? Volatile.Read(ref slot.Parked); - if (parked == null || parked.Locals == null) { - return null; - } - return Interlocked.Exchange(ref parked.Locals, null); - } - #endregion #region Light method frames diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index a708935ad..e59ef6b0d 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1408,18 +1408,12 @@ public sealed class ParkedProcs { internal readonly Proc[]/*!*/ Procs; internal int ThreadId; - // The locals tuple of the parked scope's last call, cleared, for the next call's entry to take (RubyOps.TakeParkedLocals): - // the entry makes the tuple before it knows whether it will take the scope, so the two are taken apart, each by one - // call. Null when there is none to take. - internal MutableTuple Locals; - internal ParkedProcs(int count) { Procs = new Proc[count]; } internal void Clear() { Scope = null; - Locals = null; Array.Clear(Procs, 0, Procs.Length); } } diff --git a/Util/parked-tuple-matrix.rb b/Util/parked-tuple-matrix.rb deleted file mode 100644 index 265bf19d8..000000000 --- a/Util/parked-tuple-matrix.rb +++ /dev/null @@ -1,176 +0,0 @@ -# Differential matrix for the locals tuple a method that parks its scope keeps for its next call (IR_PARKED_LOCALS: -# RubyOps.EndPark, TakeParkedLocals; ScopeBuilder.MakeLocalsStorage, MaterializeLocals). The tuple is cleared when the scope -# is parked and taken by the next call's entry, or with the scope by a light frame that keeps its locals in CLR variables. -# Run it under CRuby and under ./ir.sh with the switch on and off and with parked scopes and the tiers off, and diff: -# -# ruby Util/parked-tuple-matrix.rb > /tmp/mri.txt -# ./ir.sh Util/parked-tuple-matrix.rb > /tmp/on.txt -# IR_PARKED_LOCALS=0 ./ir.sh Util/parked-tuple-matrix.rb > /tmp/off.txt -# IR_PARKED_SCOPES=0 ./ir.sh Util/parked-tuple-matrix.rb > /tmp/noparked.txt -# ./ir.sh -X:NoJIT -X:NoOSR Util/parked-tuple-matrix.rb > /tmp/notiers.txt -# -# Every method runs thousands of times, parking its scope, around the case it probes. Their block literals are given to -# core iterators that do not keep them (each, map, times), which is what lets them park. - -def t(label) - print label.ljust(64), ' => ' - begin - v = yield - puts "#{v.inspect} (#{v.class})" - rescue Exception => e - puts "#{e.class}: #{e.message}" - end -end - -N = 3000 - -class P - def initialize; @a = [1, 2, 3]; @kept = []; end - attr_reader :kept - - # a local assigned on some calls only: nil on the others - def maybe(set) - x = 41 if set - @a.each { |e| x = x.to_i + e if set } - [x, defined?(x), local_variables.sort] - end - - # a binding taken on some calls: it keeps its own locals - def bind(v) - w = v * 2 - @a.each { |e| w += e } - (v % 1000 == 7) ? binding : w - end - - # a Proc of the method's own scope kept on some calls (`proc' keeps the block it is given) - def keep(v) - u = v + 1 - @a.map { |e| e + u } - @kept << proc { [u, v] } if v % 1000 == 3 - u - end - - # an exception leaving after its locals are set - def raising(v) - q = v - @a.each { |e| q += e } - raise ArgumentError, "boom #{q}" if v % 700 == 5 - q - end - - # many locals: more than the tuple that is kept may hold - def many(v) - a1 = v; a2 = a1 + 1; a3 = a2 + 1; a4 = a3 + 1; a5 = a4 + 1; a6 = a5 + 1; a7 = a6 + 1; a8 = a7 + 1; a9 = a8 + 1 - b1 = a9 + 1; b2 = b1 + 1; b3 = b2 + 1; b4 = b3 + 1; b5 = b4 + 1; b6 = b5 + 1; b7 = b6 + 1; b8 = b7 + 1; b9 = b8 + 1 - c = nil - @a.each { |e| c = b9 + e } if v.odd? - [a1, b9, c] - end - - # recursion: each level has its own locals - def rec(d, acc) - here = d * 10 - @a.each { |e| here += e } - inner = (d > 0) ? rec(d - 1, acc) : acc - [here, inner] - end - - # many calls a light frame makes: its locals in CLR variables until the scope is made - def light(v, make) - k = v - j = nil - @a.each { |e| j = (j || 0) + e + k } if make - [k, j] - end -end - -t('a local set on some calls is nil on the others') { - o = P.new - r = [] - N.times { |n| v = o.maybe(n.even?); r << v if n > N - 4 } - r -} -t('local_variables and defined? after reuse') { o = P.new; N.times { |n| o.maybe(n % 3 == 0) }; [o.maybe(false), o.maybe(true)] } -t('a binding taken in the middle keeps its own locals') { - o = P.new - bs = [] - N.times { |n| r = o.bind(n); bs << r if r.is_a?(Binding) } - bs.map { |b| [b.local_variable_get(:v), b.local_variable_get(:w), b.local_variables.sort] } -} -t('a binding written after later calls') { - o = P.new - b = nil - N.times { |n| r = o.bind(n); b = r if r.is_a?(Binding) && b.nil? } - b.local_variable_set(:w, :changed) - N.times { |n| o.bind(n + 1) } - [b.local_variable_get(:w), b.local_variable_get(:v)] -} -t('a Proc of the scope kept in the middle') { - o = P.new - N.times { |n| o.keep(n) } - o.kept.map(&:call) -} -t('an exception after the locals are set') { - o = P.new - errs = [] - s = 0 - N.times do |n| - begin - s += o.raising(n) - rescue ArgumentError => e - errs << e.message - end - end - [s, errs] -} -t('more locals than a kept tuple holds') { o = P.new; r = []; N.times { |n| r << o.many(n) if n > N - 3 }; r } -t('recursion') { o = P.new; r = nil; 500.times { |n| r = o.rec(4, n) }; r } -t('a light frame that makes its scope on some calls') { - o = P.new - r = [] - N.times { |n| v = o.light(n, n % 3 != 0); r << v if n > N - 4 } - r -} -t('threads calling one method') { - o = P.new - ths = Array.new(4) { |ti| Thread.new { s = 0; nils = 0; 2000.times { |n| x, = o.maybe((n + ti).even?); x.nil? ? nils += 1 : s += x }; [s, nils] } } - ths.map(&:value) -} -t('threads: bindings taken while others call') { - o = P.new - ths = Array.new(4) { |ti| Thread.new { bs = []; 3000.times { |n| r = o.bind(n * 4 + ti); bs << r if r.is_a?(Binding) }; bs.map { |b| [b.local_variable_get(:v), b.local_variable_get(:w)] } } } - ths.map(&:value).flatten(1).sort -} - -class Fib - def initialize; @a = [1, 2]; end - def gen(y, v) - loc = v - @a.each { |e| y << (loc + e) } - loc - end -end - -t('a call suspended in a fiber while the method runs again') { - f = Fib.new - N.times { |n| f.gen([], n) } - e = Enumerator.new { |y| f.gen(y, 100) } - first = e.next - mid = Array.new(50) { |n| f.gen([], n) }.last - second = e.next - [first, mid, second, (e.next rescue :done)] -} -t('eval in the method sees its own locals') { - k = Class.new { def m(v); z = v; [1].each { |e| z += e }; eval('z'); end }.new - r = nil - N.times { |n| r = k.m(n) } - r -} -t('TracePoint :return binding') { - o = P.new - N.times { |n| o.maybe(n.odd?) } - seen = [] - tp = TracePoint.new(:return) { |tpp| seen << tpp.binding.local_variable_get(:x) if tpp.method_id == :maybe } - tp.enable { o.maybe(true); o.maybe(false) } - [seen, o.maybe(false)] -} From dba2fb426a11505a01f00992d0e2ee0d3dea188e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:19:51 +0000 Subject: [PATCH 224/439] Ledger: perf/parkedtuple rejected, with its numbers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/perf/LEDGER.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 86dd4a5a5..9d8191062 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -712,7 +712,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has each call); the rest of NBody's 18 MB is the harness's `times` block (its index past the cache, the `0.01` literal) and `energy`. TruffleRuby allocates nothing there; the next step for the tuple is a parked scope that keeps its tuple when no - Proc of the call outlived it. + Proc of the call outlived it. Round forty built that and rejected it (see Rejected, + perf/parkedtuple): the bytes went (18 -> 12 MB) and the time did not, since taking + and clearing the tuple costs about what allocating 24 bytes does. What is left of + NBody's 12 MB is the harness's `times` block and `energy`, not `advance`. 3. **CD's red-black tree** (`put`, `tree_insert`, `find_node`, `Vector2D#compare_to`: 18.5% of self time now that `is_in_voxel` is compiled). `compare_to` is screen-rejected over its self call of `compare_numbers`, a three-line Float-only @@ -6484,6 +6487,36 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/parkedtuple 16300b2 b0a33d4, reverted in ccad78e (round forty, 2026-11-27) - a parked method + scope keeps its locals tuple for the next call (gap 2)**. After perf/nbody2 all `advance` allocated was + its 24-byte locals tuple: a method that parks its scope with its block literals' Procs still made a new + tuple per call, at its entry (`MakeLocalsStorage`, before it knows whether it will take the parked + scope) or, for a light frame with register locals, when it makes the scope (`MaterializeLocals`). + AWFY has some thirty such methods (`IR_PARKED_SCOPES=verbose`): DeltaBlue's `satisfy`, `execute`, + `incremental_remove`, som.rb's `each`, `append`, `remove`, Queens' `place_queen`, NBody's `advance`. + Built: `EndPark` cleared the scope's tuple (flat, up to 16 slots) and kept it with the scope + (`ParkedProcs.Locals`); the next call took it with an atomic exchange (`RubyOps.TakeParkedLocals`, + [Emitted]) from the slot at its entry, or from the parked scope it took when it made the tuple with + the scope (taking from the slot there found nothing: the scope was already out of it). Safe for the + reasons parking is - a scope nothing captured, Procs reusable and inactive - and + `Util/parked-tuple-matrix.rb` (in 16300b2: a local set on some calls only, bindings and Procs of the + scope kept in the middle, an exception, more than 16 locals, recursion, threads, a fiber, eval, a + TracePoint binding) printed CRuby's answers in every mode and caught a clear left out (three rows + wrong). The parked-scope, block-scope-reuse, block-nest-reuse, nested-proc, loop-exit, osr-array, jit + and hot-shapes matrices in the gate's modes and with the switch off: 63 same. ruby/spec + language/block, language/def, core/binding, core/proc: no failures, as on the base. + Bytes (alloc.rb): NBody 18,029,866 -> 12,032,795 per iteration, Towers 137 -> 45 KB, Queens -3%, + Richards -6%, Havlak -1.2%, DeltaBlue -1%; geomean of the fourteen 0.892. + Why rejected: the time. Callgrind (switch off -> on, one tree): a parked light frame with register + locals (`sum_with`: two locals an `each` block reads) +2.9% and +2.9% in two pairs of processes, and + +2.2% after the clear was made typed instead of SetValue per slot (b0a33d4); som.rb-style `each` and + `has_some` +0.14%; `advance` -3.0% in one build and +0.4% in the next. Ten alternating AWFY processes + (medians, ranges overlapping): NBody 0.982, Richards 1.020, DeltaBlue 1.041, Havlak 1.083. The take + (an interlocked exchange, a type test) and the clear cost about what a 24-byte gen0 allocation does, + and the register-locals arms each grew by the take. What would be different: a tuple the frame owns + without an exchange - a parked scope taken at the entry together with its tuple, which changes when + the scope is taken for every light frame that parks. + - **perf/passensure (2026-11-27) - running a pending ensure clause from the filter of a rescue frame above it: designed, found unsound, not built** (stage 1 of the brief; `Docs/rescue-above-ensure.md`). The idea (perf/rescuefilter): a rescue above a passed ensure catches and throws again (~20 us for the From bf643645dd59c9db48a5a077861588a45d80726b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:20:50 +0000 Subject: [PATCH 225/439] Startup library: precompile the string evals start-up runs Start-up compiled the same string evals from text on every run: specification.rb's set_nil_attributes_to_nil, kernel_require.rb's Kernel#require, every gemspec RubyGems loads (93 in `gem list`) and Forwardable's delegators. Each is a prism parse, a transform and a lambda compile on the main thread; the two of `-e 1` cost ~4.6 ms on the R2R host before their first call. startup-files.rb now records them too (IR_EVAL_RECORD: the text and everything EvalCodeCache keys an eval on - encoding, file, line, verbosity, method, block levels, parameters, locals, the modules of the lexical scope) into startup-evals.txt, and `IronRuby.Aot startup --evals` compiles each the way CompileEval does into a class of IronRuby.Startup.dll. The library's PrecompiledEvalsAttribute carries the keys and a SHA-256 of each text; RubyUtils.Evaluate asks PrecompiledCode.TryClaimEval before it compiles. The precompiled code answers only the first runtime of the process, only the first eval of exactly that text in exactly that context (claimed once, Interlocked), so a second eval, a one-byte-different text, another file or line, another binding's locals or a module without a name compile from text as before, and the eval code cache rules are unchanged. Checked on the R2R host against the base: __FILE__/__LINE__ and binding locals in a gemspec eval, a second load, a changed byte, another path and line (all compiled from text), 8 threads loading all 29 installed gemspecs at once (31 claims, each once, one result set), Forwardable's backtraces, and the output of the five start-up commands (irb's random tip aside). `startup-files.rb --check` passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/Ruby/Runtime/PrecompiledCode.cs | 183 +++++++++++++++++++++++- Src/Ruby/Runtime/RubyUtils.cs | 25 +++- Util/aot/IronRuby.Aot/AotCompiler.cs | 106 ++++++++++++++ Util/aot/IronRuby.Aot/StartupCommand.cs | 44 +++++- Util/aot/build-startup.sh | 2 +- Util/aot/startup-evals.txt | 153 ++++++++++++++++++++ Util/aot/startup-files.rb | 45 +++++- 7 files changed, 549 insertions(+), 9 deletions(-) create mode 100644 Util/aot/startup-evals.txt diff --git a/Src/Ruby/Runtime/PrecompiledCode.cs b/Src/Ruby/Runtime/PrecompiledCode.cs index 9c1b30e62..7bd6d35ee 100644 --- a/Src/Ruby/Runtime/PrecompiledCode.cs +++ b/Src/Ruby/Runtime/PrecompiledCode.cs @@ -73,6 +73,27 @@ public PrecompiledFilesAttribute(string[] files, string[] entryPoints, string[] public string[] Hashes { get; } } + /// + /// Marks the index class of a startup library that also holds code of strings evaluated while the startup commands ran + /// (Util/aot/startup-evals.txt): RubyGems' kernel_require.rb, which it evaluates as "<internal:...>", and the like. + /// Eval i is RubyStartupIndex.EvalEntry(i); says what it was compiled for (, + /// with the tree's root as ) and its text + /// (): the texts themselves would be read with the attribute at every start. + /// + [AttributeUsage(AttributeTargets.Class), CLSCompliant(false)] + public sealed class PrecompiledEvalsAttribute : Attribute { + public PrecompiledEvalsAttribute(string[] keys, string[] hashes, int firstClass) { + Keys = keys; + Hashes = hashes; + FirstClass = firstClass; + } + + public string[] Keys { get; } + public string[] Hashes { get; } + /// Eval i's code is the class RubyStartup<FirstClass + i> (after the files'). + public int FirstClass { get; } + } + /// /// The closure object nested lambdas of saved code are bound to: .NET Core does not expose /// System.Runtime.CompilerServices.Closure, and a saved assembly must reference a public type. @@ -536,6 +557,157 @@ public static void ClearCallLocation() { /// that runtime's objects), only if the runtime compiles code the way the library was compiled, and only /// for files whose source is still what was compiled. IR_STARTUP_DLL=none turns it off. /// + #region Evals + + /// + /// What the code of a string eval depends on besides its text: the text's encoding, the file and line, $VERBOSE (0 nil, 1 + /// false, 2 true), the frame (inside a method or not, its label, block depth, method name and parameter names, a rest + /// parameter), the locals it can see, and the names of the modules its constants are looked up in, innermost first + /// (EvalCodeCache.ConstantModules; "" for none). Null if a module has no name: such an eval is not precompiled. + /// + public static string EvalKey(string/*!*/ encoding, string/*!*/ path, int line, int verbosity, bool inMethod, string baseLabel, + int blockLevels, string methodName, string[] parameterNames, bool hasUnsplat, System.Collections.Generic.IList localNames, string[] moduleNames) { + if (moduleNames == null) { + return null; + } + var sb = new System.Text.StringBuilder(); + sb.Append(encoding).Append('\u0001').Append(path).Append('\u0001').Append(line).Append('\u0001').Append(verbosity).Append('\u0001') + .Append(inMethod ? '1' : '0').Append('\u0001').Append(baseLabel).Append('\u0001').Append(blockLevels).Append('\u0001') + .Append(methodName).Append('\u0001').Append(parameterNames != null ? String.Join("\u0002", parameterNames) : "\u0003").Append('\u0001') + .Append(hasUnsplat ? '1' : '0').Append('\u0001').Append(localNames != null ? String.Join("\u0002", localNames) : "\u0003").Append('\u0001') + .Append(String.Join("\u0002", moduleNames)); + return sb.ToString(); + } + + /// The names of , or null if one of them has none. + internal static string[] ModuleNames(RubyContext/*!*/ context, object[]/*!*/ modules) { + var names = new string[modules.Length]; + for (int i = 0; i < modules.Length; i++) { + var module = modules[i] as RubyModule; + if (module == null) { + names[i] = ""; + } else if ((names[i] = module.GetName(context)) == null) { + return null; + } + } + return names; + } + + private sealed class PrecompiledEval { + internal readonly string/*!*/ Hash; + internal readonly int Index; + // 1 once an eval has run it: the code of a text with a def or a class body is one eval's (see TryClaimEval) + internal int Claimed; + + internal PrecompiledEval(string/*!*/ hash, int index) { + Hash = hash; + Index = index; + } + } + + /// The SHA-256 of an eval's text, hex: what tells the text the library was compiled from. + public static string/*!*/ HashEvalCode(byte[]/*!*/ code) { + return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(code)); + } + + // by key: an eval site makes texts of one key that differ (Forwardable's delegators, one per method), told apart by hash + private static System.Collections.Generic.Dictionary _evals; + + /// Whether the startup library has evals no eval has run yet: the only cost to an eval otherwise is reading this. + internal static bool HasEvals { + get { return Volatile.Read(ref _evalsLeft) != 0; } + } + private static Func> _evalEntry; + private static int _evalsLeft; + + /// + /// The precompiled code of an eval of exactly this text in exactly this context, the first time such an eval runs in + /// the library's runtime; null otherwise, and the eval compiles its text as it would without the library. Once, as a + /// compile is once: the code of a text with a `def', a class body or a regexp literal keeps objects of the eval that + /// ran it (see EvalCodeCache), and a second eval of the text has to get fresh ones. + /// + internal static Func TryClaimEval(RubyContext/*!*/ context, byte[]/*!*/ code, string key) { + if (key == null || Volatile.Read(ref _evalsLeft) == 0 || context != _context) { + return null; + } + PrecompiledEval[] candidates; + if (!_evals.TryGetValue(key, out candidates)) { + return null; + } + string hash = HashEvalCode(code); + PrecompiledEval eval = null; + foreach (var candidate in candidates) { + if (candidate.Hash == hash) { + eval = candidate; + break; + } + } + if (eval == null || Interlocked.Exchange(ref eval.Claimed, 1) != 0) { + return null; + } + Interlocked.Decrement(ref _evalsLeft); + if (Trace) { + Console.Error.WriteLine("IronRuby.Startup: precompiled eval of " + code.Length + " bytes, " + key.Substring(0, Math.Max(0, key.IndexOf('\u0001', key.IndexOf('\u0001') + 1))).Replace('\u0001', ' ')); + } + return _evalEntry(eval.Index); + } + + private static void RegisterEvals(Type/*!*/ index, PrecompiledEvalsAttribute/*!*/ info) { + var entry = index.GetMethod("EvalEntry"); + if (entry == null || info.Keys == null || info.Hashes == null || info.Keys.Length != info.Hashes.Length) { + return; + } + var evals = new System.Collections.Generic.Dictionary(StringComparer.Ordinal); + for (int i = 0; i < info.Keys.Length; i++) { + string key = Rooted(info.Keys[i]); + evals.TryGetValue(key, out var candidates); + var more = new PrecompiledEval[(candidates?.Length ?? 0) + 1]; + candidates?.CopyTo(more, 0); + more[more.Length - 1] = new PrecompiledEval(info.Hashes[i], i); + evals[key] = more; + } + _evals = evals; + _evalEntry = (Func>)entry.CreateDelegate(typeof(Func>)); + Volatile.Write(ref _evalsLeft, info.Keys.Length); + } + + /// + /// IR_EVAL_RECORD=file: every plain string eval compiled without a warning is appended to the file, one JSON object a + /// line, with what the startup library needs to compile it ahead of time (Util/aot/startup-files.rb writes + /// startup-evals.txt from it). + /// + internal static readonly string EvalRecordPath = Environment.GetEnvironmentVariable("IR_EVAL_RECORD"); + + internal static void RecordEval(byte[]/*!*/ code, string/*!*/ encoding, string/*!*/ path, int line, int verbosity, bool inMethod, + string baseLabel, int blockLevels, string methodName, string[] parameterNames, bool hasUnsplat, System.Collections.Generic.IList localNames, + string[] moduleNames) { + if (moduleNames == null) { + return; + } + var o = new System.Text.Json.Nodes.JsonObject { + ["code"] = Convert.ToBase64String(code), + ["encoding"] = encoding, + ["path"] = path, + ["line"] = line, + ["verbosity"] = verbosity, + ["inMethod"] = inMethod, + ["baseLabel"] = baseLabel, + ["blockLevels"] = blockLevels, + ["methodName"] = methodName, + ["parameterNames"] = parameterNames != null ? new System.Text.Json.Nodes.JsonArray(Array.ConvertAll(parameterNames, n => (System.Text.Json.Nodes.JsonNode)n)) : null, + ["hasUnsplat"] = hasUnsplat, + ["localNames"] = localNames != null ? new System.Text.Json.Nodes.JsonArray(localNames.Select(n => (System.Text.Json.Nodes.JsonNode)n).ToArray()) : null, + ["moduleNames"] = new System.Text.Json.Nodes.JsonArray(Array.ConvertAll(moduleNames, n => (System.Text.Json.Nodes.JsonNode)n)), + }; + lock (_recordLock) { + File.AppendAllText(EvalRecordPath, o.ToJsonString() + "\n"); + } + } + + private static readonly object/*!*/ _recordLock = new object(); + + #endregion + internal static void TryRegisterStartupLibrary(RubyContext/*!*/ context) { string path = Environment.GetEnvironmentVariable("IR_STARTUP_DLL"); if (path == "none" || path == "") { @@ -591,7 +763,10 @@ internal static void TryRegisterStartupLibrary(RubyContext/*!*/ context) { // each file's code is a class of its own (RubyStartup), loaded when the file first runs var entry = (Func>)index.GetMethod("Entry").CreateDelegate( typeof(Func>)); - _lineTables = new System.Collections.Generic.Dictionary[info.Files.Length]; + // the files' classes, then the evals' (PrecompiledEvalsAttribute.FirstClass) + var evalsAttribute = index.GetCustomAttribute(); + _lineTables = new System.Collections.Generic.Dictionary[ + evalsAttribute != null && evalsAttribute.Keys != null ? Math.Max(info.Files.Length, evalsAttribute.FirstClass + evalsAttribute.Keys.Length) : info.Files.Length]; _startupAssembly = assembly; _context = context; if (Trace) { @@ -625,6 +800,12 @@ internal static void TryRegisterStartupLibrary(RubyContext/*!*/ context) { context.Loader.RegisterPrecompiledFile(file, new RubyScriptCode(lazyTarget, context.CreateFileUnit(file), TopScopeFactoryKind.File), isCurrent); } _fileHashes = fileHashes; + if (evalsAttribute != null) { + RegisterEvals(index, evalsAttribute); + if (Trace) { + Console.Error.WriteLine("IronRuby.Startup: " + _evalsLeft + " precompiled evals"); + } + } if (Trace) { // every file, not only the ones this run loads: a library that no longer matches its sources is slower // for each stale file (it is compiled from source) and otherwise says nothing (Util/aot/check-startup.sh) diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index b42c91ae4..fc56788ff 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1579,23 +1579,44 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop // last eval in the same place (EvalCodeCache): an ERB template evaluated at every #result. EvalCodeCache.Key cacheKey = null; EvalEntryPointDelegate compiled = null; + string precompiledKey = null; + string[] moduleNames = null; + int verbosity = 0; if (module == null && bytes.Length <= EvalCodeCache.MaxCodeLength && options.TopLevelParameterSignature == null && options.IsolatedLocalNames == null && context.Coverage == null) { object verbose = context.Verbose; + verbosity = verbose == null ? 0 : (RubyOps.IsTrue(verbose) ? 2 : 1); + object[] constantModules = EvalCodeCache.ConstantModules(targetScope); cacheKey = new EvalCodeCache.Key(bytes, code.Encoding, sourcePath, line, - verbose == null ? 0 : (RubyOps.IsTrue(verbose) ? 2 : 1), methodScope != null, + verbosity, methodScope != null, options.EvalFrameBaseLabel, options.EvalFrameBlockLevels, options.TopLevelMethodName, options.TopLevelParameterNames, - options.TopLevelHasUnsplatParameter, options.LocalNames, EvalCodeCache.ConstantModules(targetScope)); + options.TopLevelHasUnsplatParameter, options.LocalNames, constantModules); var cache = context.EvalCodeCache; if (cache != null) { compiled = (EvalEntryPointDelegate)cache.TryGet(cacheKey); } options.CheckEvalCodeShareable = true; + + // The startup library's code of this text in this context, if it has it and no eval has run it yet + // (IronRuby.Runtime.Precompiled.PrecompiledCode.TryClaimEval), or a record of the eval for the library (IR_EVAL_RECORD). + if (compiled == null && (IronRuby.Runtime.Precompiled.PrecompiledCode.HasEvals || IronRuby.Runtime.Precompiled.PrecompiledCode.EvalRecordPath != null)) { + moduleNames = IronRuby.Runtime.Precompiled.PrecompiledCode.ModuleNames(context, constantModules); + precompiledKey = IronRuby.Runtime.Precompiled.PrecompiledCode.EvalKey(code.Encoding.Name, sourcePath, line, verbosity, methodScope != null, + options.EvalFrameBaseLabel, options.EvalFrameBlockLevels, options.TopLevelMethodName, options.TopLevelParameterNames, + options.TopLevelHasUnsplatParameter, options.LocalNames, moduleNames); + compiled = IronRuby.Runtime.Precompiled.PrecompiledCode.TryClaimEval(context, bytes, precompiledKey); + } } if (compiled == null) { + int warnings = context.RuntimeErrorSink.WarningCount; compiled = CompileEval(context, bytes, code, sourcePath, options, line, cacheKey); + if (precompiledKey != null && IronRuby.Runtime.Precompiled.PrecompiledCode.EvalRecordPath != null && context.RuntimeErrorSink.WarningCount == warnings) { + IronRuby.Runtime.Precompiled.PrecompiledCode.RecordEval(bytes, code.Encoding.Name, sourcePath, line, verbosity, methodScope != null, + options.EvalFrameBaseLabel, options.EvalFrameBlockLevels, options.TopLevelMethodName, options.TopLevelParameterNames, + options.TopLevelHasUnsplatParameter, options.LocalNames, moduleNames); + } } var blockParameter = (methodScope != null) ? methodScope.BlockParameter : null; diff --git a/Util/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index 6af84e9aa..ae61a5ab6 100644 --- a/Util/aot/IronRuby.Aot/AotCompiler.cs +++ b/Util/aot/IronRuby.Aot/AotCompiler.cs @@ -229,6 +229,10 @@ public void Compile(string mainFile, IList files, string outputPath) { if (Environment.GetEnvironmentVariable("IR_AOT_CHECK_BRANCHES") == "1") CheckBranches(); } + if (Library && Evals != null) { + CompileEvals(paths.Length, extended); + } + // load-time initialization of the constants, in chunks to keep methods a sane size const int ChunkSize = 200; int chunks = 0; @@ -543,6 +547,87 @@ protected override Expression VisitLoop(LoopExpression node) { protected override Expression VisitExtension(Expression node) => node.CanReduce ? Visit(node.Reduce()) : node; } + /// + /// A string eval a startup command ran (Util/aot/startup-evals.txt, which IR_EVAL_RECORD records): its text and what it + /// was compiled for (RubyUtils.Evaluate, CreateCompilerOptionsForEval). + /// + public sealed class EvalUnit { + public byte[] Code; + public string Encoding, Path, BaseLabel, MethodName; + public int Line, Verbosity, BlockLevels; + public bool InMethod, HasUnsplat; + public string[] ParameterNames, LocalNames, ModuleNames; + } + + /// A library's evals, compiled after its files (see PrecompiledEvalsAttribute). + public List Evals; + + private readonly List _evalEntryMethods = new(); + private readonly List _evalKeys = new(), _evalCodes = new(); + private int _firstEvalClass; + + /// + /// Each eval as RubyUtils.Evaluate compiles it - the same options, from the same record - into a class of its own after + /// the files' (RubyStartup<firstClass + i>, with its line table), its entry an EvalEntryPointDelegate. An eval the + /// compiler leaves out (refinements, a syntax error, a text it cannot transform) is compiled from its text at run time. + /// + private void CompileEvals(int firstClass, HashSet extended) { + _firstEvalClass = firstClass; + foreach (var e in Evals) { + var encoding = RubyEncoding.FindByName(e.Encoding); + if (encoding == null) { + Console.Error.WriteLine($"left out eval at {e.Path}:{e.Line}: encoding {e.Encoding}"); + continue; + } + // CreateCompilerOptionsForEval, from the record + var options = new RubyCompilerOptions() { + IsEval = true, + EvalFrameBaseLabel = e.BaseLabel, + EvalFrameBlockLevels = e.BlockLevels, + FactoryKind = TopScopeFactoryKind.None, + LocalNames = e.LocalNames != null ? new List(e.LocalNames) : null, + TopLevelMethodName = e.InMethod ? e.MethodName : null, + TopLevelParameterNames = e.InMethod ? e.ParameterNames : null, + TopLevelHasUnsplatParameter = e.InMethod && e.HasUnsplat, + InitialLocation = new SourceLocation(0, e.Line <= 0 ? 1 : e.Line, 1), + EvalSourceEncoding = e.Code.Length >= 3 && encoding.IsAsciiIdentity && e.Code[0] == 0xEF && e.Code[1] == 0xBB && e.Code[2] == 0xBF ? RubyEncoding.UTF8 : encoding, + }; + var unit = _context.CreateSourceUnit(new BinaryContentProvider(e.Code), e.Path, encoding.Encoding, SourceCodeKind.File); + SourceUnitTree ast; + Expression> lambda; + try { + ast = IronRuby.Prism.PrismAstBridge.Parse(unit, options, ErrorSink.Default); + if (ast == null) throw new InvalidOperationException("syntax error"); + if (UnsupportedFinder.Find(ast) is string why) throw new InvalidOperationException(why); + new ExtendWalker(extended).Walk(ast); + new FrameLabelWalker(_frameOwners, _context, extended).Walk(ast); + lambda = _context.TransformTree>(ast, unit, options); + } catch (Exception ex) { + Console.Error.WriteLine($"left out eval at {e.Path}:{e.Line}: {ex.Message}"); + continue; + } + int index = firstClass + _evalEntryMethods.Count; + _lines.Add(new Dictionary>()); + _type = _module.DefineType("RubyStartup" + index, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed); + _constantFields.Clear(); + _rootedStrings.Clear(); + _boxedLiterals.Clear(); + var method = _type.DefineMethod(lambda.Name, MethodAttributes.Public | MethodAttributes.Static); + ExpressionCompiler.CompileToMethod((LambdaExpression)Rewrite(lambda), method); + DefineLineTable(_lines[_lines.Count - 1]); + _type.CreateType(); + _evalEntryMethods.Add(method); + // the key the runtime computes for the eval (PrecompiledCode.EvalKey), with the tree's root as the marker that + // PrecompiledCode.Rooted replaces by the tree the library runs from + string path = RootPrefix != null ? e.Path.Replace(RootPrefix, PrecompiledCode.RootMarker.ToString()) : e.Path; + _evalKeys.Add(PrecompiledCode.EvalKey(e.Encoding, path, e.Line, e.Verbosity, e.InMethod, e.BaseLabel, e.BlockLevels, + e.MethodName, e.ParameterNames, e.HasUnsplat, e.LocalNames, e.ModuleNames)); + _evalCodes.Add(PrecompiledCode.HashEvalCode(e.Code)); + Count("evals compiled"); + Console.Error.WriteLine($"compiled eval at {e.Path}:{e.Line} ({e.Code.Length} bytes)"); + } + } + /// /// RubyStartupIndex, the library's small entry class (the files' code is in RubyStartup<i>, one class per /// file, which is loaded when the file is), carrying the PrecompiledFilesAttribute: @@ -568,6 +653,27 @@ private void DefineStartupIndex(CustomAttributeBuilder files) { il.Emit(OpCodes.Ret); } + // EvalEntry(i): the delegate of eval i's code, in PrecompiledEvalsAttribute order + if (_evalEntryMethods.Count > 0) { + index.SetCustomAttribute(new CustomAttributeBuilder(typeof(PrecompiledEvalsAttribute).GetConstructors()[0], + new object[] { _evalKeys.ToArray(), _evalCodes.ToArray(), _firstEvalClass })); + var evalType = typeof(Func); + var evalEntry = index.DefineMethod("EvalEntry", MethodAttributes.Public | MethodAttributes.Static, evalType, new[] { typeof(int) }); + var eil = evalEntry.GetILGenerator(); + var evalLabels = _evalEntryMethods.Select(_ => eil.DefineLabel()).ToArray(); + eil.Emit(OpCodes.Ldarg_0); + eil.Emit(OpCodes.Switch, evalLabels); + eil.Emit(OpCodes.Ldnull); + eil.Emit(OpCodes.Ret); + for (int i = 0; i < _evalEntryMethods.Count; i++) { + eil.MarkLabel(evalLabels[i]); + eil.Emit(OpCodes.Ldnull); + eil.Emit(OpCodes.Ldftn, _evalEntryMethods[i]); + eil.Emit(OpCodes.Newobj, evalType.GetConstructor(new[] { typeof(object), typeof(IntPtr) })); + eil.Emit(OpCodes.Ret); + } + } + index.CreateType(); } diff --git a/Util/aot/IronRuby.Aot/StartupCommand.cs b/Util/aot/IronRuby.Aot/StartupCommand.cs index ce60eb9e8..024c534a6 100644 --- a/Util/aot/IronRuby.Aot/StartupCommand.cs +++ b/Util/aot/IronRuby.Aot/StartupCommand.cs @@ -15,7 +15,7 @@ namespace IronRuby.Aot { /// /// IronRuby.Aot startup -o dir [--tfm net10.0|net11.0] [--r2r] [--host dir] [--rid rid] [--root dir] - /// [--crossgen2 path] [--cache dir] (file.rb | @list)... + /// [--crossgen2 path] [--cache dir] [--evals file] (file.rb | @list)... /// /// Compiles the Ruby code `ir` runs at startup - the core prelude (ruby4.rb), rbconfig, rubygems /// and the rest - into dir/IronRuby.Startup.dll, a library IronRuby's loader picks up when it @@ -37,13 +37,45 @@ namespace IronRuby.Aot { /// copy of the whole tree elsewhere (an unpacked release) uses it too: paths compiled into the code are moved /// to wherever the tree is at run time. /// + /// --evals names the string evals the startup commands run (Util/aot/startup-evals.txt): each is compiled in too, for + /// the first eval of exactly that text in exactly that context (PrecompiledCode.TryClaimEval). + /// /// --cache keeps the last library made in a directory, with a key of everything it was made from - the compiler, /// the host's assemblies, the files' contents, the options - and copies it out instead of compiling when the key /// is the same: an unchanged rebuild costs a second, not twenty. /// internal static class StartupCommand { + /// The marker startup-evals.txt has for the tree's root in a path: the tree the library is compiled for replaces it. + private const string EvalRootMarker = "${ROOT}"; + + // one JSON object a line, as PrecompiledCode.RecordEval writes them + private static List ReadEvals(string file, string root) { + var result = new List(); + foreach (var line in File.ReadAllLines(file)) { + if (line.Length == 0 || line.StartsWith("#", StringComparison.Ordinal)) continue; + var o = System.Text.Json.Nodes.JsonNode.Parse(line).AsObject(); + string[] Names(string name) => o[name] is System.Text.Json.Nodes.JsonArray a ? a.Select(n => (string)n).ToArray() : null; + result.Add(new AotCompiler.EvalUnit { + Code = Convert.FromBase64String((string)o["code"]), + Encoding = (string)o["encoding"], + Path = ((string)o["path"]).Replace(EvalRootMarker, root), + Line = (int)o["line"], + Verbosity = (int)o["verbosity"], + InMethod = (bool)o["inMethod"], + BaseLabel = (string)o["baseLabel"], + BlockLevels = (int)o["blockLevels"], + MethodName = (string)o["methodName"], + ParameterNames = Names("parameterNames"), + HasUnsplat = (bool)o["hasUnsplat"], + LocalNames = Names("localNames"), + ModuleNames = Names("moduleNames"), + }); + } + return result; + } + public static int Run(string[] args) { - string outDir = null, tfm = "net10.0", host = null, rid = null, root = null, crossgen = null, cache = null; + string outDir = null, tfm = "net10.0", host = null, rid = null, root = null, crossgen = null, cache = null, evalsFile = null; bool r2r = false; var listed = new List(); for (int i = 0; i < args.Length; i++) { @@ -56,6 +88,8 @@ public static int Run(string[] args) { case "--root": root = args[++i]; break; case "--crossgen2": crossgen = args[++i]; break; case "--cache": cache = args[++i]; break; + // the string evals the startup commands run (Util/aot/startup-evals.txt, written by startup-files.rb) + case "--evals": evalsFile = args[++i]; break; default: if (args[i].StartsWith("@", StringComparison.Ordinal)) { string list = args[i].Substring(1), baseDir = Path.GetDirectoryName(Path.GetFullPath(list)); @@ -72,7 +106,7 @@ public static int Run(string[] args) { } if (outDir == null || listed.Count == 0) { Console.Error.WriteLine("usage: IronRuby.Aot startup -o dir [--tfm net10.0|net11.0] [--r2r] [--host dir] [--rid rid] [--root dir] " + - "[--crossgen2 path] [--cache dir] (file.rb | @list)..."); + "[--crossgen2 path] [--cache dir] [--evals file] (file.rb | @list)..."); return 2; } var tfmMatch = System.Text.RegularExpressions.Regex.Match(tfm, @"\Anet(\d+)\.0\z"); @@ -153,6 +187,7 @@ public static int Run(string[] args) { } if (r2r) k.Append(crossgen).Append('=').Append(new FileInfo(crossgen).Length).Append('\n').Append(framework ?? "self-contained").Append('\n'); foreach (var f in files) k.Append(f).Append('=').Append(PrecompiledCode.HashFile(f)).Append('\n'); + if (evalsFile != null && File.Exists(evalsFile)) k.Append("evals=").Append(PrecompiledCode.HashFile(evalsFile)).Append('\n'); key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(k.ToString()))); string keyFile = Path.Combine(cache, "key"); if (File.Exists(keyFile) && File.ReadAllText(keyFile).Trim() == key) { @@ -189,6 +224,9 @@ public static int Run(string[] args) { _ => r2r && rid.EndsWith("-arm64", StringComparison.Ordinal) ? SplitNodes : 0 } }; + if (evalsFile != null && File.Exists(evalsFile)) { + compiler.Evals = ReadEvals(evalsFile, root); + } compiler.Compile(null, files, dll); Console.Error.WriteLine($"wrote {dll} ({new FileInfo(dll).Length:N0} bytes, {files.Count - compiler.LeftOut.Count} files) in {sw.ElapsedMilliseconds} ms"); foreach (var kv in compiler.Stats.OrderBy(kv => kv.Key)) { diff --git a/Util/aot/build-startup.sh b/Util/aot/build-startup.sh index 4fe04c3c1..0eecd5e54 100755 --- a/Util/aot/build-startup.sh +++ b/Util/aot/build-startup.sh @@ -92,7 +92,7 @@ fi OUT="$(mktemp -d)" trap 'rm -rf "$OUT"' EXIT if ! "$AOT" startup -o "$OUT" --tfm "$TFM" $R2R --host "$HOST" ${RID:+--rid "$RID"} ${ROOT:+--root "$ROOT"} \ - --cache "$CACHE" @Util/aot/startup-files.txt 2>"$OUT/log"; then + --cache "$CACHE" --evals Util/aot/startup-evals.txt @Util/aot/startup-files.txt 2>"$OUT/log"; then cat "$OUT/log" >&2 exit 1 fi diff --git a/Util/aot/startup-evals.txt b/Util/aot/startup-evals.txt new file mode 100644 index 000000000..a511b5a43 --- /dev/null +++ b/Util/aot/startup-evals.txt @@ -0,0 +1,153 @@ +# Written by startup-files.rb with startup-files.txt: the string evals those commands run, one JSON object a line +# (PrecompiledCode.RecordEval), compiled into IronRuby.Startup.dll for the first eval of exactly that text in exactly +# that context. ${ROOT} is the IronRuby tree. +{"code":"ICAgICMgZnJvemVuX3N0cmluZ19saXRlcmFsOiB0cnVlCgogICAgZGVmIHNldF9uaWxfYXR0cmlidXRlc190b19uaWwKICAgICAgQGF1dG9yZXF1aXJlID0gbmlsOyBAZGF0ZSA9IG5pbDsgQGRlc2NyaXB0aW9uID0gbmlsOyBAZW1haWwgPSBuaWw7IEBob21lcGFnZSA9IG5pbDsgQG5hbWUgPSBuaWw7IEBwb3N0X2luc3RhbGxfbWVzc2FnZSA9IG5pbDsgQHNpZ25pbmdfa2V5ID0gbmlsOyBAc3VtbWFyeSA9IG5pbDsgQHZlcnNpb24gPSBuaWwKICAgIGVuZAogICAgcHJpdmF0ZSA6c2V0X25pbF9hdHRyaWJ1dGVzX3RvX25pbAoKICAgIGRlZiBzZXRfbm90X25pbF9hdHRyaWJ1dGVzX3RvX2RlZmF1bHRfdmFsdWVzCiAgICAgIEBhdXRob3JzID0gW107QGJpbmRpciA9ICJiaW4iO0BjZXJ0X2NoYWluID0gW107QGRlcGVuZGVuY2llcyA9IFtdO0BleGVjdXRhYmxlcyA9IFtdO0BleHRlbnNpb25zID0gW107QGV4dHJhX3Jkb2NfZmlsZXMgPSBbXTtAZmlsZXMgPSBbXTtAbGljZW5zZXMgPSBbXTtAbWV0YWRhdGEgPSB7fTtAcGxhdGZvcm0gPSAicnVieSI7QHJkb2Nfb3B0aW9ucyA9IFtdO0ByZXF1aXJlX3BhdGhzID0gZGVmYXVsdF92YWx1ZSg6cmVxdWlyZV9wYXRocykuZHVwO0ByZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBkZWZhdWx0X3ZhbHVlKDpyZXF1aXJlZF9ydWJ5X3ZlcnNpb24pLmR1cDtAcmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IGRlZmF1bHRfdmFsdWUoOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24pLmR1cDtAcmVxdWlyZW1lbnRzID0gW107QHJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjIwIjtAc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNDtAdGVzdF9maWxlcyA9IFtdCiAgICBlbmQKICAgIHByaXZhdGUgOnNldF9ub3RfbmlsX2F0dHJpYnV0ZXNfdG9fZGVmYXVsdF92YWx1ZXMK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/rubygems/specification.rb","line":1938,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["today"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyBmcm96ZW5fc3RyaW5nX2xpdGVyYWw6IHRydWUKCiMtLQojIENvcHlyaWdodCAyMDA2IGJ5IENoYWQgRm93bGVyLCBSaWNoIEtpbG1lciwgSmltIFdlaXJpY2ggYW5kIG90aGVycy4KIyBBbGwgcmlnaHRzIHJlc2VydmVkLgojIFNlZSBMSUNFTlNFLnR4dCBmb3IgcGVybWlzc2lvbnMuCiMrKwoKcmVxdWlyZSAibW9uaXRvciIKCm1vZHVsZSBLZXJuZWwKICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1IgPSBNb25pdG9yLm5ldyAjIDpub2RvYzoKCiAgIyBNYWtlIHN1cmUgd2UgaGF2ZSBhIHJlZmVyZW5jZSB0byBSdWJ5J3Mgb3JpZ2luYWwgS2VybmVsI3JlcXVpcmUKICB1bmxlc3MgZGVmaW5lZD8oZ2VtX29yaWdpbmFsX3JlcXVpcmUpCiAgICAjIDpzdG9wZG9jOgogICAgYWxpYXNfbWV0aG9kIDpnZW1fb3JpZ2luYWxfcmVxdWlyZSwgOnJlcXVpcmUKICAgIHByaXZhdGUgOmdlbV9vcmlnaW5hbF9yZXF1aXJlCiAgICAjIDpzdGFydGRvYzoKICBlbmQKCiAgIyMKICAjIFdoZW4gUnVieUdlbXMgaXMgcmVxdWlyZWQsIEtlcm5lbCNyZXF1aXJlIGlzIHJlcGxhY2VkIHdpdGggb3VyIG93biB3aGljaAogICMgaXMgY2FwYWJsZSBvZiBsb2FkaW5nIGdlbXMgb24gZGVtYW5kLgogICMKICAjIFdoZW4geW91IGNhbGwgPHR0PnJlcXVpcmUgJ3gnPC90dD4sIHRoaXMgaXMgd2hhdCBoYXBwZW5zOgogICMgKiBJZiB0aGUgZmlsZSBjYW4gYmUgbG9hZGVkIGZyb20gdGhlIGV4aXN0aW5nIFJ1YnkgbG9hZHBhdGgsIGl0CiAgIyAgIGlzLgogICMgKiBPdGhlcndpc2UsIGluc3RhbGxlZCBnZW1zIGFyZSBzZWFyY2hlZCBmb3IgYSBmaWxlIHRoYXQgbWF0Y2hlcy4KICAjICAgSWYgaXQncyBmb3VuZCBpbiBnZW0gJ3knLCB0aGF0IGdlbSBpcyBhY3RpdmF0ZWQgKGFkZGVkIHRvIHRoZQogICMgICBsb2FkcGF0aCkuCiAgIwogICMgVGhlIG5vcm1hbCA8dHQ+cmVxdWlyZTwvdHQ+IGZ1bmN0aW9uYWxpdHkgb2YgcmV0dXJuaW5nIGZhbHNlIGlmCiAgIyB0aGF0IGZpbGUgaGFzIGFscmVhZHkgYmVlbiBsb2FkZWQgaXMgcHJlc2VydmVkLgoKICBkZWYgcmVxdWlyZShwYXRoKSAjIDpkb2M6CiAgICByZXR1cm4gZ2VtX29yaWdpbmFsX3JlcXVpcmUocGF0aCkgdW5sZXNzIEdlbS5kaXNjb3Zlcl9nZW1zX29uX3JlcXVpcmUKCiAgICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1Iuc3luY2hyb25pemUgZG8KICAgICAgcGF0aCA9IEZpbGUucGF0aChwYXRoKQoKICAgICAgIyBJZiArcGF0aCsgYmVsb25ncyB0byBhIGRlZmF1bHQgZ2VtLCB3ZSBhY3RpdmF0ZSBpdCBhbmQgdGhlbiBnbyBzdHJhaWdodAogICAgICAjIHRvIG5vcm1hbCByZXF1aXJlCgogICAgICBpZiBzcGVjID0gR2VtLmZpbmRfZGVmYXVsdF9zcGVjKHBhdGgpCiAgICAgICAgbmFtZSA9IHNwZWMubmFtZQoKICAgICAgICBuZXh0IGlmIEdlbS5sb2FkZWRfc3BlY3NbbmFtZV0KCiAgICAgICAgIyBFbnN1cmUgLUkgYmVhdHMgYSBkZWZhdWx0IGdlbQogICAgICAgIHJlc29sdmVkX3BhdGggPSBiZWdpbgogICAgICAgICAgcnAgPSBuaWwKICAgICAgICAgIGxvYWRfcGF0aF9jaGVja19pbmRleCA9IEdlbS5sb2FkX3BhdGhfaW5zZXJ0X2luZGV4IC0gR2VtLmFjdGl2YXRlZF9nZW1fcGF0aHMKICAgICAgICAgIEdlbS5zdWZmaXhlcy5maW5kIGRvIHxzfAogICAgICAgICAgICAkTE9BRF9QQVRIWzAuLi5sb2FkX3BhdGhfY2hlY2tfaW5kZXhdLmZpbmQgZG8gfGxwfAogICAgICAgICAgICAgIGlmIEZpbGUuc3ltbGluaz8gbHAgIyBmb3IgYmFja3dhcmQgY29tcGF0aWJpbGl0eQogICAgICAgICAgICAgICAgbmV4dAogICAgICAgICAgICAgIGVuZAoKICAgICAgICAgICAgICBmdWxsX3BhdGggPSBGaWxlLmV4cGFuZF9wYXRoKEZpbGUuam9pbihscCwgIiN7cGF0aH0je3N9IikpCiAgICAgICAgICAgICAgcnAgPSBmdWxsX3BhdGggaWYgRmlsZS5maWxlPyhmdWxsX3BhdGgpCiAgICAgICAgICAgIGVuZAogICAgICAgICAgZW5kCiAgICAgICAgICBycAogICAgICAgIGVuZAoKICAgICAgICBuZXh0IGlmIHJlc29sdmVkX3BhdGgKCiAgICAgICAgS2VybmVsLnNlbmQoOmdlbSwgbmFtZSwgR2VtOjpSZXF1aXJlbWVudC5kZWZhdWx0X3ByZXJlbGVhc2UpCgogICAgICAgIEdlbS5sb2FkX2J1bmRsZXJfZXh0ZW5zaW9ucyhHZW0ubG9hZGVkX3NwZWNzW25hbWVdLnZlcnNpb24pIGlmIG5hbWUgPT0gImJ1bmRsZXIiCgogICAgICAgIG5leHQKICAgICAgZW5kCgogICAgICAjIElmIHRoZXJlIGFyZSBubyB1bnJlc29sdmVkIGRlcHMsIHRoZW4gd2UgY2FuIHVzZSBqdXN0IHRyeQogICAgICAjIG5vcm1hbCByZXF1aXJlIGhhbmRsZSBsb2FkaW5nIGEgZ2VtIGZyb20gdGhlIHJlc2N1ZSBiZWxvdy4KCiAgICAgIGlmIEdlbTo6U3BlY2lmaWNhdGlvbi51bnJlc29sdmVkX2RlcHMuZW1wdHk/CiAgICAgICAgbmV4dAogICAgICBlbmQKCiAgICAgICMgSWYgK3BhdGgrIGlzIGZvciBhIGdlbSB0aGF0IGhhcyBhbHJlYWR5IGJlZW4gbG9hZGVkLCBkb24ndAogICAgICAjIGJvdGhlciB0cnlpbmcgdG8gZmluZCBpdCBpbiBhbiB1bnJlc29sdmVkIGdlbSwganVzdCBnbyBzdHJhaWdodAogICAgICAjIHRvIG5vcm1hbCByZXF1aXJlLgogICAgICAjLS0KICAgICAgIyBUT0RPIHJlcXVlc3QgYWNjZXNzIHRvIHRoZSBDIGltcGxlbWVudGF0aW9uIG9mIHRoaXMgdG8gc3BlZWQgdXAgUnVieUdlbXMKCiAgICAgIGlmIEdlbTo6U3BlY2lmaWNhdGlvbi5maW5kX2FjdGl2ZV9zdHViX2J5X3BhdGgocGF0aCkKICAgICAgICBuZXh0CiAgICAgIGVuZAoKICAgICAgIyBBdHRlbXB0IHRvIGZpbmQgK3BhdGgrIGluIGFueSB1bnJlc29sdmVkIGdlbXMuLi4KCiAgICAgIGZvdW5kX3NwZWNzID0gR2VtOjpTcGVjaWZpY2F0aW9uLmZpbmRfaW5fdW5yZXNvbHZlZCBwYXRoCgogICAgICAjIElmIHRoZXJlIGFyZSBubyBkaXJlY3RseSB1bnJlc29sdmVkIGdlbXMsIHRoZW4gdHJ5IGFuZCBmaW5kICtwYXRoKwogICAgICAjIGluIGFueSBnZW1zIHRoYXQgYXJlIGF2YWlsYWJsZSB2aWEgdGhlIGN1cnJlbnRseSB1bnJlc29sdmVkIGdlbXMuCiAgICAgICMgRm9yIGV4YW1wbGUsIGdpdmVuOgogICAgICAjCiAgICAgICMgICBhID0+IGIgPT4gYyA9PiBkCiAgICAgICMKICAgICAgIyBJZiBhIGFuZCBiIGFyZSBjdXJyZW50bHkgYWN0aXZlIHdpdGggYyBiZWluZyB1bnJlc29sdmVkIGFuZCBkLnJiIGlzCiAgICAgICMgcmVxdWVzdGVkLCB0aGVuIGZpbmRfaW5fdW5yZXNvbHZlZF90cmVlIHdpbGwgZmluZCBkLnJiIGluIGQgYmVjYXVzZQogICAgICAjIGl0J3MgYSBkZXBlbmRlbmN5IG9mIGMuCiAgICAgICMKICAgICAgaWYgZm91bmRfc3BlY3MuZW1wdHk/CiAgICAgICAgZm91bmRfc3BlY3MgPSBHZW06OlNwZWNpZmljYXRpb24uZmluZF9pbl91bnJlc29sdmVkX3RyZWUgcGF0aAoKICAgICAgICBmb3VuZF9zcGVjcy5lYWNoKCY6YWN0aXZhdGUpCgogICAgICAjIFdlIGZvdW5kICtwYXRoKyBkaXJlY3RseSBpbiBhbiB1bnJlc29sdmVkIGdlbS4gTm93IHdlIGZpZ3VyZSBvdXQsIG9mCiAgICAgICMgdGhlIHBvc3NpYmxlIGZvdW5kIHNwZWNzLCB3aGljaCBvbmUgd2Ugc2hvdWxkIGFjdGl2YXRlLgogICAgICBlbHNlCgogICAgICAgICMgQ2hlY2sgdGhhdCBhbGwgdGhlIGZvdW5kIHNwZWNzIGFyZSBqdXN0IGRpZmZlcmVudAogICAgICAgICMgdmVyc2lvbnMgb2YgdGhlIHNhbWUgZ2VtCiAgICAgICAgbmFtZXMgPSBmb3VuZF9zcGVjcy5tYXAoJjpuYW1lKS51bmlxCgogICAgICAgIGlmIG5hbWVzLnNpemUgPiAxCiAgICAgICAgICByYWlzZSBHZW06OkxvYWRFcnJvciwgIiN7cGF0aH0gZm91bmQgaW4gbXVsdGlwbGUgZ2VtczogI3tuYW1lcy5qb2luICIsICJ9IgogICAgICAgIGVuZAoKICAgICAgICAjIE9rLCBub3cgZmluZCBhIGdlbSB0aGF0IGhhcyBubyBjb25mbGljdHMsIHN0YXJ0aW5nCiAgICAgICAgIyBhdCB0aGUgaGlnaGVzdCB2ZXJzaW9uLgogICAgICAgIHZhbGlkID0gZm91bmRfc3BlY3MuZmluZCB7fHN8ICFzLmhhc19jb25mbGljdHM/IH0KCiAgICAgICAgdW5sZXNzIHZhbGlkCiAgICAgICAgICBsZSA9IEdlbTo6TG9hZEVycm9yLm5ldyAidW5hYmxlIHRvIGZpbmQgYSB2ZXJzaW9uIG9mICcje25hbWVzLmZpcnN0fScgdG8gYWN0aXZhdGUiCiAgICAgICAgICBsZS5uYW1lID0gbmFtZXMuZmlyc3QKICAgICAgICAgIHJhaXNlIGxlCiAgICAgICAgZW5kCgogICAgICAgIHZhbGlkLmFjdGl2YXRlCiAgICAgIGVuZAogICAgZW5kCgogICAgYmVnaW4KICAgICAgZ2VtX29yaWdpbmFsX3JlcXVpcmUocGF0aCkKICAgIHJlc2N1ZSBMb2FkRXJyb3IgPT4gbG9hZF9lcnJvcgogICAgICBpZiBsb2FkX2Vycm9yLnBhdGggPT0gcGF0aCAmJgogICAgICAgICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1Iuc3luY2hyb25pemUgeyBHZW0udHJ5X2FjdGl2YXRlKHBhdGgpIH0KCiAgICAgICAgcmV0dXJuIGdlbV9vcmlnaW5hbF9yZXF1aXJlKHBhdGgpCiAgICAgIGVuZAoKICAgICAgcmFpc2UgbG9hZF9lcnJvcgogICAgZW5kCiAgZW5kCgogIHByaXZhdGUgOnJlcXVpcmUKZW5kCg==","encoding":"US-ASCII","path":"","line":1,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["e","path","msg","file"],"moduleNames":[]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGpzb24gMi4xOC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJqc29uIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4xOC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSlNPTiBwYXJzaW5nIGFuZCBnZW5lcmF0aW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkpTT04gcGFyc2luZyBhbmQgZ2VuZXJhdGlvbiIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2pzb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvYmlnZGVjaW1hbC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9jb21wbGV4LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL2NvcmUucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9kYXRlX3RpbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvZXhjZXB0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL29zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmFuZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmF0aW9uYWwucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmVnZXhwLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL3NldC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9zdHJpbmcucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvc3RydWN0LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL3N5bWJvbC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC90aW1lLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vY29tbW9uLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vZXh0LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vZ2VuZXJpY19vYmplY3QucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/json-2.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN0cmluZ2lvIDMuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJzdHJpbmdpbyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSU8gb24gc3RyaW5ncy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJTyBvbiBzdHJpbmdzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvc3RyaW5naW8ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/stringio-3.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN0cnNjYW4gMy4xLjYgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInN0cnNjYW4iLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjEuNiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkxleGljYWwgc2Nhbm5pbmcgb2Ygc3RyaW5ncy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJMZXhpY2FsIHNjYW5uaW5nIG9mIHN0cmluZ3MiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zdHJzY2FuLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/strscan-3.1.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLWNvbnNvbGUgMC44LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlvLWNvbnNvbGUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkNvbnNvbGUgc2l6ZSBhbmQgcmF3IG1vZGUuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ29uc29sZSBzaXplIGFuZCByYXcgbW9kZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2lvL2NvbnNvbGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaW8vY29uc29sZS9zaXplLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-console-0.8.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRhdGUgMy4zLjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImRhdGUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjMuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkRhdGUgYW5kIERhdGVUaW1lLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRhdGUgYW5kIERhdGVUaW1lIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9kYXRlL2Zvcm1hdC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/date-3.3.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wdHBhcnNlIDAuOC4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcHRwYXJzZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuOC4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiT3B0aW9uUGFyc2VyIGlzIGEgY2xhc3MgZm9yIGNvbW1hbmQtbGluZSBvcHRpb24gYW5hbHlzaXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3B0aW9uUGFyc2VyIGlzIGEgY2xhc3MgZm9yIGNvbW1hbmQtbGluZSBvcHRpb24gYW5hbHlzaXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL29wdHBhcnNlLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL2FjLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL2RhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2Uva3dhcmdzLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL3NoZWxsd29yZHMucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2UvdGltZS5yYiIuZnJlZXplLAogICAgImxpYi9vcHRwYXJzZS91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2UvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9vcHRpb25wYXJzZXIucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/optparse-0.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBwIDAuNi4zIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNi4zIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUHJldHR5LXByaW50cyBSdWJ5IG9iamVjdHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiUHJldHR5LXByaW50cyBSdWJ5IG9iamVjdHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3BwLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/pp-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByZXR0eXByaW50IDAuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmV0dHlwcmludCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSW1wbGVtZW50cyBhIHByZXR0eSBwcmludGluZyBhbGdvcml0aG0gZm9yIHJlYWRhYmxlIHN0cnVjdHVyZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJbXBsZW1lbnRzIGEgcHJldHR5IHByaW50aW5nIGFsZ29yaXRobSBmb3IgcmVhZGFibGUgc3RydWN0dXJlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9wcmV0dHlwcmludC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/prettyprint-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRlbXBmaWxlIDAuMy4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ0ZW1wZmlsZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQSB1dGlsaXR5IGNsYXNzIGZvciBtYW5hZ2luZyB0ZW1wb3JhcnkgZmlsZXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQSB1dGlsaXR5IGNsYXNzIGZvciBtYW5hZ2luZyB0ZW1wb3JhcnkgZmlsZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3RlbXBmaWxlLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tempfile-0.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRlbGVnYXRlIDAuNi4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJkZWxlZ2F0ZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNi4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiRGVsZWdhdGlvbiBvZiBtZXRob2QgY2FsbHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiRGVsZWdhdGlvbiBvZiBtZXRob2QgY2FsbHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL2RlbGVnYXRlLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/delegate-0.6.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRtcGRpciAwLjMuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidG1wZGlyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJFeHRlbmRzIHRoZSBEaXIgY2xhc3MgdG8gbWFuYWdlIHRoZSBPUyB0ZW1wb3JhcnkgZmlsZSBwYXRoLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkV4dGVuZHMgdGhlIERpciBjbGFzcyB0byBtYW5hZ2UgdGhlIE9TIHRlbXBvcmFyeSBmaWxlIHBhdGgiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3RtcGRpci5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tmpdir-0.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpbGV1dGlscyAxLjguMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZmlsZXV0aWxzIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS44LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJTZXZlcmFsIGZpbGUgdXRpbGl0eSBtZXRob2RzIGZvciBjb3B5aW5nLCBtb3ZpbmcsIHJlbW92aW5nLCBldGMuLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlNldmVyYWwgZmlsZSB1dGlsaXR5IG1ldGhvZHMgZm9yIGNvcHlpbmcsIG1vdmluZywgcmVtb3ZpbmcsIGV0Yy4iLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL2ZpbGV1dGlscy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fileutils-1.8.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRpbWUgMC40LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInRpbWUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkV4dGVuZHMgdGhlIFRpbWUgY2xhc3Mgd2l0aCBtZXRob2RzIGZvciBwYXJzaW5nIGFuZCBjb252ZXJzaW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkV4dGVuZHMgdGhlIFRpbWUgY2xhc3Mgd2l0aCBtZXRob2RzIGZvciBwYXJzaW5nIGFuZCBjb252ZXJzaW9uIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi90aW1lLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/time-0.4.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGV0YyAxLjQuNiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXRjIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS40LjYiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBY2Nlc3MgdG8gaW5mb3JtYXRpb24gZnJvbSB0aGUgcGFzc3dkIGFuZCBncm91cCBmaWxlcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBY2Nlc3MgdG8gaW5mb3JtYXRpb24gZnJvbSB0aGUgcGFzc3dkIGFuZCBncm91cCBmaWxlcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2V0Yy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/etc-1.4.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLXdhaXQgMC40LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlvLXdhaXQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIklPI3dhaXQgYW5kIGZyaWVuZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSU8jd2FpdCBhbmQgZnJpZW5kcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2lvL3dhaXQucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-wait-0.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHpsaWIgMy4yLjMgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInpsaWIiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjIuMyIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkRlZmxhdGUvaW5mbGF0ZSwgb24gU3lzdGVtLklPLkNvbXByZXNzaW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRlZmxhdGUvaW5mbGF0ZSwgb24gU3lzdGVtLklPLkNvbXByZXNzaW9uIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvemxpYi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/zlib-3.2.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW5zc2wgMy4yLjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm9wZW5zc2wiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjIuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk9wZW5TU0wgYmluZGluZ3MsIG9uIC5ORVQncyBjcnlwdG9ncmFwaHkgc3RhY2suICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3BlblNTTCBiaW5kaW5ncywgb24gLk5FVCdzIGNyeXB0b2dyYXBoeSBzdGFjayIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL29wZW5zc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9hc24xLnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wvYm4ucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9jaXBoZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9kaWdlc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9wa2V5LnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wvc3NsLnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wveDUwOS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/openssl-3.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGFiYnJldiAwLjEuMiBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYWJicmV2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4xLjIiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9hYmJyZXYiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYWJicmV2IiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJBa2lub3JpIE1VU0hBIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMy0xMi0xNiIKICBzLmRlc2NyaXB0aW9uID0gIkNhbGN1bGF0ZXMgYSBzZXQgb2YgdW5pcXVlIGFiYnJldmlhdGlvbnMgZm9yIGEgZ2l2ZW4gc2V0IG9mIHN0cmluZ3MiLmZyZWV6ZQogIHMuZW1haWwgPSBbImtudUBpZGFlbW9ucy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2FiYnJldiIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2FsY3VsYXRlcyBhIHNldCBvZiB1bmlxdWUgYWJicmV2aWF0aW9ucyBmb3IgYSBnaXZlbiBzZXQgb2Ygc3RyaW5ncyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/abbrev-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJhc2U2NCAwLjMuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYmFzZTY0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYmFzZTY0L3JlbGVhc2VzIiwgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2Jhc2U2NCIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iYXNlNjQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1c3VrZSBFbmRvaCIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJTdXBwb3J0IGZvciBlbmNvZGluZyBhbmQgZGVjb2RpbmcgYmluYXJ5IGRhdGEgdXNpbmcgYSBCYXNlNjQgcmVwcmVzZW50YXRpb24uIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYW1lQHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2Jhc2U2NCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi40Ii5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi43Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiU3VwcG9ydCBmb3IgZW5jb2RpbmcgYW5kIGRlY29kaW5nIGJpbmFyeSBkYXRhIHVzaW5nIGEgQmFzZTY0IHJlcHJlc2VudGF0aW9uLiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/base64-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJjcnlwdCAzLjEuMjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImJjcnlwdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuMS4yMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk9wZW5CU0QgYmNyeXB0IHBhc3N3b3JkIGhhc2hpbmc7IGJjcnlwdF9leHQgaW4gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3BlbkJTRCBiY3J5cHQgcGFzc3dvcmQgaGFzaGluZzsgYmNyeXB0X2V4dCBpbiBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2JjcnlwdC5yYiIuZnJlZXplLAogICAgImxpYi9iY3J5cHQvZW5naW5lLnJiIi5mcmVlemUsCiAgICAibGliL2JjcnlwdC9lcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9iY3J5cHQvcGFzc3dvcmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYmNyeXB0X2V4dC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bcrypt-3.1.22.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJlbmNobWFyayAwLjUuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYmVuY2htYXJrIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC41LjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iZW5jaG1hcmsiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYmVuY2htYXJrIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJZdWtpaGlybyBNYXRzdW1vdG8iLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiYSBwZXJmb3JtYW5jZSBiZW5jaG1hcmtpbmcgbGlicmFyeSIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iZW5jaG1hcmsiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuMS4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiYSBwZXJmb3JtYW5jZSBiZW5jaG1hcmtpbmcgbGlicmFyeSIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/benchmark-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJpZ2RlY2ltYWwgNC4wLjEgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImJpZ2RlY2ltYWwiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICI0LjAuMSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkFyYml0cmFyeS1wcmVjaXNpb24gZGVjaW1hbCBhcml0aG1ldGljLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkFyYml0cmFyeS1wcmVjaXNpb24gZGVjaW1hbCBhcml0aG1ldGljIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvYmlnZGVjaW1hbC5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL2phY29iaWFuLnJiIi5mcmVlemUsCiAgICAibGliL2JpZ2RlY2ltYWwvbHVkY21wLnJiIi5mcmVlemUsCiAgICAibGliL2JpZ2RlY2ltYWwvbWF0aC5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL25ld3Rvbi5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL3V0aWwucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bigdecimal-4.0.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJ1bmRsZXIgNC4wLjIwIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJidW5kbGVyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiNC4wLjIwIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVGhlIGJlc3Qgd2F5IHRvIG1hbmFnZSBhIFJ1YnkgYXBwbGljYXRpb24ncyBnZW1zLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBiZXN0IHdheSB0byBtYW5hZ2UgYSBSdWJ5IGFwcGxpY2F0aW9uJ3MgZ2VtcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmV4ZWN1dGFibGVzID0gWyJidW5kbGUiLmZyZWV6ZSwgImJ1bmRsZXIiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9idW5kbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvYnVpbGRfbWV0YWRhdGEucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jYXBpc3RyYW5vLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2hlY2tzdW0ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jaV9kZXRlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9hZGQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvYmluc3R1YnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2FjaGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2hlY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2xlYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY29tbW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2NvbmZpZy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9jb25zb2xlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2RvY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9kb2N0b3IvZGlhZ25vc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvZG9jdG9yL3NzbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9leGVjLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2Z1bmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvZ2VtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2luZm8ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvaW5pdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9pbnN0YWxsLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2lzc3VlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2xpc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvbG9jay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9vcGVuLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL291dGRhdGVkLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL3BsdWdpbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9wcmlzdGluZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9yZW1vdmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvc2hvdy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS91cGRhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jb21wYWN0X2luZGV4X2NsaWVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L2NhY2hlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY29tcGFjdF9pbmRleF9jbGllbnQvY2FjaGVfZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L3VwZGF0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jb25zdGFudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jdXJyZW50X3J1YnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kZWZpbml0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZGVwZW5kZW5jeS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2RlcGxveW1lbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kZXByZWNhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kaWdlc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9lbmRwb2ludF9zcGVjaWZpY2F0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZW52LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZW52aXJvbm1lbnRfcHJlc2VydmVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmVhdHVyZV9mbGFnLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmV0Y2hlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvY29tcGFjdF9pbmRleC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZGVwZW5kZW5jeS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZG93bmxvYWRlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZ2VtX3JlbW90ZV9mZXRjaGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmV0Y2hlci9pbmRleC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZvcmNlX3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZnJpZW5kbHlfZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZ2VtX2hlbHBlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2dlbV90YXNrcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2dlbV92ZXJzaW9uX3Byb21vdGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvaW5kZXgucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9pbmplY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2lubGluZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci9nZW1faW5zdGFsbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvaW5zdGFsbGVyL3BhcmFsbGVsX2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci9zdGFuZGFsb25lLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbGF6eV9zcGVjaWZpY2F0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbG9ja2ZpbGVfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbG9ja2ZpbGVfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbWF0Y2hfbWV0YWRhdGEucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9tYXRjaF9wbGF0Zm9ybS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21hdGNoX3JlbW90ZV9tZXRhZGF0YS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21hdGVyaWFsaXphdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21pcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9hcGkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wbHVnaW4vYXBpL3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wbHVnaW4vZXZlbnRzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luZGV4LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9pbnN0YWxsZXIvZ2l0LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci9wYXRoLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci9ydWJ5Z2Vtcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9zb3VyY2VfbGlzdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi91bmxvYWRlZF9zb3VyY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wcm9jZXNzX2xvY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9yZW1vdGVfc3BlY2lmaWNhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmVzb2x2ZXIvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL2NhbmRpZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL2luY29tcGF0aWJpbGl0eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL3BhY2thZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9yZXNvbHZlci9yb290LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmVzb2x2ZXIvc3BlY19ncm91cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL3N0cmF0ZWd5LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmV0cnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9ydWJ5X2RzbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlfdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlnZW1zX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlnZW1zX2dlbV9pbnN0YWxsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9ydWJ5Z2Vtc19pbnRlZ3JhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1bnRpbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zYWZlX21hcnNoYWwucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zZWxmX21hbmFnZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zZXR0aW5ncy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NldHRpbmdzL3ZhbGlkYXRvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NldHVwLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc2hhcmVkX2hlbHBlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UvZ2Vtc3BlYy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9naXQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UvZ2l0L2dpdF9wcm94eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9tZXRhZGF0YS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9wYXRoLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3BhdGgvaW5zdGFsbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3J1YnlnZW1zLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3J1YnlnZW1zL3JlbW90ZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9ydWJ5Z2Vtc19hZ2dyZWdhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2VfbGlzdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZV9tYXAucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zcGVjX3NldC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3N0dWJfc3BlY2lmaWNhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VpLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdWkvcmdfcHJveHkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci91aS9zaGVsbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VpL3NpbGVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VyaV9jcmVkZW50aWFsc19maWx0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci91cmlfbm9ybWFsaXplci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC90aW1lZF9zdGFjay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL2Nvbm5lY3Rpb25fcG9vbC9saWIvY29ubmVjdGlvbl9wb29sL3dyYXBwZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvZmlsZXV0aWxzL2xpYi9maWxldXRpbHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvbmV0LWh0dHAtcGVyc2lzdGVudC9saWIvbmV0L2h0dHAvcGVyc2lzdGVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9uZXQtaHR0cC1wZXJzaXN0ZW50L2xpYi9uZXQvaHR0cC9wZXJzaXN0ZW50L2Nvbm5lY3Rpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvbmV0LWh0dHAtcGVyc2lzdGVudC9saWIvbmV0L2h0dHAvcGVyc2lzdGVudC9wb29sLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL25ldC1odHRwLXBlcnNpc3RlbnQvbGliL25ldC9odHRwL3BlcnNpc3RlbnQvdGltZWRfc3RhY2tfbXVsdGkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3B1Yl9ncnViL2xpYi9wdWJfZ3J1Yi9hc3NpZ25tZW50LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3B1Yl9ncnViL2xpYi9wdWJfZ3J1Yi9iYXNpY19wYWNrYWdlX3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvZmFpbHVyZV93cml0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL2luY29tcGF0aWJpbGl0eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcGFja2FnZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcGFydGlhbF9zb2x1dGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcnVieWdlbXMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3NvbHZlX2ZhaWx1cmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3N0YXRpY19wYWNrYWdlX3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvc3RyYXRlZ3kucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3Rlcm0ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb25fY29uc3RyYWludC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvdmVyc2lvbl9yYW5nZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvdmVyc2lvbl9zb2x2ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb25fdW5pb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3Ivc2VjdXJlcmFuZG9tL2xpYi9zZWN1cmVyYW5kb20ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2FjdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9hY3Rpb25zL2NyZWF0ZV9maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9jcmVhdGVfbGluay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2FjdGlvbnMvZGlyZWN0b3J5LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9lbXB0eV9kaXJlY3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9hY3Rpb25zL2ZpbGVfbWFuaXB1bGF0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9pbmplY3RfaW50b19maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2NvbW1hbmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9jb3JlX2V4dC9oYXNoX3dpdGhfaW5kaWZmZXJlbnRfYWNjZXNzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9ncm91cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2ludm9jYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9saW5lX2VkaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2xpbmVfZWRpdG9yL2Jhc2ljLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvbGluZV9lZGl0b3IvcmVhZGxpbmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9uZXN0ZWRfY29udGV4dC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci9hcmd1bWVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci9hcmd1bWVudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9wYXJzZXIvb3B0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvcGFyc2VyL29wdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9yYWtlX2NvbXBhdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3J1bm5lci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3Ivc2hlbGwvYmFzaWMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9zaGVsbC9jb2xvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL2NvbHVtbl9wcmludGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3Ivc2hlbGwvaHRtbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL3RhYmxlX3ByaW50ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9zaGVsbC90ZXJtaW5hbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL3dyYXBwZWRfcHJpbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3V0aWwucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2NvbW1vbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2Z0cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9nZW5lcmljLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvaHR0cHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvbGRhcC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9sZGFwcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9tYWlsdG8ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvcmZjMjM5Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvcmZjMzk4Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS93cy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS93c3MucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9maWxldXRpbHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9uZXRfaHR0cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3BlcnNpc3RlbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9wdWJfZ3J1Yi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3NlY3VyZXJhbmRvbS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3Rob3IucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF90aW1lb3V0LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yZWRfdHNvcnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmxhZC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3dvcmtlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3lhbWxfc2VyaWFsaXplci5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bundler-4.0.20.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGNnaSAwLjUuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiY2dpIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC41LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJDR0kuZXNjYXBlIGFuZCBmcmllbmRzIC0gUnVieSA0LjAncyBjZ2kvZXNjYXBlLCBub3QgdGhlIGZ1bGwgQ0dJIGNsYXNzLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkNHSS5lc2NhcGUgYW5kIGZyaWVuZHMgLSBSdWJ5IDQuMCdzIGNnaS9lc2NhcGUsIG5vdCB0aGUgZnVsbCBDR0kgY2xhc3MiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9jZ2kucmIiLmZyZWV6ZSwKICAgICJsaWIvY2dpL2VzY2FwZS5yYiIuZnJlZXplLAogICAgImxpYi9jZ2kvdXRpbC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/cgi-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGNzdiAzLjMuNSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiY3N2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4zLjUiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvY3N2L3JlbGVhc2VzL3RhZy92My4zLjUiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIkphbWVzIEVkd2FyZCBHcmF5IElJIi5mcmVlemUsICJLb3VoZWkgU3V0b3UiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlRoZSBDU1YgbGlicmFyeSBwcm92aWRlcyBhIGNvbXBsZXRlIGludGVyZmFjZSB0byBDU1YgZmlsZXMgYW5kIGRhdGEuIEl0IG9mZmVycyB0b29scyB0byBlbmFibGUgeW91IHRvIHJlYWQgYW5kIHdyaXRlIHRvIGFuZCBmcm9tIFN0cmluZ3Mgb3IgSU8gb2JqZWN0cywgYXMgbmVlZGVkLiIuZnJlZXplCiAgcy5lbWFpbCA9IFtuaWwsICJrb3VAY296bWl4bmcub3JnIi5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvY3N2L3JlY2lwZXMvZmlsdGVyaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9nZW5lcmF0aW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9wYXJzaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9yZWNpcGVzLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvY3N2L3JlY2lwZXMvZmlsdGVyaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9nZW5lcmF0aW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9wYXJzaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9yZWNpcGVzLnJkb2MiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2NzdiIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjciLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJDU1YgUmVhZGluZyBhbmQgV3JpdGluZyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/csv-3.3.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRpZF95b3VfbWVhbiAyLjAuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZGlkX3lvdV9tZWFuIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4wLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJEaWQgeW91IG1lYW4/IGV4cGVyaWVuY2UuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiRGlkIHlvdSBtZWFuPyBleHBlcmllbmNlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9kaWRfeW91X21lYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL2NvcmVfZXh0L25hbWVfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL2V4cGVyaW1lbnRhbC5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vZm9ybWF0dGVyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9mb3JtYXR0ZXJzL3BsYWluX2Zvcm1hdHRlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vZm9ybWF0dGVycy92ZXJib3NlX2Zvcm1hdHRlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vamFyb193aW5rbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9sZXZlbnNodGVpbi5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlcnMva2V5X2Vycm9yX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL21ldGhvZF9uYW1lX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL25hbWVfZXJyb3JfY2hlY2tlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL25hbWVfZXJyb3JfY2hlY2tlcnMvY2xhc3NfbmFtZV9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9zcGVsbF9jaGVja2Vycy9uYW1lX2Vycm9yX2NoZWNrZXJzL3ZhcmlhYmxlX25hbWVfY2hlY2tlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlcnMvbnVsbF9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9zcGVsbF9jaGVja2Vycy9wYXR0ZXJuX2tleV9uYW1lX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL3JlcXVpcmVfcGF0aF9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi90cmVlX3NwZWxsX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3ZlcmJvc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/did_you_mean-2.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRpZ2VzdCAzLjIuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZGlnZXN0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4yLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJNZXNzYWdlIGRpZ2VzdCBsaWJyYXJpZXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWVzc2FnZSBkaWdlc3QgbGlicmFyaWVzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZGlnZXN0LnJiIi5mcmVlemUsCiAgICAibGliL2RpZ2VzdC9idWJibGViYWJibGUucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlnZXN0L21kNS5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3Qvc2hhMS5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3Qvc2hhMi5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3QvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/digest-3.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRyYiAyLjIuMyBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZHJiIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4yLjMiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiL3JlbGVhc2VzL3RhZy92Mi4yLjMiLCAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2RyYiIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiTWFzYXRvc2hpIFNFS0kiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIkRpc3RyaWJ1dGVkIG9iamVjdCBzeXN0ZW0gZm9yIFJ1YnkiLmZyZWV6ZQogIHMuZW1haWwgPSBbInNla2lAcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjcuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuNyIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRpc3RyaWJ1dGVkIG9iamVjdCBzeXN0ZW0gZm9yIFJ1YnkiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/drb-2.2.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVuZ2xpc2ggMC44LjEgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImVuZ2xpc2giLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlJlYWRhYmxlIGFsaWFzZXMgZm9yIHRoZSBzcGVjaWFsIHZhcmlhYmxlcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJSZWFkYWJsZSBhbGlhc2VzIGZvciB0aGUgc3BlY2lhbCB2YXJpYWJsZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL0VuZ2xpc2gucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/english-0.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVyYiA2LjAuNyBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXJiIi5mcmVlemUKICBzLnZlcnNpb24gPSAiNi4wLjciCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBbiBlYXN5LXRvLXVzZSBidXQgcG93ZXJmdWwgdGVtcGxhdGluZyBzeXN0ZW0uICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQW4gZWFzeS10by11c2UgYnV0IHBvd2VyZnVsIHRlbXBsYXRpbmcgc3lzdGVtIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZXJiLnJiIi5mcmVlemUsCiAgICAibGliL2VyYi9jb21waWxlci5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvZGVmX21ldGhvZC5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvdXRpbC5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/erb-6.0.7.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVycm9yX2hpZ2hsaWdodCAwLjcuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXJyb3JfaGlnaGxpZ2h0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC43LjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgZXJyb3JfaGlnaGxpZ2h0IEFQSTsgc3BvdCBhbHdheXMgYW5zd2VycyBuaWwgaGVyZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJUaGUgZXJyb3JfaGlnaGxpZ2h0IEFQSTsgc3BvdCBhbHdheXMgYW5zd2VycyBuaWwgaGVyZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvZXJyb3JfaGlnaGxpZ2h0LnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC9iYXNlLnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC9jb3JlX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9lcnJvcl9oaWdobGlnaHQvZm9ybWF0dGVyLnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/error_highlight-0.7.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZjbnRsIDEuMy4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJmY250bCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMy4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQ29uc3RhbnRzIGZvciBmY250bCgyKSBhbmQgb3BlbigyKS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJDb25zdGFudHMgZm9yIGZjbnRsKDIpIGFuZCBvcGVuKDIpIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZmNudGwucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fcntl-1.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZmaSAxLjE3LjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImZmaSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMTcuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlRoZSBmZmkgZ2VtJ3MgQVBJLCBvbiBGaWRkbGUuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhlIGZmaSBnZW0ncyBBUEksIG9uIEZpZGRsZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2ZmaS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvYWJzdHJhY3RfbWVtb3J5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9hdXRvcG9pbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9jYWxsYmFjay5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvY29tcGF0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9kYXRhX2NvbnZlcnRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvZHluYW1pY19saWJyYXJ5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9lbnVtLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9lcnJuby5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvZmZpLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9mdW5jdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaW8ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L2R5bmFtaWNfbGlicmFyeS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaXJvbnJ1YnkvZnVuY3Rpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L2xhc3RfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L21lbW9yeS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaXJvbnJ1Ynkvc3RydWN0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9pcm9ucnVieS9zdHJ1Y3RfbGF5b3V0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9pcm9ucnVieS90eXBlLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9saWJyYXJ5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9saWJyYXJ5X3BhdGgucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL21hbmFnZWRzdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL21lbW9yeXBvaW50ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9wb2ludGVyLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9ieV9yZWZlcmVuY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9sYXlvdXQucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9sYXlvdXRfYnVpbGRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvdG9vbHMvY29uc3RfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90b29scy9nZW5lcmF0b3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3Rvb2xzL2dlbmVyYXRvcl90YXNrLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90b29scy9zdHJ1Y3RfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90eXBlcy5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvdW5pb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3ZhcmlhZGljLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ffi-1.17.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpZGRsZSAxLjEuOCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZmlkZGxlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4xLjgiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJDYWxsaW5nIHNoYXJlZC1saWJyYXJ5IGZ1bmN0aW9ucywgb24gTmF0aXZlTGlicmFyeSBhbmQgY2FsbGkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2FsbGluZyBzaGFyZWQtbGlicmFyeSBmdW5jdGlvbnMsIG9uIE5hdGl2ZUxpYnJhcnkgYW5kIGNhbGxpIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZmlkZGxlLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9jbG9zdXJlLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9jcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9mdW5jdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9maWRkbGUvaW1wb3J0LnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9wYWNrLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmlkZGxlL3R5cGVzLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS92YWx1ZS5yYiIuZnJlZXplLAogICAgImxpYi9maWRkbGUvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fiddle-1.1.8.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpbmQgMC4yLjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImZpbmQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlRyYXZlcnNlIGEgZmlsZSB0cmVlLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRyYXZlcnNlIGEgZmlsZSB0cmVlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9maW5kLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/find-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZvcndhcmRhYmxlIDEuNC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJmb3J3YXJkYWJsZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuNC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUHJvdmlkZXMgZGVsZWdhdGlvbiBvZiBzcGVjaWZpZWQgbWV0aG9kcyB0byBhIGRlc2lnbmF0ZWQgb2JqZWN0LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlByb3ZpZGVzIGRlbGVnYXRpb24gb2Ygc3BlY2lmaWVkIG1ldGhvZHMgdG8gYSBkZXNpZ25hdGVkIG9iamVjdCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvZm9yd2FyZGFibGUucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/forwardable-1.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGdldG9wdGxvbmcgMC4yLjEgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImdldG9wdGxvbmciLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2dldG9wdGxvbmciLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZ2V0b3B0bG9uZyIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiWXVraWhpcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5kYXRlID0gIjIwMjMtMTEtMDciCiAgcy5kZXNjcmlwdGlvbiA9ICJHZXRvcHRMb25nIGZvciBSdWJ5Ii5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2dldG9wdGxvbmciLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjUuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJHZXRvcHRMb25nIGZvciBSdWJ5Ii5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/getoptlong-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLW5vbmJsb2NrIDAuMy4yIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJpby1ub25ibG9jayIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4yIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSU8jbm9uYmxvY2suICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSU8jbm9uYmxvY2siLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9pby9ub25ibG9jay5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-nonblock-0.3.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlwYWRkciAxLjIuOCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiaXBhZGRyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4yLjgiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBIGNsYXNzIHRvIG1hbmlwdWxhdGUgYW4gSVAgYWRkcmVzcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBIGNsYXNzIHRvIG1hbmlwdWxhdGUgYW4gSVAgYWRkcmVzcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvaXBhZGRyLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ipaddr-1.2.8.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlyYiAxLjE4LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlyYiIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMTguMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkludGVyYWN0aXZlIFJ1YnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSW50ZXJhY3RpdmUgUnVieSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5leGVjdXRhYmxlcyA9IFsiaXJiIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvaXJiLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jbWQvbm9wLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb2xvci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29sb3JfcHJpbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9iYWNrdHJhY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9icmVhay5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jYXRjaC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jaHdzLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2NvbnRleHQucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvY29udGludWUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvY29weS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9kZWJ1Zy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9kZWxldGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvZGlzYWJsZV9pcmIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvZWRpdC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9leGl0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2ZpbmlzaC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9mb3JjZV9leGl0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2hlbHAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvaGlzdG9yeS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9pbmZvLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2ludGVybmFsX2hlbHBlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvaXJiX2luZm8ucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvbG9hZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9scy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9tZWFzdXJlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL25leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvcHVzaHdzLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3Nob3dfZG9jLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3Nob3dfc291cmNlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3N0ZXAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvc3ViaXJiLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3doZXJlYW1pLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21wbGV0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb250ZXh0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9kZWJ1Zy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvZGVidWcvdWkucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2RlZmF1bHRfY29tbWFuZHMucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2Vhc3Rlci1lZ2cucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9jaGFuZ2Utd3MucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9ldmFsX2hpc3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9sb2FkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9tdWx0aS1pcmIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC90cmFjZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC91c2UtbG9hZGVyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9leHQvd29ya3NwYWNlcy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvZnJhbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHBlcl9tZXRob2QucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHBlcl9tZXRob2QvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvaGVscGVyX21ldGhvZC9jb25mLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9oaXN0b3J5LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9pbml0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9pbnB1dC1tZXRob2QucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2luc3BlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvbGMvZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2xjL2phL2Vycm9yLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9sb2NhbGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL25lc3RpbmdfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9ub3RpZmllci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvb3V0cHV0LW1ldGhvZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvcGFnZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL3J1YnktbGV4LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9zb3VyY2VfZmluZGVyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9zdGFydHVwX21lc3NhZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL3N0YXRlbWVudC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvd29ya3NwYWNlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi93cy1mb3ItY2FzZS0yLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi94bXAucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/irb-1.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGxvZ2dlciAxLjcuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibG9nZ2VyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS43LjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbG9nZ2VyL3JlbGVhc2VzIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJOYW90b3NoaSBTZW8iLmZyZWV6ZSwgIlNISUJBVEEgSGlyb3NoaSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTAzLTI3IgogIHMuZGVzY3JpcHRpb24gPSAiUHJvdmlkZXMgYSBzaW1wbGUgbG9nZ2luZyB1dGlsaXR5IGZvciBvdXRwdXR0aW5nIG1lc3NhZ2VzLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsic29ub3RzQGdtYWlsLmNvbSIuZnJlZXplLCAiaHNidEBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9sb2dnZXIiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuNS4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4xMSIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlByb3ZpZGVzIGEgc2ltcGxlIGxvZ2dpbmcgdXRpbGl0eSBmb3Igb3V0cHV0dGluZyBtZXNzYWdlcy4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/logger-1.7.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1hdHJpeCAwLjQuMyBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibWF0cml4Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC40LjMiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJNYXJjLUFuZHJlIExhZm9ydHVuZSIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjIwMjUtMDYtMTgiCiAgcy5kZXNjcmlwdGlvbiA9ICJBbiBpbXBsZW1lbnRhdGlvbiBvZiBNYXRyaXggYW5kIFZlY3RvciBjbGFzc2VzLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnVieS1jb3JlQG1hcmMtYW5kcmUuY2EiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L21hdHJpeCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQW4gaW1wbGVtZW50YXRpb24gb2YgTWF0cml4IGFuZCBWZWN0b3IgY2xhc3Nlcy4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/matrix-0.4.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1pbml0ZXN0IDYuMC4wIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJtaW5pdGVzdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjYuMC4wIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiYnVnX3RyYWNrZXJfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0L2lzc3VlcyIsICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0L2Jsb2IvbWFzdGVyL0hpc3RvcnkucmRvYyIsICJob21lcGFnZV91cmkiID0+ICJodHRwczovL21pbml0ZS5zdC8iLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0IiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJSeWFuIERhdmlzIi5mcmVlemVdCiAgcy5jZXJ0X2NoYWluID0gWyItLS0tLUJFR0lOIENFUlRJRklDQVRFLS0tLS1cbk1JSURQakNDQWlhZ0F3SUJBZ0lCQ1RBTkJna3Foa2lHOXcwQkFRc0ZBREJGTVJNd0VRWURWUVFEREFweWVXRnVcblpDMXlkV0o1TVJrd0Z3WUtDWkltaVpQeUxHUUJHUllKZW1WdWMzQnBaR1Z5TVJNd0VRWUtDWkltaVpQeUxHUUJcbkdSWURZMjl0TUI0WERUSTFNREV3TmpJek1qY3dNVm9YRFRJMk1ERXdOakl6TWpjd01Wb3dSVEVUTUJFR0ExVUVcbkF3d0tjbmxoYm1RdGNuVmllVEVaTUJjR0NnbVNKb21UOGl4a0FSa1dDWHBsYm5Od2FXUmxjakVUTUJFR0NnbVNcbkpvbVQ4aXhrQVJrV0EyTnZiVENDQVNJd0RRWUpLb1pJaHZjTkFRRUJCUUFEZ2dFUEFEQ0NBUW9DZ2dFQkFMZGFcbmI5RENnSys2MjdnUEprQjZYZmpaMWl0b09RdnBxSDFFWFNjU2FiYTkvUzJWRjIyVllRYlhVMXhRWEwvV3pDa3hcbnRhQ1BhTG1mWUlhRmNISENTWTRoWURKaWpSUWtMeFBlQjN4Yk9memZMb0JEYmp2eDVKeGdKeFVqbUdhN3hoY1Rcbm9Pdmp0dDVQOCtHU0s5ekx6eFFQMGdWTFMvRDBGbW9FNDRYdURyM2lRa1ZTMnVqVTV6Wkw4NG1NTnFOQjF6bmhcbkdpYWRNOUdIUmFEaWF4dVgwY0lVQmoxOVQwMW1WRTJpeW1mOUk2YkVzaWF5Sy9uNlF1anR5Q2JUV3NBUzlScXRcbnFodFY3SEp4Tkt1UGovSkZIMEQyY3N3dnp6bkUvYTVGT1lPNjhnK1lDdUZpNUw4d1p1dU04enpkd2pyV0hxU1ZcbmdCRWZvVEVHcjdaaWk3MmN4K3NDQXdFQUFhTTVNRGN3Q1FZRFZSMFRCQUl3QURBTEJnTlZIUThFQkFNQ0JMQXdcbkhRWURWUjBPQkJZRUZFZkZlOW1kL3IvdGovV213cHkrTUk4ZDlrL2hNQTBHQ1NxR1NJYjNEUUVCQ3dVQUE0SUJcbkFRQUMwV1FKY1BPV1BGd2tvamh6d2VpbFJWalRKMTlVaUxoaUJUdzNDMXdKTzNMVmRCa1dEbW5uaEFtS3VYNERcbnI3dmpRdkVTbEFCR0lQZHV0STFZbDdtckhRelRrZkxmWHZOTjZNVDBuTENoUHlJWWF1VDZTWlp4dWJ3SnJVZkFcbjdSMGMyQ0pUSWJvWjBYYUdwTHNYcUhFRjFjMjlIN1RWMVF2VnVxS0FOMm1Damg0TjgyUVZuK1pLdHlzMjhBd1RcbjZHZlFYMmZxTG9pNEtTYzd4SXpIS2FOenF4ZU9JQ21Kb2ZrOXc1VloyclJONnllczhqdkZZd3o5SFI0MXdkajhcbmJ3ZmludjdZcDVmQTZBeXN1WkxoQ3lreWZEdVpWUnJVcDBWYjY4WUNLc0xqSmx5L1RoZWFrK2V1TlR4dkhzQitcbmFsOW9TZ1BQSElDTUVYNjVxdkx5d2l0eFxuLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLVxuIi5mcmVlemVdCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJtaW5pdGVzdCBwcm92aWRlcyBhIGNvbXBsZXRlIHN1aXRlIG9mIHRlc3RpbmcgZmFjaWxpdGllcyBzdXBwb3J0aW5nXG5UREQsIEJERCwgYW5kIGJlbmNobWFya2luZy5cblxuICAgIFwiSSBoYWQgYSBjbGFzcyB3aXRoIEppbSBXZWlyaWNoIG9uIHRlc3RpbmcgbGFzdCB3ZWVrIGFuZCB3ZSB3ZXJlXG4gICAgIGFsbG93ZWQgdG8gY2hvb3NlIG91ciB0ZXN0aW5nIGZyYW1ld29ya3MuIEtpcmsgSGFpbmVzIGFuZCBJIHdlcmVcbiAgICAgcGFpcmVkIHVwIGFuZCB3ZSBjcmFja2VkIG9wZW4gdGhlIGNvZGUgZm9yIGEgZmV3IHRlc3RcbiAgICAgZnJhbWV3b3Jrcy4uLlxuXG4gICAgIEkgTVVTVCBzYXkgdGhhdCBtaW5pdGVzdCBpcyAqdmVyeSogcmVhZGFibGUgLyB1bmRlcnN0YW5kYWJsZVxuICAgICBjb21wYXJlZCB0byB0aGUgJ290aGVyIHR3bycgb3B0aW9ucyB3ZSBsb29rZWQgYXQuIE5pY2VseSBkb25lIGFuZFxuICAgICB0aGFuayB5b3UgZm9yIGhlbHBpbmcgdXMga2VlcCBvdXIgbWVudGFsIHNhbml0eS5cIlxuXG4gICAgLS0gV2F5bmUgRS4gU2VndWluXG5cbm1pbml0ZXN0L3Rlc3QgaXMgYSBzbWFsbCBhbmQgaW5jcmVkaWJseSBmYXN0IHVuaXQgdGVzdGluZyBmcmFtZXdvcmsuXG5JdCBwcm92aWRlcyBhIHJpY2ggc2V0IG9mIGFzc2VydGlvbnMgdG8gbWFrZSB5b3VyIHRlc3RzIGNsZWFuIGFuZFxucmVhZGFibGUuXG5cbm1pbml0ZXN0L3NwZWMgaXMgYSBmdW5jdGlvbmFsbHkgY29tcGxldGUgc3BlYyBlbmdpbmUuIEl0IGhvb2tzIG9udG9cbm1pbml0ZXN0L3Rlc3QgYW5kIHNlYW1sZXNzbHkgYnJpZGdlcyB0ZXN0IGFzc2VydGlvbnMgb3ZlciB0byBzcGVjXG5leHBlY3RhdGlvbnMuXG5cbm1pbml0ZXN0L2JlbmNobWFyayBpcyBhbiBhd2Vzb21lIHdheSB0byBhc3NlcnQgdGhlIHBlcmZvcm1hbmNlIG9mIHlvdXJcbmFsZ29yaXRobXMgaW4gYSByZXBlYXRhYmxlIG1hbm5lci4gTm93IHlvdSBjYW4gYXNzZXJ0IHRoYXQgeW91ciBuZXdiXG5jby13b3JrZXIgZG9lc24ndCByZXBsYWNlIHlvdXIgbGluZWFyIGFsZ29yaXRobSB3aXRoIGFuIGV4cG9uZW50aWFsXG5vbmUhXG5cbm1pbml0ZXN0L3ByaWRlIHNob3dzIHByaWRlIGluIHRlc3RpbmcgYW5kIGFkZHMgY29sb3JpbmcgdG8geW91ciB0ZXN0XG5vdXRwdXQuIEkgZ3Vlc3MgaXQgaXMgYW4gZXhhbXBsZSBvZiBob3cgdG8gd3JpdGUgSU8gcGlwZXMgdG9vLiA6UFxuXG5taW5pdGVzdC90ZXN0IGlzIG1lYW50IHRvIGhhdmUgYSBjbGVhbiBpbXBsZW1lbnRhdGlvbiBmb3IgbGFuZ3VhZ2VcbmltcGxlbWVudG9ycyB0aGF0IG5lZWQgYSBtaW5pbWFsIHNldCBvZiBtZXRob2RzIHRvIGJvb3RzdHJhcCBhIHdvcmtpbmdcbnRlc3Qgc3VpdGUuIEZvciBleGFtcGxlLCB0aGVyZSBpcyBubyBtYWdpYyBpbnZvbHZlZCBmb3IgdGVzdC1jYXNlXG5kaXNjb3ZlcnkuXG5cbiAgICBcIkFnYWluLCBJIGNhbid0IHByYWlzZSBlbm91Z2ggdGhlIGlkZWEgb2YgYSB0ZXN0aW5nL3NwZWNpbmdcbiAgICAgZnJhbWV3b3JrIHRoYXQgSSBjYW4gYWN0dWFsbHkgcmVhZCBpbiBmdWxsIGluIG9uZSBzaXR0aW5nIVwiXG5cbiAgICAtLSBQaW90ciBTem90a293c2tpXG5cbkNvbXBhcmluZyB0byByc3BlYzpcblxuICAgIHJzcGVjIGlzIGEgdGVzdGluZyBEU0wuIG1pbml0ZXN0IGlzIHJ1YnkuXG5cbiAgICAtLSBBZGFtIEhhd2tpbnMsIFwiQm93IEJlZm9yZSBNaW5pVGVzdFwiXG5cbm1pbml0ZXN0IGRvZXNuJ3QgcmVpbnZlbnQgYW55dGhpbmcgdGhhdCBydWJ5IGFscmVhZHkgcHJvdmlkZXMsIGxpa2U6XG5jbGFzc2VzLCBtb2R1bGVzLCBpbmhlcml0YW5jZSwgbWV0aG9kcy4gVGhpcyBtZWFucyB5b3Ugb25seSBoYXZlIHRvXG5sZWFybiBydWJ5IHRvIHVzZSBtaW5pdGVzdCBhbmQgYWxsIG9mIHlvdXIgcmVndWxhciBPTyBwcmFjdGljZXMgbGlrZVxuZXh0cmFjdC1tZXRob2QgcmVmYWN0b3JpbmdzIHN0aWxsIGFwcGx5LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnlhbmQtcnVieUB6ZW5zcGlkZXIuY29tIi5mcmVlemVdCiAgcy5leGVjdXRhYmxlcyA9IFsibWluaXRlc3QiLmZyZWV6ZV0KICBzLmV4dHJhX3Jkb2NfZmlsZXMgPSBbIkhpc3RvcnkucmRvYyIuZnJlZXplLCAiTWFuaWZlc3QudHh0Ii5mcmVlemUsICJSRUFETUUucmRvYyIuZnJlZXplXQogIHMuZmlsZXMgPSBbIkhpc3RvcnkucmRvYyIuZnJlZXplLCAiTWFuaWZlc3QudHh0Ii5mcmVlemUsICJSRUFETUUucmRvYyIuZnJlZXplLCAiYmluL21pbml0ZXN0Ii5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL21pbml0ZS5zdC8iLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIk1JVCIuZnJlZXplXQogIHMucmRvY19vcHRpb25zID0gWyItLW1haW4iLmZyZWV6ZSwgIlJFQURNRS5yZG9jIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNy4yIi5mcmVlemUKICBzLnN1bW1hcnkgPSAibWluaXRlc3QgcHJvdmlkZXMgYSBjb21wbGV0ZSBzdWl0ZSBvZiB0ZXN0aW5nIGZhY2lsaXRpZXMgc3VwcG9ydGluZyBUREQsIEJERCwgYW5kIGJlbmNobWFya2luZyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxwcmlzbT4uZnJlZXplLCBbIj49IDEuNSIuZnJlZXplXSkKICBzLmFkZF9kZXZlbG9wbWVudF9kZXBlbmRlbmN5KCVxPHJkb2M+LmZyZWV6ZSwgWyI+PSA0LjAiLmZyZWV6ZSwgIjwgNyIuZnJlZXplXSkKICBzLmFkZF9kZXZlbG9wbWVudF9kZXBlbmRlbmN5KCVxPHNpbXBsZWNvdj4uZnJlZXplLCBbIn4+IDAuMjEiLmZyZWV6ZV0pCiAgcy5hZGRfZGV2ZWxvcG1lbnRfZGVwZW5kZW5jeSglcTxob2U+LmZyZWV6ZSwgWyJ+PiA0LjMiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/minitest-6.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1zZ3BhY2sgMS44LjUgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm1zZ3BhY2siLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIxLjguNSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk1lc3NhZ2VQYWNrIHNlcmlhbGl6YXRpb247IHRoZSBDIGV4dGVuc2lvbiBwb3J0ZWQgdG8gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWVzc2FnZVBhY2sgc2VyaWFsaXphdGlvbjsgdGhlIEMgZXh0ZW5zaW9uIHBvcnRlZCB0byBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL21zZ3BhY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9iaWdpbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9idWZmZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9jb3JlX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL2ZhY3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9tc2dwYWNrLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svcGFja2VyLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svc3ltYm9sLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svdGltZS5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL3RpbWVzdGFtcC5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL3VucGFja2VyLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/msgpack-1.8.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG11dGV4X20gMC4zLjAgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm11dGV4X20iLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjMuMCIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImJ1Z190cmFja2VyX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L211dGV4X20vaXNzdWVzIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L211dGV4X20iIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIktlaWp1IElTSElUU1VLQSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI0LTExLTIwIgogIHMuZGVzY3JpcHRpb24gPSAiTWl4aW4gdG8gZXh0ZW5kIG9iamVjdHMgdG8gYmUgaGFuZGxlZCBsaWtlIGEgTXV0ZXguIi5mcmVlemUKICBzLmVtYWlsID0gWyJrZWlqdUBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9tdXRleF9tIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWl4aW4gdG8gZXh0ZW5kIG9iamVjdHMgdG8gYmUgaGFuZGxlZCBsaWtlIGEgTXV0ZXguIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/mutex_m-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1mdHAgMC4zLjkgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1mdHAiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjMuOSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1mdHAiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LWZ0cCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiU2h1Z28gTWFlZGEiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlN1cHBvcnQgZm9yIHRoZSBGaWxlIFRyYW5zZmVyIFByb3RvY29sLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsic2h1Z29AcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LWZ0cCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi42LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTdXBwb3J0IGZvciB0aGUgRmlsZSBUcmFuc2ZlciBQcm90b2NvbC4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8bmV0LXByb3RvY29sPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8dGltZT4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-ftp-0.3.9.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1odHRwIDAuOS4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuZXQtaHR0cCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuOS4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSFRUUCBjbGllbnQgYXBpIGZvciBSdWJ5LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkhUVFAgY2xpZW50IGFwaSBmb3IgUnVieSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvbmV0L2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvbmV0L2h0dHBzLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL2V4Y2VwdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvbmV0L2h0dHAvZ2VuZXJpY19yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL2hlYWRlci5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9wcm94eV9kZWx0YS5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3JlcXVlc3RzLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3Jlc3BvbnNlcy5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9zdGF0dXMucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/net-http-0.9.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1pbWFwIDAuNi40LjEgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1pbWFwIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC42LjQuMSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImNoYW5nZWxvZ191cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcC9yZWxlYXNlcyIsICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiU2h1Z28gTWFlZGEiLmZyZWV6ZSwgIm5pY2hvbGFzIGEuIGV2YW5zIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlJ1YnkgY2xpZW50IGFwaSBmb3IgSW50ZXJuZXQgTWVzc2FnZSBBY2Nlc3MgUHJvdG9jb2wiLmZyZWV6ZQogIHMuZW1haWwgPSBbInNodWdvQHJ1YnktbGFuZy5vcmciLmZyZWV6ZSwgIm5pY2tAcnViaW5pY2suZGV2Ii5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjEzIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiUnVieSBjbGllbnQgYXBpIGZvciBJbnRlcm5ldCBNZXNzYWdlIEFjY2VzcyBQcm90b2NvbCIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxuZXQtcHJvdG9jb2w+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxkYXRlPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-imap-0.6.4.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1wb3AgMC4xLjIgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1wb3AiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjEuMiIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1wb3AiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXBvcCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiWXVraWhpcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMi0wOS0yOCIKICBzLmRlc2NyaXB0aW9uID0gIlJ1YnkgY2xpZW50IGxpYnJhcnkgZm9yIFBPUDMuIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1wb3AiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjQuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJSdWJ5IGNsaWVudCBsaWJyYXJ5IGZvciBQT1AzLiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxuZXQtcHJvdG9jb2w+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-pop-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1wcm90b2NvbCAwLjIuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibmV0LXByb3RvY29sIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgYWJzdHJhY3QgaW50ZXJmYWNlIGZvciBuZXQtKiBjbGllbnQuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhlIGFic3RyYWN0IGludGVyZmFjZSBmb3IgbmV0LSogY2xpZW50Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9uZXQvcHJvdG9jb2wucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/net-protocol-0.2.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1zbXRwIDAuNS4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuZXQtc210cCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNS4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXNtdHAiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXNtdHAiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1a2loaXJvIE1hdHN1bW90byIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTAyLTA1IgogIHMuZGVzY3JpcHRpb24gPSAiU2ltcGxlIE1haWwgVHJhbnNmZXIgUHJvdG9jb2wgY2xpZW50IGxpYnJhcnkgZm9yIFJ1YnkuIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1zbXRwIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjYuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjcuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTaW1wbGUgTWFpbCBUcmFuc2ZlciBQcm90b2NvbCBjbGllbnQgbGlicmFyeSBmb3IgUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8bmV0LXByb3RvY29sPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-smtp-0.5.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5pbzRyIDIuNy41IHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuaW80ciIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuNy41IgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiTklPOjpTZWxlY3RvciwgTW9uaXRvciBhbmQgQnl0ZUJ1ZmZlciwgb24gZXBvbGwsIHBvbGwoMikgb3IgU29ja2V0LlNlbGVjdC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJOSU86OlNlbGVjdG9yLCBNb25pdG9yIGFuZCBCeXRlQnVmZmVyLCBvbiBlcG9sbCwgcG9sbCgyKSBvciBTb2NrZXQuU2VsZWN0Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvbmlvLnJiIi5mcmVlemUsCiAgICAibGliL25pby9ieXRlYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL25pby9tb25pdG9yLnJiIi5mcmVlemUsCiAgICAibGliL25pby9zZWxlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9uaW8vdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9uaW80ci5yYiIuZnJlZXplLAogICAgImxpYi9uaW80cl9leHQucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nio4r-2.7.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5rZiAwLjIuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibmtmIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJOZXR3b3JrIEthbmppIEZpbHRlciwgb24gU3RyaW5nI2VuY29kZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJOZXR3b3JrIEthbmppIEZpbHRlciwgb24gU3RyaW5nI2VuY29kZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL25rZi5yYiIuZnJlZXplLAogICAgImxpYi9rY29udi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nkf-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5va29naXJpIDEuMTguMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibm9rb2dpcmkiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIxLjE4LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJIVE1MNSwgSFRNTDQgYW5kIFhNTCBwYXJzaW5nLCBvbiBBbmdsZVNoYXJwLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkhUTUw1LCBIVE1MNCBhbmQgWE1MIHBhcnNpbmcsIG9uIEFuZ2xlU2hhcnAiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9ub2tvZ2lyaS5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS9jc3MucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkvaHRtbC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS9zZXJpYWxpemVyLnJiIi5mcmVlemUsCiAgICAibGliL25va29naXJpL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkveG1sL2RvY3VtZW50LnJiIi5mcmVlemUsCiAgICAibGliL25va29naXJpL3htbC9kb2N1bWVudF9mcmFnbWVudC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94bWwvbm9kZS5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94bWwvbm9kZV9zZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkveG1sL3NheC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94cGF0aC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nokogiri-1.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9ic2VydmVyIDAuMS4yIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvYnNlcnZlciIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS4yIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb2JzZXJ2ZXIiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb2JzZXJ2ZXIiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1a2loaXJvIE1hdHN1bW90byIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjIwMjMtMTEtMDciCiAgcy5kZXNjcmlwdGlvbiA9ICJJbXBsZW1lbnRhdGlvbiBvZiB0aGUgT2JzZXJ2ZXIgb2JqZWN0LW9yaWVudGVkIGRlc2lnbiBwYXR0ZXJuLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9vYnNlcnZlciIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4wLmRldiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkltcGxlbWVudGF0aW9uIG9mIHRoZSBPYnNlcnZlciBvYmplY3Qtb3JpZW50ZWQgZGVzaWduIHBhdHRlcm4uIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/observer-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9qIDMuMTcuNiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAib2oiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjE3LjYiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJPaidzIDpzdHJpY3QsIDpudWxsLCA6Y29tcGF0IGFuZCA6cmFpbHMgbW9kZXMgYW5kIG1pbWljX0pTT04sIGluIEMjLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIk9qJ3MgOnN0cmljdCwgOm51bGwsIDpjb21wYXQgYW5kIDpyYWlscyBtb2RlcyBhbmQgbWltaWNfSlNPTiwgaW4gQyMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9vai5yYiIuZnJlZXplLAogICAgImxpYi9vai9hY3RpdmVfc3VwcG9ydF9oZWxwZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovYmFnLnJiIi5mcmVlemUsCiAgICAibGliL29qL2Vhc3lfaGFzaC5yYiIuZnJlZXplLAogICAgImxpYi9vai9lcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9vai9qc29uLnJiIi5mcmVlemUsCiAgICAibGliL29qL21pbWljLnJiIi5mcmVlemUsCiAgICAibGliL29qL29qLnJiIi5mcmVlemUsCiAgICAibGliL29qL3Nhai5yYiIuZnJlZXplLAogICAgImxpYi9vai9zY2hhbmRsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovc3RhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/oj-3.17.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW4tdXJpIDAuNS4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcGVuLXVyaSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNS4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQW4gZWFzeS10by11c2Ugd3JhcHBlciBmb3IgTmV0OjpIVFRQIGFuZCBOZXQ6OkZUUC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiBlYXN5LXRvLXVzZSB3cmFwcGVyIGZvciBOZXQ6OkhUVFAgYW5kIE5ldDo6RlRQIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9vcGVuLXVyaS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/open-uri-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW4zIDAuMi4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcGVuMyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUG9wZW4sIGJ1dCB3aXRoIHN0ZGVyciwgdG9vLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlBvcGVuLCBidXQgd2l0aCBzdGRlcnIsIHRvbyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvb3BlbjMucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/open3-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9zdHJ1Y3QgMC42LjMgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm9zdHJ1Y3QiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjYuMyIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImNoYW5nZWxvZ191cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9vc3RydWN0L3JlbGVhc2VzIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJNYXJjLUFuZHJlIExhZm9ydHVuZSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTA3LTE3IgogIHMuZGVzY3JpcHRpb24gPSAiQ2xhc3MgdG8gYnVpbGQgY3VzdG9tIGRhdGEgc3RydWN0dXJlcywgc2ltaWxhciB0byBhIEhhc2guIi5mcmVlemUKICBzLmVtYWlsID0gWyJydWJ5LWNvcmVAbWFyYy1hbmRyZS5jYSIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb3N0cnVjdCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2xhc3MgdG8gYnVpbGQgY3VzdG9tIGRhdGEgc3RydWN0dXJlcywgc2ltaWxhciB0byBhIEhhc2guIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/ostruct-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBvd2VyX2Fzc2VydCAzLjAuMSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicG93ZXJfYXNzZXJ0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4wLjEiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJLYXp1a2kgVHN1amltb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlBvd2VyIEFzc2VydCBzaG93cyBlYWNoIHZhbHVlIG9mIHZhcmlhYmxlcyBhbmQgbWV0aG9kIGNhbGxzIGluIHRoZSBleHByZXNzaW9uLiBJdCBpcyB1c2VmdWwgZm9yIHRlc3RpbmcsIHByb3ZpZGluZyB3aGljaCB2YWx1ZSB3YXNuJ3QgY29ycmVjdCB3aGVuIHRoZSBjb25kaXRpb24gaXMgbm90IHNhdGlzZmllZC4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImthenVraUBjYWxsY2MubmV0Ii5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJSRUFETUUubWQiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJSRUFETUUubWQiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Bvd2VyX2Fzc2VydCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemUsICJSdWJ5Ii5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUG93ZXIgQXNzZXJ0IGZvciBSdWJ5Ii5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/power_assert-3.0.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByaW1lIDAuMS40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmltZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiTWFyYy1BbmRyZSBMYWZvcnR1bmUiLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIyMDI1LTA2LTE4IgogIHMuZGVzY3JpcHRpb24gPSAiUHJpbWUgbnVtYmVycyBhbmQgZmFjdG9yaXphdGlvbiBsaWJyYXJ5LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnVieS1jb3JlQG1hcmMtYW5kcmUuY2EiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3ByaW1lIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjUuMTEiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJQcmltZSBudW1iZXJzIGFuZCBmYWN0b3JpemF0aW9uIGxpYnJhcnkuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHNpbmdsZXRvbj4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPGZvcndhcmRhYmxlPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/prime-0.1.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByaXNtIDIuMC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmlzbSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuMC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVGhlIFByaXNtIFJ1YnkgcGFyc2VyIC0gSXJvblJ1YnkncyBvd24gZnJvbnQgZW5kLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBQcmlzbSBSdWJ5IHBhcnNlciAtIElyb25SdWJ5J3Mgb3duIGZyb250IGVuZCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL3ByaXNtLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2lyb25ydWJ5LnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2Rlc3VnYXJfY29tcGlsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vZGlzcGF0Y2hlci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9kb3RfdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vZmZpLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2luc3BlY3RfdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9sZXhfY29tcGF0LnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL211dGF0aW9uX2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL25vZGUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vbm9kZV9leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vbm9kZV9maW5kLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BhcnNlX3Jlc3VsdC5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wYXJzZV9yZXN1bHQvZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BhcnNlX3Jlc3VsdC9uZXdsaW5lcy5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wYXR0ZXJuLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BvbHlmaWxsL2FwcGVuZF9hc19ieXRlcy5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wb2x5ZmlsbC9ieXRlaW5kZXgucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vcG9seWZpbGwvc2Nhbl9ieXRlLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BvbHlmaWxsL3VucGFjazEucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vcG9seWZpbGwvd2Fybi5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9yZWZsZWN0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3JlbG9jYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vc2VyaWFsaXplLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3N0cmluZ19xdWVyeS5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcGFyc2VyL2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcGFyc2VyL2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3BhcnNlci9sZXhlci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXJfY3VycmVudC5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXJfdmVyc2lvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcmlwcGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9maWx0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcmlwcGVyL2xleGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9zZXhwLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9zaGltLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3J1YnlfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3Zpc2l0b3IucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/prism-2.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBzdG9yZSAwLjIuMSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicHN0b3JlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjEiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9wc3RvcmUiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcHN0b3JlIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJZdWtpaGlybyBNYXRzdW1vdG8iLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiVHJhbnNhY3Rpb25hbCBGaWxlIFN0b3JhZ2UgZm9yIFJ1YnkgT2JqZWN0cyIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9wc3RvcmUiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuOSIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRyYW5zYWN0aW9uYWwgRmlsZSBTdG9yYWdlIGZvciBSdWJ5IE9iamVjdHMiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/pstore-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBzeWNoIDUuMy4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwc3ljaCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjUuMy4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiWUFNTCBwYXJzZXIgYW5kIGVtaXR0ZXIuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiWUFNTCBwYXJzZXIgYW5kIGVtaXR0ZXIiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9wc3ljaC5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9jbGFzc19sb2FkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvY29kZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvY29yZV9leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvZXhjZXB0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2hhbmRsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvaGFuZGxlcnMvZG9jdW1lbnRfc3RyZWFtLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2hhbmRsZXJzL3JlY29yZGVyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2lyb25ydWJ5LnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2pzb24vcnVieV9ldmVudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi9zdHJlYW0ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi90cmVlX2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi95YW1sX2V2ZW50cy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9hbGlhcy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9kb2N1bWVudC5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9tYXBwaW5nLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL25vZGUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvbm9kZXMvc2NhbGFyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL3NlcXVlbmNlLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL3N0cmVhbS5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9vbWFwLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zY2FsYXJfc2Nhbm5lci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvc3RyZWFtLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3N0cmVhbWluZy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zeW50YXhfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdHJlZV9idWlsZGVyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3ZlcnNpb25zLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL2RlcHRoX2ZpcnN0LnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL2VtaXR0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdmlzaXRvcnMvanNvbl90cmVlLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL3RvX3J1YnkucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdmlzaXRvcnMvdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC92aXNpdG9ycy95YW1sX3RyZWUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gveS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/psych-5.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHB1bWEgOC4wLjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInB1bWEiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICI4LjAuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlB1bWEsIHdpdGggaXRzIEhUVFAgcGFyc2VyIGFuZCBUTFMgZW5naW5lIGluIEMjOyBzaW5nbGUgbW9kZSBvbmx5LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlB1bWEsIHdpdGggaXRzIEhUVFAgcGFyc2VyIGFuZCBUTFMgZW5naW5lIGluIEMjOyBzaW5nbGUgbW9kZSBvbmx5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmV4ZWN1dGFibGVzID0gWyJwdW1hIi5mcmVlemUsICJwdW1hY3RsIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvcHVtYS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2FwcC9zdGF0dXMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9iaW5kZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGkucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGllbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGllbnRfZW52LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NsdXN0ZXIvd29ya2VyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlci93b3JrZXJfaGFuZGxlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlcl9hY2NlcHRfbG9vcF9kZWxheS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbW1vbmxvZ2dlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbmZpZ3VyYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jb25zdC5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbnRyb2xfY2xpLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZGV0ZWN0LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZHNsLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZXJyb3JfbG9nZ2VyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZXZlbnRzLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvaW9fYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvanJ1YnlfcmVzdGFydC5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2pzb25fc2VyaWFsaXphdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2xhdW5jaGVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvbGF1bmNoZXIvYnVuZGxlX3BydW5lci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2xvZ193cml0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9taW5pc3NsLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvbWluaXNzbC9jb250ZXh0X2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9udWxsX2lvLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcGx1Z2luLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcGx1Z2luL3N5c3RlbWQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9wbHVnaW4vdG1wX3Jlc3RhcnQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9wdW1hX2h0dHAxMS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3JhY2svYnVpbGRlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3JhY2svdXJsbWFwLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcmFja19kZWZhdWx0LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcmVhY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcnVubmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2Rfbm90aWZ5LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2VydmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2VydmVyX3BsdWdpbl9jb250cm9sLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2luZ2xlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc3RhdGVfZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3RocmVhZF9wb29sLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvdXRpbC5yYiIuZnJlZXplLAogICAgImxpYi9yYWNrL2hhbmRsZXIvcHVtYS5yYiIuZnJlZXplLAogIF0KCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCJuaW80ciIuZnJlZXplLCBbIn4+IDIuMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/puma-8.0.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJhY2MgMS44LjEgcnVieSBsaWIKIyBzdHViOiBleHQvcmFjYy9jcGFyc2UvZXh0Y29uZi5yYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmFjYyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuOC4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JhY2MvcmVsZWFzZXMiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIk1pbmVybyBBb2tpIi5mcmVlemUsICJBYXJvbiBQYXR0ZXJzb24iLmZyZWV6ZV0KICBzLmRhdGUgPSAiMjAyNC0wNy0zMCIKICBzLmRlc2NyaXB0aW9uID0gIlJhY2MgaXMgYW4gTEFMUigxKSBwYXJzZXIgZ2VuZXJhdG9yLlxuICBJdCBpcyB3cml0dGVuIGluIFJ1YnkgaXRzZWxmLCBhbmQgZ2VuZXJhdGVzIFJ1YnkgcHJvZ3JhbS5cblxuICBOT1RFOiBSdWJ5IDEuOC54IGNvbWVzIHdpdGggUmFjYyBydW50aW1lIG1vZHVsZS4gIFlvdVxuICBjYW4gcnVuIHlvdXIgcGFyc2VycyBnZW5lcmF0ZWQgYnkgcmFjYyAxLjQueCBvdXQgb2YgdGhlXG4gIGJveC5cbiIuZnJlZXplCiAgcy5lbWFpbCA9IFtuaWwsICJhYXJvbkB0ZW5kZXJsb3ZlbWFraW5nLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInJhY2MiLmZyZWV6ZV0KICBzLmV4dGVuc2lvbnMgPSBbImV4dC9yYWNjL2NwYXJzZS9leHRjb25mLnJiIi5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJSRUFETUUuamEucmRvYyIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJSRUFETUUuamEucmRvYyIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZSwgImJpbi9yYWNjIi5mcmVlemUsICJleHQvcmFjYy9jcGFyc2UvZXh0Y29uZi5yYiIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFjYyIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmFjYyBpcyBhbiBMQUxSKDEpIHBhcnNlciBnZW5lcmF0b3IiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/racc-1.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJha2UgMTMuMy4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyYWtlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMTMuMy4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiYnVnX3RyYWNrZXJfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFrZS9pc3N1ZXMiLCAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jha2UvcmVsZWFzZXMiLCAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL3J1YnkuZ2l0aHViLmlvL3Jha2UiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFrZSIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSGlyb3NoaSBTSElCQVRBIi5mcmVlemUsICJFcmljIEhvZGVsIi5mcmVlemUsICJKaW0gV2VpcmljaCIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJSYWtlIGlzIGEgTWFrZS1saWtlIHByb2dyYW0gaW1wbGVtZW50ZWQgaW4gUnVieS4gVGFza3MgYW5kIGRlcGVuZGVuY2llcyBhcmVcbnNwZWNpZmllZCBpbiBzdGFuZGFyZCBSdWJ5IHN5bnRheC5cblJha2UgaGFzIHRoZSBmb2xsb3dpbmcgZmVhdHVyZXM6XG4gICogUmFrZWZpbGVzIChyYWtlJ3MgdmVyc2lvbiBvZiBNYWtlZmlsZXMpIGFyZSBjb21wbGV0ZWx5IGRlZmluZWQgaW4gc3RhbmRhcmQgUnVieSBzeW50YXguXG4gICAgTm8gWE1MIGZpbGVzIHRvIGVkaXQuIE5vIHF1aXJreSBNYWtlZmlsZSBzeW50YXggdG8gd29ycnkgYWJvdXQgKGlzIHRoYXQgYSB0YWIgb3IgYSBzcGFjZT8pXG4gICogVXNlcnMgY2FuIHNwZWNpZnkgdGFza3Mgd2l0aCBwcmVyZXF1aXNpdGVzLlxuICAqIFJha2Ugc3VwcG9ydHMgcnVsZSBwYXR0ZXJucyB0byBzeW50aGVzaXplIGltcGxpY2l0IHRhc2tzLlxuICAqIEZsZXhpYmxlIEZpbGVMaXN0cyB0aGF0IGFjdCBsaWtlIGFycmF5cyBidXQga25vdyBhYm91dCBtYW5pcHVsYXRpbmcgZmlsZSBuYW1lcyBhbmQgcGF0aHMuXG4gICogU3VwcG9ydHMgcGFyYWxsZWwgZXhlY3V0aW9uIG9mIHRhc2tzLlxuIi5mcmVlemUKICBzLmVtYWlsID0gWyJoc2J0QHJ1YnktbGFuZy5vcmciLmZyZWV6ZSwgImRyYnJhaW5Ac2VnbWVudDcubmV0Ii5mcmVlemUsICIiLmZyZWV6ZV0KICBzLmV4ZWN1dGFibGVzID0gWyJyYWtlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsiZXhlL3Jha2UiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jha2UiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIk1JVCIuZnJlZXplXQogIHMucmRvY19vcHRpb25zID0gWyItLW1haW4iLmZyZWV6ZSwgIlJFQURNRS5yZG9jIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmFrZSBpcyBhIE1ha2UtbGlrZSBwcm9ncmFtIGltcGxlbWVudGVkIGluIFJ1YnkiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rake-13.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJicyA0LjAuMC5kZXYuNSBydWJ5IGxpYgojIHN0dWI6IGV4dC9yYnNfZXh0ZW5zaW9uL2V4dGNvbmYucmIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInJicyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjQuMC4wLmRldi41Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jicy9ibG9iL21hc3Rlci9DSEFOR0VMT0cubWQiLCAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmJzIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jicy5naXQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIlNvdXRhcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlJCUyBpcyB0aGUgbGFuZ3VhZ2UgZm9yIHR5cGUgc2lnbmF0dXJlcyBmb3IgUnVieSBhbmQgc3RhbmRhcmQgbGlicmFyeSBkZWZpbml0aW9ucy4iLmZyZWV6ZQogIHMuZW1haWwgPSBbIm1hdHN1bW90b0Bzb3V0YXJvLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInJicyIuZnJlZXplXQogIHMuZXh0ZW5zaW9ucyA9IFsiZXh0L3Jic19leHRlbnNpb24vZXh0Y29uZi5yYiIuZnJlZXplXQogIHMuZmlsZXMgPSBbImV4ZS9yYnMiLmZyZWV6ZSwgImV4dC9yYnNfZXh0ZW5zaW9uL2V4dGNvbmYucmIiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JicyIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemUsICJSdWJ5Ii5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiVHlwZSBzaWduYXR1cmUgZm9yIFJ1YnkuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPGxvZ2dlcj4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHByaXNtPi5mcmVlemUsIFsiPj0gMS4zLjAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHRzb3J0Pi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rbs-4.0.0.dev.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlYWRsaW5lIDAuMC40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZWFkbGluZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMC40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiYXljYWJ0YSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDIzLTEyLTE2IgogIHMuZGVzY3JpcHRpb24gPSAiVGhpcyBpcyBqdXN0IGEgbG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIElmIFJ1YnkgaGFzIHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbVxudGhhdCBpcyBhIG5hdGl2ZSBleHRlbnNpb24sIHRoaXMgZ2VtIHdpbGwgbG9hZCBpdC4gSWYgUnVieSBkb2VzIG5vdCBoYXZlXG50aGUgXCJyZWFkbGluZS1leHRcIiBnZW0gdGhpcyBnZW0gd2lsbCBsb2FkIFwicmVsaW5lXCIsIGEgbGlicmFyeSB0aGF0IGlzXG5jb21wYXRpYmxlIHdpdGggdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIGFuZCBpbXBsZW1lbnRlZCBpbiBwdXJlIFJ1YnkuXG4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImF5Y2FidGFAZ21haWwuY29tIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZWFkbGluZSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplXQogIHMucG9zdF9pbnN0YWxsX21lc3NhZ2UgPSAiKy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLStcbnwgVGhpcyBpcyBqdXN0IGEgbG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIElmIFJ1YnkgaGFzIHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbSAgfFxufCB0aGF0IGlzIGEgbmF0aXZlIGV4dGVuc2lvbiwgdGhpcyBnZW0gd2lsbCBsb2FkIGl0LiBJZiBSdWJ5IGRvZXMgbm90IGhhdmUgIHxcbnwgdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIHRoaXMgZ2VtIHdpbGwgbG9hZCBcInJlbGluZVwiLCBhIGxpYnJhcnkgdGhhdCBpcyAgICAgfFxufCBjb21wYXRpYmxlIHdpdGggdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIGFuZCBpbXBsZW1lbnRlZCBpbiBwdXJlIFJ1YnkuICAgICAgfFxufCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHxcbnwgSWYgeW91IGludGVuZCB0byB1c2UgR05VIFJlYWRsaW5lIGJ5IGByZXF1aXJlICdyZWFkbGluZSdgLCBwbGVhc2UgaW5zdGFsbCB8XG58IHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbS4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB8XG4rLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tK1xuIi5mcmVlemUKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiTG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHJlbGluZT4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/readline-0.0.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlbGluZSAwLjYuMyBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmVsaW5lIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC42LjMiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJHTlUgUmVhZGxpbmUgYW5kIEVkaXRsaW5lLCBpbiBwdXJlIFJ1YnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiR05VIFJlYWRsaW5lIGFuZCBFZGl0bGluZSwgaW4gcHVyZSBSdWJ5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvcmVsaW5lLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9jb25maWcucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2ZhY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2hpc3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2lvLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby9hbnNpLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby9kdW1iLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby93aW5kb3dzLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2tleV9hY3Rvci9iYXNlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvY29tcG9zaXRlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvZW1hY3MucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2tleV9hY3Rvci92aV9jb21tYW5kLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvdmlfaW5zZXJ0LnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfc3Ryb2tlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9raWxsX3JpbmcucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2xpbmVfZWRpdG9yLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS91bmljb2RlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS91bmljb2RlL2Vhc3RfYXNpYW5fd2lkdGgucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/reline-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlcGxfdHlwZV9jb21wbGV0b3IgMC4xLjE2IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXBsX3R5cGVfY29tcGxldG9yIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4xLjE2Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXBsX3R5cGVfY29tcGxldG9yIiwgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JlcGxfdHlwZV9jb21wbGV0b3IiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVwbF90eXBlX2NvbXBsZXRvciIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsidG9tcG5nIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlR5cGUgYmFzZWQgY29tcGxldGlvbiBmb3IgUkVQTC4iLmZyZWV6ZQogIHMuZW1haWwgPSBbInRvbW95YXBlbmd1aW5AZ21haWwuY29tIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXBsX3R5cGVfY29tcGxldG9yIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJNSVQiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAzLjAuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuNyIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlR5cGUgYmFzZWQgY29tcGxldGlvbiBmb3IgUkVQTC4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cHJpc20+LmZyZWV6ZSwgWyI+PSAxLjAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHJicz4uZnJlZXplLCBbIj49IDIuNy4wIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/repl_type_completor-0.1.16.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlc29sdiAwLjcuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmVzb2x2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC43LjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaHJlYWQtYXdhcmUgRE5TIHJlc29sdmVyIGxpYnJhcnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhyZWFkLWF3YXJlIEROUyByZXNvbHZlciBsaWJyYXJ5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9yZXNvbHYucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/resolv-0.7.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlc29sdi1yZXBsYWNlIDAuMS4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXNvbHYtcmVwbGFjZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVzb2x2LXJlcGxhY2UiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVzb2x2LXJlcGxhY2UiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIlRhbmFrYSBBa2lyYSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDIyLTEyLTE0IgogIHMuZGVzY3JpcHRpb24gPSAiUmVwbGFjZSBTb2NrZXQgRE5TIHdpdGggUmVzb2x2LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsiYWtyQGZzaWoub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXNvbHYtcmVwbGFjZSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy40LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmVwbGFjZSBTb2NrZXQgRE5TIHdpdGggUmVzb2x2LiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxyZXNvbHY+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/resolv-replace-0.1.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJleG1sIDMuNC40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXhtbCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuNC40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JleG1sL3JlbGVhc2VzL3RhZy92My40LjQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIktvdWhlaSBTdXRvdSIuZnJlZXplXQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiQW4gWE1MIHRvb2xraXQgZm9yIFJ1YnkiLmZyZWV6ZQogIHMuZW1haWwgPSBbImtvdUBjb3ptaXhuZy5vcmciLmZyZWV6ZV0KICBzLmV4dHJhX3Jkb2NfZmlsZXMgPSBbIkxJQ0VOU0UudHh0Ii5mcmVlemUsICJORVdTLm1kIi5mcmVlemUsICJSRUFETUUubWQiLmZyZWV6ZSwgImRvYy9yZXhtbC9jb250ZXh0LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2NoaWxkLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2RvY3VtZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2VsZW1lbnQucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3Jkb2Mvbm9kZS5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9wYXJlbnQucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvY2hpbGRfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL2RvY3VtZW50X3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9lbGVtZW50X3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9tYXN0ZXJfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL25vZGVfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL3BhcmVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3R1dG9yaWFsLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvcmV4bWwvY29udGV4dC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9jaGlsZC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9kb2N1bWVudC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9lbGVtZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL25vZGUucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3Jkb2MvcGFyZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL2NoaWxkX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9kb2N1bWVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvZWxlbWVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvbWFzdGVyX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9ub2RlX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9wYXJlbnRfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90dXRvcmlhbC5yZG9jIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXhtbCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiBYTUwgdG9vbGtpdCBmb3IgUnVieSIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rexml-3.4.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJpbmRhIDAuMi4wIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyaW5kYSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIk1hc2F0b3NoaSBTRUtJIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMy0xMS0wNyIKICBzLmRlc2NyaXB0aW9uID0gIlRoZSBMaW5kYSBkaXN0cmlidXRlZCBjb21wdXRpbmcgcGFyYWRpZ20gaW4gUnVieS4iLmZyZWV6ZQogIHMuZW1haWwgPSBbInNla2lAcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuMy4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4wLmRldiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBMaW5kYSBkaXN0cmlidXRlZCBjb21wdXRpbmcgcGFyYWRpZ20gaW4gUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8ZHJiPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8aXBhZGRyPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8Zm9yd2FyZGFibGU+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rinda-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJzcyAwLjMuMiBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicnNzIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjIiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJLb3VoZWkgU3V0b3UiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIkZhbWlseSBvZiBsaWJyYXJpZXMgdGhhdCBzdXBwb3J0IHZhcmlvdXMgZm9ybWF0cyBvZiBYTUwgXCJmZWVkc1wiLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsia291QGNvem1peG5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcnNzIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjIiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJGYW1pbHkgb2YgbGlicmFyaWVzIHRoYXQgc3VwcG9ydCB2YXJpb3VzIGZvcm1hdHMgb2YgWE1MIFwiZmVlZHNcIi4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cmV4bWw+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rss-0.3.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJ1YnkyX2tleXdvcmRzIDAuMC41IHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJydWJ5Ml9rZXl3b3JkcyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMC41IgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiU2hpbSBsaWJyYXJ5IGZvciBNb2R1bGUjcnVieTJfa2V5d29yZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiU2hpbSBsaWJyYXJ5IGZvciBNb2R1bGUjcnVieTJfa2V5d29yZHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3J1YnkyX2tleXdvcmRzLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ruby2_keywords-0.0.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNlY3VyZXJhbmRvbSAwLjQuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic2VjdXJlcmFuZG9tIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC40LjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJJbnRlcmZhY2UgZm9yIHNlY3VyZSByYW5kb20gbnVtYmVyIGdlbmVyYXRvci4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJbnRlcmZhY2UgZm9yIHNlY3VyZSByYW5kb20gbnVtYmVyIGdlbmVyYXRvciIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2VjdXJlcmFuZG9tLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/securerandom-0.4.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNoZWxsd29yZHMgMC4yLjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInNoZWxsd29yZHMiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk1hbmlwdWxhdGVzIHN0cmluZ3Mgd2l0aCB3b3JkIHBhcnNpbmcgcnVsZXMgb2YgVU5JWCBCb3VybmUgc2hlbGwuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWFuaXB1bGF0ZXMgc3RyaW5ncyB3aXRoIHdvcmQgcGFyc2luZyBydWxlcyBvZiBVTklYIEJvdXJuZSBzaGVsbCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2hlbGx3b3Jkcy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/shellwords-0.2.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNpbmdsZXRvbiAwLjMuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic2luZ2xldG9uIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgU2luZ2xldG9uIG1vZHVsZSBpbXBsZW1lbnRzIHRoZSBTaW5nbGV0b24gcGF0dGVybi4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJUaGUgU2luZ2xldG9uIG1vZHVsZSBpbXBsZW1lbnRzIHRoZSBTaW5nbGV0b24gcGF0dGVybiIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2luZ2xldG9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/singleton-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNxbGl0ZTMgMi45LjYgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInNxbGl0ZTMiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIyLjkuNiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlNRTGl0ZTMsIG9uIHRoZSBuYXRpdmUgbGlicmFyeSBNaWNyb3NvZnQuRGF0YS5TcWxpdGUgY2Fycmllcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTUUxpdGUzLCBvbiB0aGUgbmF0aXZlIGxpYnJhcnkgTWljcm9zb2Z0LkRhdGEuU3FsaXRlIGNhcnJpZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zcWxpdGUzLnJiIi5mcmVlemUsCiAgICAibGliL3NxbGl0ZTMvY29uc3RhbnRzLnJiIi5mcmVlemUsCiAgICAibGliL3NxbGl0ZTMvZGF0YWJhc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9lcnJvcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9mb3JrX3NhZmV0eS5yYiIuZnJlZXplLAogICAgImxpYi9zcWxpdGUzL3ByYWdtYXMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9yZXN1bHRzZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9zdGF0ZW1lbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy92YWx1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zcWxpdGUzL3ZlcnNpb25faW5mby5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/sqlite3-2.9.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN5bnRheF9zdWdnZXN0IDIuMC4zIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJzeW50YXhfc3VnZ2VzdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuMC4zIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiRmluZCBzeW50YXggZXJyb3JzIGluIHlvdXIgc291cmNlIGluIGEgc25hcC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJGaW5kIHN5bnRheCBlcnJvcnMgaW4geW91ciBzb3VyY2UgaW4gYSBzbmFwIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9zeW50YXhfc3VnZ2VzdC5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9hcGkucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvYXJvdW5kX2Jsb2NrX3NjYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvYmxvY2tfZXhwYW5kLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NhcHR1cmUvYmVmb3JlX2FmdGVyX2tleXdvcmRfZW5kcy5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9jYXB0dXJlL2ZhbGxpbmdfaW5kZW50X2xpbmVzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NhcHR1cmVfY29kZV9jb250ZXh0LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NsZWFuX2RvY3VtZW50LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NsaS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9jb2RlX2Jsb2NrLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvZGVfZnJvbnRpZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvY29kZV9saW5lLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvZGVfc2VhcmNoLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvcmVfZXh0LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2Rpc3BsYXlfY29kZV93aXRoX2xpbmVfbnVtYmVycy5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9kaXNwbGF5X2ludmFsaWRfYmxvY2tzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2V4cGxhaW5fc3ludGF4LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2xlZnRfcmlnaHRfbGV4X2NvdW50LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2xleF9hbGwucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvbGV4X3ZhbHVlLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L21pbmlfc3RyaW5naW8ucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvcGFyc2VfYmxvY2tzX2Zyb21faW5kZW50X2xpbmUucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvcGF0aG5hbWVfZnJvbV9tZXNzYWdlLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L3ByaW9yaXR5X2VuZ3VsZl9xdWV1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9wcmlvcml0eV9xdWV1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9yaXBwZXJfZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L3NjYW5faGlzdG9yeS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC91bnZpc2l0ZWRfbGluZXMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/syntax_suggest-2.0.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN5c2xvZyAwLjMuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic3lzbG9nIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJTeXNsb2csIGltcGxlbWVudGVkIGluIFNyYy9MaWJyYXJpZXMvU3lzbG9nLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlN5c2xvZywgaW1wbGVtZW50ZWQgaW4gU3JjL0xpYnJhcmllcy9TeXNsb2ciLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zeXNsb2cucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/syslog-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRlc3QtdW5pdCAzLjcuNSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidGVzdC11bml0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy43LjUiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJidWdfdHJhY2tlcl91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vdGVzdC11bml0L3Rlc3QtdW5pdC9pc3N1ZXMiLCAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL3Rlc3QtdW5pdC5naXRodWIuaW8vdGVzdC11bml0L2VuLyIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vdGVzdC11bml0L3Rlc3QtdW5pdCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiS291aGVpIFN1dG91Ii5mcmVlemUsICJIYXJ1a2EgWW9zaGloYXJhIi5mcmVlemVdCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJ0ZXN0LXVuaXQgKFRlc3Q6OlVuaXQpIGlzIHVuaXQgdGVzdGluZyBmcmFtZXdvcmsgZm9yIFJ1YnksIGJhc2VkIG9uIHhVbml0XG5wcmluY2lwbGVzLiBUaGVzZSB3ZXJlIG9yaWdpbmFsbHkgZGVzaWduZWQgYnkgS2VudCBCZWNrLCBjcmVhdG9yIG9mIGV4dHJlbWVcbnByb2dyYW1taW5nIHNvZnR3YXJlIGRldmVsb3BtZW50IG1ldGhvZG9sb2d5LCBmb3IgU21hbGx0YWxrJ3MgU1VuaXQuIEl0IGFsbG93c1xud3JpdGluZyB0ZXN0cywgY2hlY2tpbmcgcmVzdWx0cyBhbmQgYXV0b21hdGVkIHRlc3RpbmcgaW4gUnVieS4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImtvdUBjb3ptaXhuZy5vcmciLmZyZWV6ZSwgInlvc2hpaGFyYUBjbGVhci1jb2RlLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInRlc3QtdW5pdCIuZnJlZXplXQogIHMuZmlsZXMgPSBbImJpbi90ZXN0LXVuaXQiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vdGVzdC11bml0LmdpdGh1Yi5pby8iLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTREwiLmZyZWV6ZSwgIlBTRkwiLmZyZWV6ZV0KICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiB4VW5pdCBmYW1pbHkgdW5pdCB0ZXN0aW5nIGZyYW1ld29yayBmb3IgUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cG93ZXJfYXNzZXJ0Pi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/test-unit-3.7.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRpbWVvdXQgMC42LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInRpbWVvdXQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjYuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkF1dG8tdGVybWluYXRlIHBvdGVudGlhbGx5IGxvbmctcnVubmluZyBvcGVyYXRpb25zLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkF1dG8tdGVybWluYXRlIHBvdGVudGlhbGx5IGxvbmctcnVubmluZyBvcGVyYXRpb25zIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi90aW1lb3V0LnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/timeout-0.6.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRzb3J0IDAuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ0c29ydCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVG9wb2xvZ2ljYWwgc29ydGluZyB1c2luZyBUYXJqYW4ncyBhbGdvcml0aG0uICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVG9wb2xvZ2ljYWwgc29ydGluZyB1c2luZyBUYXJqYW4ncyBhbGdvcml0aG0iLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3Rzb3J0LnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tsort-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHVuIDAuMy4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ1biIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVXRpbGl0aWVzIHRvIHJlcGxhY2UgY29tbW9uIFVOSVggY29tbWFuZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVXRpbGl0aWVzIHRvIHJlcGxhY2UgY29tbW9uIFVOSVggY29tbWFuZHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3VuLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/un-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHVyaSAxLjEuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidXJpIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4xLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJVUkkgaXMgYSBtb2R1bGUgcHJvdmlkaW5nIGNsYXNzZXMgdG8gaGFuZGxlIFVuaWZvcm0gUmVzb3VyY2UgSWRlbnRpZmllcnMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVVJJIGlzIGEgbW9kdWxlIHByb3ZpZGluZyBjbGFzc2VzIHRvIGhhbmRsZSBVbmlmb3JtIFJlc291cmNlIElkZW50aWZpZXJzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL2NvbW1vbi5yYiIuZnJlZXplLAogICAgImxpYi91cmkvZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi91cmkvZnRwLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9nZW5lcmljLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9odHRwLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9odHRwcy5yYiIuZnJlZXplLAogICAgImxpYi91cmkvbGRhcC5yYiIuZnJlZXplLAogICAgImxpYi91cmkvbGRhcHMucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL21haWx0by5yYiIuZnJlZXplLAogICAgImxpYi91cmkvcmZjMjM5Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL3JmYzM5ODZfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS93cy5yYiIuZnJlZXplLAogICAgImxpYi91cmkvd3NzLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/uri-1.1.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYWtyZWYgMC4xLjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYWtyZWYiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjEuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi93ZWFrcmVmLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/weakref-0.1.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYnNvY2tldC1kcml2ZXIgMC44LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYnNvY2tldC1kcml2ZXIiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIldlYlNvY2tldCBwcm90b2NvbCBoYW5kbGVyOyBXZWJTb2NrZXQ6Ok1hc2sgaW4gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiV2ViU29ja2V0IHByb3RvY29sIGhhbmRsZXI7IFdlYlNvY2tldDo6TWFzayBpbiBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL3dlYnNvY2tldF9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9jbGllbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9kcmFmdDc1LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvZHJhZnQ3Ni5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2V2ZW50X2VtaXR0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oZWFkZXJzLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvaHliaS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2h5YmkvZnJhbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oeWJpL21lc3NhZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9wcm94eS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3NlcnZlci5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3N0cmVhbV9yZWFkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAvaGVhZGVycy5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvaHR0cC9yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9odHRwL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC93ZWJzb2NrZXRfbWFzay5yYiIuZnJlZXplLAogIF0KCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCJ3ZWJzb2NrZXQtZXh0ZW5zaW9ucyIuZnJlZXplLCBbIj49IDAuMS4wIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/websocket-driver-0.8.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHlhbWwgMC40LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInlhbWwiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi95YW1sLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvZGJtLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvc3RvcmUucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/yaml-0.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID0oY29uZmlnKCkpCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lOjpDb3JlI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYXV0b2NvbXBsZXRpb24nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YXV0b2NvbXBsZXRpb24sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgKGNvbmZpZygpKQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIpCiAgXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2NvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlcicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXI9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9hcHBlbmRfY2hhcmFjdGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMpCiAgXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2Jhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnM9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6YmFzaWNfd29yZF9icmVha19jaGFyYWN0ZXJzPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uY29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycykKICBfLmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYmFzaWNfcXVvdGVfY2hhcmFjdGVycykKICBfLmJhc2ljX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNiYXNpY19xdW90ZV9jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJhc2ljX3F1b3RlX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmJhc2ljX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzKQogIF8uY29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycykKICBfLmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uc3BlY2lhbF9wcmVmaXhlcykKICBfLnNwZWNpYWxfcHJlZml4ZXMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3NwZWNpYWxfcHJlZml4ZXMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNzcGVjaWFsX3ByZWZpeGVzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnNwZWNpYWxfcHJlZml4ZXMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOnNwZWNpYWxfcHJlZml4ZXM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX3Byb2MpCiAgXy5jb21wbGV0aW9uX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcHJvYyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2NvbXBsZXRpb25fcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2M9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9wcm9jPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLm91dHB1dF9tb2RpZmllcl9wcm9jKQogIF8ub3V0cHV0X21vZGlmaWVyX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI291dHB1dF9tb2RpZmllcl9wcm9jIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9Iicjb3V0cHV0X21vZGlmaWVyX3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6b3V0cHV0X21vZGlmaWVyX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpvdXRwdXRfbW9kaWZpZXJfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByb21wdF9wcm9jKQogIF8ucHJvbXB0X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3Byb21wdF9wcm9jIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcHJvbXB0X3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cHJvbXB0X3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcm9tcHRfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYXV0b19pbmRlbnRfcHJvYykKICBfLmF1dG9faW5kZW50X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9faW5kZW50X3Byb2MgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvX2luZGVudF9wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmF1dG9faW5kZW50X3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmF1dG9faW5kZW50X3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vayguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByZV9pbnB1dF9ob29rKQogIF8ucHJlX2lucHV0X2hvb2soLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ByZV9pbnB1dF9ob29rIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcHJlX2lucHV0X2hvb2snLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cHJlX2lucHV0X2hvb2ssIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vaz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcmVfaW5wdXRfaG9vaz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYykKICBfLmRpZ19wZXJmZWN0X21hdGNoX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNkaWdfcGVyZmVjdF9tYXRjaF9wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmRpZ19wZXJmZWN0X21hdGNoX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmRpZ19wZXJmZWN0X21hdGNoX3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBpbnB1dD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDppbnB1dD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXQ9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6b3V0cHV0PSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy52aV9lZGl0aW5nX21vZGUpCiAgXy52aV9lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3ZpX2VkaXRpbmdfbW9kZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDp2aV9lZGl0aW5nX21vZGUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5lbWFjc19lZGl0aW5nX21vZGUpCiAgXy5lbWFjc19lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2VtYWNzX2VkaXRpbmdfbW9kZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDplbWFjc19lZGl0aW5nX21vZGUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZG11bHRpbGluZSkKICBfLnJlYWRtdWx0aWxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRtdWx0aWxpbmUgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNyZWFkbXVsdGlsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnJlYWRtdWx0aWxpbmUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnJlYWRsaW5lKQogIF8ucmVhZGxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRsaW5lIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVhZGxpbmUnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVhZGxpbmUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fY2FzZV9mb2xkKQogIF8uY29tcGxldGlvbl9jYXNlX2ZvbGQoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fY2FzZV9mb2xkIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9jYXNlX2ZvbGQnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGlvbl9jYXNlX2ZvbGQsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0aW9uX2Nhc2VfZm9sZD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyKQogIF8uY29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXInLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1SZWxpbmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZGxpbmUpCiAgXy5yZWFkbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZGxpbmUgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoxNTkgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNyZWFkbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBnZXRfc2NyZWVuX3NpemUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5nZXRfc2NyZWVuX3NpemUpCiAgXy5nZXRfc2NyZWVuX3NpemUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2dldF9zY3JlZW5fc2l6ZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2dldF9zY3JlZW5fc2l6ZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpnZXRfc2NyZWVuX3NpemUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPWxpbmVfZWRpdG9yCiAgICBpZiBkZWZpbmVkPyhfLmVvZj8pCiAgXy5lb2Y/KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNlb2Y/IGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW9mPycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDplb2Y/LCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5lb2Y/KQogIF8uZW9mPyguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjZW9mPyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjE1OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2VvZj8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZW9mPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBkZWxldGVfdGV4dCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5kZWxldGVfdGV4dCkKICBfLmRlbGV0ZV90ZXh0KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNkZWxldGVfdGV4dCBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2RlbGV0ZV90ZXh0JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmRlbGV0ZV90ZXh0LCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBsaW5lX2J1ZmZlciguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5saW5lKQogIF8ubGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjbGluZV9idWZmZXIgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDY4IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBwb2ludCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5ieXRlX3BvaW50ZXIpCiAgXy5ieXRlX3BvaW50ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3BvaW50IGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvcmVsaW5lLnJiOjQ2OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2J5dGVfcG9pbnRlcicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpieXRlX3BvaW50ZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBwb2ludD0oLi4uKQogICAgbGluZV9lZGl0b3IKICAgIC5fX3NlbmRfXyg6Ynl0ZV9wb2ludGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiByZWRpc3BsYXkoLi4uKQogICAgXyA9bGluZV9lZGl0b3IKICAgIGlmIGRlZmluZWQ/KF8ucmVyZW5kZXIpCiAgXy5yZXJlbmRlciguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVkaXNwbGF5IGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvcmVsaW5lLnJiOjQ3OCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlcmVuZGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnJlcmVuZGVyLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8udmlfZWRpdGluZ19tb2RlPykKICBfLnZpX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyN2aV9lZGl0aW5nX21vZGU/JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnZpX2VkaXRpbmdfbW9kZT8sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZW1hY3NfZWRpdGluZ19tb2RlPykKICBfLmVtYWNzX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNlbWFjc19lZGl0aW5nX21vZGU/JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVtYWNzX2VkaXRpbmdfbW9kZT8sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBhbWJpZ3VvdXNfd2lkdGgoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hbWJpZ3VvdXNfd2lkdGgpCiAgXy5hbWJpZ3VvdXNfd2lkdGgoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FtYmlndW91c193aWR0aCBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2FtYmlndW91c193aWR0aCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphbWJpZ3VvdXNfd2lkdGgsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmxhc3RfaW5jcmVtZW50YWxfc2VhcmNoKQogIF8ubGFzdF9pbmNyZW1lbnRhbF9zZWFyY2goLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2xhc3RfaW5jcmVtZW50YWxfc2VhcmNoIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjbGFzdF9pbmNyZW1lbnRhbF9zZWFyY2gnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6bGFzdF9pbmNyZW1lbnRhbF9zZWFyY2gsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBhZGRfZGlhbG9nX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hZGRfZGlhbG9nX3Byb2MpCiAgXy5hZGRfZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FkZF9kaWFsb2dfcHJvYyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2FkZF9kaWFsb2dfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphZGRfZGlhbG9nX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBkaWFsb2dfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmRpYWxvZ19wcm9jKQogIF8uZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpYWxvZ19wcm9jIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZGlhbG9nX3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGlhbG9nX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYXV0b2NvbXBsZXRpb24nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YXV0b2NvbXBsZXRpb24sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5yZWFkbXVsdGlsaW5lKQogIF8ucmVhZG11bHRpbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZG11bHRpbGluZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjE1OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRtdWx0aWxpbmUnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVhZG11bHRpbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} +{"code":"c2VsZg==","encoding":"UTF-8","path":"(eval at ${ROOT}/Src/StdLib/ruby/4.0/irb/workspace.rb:71)","line":1,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":[],"moduleNames":[]} diff --git a/Util/aot/startup-files.rb b/Util/aot/startup-files.rb index aa3e3f05e..822a1d6c4 100644 --- a/Util/aot/startup-files.rb +++ b/Util/aot/startup-files.rb @@ -10,11 +10,16 @@ # `IronRuby.Aot unsupported`, AotCompiler.UnsupportedFinder; it needs the compiler built, as build-startup.sh does). A file # is listed under the first command that loads it. The commands run with this tree's ir.sh, or IR_TREE's (IR_CONFIG as # set, else what ir.sh picks: the R2R host and the Release build load the same files). +# +# It also writes startup-evals.txt: the same commands run again with IR_EVAL_RECORD, which records every plain string eval +# compiled without a warning (the source text and everything EvalCodeCache keys on), and the library compiles each one for +# the first eval of exactly that text in exactly that context (PrecompiledCode.TryClaimEval). --check compares them too. require "open3" ROOT = File.expand_path("../..", __dir__) IR_SH = File.join(ENV["IR_TREE"] || ROOT, "ir.sh") LIST = File.join(__dir__, "startup-files.txt") +EVALS = File.join(__dir__, "startup-evals.txt") STDLIB = File.join(ROOT, "Src/StdLib/") # [title, ir arguments, stdin]. TERM is set (xterm), so irb's reline loads its ANSI terminal code, as at a terminal. @@ -55,6 +60,28 @@ def loaded_files(args, stdin) files.filter_map { |f| f.delete_prefix(stdlib) if f.start_with?(stdlib) } end +# The string evals the commands run, recorded by the runtime (IR_EVAL_RECORD: PrecompiledCode.RecordEval), with the tree's +# root as ${ROOT}: the library compiles each for the first eval of exactly that text in exactly that context. A second pass +# after the files', so that RubyGems' caches are written and only what a usual run evaluates is recorded. +require "json" +require "tmpdir" +def recorded_evals(args, stdin) + tree = File.dirname(IR_SH) + Dir.mktmpdir do |dir| + record = File.join(dir, "evals") + env = { "IR_STARTUP_DLL" => "none", "IR_EVAL_RECORD" => record, "TERM" => "xterm" } + cmd = [IR_SH, *args] + _, out, status = Open3.capture3(env, *cmd, stdin_data: stdin || "") + abort "startup-files.rb: #{cmd.join(" ")} failed:\n#{out}" unless status.success? + next [] unless File.exist?(record) + File.readlines(record, chomp: true).map do |l| + e = JSON.parse(l) + e["path"] = e["path"].gsub(tree + "/", "${ROOT}/") + JSON.generate(e) + end + end +end + sections = [] seen = {} COMMANDS.each do |title, args, stdin| @@ -62,6 +89,9 @@ def loaded_files(args, stdin) files.each { |f| seen[f] = true } sections << [title, files] end +evals = [] +COMMANDS.each { |_, args, stdin| evals.concat(recorded_evals(args, stdin)) } +evals.uniq! LEFT_OUT = unsupported(seen.keys) LEFT_OUT.each_key { |f| seen.delete(f) } sections.each { |_, files| files.reject! { |f| LEFT_OUT.key?(f) } } @@ -73,8 +103,12 @@ def loaded_files(args, stdin) extra = listed - seen.keys extra.each { |f| puts "startup-files.txt lists #{f}, which none of the commands loads" } missing.each { |f| puts "startup-files.txt lacks #{f}, which the commands load" } - if missing.empty? && extra.empty? - puts "ok: startup-files.txt lists the #{listed.size} files the commands load" + listed_evals = File.exist?(EVALS) ? File.readlines(EVALS, chomp: true).reject { |l| l.empty? || l.start_with?("#") } : [] + describe = ->(l) { e = JSON.parse(l); "#{e["path"]}:#{e["line"]} (#{e["code"].unpack1("m").bytesize} bytes)" } + (listed_evals - evals).each { |l| puts "startup-evals.txt has an eval none of the commands runs: #{describe[l]}" } + (evals - listed_evals).each { |l| puts "startup-evals.txt lacks an eval the commands run: #{describe[l]}" } + if missing.empty? && extra.empty? && listed_evals.sort == evals.sort + puts "ok: startup-files.txt lists the #{listed.size} files the commands load, startup-evals.txt their #{evals.size} evals" exit 0 end puts "rewrite it with: ruby Util/aot/startup-files.rb" @@ -92,3 +126,10 @@ def loaded_files(args, stdin) end end puts "wrote #{LIST}: #{seen.size} files" +File.open(EVALS, "w") do |io| + io.puts "# Written by startup-files.rb with startup-files.txt: the string evals those commands run, one JSON object a line" + io.puts "# (PrecompiledCode.RecordEval), compiled into IronRuby.Startup.dll for the first eval of exactly that text in exactly" + io.puts "# that context. ${ROOT} is the IronRuby tree." + evals.each { |l| io.puts l } +end +puts "wrote #{EVALS}: #{evals.size} evals" From e19f45415f681cb2951d2b7ea30449280eb9622b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:26:14 +0000 Subject: [PATCH 226/439] Method JIT: take begin/rescue/else/ensure whose protected part cannot raise The method JIT refused every method with a rescue, else or ensure clause (the screen's `Body`): 555 methods' first refusal, and the begin in zjit-post-shapes' resc and ens, which ran at about twice CRuby's time. A typed body does not raise from a frame it does not have: anything that would raise in the generic body deopts, and the generic body runs the call again. So where the protected part's typed code can raise nothing but a deopt - no call it does not inline, no loop or safe point, fallback, construction or try, checked on the emitted tree (RaiseFreeChecker) - the rescue clauses can never run in the typed body. It emits the statements, then else, then ensure: the order of a run that raises nothing, which leaves $! alone. With an ensure, the else clause must be raise-free too and no jump may leave the begin (the screen refuses that as well); a deopt passes the ensure by, and the generic body runs it once. IR_JIT_RESCUE=0 turns it off. The analyses of the body's last statement (held-back writes, the last store, the resume path) now read MethodStatements, null for a method-level rescue, else or ensure: they took the protected part's last statement for the method's value, and a method-level else's value was lost. Clock, zjit-post-shapes: rescue 53.9 -> 36.7 ns, ensure 65.6 -> 50.1 (CRuby 27.9 and 32.3). Census: 61 methods up, none down. The new section 23 of Util/jit-rescue-matrix.rb and the errinfo, rescue-light, raise, jit and light-entry matrices print what CRuby or the base does in every JIT mode; ruby/spec rescue, ensure, retry, core/exception and library/timeout and IronRuby.Tests pass (JitCensus1 updated for the verdict this changes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/IronRuby.Tests/Runtime/LoopTests.cs | 12 +- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 7 +- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 7 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 174 +++++++++++++++++++- Util/jit-rescue-matrix.rb | 165 +++++++++++++++++++ Util/perf/LEDGER.md | 44 +++++ 6 files changed, 397 insertions(+), 12 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/LoopTests.cs b/Src/IronRuby.Tests/Runtime/LoopTests.cs index 9dac20ca2..0d3def802 100644 --- a/Src/IronRuby.Tests/Runtime/LoopTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoopTests.cs @@ -864,6 +864,13 @@ rescue StandardError end def dist(o) = @x - o.x def self.zero = 0 + def jump(x) + begin + return x if x + ensure + @y = 1 + end + end end def top = puts(1) "); @@ -878,10 +885,11 @@ p IronRuby.jit_census(['/no/such/census.rb']).map { |m| m.key?(:error) } [""Point#add"", 4, true, nil, ""compiles"", nil, nil, ""Int""] [""Point#each"", 5, true, nil, ""never"", ""parameters"", ""uses its block"", nil] [""Point#log"", 6, true, nil, ""never"", ""parameters"", ""rest parameter"", nil] -[""Point#safe"", 7, true, nil, ""never"", ""screen"", ""Body"", nil] +[""Point#safe"", 7, true, nil, ""maybe"", ""emit"", ""call: fetch/0"", nil] [""Point#dist"", 12, true, nil, ""maybe"", ""emit"", ""call: x/0"", nil] [""Point.zero"", 13, true, nil, ""compiles"", nil, nil, """"] -[""Object#top"", 15, true, nil, ""never"", ""screen"", ""MethodCall puts (self)"", nil] +[""Point#jump"", 14, true, nil, ""never"", ""screen"", ""Body"", nil] +[""Object#top"", 22, true, nil, ""never"", ""screen"", ""MethodCall puts (self)"", nil] nil [true] "); diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 624fe9baa..825088d85 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1427,7 +1427,7 @@ private bool IsLibraryHashFetch() { private bool IsEarlyTopStatement(RExpr/*!*/ node) { if (_loop != null || _ast == null || _noUnloggedWrites || _noUnloggedEarlyWrites || !_refinements.IsEmpty) { return false; } - var statements = _ast.Body.Statements; + var statements = MethodStatements; if (statements == null || statements.Count == 0 || statements.Last == node) { return false; } var receiver = LastStoreReceiver(); if (receiver == null) { return false; } @@ -1443,7 +1443,8 @@ private bool IsEarlyTopStatement(RExpr/*!*/ node) { // The receiver of the store the body ends with - `@v[j] = x' or `a[j] = x', a an untyped local - or null. private RExpr LastStoreReceiver() { - var assign = _ast.Body.Statements.Last as SimpleAssignmentExpression; + var statements = MethodStatements; + var assign = (statements != null && statements.Count > 0) ? statements.Last as SimpleAssignmentExpression : null; var element = (assign != null && assign.Operation == null) ? assign.Left as ArrayItemAccess : null; if (element == null || element.Block != null || element.Arguments.Expressions.Length != 1 || element.Arguments.Expressions[0] is SplattedArgument) { @@ -1486,7 +1487,7 @@ private static bool IsPureForLastStore(RExpr node, RExpr/*!*/ receiver) { private bool IsLastStatement(RExpr/*!*/ node) { if (_loop != null || _ast == null || _noUnloggedWrites) { return false; } - var statements = _ast.Body.Statements; + var statements = MethodStatements; return statements != null && statements.Count > 0 && statements.Last == node; } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index b806de9fa..a39582636 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -85,8 +85,9 @@ private SunkIVar FindSunk(string/*!*/ name) { } private bool IsTopStatement(RExpr/*!*/ node) { - if (_ast == null || _ast.Body.Statements == null) { return false; } - foreach (var s in _ast.Body.Statements) { if (s == node) { return true; } } + var statements = MethodStatements; + if (statements == null) { return false; } + foreach (var s in statements) { if (s == node) { return true; } } return false; } @@ -183,7 +184,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { // the last statement's held-back write, whose value is the body's SunkIVar last = null; - var statements = _ast.Body.Statements; + var statements = MethodStatements; var lastWrite = (statements != null && statements.Count > 0) ? statements.Last as SimpleAssignmentExpression : null; var lastTarget = (lastWrite != null) ? lastWrite.Left as InstanceVariable : null; if (lastTarget != null) { diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index b82e9d5b8..b701d8710 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -860,7 +860,15 @@ private static Type DelegateType(JT[]/*!*/ ps, JT ret) { private MSA.Expression/*!*/ EmitBody(out JT type) { var body = _ast.Body; if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { - throw JitBailout.Instance; + // `def m ... rescue ... ensure ... end' (EmitExceptionBody); keyword defaults are statements of the body + if (_keywords != null) { throw Bail("rescue or ensure in a method with keywords"); } + var defaultsFirst = EmitOmittedDefaults(); + var handled = FinishSunkStores(EmitExceptionBody(body, out type), ref type); + if (defaultsFirst != null) { + defaultsFirst.Add(handled); + handled = Ast.Block(ClrType(type), defaultsFirst); + } + return handled; } if (_keywords != null) { // the keyword prologue is what the entry did; the parameters hold its result @@ -1043,6 +1051,162 @@ private bool IsInitialIVarValue(RExpr/*!*/ value) { (Array.IndexOf(_paramNames, local.Name) >= 0 || IsOmittedOptional(local.Name)); } + /// + /// The method's statements, the last of which makes its value: what the analyses of "the body's last statement" and "a + /// statement of the body itself" look at (held-back writes, the last store). Null when the method body has rescue, else + /// or ensure clauses (EmitExceptionBody): an else or ensure clause comes after the last statement, and the clauses may + /// make the value. + /// + private Statements MethodStatements { + get { + if (_ast == null) { return null; } + var body = _ast.Body; + return (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) ? null : body.Statements; + } + } + + // IR_JIT_RESCUE=0 turns EmitExceptionBody off + internal static readonly bool RescueBodies = Environment.GetEnvironmentVariable("IR_JIT_RESCUE") != "0"; + + /// + /// `begin ... rescue ... else ... ensure ... end' whose protected part the typed body runs without raising: its code + /// calls only helpers that throw nothing but a deopt (RaiseFreeChecker), and has no call, loop or fallback, so no + /// safe point either, where a Thread#raise or a Timeout could land. Nothing it does can then be rescued: an exception + /// it would raise in the generic body - an overflow into a Bignum, a `raise', a nil receiver - is a deopt here, and + /// the generic body runs the call again from the top, rescue clauses and all, as for any deopt (allowed only before + /// anything observable, _deoptAfterEffect). So the rescue clauses are not emitted, the else clause follows the + /// statements, and the ensure clause follows them both: the order of a run in which nothing is raised. That run leaves + /// $! as it found it (Body.LazyErrinfo; with it off the generic body stores back the value it read) and has no frame + /// whose InRescue matters. With an ensure clause, the else clause must raise nothing either (the ensure runs after + /// what it raises), and no return, break, next, redo or retry may leave any of the three (a jump would skip the + /// ensure, which here is no finally). A deopt passes the ensure clause by without running it: the generic body + /// runs it, once. + /// + private MSA.Expression/*!*/ EmitExceptionBody(Body/*!*/ body, out JT type) { + if (!RescueBodies) { throw Bail("rescue or ensure (IR_JIT_RESCUE=0)"); } + if (_loop != null) { throw Bail("rescue or ensure in an outlined loop"); } + bool hasEnsure = body.EnsureStatements != null; + if (hasEnsure && JumpsThroughEnsure(body)) { throw Bail("a jump through an ensure clause"); } + + JT bodyType; + var statements = EmitStatements(body.Statements, out bodyType); + RequireRaiseFree(statements, "the protected part"); + type = bodyType; + if (bodyType == JT.Never) { return statements; } + + MSA.Expression value = statements; + if (body.ElseStatements != null) { + JT elseType; + var elseValue = EmitStatements(body.ElseStatements, out elseType); + if (hasEnsure) { RequireRaiseFree(elseValue, "the else clause"); } + type = elseType; + value = Ast.Block(ClrType(elseType), statements, elseValue); + if (elseType == JT.Never) { return value; } + } + if (!hasEnsure) { return value; } + + JT ensureType; + var ensure = EmitStatements(body.EnsureStatements, out ensureType); + var result = Ast.Variable(ClrType(type), "#begin"); + return Ast.Block(ClrType(type), new[] { result }, Ast.Assign(result, value), ensure, result); + } + + // A return, break, next, redo or retry in a begin with an ensure clause, which the typed body does not take (JitScreen too). + internal static bool JumpsThroughEnsure(Body/*!*/ body) { + return body.EnsureStatements != null && JumpFinder.Has(body); + } + + private void RequireRaiseFree(MSA.Expression/*!*/ code, string/*!*/ part) { + var checker = new RaiseFreeChecker(); + checker.Visit(code); + if (checker.Obstacle != null) { throw Bail(part + " may raise: " + checker.Obstacle); } + } + + // return, break, next, redo or retry in the statements, else or ensure clause of a begin (not in its rescue clauses, + // which the typed body does not emit) + private sealed class JumpFinder : Walker { + private bool _found; + + internal static bool Has(Body/*!*/ body) { + var finder = new JumpFinder(); + finder.WalkAll(body.Statements); + finder.WalkAll(body.ElseStatements); + finder.WalkAll(body.EnsureStatements); + return finder._found; + } + + private void WalkAll(Statements statements) { + if (statements == null) { return; } + foreach (var statement in statements) { statement.Walk(this); } + } + + public override bool Enter(ReturnStatement/*!*/ node) { _found = true; return false; } + public override bool Enter(BreakStatement/*!*/ node) { _found = true; return false; } + public override bool Enter(NextStatement/*!*/ node) { _found = true; return false; } + public override bool Enter(RedoStatement/*!*/ node) { _found = true; return false; } + public override bool Enter(RetryStatement/*!*/ node) { _found = true; return false; } + public override bool Enter(MethodDefinition/*!*/ node) { return false; } + } + + /// + /// What the protected part of a begin may call (EmitExceptionBody): the helpers that run no Ruby code and throw nothing + /// but a deopt - the ones a body that holds its writes back may call (JitCompiler.Sink.cs) and the deopting reads and + /// identity tests - and the body of an inlined callee, which is held to the same. Not a callee's delegate (a bound or + /// self-call), a dynamic site, a fallback, a loop's safe point, a construction or a try. + /// + private static readonly HashSet/*!*/ _raiseFreeHelpers = new HashSet { + "IsIdentical", "IsNil", "CollectionEqualsNil", "IndexInt", "IndexLong", "IndexObj", "IndexIntChecked", "IndexLongChecked", + "IndexObjChecked", "HashKeyInt", + }; + + private sealed class RaiseFreeChecker : MSA.ExpressionVisitor { + internal string Obstacle; + + protected override MSA.Expression VisitMethodCall(MSA.MethodCallExpression node) { + var m = node.Method; + if (Obstacle == null && !IsRaiseFree(m)) { + Obstacle = "a call of " + m.DeclaringType.Name + "." + m.Name; + } + return base.VisitMethodCall(node); + } + + private static bool IsRaiseFree(System.Reflection.MethodInfo/*!*/ m) { + if (m.DeclaringType == typeof(JitRuntime)) { return _sinkSafeHelpers.Contains(m.Name) || _raiseFreeHelpers.Contains(m.Name); } + return m == _absLong || m == _absDouble || m == _booleanToObject || m == IsTrueMethod; + } + + protected override MSA.Expression VisitInvocation(MSA.InvocationExpression node) { + // an inlined callee's lambda is visited with it; a delegate is a body this one does not see + if (Obstacle == null && !(node.Expression is MSA.LambdaExpression)) { Obstacle = "an invoked body"; } + return base.VisitInvocation(node); + } + + protected override MSA.Expression VisitTry(MSA.TryExpression node) { + if (Obstacle == null) { Obstacle = "a try"; } + return base.VisitTry(node); + } + + protected override MSA.Expression VisitLoop(MSA.LoopExpression node) { + if (Obstacle == null) { Obstacle = "a loop"; } + return base.VisitLoop(node); + } + + protected override MSA.Expression VisitExtension(MSA.Expression node) { + if (Obstacle == null) { Obstacle = "an extension node " + node.GetType().Name; } + return node; + } + + protected override MSA.Expression VisitDynamic(MSA.DynamicExpression node) { + if (Obstacle == null) { Obstacle = "a dynamic call"; } + return base.VisitDynamic(node); + } + + protected override MSA.Expression VisitNew(MSA.NewExpression node) { + if (Obstacle == null) { Obstacle = "a construction of " + node.Type.Name; } + return base.VisitNew(node); + } + } + private MSA.Expression/*!*/ EmitStatements(Statements/*!*/ statements, int start, out JT type) { int count = statements.Count - start; if (count <= 0) { @@ -1062,7 +1226,7 @@ private bool IsInitialIVarValue(RExpr/*!*/ value) { type = JT.Obj; return Ast.Constant(null, typeof(object)); } - if (_resume != null && _ast != null && statements == _ast.Body.Statements) { + if (_resume != null && statements != null && statements == MethodStatements) { // the method's own statements, which may carry :line hooks (EmitTopStatement) return EmitStatements(statements, 0, out type); } @@ -1208,7 +1372,7 @@ private bool IsInitialIVarValue(RExpr/*!*/ value) { var body = node as Body; if (body != null) { if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { - throw JitBailout.Instance; + return EmitExceptionBody(body, out type); } return EmitStatements(body.Statements, out type); } @@ -3606,7 +3770,9 @@ private void ScreenTarget(RExpr/*!*/ target) { /// Mirrors JitCompiler.EmitBody. private bool WalkBody(Body/*!*/ body) { if (body.RescueClauses != null || body.ElseStatements != null || body.EnsureStatements != null) { - return No(body) && WalkClausesForCensus(body, 0); + // the statements, else and ensure in their order; the rescue clauses are not emitted (JitCompiler.EmitExceptionBody) + if (!JitCompiler.RescueBodies || _loops > 0 || JitCompiler.JumpsThroughEnsure(body)) { return No(body) && WalkClausesForCensus(body, 0); } + return WalkStatements(body.Statements) && WalkStatements(body.ElseStatements) && WalkStatements(body.EnsureStatements); } return WalkStatements(body.Statements); } diff --git a/Util/jit-rescue-matrix.rb b/Util/jit-rescue-matrix.rb index c81839634..e7643964f 100644 --- a/Util/jit-rescue-matrix.rb +++ b/Util/jit-rescue-matrix.rb @@ -15,6 +15,11 @@ # class list of a rescue is evaluated after the inner ensure clauses have run, `$!` is # set in the handler and restored after it, `retry` re-runs the protected part only, an # `ensure` runs once whether the body returns, raises, throws or is timed out. +# Section 23 is for typed bodies that take the begin (JitCompiler.EmitExceptionBody): they emit +# the statements, else and ensure in order and deopt where the generic body would raise, so the +# order of the clauses, the value of the begin, a deopt after an effect, TracePoint, Thread#raise +# and backtraces must be the generic body's. Which methods are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-rescue-matrix.rb 2>&1 >/dev/null | grep -a 'specialized P' def t(label) print label.ljust(56), ' => ' @@ -300,3 +305,163 @@ def pure(x) end t("21. redefined") { o.pure(10) } t("22. $! at the end") { $!.inspect } + +# 23. typed bodies that take the begin +class Q + def initialize; @n = 0; @e = 0; @log = []; end + attr_reader :n, :e, :log + + # a method-level rescue, else and ensure: the order of the clauses and the value + def mlevel(x) + @n += x + rescue ZeroDivisionError + -1 + else + @n += 1 + @n * 2 + ensure + @e += 1 + end + + # the value of a begin with else and ensure is the else clause's; the ensure clause's is dropped + def value(x) + begin + x + 1 + rescue StandardError + 0 + else + x + 2 + ensure + x + 3 + end + end + + # nested: the inner ensure before the outer else and ensure + def nested(x) + begin + begin + @n += x + ensure + @e += 1 + end + rescue StandardError + -1 + else + @e * 10 + ensure + @e += 100 + end + end + + # an effect, then a deopt in the protected part (an overflow into a Bignum): the effect once + def eff_deopt(x) + @n += 1 + begin + x * x + rescue StandardError + -1 + end + end + + # a deopt in the ensure clause after the protected part's effect + def ens_deopt(x) + begin + @n = x + ensure + @e = x * x + end + end + + # a raise in the ensure clause on the normal path + def ens_raise(x) + begin + x + 1 + ensure + raise ArgumentError, "ens" if x > 250 + end + end + + # $! read in the ensure clause of a run that raised nothing: the $! of whoever called + def ens_bang(x) + begin + x + 1 + ensure + @log << $! + end + end + + # the backtrace of an exception the protected part raises and the rescue takes, and of one that goes through + def bt(x) + begin + 100 / x + rescue ZeroDivisionError => e + e.backtrace_locations.first.label + end + end + + def bt_through(x) + begin + 100 / x + rescue ArgumentError + -1 + ensure + @e += 1 + end + end + + def plain(x) + begin + x + 1 + rescue StandardError + -1 + end + end + + # an optional parameter's default is evaluated outside the method's own rescue + def boom = raise("boom") + def dflt(x, a = 1) + x + a + rescue + :rescued + ensure + @e += 1 + end +end + +q = Q.new +t("23. method level") { [warm { |i| q.mlevel(i % 3) }, q.n, q.e] } +t("23. method level, nil") { [q.mlevel(nil), q.n, q.e] } +t("23. value") { [warm { |i| q.value(i) }, q.value(5), (q.value(nil) rescue $!.class)] } +t("23. nested") { q = Q.new; [warm { |i| q.nested(i % 3) }, q.nested(2), q.n, q.e] } +t("23. nested, nil") { [q.nested(nil), q.e] } +t("23. effect, deopt") { q = Q.new; warm { |i| q.eff_deopt(i) }; [q.eff_deopt(2**40), q.n] } +t("23. effect, raise") { [q.eff_deopt(nil), q.n] } +t("23. ensure deopt") { q = Q.new; warm { |i| q.ens_deopt(i) }; [q.ens_deopt(2**40), q.n, q.e] } +t("23. ensure raise") { q = Q.new; [warm(250) { |i| q.ens_raise(i) }, q.ens_raise(300)] } +t("23. $! in ensure") { q = Q.new; warm { |i| q.ens_bang(i) }; begin; raise "outer"; rescue; q.ens_bang(1); end; [q.log.compact.map(&:message), $!] } +t("23. backtrace, rescued") { warm { |i| q.bt(i + 1) }; q.bt(0) } +t("23. backtrace, through") { warm { |i| q.bt_through(i + 1) }; begin; q.bt_through(0); rescue ZeroDivisionError => e; e.backtrace_locations.first(2).map(&:label); end } +t("23. bt_through ensure") { q.e } +t("23. default") { q = Q.new; [warm { |i| q.dflt(i) + q.dflt(i, 2) }, q.dflt(1, nil), q.dflt(nil), q.e] } +t("23. default raises") { [(q.dflt(1, q.boom) rescue :outside), q.e] } + +events = [] +tp = TracePoint.new(:raise, :rescue) { |e| events << [e.event, e.raised_exception.class, e.method_id] if e.method_id == :bt } +warm { |i| q.bt(i + 1) } +tp.enable { q.bt(0); q.bt(1) } +t("23. TracePoint") { events } + +class Stop < Exception; end +t("23. Thread#raise") do + th = Thread.new { Thread.current.report_on_exception = false; r = 0; loop { r += q.plain(1) } } + sleep 0.05 + th.raise(Stop, "stop") + begin; th.join; rescue Stop => e; e.class; end +end +t("23. Thread#raise, rescued") do + th = Thread.new { Thread.current.report_on_exception = false; loop { q.plain(1) } rescue :out } + sleep 0.05 + th.raise(ArgumentError, "a") + th.value +end +t("23. Timeout") { Timeout.timeout(0.1) { loop { q.plain(1); q.value(1) } } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8c9250819..22dc4752d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1779,6 +1779,50 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitrescue (2026-11-28, census and timed, not gated) - `begin`/`rescue`/`else`/`ensure` in the method JIT's + typed body** (gap 22's remainder; switch `IR_JIT_RESCUE`). Built on happy-gauss 4320d4a, perf/jitbody 238d994 and + perf/lsite f7ae738 (lazy `$!`, IR_LAZY_ERRINFO). + - **Approach.** The handler is not emitted in the typed body. The typed body takes a begin, or a method-level + rescue, only where its protected part cannot raise: no call it does not inline, no loop, safe point, fallback, + construction or try. `JitCompiler.RaiseFreeChecker` checks this on the emitted tree, allowing only the helpers that + throw nothing but a deopt (the sinking allow-list plus the deopting reads and identity tests) and inlined lambdas. + An exception the generic body would raise there (an overflow, `raise`, a nil receiver) is a deopt here: the + generic body runs the call again from the top, rescue clauses and all. That is allowed only before an effect, as + for any deopt. So the typed body emits the statements, then else, then ensure: the order of a run that raises + nothing. Such a run leaves `$!` alone (with IR_LAZY_ERRINFO=0 the generic body stores back what it read) and + never sets InRescue. With an ensure, the else clause must be raise-free too, and no return, break, next, redo or + retry may leave the begin (`JumpsThroughEnsure`, refused by the screen as well). A deopt passes the ensure without + running it; the generic body runs it, once. + - **Why not a handler in the typed body.** The protected part may make calls only if each call is inlined, i.e. + raise-free as well. An exception from Ruby code needs the generic body's frame (backtrace, `$!`, TracePoint + `:rescue`, `retry`). Typed bodies already avoid raising from a frame they don't have (`InterpolatedPart`'s + comment), and this keeps to that. + - **Fixed on the way.** The analyses of "the body's last statement" (held-back writes, the last store, the resume + path) read `_ast.Body.Statements`. With method-level clauses that list is followed by else and ensure. A method + `def m(x) @n += x rescue .. else @n += 1; @n * 2 end` returned `@n`. They now read `MethodStatements`, which is + null for such a body. + - **Census** (Src/StdLib, Util/bench, AWFY, against the merged base): 61 methods up, none down. Compiles 3,583 -> + 3,585, maybe 3,238 -> 3,297, never 22,570 -> 22,509. `Body` as the first refusal: 555 -> 39 methods. Most of the + 57 that left "never (Body)" are maybe behind a call (I/O and protocol wrappers): they compile only where the call + inlines. + - **Hot methods.** app-shapes calls no method that `Body` alone refused (9 have it among others), and AWFY has no + rescue in a benchmark. Traced runs: app-shapes 118 specialized and 29 declined on both builds; + zjit-post-shapes 6 -> 8 specialized (`B#resc`, `B#ens`), declines 0 -> 0. + - **Clock** (ab.rb -r 5, zjit-post-shapes): rescue 53.9 -> 36.7 ns against the switch off (base 58.3, CRuby 27.9), + ensure 65.6 -> 50.1 (base 65.4, CRuby 32.3), no overlap. zjit-post-shapes prints no instruction counts. + - **Checks.** `Util/jit-rescue-matrix.rb` has a new section 23 (Q): method-level rescue/else/ensure order and value, + the value of a begin with else and ensure, nested begins, an effect then a deopt in the protected part or in the + ensure, a raise in the ensure, `$!` read in the ensure under an outer rescue, backtraces from the handler and + through the begin, TracePoint `:raise`/`:rescue`, Thread#raise of an Exception and of a StandardError into a hot + method, Timeout, and a default argument (evaluated outside the method's rescue). It prints CRuby's output with + the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, IR_LIGHT_FRAMES=0, the switch off, and IR_LAZY_ERRINFO=0. + errinfo, rescue-light, jit-raise, raise, jit, jit-calls, hot-shapes and light-entry in the same five modes: the + same as the base (raise's anonymous-class row prints an address). ruby/spec language rescue, ensure and retry, + core/exception and library/timeout: the same as the base, no failures. IronRuby.Tests, all 1,377: one failure, + JitCensus1, which pins census verdicts. Its `Point#safe` (a method-level rescue around `@x.fetch`) is now maybe + (call: fetch/0). The test now expects that, plus a new `Point#jump` (a return through an ensure) that is still + never (Body); it passes. + - **perf/jitblockparam (2026-11-27, census and timed, not gated) - a typed body for a call without a block** (switch `IR_JIT_BLOCK_PARAM`). A method whose block parameter is only passed on, `def w(a, b, &k) = @t.two(a, b, &k)`, was never wrapped (`JitStub.ParameterShape`: "block parameter"), and one passing `&nil` From 648b9f6ea29bec44873373d270b17b353ebfcd50 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:29:11 +0000 Subject: [PATCH 227/439] An outlined loop handed back by an epoch move that changed nothing it was built on is kept Every constant reassignment anywhere moves the code epoch, and an outlined loop's safe point compares the safe-point word with the epoch it was compiled at: the copy handed itself back and the site rebuilt it (after StaleRebuildSpacing of generic iterations), whatever was reassigned. A loop beside a thread reassigning another constant 1000 times was compiled 12 times; one whose folded constant was set again to the same object, 15. Now OsrLoopSite.Run asks the guard first (JitLoopGuard.TryKeep): the method version unchanged and each folded constant resolving as it did (or the constant version not moved) - then the copy is current, its guard's epoch moves up, and the loop goes back to it at the next back edge. The safe point compares with the immediate as before and, only once the word has moved, with the guard's epoch (reading the field on every iteration made a two-statement loop 1.4x slower). A folded constant that changed still rebuilds the copy. IR_LOOP_KEEP=0 turns it off. Util/loop-const-matrix.rb section 6: running loops (outlined and a typed body) kept through 3,500 reassignments of other constants and of their own to the same value must stop when their own then changes; a sum beside such reassignments. CRuby 4.0's output on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 12 ++++++++++++ Src/Ruby/Runtime/Jit/JitRuntime.cs | 18 ++++++++++++++++++ Src/Ruby/Runtime/Osr/OsrLoopSite.cs | 20 +++++++++++++++----- Util/loop-const-matrix.rb | 24 ++++++++++++++++++++++++ 4 files changed, 69 insertions(+), 5 deletions(-) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index a825069ef..e9b8bf1f7 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1945,6 +1945,9 @@ internal static bool ConstantGuard(RExpr/*!*/ node, out ConstantVariable guard, // safe-point word with it, as an immediate. private long _compileEpoch; + // IR_LOOP_KEEP=0: an outlined copy handed back at its safe point is rebuilt whatever moved the epoch, as before. + internal static readonly bool _KeepOutlined = Environment.GetEnvironmentVariable("IR_LOOP_KEEP") != "0"; + /// /// A typed method body's loop keeps an epoch local, which starts from the one the body last found /// current; null in an outlined loop, which has none (see EmitLoopSafePoint). @@ -1978,6 +1981,15 @@ private MSA.ParameterExpression NewLoopEpoch() { var word = Ast.Property(null, typeof(RubyUtils).GetProperty("SafePointWord")); var moved = Ast.NotEqual(word, Ast.Constant(_compileEpoch)); if (epoch == null) { + // A copy the site kept after a hand-back that changed nothing it was built on (OsrLoopSite.Run, + // JitLoopGuard.TryKeep) compares with its guard's epoch, which the site moved up: against the immediate + // alone every later iteration would hand it back again. Only once the word has moved, though: the guard is a + // constant of the closure, and reading its field on every iteration made `s += K; i += 1' 1.4x slower. + if (_KeepOutlined) { + return Ast.IfThen(moved, Ast.IfThen( + Ast.NotEqual(word, Ast.Field(Ast.Constant(_loopGuard), JitLoopGuard.EpochField)), + Ast.Throw(Ast.Call(JitRuntime.M("OsrHandBack"))))); + } return Ast.IfThen(moved, Ast.Throw(Ast.Call(JitRuntime.M("OsrHandBack")))); } return Ast.IfThen(moved, diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 29e31fd20..3291d2e0c 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1368,6 +1368,24 @@ internal bool ConstantsStillHold() { return true; } + /// + /// An outlined copy was handed back at its safe point, or failed its entry guard: if the method version is still the + /// one it was compiled under and each constant it folded resolves as it did (or the constant version has not moved), + /// the copy is current, and its safe points compare with the epoch read before these checks from now on. False + /// if anything it was built on changed. + /// + internal bool TryKeep() { + long epoch = RubyUtils.CodeEpoch; + if (RubyModule.GlobalMethodVersion != Version) { return false; } + var context = ConstantsOf; + if (context != null && System.Threading.Volatile.Read(ref context.ConstantAccessVersion) != System.Threading.Volatile.Read(ref ConstantVersion) && + !ConstantsStillHold()) { + return false; + } + System.Threading.Volatile.Write(ref Epoch, epoch); + return true; + } + /// A method table or a constant the code was built on has changed since. internal bool Stale { get { diff --git a/Src/Ruby/Runtime/Osr/OsrLoopSite.cs b/Src/Ruby/Runtime/Osr/OsrLoopSite.cs index 743bedd35..56eaffc98 100644 --- a/Src/Ruby/Runtime/Osr/OsrLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/OsrLoopSite.cs @@ -103,7 +103,7 @@ private static long ReadThreshold() { return (s != null && Int64.TryParse(s, out v) && v > 0) ? v : 2000; } - internal static int Specialized, Retired, Entered, Deopts, StaleRebuilds; + internal static int Specialized, Retired, Entered, Deopts, StaleRebuilds, Kept; internal static long CompileTicks; /// @@ -220,10 +220,20 @@ public object Run(object[]/*!*/ tuples) { } if (guard != null && (guard.Stale || RubyUtils.CodeEpoch != guard.Epoch)) { + // Nothing the copy was built on changed - another constant was reassigned, say, which moves the code + // epoch every copy's safe point compares with: the copy is current (JitLoopGuard.TryKeep), and the loop + // goes back to it at the next back edge rather than after a rebuild, which waited for + // StaleRebuildSpacing of generic iterations and a compilation. + if (Jit.JitCompiler._KeepOutlined && guard.TryKeep()) { + Kept++; + if (Verbose) { Console.Error.WriteLine("[osr] {0}: handed back, nothing it was built on changed: kept", _name); } + Counting = false; + Countdown = 1; + return Retry; + } // Not a failure either: a method the copy was built on (an inlined Array#size, a bound // callee) or a constant it folded changed since it was compiled - found on entry, or - // while it ran (JitRuntime.OsrHandBack), on this thread or another; or something else - // moved the code epoch the copy's safe points compare with. The generic loop calls what + // while it ran (JitRuntime.OsrHandBack), on this thread or another. The generic loop calls what // is defined now; a copy built for the new epoch takes over when StaleRebuildSpacing // allows. However often that happens, the loop is not retired. StaleRebuild(); @@ -322,8 +332,8 @@ private Func Compile(object[]/*!*/ tuples) { internal static void HookStats() { if (!Verbose || System.Threading.Interlocked.Exchange(ref _statsHooked, 1) != 0) { return; } AppDomain.CurrentDomain.ProcessExit += (s, e) => { - Console.Error.WriteLine("[osr] specialized={0} retired={1} entries={2} deopts={3} stale={4} compile={5:F1}ms", - Specialized, Retired, Entered, Deopts, StaleRebuilds, CompileTicks * 1000.0 / Stopwatch.Frequency); + Console.Error.WriteLine("[osr] specialized={0} retired={1} entries={2} deopts={3} stale={4} kept={5} compile={6:F1}ms", + Specialized, Retired, Entered, Deopts, StaleRebuilds, Kept, CompileTicks * 1000.0 / Stopwatch.Frequency); }; } } diff --git a/Util/loop-const-matrix.rb b/Util/loop-const-matrix.rb index d1ae6a247..78047a57e 100644 --- a/Util/loop-const-matrix.rb +++ b/Util/loop-const-matrix.rb @@ -173,4 +173,28 @@ class G13; include N13; prepend N13b; end loop13 = -> { run { i = 0; s = 0; while i < N; s += (F13::W == :own ? 1 : 0); i += 1; end; s } } row "a loop over it", entries(6, nil) { loop13.() } +# ---------------------------------------------------------------- 6. a running loop beside reassignments of other constants +# Each reassignment of any constant moves the code epoch, which every running compiled loop's safe point compares with; a loop +# that folded none of them is kept (OsrLoopSite.Run), and must still see its own constant change after being kept many times. +OTHER7 = 0 +R7 = 1 +module RL7 + def self.outlined(n = LIMIT) = run { i = 0; while R7 == 1 && i < n; i += 1; end; i < n } + def self.body(n = LIMIT) = (i = 0; while R7 == 1 && i < n; i += 1; end; i < n) +end +200.times { RL7.body(20) } +def others_then(name, mod) + # (no sleep or pass between them: CRuby's GVL would hand the loop a timeslice each time) + -> { 3000.times { |j| Object.const_set(:OTHER7, j) }; 500.times { Object.const_set(:R7, 1) }; mod.const_set(name, 2) } +end +row "running outlined, others reassigned, then its own", nearer(others_then(:R7, Object)) { RL7.outlined } +Object.const_set(:R7, 1) +row "running body, others reassigned, then its own", nearer(others_then(:R7, Object)) { RL7.body } +K8 = 3 +stop8 = false +reassigner = Thread.new { j = 0; until stop8; Object.const_set(:OTHER7, j += 1); Object.const_set(:K8, 3); Thread.pass; end } +sums8 = 20.times.map { run { i = 0; s = 0; while i < N * 10; s += K8; i += 1; end; s } } +stop8 = true; reassigner.join +row "summing beside reassignments of it to the same value and of others", sums8.uniq + puts "end" From 7aa5f06e1dfe0db28ae48d6acdadf99affa20975 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:29:11 +0000 Subject: [PATCH 228/439] Ledger: perf/loopreassign (round forty, gap 29) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Util/perf/LEDGER.md | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 5eafa4a76..2dca32367 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1614,8 +1614,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Done for outlined loops in round thirty-eight (see Landed, perf/loopconst): an outlined loop's entry looks its folded constants up again rather than comparing a baked version. And the running loop's fault (rminor's case) in perf/loopnear (see Landed): a nearer constant that appears on a - folded lookup's path moves the code epoch. Still open: an outlined loop's safe point hands the - loop back on any reassignment (the code epoch, compared as an immediate), which rebuilds the copy; + folded lookup's path moves the code epoch. An outlined copy handed back by a reassignment of + something it did not fold is kept (perf/loopreassign, see Landed). Still open: a constant kept + as a counter (a new value each time) still rebuilds the copy each time, as spaced by + StaleRebuildSpacing (12% of a 400M-iteration loop's time at 1000 reassignments); not folding it + after the second change was tried and dropped - receiver hints, `case`/`when` tests and the + `if CONST` guard fold constants too, so an unfolded read in EmitConstant alone still left the + copy guarding on it; a typed body that deopts there finishes its call in the generic body (`near.rb`: 0.45 s typed, 14.6 s once deopted, CRuby 6.6 s). 30. **`Binding#local_variable_get`, `_set`, `_defined?` and `local_variables` are an @@ -1901,6 +1906,33 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/loopreassign (round forty, 2026-11-28) - an outlined loop handed back by an epoch move that + changed nothing it was built on is kept (gap 29)** - not gated. Every constant reassignment anywhere + moves the code epoch; an outlined loop's safe point compared the safe-point word with the epoch it + was compiled at, so the copy handed itself back and the site rebuilt it (after StaleRebuildSpacing), + whatever was reassigned. Now `OsrLoopSite.Run` asks `JitLoopGuard.TryKeep` first (the method version + unchanged, each folded constant resolving as it did); the copy is then kept, its guard's epoch moves + up, and the loop goes back to it at the next back edge. The safe point compares with the immediate + and, once the word has moved, with the guard's epoch (`EmitLoopSafePoint`; the field on every + iteration was 0.55 -> 0.78 s on `s += K; i += 1`). A folded constant that changed still rebuilds. + `IR_LOOP_KEEP=0` turns it off. Correctness does not rest on TryKeep's constant check: with it taken + out the matrix still prints CRuby's (a wrongly kept copy fails its entry guard, perf/loopconst's, + and the generic iteration between reads the new value); it keeps the copy from being re-entered + only to fail. + Probe (`reassign.rb`: an outlined 400M-iteration loop `s += 1 if K > 0`, another thread reassigning + 0.4 ms apart; 3 runs, base / new, compiles of the last run): `OTHER` 10x 3.29-3.48 / 2.96-3.54 s, + 2 / 1 compiles; 100x 2.88-3.31 / 3.09-5.17 (one outlier), 2 / 1; 1000x 3.13-3.54 / 3.03-3.33, 12 / 1 + (940 kept); `K` set to the same object 1000x 3.21-3.31 / 2.99-3.57, 15 / 2; `K` a counter (a new + value each time) 1000x 3.53-3.67 / 3.51-3.70, 15 / 14 - unchanged, see gap 29; no reassignment + 2.50-2.60 / 2.55-3.11. Instructions (`deadconst-shapes.rb`, count.sh, N=20,000) 1.000 on all nine. + `Util/loop-const-matrix.rb` section 6 (running loops kept through 3,500 reassignments of other + constants and of their own to the same value must stop when their own changes; a sum beside such + reassignments): CRuby 4.0's output on base, new and `IR_LOOP_KEEP=0`, three runs in each of three + modes. `gate-matrices.rb` on hot-shapes, jit, osr-array, deadconst, jit-const, loop-const and + block-loop in ten modes (the gate's six, `IR_LOOP_KEEP=0`, `IR_LOOP_NEAR=0`, `IR_LOOP_CONSTANTS=0`, + `IR_SINGLETON_LOOKUP=0`): PASS, 68 same, 2 baseline (block-loop under R2R; loop-const with + `IR_LOOP_NEAR=0`, that switch's own rows). ruby/spec language/constants: no failures on either build. + - **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, perf/twospeed and its note, perf/extiter4 and 5, perf/fiberstart, perf/iter, perf/strsearch3 and 4, From 96750a50b9462133181b7e582a3fc264db782e2c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:31:52 +0000 Subject: [PATCH 229/439] "float X out of range of integer" names the Float as MRI's %-.10g does MRI's rb_out_of_long (and rb_num2long in the C API) prints the Float with C's "%-.10g": "float Inf out of range of integer", "-Inf", "NaN", "1e+30", "3000000000". IronRuby printed .NET's "Infinity", "1E+30" or the Float's inspect, depending on the call (Array#take, #first, #[], #*, Array.new, String#*, sprintf's arguments, the C API, round's digits). RubyUtils.FormatFloatG10 is that format (%e past ten significant digits, %f below, trailing zeros dropped), and every such message uses it; StringFormatter's own copy, which knew only %e, defers to it. round's digits message also went through the (paramName, message) overload of CreateRangeError and came out as "1e+30 (Parameter 'float {0} ...')". Util/array-take-matrix.rb: the take(Float::INFINITY) row now agrees with CRuby 4.0 (take(nil) is the pinned into wording). Float_OutOfRangeMessage1 holds CRuby's output; the take, first, element_reference, multiply, Array.new, String#*, format, sprintf and round specs pass, as do 130 numeric, conversion, array and format IronRuby.Tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 40 +++++++++++++++++++++ Src/Libraries/Builtins/StringFormatter.cs | 8 +---- Src/Libraries/Extensions/IListOps.cs | 2 +- Src/Libraries/Extensions/NumericRounding.cs | 2 +- Src/Ruby/CApi/CApi.Numbers.cs | 3 +- Src/Ruby/Runtime/RubyOps.cs | 2 +- Src/Ruby/Runtime/RubyUtils.cs | 23 ++++++++++++ 8 files changed, 70 insertions(+), 11 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 63f802751..0f463887a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1168,6 +1168,7 @@ public Tests(Driver/*!*/ driver) { Block_RegisterLocals1, TracePoint_EndlessDefLine1, TracePoint_AttrAccessorCCall1, + Float_OutOfRangeMessage1, Defined_ConditionNoFreeze1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 4a9f601b1..e9153c727 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -9269,6 +9269,46 @@ p ev2 "); } + /// + /// A Float that does not fit an integer is named as C's "%-.10g" prints it, as MRI's rb_out_of_long does: + /// "float Inf out of range of integer", "1e+30", "NaN". + /// + public void Float_OutOfRangeMessage1() { + TestOutput(@" +require 'ruby4' +def t(l) + p [l, yield] +rescue => e + p [l, e.class, e.message] +end +t(:take_inf) { [1].take(Float::INFINITY) } +t(:take_ninf) { [1].take(-Float::INFINITY) } +t(:first_nan) { [1].first(Float::NAN) } +t(:big) { [1].take(1e30) } +t(:ary_new) { Array.new(Float::INFINITY) } +t(:str_mul) { ""a"" * Float::INFINITY } +t(:at) { [1][1e19] } +t(:idx) { [1][Float::NAN] } +t(:mul) { [1] * 1e20 } +t(:fmt) { ""%c"" % 1e30 } +t(:fmt2) { ""%*d"" % [1e20, 1] } +t(:small) { [1].take(-9.5e18) } +", @" +[:take_inf, RangeError, ""float Inf out of range of integer""] +[:take_ninf, RangeError, ""float -Inf out of range of integer""] +[:first_nan, RangeError, ""float NaN out of range of integer""] +[:big, RangeError, ""float 1e+30 out of range of integer""] +[:ary_new, RangeError, ""float Inf out of range of integer""] +[:str_mul, RangeError, ""float Inf out of range of integer""] +[:at, RangeError, ""float 1e+19 out of range of integer""] +[:idx, RangeError, ""float NaN out of range of integer""] +[:mul, RangeError, ""float 1e+20 out of range of integer""] +[:fmt, RangeError, ""float 1e+30 out of range of integer""] +[:fmt2, RangeError, ""float 1e+20 out of range of integer""] +[:small, RangeError, ""float -9.5e+18 out of range of integer""] +"); + } + /// /// The expression of an endless def is not a line to TracePoint :line (prism gives it no newline flag): CRuby reports /// no event for it, with or without a rescue modifier, but does for statements in parentheses in it and in a block. diff --git a/Src/Libraries/Builtins/StringFormatter.cs b/Src/Libraries/Builtins/StringFormatter.cs index 9aea6508d..621b16c57 100644 --- a/Src/Libraries/Builtins/StringFormatter.cs +++ b/Src/Libraries/Builtins/StringFormatter.cs @@ -1505,13 +1505,7 @@ private int CharArgumentToInt(object value) { // MRI's rb_out_of_range prints the float with "%-.10g". private static string/*!*/ FormatFloatG10(double d) { - if (Double.IsNaN(d)) { - return "NaN"; - } - if (Double.IsInfinity(d)) { - return d > 0 ? "Inf" : "-Inf"; - } - return d.ToString("0.#########e+00", System.Globalization.CultureInfo.InvariantCulture); + return RubyUtils.FormatFloatG10(d); } /// diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index cef8c81fc..8416d7930 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -664,7 +664,7 @@ public static object GetElement(IList/*!*/ self, int index) { private static object GetElement(IList/*!*/ self, double index) { if (Double.IsNaN(index) || index >= 9.2233720368547758E18 || index < -9.2233720368547758E18) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", index)); + throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(index))); } long truncated = (long)index; return (truncated > Int32.MaxValue || truncated < Int32.MinValue) ? null : GetElement(self, (int)truncated); diff --git a/Src/Libraries/Extensions/NumericRounding.cs b/Src/Libraries/Extensions/NumericRounding.cs index 48225f091..97c242816 100644 --- a/Src/Libraries/Extensions/NumericRounding.cs +++ b/Src/Libraries/Extensions/NumericRounding.cs @@ -99,7 +99,7 @@ internal static int GetNDigits(ConversionStorage/*!*/ integerCast, throw new FloatDomainError("NaN"); } if (d >= 2147483648.0 || d <= -2147483649.0) { - throw RubyExceptions.CreateRangeError("float {0} out of range of integer", d); + throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(d))); } return (int)d; } diff --git a/Src/Ruby/CApi/CApi.Numbers.cs b/Src/Ruby/CApi/CApi.Numbers.cs index 9a376e1d7..245bf986e 100644 --- a/Src/Ruby/CApi/CApi.Numbers.cs +++ b/Src/Ruby/CApi/CApi.Numbers.cs @@ -66,8 +66,9 @@ private static BigInteger ToBigInteger(object obj, string/*!*/ ctype) { throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", ClassName(obj))); } + // rb_num2long's "%-.10g" private static string/*!*/ FormatFloat(double d) { - return _context.Inspect(d).ToString(); + return RubyUtils.FormatFloatG10(d); } // C's long: 64-bit on Unix, 32-bit on Windows diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index b8e5517bb..a89bbc151 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -5783,7 +5783,7 @@ public static int ConvertDoubleToFixnum(double value) { try { return checked((int)value); } catch (OverflowException) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", value)); + throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(value))); } } diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index b42c91ae4..6f5c13a29 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -39,6 +39,29 @@ namespace IronRuby.Runtime { using EvalEntryPointDelegate = Func; public static class RubyUtils { + /// + /// A Float as C's "%-.10g" prints it, which MRI's rb_out_of_long and friends use in "float %s out of range of + /// integer": "Inf", "-Inf", "NaN", "3000000000", "9.223372037e+18", "1e+30". + /// + public static string/*!*/ FormatFloatG10(double d) { + if (Double.IsNaN(d)) { + return "NaN"; + } + if (Double.IsInfinity(d)) { + return d > 0 ? "Inf" : "-Inf"; + } + if (d == 0) { + return (1 / d < 0) ? "-0" : "0"; + } + // the decimal exponent of d rounded to 10 significant digits decides between %e and %f, as in C + string e = d.ToString("E9", System.Globalization.CultureInfo.InvariantCulture); + int exponent = Int32.Parse(e.Substring(e.IndexOf('E') + 1), System.Globalization.CultureInfo.InvariantCulture); + if (exponent < -4 || exponent >= 10) { + return d.ToString("0.#########e+00", System.Globalization.CultureInfo.InvariantCulture); + } + return d.ToString("0." + new string('#', Math.Max(0, 9 - exponent)), System.Globalization.CultureInfo.InvariantCulture); + } + #region Threads /// From cd652458df2834af20bb140648accdcbead8116d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:33:34 +0000 Subject: [PATCH 230/439] Enumerable methods in the prelude walk a plain Hash with a one-value block filter_map, min_by, max_by, sort_by, min_by(n), max_by(n), flat_map and collect_concat walk an Array whose #each is the built-in one with `each { |item| }` (__plain_list__?), and everything else with the generic `each { |*values| }` block, which makes an Array per element and takes the item out again with __enum_item__ (or splats it back into the block). A Hash took the generic walk, though its built-in #each yields exactly one value per entry to such a block - the [key, value] pair, the same item the generic walk makes: IDictionaryOps.Each splits the pair only for a block that takes two parameters or more, and neither `|item|` nor `|*values|` does. {a: 3, b: 1, c: 2, d: 1}.min_by { |k, v| v } took 1370 ns against CRuby's 650. __plain_each__? (Enumerable.cs) answers as __plain_list__? for an Array, and for a Hash whose #each - through its class and any singleton class or prepended module - resolves to the built-in Hash#each; the five call sites of those methods ask it instead of __plain_list__?. The block gets the same argument either way (block.call(item) and yield(item), item the pair), so a lambda, a `|k, v|` block, &:sym and a Method behave as before. A subclass with its own #each, a prepended or singleton #each, or a redefined Hash#each keeps the generic walk; a refined Hash#each is not seen by either walk, as in MRI. IR_HASH_WALK=0 turns it off. tally and group_by stay Array-only: theirs are C# loops over an IList. Clock (Util/perf/ab.rb, four rounds, ns, unchanged / this, the switch off equal to the unchanged build): Hash#min_by 1348 -> 999 (0.74, CRuby 650), max_by 1394 -> 1019 (0.73), min_by with |pair| 1359 -> 986 (0.73), filter_map 962 -> 772 (0.80), flat_map 1544 -> 1276 (0.83), sort_by 1905 -> 1678 (0.88), min_by(2) 2075 -> 1792 (0.86). The Array rows of those methods within the noise (0.97 - 1.02), and Hash#sum and #map, which do not go through it, too. Three Hash rows are new in core-small.rb. Util/hash-walk-matrix.rb (new: the eight methods with thirteen block shapes, an empty and a one-entry Hash, a subclass, a subclass with its own #each, a prepended and a singleton #each, compare_by_identity, a default proc that must not be called, nil keys, a frozen Hash, a key added, one deleted and a value replaced in the block, break/next/raise/throw, backtrace frames, a refined, a redefined and a restored Hash#each, flat_map answers, keys that do not compare, NaN, ties, enumerators) prints what the unchanged build printed - CRuby's, but for two tie orders of min_by(2) and max_by(2) that were already different - by default, with the switch off, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. sort-by, enum, enumerable2, the five hash matrices, caller and hot-shapes print what they did in those modes, callable-parameters too but for a prelude line number. ruby/spec core/hash and core/enumerable: the same examples on both builds. IronRuby.Tests Backtrace_LibraryFrames1 and seven Enumerable and prelude tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/Libraries/Builtins/Enumerable.cs | 34 +++++++ Src/StdLib/ironruby/ruby4.rb | 29 +++--- Util/bench/core-small.rb | 6 ++ Util/hash-walk-matrix.rb | 136 +++++++++++++++++++++++++++ 4 files changed, 191 insertions(+), 14 deletions(-) create mode 100644 Util/hash-walk-matrix.rb diff --git a/Src/Libraries/Builtins/Enumerable.cs b/Src/Libraries/Builtins/Enumerable.cs index 39d605543..a57d7af52 100644 --- a/Src/Libraries/Builtins/Enumerable.cs +++ b/Src/Libraries/Builtins/Enumerable.cs @@ -57,6 +57,40 @@ public static bool IsPlainList(RubyContext/*!*/ context, object self) { return own.Found && builtin.Found && ReferenceEquals(own.Info, builtin.Info); } + // IR_HASH_WALK=0 keeps a Hash on the generic walk (__plain_each__? answers for Arrays only). + private static readonly bool _hashWalk = Environment.GetEnvironmentVariable("IR_HASH_WALK") != "0"; + + /// + /// True for an Array as says, and for a Hash whose #each is the + /// built-in Hash#each: that one yields each entry once, as one [key, value] Array to a block + /// that takes one parameter or a rest (IDictionaryOps.Each splits the pair only for a block + /// that takes two or more). The prelude's Enumerable methods written in Ruby then walk it + /// with a one-value block, `each { |item| }`, and get the same item that a `|*values|` block + /// and __enum_item__ make, without the Array and the call per entry. MRI's Enumerable + /// methods call #each with no refinements in scope, and so does the prelude: a refined + /// Hash#each is not seen by either. + /// + [RubyMethod("__plain_each__?", RubyMethodAttributes.PrivateInstance)] + public static bool IsPlainEach(RubyContext/*!*/ context, object self) { + if (!(self is Hash)) { + return IsPlainList(context, self); + } + if (!_hashWalk) { + return false; + } + RubyClass hashClass = context.GetClass(typeof(Hash)); + if (!IListOps.IsBuiltinMethod(hashClass, "each")) { + return false; + } + RubyClass cls = context.GetImmediateClassOf(self); + if (ReferenceEquals(cls, hashClass)) { + return true; + } + var own = cls.ResolveMethod("each", VisibilityContext.AllVisible); + var builtin = hashClass.ResolveMethod("each", VisibilityContext.AllVisible); + return own.Found && builtin.Found && ReferenceEquals(own.Info, builtin.Info); + } + // Enumerable#group_by over a plain list (see IsPlainList): the prelude's loop with the // result Hash filled in directly, as MRI's group_by_i does. Array#each yields one value // per element, so enum_yield yields it plainly: a lambda is not forced to take an Array diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 31f38d28b..cb9521375 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -237,9 +237,10 @@ def filter_map(&block) result = [] # Like #map, the yielded values reach the block as they were yielded: # `yield 1, 2` is 1 to a one-parameter block, not [1, 2]. - # An Array whose #each is the built-in one yields one value per element: the block - # takes it as it is, without the `|*values|` Array and the splat back (2.1x MRI). - if __plain_list__? + # An Array or a Hash whose #each is the built-in one yields one value per element (a + # Hash's is the [key, value] pair): the block takes it as it is, without the `|*values|` + # Array and the splat back (2.1x MRI; __plain_each__?). + if __plain_each__? each { |item| v = yield(item); result << v if v } else each { |*values| v = block.call(*values); result << v if v } @@ -503,7 +504,7 @@ def min_by(n = (no_n = true; nil), *extra, &block) return no_n ? to_enum(:min_by) { size if respond_to?(:size) } : to_enum(:min_by, n) { size if respond_to?(:size) } end if n.nil? - return __list_extreme_by__(-1, &block) if __plain_list__? + return __list_extreme_by__(-1, &block) if __plain_each__? return __extreme_by__(-1, &block) end # The count is checked before the block runs: MRI raises on a negative one, and answers @@ -539,8 +540,8 @@ def __extreme_by__(direction, &block) end private :__extreme_by__ - # __extreme_by__ over an Array whose #each is the built-in one (__plain_list__?): that - # #each yields one value per element, so the block takes it as it is - no `|*values|` + # __extreme_by__ over an Array or a Hash whose #each is the built-in one (__plain_each__?): + # that #each yields one value per element (a Hash's is the [key, value] pair), so the block takes it as it is - no `|*values|` # Array and no __enum_item__ per element. It still goes through #each, as MRI's # Enumerable#min_by does: a backtrace from the block shows Array#each under min_by. def __list_extreme_by__(direction) @@ -581,7 +582,7 @@ def max_by(n = (no_n = true; nil), *extra, &block) return no_n ? to_enum(:max_by) { size if respond_to?(:size) } : to_enum(:max_by, n) { size if respond_to?(:size) } end if n.nil? - return __list_extreme_by__(1, &block) if __plain_list__? + return __list_extreme_by__(1, &block) if __plain_each__? return __extreme_by__(1, &block) end count = __count_arg__(n) @@ -603,14 +604,14 @@ def __count_arg__(n) # # Every receiver is sorted by the C# Array#sort_by, taken under a private name when the # prelude loads (a program's own Array#sort_by does not change min_by): it is a stable merge - # sort, so equal keys keep their input order. An Array whose #each is the built-in one is - # walked with a one-value block (__list_sort_by_key__); anything else - a Hash, a Range, an - # Enumerator - with the generic `|*values|` block, and the elements it gathered go to the + # sort, so equal keys keep their input order. An Array or a Hash whose #each is the + # built-in one is walked with a one-value block (__list_sort_by_key__, __plain_each__?); + # anything else - a Range, an Enumerator - with the generic `|*values|` block, and the elements it gathered go to the # same sort, which takes their keys by position. Sorting [key, index, element] triples with # a Ruby comparison block and taking the elements out again was more than half of # {a: 1, b: 2, c: 3, d: 4}.sort_by { |k, v| -v }. def __sort_by_key__(block) - return __list_sort_by_key__(&block) if __plain_list__? + return __list_sort_by_key__(&block) if __plain_each__? items = [] keys = [] each do |*values| @@ -650,14 +651,14 @@ def minmax_by(&block) # flat_map and collect_concat are one C function in MRI, which a backtrace names by # the method called - so each is a method here, not an alias. # - # An Array whose #each is the built-in one yields one value per element, so the block - # takes it as it is, and the block's answer goes through Array.try_convert, which is the + # An Array or a Hash whose #each is the built-in one (__plain_each__?) yields one value per + # element, so the block takes it as it is, and the block's answer goes through Array.try_convert, which is the # rb_check_array_type MRI's flat_map_i calls: the `|*values|` block, the splat back into # yield and the two type tests per element made [4 elements].flat_map { } 2.4x MRI. def __enum_flat_map__(name) return to_enum(name) { size if respond_to?(:size) } unless block_given? result = [] - if __plain_list__? + if __plain_each__? each do |item| mapped = yield(item) array = ::Array === mapped ? mapped : ::Array.try_convert(mapped) diff --git a/Util/bench/core-small.rb b/Util/bench/core-small.rb index 688282e25..151a4798d 100644 --- a/Util/bench/core-small.rb +++ b/Util/bench/core-small.rb @@ -102,6 +102,9 @@ def m86; @sp.rstrip.size; end def m87; (1..4).sort_by { |x| -x }.size; end def m88; @h.max_by(2) { |k, v| v }.size; end def m89; @h.sort_by { |pair| pair[1] }.size; end + def m90; @h.min_by { |k, v| v }.size; end + def m91; @h.filter_map { |k, v| v if v > 2 }.size; end + def m92; @h.flat_map { |k, v| [v] }.size; end end def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end # INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the @@ -209,3 +212,6 @@ def t(name, n) t("range_sort_by", N) { |n| i = 0; s = 0; while i < n; s += h.m87; i += 1; end; s } t("hash_max_by_n", N) { |n| i = 0; s = 0; while i < n; s += h.m88; i += 1; end; s } t("hash_sort_by_pair", N) { |n| i = 0; s = 0; while i < n; s += h.m89; i += 1; end; s } +t("hash_min_by", N) { |n| i = 0; s = 0; while i < n; s += h.m90; i += 1; end; s } +t("hash_filter_map", N) { |n| i = 0; s = 0; while i < n; s += h.m91; i += 1; end; s } +t("hash_flat_map", N) { |n| i = 0; s = 0; while i < n; s += h.m92; i += 1; end; s } diff --git a/Util/hash-walk-matrix.rb b/Util/hash-walk-matrix.rb new file mode 100644 index 000000000..9c5807c48 --- /dev/null +++ b/Util/hash-walk-matrix.rb @@ -0,0 +1,136 @@ +# Differential matrix for the Enumerable methods written in Ruby (the prelude) when the receiver is a +# Hash: filter_map, min_by, max_by, sort_by, min_by(n), max_by(n), flat_map, collect_concat. A Hash +# whose #each is the built-in one is walked with a one-value block (__plain_each__?, IR_HASH_WALK), +# anything else with the generic `|*values|` block. Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/hash-walk-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/hash-walk-matrix.rb > /tmp/on.txt 2>&1 +# IR_HASH_WALK=0 ./ir.sh Util/hash-walk-matrix.rb > /tmp/off.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt + +def t(label) + print label.ljust(50), ' => ' + begin + puts yield.inspect + rescue Exception => e + puts "#{e.class}: #{e.message.sub(/0x\h+/, '0x')}" + end +end + +def h = { a: 3, b: 1, c: 2 } + +METHODS = { + filter_map: ->(r, &b) { r.filter_map(&b) }, + min_by: ->(r, &b) { r.min_by(&b) }, + max_by: ->(r, &b) { r.max_by(&b) }, + sort_by: ->(r, &b) { r.sort_by(&b) }, + 'min_by(2)': ->(r, &b) { r.min_by(2, &b) }, + 'max_by(2)': ->(r, &b) { r.max_by(2, &b) }, + flat_map: ->(r, &b) { r.flat_map(&b) }, + collect_concat: ->(r, &b) { r.collect_concat(&b) }, +} + +# ---------------------------------------------------------------- 1. what the block is given +BLOCKS = { + '|x|' => proc { |x| x.inspect }, + '|k, v|' => proc { |k, v| [v, k.to_s] }, + '|k|' => proc { |k| k.inspect }, + '|*a|' => proc { |*a| a.inspect }, + '|(k, v)|' => proc { |(k, v)| v }, + '|k, (v)|' => proc { |k, (v)| v.inspect }, + '|x, *r|' => proc { |x, *r| [r.size, x.to_s] }, + 'lambda (x)' => ->(x) { x.inspect }, + 'lambda (k, v)' => ->(k, v) { v }, + 'lambda (*a)' => ->(*a) { a.size }, + '&:first' => :first.to_proc, + '&:last' => :last.to_proc, + 'method(1 arg)' => Kernel.method(:Array).to_proc, +} +METHODS.each do |name, m| + BLOCKS.each do |bname, b| + t("#{name} #{bname}") { m.(h, &b) } + end +end + +# ---------------------------------------------------------------- 2. the Hash +class SubHash < Hash; end +class OwnEach < Hash + def each + yield :own, 1 + yield [:pair, 2] + self + end +end +module PrependEach + def each(&b) = (yield :prepended, 0; super) +end +class PrependedHash < Hash; prepend PrependEach; end +module RefineEach + refine Hash do + def each = yield(:refined, 0) + end +end + +METHODS.each do |name, m| + t("#{name} empty") { m.({}) { |k, v| v } } + t("#{name} one") { m.({ z: 9 }) { |k, v| [v] } } + t("#{name} subclass") { m.(SubHash[h]) { |k, v| [v] } } + t("#{name} subclass with its own #each") { m.(OwnEach[h]) { |k, v| [v.to_s] } } + t("#{name} a prepended #each") { m.(PrependedHash[h]) { |k, v| [v] } } + t("#{name} a singleton #each") do + x = h + def x.each = yield(:single, 5) + m.(x) { |k, v| [v] } + end + t("#{name} compare_by_identity") { x = {}.compare_by_identity; x["a".dup] = 2; x["a".dup] = 1; m.(x) { |k, v| [v] } } + t("#{name} default proc not called") { x = Hash.new { |hh, k| raise "default #{k}" }; x[:q] = 1; m.(x) { |k, v| [v] } } + t("#{name} nil keys and values") { m.({ nil => nil, 1 => 2 }) { |k, v| [v.to_i] } } + t("#{name} frozen") { m.(h.freeze) { |k, v| [v] } } + t("#{name} adding a key in the block") { x = h; m.(x) { |k, v| x[:"n#{v}"] = 0; [v] } } + t("#{name} deleting a later key") { x = h; m.(x) { |k, v| x.delete(:c); [v] } } + t("#{name} replacing a later value") { x = h; m.(x) { |k, v| x[:c] = 7; [v] } } + t("#{name} break") { m.(h) { |k, v| break [:broke, k] if v == 1; [v] } } + t("#{name} next") { m.(h) { |k, v| next [-v] } } + t("#{name} raise, frames") do + m.(h) { raise "x" } + rescue => e + e.backtrace_locations.first(3).map(&:label) + end + t("#{name} throw") { catch(:t) { m.(h) { |k, v| throw :t, k } } } +end +using RefineEach +t('min_by under a refined Hash#each') { h.min_by { |k, v| v } } +t('sort_by under a refined Hash#each') { h.sort_by { |k, v| v } } +t('flat_map under a refined Hash#each') { h.flat_map { |k, v| [v] } } + +# ---------------------------------------------------------------- 3. Hash#each redefined, then restored +t('a redefined Hash#each') do + class Hash; alias __saved_each__ each; def each = yield(:redef, 4); end + begin + [h.min_by { |k, v| v }, h.sort_by { |k, v| v }, h.filter_map { |k, v| v }, h.flat_map { |k, v| [v] }] + ensure + class Hash; alias each __saved_each__; remove_method :__saved_each__; end + end +end +t('restored') { [h.min_by { |k, v| v }, h.sort_by { |k, v| v }, h.filter_map { |k, v| v }] } +t('Hash#each aliased to each_pair\'s body') do + class Hash; alias __saved_each__ each; alias each each_pair; end + begin + h.max_by { |k, v| v } + ensure + class Hash; alias each __saved_each__; remove_method :__saved_each__; end + end +end + +# ---------------------------------------------------------------- 4. answers +t('flat_map answers: to_ary, nil, a bad to_ary') do + o = Object.new; def o.to_ary = [:t] + bad = Object.new; def bad.to_ary = :no + [h.flat_map { |k, v| v == 1 ? o : nil }, (h.flat_map { |k, v| bad } rescue $!.class)] +end +t('min_by keys that do not compare') { h.min_by { |k, v| v == 1 ? "s" : v } } +t('max_by NaN key') { h.max_by { |k, v| v == 2 ? Float::NAN : v.to_f } } +t('min_by ties: the first') { { a: 1, b: 1 }.min_by { 0 } } +t('max_by ties: the first') { { a: 1, b: 1 }.max_by { 0 } } +t('no block: enumerator sizes') { [h.min_by.size, h.sort_by.size, h.filter_map.size, h.flat_map.size, h.max_by(2).size] } +t('enumerator, then each') { h.min_by.each { |k, v| v } } From e9a8a9e38e776ffb62fd6425b8c2560cc68b77eb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:33:34 +0000 Subject: [PATCH 231/439] Ledger: perf/hashwalk landed (clock only, not gated) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e09249ccc..017bae81f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1797,6 +1797,24 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/hashwalk (/perf-core, 2026-11-27, on 52f4f22) - the prelude's Enumerable methods + walk a plain Hash with a one-value block (`__plain_each__?`, `IR_HASH_WALK`)** - clock only, + not gated. The lever perf/hsortby named: filter_map, min_by, max_by, sort_by, min_by(n), + max_by(n), flat_map and collect_concat walked a Hash with `|*values|` and __enum_item__, + though Hash#each yields one [key, value] pair per entry to that block and to `|item|` alike. + A Hash whose #each resolves to the built-in one now takes the Array's one-value walk. + - Clock (`ab.rb`, four rounds, ns, unchanged / this; the switch off equal to unchanged): + Hash `min_by` 1348 -> 999 (0.74; CRuby 650), `max_by` 0.73, `filter_map` 962 -> 772 + (0.80), `flat_map` 1544 -> 1276 (0.83), `sort_by` 1905 -> 1678 (0.88), `min_by(2)` 2075 -> + 1792 (0.86); the Array rows within the noise. + - `Util/hash-walk-matrix.rb` (new) prints the unchanged build's output (CRuby's but for two + tie orders of `min_by(2)`/`max_by(2)`, as before) in five modes, with the switch off and + R2R; sort-by, enum, enumerable2, the hash matrices, callable-parameters, caller and + hot-shapes unchanged; ruby/spec core/hash, core/enumerable the same examples. + - Left: Hash#sum (2.7x CRuby) and #each_with_object, #group_by, #uniq, #inject keep the + generic walk: their bodies are long and written once against `|*values|`; a second body + per method is the price of the same trick there. Hash#any? (3.8x) is C#, /perf-step's. + - **perf/arymin (/perf-step, 2026-11-27, on ed49c52) - `Array#take` is Array's own, as MRI's `rb_ary_take`** - clock only, not gated. Array inherited Enumerable's C# take, a walk of #each through a Proc: `[1, 2, 3, 4].take(2)` 248.0 -> 83.1 ns (CRuby 71.5), `first_n`, `min`, From 4095179838f9fdc2980cd1dca1afae6e566a8c56 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:34:00 +0000 Subject: [PATCH 232/439] A call with a block in a light frame with narrow literals takes the light site In a light body with literal blocks every call with a block went through the full site with the scope made on demand (LightScopeCall: `!BlockLiterals'), so `return nb(&P) if a; nb { }' made a scope on a path that never reaches the literal. When every literal of the body is of the narrow shape (MethodDefinition.HasOnlyNarrowLiterals: no enclosing local, return, yield, super, nested literal, lambda, def or class body, and no call of binding, eval, local_variables, __method__, __callee__, block_given?, iterator?), such a call now takes the HasLightScope site as in a body without literals, LightScopeRequired sending it to the full site with the scope as before. A literal's Proc is still made over the scope made on demand. IR_LIGHT_LITERAL_CALLS=0 is the old code. `nbx' 100 -> 56 ns (CRuby 44), 208 -> 24 bytes a call with parking off; `nb { }' and `a.each { }' unchanged: where the literal runs its Proc makes the scope anyway, so the full site was not the literal's cost (Docs/light-frame-literal-blocks.md, "What A measured"). Util/literal-block-light-matrix.rb (new) and twelve block and frame matrices print CRuby's output in seven modes and with the switch off; ruby/spec language/block, proc, return and core/proc pass; IronRuby.Tests in Debug as the baseline, but for one fiber/thread test that failed under load and passes alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Docs/light-frame-literal-blocks.md | 21 ++- .../Ast/Definitions/MethodDefinition.cs | 82 ++++++++- Util/literal-block-light-matrix.rb | 169 ++++++++++++++++++ Util/perf/LEDGER.md | 34 ++++ 4 files changed, 304 insertions(+), 2 deletions(-) create mode 100644 Util/literal-block-light-matrix.rb diff --git a/Docs/light-frame-literal-blocks.md b/Docs/light-frame-literal-blocks.md index ce8092cbe..a3b76e756 100644 --- a/Docs/light-frame-literal-blocks.md +++ b/Docs/light-frame-literal-blocks.md @@ -1,6 +1,7 @@ # A literal block in a light frame: what it costs, and a Proc without a method scope -Status: measured and designed in round thirty-seven (perf/lazyproc), not built. It is the remainder of +Status: measured and designed in round thirty-seven (perf/lazyproc); change A built in perf/literalsite +(`IR_LIGHT_LITERAL_CALLS`, on), which also attributed the cost - see "What A measured" below. B is not built. It is the remainder of gap 13 of `Util/perf/LEDGER.md` (the fixed cost of calling an iterator) and a case of gap 16 (a light frame that ends up making its scope). @@ -38,6 +39,24 @@ parking, `IR_PARKED_SCOPES=0`, costs the same). The first job of an attempt is t profile on a host with perf, or the sequence the body emits timed piece by piece in C# - because it decides which of the two steps below is worth building. +## What A measured (perf/literalsite) + +Built as designed below, for bodies whose literals are all of the narrow shape +(`MethodDefinition.HasOnlyNarrowLiterals`), alternating rounds against the switch off and CRuby: + +| shape | switch off | A | CRuby | +|---|---|---|---| +| `nbx`: `return nb(&P) if a; nb { }` | 100 | 56 | 44 | +| `nbp`: `nb(&P)` (no literal) | 56 | 56 | 40 | +| `nbl`: `nb { }` | 118 | 114 (overlapping) | 36 | +| `eachl`, `each1`, `times1`, `map1` | 138, 159, 164, 167 | 140, 162, 157, 172 (overlapping) | 68, 79, 93, 111 | + +So **the full site costs about nothing**: where the literal runs, its Proc makes the scope anyway and A +changes nothing (`nbl`); where it does not, A takes the whole 45 ns (`nbx` falls to `nbp`), because the call +no longer makes the scope (208 -> 24 bytes a call with parking off). The 45 ns is the scope being made and +published: the object, `LeaveLightMethodFrameSlow`, the parking around it. That is B's ground, and B is +what the literal's own cost (`nbl`, `each1`) needs. + ## How a literal reaches its method today - **The method's locals.** A light body's locals are in the tuple the scope made on demand wraps diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 33dde4d81..70e99d6b7 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -519,6 +519,12 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// internal static readonly bool LightBlockPassEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_BLOCK_PASS") != "0"; + /// + /// IR_LIGHT_LITERAL_CALLS=0 sends every call with a block in a light frame whose body has literal blocks through the full + /// site with the scope made on demand, as before round thirty-seven (see NarrowLiterals, LightFrameRewriter.LiteralCalls). + /// + internal static readonly bool LightLiteralCallsEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_LITERAL_CALLS") != "0"; + /// /// IR_LIGHT_SPLAT=0 keeps every method that splats a value (`inner(*args)', `[*a]', `yield(*a)') out of light frames /// (see IsScopeFree and LightFrameRewriter.VisitExtension). @@ -993,6 +999,72 @@ private bool HasLightBlockLiteral() { return !IsBodyScopeFree(false); } + /// + /// Every literal block of the body is of the narrow shape (Docs/light-frame-literal-blocks.md): it reads and writes no + /// local of an enclosing scope, has no return, yield, super, nested literal or lambda, and calls none of the Kernel + /// methods that reach for the frame (binding, eval, local_variables, __method__, __callee__, block_given?, iterator?). + /// Its Proc is still made over the frame's scope, made on demand, so a callee that keeps it, a binding taken through + /// send and a TracePoint find the method's scope as before; what the shape keeps out is a literal whose own code would + /// reach the frame through the scope its call no longer makes. + /// + private bool HasOnlyNarrowLiterals() { + var checker = new NarrowLiteralChecker(); + checker.Walk(Body); + return checker.Literals > 0 && !checker.Wide; + } + + private sealed class NarrowLiteralChecker : Walker { + internal bool Wide; + internal int Literals; + private int _inBlock; + private int _blockDepth; + + private static readonly System.Collections.Generic.HashSet FrameMethods = new System.Collections.Generic.HashSet { + "binding", "eval", "local_variables", "__method__", "__callee__", "block_given?", "iterator?", + }; + + public override bool Enter(BlockDefinition/*!*/ node) { + Literals++; + if (_inBlock > 0) { + Wide = true; + return false; + } + _inBlock++; + _blockDepth = node.DefinedScope.Depth; + return true; + } + + public override void Exit(BlockDefinition/*!*/ node) { + _inBlock--; + } + + public override bool Enter(LambdaDefinition/*!*/ node) { Wide = true; return false; } + public override bool Enter(MethodDefinition/*!*/ node) { Wide = true; return false; } + public override bool Enter(ClassDefinition/*!*/ node) { Wide = true; return false; } + public override bool Enter(ModuleDefinition/*!*/ node) { Wide = true; return false; } + public override bool Enter(SingletonDefinition/*!*/ node) { Wide = true; return false; } + + public override bool Enter(LocalVariable/*!*/ node) { + if (_inBlock > 0 && node.DefinitionLexicalDepth < _blockDepth) { Wide = true; } + return true; + } + + public override bool Enter(ReturnStatement/*!*/ node) { if (_inBlock > 0) { Wide = true; } return true; } + public override bool Enter(YieldCall/*!*/ node) { if (_inBlock > 0) { Wide = true; } return true; } + // (the walker does not visit a call's block: Walker.Walk(MethodCall) leaves it to whoever asks) + public override bool Enter(SuperCall/*!*/ node) { + if (_inBlock > 0) { Wide = true; } + if (node.Block != null) { node.Block.Walk(this); } + return true; + } + + public override bool Enter(MethodCall/*!*/ node) { + if (_inBlock > 0 && node.Target == null && FrameMethods.Contains(node.MethodName)) { Wide = true; } + if (node.Block != null) { node.Block.Walk(this); } + return true; + } + } + // Declares keyword parameters, a `**rest' or `**nil'. Not `...', whose signature says `**' but whose lowering is a // rest and a block parameter and no keyword prologue (Parameters.ForwardsArguments): what a light frame takes as // `def m(*a, &b)'. The keyword hash a call passes is bound into the rest by the method's RubyMethodInfo, whatever @@ -1609,6 +1681,7 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ var rewriter = new LightFrameRewriter(scopeVariable, light.LazyScope, light.Rfc, declaringScope, inLoop, HasBlockGuard) { BlockLiterals = LightBlocksEnabled && HasLightBlockLiteral(), + LiteralCalls = LightLiteralCallsEnabled && LightBlockPassEnabled && HasOnlyNarrowLiterals(), BlockParameter = LightBlockGivenEnabled ? blockParameter : null, SuperModule = LightSuperEnabled ? ConstantValue(declaringModule) as RubyModule : null, SuperName = _name, @@ -1671,6 +1744,13 @@ internal sealed class LightFrameRewriter : MSA.ExpressionVisitor { // used), self, block and flow-control frame, which is all the block and the call read from it. internal bool BlockLiterals; + // Every literal of the body is of the narrow shape (MethodDefinition.HasOnlyNarrowLiterals): a call with a block takes + // the light site as in a body without literals (LightScopeCall), the literal's Proc, made over the scope made on + // demand, being its block argument like any other; a rule that reads the caller's scope answers LightScopeRequired and + // the call is made again through the full site with that scope. It is the call that no longer makes the scope, not + // the literal: a literal's instantiation still does. + internal bool LiteralCalls; + // see LightFrame.MakesCalls internal bool MakesCalls; @@ -2136,7 +2216,7 @@ private MSA.Expression LightScopeCall(Microsoft.Scripting.Ast.LightDynamicExpres // blocks, whose calls use the scope made on demand (BlockLiterals). The Proc is an argument like the others: the // rules bind it as a block parameter whatever scope they are given, and one that reads the caller's scope answers // RubyOps.LightScopeRequired as for any call. - bool blockPass = signature.HasBlock && LightBlockPassEnabled && !BlockLiterals && _rfc != null; + bool blockPass = signature.HasBlock && LightBlockPassEnabled && (!BlockLiterals || LiteralCalls) && _rfc != null; if (!signature.HasScope || signature.HasBlock && !blockPass || signature.ResolveOnly || signature.IsSuperCall || signature.IsVirtualCall || signature.IsInteropCall || signature.HasLightScope) { return null; diff --git a/Util/literal-block-light-matrix.rb b/Util/literal-block-light-matrix.rb new file mode 100644 index 000000000..625d1680e --- /dev/null +++ b/Util/literal-block-light-matrix.rb @@ -0,0 +1,169 @@ +# Differential matrix for calls with a block in a light frame whose body has literal blocks (round thirty-seven, +# perf/literalsite; Docs/light-frame-literal-blocks.md, change A). In such a body a call with a block went through the +# full site with the scope made on demand (LightFrameRewriter.LightScopeCall: `!BlockLiterals'); with +# IR_LIGHT_LITERAL_CALLS on, when every literal of the body is of the narrow shape - it reads and writes no enclosing +# local, has no return, yield, super, nested literal, and calls none of binding, eval, local_variables, __method__ - the +# call takes the light site, and the full one only when its rule answers LightScopeRequired. Run it under CRuby and +# under ./ir.sh with the switch on and off, and diff: +# +# ruby Util/literal-block-light-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/literal-block-light-matrix.rb > /tmp/on.txt +# IR_LIGHT_LITERAL_CALLS=0 ./ir.sh Util/literal-block-light-matrix.rb > /tmp/off.txt +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt +# +# Every probe runs N times and reports each distinct answer once, so the interpreted body, the compiled one and a site +# whose rule is already bound all meet the case. +# +# IR_LIGHT_FRAMES=why ./ir.sh Util/literal-block-light-matrix.rb 2>&1 >/dev/null | grep -a '^\[light\]' + +N = 3000 + +def t(label) + print label.ljust(58), ' => ' + seen = [] + begin + N.times do |i| + v = yield i + seen << v unless seen.include?(v) + end + puts seen.map(&:inspect).join(', ') + rescue Exception => e + puts "#{seen.map(&:inspect).join(', ')} then #{e.class}: #{e.message[0, 60]}" + end +end + +P0 = proc { :p0 } + +class C + def nb = (block_given? ? yield : :none) + def nb2(x) = (block_given? ? yield(x) : :none) + def keep(&b) = (@kept = b; :kept) + attr_reader :kept + def run_kept = @kept.call + def kept_binding_names = @kept.binding.local_variables.sort + def priv_target = :priv + private :priv_target + def m_missing_target; end + + # ---- the narrow shape: literals that read no enclosing local + def lit(a) = nb { :lit } + def lit_x(a) = nb2(a) { |x| x * 2 } + def pass_in_lit_body(a); return nb(&P0) if a; nb { :never }; end + def plain_in_lit_body(a); return nb if a; nb { :never }; end + def each_lit(a) = a.each { |x| x }.size + def map_lit(a) = a.map { |x| x + 1 } + def times_lit(n); n.times { }; n; end + def two_lits(a) = [nb { 1 }, nb2(a) { |x| x }] + def lit_and_pass(a, b) = [nb { :l }, nb(&b)] + + # ---- the literal escapes from the callee + def lit_kept(a); keep { :from_kept }; run_kept; end + def lit_kept_later(a); keep { a.class }; :ok; end + def lit_define(a); C.send(:define_method, :defined_by_lit) { :d }; defined_by_lit; end + def lit_proc_new(a) = Kernel.proc { :pn }.call + def lit_lambda(a) = lambda { |x| x }.lambda? + def lit_kept_binding(a); x = 1; keep { :k }; [x, kept_binding_names]; end + + # ---- break, next, raise from the literal + def lit_break(a) = nb { break :broke } + def lit_break_ensure(a) + r = nb { break :broke_e } + r + ensure + @ensured = true + end + attr_reader :ensured + def lit_next(a) = nb { next :nexted } + def lit_raise(a) = (nb { raise ArgumentError, "in lit" } rescue $!.message) + def lit_throw(a) = catch(:t) { nb { throw :t, :thrown } } + + # ---- the callee reaches for the caller's scope + def lit_to_binding_callee(a) = nb2(binding) { |b| b.local_variables.sort } + def lit_send_binding(a) = nb { send(:binding).local_variables.sort } + def lit_local_variables_method(a); y = 5; nb { :x }; local_variables.sort; end + def lit_method_name(a); nb { :x }; __method__; end + def lit_match(a); nb { "abc".send(:=~, /b/) }; $~ && $~[0]; end + def lit_eval_method(a); z = 3; nb { :x }; eval("z + 1"); end + def lit_private(a) = nb { priv_target } + def lit_respond(a) = nb { respond_to?(:priv_target) } + def lit_block_given(a) = [nb { block_given? }, block_given?] + + # ---- re-entrancy and recursion + def lit_recurse(n) = (n == 0 ? :bottom : nb { lit_recurse(n - 1) }) + def lit_reenter(a) = nb { a ? lit_reenter(false) : :inner } + + # ---- literals that are not of the narrow shape: the body keeps the full site + def wide_local(a); s = 0; nb { s += 1 }; s; end + def wide_return(a); nb { return :ret }; :after; end + def wide_yield(a) = nb { yield } + def wide_binding(a); q = 1; nb { binding.local_variable_get(:q) }; end + def wide_nested(a) = nb { nb { :nested } } + def wide_pass(a); s = 0; nb { s += 1 }; nb(&P0); end +end + +c = C.new + +puts "# 1. the narrow shape" +t("lit") { c.lit(1) } +t("lit_x") { |i| c.lit_x(i % 3) } +t("pass_in_lit_body") { c.pass_in_lit_body(true) } +t("pass_in_lit_body false") { c.pass_in_lit_body(false) } +t("plain_in_lit_body") { c.plain_in_lit_body(true) } +t("each_lit") { c.each_lit([1, 2, 3]) } +t("map_lit") { c.map_lit([1, 2]) } +t("times_lit") { c.times_lit(2) } +t("two_lits") { c.two_lits(:a) } +t("lit_and_pass") { c.lit_and_pass(1, proc { :b }) } + +puts "# 2. escape" +t("lit_kept") { c.lit_kept(1) } +t("lit_kept_later") { |i| c.lit_kept_later(i.odd? ? 1 : "s"); c.run_kept } +t("lit_define") { c.lit_define(1) } +t("lit_proc_new") { c.lit_proc_new(1) } +t("lit_lambda") { c.lit_lambda(1) } +t("lit_kept_binding") { c.lit_kept_binding(1) } + +puts "# 3. break, next, raise" +t("lit_break") { c.lit_break(1) } +t("lit_break_ensure") { [c.lit_break_ensure(1), c.ensured] } +t("lit_next") { c.lit_next(1) } +t("lit_raise") { c.lit_raise(1) } +t("lit_throw") { c.lit_throw(1) } + +puts "# 4. the scope reached for" +t("lit_to_binding_callee") { c.lit_to_binding_callee(1) } +t("lit_send_binding") { c.lit_send_binding(1) } +t("lit_local_variables_method"){ c.lit_local_variables_method(1) } +t("lit_method_name") { c.lit_method_name(1) } +t("lit_match") { c.lit_match(1) } +t("lit_eval_method") { c.lit_eval_method(1) } +t("lit_private") { c.lit_private(1) } +t("lit_respond") { c.lit_respond(1) } +t("lit_block_given") { c.lit_block_given(1) } + +puts "# 5. re-entrancy, threads" +t("lit_recurse") { c.lit_recurse(3) } +t("lit_reenter") { c.lit_reenter(true) } +t("threads") { |i| i % 300 == 0 ? 4.times.map { |k| Thread.new { lt_r = []; 50.times { lt_r << c.lit_x(k) }; lt_r.uniq } }.map(&:value) : :skip } + +puts "# 6. not the narrow shape" +t("wide_local") { c.wide_local(1) } +t("wide_return") { c.wide_return(1) } +t("wide_yield") { c.wide_yield(1) { :y } } +t("wide_binding") { c.wide_binding(1) } +t("wide_nested") { c.wide_nested(1) } +t("wide_pass") { c.wide_pass(1) } + +puts "# 7. tracing" +ev = [] +tp = TracePoint.new(:call, :b_call, :c_call) { |x| ev << [x.event, x.method_id] if x.path == __FILE__ && [:lit, :nb, :pass_in_lit_body].include?(x.method_id) } +tp.enable +3.times { c.lit(1); c.pass_in_lit_body(true) } +tp.disable +p ev.uniq +bl = [] +tp = TracePoint.new(:b_call) { |x| bl << x.binding.local_variables.sort if x.path == __FILE__ && x.lineno == C.instance_method(:lit_x).source_location[1] } +tp.enable +c.lit_x(4) +tp.disable +p bl diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a6d449b34..43cf9bb74 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1180,6 +1180,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has site; B, its Proc's scope made but not published as the frame's (no slow exit, no parking, the frame's calls still light), with one scope per invocation and the frame's exit marking it left when the Proc escaped. + perf/literalsite (see Landed, not gated) built A and with it the attribution: where the + literal runs, its Proc makes the scope anyway and A changes nothing (`nbl` 118 -> 114, + overlapping); where it does not, A takes the whole 45 ns (`nbx` 100 -> 56, `nbp`'s 56). So + the full site costs about nothing, and the literal's own ~60 ns is the scope made and + published (the object, `LeaveLightMethodFrameSlow`, the parking around it) plus the Proc: + change B is what is left for `nb { }` and `a.each { }`. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per @@ -1916,6 +1922,34 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/literalsite (round thirty-seven, 2026-11-27) - a call with a block in a light frame whose + literals are all narrow takes the light site (gaps 16 and 13)** - instructions not counted, time and + bytes, not gated. Change A of `Docs/light-frame-literal-blocks.md`. In a light body with literal blocks + every call with a block took the full site with the scope made on demand (`blockPass = ... && + !BlockLiterals`), so `return nb(&P) if a; nb { }` made a scope on the hot path, which never reaches the + literal. Now, when every literal of the body is of the narrow shape (`HasOnlyNarrowLiterals`: no + enclosing local read or written, no return, yield, super, nested literal, lambda, def or class body, + no call of binding, eval, local_variables, __method__, __callee__, block_given?, iterator? - the AST + walker does not visit a call's block, so the checker walks it), such a call takes the `HasLightScope` + site as in a body without literals, with LightScopeRequired sending it to the full site with the scope + as before; a literal's Proc is still made over the scope made on demand. `IR_LIGHT_LITERAL_CALLS=0` is + the old code. Six alternating rounds against the switch off, ns per call: `nbx` 100 -> 56 (CRuby 44), + `nbp` 56 -> 56, `nby` 52 -> 48, `nbl` 118 -> 114, `eachl` 138 -> 140, `each1` 159 -> 162, `times1` 164 -> + 157, `map1` 167 -> 172, `call` 59 -> 60 (all but `nbx` overlapping); bytes a call with parking off, `nbx` + 208 -> 24. What it measured is the point (see gap 16): the full site is not where a literal's cost is. + Checked: `Util/literal-block-light-matrix.rb` (new: the narrow shape to a light method, each, times, + map; escape through `&b` kept and called after the method returned, `define_method`, `Kernel.proc`, + `lambda`, the kept Proc's `binding.local_variables`; break with an ensure, next, raise, throw; the + callee taking `binding`, `send(:binding)` in the literal, `local_variables`, `__method__`, `$~` set + through `send`, `eval` in the method, a private callee, `block_given?`; recursion, re-entrancy, four + threads; six bodies that are not of the shape; TracePoint `:call`/`:b_call`/`:c_call` and a `:b_call` + binding) with CRuby's output on both builds and with the switch off; with it block-pass, block-given, + parked-scope, block-scope-reuse (three), block-nest-reuse, light-entry, light-rest, parked-iterator, + hot-shapes and jit in the seven modes and the switch off: PASS, 91 same. ruby/spec language/block, + proc, return and core/proc: 496 examples, no failure on either build. IronRuby.Tests in full on a + Debug build: one failure, `Fiber_ThreadRaiseInSwitchBookkeeping1`, run while the specs loaded the + host; alone it passed five times of five (three of three on the baseline). + - **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, perf/twospeed and its note, perf/extiter4 and 5, perf/fiberstart, perf/iter, perf/strsearch3 and 4, From 540bdb0823df8abc9f05044cfeec514314287295 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:34:18 +0000 Subject: [PATCH 233/439] case over Symbol literals is not looked up as one over Strings perf/json's CaseStringSite took a case whose whens were all String literals, tested with `comparison as StringLiteral'; a SymbolLiteral is a StringLiteral in the AST, so `case "all" when :all' ran the :all arm. Matrix#each("all") returned instead of raising ArgumentError (three library/matrix specs failed in round 6's gate sweep). CRuby: :all === "all" is false. Symbol literals are now refused, as the method JIT's case already did (it tests for a Symbol first). case-string-matrix only met the bug's path on a method's first, uncompiled calls before any refinement existed, which its rows never did; its new Symbol section calls each subject on a fresh method once, then warm, and prints CRuby's output on the fix (the unfixed build differs in two rows). CaseEquals4 is the same check as a test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/CaseEqualsTests.cs | 17 +++++++++++++++++ .../Compiler/Ast/Expressions/CaseExpression.cs | 3 ++- Util/case-string-matrix.rb | 15 +++++++++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fd1166bce..0323816f0 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -558,6 +558,7 @@ public Tests(Driver/*!*/ driver) { CaseEquals1, CaseEquals2, CaseEquals3, + CaseEquals4, ComparableEqual1, Hooks1, Hooks2, diff --git a/Src/IronRuby.Tests/Runtime/CaseEqualsTests.cs b/Src/IronRuby.Tests/Runtime/CaseEqualsTests.cs index c874d7b6e..66e85affd 100644 --- a/Src/IronRuby.Tests/Runtime/CaseEqualsTests.cs +++ b/Src/IronRuby.Tests/Runtime/CaseEqualsTests.cs @@ -208,6 +208,23 @@ public void Kernel_IsAModuleRequired1() { true true false +"); + } + + /// + /// A `case' whose `when's are Symbol literals is not one over Strings: a SymbolLiteral is a StringLiteral in the AST, and + /// CaseExpression's String dispatch (CaseStringSite) took `when :all' for `when "all"', so `case "all"' ran the :all arm + /// (Matrix#each("all") returned instead of raising ArgumentError; round 6's gate). The answers are CRuby's. + /// + public void CaseEquals4() { + TestOutput(@" +def k(c) = (case c when :all then 1 when :diagonal then 2 else :none end) +def m(c) = (case c when :all then 1 when 'all' then 2 else :none end) +r = nil +50.times { r = [k(:all), k('all'), k('diagonal'), k(nil), m(:all), m('all'), m('x')] } +p r +", @" +[1, :none, :none, :none, 1, 2, :none] "); } } diff --git a/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs index 46f70f8d6..d2cf07118 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs @@ -147,8 +147,9 @@ private CaseStringSite TryMakeStringDispatch() { return null; } foreach (var comparison in _whenClauses[i].Comparisons) { + // a SymbolLiteral is a StringLiteral too, and `:all === "all"' is false: Strings only var literal = comparison as StringLiteral; - if (literal == null) { + if (literal == null || literal is SymbolLiteral) { return null; } var str = literal.GetMutableString(); diff --git a/Util/case-string-matrix.rb b/Util/case-string-matrix.rb index 757bbaad3..fd72d947e 100644 --- a/Util/case-string-matrix.rb +++ b/Util/case-string-matrix.rb @@ -86,6 +86,21 @@ def no_value_case(c) CASES = %i[value_case value_case_declined multi_case dup_case mixed_case no_value_case] +# A `when' of Symbol literals is no String literal (a SymbolLiteral is a StringLiteral in the AST): `:all === "all"' is +# false, and the case is not looked up as one over Strings (round 6's gate: Matrix#each("all") ran the :all arm). Before any refinement exists: the +# dispatch stands aside while the runtime has one. +def symbol_case(c) = (case c when :all then 1 when :diagonal then 2 else :none end) +def symbol_string_case(c) = (case c when :all then 1 when "all" then 2 else :none end) +puts "== Symbol whens" +# each subject on a method of its own, called once (the generic code's dispatch; a warm method is the JIT's), then warm +SUBJECTS.merge(sym_all: :all, str_all: "all", str_diagonal: "diagonal").each_with_index do |(name, s), i| + eval "def sc_#{i}(c) = (case c when :all then 1 when :diagonal then 2 else :none end)" + eval "def ssc_#{i}(c) = (case c when :all then 1 when 'all' then 2 else :none end)" + cold = [(send(:"sc_#{i}", s) rescue $!.class), (send(:"ssc_#{i}", s) rescue $!.class)] + warm = [(30.times.map { symbol_case(s) }.uniq.inspect rescue $!.class), (30.times.map { symbol_string_case(s) }.uniq.inspect rescue $!.class)] + puts "#{name}\tcold #{cold.inspect}\twarm #{warm.inspect}" +end + def run(label) puts "== #{label}" SUBJECTS.each do |name, s| From 16676d9bcf0231e866f6b0dfac2046368b28ba84 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:36:57 +0000 Subject: [PATCH 234/439] round/floor/ceil/truncate: Float digits convert as MRI's rb_num2int The digits argument goes through rb_num2int: a Float becomes a long first, so NaN and a Float beyond the long range are "float NaN out of range of integer" (RangeError), and one that is a long but not an int is "integer 3000000000 too big to convert to 'int'" (or "too small"). IronRuby raised FloatDomainError for NaN and the float message for anything beyond an int. Float_RoundDigitsRange1 holds CRuby's output; the Float, Integer and Rational round/floor/ceil/truncate specs pass, as do the round, float and rational IronRuby.Tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 34 +++++++++++++++++++++ Src/Libraries/Extensions/NumericRounding.cs | 13 +++++--- 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0f463887a..949425ca4 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1169,6 +1169,7 @@ public Tests(Driver/*!*/ driver) { TracePoint_EndlessDefLine1, TracePoint_AttrAccessorCCall1, Float_OutOfRangeMessage1, + Float_RoundDigitsRange1, Defined_ConditionNoFreeze1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index e9153c727..f9c8033da 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -9309,6 +9309,40 @@ def t(l) "); } + /// + /// round, floor, ceil and truncate convert Float digits as MRI's rb_num2int does: to a long first (NaN and huge + /// values: "float ... out of range of integer"), then to an int ("integer 3000000000 too big to convert to 'int'"). + /// + public void Float_RoundDigitsRange1() { + TestOutput(@" +require 'ruby4' +def t(l) + p [l, yield] +rescue => e + p [l, e.class, e.message] +end +t(:f_big) { 1.5.round(1e30) } +t(:f_neg) { 1.5.round(-3e9) } +t(:f_nan) { 1.5.round(0.0 / 0) } +t(:i_big) { 1.round(3e9) } +t(:floor) { 1.5.floor(3e9) } +t(:ceil) { 1.5.ceil(-2147483649.5) } +t(:ok) { 1.25.round(1.9) } +t(:trunc) { 12.5.truncate(-1.5) } +t(:rational) { Rational(3, 2).round(3e9) } +", @" +[:f_big, RangeError, ""float 1e+30 out of range of integer""] +[:f_neg, RangeError, ""integer -3000000000 too small to convert to 'int'""] +[:f_nan, RangeError, ""float NaN out of range of integer""] +[:i_big, RangeError, ""integer 3000000000 too big to convert to 'int'""] +[:floor, RangeError, ""integer 3000000000 too big to convert to 'int'""] +[:ceil, RangeError, ""integer -2147483649 too small to convert to 'int'""] +[:ok, 1.3] +[:trunc, 10] +[:rational, TypeError, ""not an integer""] +"); + } + /// /// The expression of an endless def is not a line to TracePoint :line (prism gives it no newline flag): CRuby reports /// no event for it, with or without a rescue modifier, but does for statements in parentheses in it and in a block. diff --git a/Src/Libraries/Extensions/NumericRounding.cs b/Src/Libraries/Extensions/NumericRounding.cs index 97c242816..52ac76b20 100644 --- a/Src/Libraries/Extensions/NumericRounding.cs +++ b/Src/Libraries/Extensions/NumericRounding.cs @@ -95,13 +95,16 @@ internal static int GetNDigits(ConversionStorage/*!*/ integerCast, if (ndigits is double) { double d = (double)ndigits; - if (Double.IsNaN(d)) { - throw new FloatDomainError("NaN"); - } - if (d >= 2147483648.0 || d <= -2147483649.0) { + // rb_num2int of a Float: to a long first ("float NaN out of range of integer"), then to an int + // ("integer 3000000000 too big to convert to 'int'") + if (Double.IsNaN(d) || d >= 9223372036854775808.0 || d < -9223372036854775808.0) { throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(d))); } - return (int)d; + long whole = (long)d; + if (whole > Int32.MaxValue || whole < Int32.MinValue) { + throw RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", whole, whole < 0 ? "small" : "big")); + } + return (int)whole; } IntegerValue value = Protocols.CastToInteger(integerCast, ndigits); From 7f88cdb941500763ece4cd592d40d77a8f17472c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:37:23 +0000 Subject: [PATCH 235/439] JIT: CD's Node#successor compiles; a body bound to a recompiled callee recompiles Node#successor (`x = self ... while y && x == y.right`) was declined at "== on a receiver of unknown type". A local whose first value is self now samples self, as one from a local or an instance variable does, and the ==/equal? decision takes a method local for an object of a Ruby class when its sample is one or an unsampled attribute access or inlined call on it compiled. It emits IsIdentical, which checks the receiver's == and deopts where it is not BasicObject's. Since perf/havlak2 compiled RedBlackTree#get, which calls find_node's typed body directly, CD retired get eight times in three iterations and then for good: find_node was compiled for one key class, later for both, and get kept the first body, being only put back after each cool-down. JitCode.BoundCallees records the callee specializations a body bound, and CoolDownCheck compiles the body again when one is no longer current. CD: successor specialized, retirements 8 -> 0; the other benchmarks make the same decisions and all verify; census unchanged. Callgrind new/base: successor 0.769, phases 0.946, get and put of a new key 1.000 (put of an existing key 1.000 alone; in the full file the recompile's timers land in its sections). AWFY, ten processes per build: CD 0.996, DeltaBlue 0.980, Havlak 1.002, Richards 1.001, within their spread. unsampled-matrix grows to 39 cases and prints CRuby's output on both builds in every mode; jit-construct, jit, jit-calls, jit-const, ivar, hot-shapes, deadconst and inline are unchanged; the def, Class.new and equality specs pass; the whole IronRuby.Tests suite passes on a Debug build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5NtGd2eCVJ7fCeWbG --- Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs | 1 + Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 26 ++- Src/Ruby/Runtime/Jit/JitCompiler.cs | 17 ++ Src/Ruby/Runtime/Jit/JitStub.cs | 33 +++- Util/bench/cdtree-shapes.rb | 169 ++++++++++++++++++++ Util/perf/LEDGER.md | 50 ++++++ Util/unsampled-matrix.rb | 125 ++++++++++++++- 7 files changed, 418 insertions(+), 3 deletions(-) create mode 100644 Util/bench/cdtree-shapes.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs index f403c7681..38a71cccf 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs @@ -73,6 +73,7 @@ private MSA.Expression TryInlineCall(MethodCall/*!*/ node, out JT type) { !JitRuntime.InlineUnsampled || !UnsampledCallees(node.MethodName, args.Length, out cls, out code, out otherCls, out otherCode)) { return null; } + NoteUnsampledObject(receiverLocal); (_unsampledClasses ?? (_unsampledClasses = new System.Collections.Generic.Dictionary()))[receiverLocal.Name] = (otherCls != null) ? new[] { cls, otherCls } : new[] { cls }; } else { diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 26c39724c..d7bef3729 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1749,7 +1749,8 @@ private bool TrySampleOfLocal(LocalVariable/*!*/ local, out object sample) { // to is as good a profile, and as above an attr read of it checks the class it finds. So is an instance // variable of self, `current = @root' before `current = current.left' (CD's RedBlackTree#find_node). var from = (_firstSources.TryGetValue(local.Name, out source) && !_singleSources.ContainsKey(local.Name)) ? source : null; - if (from is LocalVariable && ((LocalVariable)from).Name != local.Name || from is InstanceVariable) { + // (and so is self, `x = self' before `x = y' walking up a tree: CD's Node#successor) + if (from is LocalVariable && ((LocalVariable)from).Name != local.Name || from is InstanceVariable || from is SelfReference) { _sampleDepth++; try { return TrySample(from, out sample); @@ -1826,6 +1827,7 @@ private MSA.Expression EmitMethodAttrRead(MethodCall/*!*/ node, out JT type) { // and deopts unless the name is the same variable's reader there. Its value is an object. string name = UnsampledAttrVariable(target as LocalVariable, node.MethodName, false); if (name == null || CanFallBack(target)) { return null; } + NoteUnsampledObject(target as LocalVariable); JT lt; var localReceiver = Coerce(Emit(target, out lt), lt, JT.Obj); _canDeopt = true; @@ -1872,6 +1874,27 @@ private MSA.Expression EmitMethodAttrRead(MethodCall/*!*/ node, out JT type) { /// must be one (AgreedAccessorVariable). Null otherwise. Only the name is decided here: the read or write checks the class of the object it /// meets, and deopts where the accessor is not that variable's (a private one, method_missing, another class's). /// + // The locals nothing samples that an attribute of was read or written, or a call on was inlined, as an object of a Ruby + // class (UnsampledAttrVariable, UnsampledCallees): `==' on one is taken for BasicObject#== (IsLocalObject). + private HashSet _unsampledObjects; + + private void NoteUnsampledObject(LocalVariable local) { + if (local != null) { (_unsampledObjects ?? (_unsampledObjects = new HashSet())).Add(local.Name); } + } + + /// + /// A local of the method, not a parameter, that is taken to hold an object of a Ruby class: its sample is one + /// (TrySampleOfLocal), or an attribute of it was read or written or a call on it inlined on that assumption before + /// (_unsampledObjects). Only a profile: what `==' does with it checks the receiver's class (IsIdentical). + /// + private bool IsLocalObject(RExpr/*!*/ node) { + var local = node as LocalVariable; + if (local == null || local.DefinitionLexicalDepth != _scopeDepth || Array.IndexOf(_paramNames, local.Name) >= 0) { return false; } + if (_unsampledObjects != null && _unsampledObjects.Contains(local.Name)) { return true; } + object sample; + return TrySample(local, out sample) && sample is RubyObject; + } + private string UnsampledAttrVariable(LocalVariable local, string/*!*/ name, bool writer) { if (!JitRuntime.InlineUnsampled || local == null || local.DefinitionLexicalDepth != _scopeDepth || !_refinements.IsEmpty) { return null; } RubyClass[] inlinedFor; @@ -1929,6 +1952,7 @@ private static string AgreedAccessorVariable(IEnumerable/*!*/ classes sample = null; variableName = UnsampledAttrVariable(target as LocalVariable, node.Name, true); if (variableName == null) { throw Bail("attribute assignment " + node.Name + " on an unprofiled receiver"); } + NoteUnsampledObject(target as LocalVariable); } else { variableName = JitRuntime.SelfAttrSite.WriterVariable(JitRuntime.ClassOf(_context, sample), node.Name, explicitReceiver); } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index a825069ef..82f47c99f 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -51,6 +51,9 @@ private JitBailout() { } /// The result of a successful specialization. internal sealed class JitCode { + // The specializations of the callees this body calls directly, its own and theirs (EmitDirectCall): a retired body + // whose callee has been compiled again since is compiled again too, not put back (JitStub.CoolDownCheck). + internal JitStub.Specialization[] BoundCallees; internal MSA.LambdaExpression/*!*/ Lambda; internal StrongBox/*!*/ SelfCell; internal JT ReturnType; @@ -108,6 +111,8 @@ internal sealed class JitCallee { // What the caller invokes with (self, typed arguments): the typed body's delegate, as a // constant. -X:JITMethods emits a call of the method behind it (JitMethodEmitter.Lifter). internal MSA.Expression/*!*/ Target; + // the callee's specialization the body was bound from (JitStub.BindCallee) + internal JitStub.Specialization Spec; } internal sealed partial class JitCompiler { @@ -198,6 +203,8 @@ private bool _canDeopt { private bool _directCalls; // a body called directly has a loop (JitCode.HasLoop) private bool _calleeLoop; + // the specializations of the bodies called directly (JitCode.BoundCallees) + private List _boundCallees; // Explicit `return'. The label is created on the first one met, typed by the return type // the round is compiling under (_selfReturn); _returnUnion is what the values actually @@ -802,6 +809,7 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ GlobalsRead = c._globalsRead, GlobalsWritten = c._globalsWritten, DirectCalls = c._directCalls, + BoundCallees = (c._boundCallees != null) ? c._boundCallees.ToArray() : null, Inlinable = c._pure && !c._selfCall && !c._directCalls && !c._hasLoop && !c._construction && !c._ivarWrite && !c._usesConstants && !c._hashWrite && c._undoLog == null && c._arrayLoads == null && keywords == null && supplied < 0 && ast.Parameters.Optional.Length == 0 && ast.Parameters.Unsplat == null && ast.Parameters.Block == null && @@ -2574,6 +2582,10 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { // number, an Array) would deopt on every call. An instance variable is typed by the receiver // that turned the method hot (ObservedType). Type observed = ObservedType(node.Target); + // A local of the method taken to hold an object of a Ruby class (`x == y.right' in CD's Node#successor, + // x = self or a node walked to): IsIdentical checks the receiver's `==' and deopts where it is not + // BasicObject's, as for a profiled one. + if (observed == null && JitRuntime.InlineUnsampled && IsLocalObject(node.Target)) { observed = typeof(RubyObject); } if (observed == typeof(void) && node.Target is ConstantVariable && node.MethodName != "equal?" && _refinements.IsEmpty) { // `NO_WORK == x' (Richards), NO_WORK a constant whose value is nil, which the constant // version guard keeps: NilClass#== (and BasicObject#!=, which calls it) being the public @@ -2662,6 +2674,11 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { // runs them - its deopts come before its effects, or TryCompile would not have accepted // it (_deoptAfterEffect). if (code.Deopts) { _canDeopt = true; } + if (callee.Spec != null || code.BoundCallees != null) { + if (_boundCallees == null) { _boundCallees = new List(); } + if (callee.Spec != null) { _boundCallees.Add(callee.Spec); } + if (code.BoundCallees != null) { _boundCallees.AddRange(code.BoundCallees); } + } if (code.IvarWrite) { // The callee's self is this body's, so its first instance variable write is still // the first one that could meet a frozen object - unless this body has already done diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index acb6ce4de..6e0913f52 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -853,6 +853,7 @@ protected bool CoolRaised(long start) { /// the entry back once its cool-down is over. /// protected void CoolDownCheck() { + bool settled = false; lock (_sync) { if (_state != Cooling) { return; } _coolCalls = CoolCheckCalls; @@ -866,6 +867,19 @@ protected void CoolDownCheck() { _genericCostInterpreted = !_genericCompiled; } var spec = _current; + // A callee the body calls directly has been compiled again since (profiled again for a second class + // of an argument, say): the body bound the one that deopted, and would deopt again as it did. Compile + // it again instead, binding the callee's current body (RedBlackTree#get over find_node in CD). + if (HasReplacedCallee(spec)) { + if (JitRuntime.Verbose) { + Console.Error.WriteLine("[jit] profiling {0}/{1} arity {2} again: a callee it calls directly was compiled again", + _declaringModule.Name ?? "main", _ast.Name, _arity); + } + // (Respecialize drops the entry it is given, which is the one being cooled) + _state = Specialized; + settled = Respecialize(spec); + goto done; + } spec.Countdown = 0; spec.WindowDeopts = 0; JitRuntime.DeoptRetried++; @@ -877,6 +891,23 @@ protected void CoolDownCheck() { _direct = spec.Direct; Install(spec.Entry); } + done: + if (settled) { NotifyOwner(); } + } + + // Some specialization the body bound (JitCode.BoundCallees) is no longer its stub's current one. + private static bool HasReplacedCallee(Specialization/*!*/ spec) { + var bound = (spec.Code != null) ? spec.Code.BoundCallees : null; + if (bound == null) { return false; } + foreach (var callee in bound) { + if (!callee.Stub.IsCurrent(callee)) { return true; } + } + return false; + } + + // A hint, read without the lock: the specialization is the one this stub runs now. + private bool IsCurrent(Specialization/*!*/ spec) { + return _state == Specialized && ReferenceEquals(System.Threading.Volatile.Read(ref _current), spec); } private bool TrySpecialize() { @@ -1085,7 +1116,7 @@ internal JitCallee BindCallee(RubyClass/*!*/ receiverClass, int argc, int versio // (a body that does not call itself was made part of its entry, and not compiled on its own) typed = spec.Typed ?? (spec.Typed = CompileTyped(code)); } - return new JitCallee { Code = code, Target = Ast.Constant(typed, typed.GetType()) }; + return new JitCallee { Code = code, Target = Ast.Constant(typed, typed.GetType()), Spec = spec }; } /// diff --git a/Util/bench/cdtree-shapes.rb b/Util/bench/cdtree-shapes.rb new file mode 100644 index 000000000..100aefcdd --- /dev/null +++ b/Util/bench/cdtree-shapes.rb @@ -0,0 +1,169 @@ +# Shapes for CD's red-black tree (Util/perf/LEDGER.md gap 3), modelled on AWFY cd.rb's RedBlackTree, Node and +# Vector2D: get (find_node, which inlines Vector2D#compare_to), put (tree_insert, rejected at its `Node.new'), a walk +# by Node#successor (an identity `==' on a local nothing samples), and lookups whose keys are of one class for a +# while and then of another, as CD's voxel map and its call-sign map take turns (a caller bound to a callee that is +# compiled again for the second class). Format of Util/perf/ab.rb: ` ns `, N from the +# environment, INSTR=1 or Util/perf/callgrind/count.sh for instructions. +# +# ruby Util/perf/ab.rb -i -r 2 -c none -n 20000 Util/bench/cdtree-shapes.rb \ +# "base=Util/perf/callgrind/count.sh ." "new=Util/perf/callgrind/count.sh ../wt-NAME" +$stdout.sync = true + +class TV2 + attr_reader :x, :y + def initialize(x, y); @x = x; @y = y; end + def compare_to(other) + result = compare_numbers(@x, other.x) + return result if result != 0 + compare_numbers(@y, other.y) + end + def compare_numbers(a, b) + if a == b + return 0 + end + if a < b + return -1 + end + if a > b + return 1 + end + # We say that NaN is smaller than non-NaN. + return 1 if a == a + -1 + end +end + +class TSign + attr_reader :value + def initialize(value); @value = value; end + def compare_to(other) + (@value == other.value) ? 0 : ((@value < other.value) ? -1 : 1) + end +end + +class TNode2 + attr_reader :key + attr_accessor :value, :left, :right, :parent, :color + def initialize(key, value) + @key = key + @value = value + @left = nil + @right = nil + @parent = nil + @color = :red + end + def successor + x = self + return tree_minimum2(x.right) if x.right + y = x.parent + while y && x == y.right + x = y + y = y.parent + end + y + end +end + +def tree_minimum2(x) + current = x + current = current.left while current.left + current +end + +class TInsert + attr_reader :is_new_entry, :new_node, :old_value + def initialize(is_new_entry, new_node, old_value); @is_new_entry = is_new_entry; @new_node = new_node; @old_value = old_value; end +end + +class TTree + attr_reader :root + def initialize; @root = nil; end + def get(key) + node = find_node(key) + return nil unless node + node.value + end + def find_node(key) + current = @root + while current + comparison_result = key.compare_to(current.key) + return current if comparison_result == 0 + if comparison_result < 0 + current = current.left + else + current = current.right + end + end + nil + end + # tree_insert without the rebalancing put does after it: the shape the JIT rejects at `TNode2.new' + def put(key, value) + tree_insert(key, value).is_new_entry + end + def tree_insert(key, value) + y = nil + x = @root + while x + y = x + comparison_result = key.compare_to(x.key) + if comparison_result < 0 + x = x.left + elsif comparison_result > 0 + x = x.right + else + old_value = x.value + x.value = value + return TInsert.new(false, nil, old_value) + end + end + z = TNode2.new(key, value) + z.parent = y + unless y + @root = z + else + if key.compare_to(y.key) < 0 + y.left = z + else + y.right = z + end + end + TInsert.new(true, z, nil) + end +end + +def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end +INSTR = ENV["INSTR"] && (require_relative "../perf/instructions"; Instructions.open || warn("no instruction counter (perf_event_open)")) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; fewest = nil; counted = !!INSTR; sum = nil + 7.times do + c0 = INSTR && INSTR.read; t0 = cpu; sum = yield n; d = cpu - t0; c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 then c = c1 - c0; fewest = c if fewest.nil? || c < fewest else counted = false end + end + printf "%-16s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(" %.1f instr", fewest.to_f / n) : "" +end + +KEYS = (0...64).map { |i| TV2.new(((i * 37) % 64).to_f, (i % 8).to_f) } +SIGNS = (0...64).map { |i| TSign.new((i * 29) % 64) } +vtree = TTree.new +KEYS.each_with_index { |k, i| vtree.put(k, i) } +stree = TTree.new +SIGNS.each_with_index { |k, i| stree.put(k, i) } +NODES = [] +cur = tree_minimum2(vtree.root) +while cur + NODES << cur + cur = cur.successor +end + +N = (ENV["N"] || 1_000_000).to_i +t("get64", N) { |n| i = 0; s = 0; while i < n; s += vtree.get(KEYS[i & 63]); i += 1; end; s } +# a put of an existing key (the loop's update and return) and, every 64th, a fresh tree's first insert +t("put64", N) { |n| i = 0; s = 0; while i < n; s += 1 if vtree.put(KEYS[i & 63], i); i += 1; end; s } +t("put_new", N / 64 * 64) { |n| i = 0; s = 0; tr = nil; while i < n; tr = TTree.new if (i & 63) == 0; s += 1 if tr.put(KEYS[i & 63], i); i += 1; end; s } +t("successor", N) { |n| i = 0; s = 0; while i < n; nx = NODES[i & 63].successor; s += 1 if nx; i += 1; end; s } +# keys of one class for 4,096 lookups, then of the other: a caller (get) bound to a callee (find_node) that is +# compiled again when the second class arrives +t("phases", N) { |n| i = 0; s = 0; while i < n; s += ((i >> 12).even? ? vtree.get(KEYS[i & 63]) : stree.get(SIGNS[i & 63])); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 5eafa4a76..0bb06c124 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -765,6 +765,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has through the JIT's state: a probe that meets an invalidated method, or meets a compiled one and does not deopt, fails (exit status 1). Today every such probe reports "not compiled, semantics only" on stderr. See Rejected. + perf/cdtree (2026-11-27, see Landed) compiled `Node#successor` and stopped `get`'s deopt + storm; `tree_insert`'s four changes were not attempted in that step (each needs the + effect rule changed for a construction, and the gain estimated above is 2-4% of CD). + They are still the next thing here, in that order, with jit-construct-matrix as the gate + of each. 4. **Permute: the `downto` block in `permute`** (the method is 15% self). `permute` is a light frame (`IR_LIGHT_FRAMES=why` says so; an earlier version of this entry said it was not, from the `RubyMethodScope::.ctor` line of the profile alone), and the method @@ -1901,6 +1906,51 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/cdtree (/perf-step, 2026-11-27, on f67ac44) - CD's `Node#successor` compiles (an identity + `==` on a local nothing samples), and a body bound to a callee that was compiled again is compiled + again instead of being put back (gap 3)** - not gated. (1) `x = self; ...; while y && x == y.right`: + `TrySampleOfLocal` takes a local whose first value is `self` from self's sample, as it does one from + another local or an instance variable; and the `==`/`equal?` decision takes a method local (not a + parameter) for an object of a Ruby class when its sample is one or an unsampled attribute access or + inlined call on it was compiled (`IsLocalObject`, `_unsampledObjects`), so it emits `IsIdentical`, + which checks the receiver's `==` against BasicObject#== and deopts otherwise. (2) Found on the way: + since perf/havlak2 compiled `RedBlackTree#get`, which calls `find_node`'s typed body directly, CD's + trace showed `get` retired eight times in three iterations, then for good. CD looks its voxel map + (Vector2D keys) and its call-sign map (CallSign keys) up in turns, so `find_node` was first compiled + for one class and later profiled again and compiled for both; `get` had bound the first body, and a + retired body is only put back (`CoolDownCheck`), deopting as before. `JitCode.BoundCallees` now + records the callee specializations a body bound (its own and theirs), and `CoolDownCheck` compiles + the body again (`Respecialize`) when one of them is no longer its stub's current one. + Census: 0 changed (it sees neither a profile nor a callee's body). CD traced (3 x 100): `successor` + specialized (`tree_minimum` bound), its OSR loop no longer offered, retirements 8 -> 0 (on f67ac44 + `get` ends retired for good; here it is compiled again once and stays), deopts 432 -> 304; the other + thirteen make the same JIT and OSR decisions, all fourteen verify; app-shapes and `gem list` the + same counts and checksums. `Util/bench/cdtree-shapes.rb` (new; cd.rb's tree on 64 Vector2D keys), + instructions a call (callgrind, two rounds, new/base): `successor` 0.769, `phases` (get with the key + class changing every 4,096 calls) 0.946, `get64` and `put_new` 1.000; `put64` 1.262 with a 6.5% + spread in the full file and 1.000 alone in two rounds - in the tiered run it is 699 against 995 ns, + so under callgrind the retry timers (in ms) fall in its sections and count `get`'s recompile there. + Time (tiered, ns): `phases` 384 -> 194, `put64` 995 -> 699, `successor` and `get64` level. AWFY, ten + processes per build, alternating, mean new/base: CD 0.996 (best 0.962), DeltaBlue 0.980, Havlak + 1.002, Richards 1.001 - within their spread. + Checked: `Util/unsampled-matrix.rb` 32 -> 39 cases (successor with `==` redefined, a singleton `==` + on a left child, a subclass with its own `==`, method_missing; `get` over `find` with the key class + changing by phase, and with `cmp` redefined in phase five) prints CRuby's output on the unchanged + build and on the new one with the JIT on, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, `IR_JIT_UNSAMPLED=0` + and `IR_JIT_NESTED=0`; jit-construct (its probes still "not compiled, semantics only"), jit, + jit-calls, jit-const, ivar, hot-shapes, deadconst print CRuby's in all modes, inline the base's + (`tree_int_key`). ruby/spec language/def, core/class/new, core/basicobject/equal and equal_value, + core/kernel/equal_value: no failures on either build. IronRuby.Tests, the whole suite on a Debug + build after merging f67ac44 (`Util/parallel-tests.sh`): 81 processes, 1,402 tests, all PASSED, no + failed or flaky (the script's "listed but never run: Current culture:" is the driver's banner taken + for a test name). The battery before the merge ran with a temporary deopt trace (behind an + environment variable, off) compiled in; the rechecks after the merge (unsampled in five modes, + jit-construct, jit, jit-calls, deadconst, CD's trace) ran on the final build. + For the gate: `HasReplacedCallee` reads another stub's state without its lock (a hint: a wrong + answer recompiles once or puts the body back as before); `Respecialize` counts against + `MaxRespecializations`, so a body whose callees keep being recompiled settles on its generic body. + Not done: `tree_insert`'s four changes (see gap 3). + - **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, perf/twospeed and its note, perf/extiter4 and 5, perf/fiberstart, perf/iter, perf/strsearch3 and 4, diff --git a/Util/unsampled-matrix.rb b/Util/unsampled-matrix.rb index d8f205001..9e0a6b823 100644 --- a/Util/unsampled-matrix.rb +++ b/Util/unsampled-matrix.rb @@ -17,7 +17,9 @@ subclass subclass_private private_value private_match protected_match remove_match frozen nil_entry nested nested_redefine nested_other nested_singleton write write_frozen write_private write_subclass_private write_missing write_thread - pop pop_frozen pop_private pop_subclass_private pop_missing pop_thread] + pop pop_frozen pop_private pop_subclass_private pop_missing pop_thread + succ succ_eq_redefined succ_eq_singleton succ_eq_subclass succ_eq_missing + phases phases_redefined] if ARGV[0] == 'list' puts CASES @@ -107,6 +109,92 @@ def run_pop(pl, n, event) [moved, pl.sizes(0), pl.sizes(1), pl.sizes(2), odd] end +# CD's Node#successor: `x = self', then `x == y.right' walking up - an identity `==' on a local nothing samples +# (JitCompiler.IsLocalObject), which IsIdentical checks against BasicObject#== per receiver +class TNode + attr_accessor :key, :left, :right, :parent + def initialize(key); @key = key; end + def successor + x = self + return tree_min(x.right) if x.right + y = x.parent + while y && x == y.right + x = y + y = y.parent + end + y + end +end +def tree_min(x) + current = x + current = current.left while current.left + current +end +def tnode_tree(keys, cls = TNode) + nodes = keys.map { |k| cls.new(k) } + root = nil + nodes.each do |n| + if root.nil? then root = n; next end + cur = root + loop do + if n.key < cur.key + if cur.left then cur = cur.left else cur.left = n; n.parent = cur; break end + else + if cur.right then cur = cur.right else cur.right = n; n.parent = cur; break end + end + end + end + nodes +end +TKEYS = [50, 30, 70, 20, 40, 60, 80, 10, 25, 35, 45, 55, 65, 75, 90, 5, 95] +# each node's successor's key (nil for the last), N times over, the event at the half: the keys seen, summed +def run_succ(nodes, n, event) + sum = 0 + ends = 0 + odd = nil + n.times do |i| + event.call if i == n / 2 + v = answer { s = nodes[i % nodes.size].successor; s && s.key } + if v.is_a?(Integer) then sum += v elsif v.nil? then ends += 1 else odd ||= v end + end + [sum, ends, odd] +end + +# A method that calls another directly (RedBlackTree#get over find_node), the callee inlining a call on its parameter +# for the class it saw: keys of one class for a while, then of another, then mixed (JitStub.CoolDownCheck) +class PKeyA; attr_reader :v; def initialize(v); @v = v; end; def cmp(o); (@v == o.v) ? 0 : ((@v < o.v) ? -1 : 1); end; end +class PKeyB; attr_reader :v; def initialize(v); @v = v; end; def cmp(o); (@v == o.v) ? 0 : ((@v < o.v) ? 1 : -1); end; end +class PNode; attr_reader :key, :value; attr_accessor :left, :right; def initialize(k, v); @key = k; @value = v; end; end +class PTree + def initialize; @root = nil; end + def add(key, value) + n = PNode.new(key, value) + if @root.nil? then @root = n; return end + cur = @root + loop do + if key.cmp(cur.key) < 0 + if cur.left then cur = cur.left else cur.left = n; return end + else + if cur.right then cur = cur.right else cur.right = n; return end + end + end + end + def find(key) + current = @root + while current + c = key.cmp(current.key) + return current if c == 0 + current = (c < 0) ? current.left : current.right + end + nil + end + def get(key) + node = find(key) + return nil unless node + node.value + end +end + # the same in a module: classes nested in one are candidates too (JitStub.ClassesDefining) module Ns class Ent @@ -343,6 +431,41 @@ def respond_to_missing?(name, priv = false); name == :next || name == :next= || stop_pt = true reader_pt.join p [r_pt, bad_pt] +when 'succ' + p run_succ(tnode_tree(TKEYS), N, -> {}) +when 'succ_eq_redefined' + # == always true from the half: the walk goes on up to the root + nodes = tnode_tree(TKEYS) + p run_succ(nodes, N, -> { TNode.class_eval { def ==(o); true; end } }) +when 'succ_eq_singleton' + nodes = tnode_tree(TKEYS) + # 35 is a left child: equal to everything, its successor is no longer its parent + p run_succ(nodes, N, -> { n35 = nodes.find { |n| n.key == 35 }; def n35.==(o); true; end }) +when 'succ_eq_subclass' + Object.const_set(:TNodeEq, Class.new(TNode) { def ==(o); o.is_a?(TNode) && o.key.to_s.size == key.to_s.size; end }) + plain = tnode_tree(TKEYS) + eqs = tnode_tree(TKEYS, TNodeEq) + cur = plain + p run_succ(cur, N / 2, -> {}) + run_succ(eqs, N / 2, -> {}) +when 'succ_eq_missing' + # a node class with no == of its own but method_missing (== is BasicObject's: method_missing is not reached) + Object.const_set(:TNodeMM, Class.new(TNode) { def method_missing(name, *a); name == :== ? false : super; end; def respond_to_missing?(n, p = false) = super }) + p run_succ(tnode_tree(TKEYS, TNodeMM), N, -> {}) +when 'phases', 'phases_redefined' + ta = PTree.new; tb = PTree.new + (0...30).each { |i| ta.add(PKeyA.new(i * 7 % 30), i) } + (0...30).each { |i| tb.add(PKeyB.new(i * 11 % 30), i * 2) } + ka = (0...30).map { |i| PKeyA.new(i) } + kb = (0...30).map { |i| PKeyB.new(i) } + sum = 0 + 6.times do |phase| + PKeyB.class_eval { def cmp(o); 0; end } if c == 'phases_redefined' && phase == 4 + 2000.times do |i| + sum += (phase.even? ? ta.get(ka[i % 30]) : tb.get(kb[i % 30])) || 0 + end + end + 3000.times { |i| sum += (i.odd? ? ta.get(ka[i % 30]) : tb.get(kb[i % 30])) || 0 } + p sum when 'write_thread' # another thread reads the mark of key 3 while the writes go on; it must only ever see a value some touch wrote e3 = d.get_bucket(d.hash_of(3)) From e29424dab5f6e609148b270d047f3e185d2c4ab3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:38:53 +0000 Subject: [PATCH 236/439] Keep a match sink's $~ in its light frame; turn the sink off by default The gate of 49699fa found two faults in giving the library method the runtime's EmptyScope: a TracePoint enabled by a callee after the match read nil for the method's $~ (CRuby reads the match), and the last match and its subject String stayed reachable from the shared EmptyScope, written by every thread. Now the rule gives the String/Symbol/Regexp method a sink scope of the thread's (RubyOps.EnterMatchSink, a stack, because sub(re, hash) runs Ruby code after it has stored $~), hands what it stored over when it returns (LeaveMatchSink, or AbortMatchSink in a fault block), and the frame keeps it in a CLR variable (TakeMatchSink). A scope the frame makes later gets it (SeedLightScopeMatch), and once the frame has its scope the site makes the ordinary call. EmptyScope is never written. The method is checked by the CLR method that implements it, so an alias cannot bring Regexp#~ ($_), Regexp.last_match or Symbol#to_proc in. The hand-over costs about what the sink saves: callgrind gsub 0.992, split 0.980, kase 1.027, eqt 0.969 of the switch off; by clock one run 0.78-0.95 and one too noisy to tell. So IR_LIGHT_MATCH_SINK is now off unless set to 1; as built the census is unchanged, with the switch on +559 light frames. Checked: the matrix's mid-frame TracePoint row now runs always and matches CRuby; new rows for sub with a matching default proc and a private/protected =~; regex-light, light-entry, hot-shapes, block-pass and jit match CRuby in six gate modes and with the switch on (with and without the JIT); specs language/predefined, core/regexp and the String matching methods with the switch on as the base; new Method_LightFrameMatchSinkRetention1 (a subject String is collectable after the call; 1 of 8 stays alive on 49699fa) and 37 light-frame and regex tests pass with the switch off and on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 30 ++++- .../Ast/Definitions/MethodDefinition.cs | 63 ++++++++--- Src/Ruby/Runtime/Calls/CallArguments.cs | 14 ++- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 43 +++++-- Src/Ruby/Runtime/Calls/RubyCallSignature.cs | 4 +- Src/Ruby/Runtime/RubyOps.MatchSink.cs | 106 ++++++++++++++++++ Util/light-match-sink-matrix.rb | 38 +++++-- Util/perf/LEDGER.md | 86 +++++++------- 9 files changed, 302 insertions(+), 83 deletions(-) create mode 100644 Src/Ruby/Runtime/RubyOps.MatchSink.cs diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 14e1e7acb..84ba1dbce 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1179,6 +1179,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameRest1, Method_LightFrameMemberOpAssign1, Method_LightFrameMatchSink1, + Method_LightFrameMatchSinkRetention1, Method_LightFrameKeywordRest1, Method_KeywordHashIntoRest1, Method_KeywordPrologue1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index b65f9b8a0..f03cfd80e 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8178,9 +8178,10 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters } /// - /// IR_LIGHT_MATCH_SINK: a light frame whose regex literals go to String and Regexp methods that store $~, in a method - /// that reads no $~ of its own (MethodDefinition.IsMatchSink): the caller's $~ is left as it was, in its thread too; a - /// method that reads its $~ ($~, Regexp.last_match, binding) sees its match. + /// IR_LIGHT_MATCH_SINK=1 (off by default: run the test with it set to exercise it): a light frame whose regex literals + /// go to String and Regexp methods that store $~, in a method that reads no $~ of its own (MethodDefinition.IsMatchSink): + /// the caller's $~ is left as it was, in its thread too; a method that reads its $~ ($~, Regexp.last_match, binding) + /// sees its match. /// public void Method_LightFrameMatchSink1() { TestOutput(@" @@ -8219,6 +8220,29 @@ p th.value "); } + /// + /// IR_LIGHT_MATCH_SINK=1 (off by default: run the test with it set to exercise it): the match a light frame's String + /// call stores is the frame's alone (RubyOps.TakeMatchSink): once the frame has returned nothing keeps it, or the String + /// it matched in - not a scope the runtime shares. + /// + public void Method_LightFrameMatchSinkRetention1() { + TestOutput(@" +def sink(s) = s.gsub(/b/, ""x"").size + (s =~ /b+/) +def make + Array.new(8) do + s = ""b"" * 1000 + sink(s) + System::WeakReference.new(s) + end +end +refs = make +3.times { System::GC.Collect; System::GC.WaitForPendingFinalizers } +puts refs.count { |r| r.IsAlive } +", @" +0 +"); + } + /// /// `recv.m op= v' in a light frame (IR_LIGHT_MEMBER_OPASSIGN): the read of m, the operator and the write of m= are calls of /// the frame's light sites; the value is the right-hand side whatever m= returns; a private accessor on self; `&.'; binding. diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 37329670a..c83f16a64 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -635,13 +635,14 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { }; /// - /// IR_LIGHT_MATCH_SINK=0 keeps a method whose regex literal goes to a method that stores $~ out of light frames, as before - /// (see IsMatchSink). + /// IR_LIGHT_MATCH_SINK=1 lets a method whose regex literal goes to a method that stores $~ into light frames if nothing in + /// it reads its $~ (see IsMatchSink). Off by default: the frame's $~ handed from a sink scope of the thread's to a CLR + /// variable costs about what the scope made on demand did (Util/perf/LEDGER.md, perf/lightmatch). /// - internal static readonly bool LightMatchSinkEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_MATCH_SINK") != "0"; + internal static readonly bool LightMatchSinkEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_MATCH_SINK") == "1"; // The names of RegexScopeMethods that String, Symbol and Regexp define (RubyCallAction.IsMatchSinkMethod): a light site - // of one in a method that is a match sink stores $~ in no frame (RubyCallFlags.HasMatchSink). + // of one in a method that is a match sink stores $~ in a sink scope (RubyCallFlags.HasMatchSink). private static readonly HashSet/*!*/ MatchSinkMethods = new HashSet { "=~", "===", "match", "gsub", "gsub!", "sub", "sub!", "scan", "split", "index", "rindex", "byteindex", "byterindex", "[]", "[]=", "slice", "slice!", "start_with?", "partition", "rpartition", @@ -670,9 +671,10 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// `$~', `$&', `$1', Regexp.last_match or other reference to it, no block or lambda (whose binding a callee may be given), /// no binding, string eval or call made by name (MatchObserverMethods), no global but the runtime's own /// (MatchSinkGlobals: `alias $m $~' makes `$m' the frame's $~). Such a method's light frame lets the String, Symbol and - /// Regexp methods it calls store $~ in no frame at all (RubyCallFlags.HasMatchSink), where it would otherwise make its - /// scope for them on every call and call them again (gap 16 of Util/perf/LEDGER.md). $~ after the method returns is - /// its caller's, as in CRuby. + /// Regexp methods it calls store $~ in a sink scope of the thread's, from which the frame takes it into a CLR variable + /// (RubyCallFlags.HasMatchSink, RubyOps.TakeMatchSink), where it would otherwise make its scope for them on every call + /// and call them again (gap 16 of Util/perf/LEDGER.md). A scope the frame makes later gets that $~, for a TracePoint's + /// binding; $~ after the method returns is its caller's, as in CRuby. /// private bool IsMatchSink() { if (!LightMatchSinkEnabled || !LightRegexEnabled) { @@ -1681,12 +1683,18 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ : make(Methods.CreateMethodScopeLazy, scope.LocalsTupleVariable); light.MakeScopeIfTraced = locals => make(Methods.CreateMethodScopeIfTraced, locals); var inLoop = scope.DefineHiddenVariable("#in-loop", typeof(bool)); - light.LazyScope = Ast.Coalesce(scopeVariable, Ast.Assign(scopeVariable, Ast.Call(_LightScopeInLoop, light.MakeScope, inLoop))); - bool blockLiterals = LightBlocksEnabled && HasLightBlockLiteral(); + // A match sink keeps its $~ in a CLR variable and puts it into the scope it makes on demand (RubyOps.TakeMatchSink). + var matchSlot = (!blockLiterals && IsMatchSink()) ? scope.DefineHiddenVariable("#match", typeof(MatchData)) : null; + MSA.Expression lateScope = Ast.Call(_LightScopeInLoop, light.MakeScope, inLoop); + if (matchSlot != null) { + lateScope = Ast.Call(_SeedLightScopeMatch, lateScope, matchSlot); + } + light.LazyScope = Ast.Coalesce(scopeVariable, Ast.Assign(scopeVariable, lateScope)); + var rewriter = new LightFrameRewriter(scopeVariable, light.LazyScope, light.Rfc, declaringScope, inLoop, HasBlockGuard) { BlockLiterals = blockLiterals, - MatchSink = !blockLiterals && IsMatchSink(), + MatchSlot = matchSlot, BlockParameter = LightBlockGivenEnabled ? blockParameter : null, SuperModule = LightSuperEnabled ? ConstantValue(declaringModule) as RubyModule : null, SuperName = _name, @@ -1725,6 +1733,8 @@ private static object ConstantValue(MSA.Expression/*!*/ node) { /// its scope after all. /// private static readonly MethodInfo/*!*/ _LightScopeInLoop = typeof(RubyOps).GetMethod("LightScopeInLoop"); + private static readonly MethodInfo/*!*/ _SeedLightScopeMatch = typeof(RubyOps).GetMethod("SeedLightScopeMatch"); + private static readonly MethodInfo/*!*/ _TakeMatchSink = typeof(RubyOps).GetMethod("TakeMatchSink"); private static readonly MethodInfo/*!*/ _EnterLightLoop = typeof(RubyOps).GetMethod("EnterLightLoop"); private static readonly MethodInfo/*!*/ _LeaveLightLoop = typeof(RubyOps).GetMethod("LeaveLightLoop"); @@ -1748,8 +1758,9 @@ internal sealed class LightFrameRewriter : MSA.ExpressionVisitor { // makes none. The scope made on demand has the frame's locals (its tuple, made from the register locals if those are // used), self, block and flow-control frame, which is all the block and the call read from it. internal bool BlockLiterals; - // Nothing reads the frame's $~ (IsMatchSink): a light site of one of MatchSinkMethods has RubyCallFlags.HasMatchSink. - internal bool MatchSink; + // The frame's $~ when nothing in it reads $~ (IsMatchSink), null otherwise: a light site of one of MatchSinkMethods has + // RubyCallFlags.HasMatchSink, and the frame takes the match its call stored into this variable (MakeLightCall). + internal MSA.ParameterExpression MatchSlot; // see LightFrame.MakesCalls internal bool MakesCalls; @@ -2227,11 +2238,13 @@ private MSA.Expression LightScopeCall(Microsoft.Scripting.Ast.LightDynamicExpres } var lightFlags = signature.Flags | RubyCallFlags.HasLightScope; - if (MatchSink && MatchSinkMethods.Contains(action.MethodName)) { + // (not with a block: a library method that yields stores $~ for the block, which then reads it from the frame) + bool sink = MatchSlot != null && !signature.HasBlock && MatchSinkMethods.Contains(action.MethodName); + if (sink) { lightFlags |= RubyCallFlags.HasMatchSink; } var lightAction = RubyCallAction.Make(action.Context, action.MethodName, new RubyCallSignature(signature.ArgumentCount, lightFlags)); - return MakeLightCall(reduced, action, lightAction, DispatchIntrinsics.IsLightBlockGivenSite(action.MethodName, lightAction.Signature)); + return MakeLightCall(reduced, action, lightAction, DispatchIntrinsics.IsLightBlockGivenSite(action.MethodName, lightAction.Signature), sink); } /// @@ -2289,7 +2302,7 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres // The call through the light site, then through the ordinary one with the scope made on demand if the light site's // rule answered RubyOps.LightScopeRequired, both with the same evaluated arguments (see LightScopeCall). private MSA.Expression/*!*/ MakeLightCall(MSA.DynamicExpression/*!*/ reduced, RubyMetaBinder/*!*/ action, RubyMetaBinder/*!*/ lightAction, - bool blockGiven) { + bool blockGiven, bool matchSink = false) { int count = reduced.Arguments.Count; var temps = new MSA.ParameterExpression[count]; var body = new AstExpressions(); @@ -2307,6 +2320,10 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres var result = Ast.Variable(typeof(object), "#r"); temps[0] = result; MakesCalls = true; + // (a LightDynamicExpression takes its builder's arguments: each site gets a copy) + var sinkLightArgs = matchSink ? new AstExpressions(lightArgs) : null; + var sinkFullArgs = matchSink ? new AstExpressions(fullArgs) : null; + var sinkLateArgs = matchSink ? new AstExpressions(fullArgs) : null; body.Add(Ast.Assign(result, AstUtils.LightDynamic(lightAction, typeof(object), lightArgs))); MSA.Expression needsScope = Ast.ReferenceEqual(result, AstUtils.Constant(RubyOps.LightScopeRequired)); if (blockGiven && BlockParameter == null) { @@ -2314,6 +2331,22 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres needsScope = Ast.OrElse(needsScope, Ast.ReferenceEqual(result, AstUtils.Constant(RubyOps.LightBlockGiven))); } MSA.Expression value = Ast.Condition(needsScope, AstUtils.LightDynamic(action, typeof(object), fullArgs), result); + if (matchSink) { + // The light call stored $~ in a sink scope, and the frame takes it (RubyOps.TakeMatchSink). Once the frame has + // its scope, the call stores $~ there, as an ordinary one does. + body.RemoveAt(body.Count - 1); + value = Ast.Condition( + Ast.NotEqual(_scope, AstUtils.Constant(null, _scope.Type)), + AstUtils.LightDynamic(action, typeof(object), sinkFullArgs), + Ast.Block( + Ast.Assign(result, AstUtils.LightDynamic(lightAction, typeof(object), sinkLightArgs)), + Ast.Condition(needsScope, + AstUtils.LightDynamic(action, typeof(object), sinkLateArgs), + Ast.Block(Ast.Assign(MatchSlot, Ast.Call(_TakeMatchSink, MatchSlot)), result) + ) + ) + ); + } if (blockGiven && BlockParameter != null) { // `block_given?' that is Kernel's (DispatchIntrinsics.TryBuildBlockGiven): whether the frame was given a // block, which is what Kernel#block_given? reads from the scope this frame would have to make for it - diff --git a/Src/Ruby/Runtime/Calls/CallArguments.cs b/Src/Ruby/Runtime/Calls/CallArguments.cs index af554d32c..b31d7b4b1 100644 --- a/Src/Ruby/Runtime/Calls/CallArguments.cs +++ b/Src/Ruby/Runtime/Calls/CallArguments.cs @@ -91,12 +91,17 @@ public int SimpleArgumentCount { /// /// Set by RubyCallAction.BuildCall at a site with RubyCallFlags.HasMatchSink once the method is resolved and is one that - /// takes the scope only to store $~ (RubyCallAction.IsMatchSinkMethod): the scope the rule gives it is then the runtime's - /// empty scope, which nothing reads $~ of, and reading it is not reading the frame's. + /// takes the scope only to store $~ (RubyCallAction.IsMatchSinkMethod): the scope the rule gives it is then a sink scope + /// of the thread's (RubyOps.EnterMatchSink, in MatchSinkVariable), and reading it is not reading the frame's. /// internal bool MatchSink; private DynamicMetaObject _sinkScope; + // The rule's variable for the sink scope, null if the method did not read the scope. + internal ParameterExpression MatchSinkVariable { + get { return (_sinkScope != null) ? (ParameterExpression)_sinkScope.Expression : null; } + } + /// /// The scope argument's expression, for a helper that takes the scope only for its runtime (GetInstanceVariable, /// SetAttribute): the scope a light-scope site passes has the same runtime, so this does not count as reading it. @@ -109,8 +114,9 @@ public DynamicMetaObject/*!*/ MetaScope { get { if (MatchSink) { if (_sinkScope == null) { - var sink = ((RubyContext)_context.Value).EmptyScope; - _sinkScope = new DynamicMetaObject(Ast.Constant(sink, typeof(RubyScope)), BindingRestrictions.Empty, sink); + // (the value is for nothing but the binder's questions, which a sink scope answers as the empty one does) + var empty = ((RubyContext)_context.Value).EmptyScope; + _sinkScope = new DynamicMetaObject(Ast.Variable(typeof(RubyScope), "#sink"), BindingRestrictions.Empty, empty); } return _sinkScope; } diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 87aa6605d..288932abb 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -777,13 +777,18 @@ private static bool BuildCall(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ me } method.Info.BuildCall(metaBuilder, args, methodName); - // While a TracePoint is enabled its hooks may read the frame's $~ through their binding (a :line or :return - // event): the call then stores $~ in the frame's scope, made for it (RubyOps.LightScopeRequired). - if (args.MatchSink && !metaBuilder.Error && metaBuilder.Result != null) { - metaBuilder.Result = Ast.Condition( - Ast.Equal(Ast.Field(null, typeof(TracePoint).GetField("ActiveEvents")), AstUtils.Constant(0)), - AstUtils.Convert(metaBuilder.Result, typeof(object)), - AstUtils.Constant(RubyOps.LightScopeRequired, typeof(object)) + // The method stores $~ in a sink scope of the thread's, and the frame takes it from there (RubyOps.EnterMatchSink). + var sink = args.MatchSink ? args.MatchSinkVariable : null; + if (sink != null && !metaBuilder.Error && metaBuilder.Result != null) { + var result = Ast.Variable(typeof(object), "#result"); + metaBuilder.Result = Ast.Block(new[] { sink, result }, + Ast.Assign(sink, Ast.Call(_EnterMatchSink, AstUtils.Convert(args.MetaContext.Expression, typeof(RubyContext)))), + Ast.TryFault( + Ast.Assign(result, AstUtils.Convert(metaBuilder.Result, typeof(object))), + Ast.Call(_AbortMatchSink) + ), + Ast.Call(_LeaveMatchSink), + result ); } @@ -984,18 +989,32 @@ private static MethodResolutionResult ResolveOwnClrMember(MetaObjectBuilder/*!*/ /// A library method of String, Symbol or Regexp (MutableStringOps, SymbolOps, RubyRegexOps): one that takes its caller's /// scope to store $~ in it and for the runtime, and for nothing else - not to resolve a call it makes, which goes through /// a site of its own without the caller's refinements, as CRuby's rb_funcall does. A site with RubyCallFlags.HasMatchSink - /// gives it the runtime's empty scope (CallArguments.MatchSink). Not while c_call is traced: the rule then reports the + /// gives it a sink scope of the thread's (CallArguments.MatchSink). Not while c_call is traced: the rule then reports the /// call with the caller's scope (RubyLibraryMethodInfo.AddCallTracing), and switching tracing rebinds every rule. /// internal static bool IsMatchSinkMethod(RubyContext/*!*/ context, RubyMemberInfo/*!*/ method) { - if (!(method is RubyLibraryMethodInfo) || TracePoint.CCallTracing) { + var library = method as RubyLibraryMethodInfo; + if (library == null || TracePoint.CCallTracing) { return false; } - var owner = method.DeclaringModule; - return owner == context.GetClass(typeof(MutableString)) || owner == context.GetClass(typeof(RubySymbol)) || - owner == context.GetClass(typeof(RubyRegex)); + // By the CLR method that implements it, not the module it is in or the name it is called by: an alias may put + // another library method under a sink name. Of those classes' methods that take the scope, Regexp#~ reads $_ from + // it, Regexp.last_match reads $~, and Symbol#to_proc makes a Proc with it. + foreach (var overload in library.MethodBases) { + var type = overload.DeclaringType; + if (type == null || type.Namespace != "IronRuby.Builtins" || + type.Name != "MutableStringOps" && type.Name != "SymbolOps" && type.Name != "RegexpOps" || + overload.Name == "ImplicitMatch" || overload.Name == "LastMatch" || overload.Name == "ToProc") { + return false; + } + } + return true; } + private static readonly MethodInfo/*!*/ _EnterMatchSink = typeof(RubyOps).GetMethod("EnterMatchSink"); + private static readonly MethodInfo/*!*/ _LeaveMatchSink = typeof(RubyOps).GetMethod("LeaveMatchSink"); + private static readonly MethodInfo/*!*/ _AbortMatchSink = typeof(RubyOps).GetMethod("AbortMatchSink"); + internal static MethodResolutionResult Resolve(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ methodName, CallArguments/*!*/ args, out RubyMemberInfo methodMissing) { diff --git a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs index 165a67ee3..e944fd96f 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs @@ -80,8 +80,8 @@ public enum RubyCallFlags { // CallAction only, with HasLightScope: a call in a method that runs without its scope and that nothing in its body // reads $~ of (MethodDefinition.IsMatchSink). A library method of String, Symbol or Regexp, which takes the scope only to - // store $~ in it and for its runtime, is then given the runtime's empty scope instead of reading the frame's - // (CallArguments.MatchSink), and the frame makes no scope for it. + // store $~ in it and for its runtime, is then given a sink scope of the thread's instead of reading the frame's + // (CallArguments.MatchSink, RubyOps.EnterMatchSink), and the frame takes the match from it and makes no scope. HasMatchSink = 4096, } diff --git a/Src/Ruby/Runtime/RubyOps.MatchSink.cs b/Src/Ruby/Runtime/RubyOps.MatchSink.cs new file mode 100644 index 000000000..4dfbcdff9 --- /dev/null +++ b/Src/Ruby/Runtime/RubyOps.MatchSink.cs @@ -0,0 +1,106 @@ +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Apache License, Version 2.0, please send an email to + * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound + * by the terms of the Apache License, Version 2.0. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ + +using System; +using IronRuby.Builtins; + +namespace IronRuby.Runtime { + + /// + /// The $~ of a light frame that makes no scope for its String, Symbol and Regexp calls (RubyCallFlags.HasMatchSink, + /// MethodDefinition.IsMatchSink). The rule of such a call gives the library method a scope of the thread's own to store + /// $~ in (EnterMatchSink), and hands what it stored to the frame when it returns (LeaveMatchSink); the frame keeps it in a + /// CLR local (TakeMatchSink) and puts it into its scope if one is made later (SeedLightScopeMatch) - for a TracePoint's + /// binding, say. So $~ is the frame's, as in CRuby, and nothing shared holds a match: the sink scopes are cleared as they + /// are left. A stack, because a library method may run Ruby code after it has stored $~ (`sub(re, hash)' calls the + /// hash's default proc), and that code's own calls must not take the match of the call that is still running. + /// + public static partial class RubyOps { + // stored in a sink scope when it is entered: a store by the library method replaces it + private static readonly MatchData MatchSinkUnset = new MatchData(); + + // A thread's sink scopes, one per call in progress, and what the last call left stored until the frame that made it + // takes it (MatchSinkUnset if nothing, or taken). One object, so that each helper reads one thread static. + private sealed class MatchSinkState { + internal RubyTopLevelScope[] Sinks = new RubyTopLevelScope[4]; + internal int Depth; + internal MatchData Taken = MatchSinkUnset; + } + + [ThreadStatic] + private static MatchSinkState t_matchSink; + + public static RubyScope/*!*/ EnterMatchSink(RubyContext/*!*/ context) { + var state = t_matchSink ?? (t_matchSink = new MatchSinkState()); + int depth = state.Depth; + var sinks = state.Sinks; + if (depth == sinks.Length) { + Array.Resize(ref sinks, depth * 2); + state.Sinks = sinks; + } + var sink = sinks[depth]; + // several runtimes may run on a thread: a sink scope is the runtime's whose methods it is given to + if (sink == null || sink.RubyContext != context) { + sinks[depth] = sink = new RubyTopLevelScope(context); + } + sink.CurrentMatch = MatchSinkUnset; + state.Depth = depth + 1; + return sink; + } + + public static void LeaveMatchSink() { + var state = t_matchSink; + var sink = state.Sinks[--state.Depth]; + state.Taken = sink.CurrentMatch; + sink.CurrentMatch = null; + } + + // the call raised: what it stored is no frame's + public static void AbortMatchSink() { + var state = t_matchSink; + state.Sinks[--state.Depth].CurrentMatch = null; + state.Taken = MatchSinkUnset; + } + + /// + /// The frame's $~ after a call of its light site with RubyCallFlags.HasMatchSink: what the call stored, or + /// if it stored nothing (a method of the program's own, a library method that did not + /// match: CRuby leaves the caller's $~ then too). + /// + public static MatchData TakeMatchSink(MatchData previous) { + var state = t_matchSink; + if (state == null) { + // the thread has entered no sink: nothing was stored + return previous; + } + var match = state.Taken; + if (ReferenceEquals(match, MatchSinkUnset)) { + return previous; + } + state.Taken = MatchSinkUnset; + return match; + } + + /// + /// The scope a light frame that is a match sink makes on demand, given the frame's $~. + /// + public static RubyMethodScope/*!*/ SeedLightScopeMatch(RubyMethodScope/*!*/ scope, MatchData match) { + if (match != null) { + scope.CurrentMatch = match; + } + return scope; + } + } +} diff --git a/Util/light-match-sink-matrix.rb b/Util/light-match-sink-matrix.rb index e6fd02bff..e90707975 100644 --- a/Util/light-match-sink-matrix.rb +++ b/Util/light-match-sink-matrix.rb @@ -1,6 +1,6 @@ # Differential matrix for the frame-local $~ of a method that runs in a light frame and gives a regex to a String, # Symbol or Regexp method that stores $~ (MethodDefinition.IsMatchSink, RubyCallFlags.HasMatchSink, -# IR_LIGHT_MATCH_SINK). CRuby's rules, which each row checks: +# IR_LIGHT_MATCH_SINK=1, off by default). CRuby's rules, which each row checks: # # - $~ is the frame's own: a method's match does not set its caller's $~, and leaves it as it was (nil or a match); # - a block sees its method's $~ (and sets it), a lambda too; @@ -11,12 +11,15 @@ # rpartition, byteindex and their bang forms sets $~ (or clears it on no match); # - a method calling String#=~ with an object of its own: that object's =~ runs in its own frame. # +# A method that nothing in reads its $~ keeps it in a CLR variable of its light frame, and puts it into the scope if one is +# made later (RubyOps.TakeMatchSink); rows 8-11 are about that. +# # Every method is called hot (N times) so that its sites are bound and compiled, then once more for the row. -# Run under CRuby and ./ir.sh (JIT on and off, light frames off, the switch off) and diff: +# Run under CRuby and ./ir.sh (JIT on and off, light frames off, the switch on) and diff: # # ruby Util/light-match-sink-matrix.rb > /tmp/mri.txt # ./ir.sh Util/light-match-sink-matrix.rb > /tmp/ir.txt && diff /tmp/mri.txt /tmp/ir.txt -# IR_LIGHT_MATCH_SINK=0 ./ir.sh Util/light-match-sink-matrix.rb > /tmp/off.txt && diff /tmp/mri.txt /tmp/off.txt +# IR_LIGHT_MATCH_SINK=1 ./ir.sh Util/light-match-sink-matrix.rb > /tmp/on.txt && diff /tmp/mri.txt /tmp/on.txt # # Every row must match, and the last line be `end'. @@ -226,12 +229,7 @@ def rescue_m(s) mx = Mixed.new row "9. scope made late", [hot { [mx.rt(STR), mx.bg(STR), mx.kw(STR), mx.opt(STR), mx.rescue_m(STR)] }, ("zz" =~ /z/; mx.rt(STR); mx.opt(STR); mx.rescue_m(STR); $~ && $~[0])] -# 10. TracePoint enabled by a callee after the method's match: its :line and :return bindings see the match in CRuby. -# The one row the switch changes: a match sink stored the match in no frame, and a scope made for the hooks after the -# match has no $~ (`[[:line, nil], [:return, nil]]'). Not run unless MID=1, so that the matrix diffs clean; the light -# frame's sites take the scope while a TracePoint is enabled (RubyCallAction.BuildCall), which covers every TracePoint -# enabled before the method was entered. -if ENV['MID'] +# 10. TracePoint enabled by a callee after the method's match: its :line and :return bindings see the match def mid_enabler $mid_tp = TracePoint.new(:line, :return) { |t| $mid_seen << [t.event, t.binding.eval("$~ && $~[0]")] if t.method_id == :mid } $mid_tp.enable @@ -250,6 +248,28 @@ def mid_plain(s) mid(STR) $mid_tp.disable row "10. TracePoint enabled mid-frame", $mid_seen + +# 11. a library method that runs Ruby code after it has stored $~: sub with a Hash whose default proc calls a method +# that matches too (each frame keeps its own $~), and the same seen by a TracePoint +class Nested + def inner(s) = s.sub(/q+/, "Q") + def outer(s, h); r = s.sub(/b+/, h); [r, Nested.peek_line]; end + def self.peek_line = nil +end +nh = Hash.new { |_, k| Nested.new.inner("qq" + k) } +row "11. sub with a default proc that matches", [hot { Nested.new.outer(STR, nh) }, ("zz" =~ /z/; Nested.new.outer(STR, nh); $~ && $~[0])] +seen = [] +tp3 = TracePoint.new(:return) { |t| seen << [t.method_id, t.binding.eval("$~ && $~[0]")] if t.method_id == :outer || t.method_id == :inner } +tp3.enable { Nested.new.outer(STR, nh) } +row "11a. their $~ seen by a TracePoint", seen + +# 12. String#=~ with an object whose =~ is private or protected: called anyway, as rb_funcall does +class PrivMatcher + private def =~(_) = :private_called +end +class ProtMatcher + protected def =~(_) = :protected_called end +row "12. String#=~ with a private =~", [hot { (S.eqt_obj(STR, PrivMatcher.new) rescue $!.class) }, (S.eqt_obj(STR, ProtMatcher.new) rescue $!.class)] puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 0a5506691..fbb293a44 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1166,9 +1166,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has made twice cost. Nothing was built; the about 800 methods of the census's regex lines stay out. A step on them has to make the second call or the late scope cheaper (perf/lsite and perf/lsite2 tried the second and were rejected), not the light entry. - **perf/lightmatch** took the methods that cannot observe their `$~` (no reference, block, binding or eval): - there the call stores it in no frame and makes neither (+559 light frames, 0.93-0.97 of the instructions); the - methods that read their `$~` or have blocks are what is left. + **perf/lightmatch** took the methods that cannot observe their `$~` (no reference, block, binding or eval): the + call stores it in a sink scope of the thread's and the frame keeps it in a CLR variable, making neither (+559 light + frames); but that hand-over costs about what it saves (0.97-1.03 of the instructions), so it is off by default + (`IR_LIGHT_MATCH_SINK=1`). The methods that read their `$~` or have blocks are what is left either way. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per site at start-up, 0.2-0.4 ms). TruffleRuby's `Primitive.x` is replaced at parse time. @@ -1904,47 +1905,56 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed -- **perf/lightmatch (2026-11-27) - a light frame lets String and Regexp methods store `$~` in no frame (gap 16, the - `$~` family)** - not gated. Chosen by the census of c1045a0: the regex lines were its largest refusal (gsub 273, - `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54). +- **perf/lightmatch (2026-11-27) - a light frame keeps its `$~` in a CLR variable for its String and Regexp calls (gap + 16, the `$~` family): off by default, `IR_LIGHT_MATCH_SINK=1`** - not gated. Chosen by the census of c1045a0: the + regex lines were its largest refusal (gsub 273, `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54). - CRuby's rules, the matrix's rows: `$~` is the frame's own - a method's match never sets its caller's, which keeps what it had (nil or a match); a block and a lambda see and set their method's; per thread too; `$1`..`$9`, `$&`, `` $` ``, `$'`, `$+`, Regexp.last_match read it, `$~ = nil` and `$~ = md` set it (anything else is a TypeError); binding, eval and a TracePoint's binding read the frame's; `alias $m $~` makes `$m` read it. - - So a method that cannot observe its `$~` needs it stored nowhere. `MethodDefinition.IsMatchSink`: no `$~`/`$1`... - reference, no block or lambda (a callee given one may ask for its binding), none of binding, eval, instance_eval, - class_eval, module_eval, send, `__send__`, public_send, method, public_method, singleton_method, last_match, - enable, set_trace_func, trace, and no global but the runtime's own. In such a method a regex literal given to - `=~ === match gsub(!) sub(!) scan split index rindex byteindex byterindex [] []= slice(!) start_with? partition - rpartition` or in a `when` no longer keeps it out of light frames, and those light sites get - `RubyCallFlags.HasMatchSink`. Their rule, once it has resolved a library method of String, Symbol or Regexp (which - take the scope to store `$~` and for the runtime only - not for a call they make, as rb_funcall), gives it the - runtime's EmptyScope (`CallArguments.MatchSink`) instead of answering LightScopeRequired - no late scope, no second - call. Not with c_call traced, and the rule tests `TracePoint.ActiveEvents` and takes the scope while any TracePoint - is on. Refinements, a Ruby `gsub` on String or a subclass, `!~` (Kernel's) and Enumerable#grep still read the - scope as before. Switch: `IR_LIGHT_MATCH_SINK=0`. - - **Known difference from CRuby:** a TracePoint enabled by a callee after the method's match, whose :line or - :return binding then reads the method's `$~`, sees nil (CRuby: the match). Matrix row 10, run with `MID=1`. The - sound form is a `$~` slot per light frame copied into a late scope; not built (it would pay a thread-local read - and write a call). Every TracePoint enabled before the method's entry is covered. - - Census (Src/StdLib + AWFY, 28,377 methods): light frames 26,732 -> 27,291 (+559, 94.2% -> 96.2%), none down; the - JIT's counts unchanged. The regex lines left: `=~` 138, gsub 82, `when` 45, split 31, match 29, scan 27, sub 27 - - methods that read their `$~` or have blocks. - - Instructions (`Util/perf/callgrind/count.sh`, regex-shapes, N=20000; base / switch off / new): gsub 12,610 / - 12,608 / 12,238 (0.971), split 10,769 / 10,769 / 10,378 (0.964), kase 8,426 / 8,426 / 8,133 (0.965), eqt 5,691 / - 5,690 / 5,289 (0.929); size, tilde 1.000, matchp level with off. Time (`ab.rb -r 5`, off / new, ns, load 12-14): - gsub 395 / 356 (0.90), split 326 / 306 (0.94), kase 253 / 213 (0.84), eqt 198 / 173 (0.87); size, matchp, tilde - overlap. (`ab.rb -i` over count.sh failed under ab.rb's CPU pinning here; each arm was run by hand.) + - `MethodDefinition.IsMatchSink`: a method with no `$~`/`$1`... reference, no block or lambda, none of binding, eval, + instance_eval, class_eval, module_eval, send, `__send__`, public_send, method, public_method, singleton_method, + last_match, enable, set_trace_func, trace, and no global but the runtime's own. Its regex literals given to `=~ === + match gsub(!) sub(!) scan split index rindex byteindex byterindex [] []= slice(!) start_with? partition rpartition` + or in a `when` no longer keep it out of light frames, and those light sites (without a block) get + `RubyCallFlags.HasMatchSink`. Their rule, once it has resolved a library method implemented in MutableStringOps, + SymbolOps or RegexpOps (not Regexp#~, which reads `$_`, Regexp.last_match or Symbol#to_proc; checked by the CLR + method, so an alias cannot bring one in), gives it a sink scope of the thread's instead of answering + LightScopeRequired (`RubyOps.EnterMatchSink`, a stack: `sub(re, hash)` runs the hash's default proc after storing + `$~`, and that code's own calls must not take it), hands what it stored over when it returns (`LeaveMatchSink`, + `AbortMatchSink` in a fault block), and the frame takes it into a CLR variable `#match` (`TakeMatchSink`; what it + had if the call stored nothing). A scope the frame makes later gets it (`SeedLightScopeMatch` in the lazy scope), + and once the frame has its scope the site makes the ordinary call. Not with c_call traced. + - Round one (49699fa) gave the library method the runtime's EmptyScope. The gate found two faults in it: a + TracePoint enabled by a callee after the match read nil for the method's `$~` (CRuby: the match; now matrix row + 10, which runs always), and the last match and its subject String stayed reachable from the shared EmptyScope, + written by every thread (now `Method_LightFrameMatchSinkRetention1`: 1 of 8 subjects alive after GC on 49699fa, 0 + now). The per-frame variable fixes both: nothing shared holds a match, and EmptyScope is never written. + - **Why off by default:** the hand-over costs about what it saves. Instructions (`Util/perf/callgrind/count.sh`, + regex-shapes, N=20000; switch off / round one / this): gsub 12,641 / 12,237 / 12,541 (0.992), split 10,826 / + 10,298 / 10,611 (0.980), kase 8,483 / 8,173 / 8,714 (1.027), eqt 5,768 / 5,338 / 5,588 (0.969); size and + tilde 1.00. A first form with three thread statics per helper was 0.99-1.05 (kase 1.049); one thread-static object + took a third of that back. Time (`ab.rb`, off / on): a first run of five rounds gsub 0.89, split 0.92, kase 0.95, + eqt 0.78, the controls level; a second of seven, with the machine busier, every shape overlapping (spreads 9-47%). + Under callgrind tiered compilation is off, where a thread static costs more than in tier 1; the clock's first + run says the gain may be real, the second cannot tell. Turn it on after a quiet `ab.rb -r 10`, or after a cheaper + hand-over (the frame's `#rfc` as the carrier, or the sink scope taken once per frame instead of once per call). + - Census (Src/StdLib + AWFY, 28,377 methods): as built, 0 methods changed. With `IR_LIGHT_MATCH_SINK=1` light frames + 26,732 -> 27,291 (+559, 94.2% -> 96.2%), none down, the JIT's counts unchanged. - Checks: the new `Util/light-match-sink-matrix.rb` (every method above, the caller's `$~` nil and set, no match, a Regexp in a variable, grep; 21 methods that read their `$~`; `alias $mm $~`; threads; a refined gsub; String#=~ - with an object of the program's; a String subclass; a Symbol receiver; gsub redefined and restored after binding; - TracePoint :return and :c_return; a scope made late by respond_to?, block_given?, keywords, defaults, rescue), - regex-light, light-entry, hot-shapes, block-pass and jit: CRuby's output in all seven gate modes on both trees, 41 - same and regex-light under R2R as on base. ruby/spec language/predefined, core/regexp, core/string - gsub/sub/scan/split/match: 673 examples, the same three conversion-message errors on both. IronRuby.Tests: the new - Method_LightFrameMatchSink1 and 36 light-frame and regex tests pass (the new one with the switch off too). - - Found on the way, not fixed: `instance_eval("$~")` does not see its caller's `$~` (CRuby does), with or without the - switch. + with an object of the program's, and with a private and a protected `=~`; a String subclass; a Symbol receiver; + gsub redefined and restored after binding; TracePoint :return enabled before, enabled by a callee mid-frame, + :c_return; `sub(re, hash)` whose default proc matches too, also under a TracePoint; a scope made late by + respond_to?, block_given?, keywords, defaults, rescue), regex-light, light-entry, hot-shapes, block-pass and jit: + CRuby's output in the six gate modes and with the switch on, with and without the JIT (47 same; regex-light under + R2R as on base). ruby/spec language/predefined, core/regexp, core/string gsub/sub/scan/split/match with the switch + on: 673 examples, the same three conversion-message errors as the base. IronRuby.Tests: the two new tests and 37 + light-frame and regex tests pass with the switch off and on. + - `ScopeRead` and the sink: of the scope-taking methods of MutableStringOps, SymbolOps and RegexpOps every one uses + it for `$~` and the runtime only, except the three named above; split's default separator is `$;`, read from the + runtime (`Context.StringSeparator`), not the frame. + - Found on the way, not fixed: `instance_eval("$~")` does not see its caller's `$~` (CRuby does), on base too. - **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, From 50e0bf30002f77b6c3b35e20c00ad84981568001 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:39:46 +0000 Subject: [PATCH 237/439] Enumerable#sort_by: gather the keys without a program's own Array#<< The prelude's sort_by (and min_by(n)/max_by(n), which share it) gathered the elements and their keys with Array#<<, so a program that redefined Array#<< had its method called, and raising there made sort_by raise. MRI's sort_by fills its buffer in C. The built-in push is now taken under a private name when the prelude loads (__list_push__, beside __list_sort_by__) and used for both lists. Util/sort-by-matrix.rb: the "a redefined Array#<< does not count" row now agrees with CRuby 4.0 (left: the order of equal keys and which pair a NaN comparison names, which follow CRuby's own qsort). Enumerable_SortByOwnPush1 holds CRuby's output; sort_by, min_by, max_by, Array#sort_by and core/hash specs pass (Hash.try_convert's known into/to error), as do the 54 enumerable, sort and hash IronRuby.Tests. A Hash and an Array sort_by loop timed as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 23 +++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 12 ++++++++---- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 949425ca4..7f83f4689 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1170,6 +1170,7 @@ public Tests(Driver/*!*/ driver) { TracePoint_AttrAccessorCCall1, Float_OutOfRangeMessage1, Float_RoundDigitsRange1, + Enumerable_SortByOwnPush1, Defined_ConditionNoFreeze1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index f9c8033da..30ac41efa 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -9343,6 +9343,29 @@ def t(l) "); } + /// + /// sort_by and min_by(n) gather the keys without calling a program's own Array#<<, as MRI's do. + /// + public void Enumerable_SortByOwnPush1() { + TestOutput(@" +require 'ruby4' +H = { a: 3, b: 1, c: 2, d: 1 } +class Array; alias __saved_push__ <<; remove_method :<<; def <<(x) = raise(""no""); end +begin + p H.sort_by { |k, v| v }, [3, 1, 2].sort_by { -_1 }, H.min_by(2) { |k, v| v }, (1..4).sort_by { -_1 } +ensure + class Array; remove_method :<<; alias << __saved_push__; end +end +p [1] << 2 +", @" +[[:b, 1], [:d, 1], [:c, 2], [:a, 3]] +[3, 2, 1] +[[:b, 1], [:d, 1]] +[4, 3, 2, 1] +[1, 2] +"); + } + /// /// The expression of an endless def is not a line to TracePoint :line (prism gives it no newline flag): CRuby reports /// no event for it, with or without a rescue modifier, but does for statements in parentheses in it and in a block. diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index a70e93f42..02162dc71 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -615,8 +615,8 @@ def __sort_by_key__(block) keys = [] each do |*values| item = __enum_item__(values) - keys << (values.size == 1 ? block.call(item) : __enum_yield__(values, &block)) - items << item + keys.__send__(:__list_push__, values.size == 1 ? block.call(item) : __enum_yield__(values, &block)) + items.__send__(:__list_push__, item) # the block #each was given answers nil, as MRI's does, should #each keep it and call it nil end @@ -634,8 +634,8 @@ def __list_sort_by_key__ items = [] keys = [] each do |item| - items << item - keys << yield(item) + items.__send__(:__list_push__, item) + keys.__send__(:__list_push__, yield(item)) end i = -1 items.__send__(:__list_sort_by__) { keys[i = i.succ] } @@ -1340,6 +1340,10 @@ def drop_while # change when a program redefines Array#sort_by. alias :__list_sort_by__ :sort_by private :__list_sort_by__ + # and Array#push, with which they gather the keys and elements: a program's own Array#<< is + # not called by MRI's sort_by + alias :__list_push__ :push + private :__list_push__ # #dig indexes with an Integer and nothing else: unlike #[] it does not take a # Range or an arithmetic sequence, because there would be no way to keep # digging into the several elements that would answer. From 9eeb3156fee1850bf840ce245052397de44b5ada Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:43:52 +0000 Subject: [PATCH 238/439] Ledger: perf/procscope, a literal's scope unpublished measures nothing (gaps 16, 13) Change B of Docs/light-frame-literal-blocks.md was prototyped for timing and not kept: a narrow literal's Proc over a scope that is not published as the frame's left `nb { }` at 120 ns and made `a.each { }` slower (148 -> 160), since an unpublished scope cannot be parked. With perf/literalsite's result, neither the full site nor the publication is a literal's cost: it is the scope object and the Proc themselves. The doc and the ledger record the numbers and a side finding (a literal given to a method that ignores its block is never parked); Util/bench/iter-shapes.rb gains `nyl`, a callee that yields. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Docs/light-frame-literal-blocks.md | 33 +++++++++++++++++++++++++++++- Util/bench/iter-shapes.rb | 3 +++ Util/perf/LEDGER.md | 24 ++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/Docs/light-frame-literal-blocks.md b/Docs/light-frame-literal-blocks.md index a3b76e756..d54fb96f9 100644 --- a/Docs/light-frame-literal-blocks.md +++ b/Docs/light-frame-literal-blocks.md @@ -1,7 +1,8 @@ # A literal block in a light frame: what it costs, and a Proc without a method scope Status: measured and designed in round thirty-seven (perf/lazyproc); change A built in perf/literalsite -(`IR_LIGHT_LITERAL_CALLS`, on), which also attributed the cost - see "What A measured" below. B is not built. It is the remainder of +(`IR_LIGHT_LITERAL_CALLS`, on), which also attributed the cost - see "What A measured" below. B was +prototyped in perf/procscope and rejected by its measurement - see "What B's prototype measured". It is the remainder of gap 13 of `Util/perf/LEDGER.md` (the fixed cost of calling an iterator) and a case of gap 16 (a light frame that ends up making its scope). @@ -57,6 +58,36 @@ no longer makes the scope (208 -> 24 bytes a call with parking off). The 45 ns i published: the object, `LeaveLightMethodFrameSlow`, the parking around it. That is B's ground, and B is what the literal's own cost (`nbl`, `each1`) needs. +## What B's prototype measured (perf/procscope) + +A prototype of B, for timing only (`IR_PROC_SCOPE=1`, not kept): a narrow literal's Proc made over a scope +held in `#proc-scope`, made by the same code as the frame's scope on demand but never published as the +frame's (`#scope` stays null, so the frame leaves through the inlined fast path and does not park; the +frame's own scope on demand takes `#proc-scope` if it exists). Six alternating rounds, ns per call: + +| shape | off | prototype | CRuby | +|---|---|---|---| +| `nbl`: `nb { }` (the callee ignores the block) | 120 | 120 | 40 | +| `nyl`: `ny { 1 }` (the callee yields) | 164 | 169 | 54 | +| `eachl`: `a.each { }` | 148 | 160 (1.08) | 70 | +| `map1`: `a.map { \|x\| x + 1 }` | 193 | 198 | 117 | + +**Publishing costs nothing measurable** (`nbl`, where neither arm parks: 120 and 120), and where the scope +is parked today the unpublished one cannot be, so it is allocated on every call and is slower (`eachl`). +With A's result: neither the full site nor the publication is the literal's cost. It is the scope object +and the Proc themselves - made, or taken parked and made again, which cost the same (`IR_PARKED_SCOPES=0` +leaves every shape's time as it is) - and, for a callee that yields, the conversion and the yield +(`nyl` 164 against CRuby's 54). What would take it is no heap scope and no heap Proc for a literal that +does not escape: a block passed as the frame's locals and code, as CRuby passes a block (a pointer to the +caller's frame), with the scope and Proc made when something asks for them - the TruffleRuby way, which in +IronRuby means a block calling convention that is not a Proc. That is a project, not a step. + +A finding on the side: **parking never works for a literal given to a method that ignores its block** +(`def nb; 1; end; nb { }`: 288 bytes a call with parking on, against 48 for `ny { }`, which yields). Such a +callee never converts the block, as far as the bytes show, so its Proc is not marked reusable and staging +fails on every call (not traced further). The shape is rare in real code; noted for whoever next touches +the parking. + ## How a literal reaches its method today - **The method's locals.** A light body's locals are in the tuple the scope made on demand wraps diff --git a/Util/bench/iter-shapes.rb b/Util/bench/iter-shapes.rb index e047e7583..90c1377bf 100644 --- a/Util/bench/iter-shapes.rb +++ b/Util/bench/iter-shapes.rb @@ -17,6 +17,8 @@ P = proc { } class O def nb; 1; end + def ny; yield; end + def nyl(a) = ny { 1 } def nb0(a) = nb def nbp(a) = nb(&P) def nbl(a) = nb { } @@ -87,3 +89,4 @@ def t(name, n) t("nbx", N) { |n| i = 0; s = 0; while i < n; s += o.nbx(a1); i += 1; end; s } t("nby", N) { |n| i = 0; s = 0; while i < n; s += o.nby(a1); i += 1; end; s } t("nbz", N) { |n| i = 0; s = 0; while i < n; s += o.nbz(a1); i += 1; end; s } +t("nyl", N) { |n| i = 0; s = 0; while i < n; s += o.nyl(a1); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 43cf9bb74..5e65aeece 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1186,6 +1186,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the full site costs about nothing, and the literal's own ~60 ns is the scope made and published (the object, `LeaveLightMethodFrameSlow`, the parking around it) plus the Proc: change B is what is left for `nb { }` and `a.each { }`. + perf/procscope then prototyped B for timing (not kept, see Rejected) and it measured nothing + to take: publishing the scope costs nothing (`nb { }` 120 -> 120 ns), and an unpublished + scope cannot be parked, so `a.each { }` got slower (148 -> 160). The literal's cost is the + scope object and the Proc themselves, made or taken parked - which cost the same - and for a + callee that yields the conversion and the yield (`ny { 1 }` 164 against CRuby's 54). No step + of the frame's bookkeeping is left to cut; what would take it is a block that is not a heap + Proc over a heap scope until it escapes, a calling convention of its own. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per @@ -7408,6 +7415,23 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/procscope (round thirty-seven, 2026-11-28) - a literal's Proc over a scope made but not + published as the frame's (change B of `Docs/light-frame-literal-blocks.md`): prototyped, measured, + not kept** (gaps 16 and 13). A timing prototype (`IR_PROC_SCOPE=1`): for a body whose literals are all + narrow, the literal's instantiation took `#proc-scope ?? (#proc-scope = MakeScope)` instead of the + frame's scope made on demand, and the frame's own scope on demand took `#proc-scope` if it existed, so + `#scope` stayed null, the frame left through the inlined fast path and did not park. Six alternating + rounds, ns per call, off against prototype (CRuby): `nb { }` 120 / 120 (40), `ny { 1 }` 164 / 169 (54), + `a.each { }` 148 / 160, 1.08 (70), `a.map { |x| x + 1 }` 193 / 198 (117), controls level. Publishing + is not the cost, and an unpublished scope gives up parking. With perf/literalsite (the site is not it + either), what a literal costs its caller is the scope object and the Proc themselves; the frame's + bookkeeping around them has nothing left to cut. So the escape hazards the round was to build for (a + LightScopeRequired after the Proc was made, binding in a callee after an escape, the kept Proc called + after the return, two literals sharing `#proc-scope`, threads, a TracePoint enabled mid-call) got no + matrix: the prototype ran only `Util/literal-block-light-matrix.rb` (CRuby's output) as a smoke test. + Found on the side: `def nb; 1; end; nb { }` allocates 288 bytes a call with parking on, where a callee + that yields gets 48: a literal given to a method that never touches its block is never parked. + - **perf/dotsfwd (/perf-frame, 2026-11-27) - `...` forwarding without the rest Array: stopped before building, the forwarded values are reachable after the call** (no code; on bbe4b1a, 4320d4a with claude/perf-lsite and perf/delegate's shape files). The target was the callee's From 56526b1fdb5177f912239613ce11ad866d42040f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:46:30 +0000 Subject: [PATCH 239/439] A light frame's scope holds its block until it is parked, not for good When a light-frame method that was given a literal block made its scope (CreateMethodScopeLazy, ReuseParkedScopeLazy), it cleared the block's ReusableFlag for good, since whatever asked for the scope might keep it. So a caller that passes a literal block to a method whose own block literals need its scope - som.rb's `Vector#each' and `has_some', `def each; (a..b).each { |i| yield @s[i] }; end' - could never park its own scope and Procs: Havlak's `contains', `find_set' and most of its helpers made a method scope, a Proc and BlockParams on every call, about half of the 1.9 GB an iteration allocates. Now the scope only holds the block (Proc.HeldFlag), which makes it not reusable while set, and EndPark lifts the hold when it parks the scope: parking proves that nothing captured the scope and that its own Procs are reusable and inactive, so nothing outlived the call that could reach the block through it. A call that does not park, an exception, and every other ClearReusable (a captured scope the block ran in, a retry) leave the block not reusable, as before. And the light-frame screen took `(a..b)' out of bodies with literal blocks because SOM's `each' measured 5-7% slower per call as a light frame; that was when its callers could not park anyway. With the hold it is let in, so the callers of such methods park. IR_SCOPE_HELD_BLOCKS=0 restores both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Builtins/Proc.cs | 38 ++++++++++++++++--- .../Ast/Definitions/MethodDefinition.cs | 6 ++- Src/Ruby/Runtime/RubyOps.cs | 8 ++-- 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index ba80774af..004a87698 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -75,6 +75,17 @@ public partial class Proc : RuntimeFlowControl, IDuplicable { // a block hands a Proc object on, as one whose scope converted it does (see BlockParam.IsLiteralBlock). private const int MethodConverterFlag = 16; + // The light-frame method the proc was given to made its scope, which holds the proc (RubyOps.CreateMethodScopeLazy): while + // it is set the proc is not reusable, as if ReusableFlag were clear. Unlike a clear ReusableFlag it is lifted again - by + // that scope's parking (RubyOps.EndPark), which proves that nothing kept the scope - so that the caller's literal stays + // reusable when its callee's scope is parked (`c.each { }' where `def each; (a..b).each { |i| yield @s[i] }; end'). + // A call that does not park, an exception, any other clear of ReusableFlag leave the proc not reusable, as they did. + private const int HeldFlag = 32; + private const int ReusableMask = ReusableFlag | HeldFlag; + + /// IR_SCOPE_HELD_BLOCKS=0: a light-frame method's scope clears its block's ReusableFlag for good, as it did. + internal static readonly bool ScopeHeldBlocksEnabled = Environment.GetEnvironmentVariable("IR_SCOPE_HELD_BLOCKS") != "0"; + /// /// The state few procs have, out of line: a Proc is allocated for every call with a literal block. /// @@ -127,9 +138,9 @@ internal void ConvertAsFrame() { /// literal allows that (BlockDispatcher.ReusesProc) and no TracePoint listens, which could hand out a scope it runs in. /// internal void ConvertAsLightFrame() { - _kind = (_dispatcher.ReusesProc && TracePoint.ActiveEvents == 0) + _kind = ((_dispatcher.ReusesProc && TracePoint.ActiveEvents == 0) ? (int)ProcKind.Proc | SelfConverterFlag | ReusableFlag - : (int)ProcKind.Proc | SelfConverterFlag; + : (int)ProcKind.Proc | SelfConverterFlag) | (_kind & HeldFlag); _activeFlowControlScope = this; } @@ -156,15 +167,32 @@ internal void ClearReusable() { _kind &= ~ReusableFlag; } + /// + /// The scope of the light-frame method this proc was given to was made, and holds it (see HeldFlag): ClearReusable until + /// . + /// + internal void HoldForScope() { + if (ScopeHeldBlocksEnabled) { + _kind |= HeldFlag; + } else { + _kind &= ~ReusableFlag; + } + } + + /// The scope that held this proc is being parked: nothing kept it (see HeldFlag). + internal void ReleaseHold() { + _kind &= ~HeldFlag; + } + internal bool IsReusable { - get { return (_kind & ReusableFlag) != 0; } + get { return (_kind & ReusableMask) == ReusableFlag; } } /// /// TryReuse would succeed: nothing but the frame that made the proc holds it (see RubyOps.ParkMethodScope). /// internal bool IsReusableAndInactive { - get { return (_kind & ReusableFlag) != 0 && _activeFlowControlScope == null; } + get { return (_kind & ReusableMask) == ReusableFlag && _activeFlowControlScope == null; } } /// @@ -204,7 +232,7 @@ internal void ClearForPark() { /// [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] internal bool TryReuse() { - if ((_kind & ReusableFlag) != 0 && _activeFlowControlScope == null) { + if ((_kind & ReusableMask) == ReusableFlag && _activeFlowControlScope == null) { _kind = (int)ProcKind.Block; return true; } diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 33dde4d81..bb4167ad7 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -1255,10 +1255,12 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong // Range#initialize checks the stack before the <=> it calls for bounds that are not two Integers. Not in a body // with literal blocks: its light frame makes the scope before the Proc all the same, and SOM's // `def each; (@first..(@last - 1)).each { |i| yield @s[i] }; end' was 5-7% slower per call as one than with - // the scope made on entry (`(a..b)' kept such a body out of light frames until then). + // the scope made on entry (`(a..b)' kept such a body out of light frames until then). Unless the block such a + // light frame is given stays reusable when its scope is parked (Proc.HeldFlag): a method with a scope converts + // its block for good, so its caller, Havlak's `contains' and `find_set', could not park its own scope and Proc. var range = node as RangeExpression; if (range != null) { - if (blockLiterals) { + if (blockLiterals && !IronRuby.Builtins.Proc.ScopeHeldBlocksEnabled) { return Refuse(why, "RangeExpression in a body with literal blocks"); } return IsScopeFree(range.Begin, false, why) && IsScopeFree(range.End, false, why); diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index b8e5517bb..3d5ebb881 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -299,7 +299,7 @@ private static ParkedProcs TakeParkedScopeSlow(ParkedScopeSlot/*!*/ slot, Parked // (as CreateMethodScopeLazy: the scope holds the block, and whatever asked for the scope may keep it) if (blockParameter != null) { - blockParameter.ClearReusable(); + blockParameter.HoldForScope(); } var scope = parked.Scope; scope.Reinitialize(locals, selfObject, blockParameter, interpretedFrame, rfc, calleeName); @@ -402,6 +402,8 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R proc?.ClearForPark(); } var methodScope = (RubyMethodScope)scope; + // nothing kept the scope (BeginPark) nor a Proc of it (StageParkedProc): nor the block it held (Proc.HeldFlag) + methodScope.BlockParameter?.ReleaseHold(); methodScope.ClearCallState(); parked.Scope = methodScope; parked.ThreadId = Environment.CurrentManagedThreadId; @@ -511,9 +513,9 @@ public static RubyMethodScope CreateMethodScopeIfTraced(MethodFrameShape/*!*/ sh RubyModule/*!*/ declaringModule, MutableTuple locals, object selfObject, Proc blockParameter, InterpretedFrame interpretedFrame, RuntimeFlowControl/*!*/ rfc, string calleeName) { - // the scope holds the block, and whatever asked for the scope may keep it + // the scope holds the block, and whatever asked for the scope may keep it - until the scope is parked (Proc.HeldFlag) if (blockParameter != null) { - blockParameter.ClearReusable(); + blockParameter.HoldForScope(); } return new RubyMethodScope(shape, parentScope, declaringModule, locals, selfObject, blockParameter, interpretedFrame, rfc, calleeName); From 50b07b5603b20bb764768d32b3ca64f585891dbb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:47:09 +0000 Subject: [PATCH 240/439] Ledger: the two faults round 6's gate caught perf/havlak2's method-table reads outside the class hierarchy lock (fixed in f67ac44) and perf/json's case dispatch of Symbol whens as Strings (fixed in 540bdb0), each with why the experiment's own checks missed it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 5eafa4a76..74b2740b6 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -8861,3 +8861,24 @@ What to take from it: Off by default (`IR_FORWARD_REST=1` turns it on); `Util/forward-rest-matrix.rb` pins the readers. A question for any change that lets two frames share what Ruby copies: list every way the frame can be read after the call - eval by any name, binding by any route, TracePoint - before the walk. + +### Caught by the gate (round thirty-seven, round 6) + +- **A method table read outside the class hierarchy lock** - perf/havlak2, before it merged into master. + `JitStub.IsLeafMethodOfSomeClass` moved onto `ClassesDefining`, which takes the lock and lets it go + before it returns, and then read each class's method table (`TryGetDefinedMethod`) outside it; + `AgreedAccessorVariable`'s strict test did the same. The Release build, which every matrix runs, does + not check the lock; the Debug build's `RequiresClassHierarchyLock` assertion aborted 11 IronRuby.Tests + processes (the TLS, socket and Integer_FDivCoerced1 tests among them). Fixed in f67ac44. The + experiment had run its matrices and specs, and IronRuby.Tests only by name: the full suite on a Debug + build is the check that reads the locking assertions, and is now asked of every round that touches the + JIT or lookup code. +- **A `case` over Symbol literals dispatched as one over Strings** - perf/json, before it merged into + master. `CaseExpression.TryMakeStringDispatch` accepted `comparison as StringLiteral`, and a + `SymbolLiteral` is a `StringLiteral` in the AST: `case "all" when :all` ran the `:all` arm, and + `Matrix#each("all")` returned instead of raising ArgumentError (three library/matrix specs, the sweep). + Fixed in 540bdb0 (CaseEquals4; case-string-matrix's Symbol section). The experiment's matrix had 786 + rows and missed it twice over: the dispatch runs only on a method's first, uncompiled calls (the method + JIT then takes the method, and tests for a Symbol first), and it stands aside once the runtime has a + refinement, which the matrix made before most of its rows. A matrix for a fast path that only cold + code takes has to call each case cold, on a fresh method, before anything that disables the path. From 4b99330de96eff446b3be96c1274eb71ce981b61 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:47:54 +0000 Subject: [PATCH 241/439] Design: a block that is not a Proc until it escapes (gaps 13 and 16) Design only. Docs/block-calling-convention.md (new) has the cost model of a literal block per call, measured by clock and bytes against CRuby (ny { 1 } 160 ns against 50, a.each { |x| } 142 against 73; allocation is not the time), the nine steps IronRuby takes for it against CRuby's captured block on the caller's frame, a block descriptor that a callee yields to and that is made a Proc only when it escapes, every way it can escape or be observed and what each must do, and stages that can each be kept alone: 0 (attribution, which this host cannot do and which decides the rest), A ([BlockNotKept] library iterators), B (Ruby methods that only yield), C (pass-on), D (literals that read the frame's locals), with their matrices, upper bounds, and what the light frames, the call sites, the method JIT and the block-loop tier must change. The ledger points to it under gap 16. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Docs/block-calling-convention.md | 185 +++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 10 ++ 2 files changed, 195 insertions(+) create mode 100644 Docs/block-calling-convention.md diff --git a/Docs/block-calling-convention.md b/Docs/block-calling-convention.md new file mode 100644 index 000000000..38cbd5487 --- /dev/null +++ b/Docs/block-calling-convention.md @@ -0,0 +1,185 @@ +# A block that is not a Proc until it escapes: design + +Status: design only (round thirty-seven, perf/bcc). It follows `Docs/light-frame-literal-blocks.md`, +whose three experiments removed the candidates one by one: the full call site costs nothing +(perf/literalsite), publishing the frame's scope costs nothing (perf/procscope), and allocating the +scope and the Proc costs what reusing them does (`IR_PARKED_SCOPES=0` leaves every time as it is). What +is left is the work of the block protocol itself. This document says what that work is, what CRuby does +instead, a representation that could skip it, and stages that can each be built and kept on their own. +**Stage 0 is a measurement**, because the gain of every later stage depends on which steps cost what, +which this host cannot show (no `perf`; callgrind does not name JIT code). + +## 1. The cost model + +### Measured (round thirty-seven, this host, Release net10.0, ns and bytes per call of the caller) + +The caller is a light method; `ny` is `def ny; yield; end`, `keep` is `def keep(&b) = b`, `pass` is +`def pass(&b) = ny(&b)`. Bytes are the thread's allocated bytes; 22 B of each line is the driver's +(`nb0`, a call without a block, has them too). + +| shape | CRuby ns | IronRuby ns | bytes | parking off: ns, bytes | light frames off: ns, bytes | +|---|---|---|---|---|---| +| `nb0`: `nb` | 36 | 59 | 22 | 37, 22 | 30, 22 | +| `ny1`: `ny { 1 }` | 50-53 | 160-161 | 70 | 169, 358 | 185, 518 | +| `nys`: `s = 0; ny { s += 1 }; s` | 63 | 158 | 54 | 174, 342 | 184, 502 | +| `e1`: `a.each { \|x\| }` over [1] | 73-75 | 142-145 | 70 | 161, 358 | 136, 70 | +| `e1s`: `s = 0; a.each { \|x\| s += x }; s` | 81 | 147 | 54 | 161, 342 | 142, 54 | +| `pon`: `pass { 1 }` (passed on) | 85 | 195 | 358 | 194, 358 | 254, 702 | +| `cv`: `keep { 1 }.call` (converted) | 239 | 172 | 358 | 170, 358 | 205, 542 | + +What it says: + +- **A literal block costs IronRuby about 100 ns per call against CRuby's 15-40.** `ny { 1 }` is 160 + against 50; the yield itself is about 11 ns (perf/yieldloop), as CRuby's is. +- **The bytes are not the time.** With parking, a call allocates 48 bytes beyond the driver; without it + 336, and the time moves by 10 ns or less. Light frames off (a scope at entry) adds 160 bytes and + ~25 ns to the Ruby-callee shapes. The ~290 bytes a literal used to cost, by the classes' fields (not + measured one by one): the method scope (~140), the Proc (~80), its BlockParam (~48), the locals tuple + (~24). +- **Passing a block on is never parked** (`pon`: 358 bytes and 195 ns, parking on or off): the callee + that names its block (`&b`) converts the Proc as a method's (`ConvertAsMethodFrame`), which is not + reusable. +- **Converting is already cheaper than CRuby** (`cv` 172 against 239): CRuby makes its Proc and moves + the frame's environment to the heap then (`vm_make_env_object`); IronRuby already has both. + +### What IronRuby does per call of `ny { 1 }` from a light method (read from the code) + +| step | where | what | +|---|---|---| +| 1 | caller | the scope made on demand: `TakeParkedScope` (an exchange) and `ReuseParkedScopeLazy` (a dozen fields), or `CreateMethodScopeLazy`; the locals tuple made at entry (`MakeLocalsStorage`: a body with a literal keeps its locals in a heap tuple) | +| 2 | caller | the Proc: `InstantiateParkedBlock` (the parked Proc taken, `ReuseParked`, `TryReuse`), or `new Proc` | +| 3 | caller | the call through the light site, the Proc its block argument (perf/literalsite) | +| 4 | callee | `CreateRfcForMethod(proc)`: the Proc becomes the callee's flow-control frame (`ConvertAsFrame`: kind, the reusable flag, `_activeFlowControlScope`) - it is what a `break` in the block targets | +| 5 | callee | `yield`: `ReuseBfcForYield` (the Proc's `YieldBlockParam` reset), `RubyOps.Yield0`/`Yield1` -> the dispatcher -> the block's compiled lambda | +| 6 | block | entry: `EnterScopeFreeBlock` or `TakeReusableBlockScope`/`CreateReusableBlockScope` (a block that reads an enclosing local reaches it through `Proc.LocalScope`) | +| 7 | callee | after the yield: `LightMethodYield` (the BlockParam's return reason: break?) | +| 8 | callee | exit: `LeaveLightMethodFrame(rfc, scope)`: the Proc is an active rfc, so the slow path, `LeaveMethodFrame` | +| 9 | caller | exit: `BeginPark` / `StageParkedProc` / `EndPark` (an exchange, `ClearForPark`, `ClearCallState`) | + +### What CRuby does + +The caller's control frame holds a captured block, `rb_captured_block { self, ep, code.iseq }`, written by +`send` with no allocation; the callee receives a *block handler*, that pointer tagged as an iseq block +(`VM_BH_FROM_ISEQ_BLOCK`). `yield` (`vm_invoke_iseq_block`) pushes a frame for the block whose `ep` is the +captured one, so the block reads the caller's locals in the caller's own stack frame. `break` finds its +target by the captured `ep`. Nothing is on the heap until something asks for a Proc (`&b`, `proc`, +`binding`): `rb_vm_make_proc` then moves the environment to the heap (`vm_make_env_object`) and every +frame that shares it follows. Steps 1, 2, 4, 8 and 9 above have no counterpart; 5-7 are a frame push. + +## 2. The representation + +A **block descriptor**: what a callee needs to yield to a literal, and nothing it needs only when the +block escapes. + + sealed class BlockDescriptor : RuntimeFlowControl // it is the callee's flow-control frame, as the Proc is now + object Self + BlockDispatcher Dispatcher // the literal's code + MutableTuple Locals // the caller frame's tuple (or null: a narrow literal) + FrameHeader Frame // the caller's rfc, declaring scope, module, shape, block, callee name + Proc Materialized // the Proc made from it, once something asked + +- **One per (literal, frame), reused across calls of the frame**, as the parked Proc is now, but taken + with no exchange: a light frame owns its descriptors in CLR locals for the call (the caller is the + only one that runs the literal), and a recursive or concurrent call of the same method has its own + frame and its own descriptors. So the per-call work of steps 1, 2 and 9 becomes: fill four fields. +- **The scope is made from it on demand** - `binding`, `eval`, `local_variables`, a TracePoint, a callee + that answers LightScopeRequired, `$~` - from `Frame` and `Locals`, exactly as the light frame's lazy + scope is made today, and kept on the descriptor (one scope per invocation: the frame's own lazy scope + takes the descriptor's if it exists). +- **The Proc is made from it on demand** (`Materialize`): when a callee converts the block (`&b` in a + Ruby callee, `Proc.new`, `define_method`, `proc`, `lambda`, a C# method whose block parameter is a + `Proc` and not a `BlockParam`), or stores it. The Proc's scope is the descriptor's scope, made then; + from then on the descriptor answers with that Proc and is not reused by the frame's next call (it + escaped). That is CRuby's `rb_vm_make_proc`. + +What each kind of callee does with it: + +| callee | today | with a descriptor | +|---|---|---| +| a library `[BlockNotKept]` iterator (Array#each, Integer#times...) | `CreateBfcForBlockNotKept(proc)`: the Proc's reused BlockParam | a BlockParam over the descriptor (its `Proc` property materializes); the yield goes to `Dispatcher` with `Self` and the descriptor as the block's parent frame | +| a Ruby method that only yields (`def ny; yield; end`, a light frame) | step 4, 5, 7, 8 | the descriptor is its rfc; `yield` calls `Dispatcher` directly; `LightMethodYield` reads the descriptor's flow state | +| a Ruby method that passes it on (`def pass(&b) = ny(&b)`) | converted as a method's: never reused, 358 bytes | stage (c): a `&b` that is only passed on passes the descriptor (the light frame's block parameter is a descriptor until something reads `b` otherwise) | +| a method that converts it (`&b` read, `Proc.new`, `define_method`) | the Proc | `Materialize` | + +## 3. Every way it can escape or be observed + +| how | what must happen | +|---|---| +| `&b` read as an object, stored, returned, `b.call` | `Materialize`: the Proc, over the scope made from the frame now; the descriptor is spent | +| `Proc.new`/`proc`/`lambda` with no block of their own, `define_method`, `instance_exec(&b)` | the same, through the BlockParam's `Proc` | +| `binding` in the block, `eval`, `local_variables`, `__method__` | the block's scope is made with the descriptor's scope as its parent, made now from `Frame` and `Locals` | +| `binding`/`eval` in the caller after the call | the caller's lazy scope is the descriptor's if one was made (one scope per invocation) | +| a TracePoint `:b_call`/`:line` in the block, `binding.local_variables` | as `binding` in the block | +| `$~`, `$_` set by a callee of the block | through LightScopeRequired: the block's scope, with the descriptor's scope as parent | +| `break` | the descriptor is the callee's rfc, as the Proc is now (`SetFlowControl(Break, converter)`); after the frame returned, `LocalJumpError` as today (the frame header says the method has left) | +| `return` in the block | not in the first stages (the narrow shape has none) | +| `next`, `redo`, raise, throw | the block's own; nothing reaches the descriptor | +| a Fiber suspended in the block, `Enumerator#next` | the descriptor stays in use until the callee returns; the frame does not reuse it while its call is in flight (it owns it for the call) | +| another thread running the block (a callee that hands it to `Thread.new`) | that is a conversion (`Thread.new` takes a Proc): materialized | +| re-entrancy: the block calls the caller's method again | a new frame, its own descriptors | +| `yield` after the callee returned (a Proc kept and called) | only a materialized Proc can be kept; its scope's frame header says the method left | +| `block_given?` in the callee | true: the descriptor is a block | +| `Proc#==`, `object_id` of the block | only on a materialized Proc | + +## 4. Stages + +Each behind a switch of its own, with its matrix before its code, keepable alone. + +**Stage 0 - attribution (no runtime change).** Where do the ~100 ns of `ny { 1 }` and the ~70 of +`a.each { |x| }` go among steps 1-9? A `perf` profile on a host that has it (`Util/perf/profile.sh` with +a shape driver), or the steps timed one by one in C# (a test harness that runs the emitted sequence with +each step replaced by a no-op that keeps its result). The table of steps above is the checklist. Expected +outcome: an upper bound for each stage below; build only the stages whose steps carry the time. + +**Stage A - `[BlockNotKept]` library iterators, narrow literals, light callers.** The literal of the +narrow shape (`MethodDefinition.HasOnlyNarrowLiterals`) given to a `[BlockNotKept]` library method is +passed as a descriptor with `Locals = null` (the literal reads no local) and `Frame` the light frame's +header; `CreateBfcForBlockNotKept` gains an overload taking it. Removes steps 1, 2 and 9 for those calls +(the scope is never made unless escaped). Upper bound: `e1` 142 -> about `nb0` + the iterator + the +yield, by the table near 90 (CRuby 73). Matrix: `Util/literal-block-light-matrix.rb` sections 1-5 for +Array#each, #map, Integer#times, Hash#each; the escape rows of section 3 above (a `binding` through +`send` in the block, `$~` set through `send`, a TracePoint `:b_call` binding, `break` with an ensure, +Enumerator#next suspended in the block, re-entrancy, four threads); `IR_LIGHT_FRAMES=0`, +`IR_PARKED_SCOPES=0`, the switch off. + +**Stage B - Ruby methods that only yield.** A light callee whose block is a descriptor uses it as its rfc +and yields to `Dispatcher` directly (steps 4, 5, 8 lose their Proc work). Needs the light frame's yield +(`YieldCall` in `LightFrameRewriter`) and `LightMethodYield` to take a descriptor, and `block_given?`, +`defined?(yield)` and `super` (which passes the block on) to see one. Upper bound: `ny1` 160 -> about +`nb0` + one yield, near 75 (CRuby 50). Matrix: block-given, block-pass, block-scope-reuse (all three), +block-nest-reuse, light-entry, light-rest, parked-scope, parked-iterator, plus a new row set for a Ruby +callee that yields, passes on, converts, and calls `block_given?`, each with a descriptor. + +**Stage C - pass-on.** A light frame whose `&b` is only passed on (`def pass(&b) = ny(&b)`, +`IsScopeFree`'s block pass) keeps a descriptor as a descriptor; any other read of `b` materializes. +Upper bound: `pon` 195 -> near `ny1` after stage B, and its 336 bytes to the driver's. Matrix: +block-pass-matrix, and a pass-on chain of three with a conversion at each depth. + +**Stage D - literals that read the frame's locals.** `Locals` the frame's tuple; the block's compiled +code reads its parent tuples from the descriptor instead of `Proc.LocalScope` (BlockDefinition's +`CreateScopeWithParent`). This is the general case (`e1s`, `nys`) and the one where CRuby's frame-pointer +design matters most; it needs the block's lambda to take a parent that is not a scope, which touches +every closure access. Upper bound: `e1s`, `nys` to stage A's and B's numbers. + +## 5. What the method JIT and the light frames must change + +- **Light frames** (`MethodDefinition.TransformLightFrame`, `LightFrameRewriter`): the literal's + instantiation becomes the descriptor's fill (stage A on); the lazy scope takes the descriptor's scope + (one per invocation); the exit drops `BeginPark`/`EndPark` for bodies whose literals are all + descriptors; a light callee's entry takes a descriptor as its rfc (stage B); its block parameter may be + a descriptor (stage C), with every read of it that is not a pass-on materializing. +- **Call sites** (`RubyCallAction`, `MethodDispatcher`, the library binder): the block argument's static + type is `object` (a Proc or a descriptor); rules that bind a `Proc` parameter materialize; rules that + bind a `BlockParam` take either. `[BlockNotKept]` is what says a library method takes a descriptor. +- **The method JIT** (`Runtime/Jit`): it never wraps a method that uses its block (the screen), so stages A + and C do not reach it; a typed body that *calls* an iterator with a literal block (stage A's caller) + bails today at the call with a block (`EmitCall`: "call with a block") unless it is a nested block loop + in an outlined core iterator (`JitCompiler.Nest.cs`), so nothing changes there either. Stage B makes a + yielding method's entry take a descriptor, which the JIT's entry stubs (`JitStub`) must pass through + untouched (they forward `blk`). +- **The block-loop tier** (`BlockLoopSite`, OSR): it outlines a block into a C# iterator's loop from the + BlockParam's Proc; with a descriptor it reads `Dispatcher`/`Self` from it, and a block-loop copy that + needs the block's scope asks the descriptor. +- **BlockParam** keeps one shape: it gains a descriptor field and a `Proc` property that materializes; + `IsLibProcConverter`, `Break`, `ReturnReason`, `MethodYield` read the descriptor where they read the Proc's + frame. diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 5e65aeece..4d6f3566f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1193,6 +1193,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has callee that yields the conversion and the yield (`ny { 1 }` 164 against CRuby's 54). No step of the frame's bookkeeping is left to cut; what would take it is a block that is not a heap Proc over a heap scope until it escapes, a calling convention of its own. + perf/bcc (design only) wrote that convention down: `Docs/block-calling-convention.md`. The + cost model per call (`ny { 1 }` 160 ns against CRuby's 50, `a.each { |x| }` 142 against 73; + 48 bytes with parking, 336 without, the time the same; a block passed on is never parked, + 358 bytes; a conversion is already faster than CRuby's, 172 against 239), the nine steps + IronRuby takes against CRuby's captured block on the caller's frame, a block descriptor + (self, dispatcher, the frame's tuple and header, the Proc made only on escape) and every + way it escapes, and stages: 0, attribution of the ~100 ns among the nine steps on a host + with perf, which decides the rest; A, `[BlockNotKept]` library iterators with narrow + literals; B, Ruby methods that only yield; C, pass-on; D, literals that read the frame's + locals - each with its matrix and an upper bound. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per From a6333765a258d8f463dd71694acf624e1f8644dd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:48:50 +0000 Subject: [PATCH 242/439] Method#unbind of a `public :m' entry gives the inherited body's owner `public :m' (or `private :m') in a subclass of the class that defines m leaves an entry that forwards to the inherited body. MRI's Method made of it has the subclass as #owner, but #unbind resolves the entry, so the UnboundMethod's #owner is the class that defines the body. IronRuby kept the subclass. The copy RubyModule.ResolveForwarderNoLock makes for such a Method now remembers the body it forwards to (ForwardedBody), and Method#unbind uses it; an alias keeps its own owner, as in MRI. Util/callable-parameters-matrix.rb: the "OwnerSub#privm unbind" row now agrees with CRuby 4.0. Method_UnbindForwarder1 holds CRuby's output; core/method, unboundmethod, proc, Module#public/#private/#instance_method specs pass (instance_method's known into/to error), as do 195 method, proc and visibility IronRuby.Tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 26 ++++++++++++++++++++++++ Src/Libraries/Builtins/MethodOps.cs | 3 ++- Src/Ruby/Builtins/RubyModule.cs | 3 +++ Src/Ruby/Runtime/Calls/RubyMemberInfo.cs | 7 +++++++ 5 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 7f83f4689..0351762cc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1153,6 +1153,7 @@ public Tests(Driver/*!*/ driver) { Kernel_ConversionsRoundingStep1, Method_OptionalAndKeywordParameters1, Method_BindingNonRubyCaller1, + Method_UnbindForwarder1, Method_OptionalAndKeywordParameters2, Range_MinMaxInclude1, Integer_StepMatchString1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 30ac41efa..731907336 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -6476,6 +6476,32 @@ class Object; alias bnd binding; end "); } + /// + /// A Method made of a `public :m' (or `private :m') entry has that module as #owner, but MRI's #unbind resolves + /// the entry to the inherited body: the UnboundMethod's owner is the body's. An alias keeps its own owner. + /// + public void Method_UnbindForwarder1() { + TestOutput(@" +class OwnerBase; def privm = 1; def pubm = 2; private :privm; end +class OwnerSub < OwnerBase; public :privm; private :pubm; alias_method :al, :privm; end +o = OwnerSub.new +[:privm, :al].each do |n| + m = o.method(n); u = m.unbind + p [n, m.owner, m.name, m.original_name, u.owner, u.name, u.original_name, u.bind(o).call] +end +p OwnerSub.instance_method(:pubm).owner, OwnerSub.instance_method(:pubm).bind_call(o), OwnerSub.new.public_method(:privm).unbind.owner +p OwnerSub.private_instance_methods(false), OwnerSub.public_instance_methods(false).sort +", @" +[:privm, OwnerSub, :privm, :privm, OwnerBase, :privm, :privm, 1] +[:al, OwnerSub, :al, :privm, OwnerSub, :al, :privm, 1] +OwnerSub +2 +OwnerBase +[:pubm] +[:al, :privm] +"); + } + /// /// A method with optional positional parameters and keywords (`def m(a, b = 2, k: 3)') keeps its /// optionals as optional parameters; a keyword call that leaves one out has its keyword hash moved diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 0e505d38b..44c1e89fb 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -139,9 +139,10 @@ public static RubyMethod GetSuperMethod(RubyContext/*!*/ context, RubyMethod/*!* [RubyMethod("unbind")] public static UnboundMethod/*!*/ Unbind(RubyMethod/*!*/ self) { + // a Method made of a `public :m' entry unbinds to the inherited body, owner and all, as MRI's does return new UnboundMethod( self.IsMethodMissing ? self.MethodMissingOwner : self.GetTargetClass(), - self.Name, self.Info, self.IsMethodMissing + self.Name, self.Info.ForwardedBody ?? self.Info, self.IsMethodMissing ); } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 1fd1a2030..9c0399a27 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -2853,6 +2853,9 @@ private static MethodResolutionResult ResolveForwarderNoLock(MethodResolutionRes var copy = target.Info.Copy(forwarder.Flags, target.Info.DeclaringModule); copy.AliasOwner = forwarder.AliasOwner ?? forwarderResult.Owner; copy.OriginalName = forwarder.OriginalName ?? target.Info.OriginalName; + if (forwarder.AliasOwner == null) { + copy.ForwardedBody = target.Info; + } return new MethodResolutionResult(copy, forwarderResult.Owner, true); } diff --git a/Src/Ruby/Runtime/Calls/RubyMemberInfo.cs b/Src/Ruby/Runtime/Calls/RubyMemberInfo.cs index 9c53638cd..eb425cb73 100644 --- a/Src/Ruby/Runtime/Calls/RubyMemberInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyMemberInfo.cs @@ -272,6 +272,13 @@ public virtual int GetEquivalenceHashCode() { /// public RubyModule AliasOwner { get; internal set; } + /// + /// For the copy a `public :m' / `private :m' forwarder resolves to (RubyModule.ResolveForwarderNoLock): the + /// inherited body it forwards to. MRI's Method made of such an entry has the forwarder's module as #owner, but + /// #unbind resolves the entry (method_entry_resolve_refinement / zsuper) and gives the body's own owner. + /// + public RubyMemberInfo ForwardedBody { get; internal set; } + public string OriginalName { get; internal set; } /// From 516fb7c62f18e605f343e7a6e4806a59d33adfde Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:50:37 +0000 Subject: [PATCH 243/439] Ledger: perf/bootparse landed, not gated (gap 26) The string evals of start-up precompiled in the startup library: what was measured, what was checked, and the next leads (Kernel#require's first-call compile, the JIT's re-parses). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Util/perf/LEDGER.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f309d9d31..c0a413274 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1560,6 +1560,13 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has lookup on each of ~67 types. Taken: Random's interop call made lazy, field and event names read from metadata, and the failure cache keyed by a class. -0.75 to -1.97% main-thread instructions on the R2R host, -0.10 to -1.13% on the release image. + 2026-11-27, perf/bootparse (Landed, not gated): the string evals start-up runs are compiled + into the startup library: specification.rb's and kernel_require.rb's (2.3 ms each on the R2R + host before their first call), every gemspec RubyGems loads (93 in `gem list`), Forwardable's + delegators. Main-thread instructions -2.1 to -6.8% on the R2R host and -2.7 to -8.6% on the release + image; best-of-10 wall -2 to -11% and -0 to -14%. Not taken: the JIT's re-parses of start-up methods + (2-3 ms of `-e 1`), and Kernel#require's first-call body compile (~10 ms, 4 ms of it the first + def-body transform's cold path), the next leads. 27. **Closed (perf/crubydiff, third round): `send` frames are hidden.** Was: **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a @@ -2415,6 +2422,43 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - For the gate: the shared rule's set now decides `!=` for every plain-object class a program has; the cases above are the ones that must leave a class out. +- **perf/bootparse (2026-11-27) - the string evals of start-up precompiled in the startup library (gap 26)** + - not gated. Base 4703cb5 (f67ac44 with perf/clrlookup). + What start-up parses at run time (R2R host, IR_PHASE_TIMES, IR_STARTUP_DLL_TRACE): the string evals, + each a prism parse, a transform and a lambda compile on the main thread. They are + specification.rb's `set_nil_attributes_to_nil` and kernel_require.rb's Kernel#require (~2.3 ms each, + both in `-e 1`), every gemspec RubyGems loads (62 default and 29 installed, 93 evals in `gem list`), + Forwardable's `def_delegator` texts (56, irb and reline) and irb's workspace binding. The JIT's 11 + re-parses of methods it compiles cost 2-3 ms and were left; Kernel#require's body compile at its first + call (~10 ms) is the larger single cost and the next lead. + Taken (bf64364): + - startup-files.rb runs its commands again with IR_EVAL_RECORD and writes startup-evals.txt (150 evals): + each text with everything EvalCodeCache keys an eval on (encoding, file, line, verbosity, method and + parameters, block levels, locals, the names of the modules of the lexical scope). + - `IronRuby.Aot startup --evals` compiles each as CompileEval would into a class of the library; + PrecompiledEvalsAttribute carries the keys and a SHA-256 of each text, so the texts stay out of + every boot. + - RubyUtils.Evaluate asks PrecompiledCode.TryClaimEval before compiling. A hit is the first runtime of + the process, the first eval of that key with that exact text, claimed once (Interlocked); anything + else compiles from text as before, and EvalCodeCache's rules are untouched. + Numbers (base / new, one batch each): + - Main-thread instructions (callgrind, TieredCompilation=0): R2R host `-e 1` -2.09%, `gem --version` + -2.64%, `gem list` -6.79%, `require "irb"` -5.44%, irb -4.83%; release image -2.74%, -3.28%, -8.58%, + -6.47%, -6.00%. + - Wall, best of 10 alternating (ms): R2R host 414/406, 498/476, 830/742, 834/776, 941/869; release image + 276/275, 344/305, 621/537, 628/557, 712/621. + Checked: the five commands print what the base prints (irb's start-up tip is random on either); + `__FILE__`/`__LINE__` and binding locals in a gemspec eval; a second load, a one-byte change, another file + or line compile from text; 8 threads loading all 29 installed gemspecs at once claim each once and agree; + Forwardable's backtraces. Matrices eval-locals, eval-defined, eval-literals, erb-escape, eval in the + gate's modes plus r2r, r2r with IR_STARTUP_DLL=none and r2r recording: PASS (32 same, 8 baseline). + Specs core/kernel/eval, library/rubygems (R2R and Release), core/binding, instance_eval, module_eval, + class_eval, language/file and line: as the base (the five known `into`/`to` errors). + IronRuby.Tests (Debug, net10.0): PASSED. + For the gate: a gemspec or forwardable.rb that changes only misses (the hash differs), but + startup-evals.txt then wants `startup-files.rb` rerun, which `--check` now says. Keys hold module names, + not modules: two modules of one name in one file at one line with the same text and locals share code, + which compiles the same either way. - **perf/clrlookup (2026-11-27) - what makes the CLR member lookups of start-up; Random's class found on first use; field and event names from metadata; a class key for the lookup failure cache (gap 26)** - not gated. Base 4320d4a. From f544d6d876b7c0c0bd3bb412c3c84f9b99831831 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:53:02 +0000 Subject: [PATCH 244/439] Method#to_proc: the lambda's source_location is the method's, by its rules The lambda Method#to_proc makes reported the file and line of the body behind the method, so for a core method the prelude writes in Ruby but MRI writes in C, method(:puts).to_proc.source_location named ruby4.rb while method(:puts).source_location (and CRuby's for both) is nil. Proc#source_location of such a lambda now answers what Method#source_location answers for the method it wraps. Util/callable-parameters-matrix.rb now agrees with CRuby 4.0. Method_ToProcSourceLocation1 holds CRuby's output; core/proc and core/method specs pass, as do 175 method and proc IronRuby.Tests. Left: the line numbers IronRuby gives for methods (Kernel#then, #tap) differ from CRuby's, in Method#source_location too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 23 +++++++++++++++++++++++ Src/Libraries/Builtins/ProcOps.cs | 8 +++++++- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0351762cc..f1871faff 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1154,6 +1154,7 @@ public Tests(Driver/*!*/ driver) { Method_OptionalAndKeywordParameters1, Method_BindingNonRubyCaller1, Method_UnbindForwarder1, + Method_ToProcSourceLocation1, Method_OptionalAndKeywordParameters2, Range_MinMaxInclude1, Integer_StepMatchString1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 731907336..b3a6cd1d0 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -6502,6 +6502,29 @@ p OwnerSub.private_instance_methods(false), OwnerSub.public_instance_methods(fal "); } + /// + /// Method#to_proc's lambda is located where Method#source_location says the method is: nowhere for a core + /// method that is C in MRI, though the prelude writes it in Ruby. + /// + public void Method_ToProcSourceLocation1() { + TestOutput(@" +require 'ruby4' +def mine = 1 +define_method(:dm) { 2 } +p method(:puts).to_proc.source_location, method(:then).to_proc.source_location == method(:then).source_location +p method(:mine).to_proc.source_location == method(:mine).source_location, method(:dm).to_proc.source_location == method(:dm).source_location +p [1].method(:each_slice).to_proc.source_location, 1.method(:+).to_proc.source_location, :upcase.to_proc.source_location +", @" +nil +true +true +true +nil +nil +nil +"); + } + /// /// A method with optional positional parameters and keywords (`def m(a, b = 2, k: 3)') keeps its /// optionals as optional parameters; a keyword call that leaves one out has its keyword hash moved diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index 2150e1126..7510e4516 100644 --- a/Src/Libraries/Builtins/ProcOps.cs +++ b/Src/Libraries/Builtins/ProcOps.cs @@ -134,6 +134,12 @@ public static bool IsLambda(Proc/*!*/ self) { [RubyMethod("source_location")] public static RubyArray GetSourceLocation(Proc/*!*/ self) { + // Method#to_proc's lambda is located where the method is, by the same rules: a core method that is C in + // MRI has no location even though the prelude writes it in Ruby + RubyMethod wrapped = self.Dispatcher.WrapsMethod ? self.Dispatcher.WrappedMethod : null; + if (wrapped != null) { + return MethodOps.GetSourceLocation(wrapped); + } // a proc that no Ruby source produced - Symbol#to_proc, Method#to_proc, a curried // proc - has no location to report if (self.Dispatcher.SourcePath == null) { @@ -341,7 +347,7 @@ private static void GetArgumentCountRange(Proc/*!*/ self, out int min, out int m RequireCallable(respondTo, other); return Proc.CreateNative(respondTo.Context, self.Kind, (blockParam, s, args, unsplat, procArg) => { - // the keywords the composition was called with go on to the function applied first + // the keywords the composition was called with go on to the function applied first object intermediate = self.Call(procArg, RubyOps.RestoreRuby2Keywords(unsplat.ToArray())); var site = callStorage.GetCallSite("call", 1); return site.Target(site, other, intermediate); From c8010fb4149281f62be7f5fdffa2cc7e3752df31 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:54:33 +0000 Subject: [PATCH 245/439] Util/held-block-matrix.rb: a caller's block held by its callee's scope Cases where the callee's scope escapes - a binding yielded through later, a Proc of the callee's kept that yields to the caller's block, an exception after the scope is made, a fiber, threads - and the caller's literal must not be reused. Prints what CRuby 4.0 prints with IR_SCOPE_HELD_BLOCKS on and off, IR_PARKED_SCOPES=0, -X:NoJIT -X:NoOSR and on the base; with the hold made a no-op, three rows go wrong. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/held-block-matrix.rb | 126 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 Util/held-block-matrix.rb diff --git a/Util/held-block-matrix.rb b/Util/held-block-matrix.rb new file mode 100644 index 000000000..e2cee1a44 --- /dev/null +++ b/Util/held-block-matrix.rb @@ -0,0 +1,126 @@ +# Differential matrix for a literal block given to a light-frame method whose scope is made (Proc.HeldFlag, +# IR_SCOPE_HELD_BLOCKS): the scope holds the block, which is not reusable until the scope is parked; parking proves that +# nothing kept the scope. Each case is a caller whose literal is reused for its next call (and its scope parked) unless the +# callee's scope escaped - through a binding, a Proc of the callee's that is kept, an exception, a fiber or a thread - and +# then the kept thing reaches the caller's block, which must still be the block of the call it was given in: its self, its +# locals, its object identity. Run it under CRuby and under ./ir.sh with the switch on and off and with the tiers off, and diff: +# +# ruby Util/held-block-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/held-block-matrix.rb > /tmp/on.txt +# IR_SCOPE_HELD_BLOCKS=0 ./ir.sh Util/held-block-matrix.rb > /tmp/off.txt +# IR_PARKED_SCOPES=0 ./ir.sh Util/held-block-matrix.rb > /tmp/noparked.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/held-block-matrix.rb > /tmp/notiers.txt + +def t(label) + print label.ljust(64), ' => ' + begin + v = yield + puts "#{v.inspect} (#{v.class})" + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +N = 3000 + +class Vec + def initialize(n); @s = Array.new(n) { |i| i + 1 }; @first = 0; @last = n; @kept = []; end + attr_reader :kept + # the shape the change is for: a light frame whose literal needs its scope, given a literal by its caller + def each; (@first..(@last - 1)).each { |i| yield @s[i] }; end + def each_bind(take); b = nil; (@first..(@last - 1)).each { |i| yield @s[i]; b = binding if take && i == 0 }; b; end + def each_keep(take); (@first..(@last - 1)).each { |i| yield @s[i] }; @kept << proc { |x| yield x } if take; nil; end + def each_raise(at); (@first..(@last - 1)).each { |i| raise IndexError, "at #{i}" if i == at; yield @s[i] }; end + def each_fiber; (@first..(@last - 1)).each { |i| Fiber.yield(yield(@s[i])) }; end +end + +class Caller + def initialize(v, tag); @v = v; @tag = tag; end + def sum; c = 0; @v.each { |x| c += x }; c; end + def sum_bind(n); c = 0; b = @v.each_bind(n % 1000 == 1) { |x| c += x * 10 + n }; [c, b]; end + def sum_keep(n); c = [n]; @v.each_keep(n % 1000 == 2) { |x| c << x; [@tag, n, x] }; c.size; end + def sum_raise(n); c = 0; @v.each_raise(n % 700 == 3 ? 1 : -1) { |x| c += x }; c; end + def tag; @tag; end +end + +t('the shape, hot') { v = Vec.new(4); c = Caller.new(v, :a); s = 0; N.times { s += c.sum }; s } + +t('a binding of the callee kept: yield through it later') { + v = Vec.new(3) + c = Caller.new(v, :a) + kept = [] + N.times { |n| r, b = c.sum_bind(n); kept << [n, b] if b } + N.times { |n| c.sum_bind(n + 5) } + kept.map { |n, b| [n, b.eval('yield 100'), b.receiver.equal?(v)] } +} + +t('a Proc of the callee kept: it yields to the caller block later') { + v = Vec.new(3) + a = Caller.new(v, :a) + bb = Caller.new(v, :b) + N.times { |n| (n.even? ? a : bb).sum_keep(n) } + v.kept.map { |pr| pr.call(7) } +} + +t('an exception leaves the callee after its scope is made') { + v = Vec.new(3) + c = Caller.new(v, :a) + errs = [] + s = 0 + N.times { |n| begin; s += c.sum_raise(n); rescue IndexError => e; errs << [n, e.message]; end } + [s, errs.first(3), errs.size] +} + +t('a callee suspended in a fiber while the caller runs again') { + v = Vec.new(3) + c = Caller.new(v, :a) + N.times { c.sum } + seen = [] + f = Fiber.new { v.each_fiber { |x| seen << [:fiber, x]; x * 2 } } + r1 = f.resume + mid = Array.new(100) { c.sum }.last + r2 = f.resume + [r1, mid, r2, seen] +} + +t('threads: one caller per thread, one callee shared') { + v = Vec.new(5) + ths = Array.new(4) { |ti| Thread.new { c = Caller.new(v, ti); s = 0; 3000.times { s += c.sum }; s } } + ths.map(&:value) +} + +t('threads: bindings kept while others call') { + v = Vec.new(3) + ths = Array.new(4) do |ti| + Thread.new do + c = Caller.new(v, ti) + kept = [] + 2000.times { |n| r, b = c.sum_bind(n * 4 + ti); kept << b if b } + kept.map { |b| b.eval('yield 1') } + end + end + ths.map(&:value) +} + +t('block_given? and the block identity across calls') { + k = Class.new do + def initialize; @a = [1, 2]; end + def m; seen = nil; (0..1).each { |i| seen = block_given?; yield @a[i] }; seen; end + end.new + c = Class.new do + def initialize(k); @k = k; @ids = []; end + attr_reader :ids + def go(n); @k.m { |x| x + n }; end + end.new(k) + r = nil + N.times { |n| r = c.go(n) } + r +} + +t('break from the caller block through the callee') { + v = Vec.new(4) + k = Class.new { def initialize(v); @v = v; end; def first_big(lim); @v.each { |x| break x if x > lim }; end }.new(v) + s = [] + N.times { |n| s << k.first_big(n % 4) if n > N - 5 } + s +} From 8553fc4761667a682771601cbce7597a92cef7a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 23:57:05 +0000 Subject: [PATCH 246/439] Stage 0 of the block calling convention: the block-cost harness and its numbers Src/IronRuby.Tests/Perf/BlockCostHarness.cs (new), run as `IronRuby.Tests /blockcost [N]` - not a test: Driver.Main dispatches to it only for that switch, and nothing of it is in IronRuby.dll. It hosts a runtime, takes real objects from Ruby code (a literal's compiled block dispatcher, a method scope, its declaring scope and module), and times the runtime calls a call with a literal block makes, each alone and then together, against the same calls end to end through Ruby. They add up: a literal costs 50-54 ns over a stored Proc and the parked cycle with the locals tuple is 52, about 16 of it the cycle's two atomics; passing any block and yielding costs another 55-63 ns, of which the yield is 16 and the rest is compiled code around a call with a block. Docs/block-calling-convention.md replaces its arithmetic bounds with these: stage A pays most per round, and the park's compare-exchange made a release write is a step of its own of about 8 ns per call. The ledger records it under gap 16. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Docs/block-calling-convention.md | 65 +++- Src/IronRuby.Tests/Driver.cs | 5 + Src/IronRuby.Tests/Perf/BlockCostHarness.cs | 336 ++++++++++++++++++++ Util/perf/LEDGER.md | 9 + 4 files changed, 414 insertions(+), 1 deletion(-) create mode 100644 Src/IronRuby.Tests/Perf/BlockCostHarness.cs diff --git a/Docs/block-calling-convention.md b/Docs/block-calling-convention.md index 38cbd5487..163100ae5 100644 --- a/Docs/block-calling-convention.md +++ b/Docs/block-calling-convention.md @@ -1,6 +1,7 @@ # A block that is not a Proc until it escapes: design -Status: design only (round thirty-seven, perf/bcc). It follows `Docs/light-frame-literal-blocks.md`, +Status: design (round thirty-seven, perf/bcc); stage 0, the attribution, done in perf/stage0 - see +"Stage 0: measured" below, which replaces the arithmetic bounds of section 4. It follows `Docs/light-frame-literal-blocks.md`, whose three experiments removed the candidates one by one: the full call site costs nothing (perf/literalsite), publishing the frame's scope costs nothing (perf/procscope), and allocating the scope and the Proc costs what reusing them does (`IR_PARKED_SCOPES=0` leaves every time as it is). What @@ -121,6 +122,68 @@ What each kind of callee does with it: | `block_given?` in the callee | true: the descriptor is a block | | `Proc#==`, `object_id` of the block | only on a materialized Proc | +## Stage 0: measured (perf/stage0) + +`Src/IronRuby.Tests/Perf/BlockCostHarness.cs`, run as `IronRuby.Tests /blockcost [N]` (not a test: the +driver runs it only for that switch). It hosts a runtime, takes real objects from Ruby code - a literal's +compiled block dispatcher, a method scope, its declaring scope and module - and times the runtime calls the +compiled code makes, each alone and then together, Stopwatch over 3,000,000 iterations, best of five after +a warm-up, Release net10.0; then the same calls end to end through Ruby. Two runs agree to a few ns. + +| step (ns per call) | alone | +|---|---| +| the locals tuple (`MakeLocalsStorage`) | 6 | +| a scope made (`CreateMethodScopeLazy`, allocation and its collection) | 45-55 | +| a Proc made (`new Proc`) | 16-17 | +| **the parked cycle**: take the scope, reinitialize it, make the Proc again, stage, park | **45-48** | +| - take and park with nothing between (`TakeParkedScope`, `BeginPark`, `EndPark`) | 23-25 | +| - plus the scope reinitialized (`ReuseParkedScopeLazy`) | +6 | +| - plus the Proc made again and staged (`InstantiateParkedBlock`, `StageParkedProc`) | +8 | +| - the scope's fields cleared and set again, alone (`ClearCallState`, `Reinitialize`) | 7 | +| - one `Interlocked.CompareExchange`, against a `Volatile.Write` | 10.4 against 2.5 | +| the light callee's entry and exit (`EnterLightMethod`, `LeaveLightMethodFrame`) | 3 | +| a yield to `{ 1 }` (`ReuseBfcForYield`, `Yield0`, the block, `LightMethodYield`) | 15-17 | +| a `[BlockNotKept]` yield to `{ \|x\| }` (`CreateBfcForBlockNotKept`, `Yield`, `LeaveProcConverter`) | 15-17 | +| `nyl`, all its steps together (parked on every call) | 68-73 | +| `e1`, all its steps together | 52-53 | + +End to end, ns per call with the caller's loop: `nb0` (a call without a block) 42-53, `nyp` (`ny(&PY)`, a stored +Proc) 98-101, `nyl` (`ny { 1 }`) 148-155; `e0` (no call) 24-26, `ep` (`a.each(&PE)`) 86-92, `e1` (`a.each { |x| }`) +133-145. So: + +- **The literal itself costs 50-54 ns** (`nyl` - `nyp`, `e1` - `ep`), and the parked cycle plus the locals + tuple is 52: **the literal's cost is the parked cycle, entirely.** Of it, about 16 ns are its two atomics + (the take's and the park's), 6 the scope's reinitialization, 8 the Proc made again, 6 the tuple, and the + rest the cycle's checks and clearing. +- **Passing any block and yielding to it costs another 55-63 ns** (`nyp` - `nb0`, `ep` - `e0`): the yield 16, + the callee's conversion 3, and 35-45 ns in the compiled code around them - the call site with a block, the + library rule's flow-control frame, the light frames' prologues and epilogues - which no runtime call + stands for and the harness cannot split further. CRuby's whole `ny { 1 }` is 14 ns over its `nb`. +- **The sums hold**: `nyl`'s steps (68-73) are its end to end minus `nb0` (about 100) less those 35 ns; `e1`'s + (52) are its end to end minus `e0` less the 60 of calling `each` with a block at all. + +### The stages, by these numbers + +| stage | what it removes | measured bound per call | of | +|---|---|---|---| +| A: `[BlockNotKept]` iterators, narrow literals | the parked cycle and the tuple for those calls | up to ~50 ns (`e1` 133-145 -> ~85-90, `ep`'s) | CRuby 73 | +| B: Ruby methods that only yield | the parked cycle, and the conversion | up to ~55 ns (`nyl` 148-155 -> ~95-100, `nyp`'s) | CRuby 50 | +| C: pass-on | the 336 bytes and the unparked Proc of every pass-on | not measured here | | +| D: literals that read locals | as A and B for those | as A and B | | +| (none) the call with a block, the yield | 35-63 ns of compiled-code work around a block call | not reached by the convention: gap 1's call sites | | + +**Which pays most for one round's work: A.** It needs the descriptor only on the library side (a +`CreateBfcForBlockNotKept` overload, the narrow shape's instantiation in the caller) and takes up to the +same ~50 ns as B, which needs the light callee's entry, yield and `block_given?` to take a descriptor. + +**A step cheap to cut by itself, without the new convention: the park's atomic.** `EndPark` publishes the +parked scope with `Interlocked.CompareExchange`; a `Volatile.Write` does the same job (a call that parked in +the meantime loses its scope to the garbage; a taker's exchange still makes what it takes its own) and is +8 ns cheaper per call of every method with a parked literal - about 15% of the literal's cost. perf/iter3 +tried exactly this and saw nothing end to end, where the host's noise was larger than 8 ns; the harness +shows it. It is a round of its own (the take must stay atomic: two threads may reach for the same parked +scope). + ## 4. Stages Each behind a switch of its own, with its matrix before its code, keepable alone. diff --git a/Src/IronRuby.Tests/Driver.cs b/Src/IronRuby.Tests/Driver.cs index 2bf6839e1..ccceea7dc 100644 --- a/Src/IronRuby.Tests/Driver.cs +++ b/Src/IronRuby.Tests/Driver.cs @@ -167,6 +167,11 @@ bool Take(params string[] names) { } public static void Main(string[]/*!*/ arguments) { + // not a test: the block-cost harness of Docs/block-calling-convention.md, stage 0 (Perf/BlockCostHarness.cs) + if (arguments.Length > 0 && arguments[0] == "/blockcost") { + IronRuby.Tests.Perf.BlockCostHarness.Run(arguments); + return; + } string culture = Environment.GetEnvironmentVariable("IR_CULTURE"); if (!String.IsNullOrEmpty(culture)) { Thread.CurrentThread.CurrentCulture = new CultureInfo(culture, false); diff --git a/Src/IronRuby.Tests/Perf/BlockCostHarness.cs b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs new file mode 100644 index 000000000..38579646b --- /dev/null +++ b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs @@ -0,0 +1,336 @@ +/* **************************************************************************** + * + * Stage 0 of Docs/block-calling-convention.md: where the time of a call with a literal block goes. + * + * dotnet build Src/IronRuby.Tests/IronRuby.Tests.csproj -c Release -p:IronRubyTargetFrameworks=net10.0 + * Src/IronRuby.Tests/bin/Release/net10.0/IronRuby.Tests /blockcost [N] + * + * Not a test: the driver runs it only for /blockcost (Driver.Main), never in the suite. It hosts a runtime, takes + * real objects from Ruby code (a literal's block dispatcher, compiled; a method scope; the declaring scope and + * module), and times the runtime calls the compiled code of `def nyl(a) = ny { 1 }' and `def e1(a); a.each { |x| }; + * 1; end' makes per call - each step alone in a loop, then the steps together - with a Stopwatch over N iterations + * after a warm-up, best of five. Then the same calls end to end, through Ruby, for the sum to be compared with. + * + * What it cannot time: the call sites and the light frames' prologues and epilogues themselves (compiled Ruby code, + * not runtime calls): those are what end to end minus the steps leaves, against the same end to end of a call + * without a block (nb0). + * + * ***************************************************************************/ + +using System; +using System.Diagnostics; +using IronRuby.Builtins; +using IronRuby.Runtime; +using IronRuby.Runtime.Calls; +using Microsoft.Scripting; +using Microsoft.Scripting.Hosting; + +namespace IronRuby.Tests.Perf { + internal static class BlockCostHarness { + private const string Source = @" +PE = proc { |x| } +PY = proc { 1 } +class BcO + def nb; 1; end + def ny; yield; end + def nb0(a) = nb + def nyl(a) = ny { 1 } + def e1(a); a.each { |x| }; 1; end + def e0(a); 1; end + def ep(a); a.each(&PE); 1; end + def nyp(a) = ny(&PY) + def grab(&b) = b + def lit1 = grab { 1 } + def litx = grab { |x| } + def sc(a) = binding +end +def bc_run_nb0(o, a, n); i = 0; while i < n; o.nb0(a); i += 1; end; end +def bc_run_nyl(o, a, n); i = 0; while i < n; o.nyl(a); i += 1; end; end +def bc_run_e1(o, a, n); i = 0; while i < n; o.e1(a); i += 1; end; end +def bc_run_e0(o, a, n); i = 0; while i < n; o.e0(a); i += 1; end; end +def bc_run_ep(o, a, n); i = 0; while i < n; o.ep(a); i += 1; end; end +def bc_run_nyp(o, a, n); i = 0; while i < n; o.nyp(a); i += 1; end; end +"; + + internal static void Run(string[] args) { + int n = (args.Length > 1) ? Int32.Parse(args[1]) : 5_000_000; + var engine = IronRuby.Ruby.CreateEngine(); + engine.Execute(Source); + + object o = (object)engine.Execute("BcO.new"); // typed: a dynamic would send every call below through the binder + var lit1 = (Proc)engine.Execute("BcO.new.lit1"); // `{ 1 }': its dispatcher is the literal's code + var litx = (Proc)engine.Execute("BcO.new.litx"); // `{ |x| }' + var binding = (Binding)engine.Execute("BcO.new.sc(1)"); + RubyScope bscope = binding.LocalScope; + while (!(bscope is RubyMethodScope)) { bscope = bscope._parent; } // a Binding's scope is a copy over the method's + var methodScope = (RubyMethodScope)bscope; + RubyScope declaringScope = methodScope._parent; + RubyModule declaringModule = methodScope.DeclaringModule; + var shape = new MethodFrameShape(new[] { "a" }, 1, "nyl"); + var array = new RubyArray { 1 }; + + Console.WriteLine("block-cost harness: N = {0:N0}, best of 5 after a warm-up, ns per operation", n); + Console.WriteLine(); + + // ---- the steps, one at a time + Report("1a locals tuple (MakeLocalsStorage)", n, k => { + object last = null; + for (int i = 0; i < k; i++) { last = new MutableTuple(); } + return last; + }); + + Report("1b scope made (CreateMethodScopeLazy)", n, k => { + object last = null; + var rfc = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + last = RubyOps.CreateMethodScopeLazy(shape, declaringScope, declaringModule, new MutableTuple(), o, null, null, rfc, null); + } + return last; + }); + + Report("2a Proc made (new Proc)", n, k => { + object last = null; + for (int i = 0; i < k; i++) { last = new Proc(ProcKind.Block, o, methodScope, lit1.Dispatcher); } + return last; + }); + + // the parked cycle of a light frame with one literal: take, reuse the scope, make the Proc again, stage, park + var slot = new ParkedScopeSlot("nyl") { ProcCount = 1 }; + Report("1+2+9 parked cycle (Take/Reuse/Instantiate/Begin/Stage/EndPark)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + var locals = new MutableTuple(); + var parked = RubyOps.TakeParkedScope(slot, declaringScope, declaringModule); + RubyMethodScope scope = (parked != null) + ? RubyOps.ReuseParkedScopeLazy(parked, locals, o, null, null, rfc0, null) + : RubyOps.CreateMethodScopeLazy(shape, declaringScope, declaringModule, locals, o, null, null, rfc0, null); + var proc = RubyOps.InstantiateParkedBlock(null, scope, o, lit1.Dispatcher, parked, 0); + // what the light callee's entry and exit leave: a reusable, inactive Proc (EnterLightMethod, LeaveLightMethodFrame) + var rfc = RubyOps.EnterLightMethod(proc); + RubyOps.LeaveLightMethodFrame(rfc, null); + RubyOps.LeaveLightMethodFrame(rfc0, scope); + if (parked != null) { Taken++; } + var parking = RubyOps.BeginPark(slot, scope, parked); + if (parking != null) { + RubyOps.EndPark(slot, parking, scope, RubyOps.StageParkedProc(parking, 0, proc)); + } + last = proc; + } + return last; + }); + + // the parked cycle in parts: the take and the park alone (no reuse, no Proc), then each part added + var slotP = new ParkedScopeSlot("p") { ProcCount = 1 }; + { + var rfc0 = RubyOps.EnterLightMethod(null); + var s0 = RubyOps.CreateMethodScopeLazy(shape, declaringScope, declaringModule, new MutableTuple(), o, null, null, rfc0, null); + RubyOps.LeaveLightMethodFrame(rfc0, s0); + var p0 = RubyOps.BeginPark(slotP, s0, null); + RubyOps.EndPark(slotP, p0, s0, RubyOps.StageParkedProc(p0, 0, null)); + } + Report(" P1 take + park, nothing between (TakeParkedScope, BeginPark, EndPark)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + var parked = RubyOps.TakeParkedScope(slotP, declaringScope, declaringModule); + var scope = parked.Scope; + var parking = RubyOps.BeginPark(slotP, scope, parked); + RubyOps.EndPark(slotP, parking, scope, RubyOps.StageParkedProc(parking, 0, null)); + last = parking; + } + return last; + }); + Report(" P2 = P1 + the scope reinitialized (ReuseParkedScopeLazy)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + var locals = new MutableTuple(); + for (int i = 0; i < k; i++) { + var parked = RubyOps.TakeParkedScope(slotP, declaringScope, declaringModule); + var scope = RubyOps.ReuseParkedScopeLazy(parked, locals, o, null, null, rfc0, null); + RubyOps.LeaveLightMethodFrame(rfc0, scope); + var parking = RubyOps.BeginPark(slotP, scope, parked); + RubyOps.EndPark(slotP, parking, scope, RubyOps.StageParkedProc(parking, 0, null)); + last = parking; + } + return last; + }); + Report(" P3 = P2 + the Proc made again and staged (InstantiateParkedBlock, StageParkedProc)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + var locals = new MutableTuple(); + for (int i = 0; i < k; i++) { + var parked = RubyOps.TakeParkedScope(slotP, declaringScope, declaringModule); + var scope = RubyOps.ReuseParkedScopeLazy(parked, locals, o, null, null, rfc0, null); + var proc = RubyOps.InstantiateParkedBlock(null, scope, o, lit1.Dispatcher, parked, 0); + RubyOps.LeaveLightMethodFrame(RubyOps.EnterLightMethod(proc), null); // the callee's conversion (1 ns) + RubyOps.LeaveLightMethodFrame(rfc0, scope); + var parking = RubyOps.BeginPark(slotP, scope, parked); + RubyOps.EndPark(slotP, parking, scope, RubyOps.StageParkedProc(parking, 0, proc)); + last = parking; + } + return last; + }); + var scopeR = RubyOps.CreateMethodScopeLazy(shape, declaringScope, declaringModule, new MutableTuple(), o, null, null, + RubyOps.EnterLightMethod(null), null); + Report(" R the scope's fields cleared and set again alone (ClearCallState, Reinitialize)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + var locals = new MutableTuple(); + for (int i = 0; i < k; i++) { + scopeR.ClearCallState(); + scopeR.Reinitialize(locals, o, null, null, rfc0, null); + last = scopeR; + } + return last; + }); + + // what one atomic costs here, against a plain release write: the park's take and its publication are one each + var cell = new object[1]; + var token = new object(); + Report(" A1 one Interlocked.CompareExchange (take, or the park's publication)", n, k => { + for (int i = 0; i < k; i++) { + System.Threading.Interlocked.CompareExchange(ref cell[0], token, null); + cell[0] = null; + } + return cell; + }); + Report(" A2 one Volatile.Write instead", n, k => { + for (int i = 0; i < k; i++) { + System.Threading.Volatile.Write(ref cell[0], token); + cell[0] = null; + } + return cell; + }); + + var procB = new Proc(ProcKind.Block, o, methodScope, lit1.Dispatcher); + Report("4+8 callee entry and exit (EnterLightMethod, LeaveLightMethodFrame)", n, k => { + object last = null; + for (int i = 0; i < k; i++) { + procB.TryReuse(); + var rfc = RubyOps.EnterLightMethod(procB); + RubyOps.LeaveLightMethodFrame(rfc, null); + last = rfc; + } + return last; + }); + + var procY = new Proc(ProcKind.Block, o, methodScope, lit1.Dispatcher); + var rfcY = RubyOps.EnterLightMethod(procY); + Report("5+6+7 yield to { 1 } (ReuseBfcForYield, Yield0, block, LightMethodYield)", n, k => { + object last = null; + BlockParam bfc = null; + for (int i = 0; i < k; i++) { + bfc = RubyOps.ReuseBfcForYield(bfc, procY); + last = RubyOps.Yield0(null, procY.Self, bfc); + RubyOps.LightMethodYield(rfcY, null, bfc, last); + } + return last; + }); + + var procE = new Proc(ProcKind.Block, o, methodScope, litx.Dispatcher); + Report("each: CreateBfcForBlockNotKept + one Yield to { |x| } + LeaveProcConverter", n, k => { + object last = null; + for (int i = 0; i < k; i++) { + procE.TryReuse(); + var bfc = RubyOps.CreateBfcForBlockNotKept(procE); + object r; + bfc.Yield(array[0], out r); + RubyOps.LeaveProcConverter(bfc); // the [BlockNotKept] rule's finally + last = r; + } + return last; + }); + + // ---- the steps together, as one call of nyl and of e1 makes them (parked) + var slotN = new ParkedScopeSlot("nyl") { ProcCount = 1 }; + Report("nyl: all steps (parked)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + var locals = new MutableTuple(); + var parked = RubyOps.TakeParkedScope(slotN, declaringScope, declaringModule); + RubyMethodScope scope = (parked != null) + ? RubyOps.ReuseParkedScopeLazy(parked, locals, o, null, null, rfc0, null) + : RubyOps.CreateMethodScopeLazy(shape, declaringScope, declaringModule, locals, o, null, null, rfc0, null); + var proc = RubyOps.InstantiateParkedBlock(null, scope, o, lit1.Dispatcher, parked, 0); + var rfc = RubyOps.EnterLightMethod(proc); + var bfc = RubyOps.ReuseBfcForYield(null, proc); + last = RubyOps.Yield0(null, proc.Self, bfc); + RubyOps.LightMethodYield(rfc, null, bfc, last); + RubyOps.LeaveLightMethodFrame(rfc, null); + RubyOps.LeaveLightMethodFrame(rfc0, scope); + if (parked != null) { Taken++; } + var parking = RubyOps.BeginPark(slotN, scope, parked); + if (parking != null) { + RubyOps.EndPark(slotN, parking, scope, RubyOps.StageParkedProc(parking, 0, proc)); + } + } + return last; + }); + + var slotE = new ParkedScopeSlot("e1") { ProcCount = 1 }; + Report("e1: all steps (parked)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + var locals = new MutableTuple(); + var parked = RubyOps.TakeParkedScope(slotE, declaringScope, declaringModule); + RubyMethodScope scope = (parked != null) + ? RubyOps.ReuseParkedScopeLazy(parked, locals, o, null, null, rfc0, null) + : RubyOps.CreateMethodScopeLazy(shape, declaringScope, declaringModule, locals, o, null, null, rfc0, null); + var proc = RubyOps.InstantiateParkedBlock(null, scope, o, litx.Dispatcher, parked, 0); + var bfc = RubyOps.CreateBfcForBlockNotKept(proc); + object r; + bfc.Yield(array[0], out r); + RubyOps.LeaveProcConverter(bfc); // the [BlockNotKept] rule's finally: the literal inactive again + RubyOps.LeaveLightMethodFrame(rfc0, scope); + if (parked != null) { Taken++; } + var parking = RubyOps.BeginPark(slotE, scope, parked); + if (parking != null) { + RubyOps.EndPark(slotE, parking, scope, RubyOps.StageParkedProc(parking, 0, proc)); + } + last = r; + } + return last; + }); + + // ---- end to end, through Ruby + Console.WriteLine(); + foreach (var name in new[] { "nb0", "nyp", "nyl", "e0", "ep", "e1" }) { + ReportRuby(engine, name, n); + } + } + + // calls of the measured rounds that took a parked scope (a cycle that never parks times the allocating path) + private static long Taken; + + private static void Report(string label, int n, Func body) { + body(n / 10); // warm-up: tiering, the block's compilation + body(n / 10); + double best = Double.MaxValue; + Taken = 0; + for (int round = 0; round < 5; round++) { + var sw = Stopwatch.StartNew(); + GC.KeepAlive(body(n)); + sw.Stop(); + best = Math.Min(best, sw.Elapsed.TotalMilliseconds * 1e6 / n); + } + Console.WriteLine(" {0,-80} {1,7:F1} ns{2}", label, best, Taken > 0 ? String.Format(" (parked: {0:P0})", Taken / (5.0 * n)) : ""); + } + + private static void ReportRuby(ScriptEngine engine, string name, int n) { + engine.Execute(String.Format("bc_run_{0}(BcO.new, [1], {1})", name, n / 10)); + engine.Execute(String.Format("bc_run_{0}(BcO.new, [1], {1})", name, n / 10)); + double best = Double.MaxValue; + string code = String.Format("bc_run_{0}(BcO.new, [1], {1})", name, n); + for (int round = 0; round < 5; round++) { + var sw = Stopwatch.StartNew(); + engine.Execute(code); + sw.Stop(); + best = Math.Min(best, sw.Elapsed.TotalMilliseconds * 1e6 / n); + } + Console.WriteLine(" {0,-80} {1,7:F1} ns", "end to end: " + name + " (the caller's while loop included)", best); + } + } +} diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 98714486c..f603b9901 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1203,6 +1203,15 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has with perf, which decides the rest; A, `[BlockNotKept]` library iterators with narrow literals; B, Ruby methods that only yield; C, pass-on; D, literals that read the frame's locals - each with its matrix and an upper bound. + perf/stage0 measured it (`Src/IronRuby.Tests/Perf/BlockCostHarness.cs`, `IronRuby.Tests + /blockcost`): the steps the compiled code calls, timed alone and together against the same + calls end to end. A literal costs 50-54 ns over a stored Proc (`nyl` - `nyp`, `e1` - `ep`), + and the parked cycle with the locals tuple is 52: the literal's cost is the parked cycle, + about 16 ns of it its two atomics (one `CompareExchange` 10.4 ns here, a `Volatile.Write` + 2.5). Passing any block and yielding costs another 55-63 ns, of which the yield is 16 and + the call site, rule and frames around it 35-45, which the convention does not reach. + Stage A pays most per round (up to ~50 ns of `e1`); the park's compare-exchange as a release + write is a step of its own, about 8 ns per call (perf/iter3 could not see it end to end). 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per From fe2df523cc1258e5296c2b5589a3f8453ce05d4d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:01:51 +0000 Subject: [PATCH 247/439] Method#source_location: a core method CRuby writes in Ruby is at CRuby's line A core method CRuby writes in Ruby (kernel.rb, numeric.rb...) is located at "" and a line there. IronRuby named the file (from InternalMethods.SourceFiles) but its own prelude's line for a prelude method (Kernel#then at 85, CRuby's 121), and nothing at all for one it writes in C#: 3.method(:times).source_location was nil, and #inspect left the location out, where CRuby says ":255". Util/gen-internal-methods.rb now records each method's line too (InternalMethods.SourceLines, regenerated with CRuby 4.0.10: only the new table, no entry of the old ones changed), and Method/UnboundMethod #source_location and #inspect take file and line from the tables for a prelude method and for a library method alike. Of CRuby's 235 named core methods with an location, IronRuby now gives 120 (25 before); the rest are Pathname's (not loaded at boot here), RubyVM::AbstractSyntaxTree's (absent) and SizedQueue#pop's (Queue's here). Method_InternalSourceLine1 holds CRuby's output; core/method, unboundmethod and proc specs pass, callable-parameters and inspect-own-encoding matrices print CRuby's output, and 193 method, proc and inspect IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 23 ++ .../Builtins/InternalMethods.Generated.cs | 320 +++++++++++++++++- Src/Libraries/Builtins/MethodOps.cs | 2 +- Src/Libraries/Builtins/UnboundMethod.cs | 28 +- Util/gen-internal-methods.rb | 8 +- 6 files changed, 374 insertions(+), 8 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f1871faff..be2ad0708 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1155,6 +1155,7 @@ public Tests(Driver/*!*/ driver) { Method_BindingNonRubyCaller1, Method_UnbindForwarder1, Method_ToProcSourceLocation1, + Method_InternalSourceLine1, Method_OptionalAndKeywordParameters2, Range_MinMaxInclude1, Integer_StepMatchString1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index b3a6cd1d0..601f97d2e 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -6525,6 +6525,29 @@ p [1].method(:each_slice).to_proc.source_location, 1.method(:+).to_proc.source_l "); } + /// + /// A core method CRuby writes in Ruby is located where CRuby's is, file and line, whether IronRuby writes it in + /// its prelude (Kernel#then) or in C# (Integer#times). + /// + public void Method_InternalSourceLine1() { + TestOutput(@" +require 'ruby4' +p method(:then).source_location, method(:tap).source_location, 3.method(:times).source_location, Kernel.instance_method(:frozen?).source_location +p method(:then).to_proc.source_location, Integer.instance_method(:times).source_location, [].method(:each).source_location +p 3.method(:times).inspect, Kernel.instance_method(:then).inspect +", @" +["""", 121] +["""", 89] +["""", 255] +["""", 67] +["""", 121] +["""", 255] +nil +""#:255>"" +""#:121>"" +"); + } + /// /// A method with optional positional parameters and keywords (`def m(a, b = 2, k: 3)') keeps its /// optionals as optional parameters; a keyword call that leaves one out has its keyword hash moved diff --git a/Src/Libraries/Builtins/InternalMethods.Generated.cs b/Src/Libraries/Builtins/InternalMethods.Generated.cs index 2ff89d5a8..78a6f3e49 100644 --- a/Src/Libraries/Builtins/InternalMethods.Generated.cs +++ b/Src/Libraries/Builtins/InternalMethods.Generated.cs @@ -1,4 +1,4 @@ -// Generated by Util/gen-internal-methods.rb from ruby 4.0.9 (2026-10-23 revision 3e93b23afc) +PRISM [x86_64-linux]; do not edit. +// Generated by Util/gen-internal-methods.rb from ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [x86_64-linux]; do not edit. // The core methods CRuby writes in Ruby, and the file Method#source_location names for each. using System.Collections.Generic; @@ -321,6 +321,324 @@ internal static class InternalMethods { { "TracePoint.trace", "" }, }; + // The line of each in that file. + internal static readonly Dictionary/*!*/ SourceLines = new Dictionary { + { "Array#fetch_values", 210 }, + { "Array#first", 129 }, + { "Array#last", 166 }, + { "Array#pack", 7 }, + { "Array#sample", 95 }, + { "Array#shuffle", 45 }, + { "Array#shuffle!", 22 }, + { "Binding#irb", 3 }, + { "Dir#initialize", 211 }, + { "Dir.[]", 222 }, + { "Dir.glob", 410 }, + { "Dir.open", 183 }, + { "Enumerable#to_set", 39 }, + { "Float#-@", 389 }, + { "Float#abs", 373 }, + { "Float#magnitude", 373 }, + { "Float#negative?", 416 }, + { "Float#positive?", 407 }, + { "Float#to_f", 360 }, + { "Float#zero?", 398 }, + { "GC#garbage_collect", 48 }, + { "GC.config", 444 }, + { "GC.count", 124 }, + { "GC.disable", 76 }, + { "GC.enable", 62 }, + { "GC.latest_gc_info", 500 }, + { "GC.measure_total_time", 549 }, + { "GC.measure_total_time=", 536 }, + { "GC.start", 43 }, + { "GC.stat", 250 }, + { "GC.stat_heap", 389 }, + { "GC.stress", 87 }, + { "GC.stress=", 111 }, + { "GC.total_time", 585 }, + { "Hash#initialize", 37 }, + { "IO#read_nonblock", 62 }, + { "IO#readline", 133 }, + { "IO#write_nonblock", 120 }, + { "Integer#-@", 104 }, + { "Integer#abs", 137 }, + { "Integer#bit_length", 184 }, + { "Integer#ceildiv", 308 }, + { "Integer#denominator", 326 }, + { "Integer#even?", 193 }, + { "Integer#integer?", 202 }, + { "Integer#magnitude", 137 }, + { "Integer#numerator", 318 }, + { "Integer#odd?", 212 }, + { "Integer#ord", 222 }, + { "Integer#size", 239 }, + { "Integer#times", 255 }, + { "Integer#to_i", 272 }, + { "Integer#to_int", 280 }, + { "Integer#zero?", 288 }, + { "Integer#~", 123 }, + { "Kernel#Float", 194 }, + { "Kernel#Integer", 287 }, + { "Kernel#Pathname", 1167 }, + { "Kernel#class", 18 }, + { "Kernel#clone", 47 }, + { "Kernel#frozen?", 67 }, + { "Kernel#loop", 161 }, + { "Kernel#pp", 24 }, + { "Kernel#tap", 89 }, + { "Kernel#then", 121 }, + { "Kernel#warn", 52 }, + { "Kernel#yield_self", 121 }, + { "Kernel.Float", 194 }, + { "Kernel.Integer", 287 }, + { "Kernel.Pathname", 1167 }, + { "Kernel.loop", 161 }, + { "Kernel.warn", 52 }, + { "Marshal.load", 33 }, + { "Marshal.restore", 33 }, + { "NilClass#rationalize", 12 }, + { "NilClass#to_c", 24 }, + { "NilClass#to_f", 48 }, + { "NilClass#to_i", 36 }, + { "NilClass#to_r", 60 }, + { "Numeric#+@", 89 }, + { "Numeric#conj", 78 }, + { "Numeric#conjugate", 78 }, + { "Numeric#dup", 9 }, + { "Numeric#finite?", 48 }, + { "Numeric#imag", 67 }, + { "Numeric#imaginary", 67 }, + { "Numeric#infinite?", 58 }, + { "Numeric#integer?", 39 }, + { "Numeric#real", 27 }, + { "Numeric#real?", 18 }, + { "ObjectSpace#garbage_collect", 594 }, + { "ObjectSpace.garbage_collect", 594 }, + { "Pathname#+", 665 }, + { "Pathname#/", 665 }, + { "Pathname#==", 234 }, + { "Pathname#===", 234 }, + { "Pathname#absolute?", 542 }, + { "Pathname#add_trailing_separator", 453 }, + { "Pathname#ascend", 639 }, + { "Pathname#atime", 898 }, + { "Pathname#basename", 972 }, + { "Pathname#binread", 881 }, + { "Pathname#binwrite", 895 }, + { "Pathname#birthtime", 904 }, + { "Pathname#blockdev?", 1010 }, + { "Pathname#chardev?", 1013 }, + { "Pathname#children", 758 }, + { "Pathname#chmod", 913 }, + { "Pathname#chop_basename", 359 }, + { "Pathname#chown", 919 }, + { "Pathname#cleanpath", 403 }, + { "Pathname#cleanpath_aggressive", 415 }, + { "Pathname#cleanpath_conservative", 474 }, + { "Pathname#ctime", 907 }, + { "Pathname#del_trailing_separator", 462 }, + { "Pathname#delete", 1153 }, + { "Pathname#descend", 606 }, + { "Pathname#directory?", 1039 }, + { "Pathname#dirname", 975 }, + { "Pathname#each_child", 808 }, + { "Pathname#each_entry", 1133 }, + { "Pathname#each_filename", 574 }, + { "Pathname#each_line", 871 }, + { "Pathname#empty?", 1018 }, + { "Pathname#entries", 1127 }, + { "Pathname#eql?", 234 }, + { "Pathname#executable?", 1027 }, + { "Pathname#executable_real?", 1030 }, + { "Pathname#exist?", 1033 }, + { "Pathname#expand_path", 981 }, + { "Pathname#extname", 978 }, + { "Pathname#file?", 1042 }, + { "Pathname#fnmatch", 926 }, + { "Pathname#fnmatch?", 929 }, + { "Pathname#freeze", 223 }, + { "Pathname#ftype", 933 }, + { "Pathname#glob", 1111 }, + { "Pathname#grpowned?", 1036 }, + { "Pathname#has_trailing_separator?", 442 }, + { "Pathname#hash", 249 }, + { "Pathname#initialize", 214 }, + { "Pathname#inspect", 261 }, + { "Pathname#join", 725 }, + { "Pathname#lchmod", 916 }, + { "Pathname#lchown", 922 }, + { "Pathname#lstat", 953 }, + { "Pathname#lutime", 969 }, + { "Pathname#make_link", 936 }, + { "Pathname#make_symlink", 956 }, + { "Pathname#mkdir", 1139 }, + { "Pathname#mkpath", 334 }, + { "Pathname#mountpoint?", 510 }, + { "Pathname#mtime", 910 }, + { "Pathname#open", 939 }, + { "Pathname#opendir", 1145 }, + { "Pathname#owned?", 1051 }, + { "Pathname#parent", 505 }, + { "Pathname#path", 205 }, + { "Pathname#pipe?", 1045 }, + { "Pathname#plus", 671 }, + { "Pathname#prepend_prefix", 380 }, + { "Pathname#read", 877 }, + { "Pathname#readable?", 1054 }, + { "Pathname#readable_real?", 1060 }, + { "Pathname#readlines", 884 }, + { "Pathname#readlink", 944 }, + { "Pathname#realdirpath", 1003 }, + { "Pathname#realpath", 996 }, + { "Pathname#relative?", 557 }, + { "Pathname#relative_path_from", 826 }, + { "Pathname#rename", 947 }, + { "Pathname#rmdir", 1142 }, + { "Pathname#root?", 527 }, + { "Pathname#same_paths?", 202 }, + { "Pathname#setgid?", 1066 }, + { "Pathname#setuid?", 1063 }, + { "Pathname#size", 1069 }, + { "Pathname#size?", 1072 }, + { "Pathname#socket?", 1048 }, + { "Pathname#split", 985 }, + { "Pathname#split_names", 370 }, + { "Pathname#stat", 950 }, + { "Pathname#sticky?", 1075 }, + { "Pathname#sub_ext", 292 }, + { "Pathname#symlink?", 1078 }, + { "Pathname#sysopen", 887 }, + { "Pathname#to_path", 254 }, + { "Pathname#to_s", 254 }, + { "Pathname#truncate", 959 }, + { "Pathname#unlink", 1153 }, + { "Pathname#utime", 962 }, + { "Pathname#world_readable?", 1057 }, + { "Pathname#world_writable?", 1084 }, + { "Pathname#writable?", 1081 }, + { "Pathname#writable_real?", 1087 }, + { "Pathname#write", 890 }, + { "Pathname#zero?", 1090 }, + { "Pathname.getwd", 1120 }, + { "Pathname.glob", 1096 }, + { "Pathname.pwd", 1120 }, + { "Ractor#<<", 368 }, + { "Ractor#[]", 473 }, + { "Ractor#[]=", 482 }, + { "Ractor#close", 403 }, + { "Ractor#default_port", 566 }, + { "Ractor#inspect", 374 }, + { "Ractor#join", 585 }, + { "Ractor#monitor", 634 }, + { "Ractor#name", 387 }, + { "Ractor#receive", 358 }, + { "Ractor#recv", 358 }, + { "Ractor#send", 368 }, + { "Ractor#to_s", 374 }, + { "Ractor#unmonitor", 644 }, + { "Ractor#value", 611 }, + { "Ractor.[]", 490 }, + { "Ractor.[]=", 495 }, + { "Ractor._activated", 545 }, + { "Ractor._require", 533 }, + { "Ractor.count", 258 }, + { "Ractor.current", 244 }, + { "Ractor.main", 519 }, + { "Ractor.main?", 526 }, + { "Ractor.make_shareable", 459 }, + { "Ractor.new", 229 }, + { "Ractor.receive", 349 }, + { "Ractor.recv", 349 }, + { "Ractor.select", 308 }, + { "Ractor.shareable?", 418 }, + { "Ractor.shareable_lambda", 681 }, + { "Ractor.shareable_proc", 667 }, + { "Ractor.store_if_absent", 513 }, + { "Ractor::Port#<<", 784 }, + { "Ractor::Port#close", 806 }, + { "Ractor::Port#closed?", 817 }, + { "Ractor::Port#inspect", 826 }, + { "Ractor::Port#receive", 741 }, + { "Ractor::Port#send", 784 }, + { "Ractor::RemoteError#ractor", 393 }, + { "RubyVM::AbstractSyntaxTree.node_id_for_backtrace_location", 110 }, + { "RubyVM::AbstractSyntaxTree.of", 95 }, + { "RubyVM::AbstractSyntaxTree.parse", 57 }, + { "RubyVM::AbstractSyntaxTree.parse_file", 74 }, + { "RubyVM::AbstractSyntaxTree::Location#first_column", 304 }, + { "RubyVM::AbstractSyntaxTree::Location#first_lineno", 296 }, + { "RubyVM::AbstractSyntaxTree::Location#inspect", 328 }, + { "RubyVM::AbstractSyntaxTree::Location#last_column", 320 }, + { "RubyVM::AbstractSyntaxTree::Location#last_lineno", 312 }, + { "RubyVM::AbstractSyntaxTree::Node#all_tokens", 205 }, + { "RubyVM::AbstractSyntaxTree::Node#children", 216 }, + { "RubyVM::AbstractSyntaxTree::Node#first_column", 148 }, + { "RubyVM::AbstractSyntaxTree::Node#first_lineno", 140 }, + { "RubyVM::AbstractSyntaxTree::Node#inspect", 224 }, + { "RubyVM::AbstractSyntaxTree::Node#last_column", 164 }, + { "RubyVM::AbstractSyntaxTree::Node#last_lineno", 156 }, + { "RubyVM::AbstractSyntaxTree::Node#locations", 280 }, + { "RubyVM::AbstractSyntaxTree::Node#node_id", 235 }, + { "RubyVM::AbstractSyntaxTree::Node#script_lines", 247 }, + { "RubyVM::AbstractSyntaxTree::Node#source", 263 }, + { "RubyVM::AbstractSyntaxTree::Node#tokens", 184 }, + { "RubyVM::AbstractSyntaxTree::Node#type", 132 }, + { "String#unpack", 25 }, + { "String#unpack1", 37 }, + { "Symbol#id2name", 10 }, + { "Symbol#intern", 37 }, + { "Symbol#name", 26 }, + { "Symbol#to_s", 10 }, + { "Symbol#to_sym", 37 }, + { "Thread::ConditionVariable#broadcast", 176 }, + { "Thread::ConditionVariable#initialize", 156 }, + { "Thread::ConditionVariable#marshal_dump", 162 }, + { "Thread::ConditionVariable#signal", 169 }, + { "Thread::ConditionVariable#wait", 191 }, + { "Thread::Mutex#initialize", 76 }, + { "Thread::Mutex#lock", 100 }, + { "Thread::Mutex#locked?", 83 }, + { "Thread::Mutex#owned?", 91 }, + { "Thread::Mutex#sleep", 147 }, + { "Thread::Mutex#synchronize", 127 }, + { "Thread::Mutex#try_lock", 109 }, + { "Thread::Mutex#unlock", 118 }, + { "Thread::Queue#deq", 16 }, + { "Thread::Queue#pop", 16 }, + { "Thread::Queue#shift", 16 }, + { "Thread::SizedQueue#<<", 61 }, + { "Thread::SizedQueue#deq", 38 }, + { "Thread::SizedQueue#enq", 61 }, + { "Thread::SizedQueue#pop", 38 }, + { "Thread::SizedQueue#push", 61 }, + { "Thread::SizedQueue#shift", 38 }, + { "Time#initialize", 440 }, + { "Time.at", 329 }, + { "Time.now", 270 }, + { "TracePoint#binding", 383 }, + { "TracePoint#callee_id", 339 }, + { "TracePoint#defined_class", 375 }, + { "TracePoint#disable", 297 }, + { "TracePoint#enable", 261 }, + { "TracePoint#enabled?", 306 }, + { "TracePoint#eval_script", 409 }, + { "TracePoint#event", 313 }, + { "TracePoint#inspect", 106 }, + { "TracePoint#instruction_sequence", 417 }, + { "TracePoint#lineno", 318 }, + { "TracePoint#method_id", 334 }, + { "TracePoint#parameters", 329 }, + { "TracePoint#path", 323 }, + { "TracePoint#raised_exception", 403 }, + { "TracePoint#return_value", 398 }, + { "TracePoint#self", 393 }, + { "TracePoint.allow_reentry", 200 }, + { "TracePoint.new", 96 }, + { "TracePoint.stat", 119 }, + { "TracePoint.trace", 134 }, + }; + // Method#arity and #parameters of each, as "arity|kind name,kind name". internal static readonly Dictionary/*!*/ Signatures = new Dictionary { { "Array#fetch_values", "-1|rest indexes,block block" }, diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 44c1e89fb..2c32e6132 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -186,7 +186,7 @@ public static RubyMethod GetSuperMethod(RubyContext/*!*/ context, RubyMethod/*!* [RubyMethod("source_location")] public static RubyArray GetSourceLocation(RubyMethod/*!*/ self) { - return self.IsMethodMissing ? null : UnboundMethod.GetSourceLocation(self.Info); + return self.IsMethodMissing ? null : UnboundMethod.GetSourceLocation(self.Info, self.Name); } [RubyMethod("parameters")] diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index e64480a90..fdf08ea59 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -273,7 +273,7 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet result.Append(MethodReflection.FormatParameters(context, info, methodName) ?? info.GetParameterSignature().ToParameterListString()); } - var location = isMissingMethod ? null : GetSourceLocation(info); + var location = isMissingMethod ? null : GetSourceLocation(info, methodName); if (location != null) { result.Append(' '); result.Append(location[0] as MutableString); @@ -317,7 +317,7 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet [RubyMethod("source_location")] public static RubyArray GetSourceLocation(UnboundMethod/*!*/ self) { - return self._isMethodMissing ? null : GetSourceLocation(self.Info); + return self._isMethodMissing ? null : GetSourceLocation(self.Info, self.Name); } [RubyMethod("parameters")] @@ -328,23 +328,30 @@ public static RubyArray GetSourceLocation(UnboundMethod/*!*/ self) { return MethodReflection.GetParameters(context, self.Info, self.Name); } - internal static RubyArray GetSourceLocation(RubyMemberInfo/*!*/ info) { + internal static RubyArray GetSourceLocation(RubyMemberInfo/*!*/ info, string/*!*/ name) { RubyMethodInfo rubyInfo = info as RubyMethodInfo; if (rubyInfo != null) { string file = rubyInfo.Document.FileName; + int line = rubyInfo.SourceSpan.Start.Line; // A core method IronRuby writes in Ruby is located where MRI's is when MRI writes it // in Ruby too ( for Kernel#tap); where MRI's is C, it has no // location at all, as a C method has none - method_source and pry rely on that. if (RubyStackTraceBuilder.IsInternalFile(file)) { string mriFile; - if (!InternalMethods.SourceFiles.TryGetValue(MethodReflection.GetInternalMethodKey(rubyInfo.DeclaringModule, rubyInfo.DefinitionName), out mriFile)) { + string key = MethodReflection.GetInternalMethodKey(rubyInfo.DeclaringModule, rubyInfo.DefinitionName); + if (!InternalMethods.SourceFiles.TryGetValue(key, out mriFile)) { return null; } file = mriFile; + // and at CRuby's line there, not the prelude's + int mriLine; + if (InternalMethods.SourceLines.TryGetValue(key, out mriLine)) { + line = mriLine; + } } return new RubyArray(2) { rubyInfo.DeclaringModule.Context.EncodePath(file), - rubyInfo.SourceSpan.Start.Line + line }; } @@ -358,6 +365,17 @@ internal static RubyArray GetSourceLocation(RubyMemberInfo/*!*/ info) { }; } + // a core method IronRuby writes in C# that CRuby writes in Ruby (Integer#times) is located where CRuby's is + RubyModule owner = info.DeclaringModule; + if (info is RubyLibraryMethodInfo && owner != null && (owner.Name != null || owner.IsSingletonClass)) { + string key = MethodReflection.GetInternalMethodKey(owner, info.OriginalName ?? name); + string mriFile; + int mriLine; + if (InternalMethods.SourceFiles.TryGetValue(key, out mriFile) && InternalMethods.SourceLines.TryGetValue(key, out mriLine)) { + return new RubyArray(2) { owner.Context.EncodePath(mriFile), mriLine }; + } + } + return null; } diff --git a/Util/gen-internal-methods.rb b/Util/gen-internal-methods.rb index d2a5730b0..a7cb03228 100644 --- a/Util/gen-internal-methods.rb +++ b/Util/gen-internal-methods.rb @@ -2,7 +2,7 @@ # # Regenerates Src/Libraries/Builtins/InternalMethods.Generated.cs: the core methods CRuby # itself writes in Ruby (kernel.rb, numeric.rb, ... compiled into the interpreter), with the -# "" file Method#source_location names for each. +# "" file and line Method#source_location names for each. # # Run it with CRuby 4.0 - the oracle - from the root of the source tree: # @@ -27,6 +27,7 @@ abort "run this with CRuby 4.0, not #{RUBY_ENGINE} #{RUBY_VERSION}" unless RUBY_ENGINE == "ruby" && RUBY_VERSION.start_with?("4.0") entries = {} +lines = {} signatures = {} ObjectSpace.each_object(Module) do |mod| name = mod.name @@ -38,6 +39,7 @@ next unless location && location[0].start_with?("/*!*/ SourceLines = new Dictionary {\n" +lines.sort.each { |key, line| out << " { #{key.dump}, #{line} },\n" } +out << " };\n\n" out << " // Method#arity and #parameters of each, as \"arity|kind name,kind name\".\n" out << " internal static readonly Dictionary/*!*/ Signatures = new Dictionary {\n" signatures.sort.each { |key, signature| out << " { #{key.dump}, #{signature.dump} },\n" } From 7a7a50d0223a09a06ad53e3afe1086c413a293b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:02:08 +0000 Subject: [PATCH 248/439] LEDGER: perf/crubydiff's sixth round Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index b058564b6..7a4c93b51 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -3065,6 +3065,35 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has a call's own line means a marker before each call whose line differs from the last one emitted on that path (and after it, for a later call back on the statement's line): free in the interpreter, a store per such call in compiled code, and support in the JIT's and light frames' line records - multi-line statements only. + Sixth round (2026-11-28, on claude/happy-gauss-95wm2j f67ac44 + the fifth), one commit each with CRuby + 4.0's output as a test: + - TracePoint reports attr_reader/attr_writer calls as :c_call/:c_return: while c_call is traced the + attribute rule takes the library methods' tracing, the attribute dispatchers stand aside and the JIT's + attribute sites do not bind - all decided when a site binds (tracing toggles rebind every rule and bump + the method version). frame-cost and app-shapes (invoice, render, rules, ostruct) by clock against the + same merge without it: within noise. TracePoint_AttrAccessorCCall1. + - StringScanner's escaped-bytes translation: \S \D \W \H, a class negated at its top and \X take an + undecodable byte too (Onigmo's rule; [\S] and \w do not). StringScanner_NegatedClassOnSplitByte1. + - "float X out of range of integer" prints X as %-.10g (Inf, NaN, 1e+30) everywhere + (RubyUtils.FormatFloatG10). Float_OutOfRangeMessage1. + - round/floor/ceil/truncate's Float digits convert as rb_num2int ("integer 3000000000 too big to + convert to 'int'"; NaN a RangeError). Float_RoundDigitsRange1. + - sort_by/min_by(n) gather with a private alias of the built-in push, not a program's Array#<<. + Enumerable_SortByOwnPush1. + - Method#unbind of a `public :m' entry gives the inherited body's owner. Method_UnbindForwarder1. + - Method#to_proc's lambda reports the method's source_location, by the same rules (nil for puts). + Method_ToProcSourceLocation1. + - A core method CRuby writes in Ruby is at CRuby's file and line, prelude or C# + (gen-internal-methods.rb records lines: InternalMethods.SourceLines). Method_InternalSourceLine1. + All matrices (jit) on this branch against the same merge without it: callable-parameters, array-take's + Inf row and sort-by's Array#<< row now same. Left: sort-by's order of equal keys and which pair a NaN + comparison names (CRuby's own qsort), string-race-matrix (readers racing writers without a GVL; the + unchanged build answers the same "wrong"/raises rows - perf/strrace's subject), and the known-left list. + For the gate, behaviour that changed outside a message: TracePoint events for attribute calls; StringScanner + matches from inside a character for \S and negated classes; NaN digits for round are a RangeError (were + FloatDomainError); sort_by no longer calls Array#<<; Method#unbind's owner for a visibility forwarder; + Proc#source_location of a method's to_proc; Method#source_location and #inspect of core methods (C# ones + now have CRuby's location; prelude ones CRuby's line). - **perf/json (2026-11-27) - `case` over String literals looks its subject up once while String#=== is the library's (gap 7)** - not gated. Commit 0a78877 on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j 15285eb with 0518f08 merged in. Measured first: a perf profile of AWFY From aea43ac43062cad1862eefc215144ea928fe0889 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:10:41 +0000 Subject: [PATCH 249/439] Startup library: precompile module_evals of a named module too The startup library's precompiled evals (perf/bootparse) covered plain string evals only: RubyUtils.Evaluate left a module_eval out with the eval code cache. FileUtils defines Verbose, NoWrite and DryRun with 92 `module_eval <<-EOS def #{name}...` strings, and Date::Format::Bag its accessors with 22 `class_eval`s; `require "irb"` loads fileutils, so irb parsed, transformed and compiled 135 texts at start-up, 92 of them those. A module_eval (class_eval) of a module with a name that is not a singleton class is now recorded and claimed like a plain eval, with the module's name added to the key: a def's frame label names the module, and the compiler walks the text as the body of that module, so FileUtils::Verbose#mkdir is labelled as it is without the library and its body is not compiled again from source at its first call. It is compiled with FactoryKind.ModuleEval, as CreateCompilerOptionsForEval does. instance_eval (a singleton class) and module_eval of an anonymous module compile from text as before, and the eval code cache still takes plain evals only. startup-evals.txt: 150 -> 264 evals (every record now says "module"). Checked on the R2R host: irb `1+1` claims 212 evals (84 before), top-level transforms 135 -> 7; FileUtils::Verbose/NoWrite/DryRun output, frame labels, owners, source_location, parameters and an ArgumentError's backtrace as the base and CRuby 4.0; Date parsing as the base; the five start-up commands print what the base prints; `startup-files.rb --check` passes; eval, eval-locals, eval-defined, eval-literals, erb-escape, forwardable, binding-lvar, caller, sdef, refinement, error-message and super-light matrices in the gate's modes, r2r and r2r with IR_STARTUP_DLL=none: PASS. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/Ruby/Runtime/PrecompiledCode.cs | 13 +- Src/Ruby/Runtime/RubyUtils.cs | 31 +- Util/aot/IronRuby.Aot/AotCompiler.cs | 16 +- Util/aot/IronRuby.Aot/StartupCommand.cs | 1 + Util/aot/startup-evals.txt | 414 +++++++++++++++--------- 5 files changed, 305 insertions(+), 170 deletions(-) diff --git a/Src/Ruby/Runtime/PrecompiledCode.cs b/Src/Ruby/Runtime/PrecompiledCode.cs index 7bd6d35ee..4a50b7815 100644 --- a/Src/Ruby/Runtime/PrecompiledCode.cs +++ b/Src/Ruby/Runtime/PrecompiledCode.cs @@ -563,10 +563,12 @@ public static void ClearCallLocation() { /// What the code of a string eval depends on besides its text: the text's encoding, the file and line, $VERBOSE (0 nil, 1 /// false, 2 true), the frame (inside a method or not, its label, block depth, method name and parameter names, a rest /// parameter), the locals it can see, and the names of the modules its constants are looked up in, innermost first - /// (EvalCodeCache.ConstantModules; "" for none). Null if a module has no name: such an eval is not precompiled. + /// (EvalCodeCache.ConstantModules; "" for none), and for a module_eval the name of the module it runs in, which its + /// defs' frame labels name (null for a plain eval). Null if a module has no name: such an eval is not precompiled. /// public static string EvalKey(string/*!*/ encoding, string/*!*/ path, int line, int verbosity, bool inMethod, string baseLabel, - int blockLevels, string methodName, string[] parameterNames, bool hasUnsplat, System.Collections.Generic.IList localNames, string[] moduleNames) { + int blockLevels, string methodName, string[] parameterNames, bool hasUnsplat, System.Collections.Generic.IList localNames, string[] moduleNames, + string evalModule) { if (moduleNames == null) { return null; } @@ -575,7 +577,7 @@ public static string EvalKey(string/*!*/ encoding, string/*!*/ path, int line, i .Append(inMethod ? '1' : '0').Append('\u0001').Append(baseLabel).Append('\u0001').Append(blockLevels).Append('\u0001') .Append(methodName).Append('\u0001').Append(parameterNames != null ? String.Join("\u0002", parameterNames) : "\u0003").Append('\u0001') .Append(hasUnsplat ? '1' : '0').Append('\u0001').Append(localNames != null ? String.Join("\u0002", localNames) : "\u0003").Append('\u0001') - .Append(String.Join("\u0002", moduleNames)); + .Append(String.Join("\u0002", moduleNames)).Append('\u0001').Append(evalModule ?? "\u0003"); return sb.ToString(); } @@ -672,7 +674,7 @@ private static void RegisterEvals(Type/*!*/ index, PrecompiledEvalsAttribute/*!* } /// - /// IR_EVAL_RECORD=file: every plain string eval compiled without a warning is appended to the file, one JSON object a + /// IR_EVAL_RECORD=file: every plain string eval and module_eval compiled without a warning is appended to the file, one JSON object a /// line, with what the startup library needs to compile it ahead of time (Util/aot/startup-files.rb writes /// startup-evals.txt from it). /// @@ -680,7 +682,7 @@ private static void RegisterEvals(Type/*!*/ index, PrecompiledEvalsAttribute/*!* internal static void RecordEval(byte[]/*!*/ code, string/*!*/ encoding, string/*!*/ path, int line, int verbosity, bool inMethod, string baseLabel, int blockLevels, string methodName, string[] parameterNames, bool hasUnsplat, System.Collections.Generic.IList localNames, - string[] moduleNames) { + string[] moduleNames, string evalModule) { if (moduleNames == null) { return; } @@ -698,6 +700,7 @@ internal static void RecordEval(byte[]/*!*/ code, string/*!*/ encoding, string/* ["hasUnsplat"] = hasUnsplat, ["localNames"] = localNames != null ? new System.Text.Json.Nodes.JsonArray(localNames.Select(n => (System.Text.Json.Nodes.JsonNode)n).ToArray()) : null, ["moduleNames"] = new System.Text.Json.Nodes.JsonArray(Array.ConvertAll(moduleNames, n => (System.Text.Json.Nodes.JsonNode)n)), + ["module"] = evalModule, }; lock (_recordLock) { File.AppendAllText(EvalRecordPath, o.ToJsonString() + "\n"); diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index fc56788ff..7b9e5523a 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1582,29 +1582,36 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop string precompiledKey = null; string[] moduleNames = null; int verbosity = 0; - if (module == null && bytes.Length <= EvalCodeCache.MaxCodeLength && options.TopLevelParameterSignature == null && + string evalModule = null; + if (bytes.Length <= EvalCodeCache.MaxCodeLength && options.TopLevelParameterSignature == null && options.IsolatedLocalNames == null && context.Coverage == null) { object verbose = context.Verbose; verbosity = verbose == null ? 0 : (RubyOps.IsTrue(verbose) ? 2 : 1); object[] constantModules = EvalCodeCache.ConstantModules(targetScope); - cacheKey = new EvalCodeCache.Key(bytes, code.Encoding, sourcePath, line, - verbosity, methodScope != null, - options.EvalFrameBaseLabel, options.EvalFrameBlockLevels, options.TopLevelMethodName, options.TopLevelParameterNames, - options.TopLevelHasUnsplatParameter, options.LocalNames, constantModules); - var cache = context.EvalCodeCache; - if (cache != null) { - compiled = (EvalEntryPointDelegate)cache.TryGet(cacheKey); + if (module == null) { + cacheKey = new EvalCodeCache.Key(bytes, code.Encoding, sourcePath, line, + verbosity, methodScope != null, + options.EvalFrameBaseLabel, options.EvalFrameBlockLevels, options.TopLevelMethodName, options.TopLevelParameterNames, + options.TopLevelHasUnsplatParameter, options.LocalNames, constantModules); + var cache = context.EvalCodeCache; + if (cache != null) { + compiled = (EvalEntryPointDelegate)cache.TryGet(cacheKey); + } + options.CheckEvalCodeShareable = true; } - options.CheckEvalCodeShareable = true; // The startup library's code of this text in this context, if it has it and no eval has run it yet // (IronRuby.Runtime.Precompiled.PrecompiledCode.TryClaimEval), or a record of the eval for the library (IR_EVAL_RECORD). - if (compiled == null && (IronRuby.Runtime.Precompiled.PrecompiledCode.HasEvals || IronRuby.Runtime.Precompiled.PrecompiledCode.EvalRecordPath != null)) { + // A module_eval is one too when its module has a name, which the frame labels of its defs are compiled with + // (FileUtils::Verbose's 30-odd `module_eval <<-EOS def #{name}...'): not an instance_eval, whose module is a + // singleton class, nor a module_eval of an anonymous module. + if (compiled == null && (IronRuby.Runtime.Precompiled.PrecompiledCode.HasEvals || IronRuby.Runtime.Precompiled.PrecompiledCode.EvalRecordPath != null) && + (module == null || !module.IsSingletonClass && (evalModule = module.GetName(context)) != null)) { moduleNames = IronRuby.Runtime.Precompiled.PrecompiledCode.ModuleNames(context, constantModules); precompiledKey = IronRuby.Runtime.Precompiled.PrecompiledCode.EvalKey(code.Encoding.Name, sourcePath, line, verbosity, methodScope != null, options.EvalFrameBaseLabel, options.EvalFrameBlockLevels, options.TopLevelMethodName, options.TopLevelParameterNames, - options.TopLevelHasUnsplatParameter, options.LocalNames, moduleNames); + options.TopLevelHasUnsplatParameter, options.LocalNames, moduleNames, evalModule); compiled = IronRuby.Runtime.Precompiled.PrecompiledCode.TryClaimEval(context, bytes, precompiledKey); } } @@ -1615,7 +1622,7 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop if (precompiledKey != null && IronRuby.Runtime.Precompiled.PrecompiledCode.EvalRecordPath != null && context.RuntimeErrorSink.WarningCount == warnings) { IronRuby.Runtime.Precompiled.PrecompiledCode.RecordEval(bytes, code.Encoding.Name, sourcePath, line, verbosity, methodScope != null, options.EvalFrameBaseLabel, options.EvalFrameBlockLevels, options.TopLevelMethodName, options.TopLevelParameterNames, - options.TopLevelHasUnsplatParameter, options.LocalNames, moduleNames); + options.TopLevelHasUnsplatParameter, options.LocalNames, moduleNames, evalModule); } } diff --git a/Util/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index ae61a5ab6..a4a0753a3 100644 --- a/Util/aot/IronRuby.Aot/AotCompiler.cs +++ b/Util/aot/IronRuby.Aot/AotCompiler.cs @@ -554,6 +554,8 @@ protected override Expression VisitLoop(LoopExpression node) { public sealed class EvalUnit { public byte[] Code; public string Encoding, Path, BaseLabel, MethodName; + // a module_eval's module (its name), null for a plain eval + public string Module; public int Line, Verbosity, BlockLevels; public bool InMethod, HasUnsplat; public string[] ParameterNames, LocalNames, ModuleNames; @@ -584,7 +586,7 @@ private void CompileEvals(int firstClass, HashSet extended) { IsEval = true, EvalFrameBaseLabel = e.BaseLabel, EvalFrameBlockLevels = e.BlockLevels, - FactoryKind = TopScopeFactoryKind.None, + FactoryKind = e.Module != null ? TopScopeFactoryKind.ModuleEval : TopScopeFactoryKind.None, LocalNames = e.LocalNames != null ? new List(e.LocalNames) : null, TopLevelMethodName = e.InMethod ? e.MethodName : null, TopLevelParameterNames = e.InMethod ? e.ParameterNames : null, @@ -600,7 +602,10 @@ private void CompileEvals(int firstClass, HashSet extended) { if (ast == null) throw new InvalidOperationException("syntax error"); if (UnsupportedFinder.Find(ast) is string why) throw new InvalidOperationException(why); new ExtendWalker(extended).Walk(ast); - new FrameLabelWalker(_frameOwners, _context, extended).Walk(ast); + // a module_eval's defs are the module's methods, as a module body's are + var labels = new FrameLabelWalker(_frameOwners, _context, extended); + if (e.Module != null) labels.EnterModule(e.Module); + labels.Walk(ast); lambda = _context.TransformTree>(ast, unit, options); } catch (Exception ex) { Console.Error.WriteLine($"left out eval at {e.Path}:{e.Line}: {ex.Message}"); @@ -621,7 +626,7 @@ private void CompileEvals(int firstClass, HashSet extended) { // PrecompiledCode.Rooted replaces by the tree the library runs from string path = RootPrefix != null ? e.Path.Replace(RootPrefix, PrecompiledCode.RootMarker.ToString()) : e.Path; _evalKeys.Add(PrecompiledCode.EvalKey(e.Encoding, path, e.Line, e.Verbosity, e.InMethod, e.BaseLabel, e.BlockLevels, - e.MethodName, e.ParameterNames, e.HasUnsplat, e.LocalNames, e.ModuleNames)); + e.MethodName, e.ParameterNames, e.HasUnsplat, e.LocalNames, e.ModuleNames, e.Module)); _evalCodes.Add(PrecompiledCode.HashEvalCode(e.Code)); Count("evals compiled"); Console.Error.WriteLine($"compiled eval at {e.Path}:{e.Line} ({e.Code.Length} bytes)"); @@ -1490,6 +1495,11 @@ private sealed class Frame { } private Frame Top => _frames.Count == 0 ? null : _frames[_frames.Count - 1]; + + /// Walks what follows as if in the body of the module of that full name (a module_eval's code). + public void EnterModule(string path) { + _frames.Add(new Frame { Path = path }); + } private string Enclosing => Top?.Path; private static List Segments(ConstantVariable c, out bool global) { diff --git a/Util/aot/IronRuby.Aot/StartupCommand.cs b/Util/aot/IronRuby.Aot/StartupCommand.cs index 024c534a6..8a246ead6 100644 --- a/Util/aot/IronRuby.Aot/StartupCommand.cs +++ b/Util/aot/IronRuby.Aot/StartupCommand.cs @@ -69,6 +69,7 @@ internal static class StartupCommand { HasUnsplat = (bool)o["hasUnsplat"], LocalNames = Names("localNames"), ModuleNames = Names("moduleNames"), + Module = (string)o["module"], }); } return result; diff --git a/Util/aot/startup-evals.txt b/Util/aot/startup-evals.txt index a511b5a43..cc913a6f1 100644 --- a/Util/aot/startup-evals.txt +++ b/Util/aot/startup-evals.txt @@ -1,153 +1,267 @@ # Written by startup-files.rb with startup-files.txt: the string evals those commands run, one JSON object a line # (PrecompiledCode.RecordEval), compiled into IronRuby.Startup.dll for the first eval of exactly that text in exactly # that context. ${ROOT} is the IronRuby tree. -{"code":"ICAgICMgZnJvemVuX3N0cmluZ19saXRlcmFsOiB0cnVlCgogICAgZGVmIHNldF9uaWxfYXR0cmlidXRlc190b19uaWwKICAgICAgQGF1dG9yZXF1aXJlID0gbmlsOyBAZGF0ZSA9IG5pbDsgQGRlc2NyaXB0aW9uID0gbmlsOyBAZW1haWwgPSBuaWw7IEBob21lcGFnZSA9IG5pbDsgQG5hbWUgPSBuaWw7IEBwb3N0X2luc3RhbGxfbWVzc2FnZSA9IG5pbDsgQHNpZ25pbmdfa2V5ID0gbmlsOyBAc3VtbWFyeSA9IG5pbDsgQHZlcnNpb24gPSBuaWwKICAgIGVuZAogICAgcHJpdmF0ZSA6c2V0X25pbF9hdHRyaWJ1dGVzX3RvX25pbAoKICAgIGRlZiBzZXRfbm90X25pbF9hdHRyaWJ1dGVzX3RvX2RlZmF1bHRfdmFsdWVzCiAgICAgIEBhdXRob3JzID0gW107QGJpbmRpciA9ICJiaW4iO0BjZXJ0X2NoYWluID0gW107QGRlcGVuZGVuY2llcyA9IFtdO0BleGVjdXRhYmxlcyA9IFtdO0BleHRlbnNpb25zID0gW107QGV4dHJhX3Jkb2NfZmlsZXMgPSBbXTtAZmlsZXMgPSBbXTtAbGljZW5zZXMgPSBbXTtAbWV0YWRhdGEgPSB7fTtAcGxhdGZvcm0gPSAicnVieSI7QHJkb2Nfb3B0aW9ucyA9IFtdO0ByZXF1aXJlX3BhdGhzID0gZGVmYXVsdF92YWx1ZSg6cmVxdWlyZV9wYXRocykuZHVwO0ByZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBkZWZhdWx0X3ZhbHVlKDpyZXF1aXJlZF9ydWJ5X3ZlcnNpb24pLmR1cDtAcmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IGRlZmF1bHRfdmFsdWUoOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24pLmR1cDtAcmVxdWlyZW1lbnRzID0gW107QHJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjIwIjtAc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNDtAdGVzdF9maWxlcyA9IFtdCiAgICBlbmQKICAgIHByaXZhdGUgOnNldF9ub3RfbmlsX2F0dHJpYnV0ZXNfdG9fZGVmYXVsdF92YWx1ZXMK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/rubygems/specification.rb","line":1938,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["today"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyBmcm96ZW5fc3RyaW5nX2xpdGVyYWw6IHRydWUKCiMtLQojIENvcHlyaWdodCAyMDA2IGJ5IENoYWQgRm93bGVyLCBSaWNoIEtpbG1lciwgSmltIFdlaXJpY2ggYW5kIG90aGVycy4KIyBBbGwgcmlnaHRzIHJlc2VydmVkLgojIFNlZSBMSUNFTlNFLnR4dCBmb3IgcGVybWlzc2lvbnMuCiMrKwoKcmVxdWlyZSAibW9uaXRvciIKCm1vZHVsZSBLZXJuZWwKICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1IgPSBNb25pdG9yLm5ldyAjIDpub2RvYzoKCiAgIyBNYWtlIHN1cmUgd2UgaGF2ZSBhIHJlZmVyZW5jZSB0byBSdWJ5J3Mgb3JpZ2luYWwgS2VybmVsI3JlcXVpcmUKICB1bmxlc3MgZGVmaW5lZD8oZ2VtX29yaWdpbmFsX3JlcXVpcmUpCiAgICAjIDpzdG9wZG9jOgogICAgYWxpYXNfbWV0aG9kIDpnZW1fb3JpZ2luYWxfcmVxdWlyZSwgOnJlcXVpcmUKICAgIHByaXZhdGUgOmdlbV9vcmlnaW5hbF9yZXF1aXJlCiAgICAjIDpzdGFydGRvYzoKICBlbmQKCiAgIyMKICAjIFdoZW4gUnVieUdlbXMgaXMgcmVxdWlyZWQsIEtlcm5lbCNyZXF1aXJlIGlzIHJlcGxhY2VkIHdpdGggb3VyIG93biB3aGljaAogICMgaXMgY2FwYWJsZSBvZiBsb2FkaW5nIGdlbXMgb24gZGVtYW5kLgogICMKICAjIFdoZW4geW91IGNhbGwgPHR0PnJlcXVpcmUgJ3gnPC90dD4sIHRoaXMgaXMgd2hhdCBoYXBwZW5zOgogICMgKiBJZiB0aGUgZmlsZSBjYW4gYmUgbG9hZGVkIGZyb20gdGhlIGV4aXN0aW5nIFJ1YnkgbG9hZHBhdGgsIGl0CiAgIyAgIGlzLgogICMgKiBPdGhlcndpc2UsIGluc3RhbGxlZCBnZW1zIGFyZSBzZWFyY2hlZCBmb3IgYSBmaWxlIHRoYXQgbWF0Y2hlcy4KICAjICAgSWYgaXQncyBmb3VuZCBpbiBnZW0gJ3knLCB0aGF0IGdlbSBpcyBhY3RpdmF0ZWQgKGFkZGVkIHRvIHRoZQogICMgICBsb2FkcGF0aCkuCiAgIwogICMgVGhlIG5vcm1hbCA8dHQ+cmVxdWlyZTwvdHQ+IGZ1bmN0aW9uYWxpdHkgb2YgcmV0dXJuaW5nIGZhbHNlIGlmCiAgIyB0aGF0IGZpbGUgaGFzIGFscmVhZHkgYmVlbiBsb2FkZWQgaXMgcHJlc2VydmVkLgoKICBkZWYgcmVxdWlyZShwYXRoKSAjIDpkb2M6CiAgICByZXR1cm4gZ2VtX29yaWdpbmFsX3JlcXVpcmUocGF0aCkgdW5sZXNzIEdlbS5kaXNjb3Zlcl9nZW1zX29uX3JlcXVpcmUKCiAgICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1Iuc3luY2hyb25pemUgZG8KICAgICAgcGF0aCA9IEZpbGUucGF0aChwYXRoKQoKICAgICAgIyBJZiArcGF0aCsgYmVsb25ncyB0byBhIGRlZmF1bHQgZ2VtLCB3ZSBhY3RpdmF0ZSBpdCBhbmQgdGhlbiBnbyBzdHJhaWdodAogICAgICAjIHRvIG5vcm1hbCByZXF1aXJlCgogICAgICBpZiBzcGVjID0gR2VtLmZpbmRfZGVmYXVsdF9zcGVjKHBhdGgpCiAgICAgICAgbmFtZSA9IHNwZWMubmFtZQoKICAgICAgICBuZXh0IGlmIEdlbS5sb2FkZWRfc3BlY3NbbmFtZV0KCiAgICAgICAgIyBFbnN1cmUgLUkgYmVhdHMgYSBkZWZhdWx0IGdlbQogICAgICAgIHJlc29sdmVkX3BhdGggPSBiZWdpbgogICAgICAgICAgcnAgPSBuaWwKICAgICAgICAgIGxvYWRfcGF0aF9jaGVja19pbmRleCA9IEdlbS5sb2FkX3BhdGhfaW5zZXJ0X2luZGV4IC0gR2VtLmFjdGl2YXRlZF9nZW1fcGF0aHMKICAgICAgICAgIEdlbS5zdWZmaXhlcy5maW5kIGRvIHxzfAogICAgICAgICAgICAkTE9BRF9QQVRIWzAuLi5sb2FkX3BhdGhfY2hlY2tfaW5kZXhdLmZpbmQgZG8gfGxwfAogICAgICAgICAgICAgIGlmIEZpbGUuc3ltbGluaz8gbHAgIyBmb3IgYmFja3dhcmQgY29tcGF0aWJpbGl0eQogICAgICAgICAgICAgICAgbmV4dAogICAgICAgICAgICAgIGVuZAoKICAgICAgICAgICAgICBmdWxsX3BhdGggPSBGaWxlLmV4cGFuZF9wYXRoKEZpbGUuam9pbihscCwgIiN7cGF0aH0je3N9IikpCiAgICAgICAgICAgICAgcnAgPSBmdWxsX3BhdGggaWYgRmlsZS5maWxlPyhmdWxsX3BhdGgpCiAgICAgICAgICAgIGVuZAogICAgICAgICAgZW5kCiAgICAgICAgICBycAogICAgICAgIGVuZAoKICAgICAgICBuZXh0IGlmIHJlc29sdmVkX3BhdGgKCiAgICAgICAgS2VybmVsLnNlbmQoOmdlbSwgbmFtZSwgR2VtOjpSZXF1aXJlbWVudC5kZWZhdWx0X3ByZXJlbGVhc2UpCgogICAgICAgIEdlbS5sb2FkX2J1bmRsZXJfZXh0ZW5zaW9ucyhHZW0ubG9hZGVkX3NwZWNzW25hbWVdLnZlcnNpb24pIGlmIG5hbWUgPT0gImJ1bmRsZXIiCgogICAgICAgIG5leHQKICAgICAgZW5kCgogICAgICAjIElmIHRoZXJlIGFyZSBubyB1bnJlc29sdmVkIGRlcHMsIHRoZW4gd2UgY2FuIHVzZSBqdXN0IHRyeQogICAgICAjIG5vcm1hbCByZXF1aXJlIGhhbmRsZSBsb2FkaW5nIGEgZ2VtIGZyb20gdGhlIHJlc2N1ZSBiZWxvdy4KCiAgICAgIGlmIEdlbTo6U3BlY2lmaWNhdGlvbi51bnJlc29sdmVkX2RlcHMuZW1wdHk/CiAgICAgICAgbmV4dAogICAgICBlbmQKCiAgICAgICMgSWYgK3BhdGgrIGlzIGZvciBhIGdlbSB0aGF0IGhhcyBhbHJlYWR5IGJlZW4gbG9hZGVkLCBkb24ndAogICAgICAjIGJvdGhlciB0cnlpbmcgdG8gZmluZCBpdCBpbiBhbiB1bnJlc29sdmVkIGdlbSwganVzdCBnbyBzdHJhaWdodAogICAgICAjIHRvIG5vcm1hbCByZXF1aXJlLgogICAgICAjLS0KICAgICAgIyBUT0RPIHJlcXVlc3QgYWNjZXNzIHRvIHRoZSBDIGltcGxlbWVudGF0aW9uIG9mIHRoaXMgdG8gc3BlZWQgdXAgUnVieUdlbXMKCiAgICAgIGlmIEdlbTo6U3BlY2lmaWNhdGlvbi5maW5kX2FjdGl2ZV9zdHViX2J5X3BhdGgocGF0aCkKICAgICAgICBuZXh0CiAgICAgIGVuZAoKICAgICAgIyBBdHRlbXB0IHRvIGZpbmQgK3BhdGgrIGluIGFueSB1bnJlc29sdmVkIGdlbXMuLi4KCiAgICAgIGZvdW5kX3NwZWNzID0gR2VtOjpTcGVjaWZpY2F0aW9uLmZpbmRfaW5fdW5yZXNvbHZlZCBwYXRoCgogICAgICAjIElmIHRoZXJlIGFyZSBubyBkaXJlY3RseSB1bnJlc29sdmVkIGdlbXMsIHRoZW4gdHJ5IGFuZCBmaW5kICtwYXRoKwogICAgICAjIGluIGFueSBnZW1zIHRoYXQgYXJlIGF2YWlsYWJsZSB2aWEgdGhlIGN1cnJlbnRseSB1bnJlc29sdmVkIGdlbXMuCiAgICAgICMgRm9yIGV4YW1wbGUsIGdpdmVuOgogICAgICAjCiAgICAgICMgICBhID0+IGIgPT4gYyA9PiBkCiAgICAgICMKICAgICAgIyBJZiBhIGFuZCBiIGFyZSBjdXJyZW50bHkgYWN0aXZlIHdpdGggYyBiZWluZyB1bnJlc29sdmVkIGFuZCBkLnJiIGlzCiAgICAgICMgcmVxdWVzdGVkLCB0aGVuIGZpbmRfaW5fdW5yZXNvbHZlZF90cmVlIHdpbGwgZmluZCBkLnJiIGluIGQgYmVjYXVzZQogICAgICAjIGl0J3MgYSBkZXBlbmRlbmN5IG9mIGMuCiAgICAgICMKICAgICAgaWYgZm91bmRfc3BlY3MuZW1wdHk/CiAgICAgICAgZm91bmRfc3BlY3MgPSBHZW06OlNwZWNpZmljYXRpb24uZmluZF9pbl91bnJlc29sdmVkX3RyZWUgcGF0aAoKICAgICAgICBmb3VuZF9zcGVjcy5lYWNoKCY6YWN0aXZhdGUpCgogICAgICAjIFdlIGZvdW5kICtwYXRoKyBkaXJlY3RseSBpbiBhbiB1bnJlc29sdmVkIGdlbS4gTm93IHdlIGZpZ3VyZSBvdXQsIG9mCiAgICAgICMgdGhlIHBvc3NpYmxlIGZvdW5kIHNwZWNzLCB3aGljaCBvbmUgd2Ugc2hvdWxkIGFjdGl2YXRlLgogICAgICBlbHNlCgogICAgICAgICMgQ2hlY2sgdGhhdCBhbGwgdGhlIGZvdW5kIHNwZWNzIGFyZSBqdXN0IGRpZmZlcmVudAogICAgICAgICMgdmVyc2lvbnMgb2YgdGhlIHNhbWUgZ2VtCiAgICAgICAgbmFtZXMgPSBmb3VuZF9zcGVjcy5tYXAoJjpuYW1lKS51bmlxCgogICAgICAgIGlmIG5hbWVzLnNpemUgPiAxCiAgICAgICAgICByYWlzZSBHZW06OkxvYWRFcnJvciwgIiN7cGF0aH0gZm91bmQgaW4gbXVsdGlwbGUgZ2VtczogI3tuYW1lcy5qb2luICIsICJ9IgogICAgICAgIGVuZAoKICAgICAgICAjIE9rLCBub3cgZmluZCBhIGdlbSB0aGF0IGhhcyBubyBjb25mbGljdHMsIHN0YXJ0aW5nCiAgICAgICAgIyBhdCB0aGUgaGlnaGVzdCB2ZXJzaW9uLgogICAgICAgIHZhbGlkID0gZm91bmRfc3BlY3MuZmluZCB7fHN8ICFzLmhhc19jb25mbGljdHM/IH0KCiAgICAgICAgdW5sZXNzIHZhbGlkCiAgICAgICAgICBsZSA9IEdlbTo6TG9hZEVycm9yLm5ldyAidW5hYmxlIHRvIGZpbmQgYSB2ZXJzaW9uIG9mICcje25hbWVzLmZpcnN0fScgdG8gYWN0aXZhdGUiCiAgICAgICAgICBsZS5uYW1lID0gbmFtZXMuZmlyc3QKICAgICAgICAgIHJhaXNlIGxlCiAgICAgICAgZW5kCgogICAgICAgIHZhbGlkLmFjdGl2YXRlCiAgICAgIGVuZAogICAgZW5kCgogICAgYmVnaW4KICAgICAgZ2VtX29yaWdpbmFsX3JlcXVpcmUocGF0aCkKICAgIHJlc2N1ZSBMb2FkRXJyb3IgPT4gbG9hZF9lcnJvcgogICAgICBpZiBsb2FkX2Vycm9yLnBhdGggPT0gcGF0aCAmJgogICAgICAgICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1Iuc3luY2hyb25pemUgeyBHZW0udHJ5X2FjdGl2YXRlKHBhdGgpIH0KCiAgICAgICAgcmV0dXJuIGdlbV9vcmlnaW5hbF9yZXF1aXJlKHBhdGgpCiAgICAgIGVuZAoKICAgICAgcmFpc2UgbG9hZF9lcnJvcgogICAgZW5kCiAgZW5kCgogIHByaXZhdGUgOnJlcXVpcmUKZW5kCg==","encoding":"US-ASCII","path":"","line":1,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["e","path","msg","file"],"moduleNames":[]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGpzb24gMi4xOC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJqc29uIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4xOC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSlNPTiBwYXJzaW5nIGFuZCBnZW5lcmF0aW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkpTT04gcGFyc2luZyBhbmQgZ2VuZXJhdGlvbiIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2pzb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvYmlnZGVjaW1hbC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9jb21wbGV4LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL2NvcmUucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9kYXRlX3RpbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvZXhjZXB0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL29zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmFuZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmF0aW9uYWwucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmVnZXhwLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL3NldC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9zdHJpbmcucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvc3RydWN0LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL3N5bWJvbC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC90aW1lLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vY29tbW9uLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vZXh0LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vZ2VuZXJpY19vYmplY3QucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/json-2.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN0cmluZ2lvIDMuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJzdHJpbmdpbyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSU8gb24gc3RyaW5ncy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJTyBvbiBzdHJpbmdzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvc3RyaW5naW8ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/stringio-3.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN0cnNjYW4gMy4xLjYgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInN0cnNjYW4iLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjEuNiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkxleGljYWwgc2Nhbm5pbmcgb2Ygc3RyaW5ncy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJMZXhpY2FsIHNjYW5uaW5nIG9mIHN0cmluZ3MiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zdHJzY2FuLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/strscan-3.1.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLWNvbnNvbGUgMC44LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlvLWNvbnNvbGUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkNvbnNvbGUgc2l6ZSBhbmQgcmF3IG1vZGUuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ29uc29sZSBzaXplIGFuZCByYXcgbW9kZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2lvL2NvbnNvbGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaW8vY29uc29sZS9zaXplLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-console-0.8.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRhdGUgMy4zLjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImRhdGUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjMuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkRhdGUgYW5kIERhdGVUaW1lLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRhdGUgYW5kIERhdGVUaW1lIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9kYXRlL2Zvcm1hdC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/date-3.3.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wdHBhcnNlIDAuOC4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcHRwYXJzZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuOC4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiT3B0aW9uUGFyc2VyIGlzIGEgY2xhc3MgZm9yIGNvbW1hbmQtbGluZSBvcHRpb24gYW5hbHlzaXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3B0aW9uUGFyc2VyIGlzIGEgY2xhc3MgZm9yIGNvbW1hbmQtbGluZSBvcHRpb24gYW5hbHlzaXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL29wdHBhcnNlLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL2FjLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL2RhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2Uva3dhcmdzLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL3NoZWxsd29yZHMucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2UvdGltZS5yYiIuZnJlZXplLAogICAgImxpYi9vcHRwYXJzZS91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2UvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9vcHRpb25wYXJzZXIucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/optparse-0.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBwIDAuNi4zIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNi4zIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUHJldHR5LXByaW50cyBSdWJ5IG9iamVjdHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiUHJldHR5LXByaW50cyBSdWJ5IG9iamVjdHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3BwLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/pp-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByZXR0eXByaW50IDAuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmV0dHlwcmludCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSW1wbGVtZW50cyBhIHByZXR0eSBwcmludGluZyBhbGdvcml0aG0gZm9yIHJlYWRhYmxlIHN0cnVjdHVyZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJbXBsZW1lbnRzIGEgcHJldHR5IHByaW50aW5nIGFsZ29yaXRobSBmb3IgcmVhZGFibGUgc3RydWN0dXJlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9wcmV0dHlwcmludC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/prettyprint-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRlbXBmaWxlIDAuMy4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ0ZW1wZmlsZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQSB1dGlsaXR5IGNsYXNzIGZvciBtYW5hZ2luZyB0ZW1wb3JhcnkgZmlsZXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQSB1dGlsaXR5IGNsYXNzIGZvciBtYW5hZ2luZyB0ZW1wb3JhcnkgZmlsZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3RlbXBmaWxlLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tempfile-0.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRlbGVnYXRlIDAuNi4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJkZWxlZ2F0ZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNi4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiRGVsZWdhdGlvbiBvZiBtZXRob2QgY2FsbHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiRGVsZWdhdGlvbiBvZiBtZXRob2QgY2FsbHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL2RlbGVnYXRlLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/delegate-0.6.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRtcGRpciAwLjMuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidG1wZGlyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJFeHRlbmRzIHRoZSBEaXIgY2xhc3MgdG8gbWFuYWdlIHRoZSBPUyB0ZW1wb3JhcnkgZmlsZSBwYXRoLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkV4dGVuZHMgdGhlIERpciBjbGFzcyB0byBtYW5hZ2UgdGhlIE9TIHRlbXBvcmFyeSBmaWxlIHBhdGgiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3RtcGRpci5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tmpdir-0.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpbGV1dGlscyAxLjguMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZmlsZXV0aWxzIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS44LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJTZXZlcmFsIGZpbGUgdXRpbGl0eSBtZXRob2RzIGZvciBjb3B5aW5nLCBtb3ZpbmcsIHJlbW92aW5nLCBldGMuLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlNldmVyYWwgZmlsZSB1dGlsaXR5IG1ldGhvZHMgZm9yIGNvcHlpbmcsIG1vdmluZywgcmVtb3ZpbmcsIGV0Yy4iLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL2ZpbGV1dGlscy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fileutils-1.8.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRpbWUgMC40LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInRpbWUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkV4dGVuZHMgdGhlIFRpbWUgY2xhc3Mgd2l0aCBtZXRob2RzIGZvciBwYXJzaW5nIGFuZCBjb252ZXJzaW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkV4dGVuZHMgdGhlIFRpbWUgY2xhc3Mgd2l0aCBtZXRob2RzIGZvciBwYXJzaW5nIGFuZCBjb252ZXJzaW9uIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi90aW1lLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/time-0.4.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGV0YyAxLjQuNiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXRjIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS40LjYiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBY2Nlc3MgdG8gaW5mb3JtYXRpb24gZnJvbSB0aGUgcGFzc3dkIGFuZCBncm91cCBmaWxlcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBY2Nlc3MgdG8gaW5mb3JtYXRpb24gZnJvbSB0aGUgcGFzc3dkIGFuZCBncm91cCBmaWxlcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2V0Yy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/etc-1.4.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLXdhaXQgMC40LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlvLXdhaXQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIklPI3dhaXQgYW5kIGZyaWVuZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSU8jd2FpdCBhbmQgZnJpZW5kcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2lvL3dhaXQucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-wait-0.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHpsaWIgMy4yLjMgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInpsaWIiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjIuMyIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkRlZmxhdGUvaW5mbGF0ZSwgb24gU3lzdGVtLklPLkNvbXByZXNzaW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRlZmxhdGUvaW5mbGF0ZSwgb24gU3lzdGVtLklPLkNvbXByZXNzaW9uIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvemxpYi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/zlib-3.2.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW5zc2wgMy4yLjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm9wZW5zc2wiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjIuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk9wZW5TU0wgYmluZGluZ3MsIG9uIC5ORVQncyBjcnlwdG9ncmFwaHkgc3RhY2suICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3BlblNTTCBiaW5kaW5ncywgb24gLk5FVCdzIGNyeXB0b2dyYXBoeSBzdGFjayIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL29wZW5zc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9hc24xLnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wvYm4ucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9jaXBoZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9kaWdlc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9wa2V5LnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wvc3NsLnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wveDUwOS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/openssl-3.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGFiYnJldiAwLjEuMiBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYWJicmV2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4xLjIiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9hYmJyZXYiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYWJicmV2IiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJBa2lub3JpIE1VU0hBIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMy0xMi0xNiIKICBzLmRlc2NyaXB0aW9uID0gIkNhbGN1bGF0ZXMgYSBzZXQgb2YgdW5pcXVlIGFiYnJldmlhdGlvbnMgZm9yIGEgZ2l2ZW4gc2V0IG9mIHN0cmluZ3MiLmZyZWV6ZQogIHMuZW1haWwgPSBbImtudUBpZGFlbW9ucy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2FiYnJldiIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2FsY3VsYXRlcyBhIHNldCBvZiB1bmlxdWUgYWJicmV2aWF0aW9ucyBmb3IgYSBnaXZlbiBzZXQgb2Ygc3RyaW5ncyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/abbrev-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJhc2U2NCAwLjMuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYmFzZTY0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYmFzZTY0L3JlbGVhc2VzIiwgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2Jhc2U2NCIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iYXNlNjQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1c3VrZSBFbmRvaCIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJTdXBwb3J0IGZvciBlbmNvZGluZyBhbmQgZGVjb2RpbmcgYmluYXJ5IGRhdGEgdXNpbmcgYSBCYXNlNjQgcmVwcmVzZW50YXRpb24uIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYW1lQHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2Jhc2U2NCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi40Ii5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi43Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiU3VwcG9ydCBmb3IgZW5jb2RpbmcgYW5kIGRlY29kaW5nIGJpbmFyeSBkYXRhIHVzaW5nIGEgQmFzZTY0IHJlcHJlc2VudGF0aW9uLiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/base64-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJjcnlwdCAzLjEuMjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImJjcnlwdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuMS4yMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk9wZW5CU0QgYmNyeXB0IHBhc3N3b3JkIGhhc2hpbmc7IGJjcnlwdF9leHQgaW4gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3BlbkJTRCBiY3J5cHQgcGFzc3dvcmQgaGFzaGluZzsgYmNyeXB0X2V4dCBpbiBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2JjcnlwdC5yYiIuZnJlZXplLAogICAgImxpYi9iY3J5cHQvZW5naW5lLnJiIi5mcmVlemUsCiAgICAibGliL2JjcnlwdC9lcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9iY3J5cHQvcGFzc3dvcmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYmNyeXB0X2V4dC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bcrypt-3.1.22.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJlbmNobWFyayAwLjUuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYmVuY2htYXJrIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC41LjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iZW5jaG1hcmsiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYmVuY2htYXJrIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJZdWtpaGlybyBNYXRzdW1vdG8iLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiYSBwZXJmb3JtYW5jZSBiZW5jaG1hcmtpbmcgbGlicmFyeSIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iZW5jaG1hcmsiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuMS4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiYSBwZXJmb3JtYW5jZSBiZW5jaG1hcmtpbmcgbGlicmFyeSIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/benchmark-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJpZ2RlY2ltYWwgNC4wLjEgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImJpZ2RlY2ltYWwiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICI0LjAuMSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkFyYml0cmFyeS1wcmVjaXNpb24gZGVjaW1hbCBhcml0aG1ldGljLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkFyYml0cmFyeS1wcmVjaXNpb24gZGVjaW1hbCBhcml0aG1ldGljIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvYmlnZGVjaW1hbC5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL2phY29iaWFuLnJiIi5mcmVlemUsCiAgICAibGliL2JpZ2RlY2ltYWwvbHVkY21wLnJiIi5mcmVlemUsCiAgICAibGliL2JpZ2RlY2ltYWwvbWF0aC5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL25ld3Rvbi5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL3V0aWwucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bigdecimal-4.0.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJ1bmRsZXIgNC4wLjIwIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJidW5kbGVyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiNC4wLjIwIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVGhlIGJlc3Qgd2F5IHRvIG1hbmFnZSBhIFJ1YnkgYXBwbGljYXRpb24ncyBnZW1zLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBiZXN0IHdheSB0byBtYW5hZ2UgYSBSdWJ5IGFwcGxpY2F0aW9uJ3MgZ2VtcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmV4ZWN1dGFibGVzID0gWyJidW5kbGUiLmZyZWV6ZSwgImJ1bmRsZXIiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9idW5kbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvYnVpbGRfbWV0YWRhdGEucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jYXBpc3RyYW5vLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2hlY2tzdW0ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jaV9kZXRlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9hZGQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvYmluc3R1YnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2FjaGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2hlY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2xlYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY29tbW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2NvbmZpZy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9jb25zb2xlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2RvY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9kb2N0b3IvZGlhZ25vc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvZG9jdG9yL3NzbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9leGVjLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2Z1bmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvZ2VtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2luZm8ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvaW5pdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9pbnN0YWxsLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2lzc3VlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2xpc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvbG9jay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9vcGVuLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL291dGRhdGVkLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL3BsdWdpbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9wcmlzdGluZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9yZW1vdmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvc2hvdy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS91cGRhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jb21wYWN0X2luZGV4X2NsaWVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L2NhY2hlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY29tcGFjdF9pbmRleF9jbGllbnQvY2FjaGVfZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L3VwZGF0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jb25zdGFudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jdXJyZW50X3J1YnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kZWZpbml0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZGVwZW5kZW5jeS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2RlcGxveW1lbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kZXByZWNhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kaWdlc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9lbmRwb2ludF9zcGVjaWZpY2F0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZW52LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZW52aXJvbm1lbnRfcHJlc2VydmVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmVhdHVyZV9mbGFnLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmV0Y2hlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvY29tcGFjdF9pbmRleC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZGVwZW5kZW5jeS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZG93bmxvYWRlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZ2VtX3JlbW90ZV9mZXRjaGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmV0Y2hlci9pbmRleC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZvcmNlX3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZnJpZW5kbHlfZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZ2VtX2hlbHBlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2dlbV90YXNrcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2dlbV92ZXJzaW9uX3Byb21vdGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvaW5kZXgucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9pbmplY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2lubGluZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci9nZW1faW5zdGFsbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvaW5zdGFsbGVyL3BhcmFsbGVsX2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci9zdGFuZGFsb25lLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbGF6eV9zcGVjaWZpY2F0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbG9ja2ZpbGVfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbG9ja2ZpbGVfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbWF0Y2hfbWV0YWRhdGEucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9tYXRjaF9wbGF0Zm9ybS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21hdGNoX3JlbW90ZV9tZXRhZGF0YS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21hdGVyaWFsaXphdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21pcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9hcGkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wbHVnaW4vYXBpL3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wbHVnaW4vZXZlbnRzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luZGV4LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9pbnN0YWxsZXIvZ2l0LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci9wYXRoLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci9ydWJ5Z2Vtcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9zb3VyY2VfbGlzdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi91bmxvYWRlZF9zb3VyY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wcm9jZXNzX2xvY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9yZW1vdGVfc3BlY2lmaWNhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmVzb2x2ZXIvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL2NhbmRpZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL2luY29tcGF0aWJpbGl0eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL3BhY2thZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9yZXNvbHZlci9yb290LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmVzb2x2ZXIvc3BlY19ncm91cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL3N0cmF0ZWd5LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmV0cnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9ydWJ5X2RzbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlfdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlnZW1zX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlnZW1zX2dlbV9pbnN0YWxsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9ydWJ5Z2Vtc19pbnRlZ3JhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1bnRpbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zYWZlX21hcnNoYWwucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zZWxmX21hbmFnZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zZXR0aW5ncy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NldHRpbmdzL3ZhbGlkYXRvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NldHVwLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc2hhcmVkX2hlbHBlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UvZ2Vtc3BlYy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9naXQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UvZ2l0L2dpdF9wcm94eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9tZXRhZGF0YS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9wYXRoLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3BhdGgvaW5zdGFsbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3J1YnlnZW1zLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3J1YnlnZW1zL3JlbW90ZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9ydWJ5Z2Vtc19hZ2dyZWdhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2VfbGlzdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZV9tYXAucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zcGVjX3NldC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3N0dWJfc3BlY2lmaWNhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VpLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdWkvcmdfcHJveHkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci91aS9zaGVsbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VpL3NpbGVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VyaV9jcmVkZW50aWFsc19maWx0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci91cmlfbm9ybWFsaXplci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC90aW1lZF9zdGFjay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL2Nvbm5lY3Rpb25fcG9vbC9saWIvY29ubmVjdGlvbl9wb29sL3dyYXBwZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvZmlsZXV0aWxzL2xpYi9maWxldXRpbHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvbmV0LWh0dHAtcGVyc2lzdGVudC9saWIvbmV0L2h0dHAvcGVyc2lzdGVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9uZXQtaHR0cC1wZXJzaXN0ZW50L2xpYi9uZXQvaHR0cC9wZXJzaXN0ZW50L2Nvbm5lY3Rpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvbmV0LWh0dHAtcGVyc2lzdGVudC9saWIvbmV0L2h0dHAvcGVyc2lzdGVudC9wb29sLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL25ldC1odHRwLXBlcnNpc3RlbnQvbGliL25ldC9odHRwL3BlcnNpc3RlbnQvdGltZWRfc3RhY2tfbXVsdGkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3B1Yl9ncnViL2xpYi9wdWJfZ3J1Yi9hc3NpZ25tZW50LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3B1Yl9ncnViL2xpYi9wdWJfZ3J1Yi9iYXNpY19wYWNrYWdlX3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvZmFpbHVyZV93cml0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL2luY29tcGF0aWJpbGl0eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcGFja2FnZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcGFydGlhbF9zb2x1dGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcnVieWdlbXMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3NvbHZlX2ZhaWx1cmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3N0YXRpY19wYWNrYWdlX3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvc3RyYXRlZ3kucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3Rlcm0ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb25fY29uc3RyYWludC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvdmVyc2lvbl9yYW5nZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvdmVyc2lvbl9zb2x2ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb25fdW5pb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3Ivc2VjdXJlcmFuZG9tL2xpYi9zZWN1cmVyYW5kb20ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2FjdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9hY3Rpb25zL2NyZWF0ZV9maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9jcmVhdGVfbGluay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2FjdGlvbnMvZGlyZWN0b3J5LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9lbXB0eV9kaXJlY3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9hY3Rpb25zL2ZpbGVfbWFuaXB1bGF0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9pbmplY3RfaW50b19maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2NvbW1hbmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9jb3JlX2V4dC9oYXNoX3dpdGhfaW5kaWZmZXJlbnRfYWNjZXNzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9ncm91cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2ludm9jYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9saW5lX2VkaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2xpbmVfZWRpdG9yL2Jhc2ljLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvbGluZV9lZGl0b3IvcmVhZGxpbmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9uZXN0ZWRfY29udGV4dC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci9hcmd1bWVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci9hcmd1bWVudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9wYXJzZXIvb3B0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvcGFyc2VyL29wdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9yYWtlX2NvbXBhdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3J1bm5lci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3Ivc2hlbGwvYmFzaWMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9zaGVsbC9jb2xvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL2NvbHVtbl9wcmludGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3Ivc2hlbGwvaHRtbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL3RhYmxlX3ByaW50ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9zaGVsbC90ZXJtaW5hbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL3dyYXBwZWRfcHJpbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3V0aWwucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2NvbW1vbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2Z0cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9nZW5lcmljLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvaHR0cHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvbGRhcC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9sZGFwcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9tYWlsdG8ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvcmZjMjM5Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvcmZjMzk4Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS93cy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS93c3MucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9maWxldXRpbHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9uZXRfaHR0cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3BlcnNpc3RlbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9wdWJfZ3J1Yi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3NlY3VyZXJhbmRvbS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3Rob3IucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF90aW1lb3V0LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yZWRfdHNvcnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmxhZC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3dvcmtlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3lhbWxfc2VyaWFsaXplci5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bundler-4.0.20.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGNnaSAwLjUuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiY2dpIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC41LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJDR0kuZXNjYXBlIGFuZCBmcmllbmRzIC0gUnVieSA0LjAncyBjZ2kvZXNjYXBlLCBub3QgdGhlIGZ1bGwgQ0dJIGNsYXNzLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkNHSS5lc2NhcGUgYW5kIGZyaWVuZHMgLSBSdWJ5IDQuMCdzIGNnaS9lc2NhcGUsIG5vdCB0aGUgZnVsbCBDR0kgY2xhc3MiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9jZ2kucmIiLmZyZWV6ZSwKICAgICJsaWIvY2dpL2VzY2FwZS5yYiIuZnJlZXplLAogICAgImxpYi9jZ2kvdXRpbC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/cgi-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGNzdiAzLjMuNSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiY3N2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4zLjUiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvY3N2L3JlbGVhc2VzL3RhZy92My4zLjUiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIkphbWVzIEVkd2FyZCBHcmF5IElJIi5mcmVlemUsICJLb3VoZWkgU3V0b3UiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlRoZSBDU1YgbGlicmFyeSBwcm92aWRlcyBhIGNvbXBsZXRlIGludGVyZmFjZSB0byBDU1YgZmlsZXMgYW5kIGRhdGEuIEl0IG9mZmVycyB0b29scyB0byBlbmFibGUgeW91IHRvIHJlYWQgYW5kIHdyaXRlIHRvIGFuZCBmcm9tIFN0cmluZ3Mgb3IgSU8gb2JqZWN0cywgYXMgbmVlZGVkLiIuZnJlZXplCiAgcy5lbWFpbCA9IFtuaWwsICJrb3VAY296bWl4bmcub3JnIi5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvY3N2L3JlY2lwZXMvZmlsdGVyaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9nZW5lcmF0aW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9wYXJzaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9yZWNpcGVzLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvY3N2L3JlY2lwZXMvZmlsdGVyaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9nZW5lcmF0aW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9wYXJzaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9yZWNpcGVzLnJkb2MiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2NzdiIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjciLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJDU1YgUmVhZGluZyBhbmQgV3JpdGluZyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/csv-3.3.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRpZF95b3VfbWVhbiAyLjAuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZGlkX3lvdV9tZWFuIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4wLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJEaWQgeW91IG1lYW4/IGV4cGVyaWVuY2UuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiRGlkIHlvdSBtZWFuPyBleHBlcmllbmNlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9kaWRfeW91X21lYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL2NvcmVfZXh0L25hbWVfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL2V4cGVyaW1lbnRhbC5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vZm9ybWF0dGVyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9mb3JtYXR0ZXJzL3BsYWluX2Zvcm1hdHRlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vZm9ybWF0dGVycy92ZXJib3NlX2Zvcm1hdHRlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vamFyb193aW5rbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9sZXZlbnNodGVpbi5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlcnMva2V5X2Vycm9yX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL21ldGhvZF9uYW1lX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL25hbWVfZXJyb3JfY2hlY2tlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL25hbWVfZXJyb3JfY2hlY2tlcnMvY2xhc3NfbmFtZV9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9zcGVsbF9jaGVja2Vycy9uYW1lX2Vycm9yX2NoZWNrZXJzL3ZhcmlhYmxlX25hbWVfY2hlY2tlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlcnMvbnVsbF9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9zcGVsbF9jaGVja2Vycy9wYXR0ZXJuX2tleV9uYW1lX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL3JlcXVpcmVfcGF0aF9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi90cmVlX3NwZWxsX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3ZlcmJvc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/did_you_mean-2.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRpZ2VzdCAzLjIuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZGlnZXN0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4yLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJNZXNzYWdlIGRpZ2VzdCBsaWJyYXJpZXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWVzc2FnZSBkaWdlc3QgbGlicmFyaWVzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZGlnZXN0LnJiIi5mcmVlemUsCiAgICAibGliL2RpZ2VzdC9idWJibGViYWJibGUucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlnZXN0L21kNS5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3Qvc2hhMS5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3Qvc2hhMi5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3QvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/digest-3.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRyYiAyLjIuMyBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZHJiIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4yLjMiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiL3JlbGVhc2VzL3RhZy92Mi4yLjMiLCAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2RyYiIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiTWFzYXRvc2hpIFNFS0kiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIkRpc3RyaWJ1dGVkIG9iamVjdCBzeXN0ZW0gZm9yIFJ1YnkiLmZyZWV6ZQogIHMuZW1haWwgPSBbInNla2lAcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjcuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuNyIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRpc3RyaWJ1dGVkIG9iamVjdCBzeXN0ZW0gZm9yIFJ1YnkiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/drb-2.2.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVuZ2xpc2ggMC44LjEgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImVuZ2xpc2giLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlJlYWRhYmxlIGFsaWFzZXMgZm9yIHRoZSBzcGVjaWFsIHZhcmlhYmxlcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJSZWFkYWJsZSBhbGlhc2VzIGZvciB0aGUgc3BlY2lhbCB2YXJpYWJsZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL0VuZ2xpc2gucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/english-0.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVyYiA2LjAuNyBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXJiIi5mcmVlemUKICBzLnZlcnNpb24gPSAiNi4wLjciCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBbiBlYXN5LXRvLXVzZSBidXQgcG93ZXJmdWwgdGVtcGxhdGluZyBzeXN0ZW0uICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQW4gZWFzeS10by11c2UgYnV0IHBvd2VyZnVsIHRlbXBsYXRpbmcgc3lzdGVtIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZXJiLnJiIi5mcmVlemUsCiAgICAibGliL2VyYi9jb21waWxlci5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvZGVmX21ldGhvZC5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvdXRpbC5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/erb-6.0.7.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVycm9yX2hpZ2hsaWdodCAwLjcuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXJyb3JfaGlnaGxpZ2h0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC43LjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgZXJyb3JfaGlnaGxpZ2h0IEFQSTsgc3BvdCBhbHdheXMgYW5zd2VycyBuaWwgaGVyZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJUaGUgZXJyb3JfaGlnaGxpZ2h0IEFQSTsgc3BvdCBhbHdheXMgYW5zd2VycyBuaWwgaGVyZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvZXJyb3JfaGlnaGxpZ2h0LnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC9iYXNlLnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC9jb3JlX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9lcnJvcl9oaWdobGlnaHQvZm9ybWF0dGVyLnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/error_highlight-0.7.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZjbnRsIDEuMy4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJmY250bCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMy4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQ29uc3RhbnRzIGZvciBmY250bCgyKSBhbmQgb3BlbigyKS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJDb25zdGFudHMgZm9yIGZjbnRsKDIpIGFuZCBvcGVuKDIpIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZmNudGwucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fcntl-1.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZmaSAxLjE3LjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImZmaSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMTcuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlRoZSBmZmkgZ2VtJ3MgQVBJLCBvbiBGaWRkbGUuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhlIGZmaSBnZW0ncyBBUEksIG9uIEZpZGRsZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2ZmaS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvYWJzdHJhY3RfbWVtb3J5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9hdXRvcG9pbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9jYWxsYmFjay5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvY29tcGF0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9kYXRhX2NvbnZlcnRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvZHluYW1pY19saWJyYXJ5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9lbnVtLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9lcnJuby5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvZmZpLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9mdW5jdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaW8ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L2R5bmFtaWNfbGlicmFyeS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaXJvbnJ1YnkvZnVuY3Rpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L2xhc3RfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L21lbW9yeS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaXJvbnJ1Ynkvc3RydWN0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9pcm9ucnVieS9zdHJ1Y3RfbGF5b3V0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9pcm9ucnVieS90eXBlLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9saWJyYXJ5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9saWJyYXJ5X3BhdGgucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL21hbmFnZWRzdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL21lbW9yeXBvaW50ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9wb2ludGVyLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9ieV9yZWZlcmVuY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9sYXlvdXQucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9sYXlvdXRfYnVpbGRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvdG9vbHMvY29uc3RfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90b29scy9nZW5lcmF0b3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3Rvb2xzL2dlbmVyYXRvcl90YXNrLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90b29scy9zdHJ1Y3RfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90eXBlcy5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvdW5pb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3ZhcmlhZGljLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ffi-1.17.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpZGRsZSAxLjEuOCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZmlkZGxlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4xLjgiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJDYWxsaW5nIHNoYXJlZC1saWJyYXJ5IGZ1bmN0aW9ucywgb24gTmF0aXZlTGlicmFyeSBhbmQgY2FsbGkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2FsbGluZyBzaGFyZWQtbGlicmFyeSBmdW5jdGlvbnMsIG9uIE5hdGl2ZUxpYnJhcnkgYW5kIGNhbGxpIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZmlkZGxlLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9jbG9zdXJlLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9jcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9mdW5jdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9maWRkbGUvaW1wb3J0LnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9wYWNrLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmlkZGxlL3R5cGVzLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS92YWx1ZS5yYiIuZnJlZXplLAogICAgImxpYi9maWRkbGUvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fiddle-1.1.8.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpbmQgMC4yLjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImZpbmQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlRyYXZlcnNlIGEgZmlsZSB0cmVlLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRyYXZlcnNlIGEgZmlsZSB0cmVlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9maW5kLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/find-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZvcndhcmRhYmxlIDEuNC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJmb3J3YXJkYWJsZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuNC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUHJvdmlkZXMgZGVsZWdhdGlvbiBvZiBzcGVjaWZpZWQgbWV0aG9kcyB0byBhIGRlc2lnbmF0ZWQgb2JqZWN0LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlByb3ZpZGVzIGRlbGVnYXRpb24gb2Ygc3BlY2lmaWVkIG1ldGhvZHMgdG8gYSBkZXNpZ25hdGVkIG9iamVjdCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvZm9yd2FyZGFibGUucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/forwardable-1.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGdldG9wdGxvbmcgMC4yLjEgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImdldG9wdGxvbmciLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2dldG9wdGxvbmciLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZ2V0b3B0bG9uZyIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiWXVraWhpcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5kYXRlID0gIjIwMjMtMTEtMDciCiAgcy5kZXNjcmlwdGlvbiA9ICJHZXRvcHRMb25nIGZvciBSdWJ5Ii5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2dldG9wdGxvbmciLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjUuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJHZXRvcHRMb25nIGZvciBSdWJ5Ii5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/getoptlong-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLW5vbmJsb2NrIDAuMy4yIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJpby1ub25ibG9jayIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4yIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSU8jbm9uYmxvY2suICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSU8jbm9uYmxvY2siLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9pby9ub25ibG9jay5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-nonblock-0.3.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlwYWRkciAxLjIuOCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiaXBhZGRyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4yLjgiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBIGNsYXNzIHRvIG1hbmlwdWxhdGUgYW4gSVAgYWRkcmVzcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBIGNsYXNzIHRvIG1hbmlwdWxhdGUgYW4gSVAgYWRkcmVzcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvaXBhZGRyLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ipaddr-1.2.8.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlyYiAxLjE4LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlyYiIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMTguMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkludGVyYWN0aXZlIFJ1YnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSW50ZXJhY3RpdmUgUnVieSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5leGVjdXRhYmxlcyA9IFsiaXJiIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvaXJiLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jbWQvbm9wLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb2xvci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29sb3JfcHJpbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9iYWNrdHJhY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9icmVhay5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jYXRjaC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jaHdzLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2NvbnRleHQucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvY29udGludWUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvY29weS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9kZWJ1Zy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9kZWxldGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvZGlzYWJsZV9pcmIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvZWRpdC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9leGl0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2ZpbmlzaC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9mb3JjZV9leGl0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2hlbHAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvaGlzdG9yeS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9pbmZvLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2ludGVybmFsX2hlbHBlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvaXJiX2luZm8ucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvbG9hZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9scy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9tZWFzdXJlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL25leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvcHVzaHdzLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3Nob3dfZG9jLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3Nob3dfc291cmNlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3N0ZXAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvc3ViaXJiLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3doZXJlYW1pLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21wbGV0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb250ZXh0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9kZWJ1Zy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvZGVidWcvdWkucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2RlZmF1bHRfY29tbWFuZHMucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2Vhc3Rlci1lZ2cucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9jaGFuZ2Utd3MucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9ldmFsX2hpc3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9sb2FkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9tdWx0aS1pcmIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC90cmFjZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC91c2UtbG9hZGVyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9leHQvd29ya3NwYWNlcy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvZnJhbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHBlcl9tZXRob2QucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHBlcl9tZXRob2QvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvaGVscGVyX21ldGhvZC9jb25mLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9oaXN0b3J5LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9pbml0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9pbnB1dC1tZXRob2QucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2luc3BlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvbGMvZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2xjL2phL2Vycm9yLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9sb2NhbGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL25lc3RpbmdfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9ub3RpZmllci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvb3V0cHV0LW1ldGhvZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvcGFnZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL3J1YnktbGV4LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9zb3VyY2VfZmluZGVyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9zdGFydHVwX21lc3NhZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL3N0YXRlbWVudC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvd29ya3NwYWNlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi93cy1mb3ItY2FzZS0yLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi94bXAucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/irb-1.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGxvZ2dlciAxLjcuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibG9nZ2VyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS43LjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbG9nZ2VyL3JlbGVhc2VzIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJOYW90b3NoaSBTZW8iLmZyZWV6ZSwgIlNISUJBVEEgSGlyb3NoaSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTAzLTI3IgogIHMuZGVzY3JpcHRpb24gPSAiUHJvdmlkZXMgYSBzaW1wbGUgbG9nZ2luZyB1dGlsaXR5IGZvciBvdXRwdXR0aW5nIG1lc3NhZ2VzLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsic29ub3RzQGdtYWlsLmNvbSIuZnJlZXplLCAiaHNidEBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9sb2dnZXIiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuNS4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4xMSIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlByb3ZpZGVzIGEgc2ltcGxlIGxvZ2dpbmcgdXRpbGl0eSBmb3Igb3V0cHV0dGluZyBtZXNzYWdlcy4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/logger-1.7.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1hdHJpeCAwLjQuMyBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibWF0cml4Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC40LjMiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJNYXJjLUFuZHJlIExhZm9ydHVuZSIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjIwMjUtMDYtMTgiCiAgcy5kZXNjcmlwdGlvbiA9ICJBbiBpbXBsZW1lbnRhdGlvbiBvZiBNYXRyaXggYW5kIFZlY3RvciBjbGFzc2VzLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnVieS1jb3JlQG1hcmMtYW5kcmUuY2EiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L21hdHJpeCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQW4gaW1wbGVtZW50YXRpb24gb2YgTWF0cml4IGFuZCBWZWN0b3IgY2xhc3Nlcy4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/matrix-0.4.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1pbml0ZXN0IDYuMC4wIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJtaW5pdGVzdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjYuMC4wIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiYnVnX3RyYWNrZXJfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0L2lzc3VlcyIsICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0L2Jsb2IvbWFzdGVyL0hpc3RvcnkucmRvYyIsICJob21lcGFnZV91cmkiID0+ICJodHRwczovL21pbml0ZS5zdC8iLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0IiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJSeWFuIERhdmlzIi5mcmVlemVdCiAgcy5jZXJ0X2NoYWluID0gWyItLS0tLUJFR0lOIENFUlRJRklDQVRFLS0tLS1cbk1JSURQakNDQWlhZ0F3SUJBZ0lCQ1RBTkJna3Foa2lHOXcwQkFRc0ZBREJGTVJNd0VRWURWUVFEREFweWVXRnVcblpDMXlkV0o1TVJrd0Z3WUtDWkltaVpQeUxHUUJHUllKZW1WdWMzQnBaR1Z5TVJNd0VRWUtDWkltaVpQeUxHUUJcbkdSWURZMjl0TUI0WERUSTFNREV3TmpJek1qY3dNVm9YRFRJMk1ERXdOakl6TWpjd01Wb3dSVEVUTUJFR0ExVUVcbkF3d0tjbmxoYm1RdGNuVmllVEVaTUJjR0NnbVNKb21UOGl4a0FSa1dDWHBsYm5Od2FXUmxjakVUTUJFR0NnbVNcbkpvbVQ4aXhrQVJrV0EyTnZiVENDQVNJd0RRWUpLb1pJaHZjTkFRRUJCUUFEZ2dFUEFEQ0NBUW9DZ2dFQkFMZGFcbmI5RENnSys2MjdnUEprQjZYZmpaMWl0b09RdnBxSDFFWFNjU2FiYTkvUzJWRjIyVllRYlhVMXhRWEwvV3pDa3hcbnRhQ1BhTG1mWUlhRmNISENTWTRoWURKaWpSUWtMeFBlQjN4Yk9memZMb0JEYmp2eDVKeGdKeFVqbUdhN3hoY1Rcbm9Pdmp0dDVQOCtHU0s5ekx6eFFQMGdWTFMvRDBGbW9FNDRYdURyM2lRa1ZTMnVqVTV6Wkw4NG1NTnFOQjF6bmhcbkdpYWRNOUdIUmFEaWF4dVgwY0lVQmoxOVQwMW1WRTJpeW1mOUk2YkVzaWF5Sy9uNlF1anR5Q2JUV3NBUzlScXRcbnFodFY3SEp4Tkt1UGovSkZIMEQyY3N3dnp6bkUvYTVGT1lPNjhnK1lDdUZpNUw4d1p1dU04enpkd2pyV0hxU1ZcbmdCRWZvVEVHcjdaaWk3MmN4K3NDQXdFQUFhTTVNRGN3Q1FZRFZSMFRCQUl3QURBTEJnTlZIUThFQkFNQ0JMQXdcbkhRWURWUjBPQkJZRUZFZkZlOW1kL3IvdGovV213cHkrTUk4ZDlrL2hNQTBHQ1NxR1NJYjNEUUVCQ3dVQUE0SUJcbkFRQUMwV1FKY1BPV1BGd2tvamh6d2VpbFJWalRKMTlVaUxoaUJUdzNDMXdKTzNMVmRCa1dEbW5uaEFtS3VYNERcbnI3dmpRdkVTbEFCR0lQZHV0STFZbDdtckhRelRrZkxmWHZOTjZNVDBuTENoUHlJWWF1VDZTWlp4dWJ3SnJVZkFcbjdSMGMyQ0pUSWJvWjBYYUdwTHNYcUhFRjFjMjlIN1RWMVF2VnVxS0FOMm1Damg0TjgyUVZuK1pLdHlzMjhBd1RcbjZHZlFYMmZxTG9pNEtTYzd4SXpIS2FOenF4ZU9JQ21Kb2ZrOXc1VloyclJONnllczhqdkZZd3o5SFI0MXdkajhcbmJ3ZmludjdZcDVmQTZBeXN1WkxoQ3lreWZEdVpWUnJVcDBWYjY4WUNLc0xqSmx5L1RoZWFrK2V1TlR4dkhzQitcbmFsOW9TZ1BQSElDTUVYNjVxdkx5d2l0eFxuLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLVxuIi5mcmVlemVdCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJtaW5pdGVzdCBwcm92aWRlcyBhIGNvbXBsZXRlIHN1aXRlIG9mIHRlc3RpbmcgZmFjaWxpdGllcyBzdXBwb3J0aW5nXG5UREQsIEJERCwgYW5kIGJlbmNobWFya2luZy5cblxuICAgIFwiSSBoYWQgYSBjbGFzcyB3aXRoIEppbSBXZWlyaWNoIG9uIHRlc3RpbmcgbGFzdCB3ZWVrIGFuZCB3ZSB3ZXJlXG4gICAgIGFsbG93ZWQgdG8gY2hvb3NlIG91ciB0ZXN0aW5nIGZyYW1ld29ya3MuIEtpcmsgSGFpbmVzIGFuZCBJIHdlcmVcbiAgICAgcGFpcmVkIHVwIGFuZCB3ZSBjcmFja2VkIG9wZW4gdGhlIGNvZGUgZm9yIGEgZmV3IHRlc3RcbiAgICAgZnJhbWV3b3Jrcy4uLlxuXG4gICAgIEkgTVVTVCBzYXkgdGhhdCBtaW5pdGVzdCBpcyAqdmVyeSogcmVhZGFibGUgLyB1bmRlcnN0YW5kYWJsZVxuICAgICBjb21wYXJlZCB0byB0aGUgJ290aGVyIHR3bycgb3B0aW9ucyB3ZSBsb29rZWQgYXQuIE5pY2VseSBkb25lIGFuZFxuICAgICB0aGFuayB5b3UgZm9yIGhlbHBpbmcgdXMga2VlcCBvdXIgbWVudGFsIHNhbml0eS5cIlxuXG4gICAgLS0gV2F5bmUgRS4gU2VndWluXG5cbm1pbml0ZXN0L3Rlc3QgaXMgYSBzbWFsbCBhbmQgaW5jcmVkaWJseSBmYXN0IHVuaXQgdGVzdGluZyBmcmFtZXdvcmsuXG5JdCBwcm92aWRlcyBhIHJpY2ggc2V0IG9mIGFzc2VydGlvbnMgdG8gbWFrZSB5b3VyIHRlc3RzIGNsZWFuIGFuZFxucmVhZGFibGUuXG5cbm1pbml0ZXN0L3NwZWMgaXMgYSBmdW5jdGlvbmFsbHkgY29tcGxldGUgc3BlYyBlbmdpbmUuIEl0IGhvb2tzIG9udG9cbm1pbml0ZXN0L3Rlc3QgYW5kIHNlYW1sZXNzbHkgYnJpZGdlcyB0ZXN0IGFzc2VydGlvbnMgb3ZlciB0byBzcGVjXG5leHBlY3RhdGlvbnMuXG5cbm1pbml0ZXN0L2JlbmNobWFyayBpcyBhbiBhd2Vzb21lIHdheSB0byBhc3NlcnQgdGhlIHBlcmZvcm1hbmNlIG9mIHlvdXJcbmFsZ29yaXRobXMgaW4gYSByZXBlYXRhYmxlIG1hbm5lci4gTm93IHlvdSBjYW4gYXNzZXJ0IHRoYXQgeW91ciBuZXdiXG5jby13b3JrZXIgZG9lc24ndCByZXBsYWNlIHlvdXIgbGluZWFyIGFsZ29yaXRobSB3aXRoIGFuIGV4cG9uZW50aWFsXG5vbmUhXG5cbm1pbml0ZXN0L3ByaWRlIHNob3dzIHByaWRlIGluIHRlc3RpbmcgYW5kIGFkZHMgY29sb3JpbmcgdG8geW91ciB0ZXN0XG5vdXRwdXQuIEkgZ3Vlc3MgaXQgaXMgYW4gZXhhbXBsZSBvZiBob3cgdG8gd3JpdGUgSU8gcGlwZXMgdG9vLiA6UFxuXG5taW5pdGVzdC90ZXN0IGlzIG1lYW50IHRvIGhhdmUgYSBjbGVhbiBpbXBsZW1lbnRhdGlvbiBmb3IgbGFuZ3VhZ2VcbmltcGxlbWVudG9ycyB0aGF0IG5lZWQgYSBtaW5pbWFsIHNldCBvZiBtZXRob2RzIHRvIGJvb3RzdHJhcCBhIHdvcmtpbmdcbnRlc3Qgc3VpdGUuIEZvciBleGFtcGxlLCB0aGVyZSBpcyBubyBtYWdpYyBpbnZvbHZlZCBmb3IgdGVzdC1jYXNlXG5kaXNjb3ZlcnkuXG5cbiAgICBcIkFnYWluLCBJIGNhbid0IHByYWlzZSBlbm91Z2ggdGhlIGlkZWEgb2YgYSB0ZXN0aW5nL3NwZWNpbmdcbiAgICAgZnJhbWV3b3JrIHRoYXQgSSBjYW4gYWN0dWFsbHkgcmVhZCBpbiBmdWxsIGluIG9uZSBzaXR0aW5nIVwiXG5cbiAgICAtLSBQaW90ciBTem90a293c2tpXG5cbkNvbXBhcmluZyB0byByc3BlYzpcblxuICAgIHJzcGVjIGlzIGEgdGVzdGluZyBEU0wuIG1pbml0ZXN0IGlzIHJ1YnkuXG5cbiAgICAtLSBBZGFtIEhhd2tpbnMsIFwiQm93IEJlZm9yZSBNaW5pVGVzdFwiXG5cbm1pbml0ZXN0IGRvZXNuJ3QgcmVpbnZlbnQgYW55dGhpbmcgdGhhdCBydWJ5IGFscmVhZHkgcHJvdmlkZXMsIGxpa2U6XG5jbGFzc2VzLCBtb2R1bGVzLCBpbmhlcml0YW5jZSwgbWV0aG9kcy4gVGhpcyBtZWFucyB5b3Ugb25seSBoYXZlIHRvXG5sZWFybiBydWJ5IHRvIHVzZSBtaW5pdGVzdCBhbmQgYWxsIG9mIHlvdXIgcmVndWxhciBPTyBwcmFjdGljZXMgbGlrZVxuZXh0cmFjdC1tZXRob2QgcmVmYWN0b3JpbmdzIHN0aWxsIGFwcGx5LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnlhbmQtcnVieUB6ZW5zcGlkZXIuY29tIi5mcmVlemVdCiAgcy5leGVjdXRhYmxlcyA9IFsibWluaXRlc3QiLmZyZWV6ZV0KICBzLmV4dHJhX3Jkb2NfZmlsZXMgPSBbIkhpc3RvcnkucmRvYyIuZnJlZXplLCAiTWFuaWZlc3QudHh0Ii5mcmVlemUsICJSRUFETUUucmRvYyIuZnJlZXplXQogIHMuZmlsZXMgPSBbIkhpc3RvcnkucmRvYyIuZnJlZXplLCAiTWFuaWZlc3QudHh0Ii5mcmVlemUsICJSRUFETUUucmRvYyIuZnJlZXplLCAiYmluL21pbml0ZXN0Ii5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL21pbml0ZS5zdC8iLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIk1JVCIuZnJlZXplXQogIHMucmRvY19vcHRpb25zID0gWyItLW1haW4iLmZyZWV6ZSwgIlJFQURNRS5yZG9jIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNy4yIi5mcmVlemUKICBzLnN1bW1hcnkgPSAibWluaXRlc3QgcHJvdmlkZXMgYSBjb21wbGV0ZSBzdWl0ZSBvZiB0ZXN0aW5nIGZhY2lsaXRpZXMgc3VwcG9ydGluZyBUREQsIEJERCwgYW5kIGJlbmNobWFya2luZyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxwcmlzbT4uZnJlZXplLCBbIj49IDEuNSIuZnJlZXplXSkKICBzLmFkZF9kZXZlbG9wbWVudF9kZXBlbmRlbmN5KCVxPHJkb2M+LmZyZWV6ZSwgWyI+PSA0LjAiLmZyZWV6ZSwgIjwgNyIuZnJlZXplXSkKICBzLmFkZF9kZXZlbG9wbWVudF9kZXBlbmRlbmN5KCVxPHNpbXBsZWNvdj4uZnJlZXplLCBbIn4+IDAuMjEiLmZyZWV6ZV0pCiAgcy5hZGRfZGV2ZWxvcG1lbnRfZGVwZW5kZW5jeSglcTxob2U+LmZyZWV6ZSwgWyJ+PiA0LjMiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/minitest-6.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1zZ3BhY2sgMS44LjUgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm1zZ3BhY2siLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIxLjguNSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk1lc3NhZ2VQYWNrIHNlcmlhbGl6YXRpb247IHRoZSBDIGV4dGVuc2lvbiBwb3J0ZWQgdG8gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWVzc2FnZVBhY2sgc2VyaWFsaXphdGlvbjsgdGhlIEMgZXh0ZW5zaW9uIHBvcnRlZCB0byBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL21zZ3BhY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9iaWdpbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9idWZmZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9jb3JlX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL2ZhY3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9tc2dwYWNrLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svcGFja2VyLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svc3ltYm9sLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svdGltZS5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL3RpbWVzdGFtcC5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL3VucGFja2VyLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/msgpack-1.8.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG11dGV4X20gMC4zLjAgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm11dGV4X20iLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjMuMCIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImJ1Z190cmFja2VyX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L211dGV4X20vaXNzdWVzIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L211dGV4X20iIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIktlaWp1IElTSElUU1VLQSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI0LTExLTIwIgogIHMuZGVzY3JpcHRpb24gPSAiTWl4aW4gdG8gZXh0ZW5kIG9iamVjdHMgdG8gYmUgaGFuZGxlZCBsaWtlIGEgTXV0ZXguIi5mcmVlemUKICBzLmVtYWlsID0gWyJrZWlqdUBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9tdXRleF9tIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWl4aW4gdG8gZXh0ZW5kIG9iamVjdHMgdG8gYmUgaGFuZGxlZCBsaWtlIGEgTXV0ZXguIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/mutex_m-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1mdHAgMC4zLjkgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1mdHAiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjMuOSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1mdHAiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LWZ0cCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiU2h1Z28gTWFlZGEiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlN1cHBvcnQgZm9yIHRoZSBGaWxlIFRyYW5zZmVyIFByb3RvY29sLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsic2h1Z29AcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LWZ0cCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi42LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTdXBwb3J0IGZvciB0aGUgRmlsZSBUcmFuc2ZlciBQcm90b2NvbC4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8bmV0LXByb3RvY29sPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8dGltZT4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-ftp-0.3.9.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1odHRwIDAuOS4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuZXQtaHR0cCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuOS4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSFRUUCBjbGllbnQgYXBpIGZvciBSdWJ5LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkhUVFAgY2xpZW50IGFwaSBmb3IgUnVieSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvbmV0L2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvbmV0L2h0dHBzLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL2V4Y2VwdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvbmV0L2h0dHAvZ2VuZXJpY19yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL2hlYWRlci5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9wcm94eV9kZWx0YS5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3JlcXVlc3RzLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3Jlc3BvbnNlcy5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9zdGF0dXMucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/net-http-0.9.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1pbWFwIDAuNi40LjEgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1pbWFwIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC42LjQuMSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImNoYW5nZWxvZ191cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcC9yZWxlYXNlcyIsICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiU2h1Z28gTWFlZGEiLmZyZWV6ZSwgIm5pY2hvbGFzIGEuIGV2YW5zIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlJ1YnkgY2xpZW50IGFwaSBmb3IgSW50ZXJuZXQgTWVzc2FnZSBBY2Nlc3MgUHJvdG9jb2wiLmZyZWV6ZQogIHMuZW1haWwgPSBbInNodWdvQHJ1YnktbGFuZy5vcmciLmZyZWV6ZSwgIm5pY2tAcnViaW5pY2suZGV2Ii5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjEzIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiUnVieSBjbGllbnQgYXBpIGZvciBJbnRlcm5ldCBNZXNzYWdlIEFjY2VzcyBQcm90b2NvbCIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxuZXQtcHJvdG9jb2w+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxkYXRlPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-imap-0.6.4.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1wb3AgMC4xLjIgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1wb3AiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjEuMiIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1wb3AiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXBvcCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiWXVraWhpcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMi0wOS0yOCIKICBzLmRlc2NyaXB0aW9uID0gIlJ1YnkgY2xpZW50IGxpYnJhcnkgZm9yIFBPUDMuIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1wb3AiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjQuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJSdWJ5IGNsaWVudCBsaWJyYXJ5IGZvciBQT1AzLiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxuZXQtcHJvdG9jb2w+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-pop-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1wcm90b2NvbCAwLjIuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibmV0LXByb3RvY29sIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgYWJzdHJhY3QgaW50ZXJmYWNlIGZvciBuZXQtKiBjbGllbnQuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhlIGFic3RyYWN0IGludGVyZmFjZSBmb3IgbmV0LSogY2xpZW50Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9uZXQvcHJvdG9jb2wucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/net-protocol-0.2.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1zbXRwIDAuNS4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuZXQtc210cCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNS4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXNtdHAiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXNtdHAiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1a2loaXJvIE1hdHN1bW90byIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTAyLTA1IgogIHMuZGVzY3JpcHRpb24gPSAiU2ltcGxlIE1haWwgVHJhbnNmZXIgUHJvdG9jb2wgY2xpZW50IGxpYnJhcnkgZm9yIFJ1YnkuIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1zbXRwIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjYuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjcuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTaW1wbGUgTWFpbCBUcmFuc2ZlciBQcm90b2NvbCBjbGllbnQgbGlicmFyeSBmb3IgUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8bmV0LXByb3RvY29sPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-smtp-0.5.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5pbzRyIDIuNy41IHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuaW80ciIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuNy41IgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiTklPOjpTZWxlY3RvciwgTW9uaXRvciBhbmQgQnl0ZUJ1ZmZlciwgb24gZXBvbGwsIHBvbGwoMikgb3IgU29ja2V0LlNlbGVjdC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJOSU86OlNlbGVjdG9yLCBNb25pdG9yIGFuZCBCeXRlQnVmZmVyLCBvbiBlcG9sbCwgcG9sbCgyKSBvciBTb2NrZXQuU2VsZWN0Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvbmlvLnJiIi5mcmVlemUsCiAgICAibGliL25pby9ieXRlYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL25pby9tb25pdG9yLnJiIi5mcmVlemUsCiAgICAibGliL25pby9zZWxlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9uaW8vdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9uaW80ci5yYiIuZnJlZXplLAogICAgImxpYi9uaW80cl9leHQucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nio4r-2.7.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5rZiAwLjIuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibmtmIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJOZXR3b3JrIEthbmppIEZpbHRlciwgb24gU3RyaW5nI2VuY29kZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJOZXR3b3JrIEthbmppIEZpbHRlciwgb24gU3RyaW5nI2VuY29kZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL25rZi5yYiIuZnJlZXplLAogICAgImxpYi9rY29udi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nkf-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5va29naXJpIDEuMTguMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibm9rb2dpcmkiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIxLjE4LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJIVE1MNSwgSFRNTDQgYW5kIFhNTCBwYXJzaW5nLCBvbiBBbmdsZVNoYXJwLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkhUTUw1LCBIVE1MNCBhbmQgWE1MIHBhcnNpbmcsIG9uIEFuZ2xlU2hhcnAiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9ub2tvZ2lyaS5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS9jc3MucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkvaHRtbC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS9zZXJpYWxpemVyLnJiIi5mcmVlemUsCiAgICAibGliL25va29naXJpL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkveG1sL2RvY3VtZW50LnJiIi5mcmVlemUsCiAgICAibGliL25va29naXJpL3htbC9kb2N1bWVudF9mcmFnbWVudC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94bWwvbm9kZS5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94bWwvbm9kZV9zZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkveG1sL3NheC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94cGF0aC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nokogiri-1.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9ic2VydmVyIDAuMS4yIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvYnNlcnZlciIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS4yIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb2JzZXJ2ZXIiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb2JzZXJ2ZXIiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1a2loaXJvIE1hdHN1bW90byIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjIwMjMtMTEtMDciCiAgcy5kZXNjcmlwdGlvbiA9ICJJbXBsZW1lbnRhdGlvbiBvZiB0aGUgT2JzZXJ2ZXIgb2JqZWN0LW9yaWVudGVkIGRlc2lnbiBwYXR0ZXJuLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9vYnNlcnZlciIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4wLmRldiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkltcGxlbWVudGF0aW9uIG9mIHRoZSBPYnNlcnZlciBvYmplY3Qtb3JpZW50ZWQgZGVzaWduIHBhdHRlcm4uIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/observer-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9qIDMuMTcuNiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAib2oiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjE3LjYiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJPaidzIDpzdHJpY3QsIDpudWxsLCA6Y29tcGF0IGFuZCA6cmFpbHMgbW9kZXMgYW5kIG1pbWljX0pTT04sIGluIEMjLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIk9qJ3MgOnN0cmljdCwgOm51bGwsIDpjb21wYXQgYW5kIDpyYWlscyBtb2RlcyBhbmQgbWltaWNfSlNPTiwgaW4gQyMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9vai5yYiIuZnJlZXplLAogICAgImxpYi9vai9hY3RpdmVfc3VwcG9ydF9oZWxwZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovYmFnLnJiIi5mcmVlemUsCiAgICAibGliL29qL2Vhc3lfaGFzaC5yYiIuZnJlZXplLAogICAgImxpYi9vai9lcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9vai9qc29uLnJiIi5mcmVlemUsCiAgICAibGliL29qL21pbWljLnJiIi5mcmVlemUsCiAgICAibGliL29qL29qLnJiIi5mcmVlemUsCiAgICAibGliL29qL3Nhai5yYiIuZnJlZXplLAogICAgImxpYi9vai9zY2hhbmRsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovc3RhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/oj-3.17.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW4tdXJpIDAuNS4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcGVuLXVyaSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNS4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQW4gZWFzeS10by11c2Ugd3JhcHBlciBmb3IgTmV0OjpIVFRQIGFuZCBOZXQ6OkZUUC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiBlYXN5LXRvLXVzZSB3cmFwcGVyIGZvciBOZXQ6OkhUVFAgYW5kIE5ldDo6RlRQIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9vcGVuLXVyaS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/open-uri-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW4zIDAuMi4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcGVuMyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUG9wZW4sIGJ1dCB3aXRoIHN0ZGVyciwgdG9vLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlBvcGVuLCBidXQgd2l0aCBzdGRlcnIsIHRvbyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvb3BlbjMucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/open3-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9zdHJ1Y3QgMC42LjMgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm9zdHJ1Y3QiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjYuMyIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImNoYW5nZWxvZ191cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9vc3RydWN0L3JlbGVhc2VzIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJNYXJjLUFuZHJlIExhZm9ydHVuZSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTA3LTE3IgogIHMuZGVzY3JpcHRpb24gPSAiQ2xhc3MgdG8gYnVpbGQgY3VzdG9tIGRhdGEgc3RydWN0dXJlcywgc2ltaWxhciB0byBhIEhhc2guIi5mcmVlemUKICBzLmVtYWlsID0gWyJydWJ5LWNvcmVAbWFyYy1hbmRyZS5jYSIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb3N0cnVjdCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2xhc3MgdG8gYnVpbGQgY3VzdG9tIGRhdGEgc3RydWN0dXJlcywgc2ltaWxhciB0byBhIEhhc2guIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/ostruct-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBvd2VyX2Fzc2VydCAzLjAuMSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicG93ZXJfYXNzZXJ0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4wLjEiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJLYXp1a2kgVHN1amltb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlBvd2VyIEFzc2VydCBzaG93cyBlYWNoIHZhbHVlIG9mIHZhcmlhYmxlcyBhbmQgbWV0aG9kIGNhbGxzIGluIHRoZSBleHByZXNzaW9uLiBJdCBpcyB1c2VmdWwgZm9yIHRlc3RpbmcsIHByb3ZpZGluZyB3aGljaCB2YWx1ZSB3YXNuJ3QgY29ycmVjdCB3aGVuIHRoZSBjb25kaXRpb24gaXMgbm90IHNhdGlzZmllZC4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImthenVraUBjYWxsY2MubmV0Ii5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJSRUFETUUubWQiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJSRUFETUUubWQiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Bvd2VyX2Fzc2VydCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemUsICJSdWJ5Ii5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUG93ZXIgQXNzZXJ0IGZvciBSdWJ5Ii5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/power_assert-3.0.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByaW1lIDAuMS40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmltZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiTWFyYy1BbmRyZSBMYWZvcnR1bmUiLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIyMDI1LTA2LTE4IgogIHMuZGVzY3JpcHRpb24gPSAiUHJpbWUgbnVtYmVycyBhbmQgZmFjdG9yaXphdGlvbiBsaWJyYXJ5LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnVieS1jb3JlQG1hcmMtYW5kcmUuY2EiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3ByaW1lIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjUuMTEiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJQcmltZSBudW1iZXJzIGFuZCBmYWN0b3JpemF0aW9uIGxpYnJhcnkuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHNpbmdsZXRvbj4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPGZvcndhcmRhYmxlPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/prime-0.1.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByaXNtIDIuMC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmlzbSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuMC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVGhlIFByaXNtIFJ1YnkgcGFyc2VyIC0gSXJvblJ1YnkncyBvd24gZnJvbnQgZW5kLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBQcmlzbSBSdWJ5IHBhcnNlciAtIElyb25SdWJ5J3Mgb3duIGZyb250IGVuZCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL3ByaXNtLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2lyb25ydWJ5LnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2Rlc3VnYXJfY29tcGlsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vZGlzcGF0Y2hlci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9kb3RfdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vZmZpLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2luc3BlY3RfdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9sZXhfY29tcGF0LnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL211dGF0aW9uX2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL25vZGUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vbm9kZV9leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vbm9kZV9maW5kLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BhcnNlX3Jlc3VsdC5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wYXJzZV9yZXN1bHQvZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BhcnNlX3Jlc3VsdC9uZXdsaW5lcy5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wYXR0ZXJuLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BvbHlmaWxsL2FwcGVuZF9hc19ieXRlcy5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wb2x5ZmlsbC9ieXRlaW5kZXgucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vcG9seWZpbGwvc2Nhbl9ieXRlLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BvbHlmaWxsL3VucGFjazEucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vcG9seWZpbGwvd2Fybi5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9yZWZsZWN0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3JlbG9jYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vc2VyaWFsaXplLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3N0cmluZ19xdWVyeS5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcGFyc2VyL2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcGFyc2VyL2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3BhcnNlci9sZXhlci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXJfY3VycmVudC5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXJfdmVyc2lvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcmlwcGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9maWx0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcmlwcGVyL2xleGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9zZXhwLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9zaGltLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3J1YnlfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3Zpc2l0b3IucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/prism-2.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBzdG9yZSAwLjIuMSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicHN0b3JlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjEiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9wc3RvcmUiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcHN0b3JlIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJZdWtpaGlybyBNYXRzdW1vdG8iLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiVHJhbnNhY3Rpb25hbCBGaWxlIFN0b3JhZ2UgZm9yIFJ1YnkgT2JqZWN0cyIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9wc3RvcmUiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuOSIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRyYW5zYWN0aW9uYWwgRmlsZSBTdG9yYWdlIGZvciBSdWJ5IE9iamVjdHMiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/pstore-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBzeWNoIDUuMy4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwc3ljaCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjUuMy4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiWUFNTCBwYXJzZXIgYW5kIGVtaXR0ZXIuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiWUFNTCBwYXJzZXIgYW5kIGVtaXR0ZXIiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9wc3ljaC5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9jbGFzc19sb2FkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvY29kZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvY29yZV9leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvZXhjZXB0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2hhbmRsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvaGFuZGxlcnMvZG9jdW1lbnRfc3RyZWFtLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2hhbmRsZXJzL3JlY29yZGVyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2lyb25ydWJ5LnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2pzb24vcnVieV9ldmVudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi9zdHJlYW0ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi90cmVlX2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi95YW1sX2V2ZW50cy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9hbGlhcy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9kb2N1bWVudC5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9tYXBwaW5nLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL25vZGUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvbm9kZXMvc2NhbGFyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL3NlcXVlbmNlLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL3N0cmVhbS5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9vbWFwLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zY2FsYXJfc2Nhbm5lci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvc3RyZWFtLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3N0cmVhbWluZy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zeW50YXhfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdHJlZV9idWlsZGVyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3ZlcnNpb25zLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL2RlcHRoX2ZpcnN0LnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL2VtaXR0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdmlzaXRvcnMvanNvbl90cmVlLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL3RvX3J1YnkucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdmlzaXRvcnMvdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC92aXNpdG9ycy95YW1sX3RyZWUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gveS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/psych-5.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHB1bWEgOC4wLjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInB1bWEiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICI4LjAuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlB1bWEsIHdpdGggaXRzIEhUVFAgcGFyc2VyIGFuZCBUTFMgZW5naW5lIGluIEMjOyBzaW5nbGUgbW9kZSBvbmx5LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlB1bWEsIHdpdGggaXRzIEhUVFAgcGFyc2VyIGFuZCBUTFMgZW5naW5lIGluIEMjOyBzaW5nbGUgbW9kZSBvbmx5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmV4ZWN1dGFibGVzID0gWyJwdW1hIi5mcmVlemUsICJwdW1hY3RsIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvcHVtYS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2FwcC9zdGF0dXMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9iaW5kZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGkucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGllbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGllbnRfZW52LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NsdXN0ZXIvd29ya2VyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlci93b3JrZXJfaGFuZGxlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlcl9hY2NlcHRfbG9vcF9kZWxheS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbW1vbmxvZ2dlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbmZpZ3VyYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jb25zdC5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbnRyb2xfY2xpLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZGV0ZWN0LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZHNsLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZXJyb3JfbG9nZ2VyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZXZlbnRzLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvaW9fYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvanJ1YnlfcmVzdGFydC5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2pzb25fc2VyaWFsaXphdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2xhdW5jaGVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvbGF1bmNoZXIvYnVuZGxlX3BydW5lci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2xvZ193cml0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9taW5pc3NsLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvbWluaXNzbC9jb250ZXh0X2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9udWxsX2lvLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcGx1Z2luLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcGx1Z2luL3N5c3RlbWQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9wbHVnaW4vdG1wX3Jlc3RhcnQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9wdW1hX2h0dHAxMS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3JhY2svYnVpbGRlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3JhY2svdXJsbWFwLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcmFja19kZWZhdWx0LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcmVhY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcnVubmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2Rfbm90aWZ5LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2VydmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2VydmVyX3BsdWdpbl9jb250cm9sLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2luZ2xlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc3RhdGVfZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3RocmVhZF9wb29sLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvdXRpbC5yYiIuZnJlZXplLAogICAgImxpYi9yYWNrL2hhbmRsZXIvcHVtYS5yYiIuZnJlZXplLAogIF0KCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCJuaW80ciIuZnJlZXplLCBbIn4+IDIuMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/puma-8.0.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJhY2MgMS44LjEgcnVieSBsaWIKIyBzdHViOiBleHQvcmFjYy9jcGFyc2UvZXh0Y29uZi5yYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmFjYyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuOC4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JhY2MvcmVsZWFzZXMiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIk1pbmVybyBBb2tpIi5mcmVlemUsICJBYXJvbiBQYXR0ZXJzb24iLmZyZWV6ZV0KICBzLmRhdGUgPSAiMjAyNC0wNy0zMCIKICBzLmRlc2NyaXB0aW9uID0gIlJhY2MgaXMgYW4gTEFMUigxKSBwYXJzZXIgZ2VuZXJhdG9yLlxuICBJdCBpcyB3cml0dGVuIGluIFJ1YnkgaXRzZWxmLCBhbmQgZ2VuZXJhdGVzIFJ1YnkgcHJvZ3JhbS5cblxuICBOT1RFOiBSdWJ5IDEuOC54IGNvbWVzIHdpdGggUmFjYyBydW50aW1lIG1vZHVsZS4gIFlvdVxuICBjYW4gcnVuIHlvdXIgcGFyc2VycyBnZW5lcmF0ZWQgYnkgcmFjYyAxLjQueCBvdXQgb2YgdGhlXG4gIGJveC5cbiIuZnJlZXplCiAgcy5lbWFpbCA9IFtuaWwsICJhYXJvbkB0ZW5kZXJsb3ZlbWFraW5nLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInJhY2MiLmZyZWV6ZV0KICBzLmV4dGVuc2lvbnMgPSBbImV4dC9yYWNjL2NwYXJzZS9leHRjb25mLnJiIi5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJSRUFETUUuamEucmRvYyIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJSRUFETUUuamEucmRvYyIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZSwgImJpbi9yYWNjIi5mcmVlemUsICJleHQvcmFjYy9jcGFyc2UvZXh0Y29uZi5yYiIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFjYyIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmFjYyBpcyBhbiBMQUxSKDEpIHBhcnNlciBnZW5lcmF0b3IiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/racc-1.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJha2UgMTMuMy4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyYWtlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMTMuMy4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiYnVnX3RyYWNrZXJfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFrZS9pc3N1ZXMiLCAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jha2UvcmVsZWFzZXMiLCAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL3J1YnkuZ2l0aHViLmlvL3Jha2UiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFrZSIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSGlyb3NoaSBTSElCQVRBIi5mcmVlemUsICJFcmljIEhvZGVsIi5mcmVlemUsICJKaW0gV2VpcmljaCIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJSYWtlIGlzIGEgTWFrZS1saWtlIHByb2dyYW0gaW1wbGVtZW50ZWQgaW4gUnVieS4gVGFza3MgYW5kIGRlcGVuZGVuY2llcyBhcmVcbnNwZWNpZmllZCBpbiBzdGFuZGFyZCBSdWJ5IHN5bnRheC5cblJha2UgaGFzIHRoZSBmb2xsb3dpbmcgZmVhdHVyZXM6XG4gICogUmFrZWZpbGVzIChyYWtlJ3MgdmVyc2lvbiBvZiBNYWtlZmlsZXMpIGFyZSBjb21wbGV0ZWx5IGRlZmluZWQgaW4gc3RhbmRhcmQgUnVieSBzeW50YXguXG4gICAgTm8gWE1MIGZpbGVzIHRvIGVkaXQuIE5vIHF1aXJreSBNYWtlZmlsZSBzeW50YXggdG8gd29ycnkgYWJvdXQgKGlzIHRoYXQgYSB0YWIgb3IgYSBzcGFjZT8pXG4gICogVXNlcnMgY2FuIHNwZWNpZnkgdGFza3Mgd2l0aCBwcmVyZXF1aXNpdGVzLlxuICAqIFJha2Ugc3VwcG9ydHMgcnVsZSBwYXR0ZXJucyB0byBzeW50aGVzaXplIGltcGxpY2l0IHRhc2tzLlxuICAqIEZsZXhpYmxlIEZpbGVMaXN0cyB0aGF0IGFjdCBsaWtlIGFycmF5cyBidXQga25vdyBhYm91dCBtYW5pcHVsYXRpbmcgZmlsZSBuYW1lcyBhbmQgcGF0aHMuXG4gICogU3VwcG9ydHMgcGFyYWxsZWwgZXhlY3V0aW9uIG9mIHRhc2tzLlxuIi5mcmVlemUKICBzLmVtYWlsID0gWyJoc2J0QHJ1YnktbGFuZy5vcmciLmZyZWV6ZSwgImRyYnJhaW5Ac2VnbWVudDcubmV0Ii5mcmVlemUsICIiLmZyZWV6ZV0KICBzLmV4ZWN1dGFibGVzID0gWyJyYWtlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsiZXhlL3Jha2UiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jha2UiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIk1JVCIuZnJlZXplXQogIHMucmRvY19vcHRpb25zID0gWyItLW1haW4iLmZyZWV6ZSwgIlJFQURNRS5yZG9jIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmFrZSBpcyBhIE1ha2UtbGlrZSBwcm9ncmFtIGltcGxlbWVudGVkIGluIFJ1YnkiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rake-13.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJicyA0LjAuMC5kZXYuNSBydWJ5IGxpYgojIHN0dWI6IGV4dC9yYnNfZXh0ZW5zaW9uL2V4dGNvbmYucmIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInJicyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjQuMC4wLmRldi41Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jicy9ibG9iL21hc3Rlci9DSEFOR0VMT0cubWQiLCAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmJzIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jicy5naXQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIlNvdXRhcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlJCUyBpcyB0aGUgbGFuZ3VhZ2UgZm9yIHR5cGUgc2lnbmF0dXJlcyBmb3IgUnVieSBhbmQgc3RhbmRhcmQgbGlicmFyeSBkZWZpbml0aW9ucy4iLmZyZWV6ZQogIHMuZW1haWwgPSBbIm1hdHN1bW90b0Bzb3V0YXJvLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInJicyIuZnJlZXplXQogIHMuZXh0ZW5zaW9ucyA9IFsiZXh0L3Jic19leHRlbnNpb24vZXh0Y29uZi5yYiIuZnJlZXplXQogIHMuZmlsZXMgPSBbImV4ZS9yYnMiLmZyZWV6ZSwgImV4dC9yYnNfZXh0ZW5zaW9uL2V4dGNvbmYucmIiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JicyIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemUsICJSdWJ5Ii5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiVHlwZSBzaWduYXR1cmUgZm9yIFJ1YnkuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPGxvZ2dlcj4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHByaXNtPi5mcmVlemUsIFsiPj0gMS4zLjAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHRzb3J0Pi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rbs-4.0.0.dev.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlYWRsaW5lIDAuMC40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZWFkbGluZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMC40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiYXljYWJ0YSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDIzLTEyLTE2IgogIHMuZGVzY3JpcHRpb24gPSAiVGhpcyBpcyBqdXN0IGEgbG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIElmIFJ1YnkgaGFzIHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbVxudGhhdCBpcyBhIG5hdGl2ZSBleHRlbnNpb24sIHRoaXMgZ2VtIHdpbGwgbG9hZCBpdC4gSWYgUnVieSBkb2VzIG5vdCBoYXZlXG50aGUgXCJyZWFkbGluZS1leHRcIiBnZW0gdGhpcyBnZW0gd2lsbCBsb2FkIFwicmVsaW5lXCIsIGEgbGlicmFyeSB0aGF0IGlzXG5jb21wYXRpYmxlIHdpdGggdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIGFuZCBpbXBsZW1lbnRlZCBpbiBwdXJlIFJ1YnkuXG4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImF5Y2FidGFAZ21haWwuY29tIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZWFkbGluZSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplXQogIHMucG9zdF9pbnN0YWxsX21lc3NhZ2UgPSAiKy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLStcbnwgVGhpcyBpcyBqdXN0IGEgbG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIElmIFJ1YnkgaGFzIHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbSAgfFxufCB0aGF0IGlzIGEgbmF0aXZlIGV4dGVuc2lvbiwgdGhpcyBnZW0gd2lsbCBsb2FkIGl0LiBJZiBSdWJ5IGRvZXMgbm90IGhhdmUgIHxcbnwgdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIHRoaXMgZ2VtIHdpbGwgbG9hZCBcInJlbGluZVwiLCBhIGxpYnJhcnkgdGhhdCBpcyAgICAgfFxufCBjb21wYXRpYmxlIHdpdGggdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIGFuZCBpbXBsZW1lbnRlZCBpbiBwdXJlIFJ1YnkuICAgICAgfFxufCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHxcbnwgSWYgeW91IGludGVuZCB0byB1c2UgR05VIFJlYWRsaW5lIGJ5IGByZXF1aXJlICdyZWFkbGluZSdgLCBwbGVhc2UgaW5zdGFsbCB8XG58IHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbS4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB8XG4rLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tK1xuIi5mcmVlemUKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiTG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHJlbGluZT4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/readline-0.0.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlbGluZSAwLjYuMyBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmVsaW5lIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC42LjMiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJHTlUgUmVhZGxpbmUgYW5kIEVkaXRsaW5lLCBpbiBwdXJlIFJ1YnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiR05VIFJlYWRsaW5lIGFuZCBFZGl0bGluZSwgaW4gcHVyZSBSdWJ5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvcmVsaW5lLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9jb25maWcucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2ZhY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2hpc3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2lvLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby9hbnNpLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby9kdW1iLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby93aW5kb3dzLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2tleV9hY3Rvci9iYXNlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvY29tcG9zaXRlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvZW1hY3MucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2tleV9hY3Rvci92aV9jb21tYW5kLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvdmlfaW5zZXJ0LnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfc3Ryb2tlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9raWxsX3JpbmcucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2xpbmVfZWRpdG9yLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS91bmljb2RlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS91bmljb2RlL2Vhc3RfYXNpYW5fd2lkdGgucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/reline-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlcGxfdHlwZV9jb21wbGV0b3IgMC4xLjE2IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXBsX3R5cGVfY29tcGxldG9yIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4xLjE2Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXBsX3R5cGVfY29tcGxldG9yIiwgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JlcGxfdHlwZV9jb21wbGV0b3IiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVwbF90eXBlX2NvbXBsZXRvciIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsidG9tcG5nIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlR5cGUgYmFzZWQgY29tcGxldGlvbiBmb3IgUkVQTC4iLmZyZWV6ZQogIHMuZW1haWwgPSBbInRvbW95YXBlbmd1aW5AZ21haWwuY29tIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXBsX3R5cGVfY29tcGxldG9yIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJNSVQiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAzLjAuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuNyIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlR5cGUgYmFzZWQgY29tcGxldGlvbiBmb3IgUkVQTC4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cHJpc20+LmZyZWV6ZSwgWyI+PSAxLjAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHJicz4uZnJlZXplLCBbIj49IDIuNy4wIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/repl_type_completor-0.1.16.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlc29sdiAwLjcuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmVzb2x2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC43LjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaHJlYWQtYXdhcmUgRE5TIHJlc29sdmVyIGxpYnJhcnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhyZWFkLWF3YXJlIEROUyByZXNvbHZlciBsaWJyYXJ5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9yZXNvbHYucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/resolv-0.7.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlc29sdi1yZXBsYWNlIDAuMS4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXNvbHYtcmVwbGFjZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVzb2x2LXJlcGxhY2UiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVzb2x2LXJlcGxhY2UiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIlRhbmFrYSBBa2lyYSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDIyLTEyLTE0IgogIHMuZGVzY3JpcHRpb24gPSAiUmVwbGFjZSBTb2NrZXQgRE5TIHdpdGggUmVzb2x2LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsiYWtyQGZzaWoub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXNvbHYtcmVwbGFjZSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy40LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmVwbGFjZSBTb2NrZXQgRE5TIHdpdGggUmVzb2x2LiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxyZXNvbHY+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/resolv-replace-0.1.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJleG1sIDMuNC40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXhtbCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuNC40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JleG1sL3JlbGVhc2VzL3RhZy92My40LjQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIktvdWhlaSBTdXRvdSIuZnJlZXplXQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiQW4gWE1MIHRvb2xraXQgZm9yIFJ1YnkiLmZyZWV6ZQogIHMuZW1haWwgPSBbImtvdUBjb3ptaXhuZy5vcmciLmZyZWV6ZV0KICBzLmV4dHJhX3Jkb2NfZmlsZXMgPSBbIkxJQ0VOU0UudHh0Ii5mcmVlemUsICJORVdTLm1kIi5mcmVlemUsICJSRUFETUUubWQiLmZyZWV6ZSwgImRvYy9yZXhtbC9jb250ZXh0LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2NoaWxkLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2RvY3VtZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2VsZW1lbnQucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3Jkb2Mvbm9kZS5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9wYXJlbnQucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvY2hpbGRfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL2RvY3VtZW50X3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9lbGVtZW50X3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9tYXN0ZXJfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL25vZGVfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL3BhcmVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3R1dG9yaWFsLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvcmV4bWwvY29udGV4dC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9jaGlsZC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9kb2N1bWVudC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9lbGVtZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL25vZGUucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3Jkb2MvcGFyZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL2NoaWxkX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9kb2N1bWVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvZWxlbWVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvbWFzdGVyX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9ub2RlX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9wYXJlbnRfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90dXRvcmlhbC5yZG9jIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXhtbCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiBYTUwgdG9vbGtpdCBmb3IgUnVieSIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rexml-3.4.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJpbmRhIDAuMi4wIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyaW5kYSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIk1hc2F0b3NoaSBTRUtJIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMy0xMS0wNyIKICBzLmRlc2NyaXB0aW9uID0gIlRoZSBMaW5kYSBkaXN0cmlidXRlZCBjb21wdXRpbmcgcGFyYWRpZ20gaW4gUnVieS4iLmZyZWV6ZQogIHMuZW1haWwgPSBbInNla2lAcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuMy4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4wLmRldiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBMaW5kYSBkaXN0cmlidXRlZCBjb21wdXRpbmcgcGFyYWRpZ20gaW4gUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8ZHJiPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8aXBhZGRyPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8Zm9yd2FyZGFibGU+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rinda-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJzcyAwLjMuMiBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicnNzIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjIiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJLb3VoZWkgU3V0b3UiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIkZhbWlseSBvZiBsaWJyYXJpZXMgdGhhdCBzdXBwb3J0IHZhcmlvdXMgZm9ybWF0cyBvZiBYTUwgXCJmZWVkc1wiLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsia291QGNvem1peG5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcnNzIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjIiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJGYW1pbHkgb2YgbGlicmFyaWVzIHRoYXQgc3VwcG9ydCB2YXJpb3VzIGZvcm1hdHMgb2YgWE1MIFwiZmVlZHNcIi4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cmV4bWw+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rss-0.3.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJ1YnkyX2tleXdvcmRzIDAuMC41IHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJydWJ5Ml9rZXl3b3JkcyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMC41IgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiU2hpbSBsaWJyYXJ5IGZvciBNb2R1bGUjcnVieTJfa2V5d29yZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiU2hpbSBsaWJyYXJ5IGZvciBNb2R1bGUjcnVieTJfa2V5d29yZHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3J1YnkyX2tleXdvcmRzLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ruby2_keywords-0.0.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNlY3VyZXJhbmRvbSAwLjQuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic2VjdXJlcmFuZG9tIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC40LjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJJbnRlcmZhY2UgZm9yIHNlY3VyZSByYW5kb20gbnVtYmVyIGdlbmVyYXRvci4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJbnRlcmZhY2UgZm9yIHNlY3VyZSByYW5kb20gbnVtYmVyIGdlbmVyYXRvciIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2VjdXJlcmFuZG9tLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/securerandom-0.4.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNoZWxsd29yZHMgMC4yLjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInNoZWxsd29yZHMiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk1hbmlwdWxhdGVzIHN0cmluZ3Mgd2l0aCB3b3JkIHBhcnNpbmcgcnVsZXMgb2YgVU5JWCBCb3VybmUgc2hlbGwuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWFuaXB1bGF0ZXMgc3RyaW5ncyB3aXRoIHdvcmQgcGFyc2luZyBydWxlcyBvZiBVTklYIEJvdXJuZSBzaGVsbCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2hlbGx3b3Jkcy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/shellwords-0.2.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNpbmdsZXRvbiAwLjMuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic2luZ2xldG9uIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgU2luZ2xldG9uIG1vZHVsZSBpbXBsZW1lbnRzIHRoZSBTaW5nbGV0b24gcGF0dGVybi4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJUaGUgU2luZ2xldG9uIG1vZHVsZSBpbXBsZW1lbnRzIHRoZSBTaW5nbGV0b24gcGF0dGVybiIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2luZ2xldG9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/singleton-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNxbGl0ZTMgMi45LjYgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInNxbGl0ZTMiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIyLjkuNiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlNRTGl0ZTMsIG9uIHRoZSBuYXRpdmUgbGlicmFyeSBNaWNyb3NvZnQuRGF0YS5TcWxpdGUgY2Fycmllcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTUUxpdGUzLCBvbiB0aGUgbmF0aXZlIGxpYnJhcnkgTWljcm9zb2Z0LkRhdGEuU3FsaXRlIGNhcnJpZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zcWxpdGUzLnJiIi5mcmVlemUsCiAgICAibGliL3NxbGl0ZTMvY29uc3RhbnRzLnJiIi5mcmVlemUsCiAgICAibGliL3NxbGl0ZTMvZGF0YWJhc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9lcnJvcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9mb3JrX3NhZmV0eS5yYiIuZnJlZXplLAogICAgImxpYi9zcWxpdGUzL3ByYWdtYXMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9yZXN1bHRzZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9zdGF0ZW1lbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy92YWx1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zcWxpdGUzL3ZlcnNpb25faW5mby5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/sqlite3-2.9.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN5bnRheF9zdWdnZXN0IDIuMC4zIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJzeW50YXhfc3VnZ2VzdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuMC4zIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiRmluZCBzeW50YXggZXJyb3JzIGluIHlvdXIgc291cmNlIGluIGEgc25hcC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJGaW5kIHN5bnRheCBlcnJvcnMgaW4geW91ciBzb3VyY2UgaW4gYSBzbmFwIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9zeW50YXhfc3VnZ2VzdC5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9hcGkucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvYXJvdW5kX2Jsb2NrX3NjYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvYmxvY2tfZXhwYW5kLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NhcHR1cmUvYmVmb3JlX2FmdGVyX2tleXdvcmRfZW5kcy5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9jYXB0dXJlL2ZhbGxpbmdfaW5kZW50X2xpbmVzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NhcHR1cmVfY29kZV9jb250ZXh0LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NsZWFuX2RvY3VtZW50LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NsaS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9jb2RlX2Jsb2NrLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvZGVfZnJvbnRpZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvY29kZV9saW5lLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvZGVfc2VhcmNoLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvcmVfZXh0LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2Rpc3BsYXlfY29kZV93aXRoX2xpbmVfbnVtYmVycy5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9kaXNwbGF5X2ludmFsaWRfYmxvY2tzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2V4cGxhaW5fc3ludGF4LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2xlZnRfcmlnaHRfbGV4X2NvdW50LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2xleF9hbGwucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvbGV4X3ZhbHVlLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L21pbmlfc3RyaW5naW8ucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvcGFyc2VfYmxvY2tzX2Zyb21faW5kZW50X2xpbmUucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvcGF0aG5hbWVfZnJvbV9tZXNzYWdlLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L3ByaW9yaXR5X2VuZ3VsZl9xdWV1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9wcmlvcml0eV9xdWV1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9yaXBwZXJfZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L3NjYW5faGlzdG9yeS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC91bnZpc2l0ZWRfbGluZXMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/syntax_suggest-2.0.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN5c2xvZyAwLjMuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic3lzbG9nIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJTeXNsb2csIGltcGxlbWVudGVkIGluIFNyYy9MaWJyYXJpZXMvU3lzbG9nLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlN5c2xvZywgaW1wbGVtZW50ZWQgaW4gU3JjL0xpYnJhcmllcy9TeXNsb2ciLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zeXNsb2cucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/syslog-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRlc3QtdW5pdCAzLjcuNSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidGVzdC11bml0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy43LjUiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJidWdfdHJhY2tlcl91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vdGVzdC11bml0L3Rlc3QtdW5pdC9pc3N1ZXMiLCAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL3Rlc3QtdW5pdC5naXRodWIuaW8vdGVzdC11bml0L2VuLyIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vdGVzdC11bml0L3Rlc3QtdW5pdCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiS291aGVpIFN1dG91Ii5mcmVlemUsICJIYXJ1a2EgWW9zaGloYXJhIi5mcmVlemVdCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJ0ZXN0LXVuaXQgKFRlc3Q6OlVuaXQpIGlzIHVuaXQgdGVzdGluZyBmcmFtZXdvcmsgZm9yIFJ1YnksIGJhc2VkIG9uIHhVbml0XG5wcmluY2lwbGVzLiBUaGVzZSB3ZXJlIG9yaWdpbmFsbHkgZGVzaWduZWQgYnkgS2VudCBCZWNrLCBjcmVhdG9yIG9mIGV4dHJlbWVcbnByb2dyYW1taW5nIHNvZnR3YXJlIGRldmVsb3BtZW50IG1ldGhvZG9sb2d5LCBmb3IgU21hbGx0YWxrJ3MgU1VuaXQuIEl0IGFsbG93c1xud3JpdGluZyB0ZXN0cywgY2hlY2tpbmcgcmVzdWx0cyBhbmQgYXV0b21hdGVkIHRlc3RpbmcgaW4gUnVieS4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImtvdUBjb3ptaXhuZy5vcmciLmZyZWV6ZSwgInlvc2hpaGFyYUBjbGVhci1jb2RlLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInRlc3QtdW5pdCIuZnJlZXplXQogIHMuZmlsZXMgPSBbImJpbi90ZXN0LXVuaXQiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vdGVzdC11bml0LmdpdGh1Yi5pby8iLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTREwiLmZyZWV6ZSwgIlBTRkwiLmZyZWV6ZV0KICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiB4VW5pdCBmYW1pbHkgdW5pdCB0ZXN0aW5nIGZyYW1ld29yayBmb3IgUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cG93ZXJfYXNzZXJ0Pi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/test-unit-3.7.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRpbWVvdXQgMC42LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInRpbWVvdXQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjYuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkF1dG8tdGVybWluYXRlIHBvdGVudGlhbGx5IGxvbmctcnVubmluZyBvcGVyYXRpb25zLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkF1dG8tdGVybWluYXRlIHBvdGVudGlhbGx5IGxvbmctcnVubmluZyBvcGVyYXRpb25zIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi90aW1lb3V0LnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/timeout-0.6.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRzb3J0IDAuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ0c29ydCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVG9wb2xvZ2ljYWwgc29ydGluZyB1c2luZyBUYXJqYW4ncyBhbGdvcml0aG0uICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVG9wb2xvZ2ljYWwgc29ydGluZyB1c2luZyBUYXJqYW4ncyBhbGdvcml0aG0iLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3Rzb3J0LnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tsort-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHVuIDAuMy4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ1biIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVXRpbGl0aWVzIHRvIHJlcGxhY2UgY29tbW9uIFVOSVggY29tbWFuZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVXRpbGl0aWVzIHRvIHJlcGxhY2UgY29tbW9uIFVOSVggY29tbWFuZHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3VuLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/un-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHVyaSAxLjEuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidXJpIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4xLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJVUkkgaXMgYSBtb2R1bGUgcHJvdmlkaW5nIGNsYXNzZXMgdG8gaGFuZGxlIFVuaWZvcm0gUmVzb3VyY2UgSWRlbnRpZmllcnMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVVJJIGlzIGEgbW9kdWxlIHByb3ZpZGluZyBjbGFzc2VzIHRvIGhhbmRsZSBVbmlmb3JtIFJlc291cmNlIElkZW50aWZpZXJzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL2NvbW1vbi5yYiIuZnJlZXplLAogICAgImxpYi91cmkvZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi91cmkvZnRwLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9nZW5lcmljLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9odHRwLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9odHRwcy5yYiIuZnJlZXplLAogICAgImxpYi91cmkvbGRhcC5yYiIuZnJlZXplLAogICAgImxpYi91cmkvbGRhcHMucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL21haWx0by5yYiIuZnJlZXplLAogICAgImxpYi91cmkvcmZjMjM5Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL3JmYzM5ODZfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS93cy5yYiIuZnJlZXplLAogICAgImxpYi91cmkvd3NzLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/uri-1.1.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYWtyZWYgMC4xLjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYWtyZWYiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjEuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi93ZWFrcmVmLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/weakref-0.1.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYnNvY2tldC1kcml2ZXIgMC44LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYnNvY2tldC1kcml2ZXIiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIldlYlNvY2tldCBwcm90b2NvbCBoYW5kbGVyOyBXZWJTb2NrZXQ6Ok1hc2sgaW4gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiV2ViU29ja2V0IHByb3RvY29sIGhhbmRsZXI7IFdlYlNvY2tldDo6TWFzayBpbiBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL3dlYnNvY2tldF9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9jbGllbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9kcmFmdDc1LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvZHJhZnQ3Ni5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2V2ZW50X2VtaXR0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oZWFkZXJzLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvaHliaS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2h5YmkvZnJhbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oeWJpL21lc3NhZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9wcm94eS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3NlcnZlci5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3N0cmVhbV9yZWFkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAvaGVhZGVycy5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvaHR0cC9yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9odHRwL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC93ZWJzb2NrZXRfbWFzay5yYiIuZnJlZXplLAogIF0KCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCJ3ZWJzb2NrZXQtZXh0ZW5zaW9ucyIuZnJlZXplLCBbIj49IDAuMS4wIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/websocket-driver-0.8.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHlhbWwgMC40LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInlhbWwiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi95YW1sLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvZGJtLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvc3RvcmUucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/yaml-0.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"]} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID0oY29uZmlnKCkpCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lOjpDb3JlI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYXV0b2NvbXBsZXRpb24nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YXV0b2NvbXBsZXRpb24sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgKGNvbmZpZygpKQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIpCiAgXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2NvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlcicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXI9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9hcHBlbmRfY2hhcmFjdGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMpCiAgXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2Jhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnM9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6YmFzaWNfd29yZF9icmVha19jaGFyYWN0ZXJzPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uY29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycykKICBfLmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYmFzaWNfcXVvdGVfY2hhcmFjdGVycykKICBfLmJhc2ljX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNiYXNpY19xdW90ZV9jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJhc2ljX3F1b3RlX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmJhc2ljX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzKQogIF8uY29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycykKICBfLmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uc3BlY2lhbF9wcmVmaXhlcykKICBfLnNwZWNpYWxfcHJlZml4ZXMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3NwZWNpYWxfcHJlZml4ZXMgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNzcGVjaWFsX3ByZWZpeGVzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnNwZWNpYWxfcHJlZml4ZXMsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOnNwZWNpYWxfcHJlZml4ZXM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX3Byb2MpCiAgXy5jb21wbGV0aW9uX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcHJvYyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2NvbXBsZXRpb25fcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2M9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9wcm9jPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLm91dHB1dF9tb2RpZmllcl9wcm9jKQogIF8ub3V0cHV0X21vZGlmaWVyX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI291dHB1dF9tb2RpZmllcl9wcm9jIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9Iicjb3V0cHV0X21vZGlmaWVyX3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6b3V0cHV0X21vZGlmaWVyX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpvdXRwdXRfbW9kaWZpZXJfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByb21wdF9wcm9jKQogIF8ucHJvbXB0X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3Byb21wdF9wcm9jIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcHJvbXB0X3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cHJvbXB0X3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcm9tcHRfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYXV0b19pbmRlbnRfcHJvYykKICBfLmF1dG9faW5kZW50X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9faW5kZW50X3Byb2MgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvX2luZGVudF9wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmF1dG9faW5kZW50X3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmF1dG9faW5kZW50X3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vayguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByZV9pbnB1dF9ob29rKQogIF8ucHJlX2lucHV0X2hvb2soLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ByZV9pbnB1dF9ob29rIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcHJlX2lucHV0X2hvb2snLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cHJlX2lucHV0X2hvb2ssIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vaz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcmVfaW5wdXRfaG9vaz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYykKICBfLmRpZ19wZXJmZWN0X21hdGNoX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNkaWdfcGVyZmVjdF9tYXRjaF9wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmRpZ19wZXJmZWN0X21hdGNoX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmRpZ19wZXJmZWN0X21hdGNoX3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBpbnB1dD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDppbnB1dD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXQ9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6b3V0cHV0PSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy52aV9lZGl0aW5nX21vZGUpCiAgXy52aV9lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3ZpX2VkaXRpbmdfbW9kZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDp2aV9lZGl0aW5nX21vZGUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5lbWFjc19lZGl0aW5nX21vZGUpCiAgXy5lbWFjc19lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2VtYWNzX2VkaXRpbmdfbW9kZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDplbWFjc19lZGl0aW5nX21vZGUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZG11bHRpbGluZSkKICBfLnJlYWRtdWx0aWxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRtdWx0aWxpbmUgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNyZWFkbXVsdGlsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnJlYWRtdWx0aWxpbmUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnJlYWRsaW5lKQogIF8ucmVhZGxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRsaW5lIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVhZGxpbmUnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVhZGxpbmUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fY2FzZV9mb2xkKQogIF8uY29tcGxldGlvbl9jYXNlX2ZvbGQoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fY2FzZV9mb2xkIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9jYXNlX2ZvbGQnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGlvbl9jYXNlX2ZvbGQsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0aW9uX2Nhc2VfZm9sZD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyKQogIF8uY29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXInLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1SZWxpbmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZGxpbmUpCiAgXy5yZWFkbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZGxpbmUgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoxNTkgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNyZWFkbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBnZXRfc2NyZWVuX3NpemUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5nZXRfc2NyZWVuX3NpemUpCiAgXy5nZXRfc2NyZWVuX3NpemUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2dldF9zY3JlZW5fc2l6ZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2dldF9zY3JlZW5fc2l6ZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpnZXRfc2NyZWVuX3NpemUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPWxpbmVfZWRpdG9yCiAgICBpZiBkZWZpbmVkPyhfLmVvZj8pCiAgXy5lb2Y/KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNlb2Y/IGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW9mPycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDplb2Y/LCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5lb2Y/KQogIF8uZW9mPyguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjZW9mPyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjE1OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2VvZj8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZW9mPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBkZWxldGVfdGV4dCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5kZWxldGVfdGV4dCkKICBfLmRlbGV0ZV90ZXh0KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNkZWxldGVfdGV4dCBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2RlbGV0ZV90ZXh0JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmRlbGV0ZV90ZXh0LCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBsaW5lX2J1ZmZlciguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5saW5lKQogIF8ubGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjbGluZV9idWZmZXIgYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDY4IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBwb2ludCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5ieXRlX3BvaW50ZXIpCiAgXy5ieXRlX3BvaW50ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3BvaW50IGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvcmVsaW5lLnJiOjQ2OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2J5dGVfcG9pbnRlcicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpieXRlX3BvaW50ZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBwb2ludD0oLi4uKQogICAgbGluZV9lZGl0b3IKICAgIC5fX3NlbmRfXyg6Ynl0ZV9wb2ludGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiByZWRpc3BsYXkoLi4uKQogICAgXyA9bGluZV9lZGl0b3IKICAgIGlmIGRlZmluZWQ/KF8ucmVyZW5kZXIpCiAgXy5yZXJlbmRlciguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVkaXNwbGF5IGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvcmVsaW5lLnJiOjQ3OCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlcmVuZGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnJlcmVuZGVyLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8udmlfZWRpdGluZ19tb2RlPykKICBfLnZpX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyN2aV9lZGl0aW5nX21vZGU/JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnZpX2VkaXRpbmdfbW9kZT8sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZW1hY3NfZWRpdGluZ19tb2RlPykKICBfLmVtYWNzX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1ib290cGFyc2UvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNlbWFjc19lZGl0aW5nX21vZGU/JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVtYWNzX2VkaXRpbmdfbW9kZT8sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBhbWJpZ3VvdXNfd2lkdGgoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hbWJpZ3VvdXNfd2lkdGgpCiAgXy5hbWJpZ3VvdXNfd2lkdGgoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FtYmlndW91c193aWR0aCBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2FtYmlndW91c193aWR0aCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphbWJpZ3VvdXNfd2lkdGgsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmxhc3RfaW5jcmVtZW50YWxfc2VhcmNoKQogIF8ubGFzdF9pbmNyZW1lbnRhbF9zZWFyY2goLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2xhc3RfaW5jcmVtZW50YWxfc2VhcmNoIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjbGFzdF9pbmNyZW1lbnRhbF9zZWFyY2gnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6bGFzdF9pbmNyZW1lbnRhbF9zZWFyY2gsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBhZGRfZGlhbG9nX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hZGRfZGlhbG9nX3Byb2MpCiAgXy5hZGRfZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FkZF9kaWFsb2dfcHJvYyBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2FkZF9kaWFsb2dfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphZGRfZGlhbG9nX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBkaWFsb2dfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmRpYWxvZ19wcm9jKQogIF8uZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpYWxvZ19wcm9jIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZGlhbG9nX3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGlhbG9nX3Byb2MsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtYm9vdHBhcnNlL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYXV0b2NvbXBsZXRpb24nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YXV0b2NvbXBsZXRpb24sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5yZWFkbXVsdGlsaW5lKQogIF8ucmVhZG11bHRpbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZG11bHRpbGluZSBhdCAvaG9tZS91c2VyL3d0LWJvb3RwYXJzZS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjE1OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRtdWx0aWxpbmUnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVhZG11bHRpbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"]} -{"code":"c2VsZg==","encoding":"UTF-8","path":"(eval at ${ROOT}/Src/StdLib/ruby/4.0/irb/workspace.rb:71)","line":1,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":[],"moduleNames":[]} +{"code":"ICAgICMgZnJvemVuX3N0cmluZ19saXRlcmFsOiB0cnVlCgogICAgZGVmIHNldF9uaWxfYXR0cmlidXRlc190b19uaWwKICAgICAgQGF1dG9yZXF1aXJlID0gbmlsOyBAZGF0ZSA9IG5pbDsgQGRlc2NyaXB0aW9uID0gbmlsOyBAZW1haWwgPSBuaWw7IEBob21lcGFnZSA9IG5pbDsgQG5hbWUgPSBuaWw7IEBwb3N0X2luc3RhbGxfbWVzc2FnZSA9IG5pbDsgQHNpZ25pbmdfa2V5ID0gbmlsOyBAc3VtbWFyeSA9IG5pbDsgQHZlcnNpb24gPSBuaWwKICAgIGVuZAogICAgcHJpdmF0ZSA6c2V0X25pbF9hdHRyaWJ1dGVzX3RvX25pbAoKICAgIGRlZiBzZXRfbm90X25pbF9hdHRyaWJ1dGVzX3RvX2RlZmF1bHRfdmFsdWVzCiAgICAgIEBhdXRob3JzID0gW107QGJpbmRpciA9ICJiaW4iO0BjZXJ0X2NoYWluID0gW107QGRlcGVuZGVuY2llcyA9IFtdO0BleGVjdXRhYmxlcyA9IFtdO0BleHRlbnNpb25zID0gW107QGV4dHJhX3Jkb2NfZmlsZXMgPSBbXTtAZmlsZXMgPSBbXTtAbGljZW5zZXMgPSBbXTtAbWV0YWRhdGEgPSB7fTtAcGxhdGZvcm0gPSAicnVieSI7QHJkb2Nfb3B0aW9ucyA9IFtdO0ByZXF1aXJlX3BhdGhzID0gZGVmYXVsdF92YWx1ZSg6cmVxdWlyZV9wYXRocykuZHVwO0ByZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBkZWZhdWx0X3ZhbHVlKDpyZXF1aXJlZF9ydWJ5X3ZlcnNpb24pLmR1cDtAcmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IGRlZmF1bHRfdmFsdWUoOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24pLmR1cDtAcmVxdWlyZW1lbnRzID0gW107QHJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjIwIjtAc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNDtAdGVzdF9maWxlcyA9IFtdCiAgICBlbmQKICAgIHByaXZhdGUgOnNldF9ub3RfbmlsX2F0dHJpYnV0ZXNfdG9fZGVmYXVsdF92YWx1ZXMK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/rubygems/specification.rb","line":1938,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["today"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyBmcm96ZW5fc3RyaW5nX2xpdGVyYWw6IHRydWUKCiMtLQojIENvcHlyaWdodCAyMDA2IGJ5IENoYWQgRm93bGVyLCBSaWNoIEtpbG1lciwgSmltIFdlaXJpY2ggYW5kIG90aGVycy4KIyBBbGwgcmlnaHRzIHJlc2VydmVkLgojIFNlZSBMSUNFTlNFLnR4dCBmb3IgcGVybWlzc2lvbnMuCiMrKwoKcmVxdWlyZSAibW9uaXRvciIKCm1vZHVsZSBLZXJuZWwKICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1IgPSBNb25pdG9yLm5ldyAjIDpub2RvYzoKCiAgIyBNYWtlIHN1cmUgd2UgaGF2ZSBhIHJlZmVyZW5jZSB0byBSdWJ5J3Mgb3JpZ2luYWwgS2VybmVsI3JlcXVpcmUKICB1bmxlc3MgZGVmaW5lZD8oZ2VtX29yaWdpbmFsX3JlcXVpcmUpCiAgICAjIDpzdG9wZG9jOgogICAgYWxpYXNfbWV0aG9kIDpnZW1fb3JpZ2luYWxfcmVxdWlyZSwgOnJlcXVpcmUKICAgIHByaXZhdGUgOmdlbV9vcmlnaW5hbF9yZXF1aXJlCiAgICAjIDpzdGFydGRvYzoKICBlbmQKCiAgIyMKICAjIFdoZW4gUnVieUdlbXMgaXMgcmVxdWlyZWQsIEtlcm5lbCNyZXF1aXJlIGlzIHJlcGxhY2VkIHdpdGggb3VyIG93biB3aGljaAogICMgaXMgY2FwYWJsZSBvZiBsb2FkaW5nIGdlbXMgb24gZGVtYW5kLgogICMKICAjIFdoZW4geW91IGNhbGwgPHR0PnJlcXVpcmUgJ3gnPC90dD4sIHRoaXMgaXMgd2hhdCBoYXBwZW5zOgogICMgKiBJZiB0aGUgZmlsZSBjYW4gYmUgbG9hZGVkIGZyb20gdGhlIGV4aXN0aW5nIFJ1YnkgbG9hZHBhdGgsIGl0CiAgIyAgIGlzLgogICMgKiBPdGhlcndpc2UsIGluc3RhbGxlZCBnZW1zIGFyZSBzZWFyY2hlZCBmb3IgYSBmaWxlIHRoYXQgbWF0Y2hlcy4KICAjICAgSWYgaXQncyBmb3VuZCBpbiBnZW0gJ3knLCB0aGF0IGdlbSBpcyBhY3RpdmF0ZWQgKGFkZGVkIHRvIHRoZQogICMgICBsb2FkcGF0aCkuCiAgIwogICMgVGhlIG5vcm1hbCA8dHQ+cmVxdWlyZTwvdHQ+IGZ1bmN0aW9uYWxpdHkgb2YgcmV0dXJuaW5nIGZhbHNlIGlmCiAgIyB0aGF0IGZpbGUgaGFzIGFscmVhZHkgYmVlbiBsb2FkZWQgaXMgcHJlc2VydmVkLgoKICBkZWYgcmVxdWlyZShwYXRoKSAjIDpkb2M6CiAgICByZXR1cm4gZ2VtX29yaWdpbmFsX3JlcXVpcmUocGF0aCkgdW5sZXNzIEdlbS5kaXNjb3Zlcl9nZW1zX29uX3JlcXVpcmUKCiAgICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1Iuc3luY2hyb25pemUgZG8KICAgICAgcGF0aCA9IEZpbGUucGF0aChwYXRoKQoKICAgICAgIyBJZiArcGF0aCsgYmVsb25ncyB0byBhIGRlZmF1bHQgZ2VtLCB3ZSBhY3RpdmF0ZSBpdCBhbmQgdGhlbiBnbyBzdHJhaWdodAogICAgICAjIHRvIG5vcm1hbCByZXF1aXJlCgogICAgICBpZiBzcGVjID0gR2VtLmZpbmRfZGVmYXVsdF9zcGVjKHBhdGgpCiAgICAgICAgbmFtZSA9IHNwZWMubmFtZQoKICAgICAgICBuZXh0IGlmIEdlbS5sb2FkZWRfc3BlY3NbbmFtZV0KCiAgICAgICAgIyBFbnN1cmUgLUkgYmVhdHMgYSBkZWZhdWx0IGdlbQogICAgICAgIHJlc29sdmVkX3BhdGggPSBiZWdpbgogICAgICAgICAgcnAgPSBuaWwKICAgICAgICAgIGxvYWRfcGF0aF9jaGVja19pbmRleCA9IEdlbS5sb2FkX3BhdGhfaW5zZXJ0X2luZGV4IC0gR2VtLmFjdGl2YXRlZF9nZW1fcGF0aHMKICAgICAgICAgIEdlbS5zdWZmaXhlcy5maW5kIGRvIHxzfAogICAgICAgICAgICAkTE9BRF9QQVRIWzAuLi5sb2FkX3BhdGhfY2hlY2tfaW5kZXhdLmZpbmQgZG8gfGxwfAogICAgICAgICAgICAgIGlmIEZpbGUuc3ltbGluaz8gbHAgIyBmb3IgYmFja3dhcmQgY29tcGF0aWJpbGl0eQogICAgICAgICAgICAgICAgbmV4dAogICAgICAgICAgICAgIGVuZAoKICAgICAgICAgICAgICBmdWxsX3BhdGggPSBGaWxlLmV4cGFuZF9wYXRoKEZpbGUuam9pbihscCwgIiN7cGF0aH0je3N9IikpCiAgICAgICAgICAgICAgcnAgPSBmdWxsX3BhdGggaWYgRmlsZS5maWxlPyhmdWxsX3BhdGgpCiAgICAgICAgICAgIGVuZAogICAgICAgICAgZW5kCiAgICAgICAgICBycAogICAgICAgIGVuZAoKICAgICAgICBuZXh0IGlmIHJlc29sdmVkX3BhdGgKCiAgICAgICAgS2VybmVsLnNlbmQoOmdlbSwgbmFtZSwgR2VtOjpSZXF1aXJlbWVudC5kZWZhdWx0X3ByZXJlbGVhc2UpCgogICAgICAgIEdlbS5sb2FkX2J1bmRsZXJfZXh0ZW5zaW9ucyhHZW0ubG9hZGVkX3NwZWNzW25hbWVdLnZlcnNpb24pIGlmIG5hbWUgPT0gImJ1bmRsZXIiCgogICAgICAgIG5leHQKICAgICAgZW5kCgogICAgICAjIElmIHRoZXJlIGFyZSBubyB1bnJlc29sdmVkIGRlcHMsIHRoZW4gd2UgY2FuIHVzZSBqdXN0IHRyeQogICAgICAjIG5vcm1hbCByZXF1aXJlIGhhbmRsZSBsb2FkaW5nIGEgZ2VtIGZyb20gdGhlIHJlc2N1ZSBiZWxvdy4KCiAgICAgIGlmIEdlbTo6U3BlY2lmaWNhdGlvbi51bnJlc29sdmVkX2RlcHMuZW1wdHk/CiAgICAgICAgbmV4dAogICAgICBlbmQKCiAgICAgICMgSWYgK3BhdGgrIGlzIGZvciBhIGdlbSB0aGF0IGhhcyBhbHJlYWR5IGJlZW4gbG9hZGVkLCBkb24ndAogICAgICAjIGJvdGhlciB0cnlpbmcgdG8gZmluZCBpdCBpbiBhbiB1bnJlc29sdmVkIGdlbSwganVzdCBnbyBzdHJhaWdodAogICAgICAjIHRvIG5vcm1hbCByZXF1aXJlLgogICAgICAjLS0KICAgICAgIyBUT0RPIHJlcXVlc3QgYWNjZXNzIHRvIHRoZSBDIGltcGxlbWVudGF0aW9uIG9mIHRoaXMgdG8gc3BlZWQgdXAgUnVieUdlbXMKCiAgICAgIGlmIEdlbTo6U3BlY2lmaWNhdGlvbi5maW5kX2FjdGl2ZV9zdHViX2J5X3BhdGgocGF0aCkKICAgICAgICBuZXh0CiAgICAgIGVuZAoKICAgICAgIyBBdHRlbXB0IHRvIGZpbmQgK3BhdGgrIGluIGFueSB1bnJlc29sdmVkIGdlbXMuLi4KCiAgICAgIGZvdW5kX3NwZWNzID0gR2VtOjpTcGVjaWZpY2F0aW9uLmZpbmRfaW5fdW5yZXNvbHZlZCBwYXRoCgogICAgICAjIElmIHRoZXJlIGFyZSBubyBkaXJlY3RseSB1bnJlc29sdmVkIGdlbXMsIHRoZW4gdHJ5IGFuZCBmaW5kICtwYXRoKwogICAgICAjIGluIGFueSBnZW1zIHRoYXQgYXJlIGF2YWlsYWJsZSB2aWEgdGhlIGN1cnJlbnRseSB1bnJlc29sdmVkIGdlbXMuCiAgICAgICMgRm9yIGV4YW1wbGUsIGdpdmVuOgogICAgICAjCiAgICAgICMgICBhID0+IGIgPT4gYyA9PiBkCiAgICAgICMKICAgICAgIyBJZiBhIGFuZCBiIGFyZSBjdXJyZW50bHkgYWN0aXZlIHdpdGggYyBiZWluZyB1bnJlc29sdmVkIGFuZCBkLnJiIGlzCiAgICAgICMgcmVxdWVzdGVkLCB0aGVuIGZpbmRfaW5fdW5yZXNvbHZlZF90cmVlIHdpbGwgZmluZCBkLnJiIGluIGQgYmVjYXVzZQogICAgICAjIGl0J3MgYSBkZXBlbmRlbmN5IG9mIGMuCiAgICAgICMKICAgICAgaWYgZm91bmRfc3BlY3MuZW1wdHk/CiAgICAgICAgZm91bmRfc3BlY3MgPSBHZW06OlNwZWNpZmljYXRpb24uZmluZF9pbl91bnJlc29sdmVkX3RyZWUgcGF0aAoKICAgICAgICBmb3VuZF9zcGVjcy5lYWNoKCY6YWN0aXZhdGUpCgogICAgICAjIFdlIGZvdW5kICtwYXRoKyBkaXJlY3RseSBpbiBhbiB1bnJlc29sdmVkIGdlbS4gTm93IHdlIGZpZ3VyZSBvdXQsIG9mCiAgICAgICMgdGhlIHBvc3NpYmxlIGZvdW5kIHNwZWNzLCB3aGljaCBvbmUgd2Ugc2hvdWxkIGFjdGl2YXRlLgogICAgICBlbHNlCgogICAgICAgICMgQ2hlY2sgdGhhdCBhbGwgdGhlIGZvdW5kIHNwZWNzIGFyZSBqdXN0IGRpZmZlcmVudAogICAgICAgICMgdmVyc2lvbnMgb2YgdGhlIHNhbWUgZ2VtCiAgICAgICAgbmFtZXMgPSBmb3VuZF9zcGVjcy5tYXAoJjpuYW1lKS51bmlxCgogICAgICAgIGlmIG5hbWVzLnNpemUgPiAxCiAgICAgICAgICByYWlzZSBHZW06OkxvYWRFcnJvciwgIiN7cGF0aH0gZm91bmQgaW4gbXVsdGlwbGUgZ2VtczogI3tuYW1lcy5qb2luICIsICJ9IgogICAgICAgIGVuZAoKICAgICAgICAjIE9rLCBub3cgZmluZCBhIGdlbSB0aGF0IGhhcyBubyBjb25mbGljdHMsIHN0YXJ0aW5nCiAgICAgICAgIyBhdCB0aGUgaGlnaGVzdCB2ZXJzaW9uLgogICAgICAgIHZhbGlkID0gZm91bmRfc3BlY3MuZmluZCB7fHN8ICFzLmhhc19jb25mbGljdHM/IH0KCiAgICAgICAgdW5sZXNzIHZhbGlkCiAgICAgICAgICBsZSA9IEdlbTo6TG9hZEVycm9yLm5ldyAidW5hYmxlIHRvIGZpbmQgYSB2ZXJzaW9uIG9mICcje25hbWVzLmZpcnN0fScgdG8gYWN0aXZhdGUiCiAgICAgICAgICBsZS5uYW1lID0gbmFtZXMuZmlyc3QKICAgICAgICAgIHJhaXNlIGxlCiAgICAgICAgZW5kCgogICAgICAgIHZhbGlkLmFjdGl2YXRlCiAgICAgIGVuZAogICAgZW5kCgogICAgYmVnaW4KICAgICAgZ2VtX29yaWdpbmFsX3JlcXVpcmUocGF0aCkKICAgIHJlc2N1ZSBMb2FkRXJyb3IgPT4gbG9hZF9lcnJvcgogICAgICBpZiBsb2FkX2Vycm9yLnBhdGggPT0gcGF0aCAmJgogICAgICAgICBSVUJZR0VNU19BQ1RJVkFUSU9OX01PTklUT1Iuc3luY2hyb25pemUgeyBHZW0udHJ5X2FjdGl2YXRlKHBhdGgpIH0KCiAgICAgICAgcmV0dXJuIGdlbV9vcmlnaW5hbF9yZXF1aXJlKHBhdGgpCiAgICAgIGVuZAoKICAgICAgcmFpc2UgbG9hZF9lcnJvcgogICAgZW5kCiAgZW5kCgogIHByaXZhdGUgOnJlcXVpcmUKZW5kCg==","encoding":"US-ASCII","path":"","line":1,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["e","path","msg","file"],"moduleNames":[],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGpzb24gMi4xOC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJqc29uIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4xOC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSlNPTiBwYXJzaW5nIGFuZCBnZW5lcmF0aW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkpTT04gcGFyc2luZyBhbmQgZ2VuZXJhdGlvbiIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2pzb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvYmlnZGVjaW1hbC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9jb21wbGV4LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL2NvcmUucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9kYXRlX3RpbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvZXhjZXB0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL29zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmFuZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmF0aW9uYWwucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvcmVnZXhwLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL3NldC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC9zdHJpbmcucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi9hZGQvc3RydWN0LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vYWRkL3N5bWJvbC5yYiIuZnJlZXplLAogICAgImxpYi9qc29uL2FkZC90aW1lLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vY29tbW9uLnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vZXh0LnJiIi5mcmVlemUsCiAgICAibGliL2pzb24vZ2VuZXJpY19vYmplY3QucmIiLmZyZWV6ZSwKICAgICJsaWIvanNvbi92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/json-2.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN0cmluZ2lvIDMuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJzdHJpbmdpbyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSU8gb24gc3RyaW5ncy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJTyBvbiBzdHJpbmdzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvc3RyaW5naW8ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/stringio-3.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN0cnNjYW4gMy4xLjYgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInN0cnNjYW4iLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjEuNiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkxleGljYWwgc2Nhbm5pbmcgb2Ygc3RyaW5ncy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJMZXhpY2FsIHNjYW5uaW5nIG9mIHN0cmluZ3MiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zdHJzY2FuLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/strscan-3.1.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLWNvbnNvbGUgMC44LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlvLWNvbnNvbGUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkNvbnNvbGUgc2l6ZSBhbmQgcmF3IG1vZGUuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ29uc29sZSBzaXplIGFuZCByYXcgbW9kZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2lvL2NvbnNvbGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaW8vY29uc29sZS9zaXplLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-console-0.8.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRhdGUgMy4zLjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImRhdGUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjMuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkRhdGUgYW5kIERhdGVUaW1lLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRhdGUgYW5kIERhdGVUaW1lIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9kYXRlL2Zvcm1hdC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/date-3.3.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"ZGVmIHllYXI7IEBlbGVtWzp5ZWFyXTsgZW5kOyBkZWYgeWVhcj0odik7IEBlbGVtWzp5ZWFyXSA9IHY7IGVuZA==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIG1vbjsgQGVsZW1bOm1vbl07IGVuZDsgZGVmIG1vbj0odik7IEBlbGVtWzptb25dID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIG1kYXk7IEBlbGVtWzptZGF5XTsgZW5kOyBkZWYgbWRheT0odik7IEBlbGVtWzptZGF5XSA9IHY7IGVuZA==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIGhvdXI7IEBlbGVtWzpob3VyXTsgZW5kOyBkZWYgaG91cj0odik7IEBlbGVtWzpob3VyXSA9IHY7IGVuZA==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIG1pbjsgQGVsZW1bOm1pbl07IGVuZDsgZGVmIG1pbj0odik7IEBlbGVtWzptaW5dID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHNlYzsgQGVsZW1bOnNlY107IGVuZDsgZGVmIHNlYz0odik7IEBlbGVtWzpzZWNdID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHNlY19mcmFjdGlvbjsgQGVsZW1bOnNlY19mcmFjdGlvbl07IGVuZDsgZGVmIHNlY19mcmFjdGlvbj0odik7IEBlbGVtWzpzZWNfZnJhY3Rpb25dID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHNlY29uZHM7IEBlbGVtWzpzZWNvbmRzXTsgZW5kOyBkZWYgc2Vjb25kcz0odik7IEBlbGVtWzpzZWNvbmRzXSA9IHY7IGVuZA==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHpvbmU7IEBlbGVtWzp6b25lXTsgZW5kOyBkZWYgem9uZT0odik7IEBlbGVtWzp6b25lXSA9IHY7IGVuZA==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIG9mZnNldDsgQGVsZW1bOm9mZnNldF07IGVuZDsgZGVmIG9mZnNldD0odik7IEBlbGVtWzpvZmZzZXRdID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHdkYXk7IEBlbGVtWzp3ZGF5XTsgZW5kOyBkZWYgd2RheT0odik7IEBlbGVtWzp3ZGF5XSA9IHY7IGVuZA==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHlkYXk7IEBlbGVtWzp5ZGF5XTsgZW5kOyBkZWYgeWRheT0odik7IEBlbGVtWzp5ZGF5XSA9IHY7IGVuZA==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIGN3eWVhcjsgQGVsZW1bOmN3eWVhcl07IGVuZDsgZGVmIGN3eWVhcj0odik7IEBlbGVtWzpjd3llYXJdID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIGN3ZWVrOyBAZWxlbVs6Y3dlZWtdOyBlbmQ7IGRlZiBjd2Vlaz0odik7IEBlbGVtWzpjd2Vla10gPSB2OyBlbmQ=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIGN3ZGF5OyBAZWxlbVs6Y3dkYXldOyBlbmQ7IGRlZiBjd2RheT0odik7IEBlbGVtWzpjd2RheV0gPSB2OyBlbmQ=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHdudW0wOyBAZWxlbVs6d251bTBdOyBlbmQ7IGRlZiB3bnVtMD0odik7IEBlbGVtWzp3bnVtMF0gPSB2OyBlbmQ=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIHdudW0xOyBAZWxlbVs6d251bTFdOyBlbmQ7IGRlZiB3bnVtMT0odik7IEBlbGVtWzp3bnVtMV0gPSB2OyBlbmQ=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIGxlZnRvdmVyOyBAZWxlbVs6bGVmdG92ZXJdOyBlbmQ7IGRlZiBsZWZ0b3Zlcj0odik7IEBlbGVtWzpsZWZ0b3Zlcl0gPSB2OyBlbmQ=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIF9jZW50OyBAZWxlbVs6X2NlbnRdOyBlbmQ7IGRlZiBfY2VudD0odik7IEBlbGVtWzpfY2VudF0gPSB2OyBlbmQ=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIF9tZXJpZDsgQGVsZW1bOl9tZXJpZF07IGVuZDsgZGVmIF9tZXJpZD0odik7IEBlbGVtWzpfbWVyaWRdID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIF9jb21wOyBAZWxlbVs6X2NvbXBdOyBlbmQ7IGRlZiBfY29tcD0odik7IEBlbGVtWzpfY29tcF0gPSB2OyBlbmQ=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"ZGVmIF9iYzsgQGVsZW1bOl9iY107IGVuZDsgZGVmIF9iYz0odik7IEBlbGVtWzpfYmNdID0gdjsgZW5k","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ironruby/date/format.rb","line":134,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name"],"moduleNames":["Date::Format::Bag","Date::Format::Bag","Date::Format","Date::Format","Date","Date"],"module":"Date::Format::Bag"} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wdHBhcnNlIDAuOC4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcHRwYXJzZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuOC4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiT3B0aW9uUGFyc2VyIGlzIGEgY2xhc3MgZm9yIGNvbW1hbmQtbGluZSBvcHRpb24gYW5hbHlzaXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3B0aW9uUGFyc2VyIGlzIGEgY2xhc3MgZm9yIGNvbW1hbmQtbGluZSBvcHRpb24gYW5hbHlzaXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL29wdHBhcnNlLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL2FjLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL2RhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2Uva3dhcmdzLnJiIi5mcmVlemUsCiAgICAibGliL29wdHBhcnNlL3NoZWxsd29yZHMucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2UvdGltZS5yYiIuZnJlZXplLAogICAgImxpYi9vcHRwYXJzZS91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvb3B0cGFyc2UvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9vcHRpb25wYXJzZXIucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/optparse-0.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBwIDAuNi4zIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNi4zIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUHJldHR5LXByaW50cyBSdWJ5IG9iamVjdHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiUHJldHR5LXByaW50cyBSdWJ5IG9iamVjdHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3BwLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/pp-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByZXR0eXByaW50IDAuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmV0dHlwcmludCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSW1wbGVtZW50cyBhIHByZXR0eSBwcmludGluZyBhbGdvcml0aG0gZm9yIHJlYWRhYmxlIHN0cnVjdHVyZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJbXBsZW1lbnRzIGEgcHJldHR5IHByaW50aW5nIGFsZ29yaXRobSBmb3IgcmVhZGFibGUgc3RydWN0dXJlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9wcmV0dHlwcmludC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/prettyprint-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRlbXBmaWxlIDAuMy4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ0ZW1wZmlsZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQSB1dGlsaXR5IGNsYXNzIGZvciBtYW5hZ2luZyB0ZW1wb3JhcnkgZmlsZXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQSB1dGlsaXR5IGNsYXNzIGZvciBtYW5hZ2luZyB0ZW1wb3JhcnkgZmlsZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3RlbXBmaWxlLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tempfile-0.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRlbGVnYXRlIDAuNi4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJkZWxlZ2F0ZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNi4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiRGVsZWdhdGlvbiBvZiBtZXRob2QgY2FsbHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiRGVsZWdhdGlvbiBvZiBtZXRob2QgY2FsbHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL2RlbGVnYXRlLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/delegate-0.6.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRtcGRpciAwLjMuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidG1wZGlyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJFeHRlbmRzIHRoZSBEaXIgY2xhc3MgdG8gbWFuYWdlIHRoZSBPUyB0ZW1wb3JhcnkgZmlsZSBwYXRoLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkV4dGVuZHMgdGhlIERpciBjbGFzcyB0byBtYW5hZ2UgdGhlIE9TIHRlbXBvcmFyeSBmaWxlIHBhdGgiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3RtcGRpci5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tmpdir-0.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpbGV1dGlscyAxLjguMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZmlsZXV0aWxzIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS44LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJTZXZlcmFsIGZpbGUgdXRpbGl0eSBtZXRob2RzIGZvciBjb3B5aW5nLCBtb3ZpbmcsIHJlbW92aW5nLCBldGMuLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlNldmVyYWwgZmlsZSB1dGlsaXR5IG1ldGhvZHMgZm9yIGNvcHlpbmcsIG1vdmluZywgcmVtb3ZpbmcsIGV0Yy4iLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL2ZpbGV1dGlscy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fileutils-1.8.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"ICAgICAgICBkZWYgY2QoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY2hkaXIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbWtkaXIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbWtkaXJfcCgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbWtwYXRoKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCB2ZXJib3NlOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbWFrZWRpcnMoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgcm1kaXIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbG4oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbGluaygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY3BfbHIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbG5fcygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgc3ltbGluaygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbG5fc2YoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbG5fc3IoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY3AoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY29weSgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY3BfcigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbXYoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbW92ZSgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgcm0oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgcmVtb3ZlKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCB2ZXJib3NlOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgcm1fZigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgc2FmZV91bmxpbmsoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgcm1fcigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgcm1fcmYoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgcm10cmVlKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCB2ZXJib3NlOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgaW5zdGFsbCgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY2htb2QoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY2htb2RfUigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY2hvd24oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgY2hvd25fUigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgdG91Y2goKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2642,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::Verbose","FileUtils::Verbose","FileUtils","FileUtils"],"module":"FileUtils::Verbose"} +{"code":"ICAgICAgICBkZWYgbWtkaXIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbWtkaXJfcCgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbWtwYXRoKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCBub29wOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbWFrZWRpcnMoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgcm1kaXIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbG4oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbGluaygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY3BfbHIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbG5fcygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgc3ltbGluaygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbG5fc2YoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbG5fc3IoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY3AoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY29weSgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY3BfcigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbXYoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbW92ZSgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgcm0oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgcmVtb3ZlKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCBub29wOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgcm1fZigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgc2FmZV91bmxpbmsoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgcm1fcigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgcm1fcmYoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgcm10cmVlKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCBub29wOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgaW5zdGFsbCgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY2htb2QoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY2htb2RfUigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY2hvd24oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgY2hvd25fUigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgdG91Y2goKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2665,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::NoWrite","FileUtils::NoWrite","FileUtils","FileUtils"],"module":"FileUtils::NoWrite"} +{"code":"ICAgICAgICBkZWYgbWtkaXIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbWtkaXJfcCgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbWtwYXRoKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCBub29wOiB0cnVlLCB2ZXJib3NlOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbWFrZWRpcnMoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgcm1kaXIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbG4oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbGluaygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY3BfbHIoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbG5fcygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgc3ltbGluaygqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbG5fc2YoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbG5fc3IoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY3AoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY29weSgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY3BfcigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbXYoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgbW92ZSgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgcm0oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgcmVtb3ZlKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCBub29wOiB0cnVlLCB2ZXJib3NlOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgcm1fZigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgc2FmZV91bmxpbmsoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgcm1fcigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgcm1fcmYoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgcm10cmVlKCphcmdzLCAqKm9wdGlvbnMpCiAgICAgICAgICBzdXBlcigqYXJncywgKipvcHRpb25zLCBub29wOiB0cnVlLCB2ZXJib3NlOiB0cnVlKQogICAgICAgIGVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgaW5zdGFsbCgqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY2htb2QoKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY2htb2RfUigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY2hvd24oKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgY2hvd25fUigqYXJncywgKipvcHRpb25zKQogICAgICAgICAgc3VwZXIoKmFyZ3MsICoqb3B0aW9ucywgbm9vcDogdHJ1ZSwgdmVyYm9zZTogdHJ1ZSkKICAgICAgICBlbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"ICAgICAgICBkZWYgdG91Y2goKmFyZ3MsICoqb3B0aW9ucykKICAgICAgICAgIHN1cGVyKCphcmdzLCAqKm9wdGlvbnMsIG5vb3A6IHRydWUsIHZlcmJvc2U6IHRydWUpCiAgICAgICAgZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/fileutils.rb","line":2689,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":1,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":["name","names"],"moduleNames":["FileUtils::DryRun","FileUtils::DryRun","FileUtils","FileUtils"],"module":"FileUtils::DryRun"} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRpbWUgMC40LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInRpbWUiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkV4dGVuZHMgdGhlIFRpbWUgY2xhc3Mgd2l0aCBtZXRob2RzIGZvciBwYXJzaW5nIGFuZCBjb252ZXJzaW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkV4dGVuZHMgdGhlIFRpbWUgY2xhc3Mgd2l0aCBtZXRob2RzIGZvciBwYXJzaW5nIGFuZCBjb252ZXJzaW9uIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi90aW1lLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/time-0.4.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGV0YyAxLjQuNiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXRjIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS40LjYiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBY2Nlc3MgdG8gaW5mb3JtYXRpb24gZnJvbSB0aGUgcGFzc3dkIGFuZCBncm91cCBmaWxlcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBY2Nlc3MgdG8gaW5mb3JtYXRpb24gZnJvbSB0aGUgcGFzc3dkIGFuZCBncm91cCBmaWxlcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2V0Yy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/etc-1.4.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLXdhaXQgMC40LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlvLXdhaXQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIklPI3dhaXQgYW5kIGZyaWVuZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSU8jd2FpdCBhbmQgZnJpZW5kcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2lvL3dhaXQucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-wait-0.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHpsaWIgMy4yLjMgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInpsaWIiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjIuMyIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkRlZmxhdGUvaW5mbGF0ZSwgb24gU3lzdGVtLklPLkNvbXByZXNzaW9uLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRlZmxhdGUvaW5mbGF0ZSwgb24gU3lzdGVtLklPLkNvbXByZXNzaW9uIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvemxpYi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/zlib-3.2.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW5zc2wgMy4yLjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm9wZW5zc2wiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjIuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk9wZW5TU0wgYmluZGluZ3MsIG9uIC5ORVQncyBjcnlwdG9ncmFwaHkgc3RhY2suICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3BlblNTTCBiaW5kaW5ncywgb24gLk5FVCdzIGNyeXB0b2dyYXBoeSBzdGFjayIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL29wZW5zc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9hc24xLnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wvYm4ucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9jaXBoZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9kaWdlc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvb3BlbnNzbC9wa2V5LnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wvc3NsLnJiIi5mcmVlemUsCiAgICAibGliL29wZW5zc2wveDUwOS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/openssl-3.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGFiYnJldiAwLjEuMiBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYWJicmV2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4xLjIiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9hYmJyZXYiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYWJicmV2IiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJBa2lub3JpIE1VU0hBIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMy0xMi0xNiIKICBzLmRlc2NyaXB0aW9uID0gIkNhbGN1bGF0ZXMgYSBzZXQgb2YgdW5pcXVlIGFiYnJldmlhdGlvbnMgZm9yIGEgZ2l2ZW4gc2V0IG9mIHN0cmluZ3MiLmZyZWV6ZQogIHMuZW1haWwgPSBbImtudUBpZGFlbW9ucy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2FiYnJldiIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2FsY3VsYXRlcyBhIHNldCBvZiB1bmlxdWUgYWJicmV2aWF0aW9ucyBmb3IgYSBnaXZlbiBzZXQgb2Ygc3RyaW5ncyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/abbrev-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJhc2U2NCAwLjMuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYmFzZTY0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYmFzZTY0L3JlbGVhc2VzIiwgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2Jhc2U2NCIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iYXNlNjQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1c3VrZSBFbmRvaCIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJTdXBwb3J0IGZvciBlbmNvZGluZyBhbmQgZGVjb2RpbmcgYmluYXJ5IGRhdGEgdXNpbmcgYSBCYXNlNjQgcmVwcmVzZW50YXRpb24uIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYW1lQHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2Jhc2U2NCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi40Ii5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi43Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiU3VwcG9ydCBmb3IgZW5jb2RpbmcgYW5kIGRlY29kaW5nIGJpbmFyeSBkYXRhIHVzaW5nIGEgQmFzZTY0IHJlcHJlc2VudGF0aW9uLiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/base64-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJjcnlwdCAzLjEuMjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImJjcnlwdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuMS4yMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk9wZW5CU0QgYmNyeXB0IHBhc3N3b3JkIGhhc2hpbmc7IGJjcnlwdF9leHQgaW4gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiT3BlbkJTRCBiY3J5cHQgcGFzc3dvcmQgaGFzaGluZzsgYmNyeXB0X2V4dCBpbiBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2JjcnlwdC5yYiIuZnJlZXplLAogICAgImxpYi9iY3J5cHQvZW5naW5lLnJiIi5mcmVlemUsCiAgICAibGliL2JjcnlwdC9lcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9iY3J5cHQvcGFzc3dvcmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYmNyeXB0X2V4dC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bcrypt-3.1.22.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJlbmNobWFyayAwLjUuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiYmVuY2htYXJrIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC41LjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iZW5jaG1hcmsiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvYmVuY2htYXJrIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJZdWtpaGlybyBNYXRzdW1vdG8iLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiYSBwZXJmb3JtYW5jZSBiZW5jaG1hcmtpbmcgbGlicmFyeSIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9iZW5jaG1hcmsiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuMS4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiYSBwZXJmb3JtYW5jZSBiZW5jaG1hcmtpbmcgbGlicmFyeSIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/benchmark-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJpZ2RlY2ltYWwgNC4wLjEgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImJpZ2RlY2ltYWwiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICI0LjAuMSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkFyYml0cmFyeS1wcmVjaXNpb24gZGVjaW1hbCBhcml0aG1ldGljLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkFyYml0cmFyeS1wcmVjaXNpb24gZGVjaW1hbCBhcml0aG1ldGljIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvYmlnZGVjaW1hbC5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL2phY29iaWFuLnJiIi5mcmVlemUsCiAgICAibGliL2JpZ2RlY2ltYWwvbHVkY21wLnJiIi5mcmVlemUsCiAgICAibGliL2JpZ2RlY2ltYWwvbWF0aC5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL25ld3Rvbi5yYiIuZnJlZXplLAogICAgImxpYi9iaWdkZWNpbWFsL3V0aWwucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bigdecimal-4.0.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGJ1bmRsZXIgNC4wLjIwIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJidW5kbGVyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiNC4wLjIwIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVGhlIGJlc3Qgd2F5IHRvIG1hbmFnZSBhIFJ1YnkgYXBwbGljYXRpb24ncyBnZW1zLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBiZXN0IHdheSB0byBtYW5hZ2UgYSBSdWJ5IGFwcGxpY2F0aW9uJ3MgZ2VtcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmV4ZWN1dGFibGVzID0gWyJidW5kbGUiLmZyZWV6ZSwgImJ1bmRsZXIiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9idW5kbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvYnVpbGRfbWV0YWRhdGEucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jYXBpc3RyYW5vLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2hlY2tzdW0ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jaV9kZXRlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9hZGQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvYmluc3R1YnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2FjaGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2hlY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY2xlYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvY29tbW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2NvbmZpZy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9jb25zb2xlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2RvY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9kb2N0b3IvZGlhZ25vc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvZG9jdG9yL3NzbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9leGVjLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2Z1bmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvZ2VtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2luZm8ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvaW5pdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9pbnN0YWxsLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2lzc3VlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL2xpc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvbG9jay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9vcGVuLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL291dGRhdGVkLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY2xpL3BsdWdpbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9wcmlzdGluZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS9yZW1vdmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jbGkvc2hvdy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NsaS91cGRhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jb21wYWN0X2luZGV4X2NsaWVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L2NhY2hlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvY29tcGFjdF9pbmRleF9jbGllbnQvY2FjaGVfZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2NvbXBhY3RfaW5kZXhfY2xpZW50L3VwZGF0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jb25zdGFudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9jdXJyZW50X3J1YnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kZWZpbml0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZGVwZW5kZW5jeS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2RlcGxveW1lbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kZXByZWNhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kaWdlc3QucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9lbmRwb2ludF9zcGVjaWZpY2F0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZW52LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZW52aXJvbm1lbnRfcHJlc2VydmVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmVhdHVyZV9mbGFnLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmV0Y2hlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvY29tcGFjdF9pbmRleC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZGVwZW5kZW5jeS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZG93bmxvYWRlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZldGNoZXIvZ2VtX3JlbW90ZV9mZXRjaGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZmV0Y2hlci9pbmRleC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2ZvcmNlX3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZnJpZW5kbHlfZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvZ2VtX2hlbHBlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2dlbV90YXNrcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2dlbV92ZXJzaW9uX3Byb21vdGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvaW5kZXgucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9pbmplY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2lubGluZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci9nZW1faW5zdGFsbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvaW5zdGFsbGVyL3BhcmFsbGVsX2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL2luc3RhbGxlci9zdGFuZGFsb25lLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbGF6eV9zcGVjaWZpY2F0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbG9ja2ZpbGVfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbG9ja2ZpbGVfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvbWF0Y2hfbWV0YWRhdGEucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9tYXRjaF9wbGF0Zm9ybS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21hdGNoX3JlbW90ZV9tZXRhZGF0YS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21hdGVyaWFsaXphdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL21pcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9hcGkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wbHVnaW4vYXBpL3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wbHVnaW4vZXZlbnRzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luZGV4LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9pbnN0YWxsZXIvZ2l0LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci9wYXRoLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcGx1Z2luL2luc3RhbGxlci9ydWJ5Z2Vtcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi9zb3VyY2VfbGlzdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3BsdWdpbi91bmxvYWRlZF9zb3VyY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9wcm9jZXNzX2xvY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9yZW1vdGVfc3BlY2lmaWNhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmVzb2x2ZXIvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL2NhbmRpZGF0ZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL2luY29tcGF0aWJpbGl0eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL3BhY2thZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9yZXNvbHZlci9yb290LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmVzb2x2ZXIvc3BlY19ncm91cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3Jlc29sdmVyL3N0cmF0ZWd5LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvcmV0cnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9ydWJ5X2RzbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlfdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlnZW1zX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1YnlnZW1zX2dlbV9pbnN0YWxsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9ydWJ5Z2Vtc19pbnRlZ3JhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3J1bnRpbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zYWZlX21hcnNoYWwucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zZWxmX21hbmFnZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zZXR0aW5ncy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NldHRpbmdzL3ZhbGlkYXRvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NldHVwLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc2hhcmVkX2hlbHBlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UvZ2Vtc3BlYy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9naXQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2UvZ2l0L2dpdF9wcm94eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9tZXRhZGF0YS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9wYXRoLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3BhdGgvaW5zdGFsbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3J1YnlnZW1zLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvc291cmNlL3J1YnlnZW1zL3JlbW90ZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZS9ydWJ5Z2Vtc19hZ2dyZWdhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zb3VyY2VfbGlzdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3NvdXJjZV9tYXAucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci9zcGVjX3NldC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3N0dWJfc3BlY2lmaWNhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VpLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdWkvcmdfcHJveHkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci91aS9zaGVsbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VpL3NpbGVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3VyaV9jcmVkZW50aWFsc19maWx0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci91cmlfbm9ybWFsaXplci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC90aW1lZF9zdGFjay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9jb25uZWN0aW9uX3Bvb2wvbGliL2Nvbm5lY3Rpb25fcG9vbC92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL2Nvbm5lY3Rpb25fcG9vbC9saWIvY29ubmVjdGlvbl9wb29sL3dyYXBwZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvZmlsZXV0aWxzL2xpYi9maWxldXRpbHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvbmV0LWh0dHAtcGVyc2lzdGVudC9saWIvbmV0L2h0dHAvcGVyc2lzdGVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9uZXQtaHR0cC1wZXJzaXN0ZW50L2xpYi9uZXQvaHR0cC9wZXJzaXN0ZW50L2Nvbm5lY3Rpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvbmV0LWh0dHAtcGVyc2lzdGVudC9saWIvbmV0L2h0dHAvcGVyc2lzdGVudC9wb29sLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL25ldC1odHRwLXBlcnNpc3RlbnQvbGliL25ldC9odHRwL3BlcnNpc3RlbnQvdGltZWRfc3RhY2tfbXVsdGkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3B1Yl9ncnViL2xpYi9wdWJfZ3J1Yi9hc3NpZ25tZW50LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3B1Yl9ncnViL2xpYi9wdWJfZ3J1Yi9iYXNpY19wYWNrYWdlX3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvZmFpbHVyZV93cml0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL2luY29tcGF0aWJpbGl0eS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcGFja2FnZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcGFydGlhbF9zb2x1dGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvcnVieWdlbXMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3NvbHZlX2ZhaWx1cmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3N0YXRpY19wYWNrYWdlX3NvdXJjZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvc3RyYXRlZ3kucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3Rlcm0ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb25fY29uc3RyYWludC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvdmVyc2lvbl9yYW5nZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci9wdWJfZ3J1Yi9saWIvcHViX2dydWIvdmVyc2lvbl9zb2x2ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvcHViX2dydWIvbGliL3B1Yl9ncnViL3ZlcnNpb25fdW5pb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3Ivc2VjdXJlcmFuZG9tL2xpYi9zZWN1cmVyYW5kb20ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2FjdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9hY3Rpb25zL2NyZWF0ZV9maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9jcmVhdGVfbGluay5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2FjdGlvbnMvZGlyZWN0b3J5LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9lbXB0eV9kaXJlY3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9hY3Rpb25zL2ZpbGVfbWFuaXB1bGF0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYWN0aW9ucy9pbmplY3RfaW50b19maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2NvbW1hbmQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9jb3JlX2V4dC9oYXNoX3dpdGhfaW5kaWZmZXJlbnRfYWNjZXNzLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9ncm91cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2ludm9jYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9saW5lX2VkaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL2xpbmVfZWRpdG9yL2Jhc2ljLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvbGluZV9lZGl0b3IvcmVhZGxpbmUucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9uZXN0ZWRfY29udGV4dC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci9hcmd1bWVudC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3BhcnNlci9hcmd1bWVudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9wYXJzZXIvb3B0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3IvcGFyc2VyL29wdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9yYWtlX2NvbXBhdC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3J1bm5lci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3Ivc2hlbGwvYmFzaWMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9zaGVsbC9jb2xvci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL2NvbHVtbl9wcmludGVyLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3Rob3IvbGliL3Rob3Ivc2hlbGwvaHRtbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL3RhYmxlX3ByaW50ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci9zaGVsbC90ZXJtaW5hbC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3NoZWxsL3dyYXBwZWRfcHJpbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci90aG9yL2xpYi90aG9yL3V0aWwucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdGhvci9saWIvdGhvci92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2NvbW1vbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9maWxlLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2Z0cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9nZW5lcmljLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yL3VyaS9saWIvdXJpL2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvaHR0cHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvbGRhcC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9sZGFwcy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS9tYWlsdG8ucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvcmZjMjM5Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvcmZjMzk4Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3IvdXJpL2xpYi91cmkvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS93cy5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvci91cmkvbGliL3VyaS93c3MucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9maWxldXRpbHMucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9uZXRfaHR0cC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3BlcnNpc3RlbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF9wdWJfZ3J1Yi5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3NlY3VyZXJhbmRvbS5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3ZlbmRvcmVkX3Rob3IucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF90aW1lb3V0LnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmVuZG9yZWRfdHNvcnQucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZW5kb3JlZF91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvYnVuZGxlci92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL2J1bmRsZXIvdmxhZC5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3dvcmtlci5yYiIuZnJlZXplLAogICAgImxpYi9idW5kbGVyL3lhbWxfc2VyaWFsaXplci5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/bundler-4.0.20.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGNnaSAwLjUuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiY2dpIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC41LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJDR0kuZXNjYXBlIGFuZCBmcmllbmRzIC0gUnVieSA0LjAncyBjZ2kvZXNjYXBlLCBub3QgdGhlIGZ1bGwgQ0dJIGNsYXNzLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkNHSS5lc2NhcGUgYW5kIGZyaWVuZHMgLSBSdWJ5IDQuMCdzIGNnaS9lc2NhcGUsIG5vdCB0aGUgZnVsbCBDR0kgY2xhc3MiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9jZ2kucmIiLmZyZWV6ZSwKICAgICJsaWIvY2dpL2VzY2FwZS5yYiIuZnJlZXplLAogICAgImxpYi9jZ2kvdXRpbC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/cgi-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGNzdiAzLjMuNSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiY3N2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4zLjUiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvY3N2L3JlbGVhc2VzL3RhZy92My4zLjUiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIkphbWVzIEVkd2FyZCBHcmF5IElJIi5mcmVlemUsICJLb3VoZWkgU3V0b3UiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlRoZSBDU1YgbGlicmFyeSBwcm92aWRlcyBhIGNvbXBsZXRlIGludGVyZmFjZSB0byBDU1YgZmlsZXMgYW5kIGRhdGEuIEl0IG9mZmVycyB0b29scyB0byBlbmFibGUgeW91IHRvIHJlYWQgYW5kIHdyaXRlIHRvIGFuZCBmcm9tIFN0cmluZ3Mgb3IgSU8gb2JqZWN0cywgYXMgbmVlZGVkLiIuZnJlZXplCiAgcy5lbWFpbCA9IFtuaWwsICJrb3VAY296bWl4bmcub3JnIi5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvY3N2L3JlY2lwZXMvZmlsdGVyaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9nZW5lcmF0aW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9wYXJzaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9yZWNpcGVzLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvY3N2L3JlY2lwZXMvZmlsdGVyaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9nZW5lcmF0aW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9wYXJzaW5nLnJkb2MiLmZyZWV6ZSwgImRvYy9jc3YvcmVjaXBlcy9yZWNpcGVzLnJkb2MiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2NzdiIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjciLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJDU1YgUmVhZGluZyBhbmQgV3JpdGluZyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/csv-3.3.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRpZF95b3VfbWVhbiAyLjAuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZGlkX3lvdV9tZWFuIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4wLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJEaWQgeW91IG1lYW4/IGV4cGVyaWVuY2UuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiRGlkIHlvdSBtZWFuPyBleHBlcmllbmNlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9kaWRfeW91X21lYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL2NvcmVfZXh0L25hbWVfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL2V4cGVyaW1lbnRhbC5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vZm9ybWF0dGVyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9mb3JtYXR0ZXJzL3BsYWluX2Zvcm1hdHRlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vZm9ybWF0dGVycy92ZXJib3NlX2Zvcm1hdHRlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vamFyb193aW5rbGVyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9sZXZlbnNodGVpbi5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlcnMva2V5X2Vycm9yX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL21ldGhvZF9uYW1lX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL25hbWVfZXJyb3JfY2hlY2tlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL25hbWVfZXJyb3JfY2hlY2tlcnMvY2xhc3NfbmFtZV9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9zcGVsbF9jaGVja2Vycy9uYW1lX2Vycm9yX2NoZWNrZXJzL3ZhcmlhYmxlX25hbWVfY2hlY2tlci5yYiIuZnJlZXplLAogICAgImxpYi9kaWRfeW91X21lYW4vc3BlbGxfY2hlY2tlcnMvbnVsbF9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi9zcGVsbF9jaGVja2Vycy9wYXR0ZXJuX2tleV9uYW1lX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3NwZWxsX2NoZWNrZXJzL3JlcXVpcmVfcGF0aF9jaGVja2VyLnJiIi5mcmVlemUsCiAgICAibGliL2RpZF95b3VfbWVhbi90cmVlX3NwZWxsX2NoZWNrZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3ZlcmJvc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlkX3lvdV9tZWFuL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/did_you_mean-2.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRpZ2VzdCAzLjIuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZGlnZXN0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4yLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJNZXNzYWdlIGRpZ2VzdCBsaWJyYXJpZXMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWVzc2FnZSBkaWdlc3QgbGlicmFyaWVzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZGlnZXN0LnJiIi5mcmVlemUsCiAgICAibGliL2RpZ2VzdC9idWJibGViYWJibGUucmIiLmZyZWV6ZSwKICAgICJsaWIvZGlnZXN0L21kNS5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3Qvc2hhMS5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3Qvc2hhMi5yYiIuZnJlZXplLAogICAgImxpYi9kaWdlc3QvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/digest-3.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGRyYiAyLjIuMyBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZHJiIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMi4yLjMiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiL3JlbGVhc2VzL3RhZy92Mi4yLjMiLCAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2RyYiIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiTWFzYXRvc2hpIFNFS0kiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIkRpc3RyaWJ1dGVkIG9iamVjdCBzeXN0ZW0gZm9yIFJ1YnkiLmZyZWV6ZQogIHMuZW1haWwgPSBbInNla2lAcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZHJiIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjcuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuNyIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkRpc3RyaWJ1dGVkIG9iamVjdCBzeXN0ZW0gZm9yIFJ1YnkiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/drb-2.2.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVuZ2xpc2ggMC44LjEgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImVuZ2xpc2giLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlJlYWRhYmxlIGFsaWFzZXMgZm9yIHRoZSBzcGVjaWFsIHZhcmlhYmxlcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJSZWFkYWJsZSBhbGlhc2VzIGZvciB0aGUgc3BlY2lhbCB2YXJpYWJsZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL0VuZ2xpc2gucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/english-0.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVyYiA2LjAuNyBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXJiIi5mcmVlemUKICBzLnZlcnNpb24gPSAiNi4wLjciCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBbiBlYXN5LXRvLXVzZSBidXQgcG93ZXJmdWwgdGVtcGxhdGluZyBzeXN0ZW0uICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQW4gZWFzeS10by11c2UgYnV0IHBvd2VyZnVsIHRlbXBsYXRpbmcgc3lzdGVtIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZXJiLnJiIi5mcmVlemUsCiAgICAibGliL2VyYi9jb21waWxlci5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvZGVmX21ldGhvZC5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvdXRpbC5yYiIuZnJlZXplLAogICAgImxpYi9lcmIvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/erb-6.0.7.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGVycm9yX2hpZ2hsaWdodCAwLjcuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZXJyb3JfaGlnaGxpZ2h0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC43LjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgZXJyb3JfaGlnaGxpZ2h0IEFQSTsgc3BvdCBhbHdheXMgYW5zd2VycyBuaWwgaGVyZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJUaGUgZXJyb3JfaGlnaGxpZ2h0IEFQSTsgc3BvdCBhbHdheXMgYW5zd2VycyBuaWwgaGVyZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvZXJyb3JfaGlnaGxpZ2h0LnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC9iYXNlLnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC9jb3JlX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9lcnJvcl9oaWdobGlnaHQvZm9ybWF0dGVyLnJiIi5mcmVlemUsCiAgICAibGliL2Vycm9yX2hpZ2hsaWdodC92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/error_highlight-0.7.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZjbnRsIDEuMy4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJmY250bCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMy4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQ29uc3RhbnRzIGZvciBmY250bCgyKSBhbmQgb3BlbigyKS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJDb25zdGFudHMgZm9yIGZjbnRsKDIpIGFuZCBvcGVuKDIpIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZmNudGwucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fcntl-1.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZmaSAxLjE3LjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImZmaSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMTcuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlRoZSBmZmkgZ2VtJ3MgQVBJLCBvbiBGaWRkbGUuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhlIGZmaSBnZW0ncyBBUEksIG9uIEZpZGRsZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL2ZmaS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvYWJzdHJhY3RfbWVtb3J5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9hdXRvcG9pbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9jYWxsYmFjay5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvY29tcGF0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9kYXRhX2NvbnZlcnRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvZHluYW1pY19saWJyYXJ5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9lbnVtLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9lcnJuby5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvZmZpLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9mdW5jdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaW8ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L2R5bmFtaWNfbGlicmFyeS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaXJvbnJ1YnkvZnVuY3Rpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L2xhc3RfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL2lyb25ydWJ5L21lbW9yeS5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvaXJvbnJ1Ynkvc3RydWN0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9pcm9ucnVieS9zdHJ1Y3RfbGF5b3V0LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9pcm9ucnVieS90eXBlLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9saWJyYXJ5LnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9saWJyYXJ5X3BhdGgucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL21hbmFnZWRzdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL21lbW9yeXBvaW50ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3BsYXRmb3JtLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9wb2ludGVyLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS9zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9ieV9yZWZlcmVuY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9sYXlvdXQucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3N0cnVjdF9sYXlvdXRfYnVpbGRlci5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvdG9vbHMvY29uc3RfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90b29scy9nZW5lcmF0b3IucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3Rvb2xzL2dlbmVyYXRvcl90YXNrLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90b29scy9zdHJ1Y3RfZ2VuZXJhdG9yLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS90eXBlcy5yYiIuZnJlZXplLAogICAgImxpYi9mZmkvdW5pb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvZmZpL3ZhcmlhZGljLnJiIi5mcmVlemUsCiAgICAibGliL2ZmaS92ZXJzaW9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ffi-1.17.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpZGRsZSAxLjEuOCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiZmlkZGxlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4xLjgiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJDYWxsaW5nIHNoYXJlZC1saWJyYXJ5IGZ1bmN0aW9ucywgb24gTmF0aXZlTGlicmFyeSBhbmQgY2FsbGkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2FsbGluZyBzaGFyZWQtbGlicmFyeSBmdW5jdGlvbnMsIG9uIE5hdGl2ZUxpYnJhcnkgYW5kIGNhbGxpIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvZmlkZGxlLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9jbG9zdXJlLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9jcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9mdW5jdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9maWRkbGUvaW1wb3J0LnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9wYWNrLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS9zdHJ1Y3QucmIiLmZyZWV6ZSwKICAgICJsaWIvZmlkZGxlL3R5cGVzLnJiIi5mcmVlemUsCiAgICAibGliL2ZpZGRsZS92YWx1ZS5yYiIuZnJlZXplLAogICAgImxpYi9maWRkbGUvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/fiddle-1.1.8.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZpbmQgMC4yLjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImZpbmQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlRyYXZlcnNlIGEgZmlsZSB0cmVlLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRyYXZlcnNlIGEgZmlsZSB0cmVlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9maW5kLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/find-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGZvcndhcmRhYmxlIDEuNC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJmb3J3YXJkYWJsZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuNC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUHJvdmlkZXMgZGVsZWdhdGlvbiBvZiBzcGVjaWZpZWQgbWV0aG9kcyB0byBhIGRlc2lnbmF0ZWQgb2JqZWN0LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlByb3ZpZGVzIGRlbGVnYXRpb24gb2Ygc3BlY2lmaWVkIG1ldGhvZHMgdG8gYSBkZXNpZ25hdGVkIG9iamVjdCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvZm9yd2FyZGFibGUucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/forwardable-1.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGdldG9wdGxvbmcgMC4yLjEgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImdldG9wdGxvbmciLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2dldG9wdGxvbmciLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvZ2V0b3B0bG9uZyIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiWXVraWhpcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5kYXRlID0gIjIwMjMtMTEtMDciCiAgcy5kZXNjcmlwdGlvbiA9ICJHZXRvcHRMb25nIGZvciBSdWJ5Ii5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L2dldG9wdGxvbmciLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjUuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJHZXRvcHRMb25nIGZvciBSdWJ5Ii5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/getoptlong-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlvLW5vbmJsb2NrIDAuMy4yIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJpby1ub25ibG9jayIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4yIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSU8jbm9uYmxvY2suICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSU8jbm9uYmxvY2siLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9pby9ub25ibG9jay5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/io-nonblock-0.3.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlwYWRkciAxLjIuOCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAiaXBhZGRyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4yLjgiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJBIGNsYXNzIHRvIG1hbmlwdWxhdGUgYW4gSVAgYWRkcmVzcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBIGNsYXNzIHRvIG1hbmlwdWxhdGUgYW4gSVAgYWRkcmVzcyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvaXBhZGRyLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ipaddr-1.2.8.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGlyYiAxLjE4LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gImlyYiIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuMTguMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkludGVyYWN0aXZlIFJ1YnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiSW50ZXJhY3RpdmUgUnVieSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5leGVjdXRhYmxlcyA9IFsiaXJiIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvaXJiLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jbWQvbm9wLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb2xvci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29sb3JfcHJpbnRlci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9iYWNrdHJhY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9icmVhay5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jYXRjaC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9jaHdzLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2NvbnRleHQucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvY29udGludWUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvY29weS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9kZWJ1Zy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9kZWxldGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvZGlzYWJsZV9pcmIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvZWRpdC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9leGl0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2ZpbmlzaC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9mb3JjZV9leGl0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2hlbHAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvaGlzdG9yeS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9pbmZvLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL2ludGVybmFsX2hlbHBlcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvaXJiX2luZm8ucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvbG9hZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9scy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvY29tbWFuZC9tZWFzdXJlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL25leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvcHVzaHdzLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3Nob3dfZG9jLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3Nob3dfc291cmNlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3N0ZXAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2NvbW1hbmQvc3ViaXJiLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21tYW5kL3doZXJlYW1pLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb21wbGV0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9jb250ZXh0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9kZWJ1Zy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvZGVidWcvdWkucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2RlZmF1bHRfY29tbWFuZHMucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2Vhc3Rlci1lZ2cucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9jaGFuZ2Utd3MucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9ldmFsX2hpc3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9sb2FkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC9tdWx0aS1pcmIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC90cmFjZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2V4dC91c2UtbG9hZGVyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9leHQvd29ya3NwYWNlcy5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvZnJhbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHAucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHBlcl9tZXRob2QucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2hlbHBlcl9tZXRob2QvYmFzZS5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvaGVscGVyX21ldGhvZC9jb25mLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9oaXN0b3J5LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9pbml0LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9pbnB1dC1tZXRob2QucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2luc3BlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvbGMvZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL2xjL2phL2Vycm9yLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9sb2NhbGUucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL25lc3RpbmdfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9ub3RpZmllci5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvb3V0cHV0LW1ldGhvZC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvcGFnZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL3J1YnktbGV4LnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9zb3VyY2VfZmluZGVyLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi9zdGFydHVwX21lc3NhZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvaXJiL3N0YXRlbWVudC5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9pcmIvd29ya3NwYWNlLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi93cy1mb3ItY2FzZS0yLnJiIi5mcmVlemUsCiAgICAibGliL2lyYi94bXAucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/irb-1.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IGxvZ2dlciAxLjcuMCBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibG9nZ2VyIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS43LjAiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbG9nZ2VyL3JlbGVhc2VzIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJOYW90b3NoaSBTZW8iLmZyZWV6ZSwgIlNISUJBVEEgSGlyb3NoaSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTAzLTI3IgogIHMuZGVzY3JpcHRpb24gPSAiUHJvdmlkZXMgYSBzaW1wbGUgbG9nZ2luZyB1dGlsaXR5IGZvciBvdXRwdXR0aW5nIG1lc3NhZ2VzLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsic29ub3RzQGdtYWlsLmNvbSIuZnJlZXplLCAiaHNidEBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9sb2dnZXIiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuNS4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4xMSIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlByb3ZpZGVzIGEgc2ltcGxlIGxvZ2dpbmcgdXRpbGl0eSBmb3Igb3V0cHV0dGluZyBtZXNzYWdlcy4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/logger-1.7.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1hdHJpeCAwLjQuMyBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibWF0cml4Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC40LjMiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJNYXJjLUFuZHJlIExhZm9ydHVuZSIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjIwMjUtMDYtMTgiCiAgcy5kZXNjcmlwdGlvbiA9ICJBbiBpbXBsZW1lbnRhdGlvbiBvZiBNYXRyaXggYW5kIFZlY3RvciBjbGFzc2VzLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnVieS1jb3JlQG1hcmMtYW5kcmUuY2EiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L21hdHJpeCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQW4gaW1wbGVtZW50YXRpb24gb2YgTWF0cml4IGFuZCBWZWN0b3IgY2xhc3Nlcy4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/matrix-0.4.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1pbml0ZXN0IDYuMC4wIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJtaW5pdGVzdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjYuMC4wIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiYnVnX3RyYWNrZXJfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0L2lzc3VlcyIsICJjaGFuZ2Vsb2dfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0L2Jsb2IvbWFzdGVyL0hpc3RvcnkucmRvYyIsICJob21lcGFnZV91cmkiID0+ICJodHRwczovL21pbml0ZS5zdC8iLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL21pbml0ZXN0L21pbml0ZXN0IiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJSeWFuIERhdmlzIi5mcmVlemVdCiAgcy5jZXJ0X2NoYWluID0gWyItLS0tLUJFR0lOIENFUlRJRklDQVRFLS0tLS1cbk1JSURQakNDQWlhZ0F3SUJBZ0lCQ1RBTkJna3Foa2lHOXcwQkFRc0ZBREJGTVJNd0VRWURWUVFEREFweWVXRnVcblpDMXlkV0o1TVJrd0Z3WUtDWkltaVpQeUxHUUJHUllKZW1WdWMzQnBaR1Z5TVJNd0VRWUtDWkltaVpQeUxHUUJcbkdSWURZMjl0TUI0WERUSTFNREV3TmpJek1qY3dNVm9YRFRJMk1ERXdOakl6TWpjd01Wb3dSVEVUTUJFR0ExVUVcbkF3d0tjbmxoYm1RdGNuVmllVEVaTUJjR0NnbVNKb21UOGl4a0FSa1dDWHBsYm5Od2FXUmxjakVUTUJFR0NnbVNcbkpvbVQ4aXhrQVJrV0EyTnZiVENDQVNJd0RRWUpLb1pJaHZjTkFRRUJCUUFEZ2dFUEFEQ0NBUW9DZ2dFQkFMZGFcbmI5RENnSys2MjdnUEprQjZYZmpaMWl0b09RdnBxSDFFWFNjU2FiYTkvUzJWRjIyVllRYlhVMXhRWEwvV3pDa3hcbnRhQ1BhTG1mWUlhRmNISENTWTRoWURKaWpSUWtMeFBlQjN4Yk9memZMb0JEYmp2eDVKeGdKeFVqbUdhN3hoY1Rcbm9Pdmp0dDVQOCtHU0s5ekx6eFFQMGdWTFMvRDBGbW9FNDRYdURyM2lRa1ZTMnVqVTV6Wkw4NG1NTnFOQjF6bmhcbkdpYWRNOUdIUmFEaWF4dVgwY0lVQmoxOVQwMW1WRTJpeW1mOUk2YkVzaWF5Sy9uNlF1anR5Q2JUV3NBUzlScXRcbnFodFY3SEp4Tkt1UGovSkZIMEQyY3N3dnp6bkUvYTVGT1lPNjhnK1lDdUZpNUw4d1p1dU04enpkd2pyV0hxU1ZcbmdCRWZvVEVHcjdaaWk3MmN4K3NDQXdFQUFhTTVNRGN3Q1FZRFZSMFRCQUl3QURBTEJnTlZIUThFQkFNQ0JMQXdcbkhRWURWUjBPQkJZRUZFZkZlOW1kL3IvdGovV213cHkrTUk4ZDlrL2hNQTBHQ1NxR1NJYjNEUUVCQ3dVQUE0SUJcbkFRQUMwV1FKY1BPV1BGd2tvamh6d2VpbFJWalRKMTlVaUxoaUJUdzNDMXdKTzNMVmRCa1dEbW5uaEFtS3VYNERcbnI3dmpRdkVTbEFCR0lQZHV0STFZbDdtckhRelRrZkxmWHZOTjZNVDBuTENoUHlJWWF1VDZTWlp4dWJ3SnJVZkFcbjdSMGMyQ0pUSWJvWjBYYUdwTHNYcUhFRjFjMjlIN1RWMVF2VnVxS0FOMm1Damg0TjgyUVZuK1pLdHlzMjhBd1RcbjZHZlFYMmZxTG9pNEtTYzd4SXpIS2FOenF4ZU9JQ21Kb2ZrOXc1VloyclJONnllczhqdkZZd3o5SFI0MXdkajhcbmJ3ZmludjdZcDVmQTZBeXN1WkxoQ3lreWZEdVpWUnJVcDBWYjY4WUNLc0xqSmx5L1RoZWFrK2V1TlR4dkhzQitcbmFsOW9TZ1BQSElDTUVYNjVxdkx5d2l0eFxuLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLVxuIi5mcmVlemVdCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJtaW5pdGVzdCBwcm92aWRlcyBhIGNvbXBsZXRlIHN1aXRlIG9mIHRlc3RpbmcgZmFjaWxpdGllcyBzdXBwb3J0aW5nXG5UREQsIEJERCwgYW5kIGJlbmNobWFya2luZy5cblxuICAgIFwiSSBoYWQgYSBjbGFzcyB3aXRoIEppbSBXZWlyaWNoIG9uIHRlc3RpbmcgbGFzdCB3ZWVrIGFuZCB3ZSB3ZXJlXG4gICAgIGFsbG93ZWQgdG8gY2hvb3NlIG91ciB0ZXN0aW5nIGZyYW1ld29ya3MuIEtpcmsgSGFpbmVzIGFuZCBJIHdlcmVcbiAgICAgcGFpcmVkIHVwIGFuZCB3ZSBjcmFja2VkIG9wZW4gdGhlIGNvZGUgZm9yIGEgZmV3IHRlc3RcbiAgICAgZnJhbWV3b3Jrcy4uLlxuXG4gICAgIEkgTVVTVCBzYXkgdGhhdCBtaW5pdGVzdCBpcyAqdmVyeSogcmVhZGFibGUgLyB1bmRlcnN0YW5kYWJsZVxuICAgICBjb21wYXJlZCB0byB0aGUgJ290aGVyIHR3bycgb3B0aW9ucyB3ZSBsb29rZWQgYXQuIE5pY2VseSBkb25lIGFuZFxuICAgICB0aGFuayB5b3UgZm9yIGhlbHBpbmcgdXMga2VlcCBvdXIgbWVudGFsIHNhbml0eS5cIlxuXG4gICAgLS0gV2F5bmUgRS4gU2VndWluXG5cbm1pbml0ZXN0L3Rlc3QgaXMgYSBzbWFsbCBhbmQgaW5jcmVkaWJseSBmYXN0IHVuaXQgdGVzdGluZyBmcmFtZXdvcmsuXG5JdCBwcm92aWRlcyBhIHJpY2ggc2V0IG9mIGFzc2VydGlvbnMgdG8gbWFrZSB5b3VyIHRlc3RzIGNsZWFuIGFuZFxucmVhZGFibGUuXG5cbm1pbml0ZXN0L3NwZWMgaXMgYSBmdW5jdGlvbmFsbHkgY29tcGxldGUgc3BlYyBlbmdpbmUuIEl0IGhvb2tzIG9udG9cbm1pbml0ZXN0L3Rlc3QgYW5kIHNlYW1sZXNzbHkgYnJpZGdlcyB0ZXN0IGFzc2VydGlvbnMgb3ZlciB0byBzcGVjXG5leHBlY3RhdGlvbnMuXG5cbm1pbml0ZXN0L2JlbmNobWFyayBpcyBhbiBhd2Vzb21lIHdheSB0byBhc3NlcnQgdGhlIHBlcmZvcm1hbmNlIG9mIHlvdXJcbmFsZ29yaXRobXMgaW4gYSByZXBlYXRhYmxlIG1hbm5lci4gTm93IHlvdSBjYW4gYXNzZXJ0IHRoYXQgeW91ciBuZXdiXG5jby13b3JrZXIgZG9lc24ndCByZXBsYWNlIHlvdXIgbGluZWFyIGFsZ29yaXRobSB3aXRoIGFuIGV4cG9uZW50aWFsXG5vbmUhXG5cbm1pbml0ZXN0L3ByaWRlIHNob3dzIHByaWRlIGluIHRlc3RpbmcgYW5kIGFkZHMgY29sb3JpbmcgdG8geW91ciB0ZXN0XG5vdXRwdXQuIEkgZ3Vlc3MgaXQgaXMgYW4gZXhhbXBsZSBvZiBob3cgdG8gd3JpdGUgSU8gcGlwZXMgdG9vLiA6UFxuXG5taW5pdGVzdC90ZXN0IGlzIG1lYW50IHRvIGhhdmUgYSBjbGVhbiBpbXBsZW1lbnRhdGlvbiBmb3IgbGFuZ3VhZ2VcbmltcGxlbWVudG9ycyB0aGF0IG5lZWQgYSBtaW5pbWFsIHNldCBvZiBtZXRob2RzIHRvIGJvb3RzdHJhcCBhIHdvcmtpbmdcbnRlc3Qgc3VpdGUuIEZvciBleGFtcGxlLCB0aGVyZSBpcyBubyBtYWdpYyBpbnZvbHZlZCBmb3IgdGVzdC1jYXNlXG5kaXNjb3ZlcnkuXG5cbiAgICBcIkFnYWluLCBJIGNhbid0IHByYWlzZSBlbm91Z2ggdGhlIGlkZWEgb2YgYSB0ZXN0aW5nL3NwZWNpbmdcbiAgICAgZnJhbWV3b3JrIHRoYXQgSSBjYW4gYWN0dWFsbHkgcmVhZCBpbiBmdWxsIGluIG9uZSBzaXR0aW5nIVwiXG5cbiAgICAtLSBQaW90ciBTem90a293c2tpXG5cbkNvbXBhcmluZyB0byByc3BlYzpcblxuICAgIHJzcGVjIGlzIGEgdGVzdGluZyBEU0wuIG1pbml0ZXN0IGlzIHJ1YnkuXG5cbiAgICAtLSBBZGFtIEhhd2tpbnMsIFwiQm93IEJlZm9yZSBNaW5pVGVzdFwiXG5cbm1pbml0ZXN0IGRvZXNuJ3QgcmVpbnZlbnQgYW55dGhpbmcgdGhhdCBydWJ5IGFscmVhZHkgcHJvdmlkZXMsIGxpa2U6XG5jbGFzc2VzLCBtb2R1bGVzLCBpbmhlcml0YW5jZSwgbWV0aG9kcy4gVGhpcyBtZWFucyB5b3Ugb25seSBoYXZlIHRvXG5sZWFybiBydWJ5IHRvIHVzZSBtaW5pdGVzdCBhbmQgYWxsIG9mIHlvdXIgcmVndWxhciBPTyBwcmFjdGljZXMgbGlrZVxuZXh0cmFjdC1tZXRob2QgcmVmYWN0b3JpbmdzIHN0aWxsIGFwcGx5LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnlhbmQtcnVieUB6ZW5zcGlkZXIuY29tIi5mcmVlemVdCiAgcy5leGVjdXRhYmxlcyA9IFsibWluaXRlc3QiLmZyZWV6ZV0KICBzLmV4dHJhX3Jkb2NfZmlsZXMgPSBbIkhpc3RvcnkucmRvYyIuZnJlZXplLCAiTWFuaWZlc3QudHh0Ii5mcmVlemUsICJSRUFETUUucmRvYyIuZnJlZXplXQogIHMuZmlsZXMgPSBbIkhpc3RvcnkucmRvYyIuZnJlZXplLCAiTWFuaWZlc3QudHh0Ii5mcmVlemUsICJSRUFETUUucmRvYyIuZnJlZXplLCAiYmluL21pbml0ZXN0Ii5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL21pbml0ZS5zdC8iLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIk1JVCIuZnJlZXplXQogIHMucmRvY19vcHRpb25zID0gWyItLW1haW4iLmZyZWV6ZSwgIlJFQURNRS5yZG9jIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNy4yIi5mcmVlemUKICBzLnN1bW1hcnkgPSAibWluaXRlc3QgcHJvdmlkZXMgYSBjb21wbGV0ZSBzdWl0ZSBvZiB0ZXN0aW5nIGZhY2lsaXRpZXMgc3VwcG9ydGluZyBUREQsIEJERCwgYW5kIGJlbmNobWFya2luZyIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxwcmlzbT4uZnJlZXplLCBbIj49IDEuNSIuZnJlZXplXSkKICBzLmFkZF9kZXZlbG9wbWVudF9kZXBlbmRlbmN5KCVxPHJkb2M+LmZyZWV6ZSwgWyI+PSA0LjAiLmZyZWV6ZSwgIjwgNyIuZnJlZXplXSkKICBzLmFkZF9kZXZlbG9wbWVudF9kZXBlbmRlbmN5KCVxPHNpbXBsZWNvdj4uZnJlZXplLCBbIn4+IDAuMjEiLmZyZWV6ZV0pCiAgcy5hZGRfZGV2ZWxvcG1lbnRfZGVwZW5kZW5jeSglcTxob2U+LmZyZWV6ZSwgWyJ+PiA0LjMiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/minitest-6.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG1zZ3BhY2sgMS44LjUgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm1zZ3BhY2siLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIxLjguNSIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk1lc3NhZ2VQYWNrIHNlcmlhbGl6YXRpb247IHRoZSBDIGV4dGVuc2lvbiBwb3J0ZWQgdG8gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWVzc2FnZVBhY2sgc2VyaWFsaXphdGlvbjsgdGhlIEMgZXh0ZW5zaW9uIHBvcnRlZCB0byBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL21zZ3BhY2sucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9iaWdpbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9idWZmZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9jb3JlX2V4dC5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL2ZhY3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvbXNncGFjay9tc2dwYWNrLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svcGFja2VyLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svc3ltYm9sLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svdGltZS5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL3RpbWVzdGFtcC5yYiIuZnJlZXplLAogICAgImxpYi9tc2dwYWNrL3VucGFja2VyLnJiIi5mcmVlemUsCiAgICAibGliL21zZ3BhY2svdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/msgpack-1.8.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG11dGV4X20gMC4zLjAgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm11dGV4X20iLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjMuMCIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImJ1Z190cmFja2VyX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L211dGV4X20vaXNzdWVzIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L211dGV4X20iIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIktlaWp1IElTSElUU1VLQSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI0LTExLTIwIgogIHMuZGVzY3JpcHRpb24gPSAiTWl4aW4gdG8gZXh0ZW5kIG9iamVjdHMgdG8gYmUgaGFuZGxlZCBsaWtlIGEgTXV0ZXguIi5mcmVlemUKICBzLmVtYWlsID0gWyJrZWlqdUBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9tdXRleF9tIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWl4aW4gdG8gZXh0ZW5kIG9iamVjdHMgdG8gYmUgaGFuZGxlZCBsaWtlIGEgTXV0ZXguIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/mutex_m-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1mdHAgMC4zLjkgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1mdHAiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjMuOSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1mdHAiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LWZ0cCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiU2h1Z28gTWFlZGEiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlN1cHBvcnQgZm9yIHRoZSBGaWxlIFRyYW5zZmVyIFByb3RvY29sLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsic2h1Z29AcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LWZ0cCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi42LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTdXBwb3J0IGZvciB0aGUgRmlsZSBUcmFuc2ZlciBQcm90b2NvbC4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8bmV0LXByb3RvY29sPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8dGltZT4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-ftp-0.3.9.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1odHRwIDAuOS4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuZXQtaHR0cCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuOS4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiSFRUUCBjbGllbnQgYXBpIGZvciBSdWJ5LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkhUVFAgY2xpZW50IGFwaSBmb3IgUnVieSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvbmV0L2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvbmV0L2h0dHBzLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL2V4Y2VwdGlvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvbmV0L2h0dHAvZ2VuZXJpY19yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL2hlYWRlci5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9wcm94eV9kZWx0YS5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3JlcXVlc3RzLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL25ldC9odHRwL3Jlc3BvbnNlcy5yYiIuZnJlZXplLAogICAgImxpYi9uZXQvaHR0cC9zdGF0dXMucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/net-http-0.9.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1pbWFwIDAuNi40LjEgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1pbWFwIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC42LjQuMSIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImNoYW5nZWxvZ191cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcC9yZWxlYXNlcyIsICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiU2h1Z28gTWFlZGEiLmZyZWV6ZSwgIm5pY2hvbGFzIGEuIGV2YW5zIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlJ1YnkgY2xpZW50IGFwaSBmb3IgSW50ZXJuZXQgTWVzc2FnZSBBY2Nlc3MgUHJvdG9jb2wiLmZyZWV6ZQogIHMuZW1haWwgPSBbInNodWdvQHJ1YnktbGFuZy5vcmciLmZyZWV6ZSwgIm5pY2tAcnViaW5pY2suZGV2Ii5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9uZXQtaW1hcCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjEzIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiUnVieSBjbGllbnQgYXBpIGZvciBJbnRlcm5ldCBNZXNzYWdlIEFjY2VzcyBQcm90b2NvbCIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxuZXQtcHJvdG9jb2w+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxkYXRlPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-imap-0.6.4.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1wb3AgMC4xLjIgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm5ldC1wb3AiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjEuMiIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1wb3AiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXBvcCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiWXVraWhpcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMi0wOS0yOCIKICBzLmRlc2NyaXB0aW9uID0gIlJ1YnkgY2xpZW50IGxpYnJhcnkgZm9yIFBPUDMuIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1wb3AiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjQuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJSdWJ5IGNsaWVudCBsaWJyYXJ5IGZvciBQT1AzLiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxuZXQtcHJvdG9jb2w+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-pop-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1wcm90b2NvbCAwLjIuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibmV0LXByb3RvY29sIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgYWJzdHJhY3QgaW50ZXJmYWNlIGZvciBuZXQtKiBjbGllbnQuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhlIGFic3RyYWN0IGludGVyZmFjZSBmb3IgbmV0LSogY2xpZW50Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9uZXQvcHJvdG9jb2wucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/net-protocol-0.2.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5ldC1zbXRwIDAuNS4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuZXQtc210cCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNS4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXNtdHAiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvbmV0LXNtdHAiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1a2loaXJvIE1hdHN1bW90byIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTAyLTA1IgogIHMuZGVzY3JpcHRpb24gPSAiU2ltcGxlIE1haWwgVHJhbnNmZXIgUHJvdG9jb2wgY2xpZW50IGxpYnJhcnkgZm9yIFJ1YnkuIi5mcmVlemUKICBzLmVtYWlsID0gWyJtYXR6QHJ1YnktbGFuZy5vcmciLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L25ldC1zbXRwIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjYuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjcuMC5kZXYiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTaW1wbGUgTWFpbCBUcmFuc2ZlciBQcm90b2NvbCBjbGllbnQgbGlicmFyeSBmb3IgUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8bmV0LXByb3RvY29sPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/net-smtp-0.5.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5pbzRyIDIuNy41IHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJuaW80ciIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuNy41IgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiTklPOjpTZWxlY3RvciwgTW9uaXRvciBhbmQgQnl0ZUJ1ZmZlciwgb24gZXBvbGwsIHBvbGwoMikgb3IgU29ja2V0LlNlbGVjdC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJOSU86OlNlbGVjdG9yLCBNb25pdG9yIGFuZCBCeXRlQnVmZmVyLCBvbiBlcG9sbCwgcG9sbCgyKSBvciBTb2NrZXQuU2VsZWN0Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvbmlvLnJiIi5mcmVlemUsCiAgICAibGliL25pby9ieXRlYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL25pby9tb25pdG9yLnJiIi5mcmVlemUsCiAgICAibGliL25pby9zZWxlY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9uaW8vdmVyc2lvbi5yYiIuZnJlZXplLAogICAgImxpYi9uaW80ci5yYiIuZnJlZXplLAogICAgImxpYi9uaW80cl9leHQucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nio4r-2.7.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5rZiAwLjIuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibmtmIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJOZXR3b3JrIEthbmppIEZpbHRlciwgb24gU3RyaW5nI2VuY29kZS4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJOZXR3b3JrIEthbmppIEZpbHRlciwgb24gU3RyaW5nI2VuY29kZSIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL25rZi5yYiIuZnJlZXplLAogICAgImxpYi9rY29udi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nkf-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG5va29naXJpIDEuMTguMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAibm9rb2dpcmkiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIxLjE4LjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJIVE1MNSwgSFRNTDQgYW5kIFhNTCBwYXJzaW5nLCBvbiBBbmdsZVNoYXJwLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkhUTUw1LCBIVE1MNCBhbmQgWE1MIHBhcnNpbmcsIG9uIEFuZ2xlU2hhcnAiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9ub2tvZ2lyaS5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS9jc3MucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkvaHRtbC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS9zZXJpYWxpemVyLnJiIi5mcmVlemUsCiAgICAibGliL25va29naXJpL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkveG1sL2RvY3VtZW50LnJiIi5mcmVlemUsCiAgICAibGliL25va29naXJpL3htbC9kb2N1bWVudF9mcmFnbWVudC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94bWwvbm9kZS5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94bWwvbm9kZV9zZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvbm9rb2dpcmkveG1sL3NheC5yYiIuZnJlZXplLAogICAgImxpYi9ub2tvZ2lyaS94cGF0aC5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/nokogiri-1.18.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9ic2VydmVyIDAuMS4yIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvYnNlcnZlciIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS4yIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb2JzZXJ2ZXIiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb2JzZXJ2ZXIiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIll1a2loaXJvIE1hdHN1bW90byIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjIwMjMtMTEtMDciCiAgcy5kZXNjcmlwdGlvbiA9ICJJbXBsZW1lbnRhdGlvbiBvZiB0aGUgT2JzZXJ2ZXIgb2JqZWN0LW9yaWVudGVkIGRlc2lnbiBwYXR0ZXJuLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9vYnNlcnZlciIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4wLmRldiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkltcGxlbWVudGF0aW9uIG9mIHRoZSBPYnNlcnZlciBvYmplY3Qtb3JpZW50ZWQgZGVzaWduIHBhdHRlcm4uIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/observer-0.1.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9qIDMuMTcuNiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAib2oiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIzLjE3LjYiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJPaidzIDpzdHJpY3QsIDpudWxsLCA6Y29tcGF0IGFuZCA6cmFpbHMgbW9kZXMgYW5kIG1pbWljX0pTT04sIGluIEMjLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIk9qJ3MgOnN0cmljdCwgOm51bGwsIDpjb21wYXQgYW5kIDpyYWlscyBtb2RlcyBhbmQgbWltaWNfSlNPTiwgaW4gQyMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9vai5yYiIuZnJlZXplLAogICAgImxpYi9vai9hY3RpdmVfc3VwcG9ydF9oZWxwZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovYmFnLnJiIi5mcmVlemUsCiAgICAibGliL29qL2Vhc3lfaGFzaC5yYiIuZnJlZXplLAogICAgImxpYi9vai9lcnJvci5yYiIuZnJlZXplLAogICAgImxpYi9vai9qc29uLnJiIi5mcmVlemUsCiAgICAibGliL29qL21pbWljLnJiIi5mcmVlemUsCiAgICAibGliL29qL29qLnJiIi5mcmVlemUsCiAgICAibGliL29qL3Nhai5yYiIuZnJlZXplLAogICAgImxpYi9vai9zY2hhbmRsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovc3RhdGUucmIiLmZyZWV6ZSwKICAgICJsaWIvb2ovdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/oj-3.17.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW4tdXJpIDAuNS4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcGVuLXVyaSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuNS4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiQW4gZWFzeS10by11c2Ugd3JhcHBlciBmb3IgTmV0OjpIVFRQIGFuZCBOZXQ6OkZUUC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiBlYXN5LXRvLXVzZSB3cmFwcGVyIGZvciBOZXQ6OkhUVFAgYW5kIE5ldDo6RlRQIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9vcGVuLXVyaS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/open-uri-0.5.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9wZW4zIDAuMi4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJvcGVuMyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiUG9wZW4sIGJ1dCB3aXRoIHN0ZGVyciwgdG9vLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlBvcGVuLCBidXQgd2l0aCBzdGRlcnIsIHRvbyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvb3BlbjMucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/open3-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IG9zdHJ1Y3QgMC42LjMgcnVieSBsaWIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIm9zdHJ1Y3QiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjYuMyIuZnJlZXplCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpIGlmIHMucmVzcG9uZF90bz8gOnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb249CiAgcy5tZXRhZGF0YSA9IHsgImNoYW5nZWxvZ191cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9vc3RydWN0L3JlbGVhc2VzIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJNYXJjLUFuZHJlIExhZm9ydHVuZSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDI1LTA3LTE3IgogIHMuZGVzY3JpcHRpb24gPSAiQ2xhc3MgdG8gYnVpbGQgY3VzdG9tIGRhdGEgc3RydWN0dXJlcywgc2ltaWxhciB0byBhIEhhc2guIi5mcmVlemUKICBzLmVtYWlsID0gWyJydWJ5LWNvcmVAbWFyYy1hbmRyZS5jYSIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1Ynkvb3N0cnVjdCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjExIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiQ2xhc3MgdG8gYnVpbGQgY3VzdG9tIGRhdGEgc3RydWN0dXJlcywgc2ltaWxhciB0byBhIEhhc2guIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/ostruct-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBvd2VyX2Fzc2VydCAzLjAuMSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicG93ZXJfYXNzZXJ0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy4wLjEiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJLYXp1a2kgVHN1amltb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlBvd2VyIEFzc2VydCBzaG93cyBlYWNoIHZhbHVlIG9mIHZhcmlhYmxlcyBhbmQgbWV0aG9kIGNhbGxzIGluIHRoZSBleHByZXNzaW9uLiBJdCBpcyB1c2VmdWwgZm9yIHRlc3RpbmcsIHByb3ZpZGluZyB3aGljaCB2YWx1ZSB3YXNuJ3QgY29ycmVjdCB3aGVuIHRoZSBjb25kaXRpb24gaXMgbm90IHNhdGlzZmllZC4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImthenVraUBjYWxsY2MubmV0Ii5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJSRUFETUUubWQiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJSRUFETUUubWQiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Bvd2VyX2Fzc2VydCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemUsICJSdWJ5Ii5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUG93ZXIgQXNzZXJ0IGZvciBSdWJ5Ii5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/power_assert-3.0.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByaW1lIDAuMS40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmltZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiTWFyYy1BbmRyZSBMYWZvcnR1bmUiLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIyMDI1LTA2LTE4IgogIHMuZGVzY3JpcHRpb24gPSAiUHJpbWUgbnVtYmVycyBhbmQgZmFjdG9yaXphdGlvbiBsaWJyYXJ5LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsicnVieS1jb3JlQG1hcmMtYW5kcmUuY2EiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3ByaW1lIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjUuMTEiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJQcmltZSBudW1iZXJzIGFuZCBmYWN0b3JpemF0aW9uIGxpYnJhcnkuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHNpbmdsZXRvbj4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPGZvcndhcmRhYmxlPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/prime-0.1.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHByaXNtIDIuMC4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwcmlzbSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuMC4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVGhlIFByaXNtIFJ1YnkgcGFyc2VyIC0gSXJvblJ1YnkncyBvd24gZnJvbnQgZW5kLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBQcmlzbSBSdWJ5IHBhcnNlciAtIElyb25SdWJ5J3Mgb3duIGZyb250IGVuZCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL3ByaXNtLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2lyb25ydWJ5LnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2Rlc3VnYXJfY29tcGlsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vZGlzcGF0Y2hlci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9kb3RfdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9kc2wucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vZmZpLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL2luc3BlY3RfdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9sZXhfY29tcGF0LnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL211dGF0aW9uX2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL25vZGUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vbm9kZV9leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vbm9kZV9maW5kLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BhcnNlX3Jlc3VsdC5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wYXJzZV9yZXN1bHQvZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BhcnNlX3Jlc3VsdC9uZXdsaW5lcy5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wYXR0ZXJuLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BvbHlmaWxsL2FwcGVuZF9hc19ieXRlcy5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9wb2x5ZmlsbC9ieXRlaW5kZXgucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vcG9seWZpbGwvc2Nhbl9ieXRlLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3BvbHlmaWxsL3VucGFjazEucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vcG9seWZpbGwvd2Fybi5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS9yZWZsZWN0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3JlbG9jYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vc2VyaWFsaXplLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3N0cmluZ19xdWVyeS5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcGFyc2VyL2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcGFyc2VyL2NvbXBpbGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3BhcnNlci9sZXhlci5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXJfY3VycmVudC5yYiIuZnJlZXplLAogICAgImxpYi9wcmlzbS90cmFuc2xhdGlvbi9wYXJzZXJfdmVyc2lvbnMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcmlwcGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9maWx0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHJpc20vdHJhbnNsYXRpb24vcmlwcGVyL2xleGVyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9zZXhwLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3JpcHBlci9zaGltLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3RyYW5zbGF0aW9uL3J1YnlfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL3ByaXNtL3Zpc2l0b3IucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/prism-2.0.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBzdG9yZSAwLjIuMSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicHN0b3JlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4yLjEiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJob21lcGFnZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9wc3RvcmUiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcHN0b3JlIiB9IGlmIHMucmVzcG9uZF90bz8gOm1ldGFkYXRhPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJZdWtpaGlybyBNYXRzdW1vdG8iLmZyZWV6ZV0KICBzLmJpbmRpciA9ICJleGUiLmZyZWV6ZQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiVHJhbnNhY3Rpb25hbCBGaWxlIFN0b3JhZ2UgZm9yIFJ1YnkgT2JqZWN0cyIuZnJlZXplCiAgcy5lbWFpbCA9IFsibWF0ekBydWJ5LWxhbmcub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9wc3RvcmUiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuOSIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRyYW5zYWN0aW9uYWwgRmlsZSBTdG9yYWdlIGZvciBSdWJ5IE9iamVjdHMiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/pstore-0.2.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHBzeWNoIDUuMy4xIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJwc3ljaCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjUuMy4xIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiWUFNTCBwYXJzZXIgYW5kIGVtaXR0ZXIuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiWUFNTCBwYXJzZXIgYW5kIGVtaXR0ZXIiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9wc3ljaC5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9jbGFzc19sb2FkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvY29kZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvY29yZV9leHQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvZXhjZXB0aW9uLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2hhbmRsZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvaGFuZGxlcnMvZG9jdW1lbnRfc3RyZWFtLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2hhbmRsZXJzL3JlY29yZGVyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2lyb25ydWJ5LnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL2pzb24vcnVieV9ldmVudHMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi9zdHJlYW0ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi90cmVlX2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvanNvbi95YW1sX2V2ZW50cy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9hbGlhcy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9kb2N1bWVudC5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9ub2Rlcy9tYXBwaW5nLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL25vZGUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvbm9kZXMvc2NhbGFyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL3NlcXVlbmNlLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL25vZGVzL3N0cmVhbS5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9vbWFwLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3BhcnNlci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zY2FsYXJfc2Nhbm5lci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvc3RyZWFtLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3N0cmVhbWluZy5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC9zeW50YXhfZXJyb3IucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdHJlZV9idWlsZGVyLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3ZlcnNpb25zLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL2RlcHRoX2ZpcnN0LnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL2VtaXR0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdmlzaXRvcnMvanNvbl90cmVlLnJiIi5mcmVlemUsCiAgICAibGliL3BzeWNoL3Zpc2l0b3JzL3RvX3J1YnkucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gvdmlzaXRvcnMvdmlzaXRvci5yYiIuZnJlZXplLAogICAgImxpYi9wc3ljaC92aXNpdG9ycy95YW1sX3RyZWUucmIiLmZyZWV6ZSwKICAgICJsaWIvcHN5Y2gveS5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/psych-5.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHB1bWEgOC4wLjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInB1bWEiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICI4LjAuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlB1bWEsIHdpdGggaXRzIEhUVFAgcGFyc2VyIGFuZCBUTFMgZW5naW5lIGluIEMjOyBzaW5nbGUgbW9kZSBvbmx5LiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlB1bWEsIHdpdGggaXRzIEhUVFAgcGFyc2VyIGFuZCBUTFMgZW5naW5lIGluIEMjOyBzaW5nbGUgbW9kZSBvbmx5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmV4ZWN1dGFibGVzID0gWyJwdW1hIi5mcmVlemUsICJwdW1hY3RsIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvcHVtYS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2FwcC9zdGF0dXMucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9iaW5kZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGkucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGllbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jbGllbnRfZW52LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NsdXN0ZXIvd29ya2VyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlci93b3JrZXJfaGFuZGxlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvY2x1c3Rlcl9hY2NlcHRfbG9vcF9kZWxheS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbW1vbmxvZ2dlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbmZpZ3VyYXRpb24ucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9jb25zdC5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2NvbnRyb2xfY2xpLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZGV0ZWN0LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZHNsLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZXJyb3JfbG9nZ2VyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvZXZlbnRzLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvaW9fYnVmZmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvanJ1YnlfcmVzdGFydC5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2pzb25fc2VyaWFsaXphdGlvbi5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2xhdW5jaGVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvbGF1bmNoZXIvYnVuZGxlX3BydW5lci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL2xvZ193cml0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9taW5pc3NsLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvbWluaXNzbC9jb250ZXh0X2J1aWxkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9udWxsX2lvLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcGx1Z2luLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcGx1Z2luL3N5c3RlbWQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9wbHVnaW4vdG1wX3Jlc3RhcnQucmIiLmZyZWV6ZSwKICAgICJsaWIvcHVtYS9wdW1hX2h0dHAxMS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3JhY2svYnVpbGRlci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3JhY2svdXJsbWFwLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcmFja19kZWZhdWx0LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcmVhY3Rvci5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvcnVubmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2Rfbm90aWZ5LnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2VydmVyLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2VydmVyX3BsdWdpbl9jb250cm9sLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc2luZ2xlLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvc3RhdGVfZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi9wdW1hL3RocmVhZF9wb29sLnJiIi5mcmVlemUsCiAgICAibGliL3B1bWEvdXRpbC5yYiIuZnJlZXplLAogICAgImxpYi9yYWNrL2hhbmRsZXIvcHVtYS5yYiIuZnJlZXplLAogIF0KCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCJuaW80ciIuZnJlZXplLCBbIn4+IDIuMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/puma-8.0.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJhY2MgMS44LjEgcnVieSBsaWIKIyBzdHViOiBleHQvcmFjYy9jcGFyc2UvZXh0Y29uZi5yYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmFjYyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjEuOC4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JhY2MvcmVsZWFzZXMiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIk1pbmVybyBBb2tpIi5mcmVlemUsICJBYXJvbiBQYXR0ZXJzb24iLmZyZWV6ZV0KICBzLmRhdGUgPSAiMjAyNC0wNy0zMCIKICBzLmRlc2NyaXB0aW9uID0gIlJhY2MgaXMgYW4gTEFMUigxKSBwYXJzZXIgZ2VuZXJhdG9yLlxuICBJdCBpcyB3cml0dGVuIGluIFJ1YnkgaXRzZWxmLCBhbmQgZ2VuZXJhdGVzIFJ1YnkgcHJvZ3JhbS5cblxuICBOT1RFOiBSdWJ5IDEuOC54IGNvbWVzIHdpdGggUmFjYyBydW50aW1lIG1vZHVsZS4gIFlvdVxuICBjYW4gcnVuIHlvdXIgcGFyc2VycyBnZW5lcmF0ZWQgYnkgcmFjYyAxLjQueCBvdXQgb2YgdGhlXG4gIGJveC5cbiIuZnJlZXplCiAgcy5lbWFpbCA9IFtuaWwsICJhYXJvbkB0ZW5kZXJsb3ZlbWFraW5nLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInJhY2MiLmZyZWV6ZV0KICBzLmV4dGVuc2lvbnMgPSBbImV4dC9yYWNjL2NwYXJzZS9leHRjb25mLnJiIi5mcmVlemVdCiAgcy5leHRyYV9yZG9jX2ZpbGVzID0gWyJSRUFETUUuamEucmRvYyIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJSRUFETUUuamEucmRvYyIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZSwgImJpbi9yYWNjIi5mcmVlemUsICJleHQvcmFjYy9jcGFyc2UvZXh0Y29uZi5yYiIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFjYyIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLnJkb2MiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAyLjUiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmFjYyBpcyBhbiBMQUxSKDEpIHBhcnNlciBnZW5lcmF0b3IiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/racc-1.8.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJha2UgMTMuMy4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyYWtlIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMTMuMy4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiYnVnX3RyYWNrZXJfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFrZS9pc3N1ZXMiLCAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jha2UvcmVsZWFzZXMiLCAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL3J1YnkuZ2l0aHViLmlvL3Jha2UiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmFrZSIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSGlyb3NoaSBTSElCQVRBIi5mcmVlemUsICJFcmljIEhvZGVsIi5mcmVlemUsICJKaW0gV2VpcmljaCIuZnJlZXplXQogIHMuYmluZGlyID0gImV4ZSIuZnJlZXplCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJSYWtlIGlzIGEgTWFrZS1saWtlIHByb2dyYW0gaW1wbGVtZW50ZWQgaW4gUnVieS4gVGFza3MgYW5kIGRlcGVuZGVuY2llcyBhcmVcbnNwZWNpZmllZCBpbiBzdGFuZGFyZCBSdWJ5IHN5bnRheC5cblJha2UgaGFzIHRoZSBmb2xsb3dpbmcgZmVhdHVyZXM6XG4gICogUmFrZWZpbGVzIChyYWtlJ3MgdmVyc2lvbiBvZiBNYWtlZmlsZXMpIGFyZSBjb21wbGV0ZWx5IGRlZmluZWQgaW4gc3RhbmRhcmQgUnVieSBzeW50YXguXG4gICAgTm8gWE1MIGZpbGVzIHRvIGVkaXQuIE5vIHF1aXJreSBNYWtlZmlsZSBzeW50YXggdG8gd29ycnkgYWJvdXQgKGlzIHRoYXQgYSB0YWIgb3IgYSBzcGFjZT8pXG4gICogVXNlcnMgY2FuIHNwZWNpZnkgdGFza3Mgd2l0aCBwcmVyZXF1aXNpdGVzLlxuICAqIFJha2Ugc3VwcG9ydHMgcnVsZSBwYXR0ZXJucyB0byBzeW50aGVzaXplIGltcGxpY2l0IHRhc2tzLlxuICAqIEZsZXhpYmxlIEZpbGVMaXN0cyB0aGF0IGFjdCBsaWtlIGFycmF5cyBidXQga25vdyBhYm91dCBtYW5pcHVsYXRpbmcgZmlsZSBuYW1lcyBhbmQgcGF0aHMuXG4gICogU3VwcG9ydHMgcGFyYWxsZWwgZXhlY3V0aW9uIG9mIHRhc2tzLlxuIi5mcmVlemUKICBzLmVtYWlsID0gWyJoc2J0QHJ1YnktbGFuZy5vcmciLmZyZWV6ZSwgImRyYnJhaW5Ac2VnbWVudDcubmV0Ii5mcmVlemUsICIiLmZyZWV6ZV0KICBzLmV4ZWN1dGFibGVzID0gWyJyYWtlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsiZXhlL3Jha2UiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jha2UiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIk1JVCIuZnJlZXplXQogIHMucmRvY19vcHRpb25zID0gWyItLW1haW4iLmZyZWV6ZSwgIlJFQURNRS5yZG9jIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmFrZSBpcyBhIE1ha2UtbGlrZSBwcm9ncmFtIGltcGxlbWVudGVkIGluIFJ1YnkiLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rake-13.3.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJicyA0LjAuMC5kZXYuNSBydWJ5IGxpYgojIHN0dWI6IGV4dC9yYnNfZXh0ZW5zaW9uL2V4dGNvbmYucmIKCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInJicyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjQuMC4wLmRldi41Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jicy9ibG9iL21hc3Rlci9DSEFOR0VMT0cubWQiLCAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmJzIiwgInNvdXJjZV9jb2RlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3Jicy5naXQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIlNvdXRhcm8gTWF0c3Vtb3RvIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlJCUyBpcyB0aGUgbGFuZ3VhZ2UgZm9yIHR5cGUgc2lnbmF0dXJlcyBmb3IgUnVieSBhbmQgc3RhbmRhcmQgbGlicmFyeSBkZWZpbml0aW9ucy4iLmZyZWV6ZQogIHMuZW1haWwgPSBbIm1hdHN1bW90b0Bzb3V0YXJvLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInJicyIuZnJlZXplXQogIHMuZXh0ZW5zaW9ucyA9IFsiZXh0L3Jic19leHRlbnNpb24vZXh0Y29uZi5yYiIuZnJlZXplXQogIHMuZmlsZXMgPSBbImV4ZS9yYnMiLmZyZWV6ZSwgImV4dC9yYnNfZXh0ZW5zaW9uL2V4dGNvbmYucmIiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JicyIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemUsICJSdWJ5Ii5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMy4yIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNi45Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiVHlwZSBzaWduYXR1cmUgZm9yIFJ1YnkuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPGxvZ2dlcj4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHByaXNtPi5mcmVlemUsIFsiPj0gMS4zLjAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHRzb3J0Pi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rbs-4.0.0.dev.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlYWRsaW5lIDAuMC40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZWFkbGluZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMC40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiYXljYWJ0YSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDIzLTEyLTE2IgogIHMuZGVzY3JpcHRpb24gPSAiVGhpcyBpcyBqdXN0IGEgbG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIElmIFJ1YnkgaGFzIHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbVxudGhhdCBpcyBhIG5hdGl2ZSBleHRlbnNpb24sIHRoaXMgZ2VtIHdpbGwgbG9hZCBpdC4gSWYgUnVieSBkb2VzIG5vdCBoYXZlXG50aGUgXCJyZWFkbGluZS1leHRcIiBnZW0gdGhpcyBnZW0gd2lsbCBsb2FkIFwicmVsaW5lXCIsIGEgbGlicmFyeSB0aGF0IGlzXG5jb21wYXRpYmxlIHdpdGggdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIGFuZCBpbXBsZW1lbnRlZCBpbiBwdXJlIFJ1YnkuXG4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImF5Y2FidGFAZ21haWwuY29tIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZWFkbGluZSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplXQogIHMucG9zdF9pbnN0YWxsX21lc3NhZ2UgPSAiKy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLStcbnwgVGhpcyBpcyBqdXN0IGEgbG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIElmIFJ1YnkgaGFzIHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbSAgfFxufCB0aGF0IGlzIGEgbmF0aXZlIGV4dGVuc2lvbiwgdGhpcyBnZW0gd2lsbCBsb2FkIGl0LiBJZiBSdWJ5IGRvZXMgbm90IGhhdmUgIHxcbnwgdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIHRoaXMgZ2VtIHdpbGwgbG9hZCBcInJlbGluZVwiLCBhIGxpYnJhcnkgdGhhdCBpcyAgICAgfFxufCBjb21wYXRpYmxlIHdpdGggdGhlIFwicmVhZGxpbmUtZXh0XCIgZ2VtIGFuZCBpbXBsZW1lbnRlZCBpbiBwdXJlIFJ1YnkuICAgICAgfFxufCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHxcbnwgSWYgeW91IGludGVuZCB0byB1c2UgR05VIFJlYWRsaW5lIGJ5IGByZXF1aXJlICdyZWFkbGluZSdgLCBwbGVhc2UgaW5zdGFsbCB8XG58IHRoZSBcInJlYWRsaW5lLWV4dFwiIGdlbS4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB8XG4rLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tK1xuIi5mcmVlemUKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy41LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiTG9hZGVyIGZvciBcInJlYWRsaW5lXCIuIi5mcmVlemUKCiAgcy5pbnN0YWxsZWRfYnlfdmVyc2lvbiA9ICI0LjAuMjAiLmZyZWV6ZQoKICBzLnNwZWNpZmljYXRpb25fdmVyc2lvbiA9IDQKCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHJlbGluZT4uZnJlZXplLCBbIj49IDAiLmZyZWV6ZV0pCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/readline-0.0.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlbGluZSAwLjYuMyBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmVsaW5lIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC42LjMiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJHTlUgUmVhZGxpbmUgYW5kIEVkaXRsaW5lLCBpbiBwdXJlIFJ1YnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiR05VIFJlYWRsaW5lIGFuZCBFZGl0bGluZSwgaW4gcHVyZSBSdWJ5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLm1ldGFkYXRhID0geyAiaXJvbnJ1YnlfcGlubmVkIi5mcmVlemUgPT4gInRydWUiLmZyZWV6ZSB9CiAgcy5maWxlcyA9IFsKICAgICJsaWIvcmVsaW5lLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9jb25maWcucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2ZhY2UucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2hpc3RvcnkucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2lvLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby9hbnNpLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby9kdW1iLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9pby93aW5kb3dzLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2tleV9hY3Rvci9iYXNlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvY29tcG9zaXRlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvZW1hY3MucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2tleV9hY3Rvci92aV9jb21tYW5kLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfYWN0b3IvdmlfaW5zZXJ0LnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9rZXlfc3Ryb2tlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS9raWxsX3JpbmcucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL2xpbmVfZWRpdG9yLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS91bmljb2RlLnJiIi5mcmVlemUsCiAgICAibGliL3JlbGluZS91bmljb2RlL2Vhc3RfYXNpYW5fd2lkdGgucmIiLmZyZWV6ZSwKICAgICJsaWIvcmVsaW5lL3ZlcnNpb24ucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/reline-0.6.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlcGxfdHlwZV9jb21wbGV0b3IgMC4xLjE2IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXBsX3R5cGVfY29tcGxldG9yIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4xLjE2Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXBsX3R5cGVfY29tcGxldG9yIiwgImhvbWVwYWdlX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JlcGxfdHlwZV9jb21wbGV0b3IiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVwbF90eXBlX2NvbXBsZXRvciIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsidG9tcG5nIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIlR5cGUgYmFzZWQgY29tcGxldGlvbiBmb3IgUkVQTC4iLmZyZWV6ZQogIHMuZW1haWwgPSBbInRvbW95YXBlbmd1aW5AZ21haWwuY29tIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXBsX3R5cGVfY29tcGxldG9yIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJNSVQiLmZyZWV6ZV0KICBzLnJlcXVpcmVkX3J1YnlfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAzLjAuMCIuZnJlZXplKQogIHMucnVieWdlbXNfdmVyc2lvbiA9ICIzLjYuNyIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlR5cGUgYmFzZWQgY29tcGxldGlvbiBmb3IgUkVQTC4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cHJpc20+LmZyZWV6ZSwgWyI+PSAxLjAiLmZyZWV6ZV0pCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCVxPHJicz4uZnJlZXplLCBbIj49IDIuNy4wIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/repl_type_completor-0.1.16.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlc29sdiAwLjcuMiBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicmVzb2x2Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMC43LjIiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaHJlYWQtYXdhcmUgRE5TIHJlc29sdmVyIGxpYnJhcnkuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVGhyZWFkLWF3YXJlIEROUyByZXNvbHZlciBsaWJyYXJ5Ii5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9yZXNvbHYucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/resolv-0.7.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJlc29sdi1yZXBsYWNlIDAuMS4xIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXNvbHYtcmVwbGFjZSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMS4xIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVzb2x2LXJlcGxhY2UiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmVzb2x2LXJlcGxhY2UiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIlRhbmFrYSBBa2lyYSIuZnJlZXplXQogIHMuZGF0ZSA9ICIyMDIyLTEyLTE0IgogIHMuZGVzY3JpcHRpb24gPSAiUmVwbGFjZSBTb2NrZXQgRE5TIHdpdGggUmVzb2x2LiIuZnJlZXplCiAgcy5lbWFpbCA9IFsiYWtyQGZzaWoub3JnIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXNvbHYtcmVwbGFjZSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi4zLjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy40LjAuZGV2Ii5mcmVlemUKICBzLnN1bW1hcnkgPSAiUmVwbGFjZSBTb2NrZXQgRE5TIHdpdGggUmVzb2x2LiIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKCiAgcy5zcGVjaWZpY2F0aW9uX3ZlcnNpb24gPSA0CgogIHMuYWRkX3J1bnRpbWVfZGVwZW5kZW5jeSglcTxyZXNvbHY+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/resolv-replace-0.1.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJleG1sIDMuNC40IHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyZXhtbCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjMuNC40Ii5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiY2hhbmdlbG9nX3VyaSIgPT4gImh0dHBzOi8vZ2l0aHViLmNvbS9ydWJ5L3JleG1sL3JlbGVhc2VzL3RhZy92My40LjQiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIktvdWhlaSBTdXRvdSIuZnJlZXplXQogIHMuZGF0ZSA9ICIxOTgwLTAxLTAyIgogIHMuZGVzY3JpcHRpb24gPSAiQW4gWE1MIHRvb2xraXQgZm9yIFJ1YnkiLmZyZWV6ZQogIHMuZW1haWwgPSBbImtvdUBjb3ptaXhuZy5vcmciLmZyZWV6ZV0KICBzLmV4dHJhX3Jkb2NfZmlsZXMgPSBbIkxJQ0VOU0UudHh0Ii5mcmVlemUsICJORVdTLm1kIi5mcmVlemUsICJSRUFETUUubWQiLmZyZWV6ZSwgImRvYy9yZXhtbC9jb250ZXh0LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2NoaWxkLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2RvY3VtZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL2VsZW1lbnQucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3Jkb2Mvbm9kZS5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9wYXJlbnQucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvY2hpbGRfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL2RvY3VtZW50X3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9lbGVtZW50X3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9tYXN0ZXJfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL25vZGVfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL3BhcmVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3R1dG9yaWFsLnJkb2MiLmZyZWV6ZV0KICBzLmZpbGVzID0gWyJMSUNFTlNFLnR4dCIuZnJlZXplLCAiTkVXUy5tZCIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemUsICJkb2MvcmV4bWwvY29udGV4dC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9jaGlsZC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9kb2N1bWVudC5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvcmRvYy9lbGVtZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy9yZG9jL25vZGUucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3Jkb2MvcGFyZW50LnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90YXNrcy90b2NzL2NoaWxkX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9kb2N1bWVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvZWxlbWVudF90b2MucmRvYyIuZnJlZXplLCAiZG9jL3JleG1sL3Rhc2tzL3RvY3MvbWFzdGVyX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9ub2RlX3RvYy5yZG9jIi5mcmVlemUsICJkb2MvcmV4bWwvdGFza3MvdG9jcy9wYXJlbnRfdG9jLnJkb2MiLmZyZWV6ZSwgImRvYy9yZXhtbC90dXRvcmlhbC5yZG9jIi5mcmVlemVdCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vcnVieS9yZXhtbCIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5yZG9jX29wdGlvbnMgPSBbIi0tbWFpbiIuZnJlZXplLCAiUkVBRE1FLm1kIi5mcmVlemVdCiAgcy5yZXF1aXJlZF9ydWJ5X3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMi41LjAiLmZyZWV6ZSkKICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiBYTUwgdG9vbGtpdCBmb3IgUnVieSIuZnJlZXplCgogIHMuaW5zdGFsbGVkX2J5X3ZlcnNpb24gPSAiNC4wLjIwIi5mcmVlemUKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rexml-3.4.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJpbmRhIDAuMi4wIHJ1YnkgbGliCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJyaW5kYSIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIi5mcmVlemUKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkgaWYgcy5yZXNwb25kX3RvPyA6cmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbj0KICBzLm1ldGFkYXRhID0geyAiaG9tZXBhZ2VfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiLCAic291cmNlX2NvZGVfdXJpIiA9PiAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiIH0gaWYgcy5yZXNwb25kX3RvPyA6bWV0YWRhdGE9CiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIk1hc2F0b3NoaSBTRUtJIi5mcmVlemVdCiAgcy5iaW5kaXIgPSAiZXhlIi5mcmVlemUKICBzLmRhdGUgPSAiMjAyMy0xMS0wNyIKICBzLmRlc2NyaXB0aW9uID0gIlRoZSBMaW5kYSBkaXN0cmlidXRlZCBjb21wdXRpbmcgcGFyYWRpZ20gaW4gUnVieS4iLmZyZWV6ZQogIHMuZW1haWwgPSBbInNla2lAcnVieS1sYW5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcmluZGEiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMucmVxdWlyZWRfcnVieV92ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDIuMy4wIi5mcmVlemUpCiAgcy5ydWJ5Z2Vtc192ZXJzaW9uID0gIjMuNS4wLmRldiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlRoZSBMaW5kYSBkaXN0cmlidXRlZCBjb21wdXRpbmcgcGFyYWRpZ20gaW4gUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8ZHJiPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8aXBhZGRyPi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8Zm9yd2FyZGFibGU+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rinda-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJzcyAwLjMuMiBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAicnNzIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjIiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJLb3VoZWkgU3V0b3UiLmZyZWV6ZV0KICBzLmRhdGUgPSAiMTk4MC0wMS0wMiIKICBzLmRlc2NyaXB0aW9uID0gIkZhbWlseSBvZiBsaWJyYXJpZXMgdGhhdCBzdXBwb3J0IHZhcmlvdXMgZm9ybWF0cyBvZiBYTUwgXCJmZWVkc1wiLiIuZnJlZXplCiAgcy5lbWFpbCA9IFsia291QGNvem1peG5nLm9yZyIuZnJlZXplXQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL3J1YnkvcnNzIi5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiNC4wLjIiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJGYW1pbHkgb2YgbGlicmFyaWVzIHRoYXQgc3VwcG9ydCB2YXJpb3VzIGZvcm1hdHMgb2YgWE1MIFwiZmVlZHNcIi4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cmV4bWw+LmZyZWV6ZSwgWyI+PSAwIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/rss-0.3.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHJ1YnkyX2tleXdvcmRzIDAuMC41IHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJydWJ5Ml9rZXl3b3JkcyIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMC41IgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiU2hpbSBsaWJyYXJ5IGZvciBNb2R1bGUjcnVieTJfa2V5d29yZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiU2hpbSBsaWJyYXJ5IGZvciBNb2R1bGUjcnVieTJfa2V5d29yZHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3J1YnkyX2tleXdvcmRzLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/ruby2_keywords-0.0.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNlY3VyZXJhbmRvbSAwLjQuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic2VjdXJlcmFuZG9tIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC40LjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJJbnRlcmZhY2UgZm9yIHNlY3VyZSByYW5kb20gbnVtYmVyIGdlbmVyYXRvci4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJJbnRlcmZhY2UgZm9yIHNlY3VyZSByYW5kb20gbnVtYmVyIGdlbmVyYXRvciIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2VjdXJlcmFuZG9tLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/securerandom-0.4.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNoZWxsd29yZHMgMC4yLjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInNoZWxsd29yZHMiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjIuMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIk1hbmlwdWxhdGVzIHN0cmluZ3Mgd2l0aCB3b3JkIHBhcnNpbmcgcnVsZXMgb2YgVU5JWCBCb3VybmUgc2hlbGwuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiTWFuaXB1bGF0ZXMgc3RyaW5ncyB3aXRoIHdvcmQgcGFyc2luZyBydWxlcyBvZiBVTklYIEJvdXJuZSBzaGVsbCIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2hlbGx3b3Jkcy5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/shellwords-0.2.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNpbmdsZXRvbiAwLjMuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic2luZ2xldG9uIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJUaGUgU2luZ2xldG9uIG1vZHVsZSBpbXBsZW1lbnRzIHRoZSBTaW5nbGV0b24gcGF0dGVybi4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJUaGUgU2luZ2xldG9uIG1vZHVsZSBpbXBsZW1lbnRzIHRoZSBTaW5nbGV0b24gcGF0dGVybiIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5maWxlcyA9IFsKICAgICJsaWIvc2luZ2xldG9uLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/singleton-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHNxbGl0ZTMgMi45LjYgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInNxbGl0ZTMiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIyLjkuNiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIlNRTGl0ZTMsIG9uIHRoZSBuYXRpdmUgbGlicmFyeSBNaWNyb3NvZnQuRGF0YS5TcWxpdGUgY2Fycmllcy4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJTUUxpdGUzLCBvbiB0aGUgbmF0aXZlIGxpYnJhcnkgTWljcm9zb2Z0LkRhdGEuU3FsaXRlIGNhcnJpZXMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zcWxpdGUzLnJiIi5mcmVlemUsCiAgICAibGliL3NxbGl0ZTMvY29uc3RhbnRzLnJiIi5mcmVlemUsCiAgICAibGliL3NxbGl0ZTMvZGF0YWJhc2UucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9lcnJvcnMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9mb3JrX3NhZmV0eS5yYiIuZnJlZXplLAogICAgImxpYi9zcWxpdGUzL3ByYWdtYXMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9yZXN1bHRzZXQucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy9zdGF0ZW1lbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvc3FsaXRlMy92YWx1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zcWxpdGUzL3ZlcnNpb25faW5mby5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/sqlite3-2.9.6.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN5bnRheF9zdWdnZXN0IDIuMC4zIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJzeW50YXhfc3VnZ2VzdCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjIuMC4zIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiRmluZCBzeW50YXggZXJyb3JzIGluIHlvdXIgc291cmNlIGluIGEgc25hcC4gIFByb3ZpZGVkIGJ5IElyb25SdWJ5IGl0c2VsZi4iLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJGaW5kIHN5bnRheCBlcnJvcnMgaW4geW91ciBzb3VyY2UgaW4gYSBzbmFwIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi9zeW50YXhfc3VnZ2VzdC5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9hcGkucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvYXJvdW5kX2Jsb2NrX3NjYW4ucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvYmxvY2tfZXhwYW5kLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NhcHR1cmUvYmVmb3JlX2FmdGVyX2tleXdvcmRfZW5kcy5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9jYXB0dXJlL2ZhbGxpbmdfaW5kZW50X2xpbmVzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NhcHR1cmVfY29kZV9jb250ZXh0LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NsZWFuX2RvY3VtZW50LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NsaS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9jb2RlX2Jsb2NrLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvZGVfZnJvbnRpZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvY29kZV9saW5lLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvZGVfc2VhcmNoLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2NvcmVfZXh0LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2Rpc3BsYXlfY29kZV93aXRoX2xpbmVfbnVtYmVycy5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9kaXNwbGF5X2ludmFsaWRfYmxvY2tzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2V4cGxhaW5fc3ludGF4LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2xlZnRfcmlnaHRfbGV4X2NvdW50LnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L2xleF9hbGwucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvbGV4X3ZhbHVlLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L21pbmlfc3RyaW5naW8ucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvcGFyc2VfYmxvY2tzX2Zyb21faW5kZW50X2xpbmUucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvcGF0aG5hbWVfZnJvbV9tZXNzYWdlLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L3ByaW9yaXR5X2VuZ3VsZl9xdWV1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9wcmlvcml0eV9xdWV1ZS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC9yaXBwZXJfZXJyb3JzLnJiIi5mcmVlemUsCiAgICAibGliL3N5bnRheF9zdWdnZXN0L3NjYW5faGlzdG9yeS5yYiIuZnJlZXplLAogICAgImxpYi9zeW50YXhfc3VnZ2VzdC91bnZpc2l0ZWRfbGluZXMucmIiLmZyZWV6ZSwKICAgICJsaWIvc3ludGF4X3N1Z2dlc3QvdmVyc2lvbi5yYiIuZnJlZXplLAogIF0KZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/syntax_suggest-2.0.3.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHN5c2xvZyAwLjMuMCBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAic3lzbG9nIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMC4zLjAiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJTeXNsb2csIGltcGxlbWVudGVkIGluIFNyYy9MaWJyYXJpZXMvU3lzbG9nLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIlN5c2xvZywgaW1wbGVtZW50ZWQgaW4gU3JjL0xpYnJhcmllcy9TeXNsb2ciLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMubWV0YWRhdGEgPSB7ICJpcm9ucnVieV9waW5uZWQiLmZyZWV6ZSA9PiAidHJ1ZSIuZnJlZXplIH0KICBzLmZpbGVzID0gWwogICAgImxpYi9zeXNsb2cucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/syslog-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRlc3QtdW5pdCAzLjcuNSBydWJ5IGxpYgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidGVzdC11bml0Ii5mcmVlemUKICBzLnZlcnNpb24gPSAiMy43LjUiLmZyZWV6ZQoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKSBpZiBzLnJlc3BvbmRfdG8/IDpyZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uPQogIHMubWV0YWRhdGEgPSB7ICJidWdfdHJhY2tlcl91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vdGVzdC11bml0L3Rlc3QtdW5pdC9pc3N1ZXMiLCAiZG9jdW1lbnRhdGlvbl91cmkiID0+ICJodHRwczovL3Rlc3QtdW5pdC5naXRodWIuaW8vdGVzdC11bml0L2VuLyIsICJzb3VyY2VfY29kZV91cmkiID0+ICJodHRwczovL2dpdGh1Yi5jb20vdGVzdC11bml0L3Rlc3QtdW5pdCIgfSBpZiBzLnJlc3BvbmRfdG8/IDptZXRhZGF0YT0KICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiS291aGVpIFN1dG91Ii5mcmVlemUsICJIYXJ1a2EgWW9zaGloYXJhIi5mcmVlemVdCiAgcy5kYXRlID0gIjE5ODAtMDEtMDIiCiAgcy5kZXNjcmlwdGlvbiA9ICJ0ZXN0LXVuaXQgKFRlc3Q6OlVuaXQpIGlzIHVuaXQgdGVzdGluZyBmcmFtZXdvcmsgZm9yIFJ1YnksIGJhc2VkIG9uIHhVbml0XG5wcmluY2lwbGVzLiBUaGVzZSB3ZXJlIG9yaWdpbmFsbHkgZGVzaWduZWQgYnkgS2VudCBCZWNrLCBjcmVhdG9yIG9mIGV4dHJlbWVcbnByb2dyYW1taW5nIHNvZnR3YXJlIGRldmVsb3BtZW50IG1ldGhvZG9sb2d5LCBmb3IgU21hbGx0YWxrJ3MgU1VuaXQuIEl0IGFsbG93c1xud3JpdGluZyB0ZXN0cywgY2hlY2tpbmcgcmVzdWx0cyBhbmQgYXV0b21hdGVkIHRlc3RpbmcgaW4gUnVieS4iLmZyZWV6ZQogIHMuZW1haWwgPSBbImtvdUBjb3ptaXhuZy5vcmciLmZyZWV6ZSwgInlvc2hpaGFyYUBjbGVhci1jb2RlLmNvbSIuZnJlZXplXQogIHMuZXhlY3V0YWJsZXMgPSBbInRlc3QtdW5pdCIuZnJlZXplXQogIHMuZmlsZXMgPSBbImJpbi90ZXN0LXVuaXQiLmZyZWV6ZV0KICBzLmhvbWVwYWdlID0gImh0dHBzOi8vdGVzdC11bml0LmdpdGh1Yi5pby8iLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTREwiLmZyZWV6ZSwgIlBTRkwiLmZyZWV6ZV0KICBzLnJ1YnlnZW1zX3ZlcnNpb24gPSAiMy42LjkiLmZyZWV6ZQogIHMuc3VtbWFyeSA9ICJBbiB4VW5pdCBmYW1pbHkgdW5pdCB0ZXN0aW5nIGZyYW1ld29yayBmb3IgUnVieS4iLmZyZWV6ZQoKICBzLmluc3RhbGxlZF9ieV92ZXJzaW9uID0gIjQuMC4yMCIuZnJlZXplCgogIHMuc3BlY2lmaWNhdGlvbl92ZXJzaW9uID0gNAoKICBzLmFkZF9ydW50aW1lX2RlcGVuZGVuY3koJXE8cG93ZXJfYXNzZXJ0Pi5mcmVlemUsIFsiPj0gMCIuZnJlZXplXSkKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/test-unit-3.7.5.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRpbWVvdXQgMC42LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInRpbWVvdXQiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjYuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkF1dG8tdGVybWluYXRlIHBvdGVudGlhbGx5IGxvbmctcnVubmluZyBvcGVyYXRpb25zLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkF1dG8tdGVybWluYXRlIHBvdGVudGlhbGx5IGxvbmctcnVubmluZyBvcGVyYXRpb25zIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi90aW1lb3V0LnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/timeout-0.6.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHRzb3J0IDAuMi4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ0c29ydCIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMi4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVG9wb2xvZ2ljYWwgc29ydGluZyB1c2luZyBUYXJqYW4ncyBhbGdvcml0aG0uICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVG9wb2xvZ2ljYWwgc29ydGluZyB1c2luZyBUYXJqYW4ncyBhbGdvcml0aG0iLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3Rzb3J0LnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/tsort-0.2.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHVuIDAuMy4wIHJ1YnkgbGliCiMKIyBHZW5lcmF0ZWQgYnkgVXRpbC9nZW4tZGVmYXVsdC1nZW1zcGVjcy5yYi4gIERvIG5vdCBlZGl0IGJ5IGhhbmQuCgpHZW06OlNwZWNpZmljYXRpb24ubmV3IGRvIHxzfAogIHMubmFtZSA9ICJ1biIuZnJlZXplCiAgcy52ZXJzaW9uID0gIjAuMy4wIgoKICBzLnJlcXVpcmVkX3J1YnlnZW1zX3ZlcnNpb24gPSBHZW06OlJlcXVpcmVtZW50Lm5ldygiPj0gMCIuZnJlZXplKQogIHMucmVxdWlyZV9wYXRocyA9IFsibGliIi5mcmVlemVdCiAgcy5hdXRob3JzID0gWyJJcm9uUnVieSIuZnJlZXplXQogIHMuZGVzY3JpcHRpb24gPSAiVXRpbGl0aWVzIHRvIHJlcGxhY2UgY29tbW9uIFVOSVggY29tbWFuZHMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVXRpbGl0aWVzIHRvIHJlcGxhY2UgY29tbW9uIFVOSVggY29tbWFuZHMiLmZyZWV6ZQogIHMuaG9tZXBhZ2UgPSAiaHR0cHM6Ly9naXRodWIuY29tL0lyb25MYW5ndWFnZXMvaXJvbnJ1YnkiLmZyZWV6ZQogIHMubGljZW5zZXMgPSBbIlJ1YnkiLmZyZWV6ZSwgIkJTRC0yLUNsYXVzZSIuZnJlZXplXQogIHMuZmlsZXMgPSBbCiAgICAibGliL3VuLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/un-0.3.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHVyaSAxLjEuMSBydWJ5IGxpYgojCiMgR2VuZXJhdGVkIGJ5IFV0aWwvZ2VuLWRlZmF1bHQtZ2Vtc3BlY3MucmIuICBEbyBub3QgZWRpdCBieSBoYW5kLgoKR2VtOjpTcGVjaWZpY2F0aW9uLm5ldyBkbyB8c3wKICBzLm5hbWUgPSAidXJpIi5mcmVlemUKICBzLnZlcnNpb24gPSAiMS4xLjEiCgogIHMucmVxdWlyZWRfcnVieWdlbXNfdmVyc2lvbiA9IEdlbTo6UmVxdWlyZW1lbnQubmV3KCI+PSAwIi5mcmVlemUpCiAgcy5yZXF1aXJlX3BhdGhzID0gWyJsaWIiLmZyZWV6ZV0KICBzLmF1dGhvcnMgPSBbIklyb25SdWJ5Ii5mcmVlemVdCiAgcy5kZXNjcmlwdGlvbiA9ICJVUkkgaXMgYSBtb2R1bGUgcHJvdmlkaW5nIGNsYXNzZXMgdG8gaGFuZGxlIFVuaWZvcm0gUmVzb3VyY2UgSWRlbnRpZmllcnMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiVVJJIGlzIGEgbW9kdWxlIHByb3ZpZGluZyBjbGFzc2VzIHRvIGhhbmRsZSBVbmlmb3JtIFJlc291cmNlIElkZW50aWZpZXJzIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi91cmkucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL2NvbW1vbi5yYiIuZnJlZXplLAogICAgImxpYi91cmkvZmlsZS5yYiIuZnJlZXplLAogICAgImxpYi91cmkvZnRwLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9nZW5lcmljLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9odHRwLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS9odHRwcy5yYiIuZnJlZXplLAogICAgImxpYi91cmkvbGRhcC5yYiIuZnJlZXplLAogICAgImxpYi91cmkvbGRhcHMucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL21haWx0by5yYiIuZnJlZXplLAogICAgImxpYi91cmkvcmZjMjM5Nl9wYXJzZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvdXJpL3JmYzM5ODZfcGFyc2VyLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS92ZXJzaW9uLnJiIi5mcmVlemUsCiAgICAibGliL3VyaS93cy5yYiIuZnJlZXplLAogICAgImxpYi91cmkvd3NzLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/uri-1.1.1.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYWtyZWYgMC4xLjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYWtyZWYiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjEuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi93ZWFrcmVmLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/weakref-0.1.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYnNvY2tldC1kcml2ZXIgMC44LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYnNvY2tldC1kcml2ZXIiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIldlYlNvY2tldCBwcm90b2NvbCBoYW5kbGVyOyBXZWJTb2NrZXQ6Ok1hc2sgaW4gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiV2ViU29ja2V0IHByb3RvY29sIGhhbmRsZXI7IFdlYlNvY2tldDo6TWFzayBpbiBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL3dlYnNvY2tldF9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9jbGllbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9kcmFmdDc1LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvZHJhZnQ3Ni5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2V2ZW50X2VtaXR0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oZWFkZXJzLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvaHliaS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2h5YmkvZnJhbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oeWJpL21lc3NhZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9wcm94eS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3NlcnZlci5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3N0cmVhbV9yZWFkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAvaGVhZGVycy5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvaHR0cC9yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9odHRwL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC93ZWJzb2NrZXRfbWFzay5yYiIuZnJlZXplLAogIF0KCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCJ3ZWJzb2NrZXQtZXh0ZW5zaW9ucyIuZnJlZXplLCBbIj49IDAuMS4wIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/websocket-driver-0.8.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHlhbWwgMC40LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInlhbWwiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi95YW1sLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvZGJtLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvc3RvcmUucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/yaml-0.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID0oY29uZmlnKCkpCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lOjpDb3JlI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoxNTkgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvY29tcGxldGlvbicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbiwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgKGNvbmZpZygpKQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIpCiAgXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9hcHBlbmRfY2hhcmFjdGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXI9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9hcHBlbmRfY2hhcmFjdGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMpCiAgXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYmFzaWNfd29yZF9icmVha19jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnM9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6YmFzaWNfd29yZF9icmVha19jaGFyYWN0ZXJzPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uY29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycykKICBfLmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYmFzaWNfcXVvdGVfY2hhcmFjdGVycykKICBfLmJhc2ljX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YmFzaWNfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmJhc2ljX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzKQogIF8uY29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycykKICBfLmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uc3BlY2lhbF9wcmVmaXhlcykKICBfLnNwZWNpYWxfcHJlZml4ZXMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3NwZWNpYWxfcHJlZml4ZXMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3NwZWNpYWxfcHJlZml4ZXMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6c3BlY2lhbF9wcmVmaXhlcywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOnNwZWNpYWxfcHJlZml4ZXM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX3Byb2MpCiAgXy5jb21wbGV0aW9uX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcHJvYyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRpb25fcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2M9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9wcm9jPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLm91dHB1dF9tb2RpZmllcl9wcm9jKQogIF8ub3V0cHV0X21vZGlmaWVyX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI291dHB1dF9tb2RpZmllcl9wcm9jIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNvdXRwdXRfbW9kaWZpZXJfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpvdXRwdXRfbW9kaWZpZXJfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpvdXRwdXRfbW9kaWZpZXJfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByb21wdF9wcm9jKQogIF8ucHJvbXB0X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3Byb21wdF9wcm9jIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNwcm9tcHRfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpwcm9tcHRfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcm9tcHRfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYXV0b19pbmRlbnRfcHJvYykKICBfLmF1dG9faW5kZW50X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9faW5kZW50X3Byb2MgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2F1dG9faW5kZW50X3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YXV0b19pbmRlbnRfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmF1dG9faW5kZW50X3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vayguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByZV9pbnB1dF9ob29rKQogIF8ucHJlX2lucHV0X2hvb2soLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ByZV9pbnB1dF9ob29rIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNwcmVfaW5wdXRfaG9vaycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpwcmVfaW5wdXRfaG9vaywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vaz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcmVfaW5wdXRfaG9vaz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYykKICBfLmRpZ19wZXJmZWN0X21hdGNoX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmRpZ19wZXJmZWN0X21hdGNoX3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBpbnB1dD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDppbnB1dD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXQ9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6b3V0cHV0PSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy52aV9lZGl0aW5nX21vZGUpCiAgXy52aV9lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjdmlfZWRpdGluZ19tb2RlJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnZpX2VkaXRpbmdfbW9kZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5lbWFjc19lZGl0aW5nX21vZGUpCiAgXy5lbWFjc19lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW1hY3NfZWRpdGluZ19tb2RlJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVtYWNzX2VkaXRpbmdfbW9kZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZG11bHRpbGluZSkKICBfLnJlYWRtdWx0aWxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRtdWx0aWxpbmUgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRtdWx0aWxpbmUnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVhZG11bHRpbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnJlYWRsaW5lKQogIF8ucmVhZGxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRsaW5lIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNyZWFkbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fY2FzZV9mb2xkKQogIF8uY29tcGxldGlvbl9jYXNlX2ZvbGQoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fY2FzZV9mb2xkIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0aW9uX2Nhc2VfZm9sZCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX2Nhc2VfZm9sZCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0aW9uX2Nhc2VfZm9sZD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyKQogIF8uY29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlcicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1SZWxpbmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZGxpbmUpCiAgXy5yZWFkbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZGxpbmUgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjE1OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnJlYWRsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBnZXRfc2NyZWVuX3NpemUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5nZXRfc2NyZWVuX3NpemUpCiAgXy5nZXRfc2NyZWVuX3NpemUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2dldF9zY3JlZW5fc2l6ZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZ2V0X3NjcmVlbl9zaXplJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmdldF9zY3JlZW5fc2l6ZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPWxpbmVfZWRpdG9yCiAgICBpZiBkZWZpbmVkPyhfLmVvZj8pCiAgXy5lb2Y/KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNlb2Y/IGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNlb2Y/JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVvZj8sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5lb2Y/KQogIF8uZW9mPyguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjZW9mPyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW9mPycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDplb2Y/LCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBkZWxldGVfdGV4dCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5kZWxldGVfdGV4dCkKICBfLmRlbGV0ZV90ZXh0KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNkZWxldGVfdGV4dCBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZGVsZXRlX3RleHQnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGVsZXRlX3RleHQsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBsaW5lX2J1ZmZlciguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5saW5lKQogIF8ubGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjbGluZV9idWZmZXIgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL3JlbGluZS5yYjo0NjggZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmxpbmUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwb2ludCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5ieXRlX3BvaW50ZXIpCiAgXy5ieXRlX3BvaW50ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3BvaW50IGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDY5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYnl0ZV9wb2ludGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJ5dGVfcG9pbnRlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwb2ludD0oLi4uKQogICAgbGluZV9lZGl0b3IKICAgIC5fX3NlbmRfXyg6Ynl0ZV9wb2ludGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWRpc3BsYXkoLi4uKQogICAgXyA9bGluZV9lZGl0b3IKICAgIGlmIGRlZmluZWQ/KF8ucmVyZW5kZXIpCiAgXy5yZXJlbmRlciguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVkaXNwbGF5IGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDc4IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVyZW5kZXInLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVyZW5kZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8udmlfZWRpdGluZ19tb2RlPykKICBfLnZpX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3ZpX2VkaXRpbmdfbW9kZT8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6dmlfZWRpdGluZ19tb2RlPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZW1hY3NfZWRpdGluZ19tb2RlPykKICBfLmVtYWNzX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2VtYWNzX2VkaXRpbmdfbW9kZT8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZW1hY3NfZWRpdGluZ19tb2RlPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhbWJpZ3VvdXNfd2lkdGgoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hbWJpZ3VvdXNfd2lkdGgpCiAgXy5hbWJpZ3VvdXNfd2lkdGgoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FtYmlndW91c193aWR0aCBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYW1iaWd1b3VzX3dpZHRoJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmFtYmlndW91c193aWR0aCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmxhc3RfaW5jcmVtZW50YWxfc2VhcmNoKQogIF8ubGFzdF9pbmNyZW1lbnRhbF9zZWFyY2goLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2xhc3RfaW5jcmVtZW50YWxfc2VhcmNoIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNsYXN0X2luY3JlbWVudGFsX3NlYXJjaCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpsYXN0X2luY3JlbWVudGFsX3NlYXJjaCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhZGRfZGlhbG9nX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hZGRfZGlhbG9nX3Byb2MpCiAgXy5hZGRfZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FkZF9kaWFsb2dfcHJvYyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYWRkX2RpYWxvZ19wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmFkZF9kaWFsb2dfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBkaWFsb2dfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmRpYWxvZ19wcm9jKQogIF8uZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpYWxvZ19wcm9jIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNkaWFsb2dfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpkaWFsb2dfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvY29tcGxldGlvbicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbiwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5yZWFkbXVsdGlsaW5lKQogIF8ucmVhZG11bHRpbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZG11bHRpbGluZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVhZG11bHRpbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbXVsdGlsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"c2VsZg==","encoding":"UTF-8","path":"(eval at ${ROOT}/Src/StdLib/ruby/4.0/irb/workspace.rb:71)","line":1,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":[],"moduleNames":[],"module":null} From 8092170a156dc9c9576ffd04b9674af9d0194464 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:12:16 +0000 Subject: [PATCH 250/439] Carry a match sink's $~ in the frame's own sink; turn the sink on e29424d kept the sink sound but off: its hand-over - a stack of sink scopes per thread, entered, left and taken on every call, with a fault block in the rule - cost about what the late scope it replaces did. Now the light frame takes a sink (a RubyTopLevelScope that holds nothing but $~) from the thread's free ones at its first call that stores $~, passes it as the scope argument of those sites, and gives it back, cleared, in the finally it already has. The rule is the plain light rule: MetaScope is the argument (CallArguments.MatchSink), with no helper call, thread static or fault block per call. A late scope starts with the sink's $~; once the frame has its scope the site makes the ordinary call. BindPrecompiled leaves sink sites to the rule and they share no rules, so refinements are still read from a real scope (LightScopeRequired). The matrix found that a TracePoint :return hook runs after the finally; the finally now makes the scope from the sink first when one is enabled. Callgrind, switch off / on: gsub 0.982, split 0.977, kase 0.978, eqt 0.955, controls 1.000. ab.rb -r 10 on a quiet machine: gsub 0.89, split 0.89, eqt 0.90, kase 0.90 (overlapping), controls overlap. So IR_LIGHT_MATCH_SINK is on unless set to 0: +559 light frames in the census, none lost. Checked: light-match-sink (new row 13: raise after the match, Fibers suspended in match sinks), regex-light, light-entry, hot-shapes, block-pass and jit match CRuby in the gate's six modes and with the switch off, with and without the JIT; specs language/predefined, core/regexp and the String matching methods as the base; 76 named IronRuby.Tests (Debug) pass with the switch on and off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/IronRuby.Tests/Runtime/MiscTests.cs | 12 +-- .../Ast/Definitions/MethodDefinition.cs | 70 ++++++++---- Src/Ruby/Runtime/Calls/CallArguments.cs | 18 +--- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 28 ++--- Src/Ruby/Runtime/Calls/RubyCallSignature.cs | 4 +- Src/Ruby/Runtime/RubyOps.MatchSink.cs | 100 +++++++----------- Util/light-match-sink-matrix.rb | 26 ++++- Util/perf/LEDGER.md | 41 ++++++- 8 files changed, 170 insertions(+), 129 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index f03cfd80e..2f519ffc7 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8178,10 +8178,9 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters } /// - /// IR_LIGHT_MATCH_SINK=1 (off by default: run the test with it set to exercise it): a light frame whose regex literals - /// go to String and Regexp methods that store $~, in a method that reads no $~ of its own (MethodDefinition.IsMatchSink): - /// the caller's $~ is left as it was, in its thread too; a method that reads its $~ ($~, Regexp.last_match, binding) - /// sees its match. + /// IR_LIGHT_MATCH_SINK: a light frame whose regex literals go to String and Regexp methods that store $~, in a method + /// that reads no $~ of its own (MethodDefinition.IsMatchSink): the caller's $~ is left as it was, in its thread too; a + /// method that reads its $~ ($~, Regexp.last_match, binding) sees its match. /// public void Method_LightFrameMatchSink1() { TestOutput(@" @@ -8221,9 +8220,8 @@ p th.value } /// - /// IR_LIGHT_MATCH_SINK=1 (off by default: run the test with it set to exercise it): the match a light frame's String - /// call stores is the frame's alone (RubyOps.TakeMatchSink): once the frame has returned nothing keeps it, or the String - /// it matched in - not a scope the runtime shares. + /// IR_LIGHT_MATCH_SINK: the match a light frame's String call stores is the frame's alone (RubyOps.TakeMatchSink): once + /// the frame has returned nothing keeps it, or the String it matched in - its sink is cleared as it is given back. /// public void Method_LightFrameMatchSinkRetention1() { TestOutput(@" diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index c83f16a64..5fb30e2d2 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -341,7 +341,7 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin Ast.Return(gen.ReturnLabel, Methods.GetMethodUnwinderReturnValue.OpCall(unwinder)) ).Finally( // leave frame: - (light != null) ? Methods.LeaveLightMethodFrame.OpCall(light.Rfc, scopeVariable) : Methods.LeaveMethodFrame.OpCall(scopeVariable), + (light != null) ? LeaveLightFrame(light, scopeVariable) : Methods.LeaveMethodFrame.OpCall(scopeVariable), Ast.Empty(), profileEnd ); @@ -635,14 +635,13 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { }; /// - /// IR_LIGHT_MATCH_SINK=1 lets a method whose regex literal goes to a method that stores $~ into light frames if nothing in - /// it reads its $~ (see IsMatchSink). Off by default: the frame's $~ handed from a sink scope of the thread's to a CLR - /// variable costs about what the scope made on demand did (Util/perf/LEDGER.md, perf/lightmatch). + /// IR_LIGHT_MATCH_SINK=0 keeps a method whose regex literal goes to a method that stores $~ out of light frames, as before + /// (see IsMatchSink). /// - internal static readonly bool LightMatchSinkEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_MATCH_SINK") == "1"; + internal static readonly bool LightMatchSinkEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_MATCH_SINK") != "0"; // The names of RegexScopeMethods that String, Symbol and Regexp define (RubyCallAction.IsMatchSinkMethod): a light site - // of one in a method that is a match sink stores $~ in a sink scope (RubyCallFlags.HasMatchSink). + // of one in a method that is a match sink stores $~ in the frame's sink (RubyCallFlags.HasMatchSink). private static readonly HashSet/*!*/ MatchSinkMethods = new HashSet { "=~", "===", "match", "gsub", "gsub!", "sub", "sub!", "scan", "split", "index", "rindex", "byteindex", "byterindex", "[]", "[]=", "slice", "slice!", "start_with?", "partition", "rpartition", @@ -671,10 +670,11 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// `$~', `$&', `$1', Regexp.last_match or other reference to it, no block or lambda (whose binding a callee may be given), /// no binding, string eval or call made by name (MatchObserverMethods), no global but the runtime's own /// (MatchSinkGlobals: `alias $m $~' makes `$m' the frame's $~). Such a method's light frame lets the String, Symbol and - /// Regexp methods it calls store $~ in a sink scope of the thread's, from which the frame takes it into a CLR variable - /// (RubyCallFlags.HasMatchSink, RubyOps.TakeMatchSink), where it would otherwise make its scope for them on every call - /// and call them again (gap 16 of Util/perf/LEDGER.md). A scope the frame makes later gets that $~, for a TracePoint's - /// binding; $~ after the method returns is its caller's, as in CRuby. + /// Regexp methods it calls store $~ in a sink of the frame's own, a scope that holds nothing else, taken from the thread's + /// free ones at the first such call and given back as the frame returns (RubyCallFlags.HasMatchSink, RubyOps.TakeMatchSink), + /// where the frame would otherwise make its scope for them on every call and call them again (gap 16 of + /// Util/perf/LEDGER.md). A scope the frame makes later gets that $~, for a TracePoint's binding; $~ after the method + /// returns is its caller's, as in CRuby. /// private bool IsMatchSink() { if (!LightMatchSinkEnabled || !LightRegexEnabled) { @@ -728,6 +728,8 @@ private sealed class LightFrame { internal MSA.Expression/*!*/ MakeScope; internal Func/*!*/ MakeScopeIfTraced; internal MSA.Expression/*!*/ Name; + // The frame's sink (RubyOps.TakeMatchSink) if it is a match sink, given back as it returns. + internal MSA.ParameterExpression MatchSink; /// /// Replaces CreateMethodScope: the locals, the safe point and the call's flow-control frame, the alias @@ -1684,8 +1686,10 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ light.MakeScopeIfTraced = locals => make(Methods.CreateMethodScopeIfTraced, locals); var inLoop = scope.DefineHiddenVariable("#in-loop", typeof(bool)); bool blockLiterals = LightBlocksEnabled && HasLightBlockLiteral(); - // A match sink keeps its $~ in a CLR variable and puts it into the scope it makes on demand (RubyOps.TakeMatchSink). - var matchSlot = (!blockLiterals && IsMatchSink()) ? scope.DefineHiddenVariable("#match", typeof(MatchData)) : null; + // A match sink keeps its $~ in a sink scope of its own, taken at its first call that stores $~, and puts it into the + // scope it makes on demand (RubyOps.TakeMatchSink, SeedLightScopeMatch); it gives the sink back as it returns. + var matchSlot = (!blockLiterals && IsMatchSink()) ? scope.DefineHiddenVariable("#sink", typeof(RubyScope)) : null; + light.MatchSink = matchSlot; MSA.Expression lateScope = Ast.Call(_LightScopeInLoop, light.MakeScope, inLoop); if (matchSlot != null) { lateScope = Ast.Call(_SeedLightScopeMatch, lateScope, matchSlot); @@ -1735,6 +1739,30 @@ private static object ConstantValue(MSA.Expression/*!*/ node) { private static readonly MethodInfo/*!*/ _LightScopeInLoop = typeof(RubyOps).GetMethod("LightScopeInLoop"); private static readonly MethodInfo/*!*/ _SeedLightScopeMatch = typeof(RubyOps).GetMethod("SeedLightScopeMatch"); private static readonly MethodInfo/*!*/ _TakeMatchSink = typeof(RubyOps).GetMethod("TakeMatchSink"); + private static readonly MethodInfo/*!*/ _ReturnMatchSink = typeof(RubyOps).GetMethod("ReturnMatchSink"); + + private static MSA.Expression/*!*/ LeaveLightFrame(LightFrame/*!*/ light, MSA.ParameterExpression/*!*/ scopeVariable) { + MSA.Expression leave = Methods.LeaveLightMethodFrame.OpCall(light.Rfc, scopeVariable); + if (light.MatchSink == null) { + return leave; + } + // A TracePoint's :return hook runs after this (TraceReturnExpression) and may make the scope then: it is made now, + // with the sink's $~, before the sink is given back. + return Ast.IfThenElse(Ast.NotEqual(light.MatchSink, AstUtils.Constant(null, typeof(RubyScope))), + Ast.Block( + Ast.IfThen( + Ast.NotEqual( + Ast.And(Ast.Field(null, typeof(TracePoint).GetField("ActiveEvents")), AstUtils.Constant((int)TraceEvents.Return)), + AstUtils.Constant(0) + ), + Ast.Block(light.LazyScope, AstUtils.Empty()) + ), + leave, + Ast.Call(_ReturnMatchSink, light.MatchSink) + ), + leave + ); + } private static readonly MethodInfo/*!*/ _EnterLightLoop = typeof(RubyOps).GetMethod("EnterLightLoop"); private static readonly MethodInfo/*!*/ _LeaveLightLoop = typeof(RubyOps).GetMethod("LeaveLightLoop"); @@ -1758,8 +1786,8 @@ internal sealed class LightFrameRewriter : MSA.ExpressionVisitor { // makes none. The scope made on demand has the frame's locals (its tuple, made from the register locals if those are // used), self, block and flow-control frame, which is all the block and the call read from it. internal bool BlockLiterals; - // The frame's $~ when nothing in it reads $~ (IsMatchSink), null otherwise: a light site of one of MatchSinkMethods has - // RubyCallFlags.HasMatchSink, and the frame takes the match its call stored into this variable (MakeLightCall). + // The frame's sink when nothing in it reads $~ (IsMatchSink), null otherwise: a light site of one of MatchSinkMethods has + // RubyCallFlags.HasMatchSink and is given the sink as its scope (MakeLightCall). internal MSA.ParameterExpression MatchSlot; // see LightFrame.MakesCalls @@ -2321,7 +2349,13 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres temps[0] = result; MakesCalls = true; // (a LightDynamicExpression takes its builder's arguments: each site gets a copy) - var sinkLightArgs = matchSink ? new AstExpressions(lightArgs) : null; + AstExpressions sinkLightArgs = null; + if (matchSink) { + // the frame's sink, taken at its first such call (RubyOps.TakeMatchSink), in place of the declaring scope + sinkLightArgs = new AstExpressions(lightArgs); + sinkLightArgs[0] = Ast.Coalesce(MatchSlot, Ast.Assign(MatchSlot, + Ast.Call(_TakeMatchSink, AstUtils.Convert(_declaringScope, typeof(RubyScope))))); + } var sinkFullArgs = matchSink ? new AstExpressions(fullArgs) : null; var sinkLateArgs = matchSink ? new AstExpressions(fullArgs) : null; body.Add(Ast.Assign(result, AstUtils.LightDynamic(lightAction, typeof(object), lightArgs))); @@ -2332,8 +2366,8 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres } MSA.Expression value = Ast.Condition(needsScope, AstUtils.LightDynamic(action, typeof(object), fullArgs), result); if (matchSink) { - // The light call stored $~ in a sink scope, and the frame takes it (RubyOps.TakeMatchSink). Once the frame has - // its scope, the call stores $~ there, as an ordinary one does. + // The light call stores $~ in the frame's sink. Once the frame has its scope, the call stores $~ there, as an + // ordinary one does. body.RemoveAt(body.Count - 1); value = Ast.Condition( Ast.NotEqual(_scope, AstUtils.Constant(null, _scope.Type)), @@ -2342,7 +2376,7 @@ private MSA.Expression LightSuperCall(Microsoft.Scripting.Ast.LightDynamicExpres Ast.Assign(result, AstUtils.LightDynamic(lightAction, typeof(object), sinkLightArgs)), Ast.Condition(needsScope, AstUtils.LightDynamic(action, typeof(object), sinkLateArgs), - Ast.Block(Ast.Assign(MatchSlot, Ast.Call(_TakeMatchSink, MatchSlot)), result) + result ) ) ); diff --git a/Src/Ruby/Runtime/Calls/CallArguments.cs b/Src/Ruby/Runtime/Calls/CallArguments.cs index b31d7b4b1..13d63df0a 100644 --- a/Src/Ruby/Runtime/Calls/CallArguments.cs +++ b/Src/Ruby/Runtime/Calls/CallArguments.cs @@ -91,16 +91,10 @@ public int SimpleArgumentCount { /// /// Set by RubyCallAction.BuildCall at a site with RubyCallFlags.HasMatchSink once the method is resolved and is one that - /// takes the scope only to store $~ (RubyCallAction.IsMatchSinkMethod): the scope the rule gives it is then a sink scope - /// of the thread's (RubyOps.EnterMatchSink, in MatchSinkVariable), and reading it is not reading the frame's. + /// takes the scope only to store $~ (RubyCallAction.IsMatchSinkMethod): the scope argument is then the frame's sink + /// (RubyOps.TakeMatchSink), which the method is given, and reading it is not reading the frame's scope. /// internal bool MatchSink; - private DynamicMetaObject _sinkScope; - - // The rule's variable for the sink scope, null if the method did not read the scope. - internal ParameterExpression MatchSinkVariable { - get { return (_sinkScope != null) ? (ParameterExpression)_sinkScope.Expression : null; } - } /// /// The scope argument's expression, for a helper that takes the scope only for its runtime (GetInstanceVariable, @@ -113,12 +107,8 @@ internal Expression/*!*/ ContextScopeExpression { public DynamicMetaObject/*!*/ MetaScope { get { if (MatchSink) { - if (_sinkScope == null) { - // (the value is for nothing but the binder's questions, which a sink scope answers as the empty one does) - var empty = ((RubyContext)_context.Value).EmptyScope; - _sinkScope = new DynamicMetaObject(Ast.Variable(typeof(RubyScope), "#sink"), BindingRestrictions.Empty, empty); - } - return _sinkScope; + Debug.Assert(_scope != null && _signature.HasScope); + return _scope; } if (_signature.HasLightScope) { ScopeRead = true; diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 288932abb..bfd46c5b6 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -139,6 +139,12 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ return null; } + // A site with RubyCallFlags.HasMatchSink passes the frame's sink, not even the declaring scope: what the call would + // read of the scope (refinements) is left to the rule, which then answers RubyOps.LightScopeRequired. + if (Signature.HasMatchSink) { + return null; + } + // Nor can it hold RubyMethodInfo.BuildCallNoFlow's unmarking of a keyword-arguments // hash handed to a method that declares no keywords. A call site's syntax decides // whether it passes keywords, so seeing one here means every call at this site @@ -372,7 +378,7 @@ internal SharedRule(RubyMemberInfo/*!*/ member, bool isMissing, Type/*!*/ target private const RubyCallFlags SharableCallFlags = RubyCallFlags.HasScope | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasBlock | RubyCallFlags.HasImplicitSelf | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSourceBlock | - RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasMatchSink; + RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat; private static readonly object _SharedRulesLock = new object(); private SharedRule[] _sharedRules; @@ -777,21 +783,6 @@ private static bool BuildCall(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ me } method.Info.BuildCall(metaBuilder, args, methodName); - // The method stores $~ in a sink scope of the thread's, and the frame takes it from there (RubyOps.EnterMatchSink). - var sink = args.MatchSink ? args.MatchSinkVariable : null; - if (sink != null && !metaBuilder.Error && metaBuilder.Result != null) { - var result = Ast.Variable(typeof(object), "#result"); - metaBuilder.Result = Ast.Block(new[] { sink, result }, - Ast.Assign(sink, Ast.Call(_EnterMatchSink, AstUtils.Convert(args.MetaContext.Expression, typeof(RubyContext)))), - Ast.TryFault( - Ast.Assign(result, AstUtils.Convert(metaBuilder.Result, typeof(object))), - Ast.Call(_AbortMatchSink) - ), - Ast.Call(_LeaveMatchSink), - result - ); - } - // MRI 3.4+: a block passed to a method that never uses it may be ignored if (args.Signature.HasSourceBlock && RequiresUnusedBlockCheck(method.Info) && !metaBuilder.Error && metaBuilder.Result != null) { metaBuilder.Result = Ast.Block( @@ -989,7 +980,7 @@ private static MethodResolutionResult ResolveOwnClrMember(MetaObjectBuilder/*!*/ /// A library method of String, Symbol or Regexp (MutableStringOps, SymbolOps, RubyRegexOps): one that takes its caller's /// scope to store $~ in it and for the runtime, and for nothing else - not to resolve a call it makes, which goes through /// a site of its own without the caller's refinements, as CRuby's rb_funcall does. A site with RubyCallFlags.HasMatchSink - /// gives it a sink scope of the thread's (CallArguments.MatchSink). Not while c_call is traced: the rule then reports the + /// gives it the frame's sink, its scope argument (CallArguments.MatchSink). Not while c_call is traced: the rule then reports the /// call with the caller's scope (RubyLibraryMethodInfo.AddCallTracing), and switching tracing rebinds every rule. /// internal static bool IsMatchSinkMethod(RubyContext/*!*/ context, RubyMemberInfo/*!*/ method) { @@ -1011,9 +1002,6 @@ internal static bool IsMatchSinkMethod(RubyContext/*!*/ context, RubyMemberInfo/ return true; } - private static readonly MethodInfo/*!*/ _EnterMatchSink = typeof(RubyOps).GetMethod("EnterMatchSink"); - private static readonly MethodInfo/*!*/ _LeaveMatchSink = typeof(RubyOps).GetMethod("LeaveMatchSink"); - private static readonly MethodInfo/*!*/ _AbortMatchSink = typeof(RubyOps).GetMethod("AbortMatchSink"); internal static MethodResolutionResult Resolve(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ methodName, CallArguments/*!*/ args, out RubyMemberInfo methodMissing) { diff --git a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs index e944fd96f..0d8e04dcd 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs @@ -80,8 +80,8 @@ public enum RubyCallFlags { // CallAction only, with HasLightScope: a call in a method that runs without its scope and that nothing in its body // reads $~ of (MethodDefinition.IsMatchSink). A library method of String, Symbol or Regexp, which takes the scope only to - // store $~ in it and for its runtime, is then given a sink scope of the thread's instead of reading the frame's - // (CallArguments.MatchSink, RubyOps.EnterMatchSink), and the frame takes the match from it and makes no scope. + // store $~ in it and for its runtime, is then given the scope argument, which is the frame's sink - a scope that holds + // nothing but $~ (RubyOps.TakeMatchSink) - instead of reading the frame's scope (CallArguments.MatchSink). HasMatchSink = 4096, } diff --git a/Src/Ruby/Runtime/RubyOps.MatchSink.cs b/Src/Ruby/Runtime/RubyOps.MatchSink.cs index 4dfbcdff9..c1b4a786d 100644 --- a/Src/Ruby/Runtime/RubyOps.MatchSink.cs +++ b/Src/Ruby/Runtime/RubyOps.MatchSink.cs @@ -20,85 +20,61 @@ namespace IronRuby.Runtime { /// /// The $~ of a light frame that makes no scope for its String, Symbol and Regexp calls (RubyCallFlags.HasMatchSink, - /// MethodDefinition.IsMatchSink). The rule of such a call gives the library method a scope of the thread's own to store - /// $~ in (EnterMatchSink), and hands what it stored to the frame when it returns (LeaveMatchSink); the frame keeps it in a - /// CLR local (TakeMatchSink) and puts it into its scope if one is made later (SeedLightScopeMatch) - for a TracePoint's - /// binding, say. So $~ is the frame's, as in CRuby, and nothing shared holds a match: the sink scopes are cleared as they - /// are left. A stack, because a library method may run Ruby code after it has stored $~ (`sub(re, hash)' calls the - /// hash's default proc), and that code's own calls must not take the match of the call that is still running. + /// MethodDefinition.IsMatchSink): a scope of its own that holds nothing but $~ - its sink - which the frame takes at its + /// first such call from the thread's free sinks (TakeMatchSink), gives those calls as their scope, and gives back when it + /// returns (ReturnMatchSink, which clears it). The library method stores $~ in it; a scope the frame makes later starts with + /// it (SeedLightScopeMatch) - for a TracePoint's binding, say. So $~ is the frame's, as in CRuby; nothing shared holds a + /// match; and a call costs no more than the light call it is, the frame two reads of a thread static. /// public static partial class RubyOps { - // stored in a sink scope when it is entered: a store by the library method replaces it - private static readonly MatchData MatchSinkUnset = new MatchData(); + private const int MaxFreeMatchSinks = 8; - // A thread's sink scopes, one per call in progress, and what the last call left stored until the frame that made it - // takes it (MatchSinkUnset if nothing, or taken). One object, so that each helper reads one thread static. - private sealed class MatchSinkState { - internal RubyTopLevelScope[] Sinks = new RubyTopLevelScope[4]; - internal int Depth; - internal MatchData Taken = MatchSinkUnset; + // A thread's sinks not taken by a frame. A list, not a stack: a frame that never returns (a Fiber left suspended) only + // takes one out of it. + private sealed class MatchSinkPool { + internal readonly RubyTopLevelScope[] Free = new RubyTopLevelScope[MaxFreeMatchSinks]; + internal int Count; } [ThreadStatic] - private static MatchSinkState t_matchSink; + private static MatchSinkPool t_matchSinks; - public static RubyScope/*!*/ EnterMatchSink(RubyContext/*!*/ context) { - var state = t_matchSink ?? (t_matchSink = new MatchSinkState()); - int depth = state.Depth; - var sinks = state.Sinks; - if (depth == sinks.Length) { - Array.Resize(ref sinks, depth * 2); - state.Sinks = sinks; - } - var sink = sinks[depth]; - // several runtimes may run on a thread: a sink scope is the runtime's whose methods it is given to - if (sink == null || sink.RubyContext != context) { - sinks[depth] = sink = new RubyTopLevelScope(context); + /// + /// A sink for a light frame of the runtime of , the frame's declaring scope. + /// + public static RubyScope/*!*/ TakeMatchSink(RubyScope/*!*/ declaringScope) { + var context = declaringScope.RubyContext; + var pool = t_matchSinks; + if (pool != null && pool.Count > 0) { + int i = --pool.Count; + var sink = pool.Free[i]; + pool.Free[i] = null; + // several runtimes may run on a thread: a sink is the runtime's whose methods it is given to + if (sink.RubyContext == context) { + return sink; + } } - sink.CurrentMatch = MatchSinkUnset; - state.Depth = depth + 1; - return sink; - } - - public static void LeaveMatchSink() { - var state = t_matchSink; - var sink = state.Sinks[--state.Depth]; - state.Taken = sink.CurrentMatch; - sink.CurrentMatch = null; - } - - // the call raised: what it stored is no frame's - public static void AbortMatchSink() { - var state = t_matchSink; - state.Sinks[--state.Depth].CurrentMatch = null; - state.Taken = MatchSinkUnset; + return new RubyTopLevelScope(context); } /// - /// The frame's $~ after a call of its light site with RubyCallFlags.HasMatchSink: what the call stored, or - /// if it stored nothing (a method of the program's own, a library method that did not - /// match: CRuby leaves the caller's $~ then too). + /// Called as the frame that took returns: its $~ is no one's any more. /// - public static MatchData TakeMatchSink(MatchData previous) { - var state = t_matchSink; - if (state == null) { - // the thread has entered no sink: nothing was stored - return previous; - } - var match = state.Taken; - if (ReferenceEquals(match, MatchSinkUnset)) { - return previous; + public static void ReturnMatchSink(RubyScope/*!*/ sink) { + var top = (RubyTopLevelScope)sink; + top.CurrentMatch = null; + var pool = t_matchSinks ?? (t_matchSinks = new MatchSinkPool()); + if (pool.Count < MaxFreeMatchSinks) { + pool.Free[pool.Count++] = top; } - state.Taken = MatchSinkUnset; - return match; } /// - /// The scope a light frame that is a match sink makes on demand, given the frame's $~. + /// The scope a light frame that is a match sink makes on demand, given the $~ of its sink (null if it has taken none). /// - public static RubyMethodScope/*!*/ SeedLightScopeMatch(RubyMethodScope/*!*/ scope, MatchData match) { - if (match != null) { - scope.CurrentMatch = match; + public static RubyMethodScope/*!*/ SeedLightScopeMatch(RubyMethodScope/*!*/ scope, RubyScope sink) { + if (sink != null) { + scope.CurrentMatch = ((RubyTopLevelScope)sink).CurrentMatch; } return scope; } diff --git a/Util/light-match-sink-matrix.rb b/Util/light-match-sink-matrix.rb index e90707975..ff02b42eb 100644 --- a/Util/light-match-sink-matrix.rb +++ b/Util/light-match-sink-matrix.rb @@ -1,6 +1,6 @@ # Differential matrix for the frame-local $~ of a method that runs in a light frame and gives a regex to a String, # Symbol or Regexp method that stores $~ (MethodDefinition.IsMatchSink, RubyCallFlags.HasMatchSink, -# IR_LIGHT_MATCH_SINK=1, off by default). CRuby's rules, which each row checks: +# IR_LIGHT_MATCH_SINK). CRuby's rules, which each row checks: # # - $~ is the frame's own: a method's match does not set its caller's $~, and leaves it as it was (nil or a match); # - a block sees its method's $~ (and sets it), a lambda too; @@ -11,15 +11,15 @@ # rpartition, byteindex and their bang forms sets $~ (or clears it on no match); # - a method calling String#=~ with an object of its own: that object's =~ runs in its own frame. # -# A method that nothing in reads its $~ keeps it in a CLR variable of its light frame, and puts it into the scope if one is -# made later (RubyOps.TakeMatchSink); rows 8-11 are about that. +# A method that nothing in reads its $~ keeps it in a sink of its light frame's own, and puts it into the scope if one is +# made later (RubyOps.TakeMatchSink); rows 8-13 are about that. # # Every method is called hot (N times) so that its sites are bound and compiled, then once more for the row. -# Run under CRuby and ./ir.sh (JIT on and off, light frames off, the switch on) and diff: +# Run under CRuby and ./ir.sh (JIT on and off, light frames off, the switch off) and diff: # # ruby Util/light-match-sink-matrix.rb > /tmp/mri.txt # ./ir.sh Util/light-match-sink-matrix.rb > /tmp/ir.txt && diff /tmp/mri.txt /tmp/ir.txt -# IR_LIGHT_MATCH_SINK=1 ./ir.sh Util/light-match-sink-matrix.rb > /tmp/on.txt && diff /tmp/mri.txt /tmp/on.txt +# IR_LIGHT_MATCH_SINK=0 ./ir.sh Util/light-match-sink-matrix.rb > /tmp/off.txt && diff /tmp/mri.txt /tmp/off.txt # # Every row must match, and the last line be `end'. @@ -272,4 +272,20 @@ class ProtMatcher end row "12. String#=~ with a private =~", [hot { (S.eqt_obj(STR, PrivMatcher.new) rescue $!.class) }, (S.eqt_obj(STR, ProtMatcher.new) rescue $!.class)] +# 13. a method that raises after its match, and methods suspended in Fibers between matches: each frame's $~ its own +class Raiser + def boom(s); s.sub(/b+/, ""); raise ArgumentError, s; end + def fib(s, t); a = s.index(/b+/); Fiber.yield a; b = t.index(/c/); [a, b]; end +end +rz = Raiser.new +r = [hot { (rz.boom(STR) rescue $!.message) }, ("zz" =~ /z/; (rz.boom(STR) rescue nil); $~ && $~[0])] +f1 = Fiber.new { rz.fib("abbc", "xc") } +f2 = Fiber.new { rz.fib("bb", "ccc") } +r << f1.resume << f2.resume << f1.resume << f2.resume +seen = [] +tp4 = TracePoint.new(:raise) { |t| seen << t.binding.eval("$~ && $~[0]") if t.method_id == :boom } +tp4.enable { rz.boom(STR) rescue nil } +r << seen +row "13. raise after the match, Fibers", r + puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index fbb293a44..f04a79ec0 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1169,7 +1169,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has **perf/lightmatch** took the methods that cannot observe their `$~` (no reference, block, binding or eval): the call stores it in a sink scope of the thread's and the frame keeps it in a CLR variable, making neither (+559 light frames); but that hand-over costs about what it saves (0.97-1.03 of the instructions), so it is off by default - (`IR_LIGHT_MATCH_SINK=1`). The methods that read their `$~` or have blocks are what is left either way. + (`IR_LIGHT_MATCH_SINK=1`). **perf/sinkcarrier** made the frame's own sink the site's scope argument (0.955-0.982 + of the instructions, 0.89-0.90 of the time) and turned it on. The methods that read their `$~` or have blocks are + what is left. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per site at start-up, 0.2-0.4 ms). TruffleRuby's `Primitive.x` is replaced at parse time. @@ -1905,6 +1907,43 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/sinkcarrier (2026-11-28) - the frame's own sink carries a match sink's `$~`: `IR_LIGHT_MATCH_SINK` on by + default (gap 16, the `$~` family)** - not gated. perf/lightmatch (below) was sound but off: its hand-over (a stack + of sink scopes per thread, entered, left and taken on every call, with a fault block in the rule) cost about what + the late scope did. + - The carrier: the frame's sink - a RubyTopLevelScope that holds nothing but `$~` - is the light site's scope + argument. The frame takes it from the thread's free sinks at its first such call (`RubyOps.TakeMatchSink`, one + read of a thread static), passes it to every sink site, and gives it back, cleared, in the finally it already has + (`ReturnMatchSink`). The library method stores `$~` in it; the rule is the plain light rule, whose `MetaScope` is + the argument (`CallArguments.MatchSink`): no helper, no thread static, no fault block per call. The sink is the + frame's `$~` for as long as it runs; a scope made late starts with it (`SeedLightScopeMatch`), and once the frame + has its scope the site makes the ordinary call. A free list, not a stack, so a frame suspended in a Fiber only + takes one out. A rule that reads the scope for anything else (a refinement of the name, a method that is not + one of MutableStringOps', SymbolOps' or RegexpOps' sink methods) answers LightScopeRequired as any light site's; + `BindPrecompiled` leaves sink sites to the rule (a dispatcher would resolve refinements from the sink), and + they share no rules. + - Found by the matrix on the way: a TracePoint's :return hook runs after the frame's finally + (TraceReturnExpression), where the sink had been given back; the finally now makes the scope first, from the + sink, when a :return hook is enabled. + - Instructions (`Util/perf/callgrind/count.sh`, regex-shapes, N=20000; switch off / on): gsub 12,642 / 12,410 + (0.982), split 10,826 / 10,574 (0.977), kase 8,522 / 8,333 (0.978), eqt 5,718 / 5,460 (0.955); size and tilde + 1.000, matchp 0.989. (perf/lightmatch's EmptyScope form, unsound: 0.93-0.97; its thread-stack form 0.97-1.03.) + Time (`ab.rb -r 10`, load about 1, off / on, ns): gsub 426 / 380 (0.89), split 359 / 320 (0.89), eqt 208 / 186 + (0.90), kase 253 / 227 (0.90, spreads overlap); size, tilde and matchp overlap. + - Census (Src/StdLib + AWFY, 28,377 methods; against 540bdb0 + e29424d, where the switch is off): light frames + 26,732 -> 27,291 (+559, 94.2% -> 96.2%), none down; the JIT's counts unchanged. + - Checks: `Util/light-match-sink-matrix.rb` with a new row 13 (a method that raises after its match, seen by a + TracePoint :raise; two Fibers suspended inside match sinks), rows 10 and 11 as before; regex-light, light-entry, + hot-shapes, block-pass and jit: CRuby's output as built, -X:NoJIT, -X:NoJITCalls, IR_LIGHT_FRAMES=0, + IR_PARKED_SCOPES=0, the R2R host and the switch off with and without the JIT, on both trees (47 same; regex-light + under R2R as on base). ruby/spec language/predefined, core/regexp, core/string gsub/sub/scan/split/match/index/ + slice/partition/start_with?: 776 examples, the same three conversion-message errors as the base. + IronRuby.Tests (Debug): Method_LightFrameMatchSink1, Method_LightFrameMatchSinkRetention1 (0 of 8 subjects alive + after GC) and 74 other light-frame, regex, String, Symbol, TracePoint and Fiber tests pass with the switch on and + off; the whole suite was not run. + - Not fixed, found on the way: IronRuby reports no TracePoint :return for a method left by an exception (CRuby + does), with or without the switch. + - **perf/lightmatch (2026-11-27) - a light frame keeps its `$~` in a CLR variable for its String and Regexp calls (gap 16, the `$~` family): off by default, `IR_LIGHT_MATCH_SINK=1`** - not gated. Chosen by the census of c1045a0: the regex lines were its largest refusal (gsub 273, `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54). From b377c9578a398ae620b1d8969073182237bcc53b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:12:27 +0000 Subject: [PATCH 251/439] instance_eval/class_eval of a string share the caller's $~ and $_ $~ and $_ (and with them $1, $`, $' ...) are local to a method's frame in MRI, and a string instance_eval or class_eval runs in that frame: "ab" =~ /(b)/; instance_eval("$1") is "b", and a match inside the string is the caller's $~ afterwards. IronRuby gave a string module-eval a closure scope of its own (RubyModuleEvalScope), which kept its own $~ and $_, so it read nil and a match inside it was lost. eval and binding.eval, which run in the caller's scope, were already right, as were the block forms. The module-eval scope a string instance_eval/class_eval makes now forwards its $~ and $_ to the caller's closure scope (RubyClosureScope.ShareSpecialVariablesOf); every other scope reads its own as before, with one null test on the way. Eval_InstanceEvalSpecialVariables1 holds CRuby's output, with methods the JIT compiled and with -X:NoJIT and IR_LIGHT_FRAMES=0 too; Kernel#eval, BasicObject#instance_eval, Module#module_eval/class_eval, binding and language/predefined specs pass (the known into/to errors of module_eval and instance_eval only), as do 88 eval, binding, regex and global-variable IronRuby.Tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 48 +++++++++++++++++++++++++ Src/Ruby/Runtime/RubyScope.cs | 24 ++++++++----- Src/Ruby/Runtime/RubyUtils.cs | 2 ++ 4 files changed, 67 insertions(+), 8 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e9241ea8a..359a9d7b2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1157,6 +1157,7 @@ public Tests(Driver/*!*/ driver) { Method_UnbindForwarder1, Method_ToProcSourceLocation1, Method_InternalSourceLine1, + Eval_InstanceEvalSpecialVariables1, Method_OptionalAndKeywordParameters2, Range_MinMaxInclude1, Integer_StepMatchString1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 601f97d2e..0a56cc9c8 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -6548,6 +6548,54 @@ p 3.method(:times).inspect, Kernel.instance_method(:then).inspect "); } + /// + /// A string instance_eval or class_eval sees and sets its caller's $~ and $_ (and so $1, $`), as MRI's do: they are + /// the frame's, not the eval's. + /// + public void Eval_InstanceEvalSpecialVariables1() { + TestOutput(@" +require 'ruby4' +def m1 + ""ab"" =~ /(b)/ + [instance_eval(""$~&.to_a""), instance_eval(""$1""), binding.eval(""$~&.to_a""), eval(""$1""), instance_eval { $1 }, binding.eval(""$`"")] +end +p m1 +def m2 + $_ = ""line"" + [instance_eval(""$_""), binding.eval(""$_""), eval(""$_""), instance_exec { $_ }] +end +p m2 +def m3 + ""xy"" =~ /y/ + o = Object.new + [o.instance_eval(""$~&.to_s""), Object.class_eval(""$~&.to_s""), o.instance_exec { $~&.to_s }] +end +p m3 +""zz"" =~ /z/ +p instance_eval(""$~&.to_s""), binding.eval(""$~&.to_s"") +def m4 = (instance_eval(""'q' =~ /q/""); $~&.to_s) +p m4 +def h1(s) = (s =~ /(\w)/; instance_eval(""$1"")) +def h2(s) = (s =~ /(\w)/; Object.class_eval(""$~&.[](1)"")) +def h3(s) + $_ = s + instance_eval(""$_"") +end +def h4(s) = (instance_eval(""s =~ /(\\w)/""); $1) +r = nil +3000.times { |i| r = [h1(""a#{i % 3}""), h2(""b""), h3(""c#{i % 2}""), h4(""d"")] } +p r +", @" +[[""b"", ""b""], ""b"", [""b"", ""b""], ""b"", ""b"", ""a""] +[""line"", ""line"", ""line"", ""line""] +[""y"", ""y"", ""y""] +""z"" +""z"" +""q"" +[""a"", ""b"", ""c1"", ""d""] +"); + } + /// /// A method with optional positional parameters and keywords (`def m(a, b = 2, k: 3)') keeps its /// optionals as optional parameters; a keyword call that leaves one out has its keyword hash moved diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index a40ced965..ef9b10ea8 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1406,35 +1406,43 @@ protected override bool IsClosureScope { get { return true; } } + // The scope whose $~ and $_ these are, when not this one's own: a string instance_eval/class_eval runs in a + // module-eval scope of its own, but MRI's frame-local special variables are the caller's there. + private RubyClosureScope _specialVariablesScope; + + internal void ShareSpecialVariablesOf(RubyClosureScope/*!*/ scope) { + _specialVariablesScope = (scope._specialVariablesScope ?? scope); + } + public MatchData CurrentMatch { - get { return _currentMatch; } - set { _currentMatch = value; } + get { var owner = _specialVariablesScope; return (owner == null) ? _currentMatch : owner._currentMatch; } + set { var owner = _specialVariablesScope; if (owner == null) { _currentMatch = value; } else { owner._currentMatch = value; } } } public object LastInputLine { - get { return _lastInputLine; } - set { _lastInputLine = value; } + get { var owner = _specialVariablesScope; return (owner == null) ? _lastInputLine : owner._lastInputLine; } + set { var owner = _specialVariablesScope; if (owner == null) { _lastInputLine = value; } else { owner._lastInputLine = value; } } } internal MutableString GetCurrentMatchGroup(int index) { Debug.Assert(index >= 0); - var match = _currentMatch; + var match = CurrentMatch; return (match != null) ? match.GetGroupValue(index) : null; } internal MutableString GetCurrentPreMatch() { - var match = _currentMatch; + var match = CurrentMatch; return (match != null) ? match.GetPreMatch() : null; } internal MutableString GetCurrentPostMatch() { - var match = _currentMatch; + var match = CurrentMatch; return (match != null) ? match.GetPostMatch() : null; } internal MutableString GetCurrentMatchLastGroup() { - var match = _currentMatch; + var match = CurrentMatch; if (match != null) { // the last capture group that matched; a pattern without groups has none ($+ is nil) for (int i = match.GroupCount - 1; i >= 1; i--) { diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 6f5c13a29..0041213a2 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1655,6 +1655,8 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop // string's own, so that they are not left behind in the caller's frame. var scope = new RubyModuleEvalScope(new RubyBindingCopyScope(parent, parent.SelfObject), module, self); scope.SetDebugName("instance/module-eval"); + // its $~ and $_ are the caller's frame's, as in MRI (instance_eval("$1") after a match) + scope.ShareSpecialVariablesOf(parent.GetInnerMostClosureScope()); return scope; } From 9438792f1284d51df6b4796ef3210e709d2966b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:16:14 +0000 Subject: [PATCH 252/439] Hash#any? is Hash's own; group_by, uniq and each_with_object walk a plain Hash with a one-value block Hash#any? was Enumerable's: a walk of #each through a block of ours, a Proc and a call per entry. {a: 1, b: 2, c: 3, d: 4}.any? { |k, v| v > 3 } took 695 ns against CRuby's 228, and it differed from CRuby wherever that walk shows: CRuby's is Hash's own (rb_hash_any_p), which walks the table and never calls #each, so a prepended, singleton or redefined Hash#each is not used, a backtrace from the block shows Hash#any?, and the owner is Hash. IDictionaryOps now has #any?: an empty Hash is false, no block and no pattern is true, a block gets key and value as two values when it takes two or more (any_p_i_fast) and the pair otherwise, and a pattern is matched with pattern === [key, value]; the table is walked as #each walks it (adding a key raises, a deleted one is skipped). all? and none? stay Enumerable's, as in CRuby. group_by, uniq and each_with_object walked a Hash with the generic `|*values|` block. A Hash whose #each is the built-in one now takes a one-value block, as perf/hashwalk did for the five sites before (__plain_each__?, IR_HASH_WALK): the same item and the same block argument, without the Array and __enum_item__ per entry. sum keeps the generic walk: the walk is a third of Hash#sum (the fold alone, 1052 -> 694 ns), but its body - the compensated summation - is written once against `|*values|`, and a prologue can only choose a block, so it would be written twice. Enumerable's all?, any? and none? are not inlined any more: ReadyToRun folded the forwarders into their callers, and a backtrace from the block under the R2R host lost the Enumerable#all? frame CRuby shows (already so on the unchanged build; Array's own had the same fix). Clock (Util/perf/ab.rb, four rounds, ns, CRuby / unchanged / this): Hash#any? 228 / 695 / 403 (0.58), group_by 968 / 1334 / 976 (0.73), each_with_object 964 / 1208 / 906 (0.75), uniq { } 837 / 1284 / 924 (0.72); Array any?, group_by, uniq { } within the noise. Three rows are new in core-small.rb. Util/hash-walk-matrix.rb gains any?, all? and none? (eleven block shapes, no block, empty, a pattern and what it is given, a pattern with a block, two arguments, subclasses, a prepended and a singleton #each, compare_by_identity, default procs, changes in the block, break, next, raise and its frames, throw, the walk's order and stop, frozen; owner, arity, parameters; refined and redefined Hash#each), group_by, uniq and each_with_object (ten block shapes of its own), and moves the refinement probes last (`using` reached every later line). It prints CRuby's output - but for two tie orders of min_by(2)/max_by(2), as before - by default, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R; with IR_HASH_WALK=0 the unchanged build's, but for Hash#any?'s five lines, now CRuby's. sort-by, enum, enumerable2, the five hash matrices, caller and hot-shapes print what they did in those modes, callable-parameters too but for a prelude line number. ruby/spec core/hash (any_spec among them) and core/enumerable: the same examples on both builds. IronRuby.Tests: the 60 tests that use any?, group_by, each_with_object or uniq, and Backtrace_LibraryFrames1, pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/Libraries/Builtins/Enumerable.cs | 9 ++ Src/Libraries/Extensions/IDictionaryOps.cs | 92 ++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 23 ++++- Util/bench/core-small.rb | 6 ++ Util/hash-walk-matrix.rb | 97 +++++++++++++++++++++- 5 files changed, 222 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/Enumerable.cs b/Src/Libraries/Builtins/Enumerable.cs index 5f89677dd..f27a8141a 100644 --- a/Src/Libraries/Builtins/Enumerable.cs +++ b/Src/Libraries/Builtins/Enumerable.cs @@ -228,17 +228,23 @@ internal static object PackValues(RubyArray/*!*/ args) { #region all?, any?, none? + // Not inlined: a backtrace taken in the block names the frame by this method ('Enumerable#all?'), and + // ReadyToRun folds a forwarder this small into its caller (see IListOps' Array#all? and friends). + [RubyMethod("all?")] + [MethodImpl(MethodImplOptions.NoInlining)] public static object TrueForAll(CallSiteStorage/*!*/ each, BlockParam predicate, object self) { return TrueForItems(each, predicate, self, false, false); } [RubyMethod("none?")] + [MethodImpl(MethodImplOptions.NoInlining)] public static object TrueForNone(CallSiteStorage/*!*/ each, BlockParam predicate, object self) { return TrueForItems(each, predicate, self, true, false); } [RubyMethod("any?")] + [MethodImpl(MethodImplOptions.NoInlining)] public static object TrueForAny(CallSiteStorage/*!*/ each, BlockParam predicate, object self) { return TrueForItems(each, predicate, self, true, true); } @@ -248,16 +254,19 @@ public static object TrueForAny(CallSiteStorage/*!*/ each, BlockParam // and &block made every [x].any? { } pay for a splat, a Proc and two more calls: 400 ns where MRI // takes 70. [RubyMethod("all?")] + [MethodImpl(MethodImplOptions.NoInlining)] public static object TrueForAll(CallSiteStorage/*!*/ each, BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, object self, object pattern) { return PatternForItems(each, caseEquals, predicate, self, pattern, false, false); } [RubyMethod("none?")] + [MethodImpl(MethodImplOptions.NoInlining)] public static object TrueForNone(CallSiteStorage/*!*/ each, BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, object self, object pattern) { return PatternForItems(each, caseEquals, predicate, self, pattern, true, false); } [RubyMethod("any?")] + [MethodImpl(MethodImplOptions.NoInlining)] public static object TrueForAny(CallSiteStorage/*!*/ each, BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, object self, object pattern) { return PatternForItems(each, caseEquals, predicate, self, pattern, true, true); } diff --git a/Src/Libraries/Extensions/IDictionaryOps.cs b/Src/Libraries/Extensions/IDictionaryOps.cs index 29f917cf4..b91336897 100644 --- a/Src/Libraries/Extensions/IDictionaryOps.cs +++ b/Src/Libraries/Extensions/IDictionaryOps.cs @@ -393,6 +393,98 @@ public static object Each(RubyContext/*!*/ context, [NotNull]BlockParam/*!*/ blo return self; } + #region any? + + // Hash's own #any?, as MRI's rb_hash_any_p (all? and none? are Enumerable's there too). It walks the + // table as #each does - adding a key in the block raises, a deleted key is skipped - but never calls + // #each: a subclass's, a singleton's or a prepended #each, or a redefined Hash#each, is not used, and + // a backtrace from the block shows Hash#any? under it. Enumerable#any? went through #each and a block + // of ours, a Proc and a call per entry: {...}.any? { |k, v| } was 3.8x MRI. Not inlined, so that the + // frame is there to be named. + + [RubyMethod("any?")] + [MethodImpl(MethodImplOptions.NoInlining)] + [BlockNotKept] + public static object Any(BlockParam predicate, IDictionary/*!*/ self) { + if (self.Count == 0) { + return ScriptingRuntimeHelpers.False; + } + // a pair is never false or nil + if (predicate == null) { + return ScriptingRuntimeHelpers.True; + } + return AnyEntry(predicate, null, null, self); + } + + // The pattern form: pattern === [key, value] for each entry (any_p_i_pattern), the block never called. + [RubyMethod("any?")] + [MethodImpl(MethodImplOptions.NoInlining)] + public static object Any(BinaryOpStorage/*!*/ caseEquals, BlockParam predicate, IDictionary/*!*/ self, object pattern) { + if (self.Count == 0) { + return ScriptingRuntimeHelpers.False; + } + if (predicate != null) { + caseEquals.Context.ReportWarning("given block not used"); + } + // MRI calls #=== with rb_funcall, which a private #=== answers too, as this site's does. + return AnyEntry(null, caseEquals.GetCallSite("==="), pattern, self); + } + + // Either the block is given each entry - key and value as two values to a block that takes two or + // more (any_p_i_fast), the pair to any other (any_p_i) - or, with a site, the pattern is matched with + // the pair. + private static object AnyEntry(BlockParam predicate, CallSite> site, object pattern, + IDictionary/*!*/ self) { + bool yieldPair = predicate != null && IsPairYieldOptimizable(predicate); + var hash = self as Hash; + if (hash != null) { + hash.BeginIteration(); + try { + int index = 0; + object key, value; + while (hash.TryGetNextEntry(ref index, out key, out value)) { + object result; + if (site != null) { + result = site.Target(site, pattern, MakeArray(key, value)); + } else if (yieldPair + ? predicate.Yield(CustomStringDictionary.ObjToNull(key), value, out result) + : predicate.Yield(MakeArray(key, value), out result)) { + return result; + } + if (Protocols.IsTrue(result)) { + return ScriptingRuntimeHelpers.True; + } + } + } finally { + hash.EndIteration(); + } + return ScriptingRuntimeHelpers.False; + } + + // Any other IDictionary: as Each walks one. + var pairs = CopyKeyValuePairs(self); + for (int i = 0; i < pairs.Length; i++) { + object value; + if (!TryGetCurrentValue(self, pairs, i, out value)) { + continue; + } + object result; + if (site != null) { + result = site.Target(site, pattern, MakeArray(pairs[i].Key, value)); + } else if (yieldPair + ? predicate.Yield(CustomStringDictionary.ObjToNull(pairs[i].Key), value, out result) + : predicate.Yield(MakeArray(pairs[i].Key, value), out result)) { + return result; + } + if (Protocols.IsTrue(result)) { + return ScriptingRuntimeHelpers.True; + } + } + return ScriptingRuntimeHelpers.False; + } + + #endregion + /// /// MRI's rb_block_pair_yield_optimizable: a non-lambda block that needs at least two /// arguments gets key and value as two values rather than as one pair. For a Ruby block diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 9e77de90d..12bad2c43 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -477,6 +477,12 @@ def group_by(&block) # an Array is grouped in C#, see Enumerable.ListGroupBy return __list_group_by__(&block) if __plain_list__? result = {} + # a Hash whose #each is the built-in one yields one value, the [key, value] pair, per entry + # (__plain_each__?): the block takes it as it is, without the `|*values|` Array + if __plain_each__? + each { |item| (result[yield(item)] ||= []) << item } + return result + end each do |*values| item = __enum_item__(values) key = values.size == 1 ? block.call(item) : __enum_yield__(values, &block) @@ -487,7 +493,12 @@ def group_by(&block) def each_with_object(memo) return to_enum(:each_with_object, memo) unless block_given? - each { |*values| yield(__enum_item__(values), memo) } + # see group_by: a Hash's built-in #each yields one value per entry (an Array has its own, in C#) + if __plain_each__? + each { |item| yield(item, memo) } + else + each { |*values| yield(__enum_item__(values), memo) } + end memo end unless method_defined?(:each_with_object) ::Enumerator.__iter_cursor_method__(self, :each_with_object) @@ -706,6 +717,16 @@ def collect_concat(&block) def uniq(&block) seen = {} result = [] + # see group_by: a Hash's built-in #each yields one value per entry (an Array has its own, in C#) + if __plain_each__? + each do |item| + key = block ? yield(item) : item + next if seen.key?(key) + seen[key] = true + result << item + end + return result + end each do |*values| item = __enum_item__(values) # MRI's uniq_iter yields the values as they came (rb_yield_values2), not the packed item diff --git a/Util/bench/core-small.rb b/Util/bench/core-small.rb index 151a4798d..a04df55ed 100644 --- a/Util/bench/core-small.rb +++ b/Util/bench/core-small.rb @@ -105,6 +105,9 @@ def m89; @h.sort_by { |pair| pair[1] }.size; end def m90; @h.min_by { |k, v| v }.size; end def m91; @h.filter_map { |k, v| v if v > 2 }.size; end def m92; @h.flat_map { |k, v| [v] }.size; end + def m93; @h.group_by { |k, v| v & 1 }.size; end + def m94; @h.each_with_object([]) { |(k, v), a| a << v }.size; end + def m95; @h.uniq { |k, v| v & 1 }.size; end end def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end # INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the @@ -215,3 +218,6 @@ def t(name, n) t("hash_min_by", N) { |n| i = 0; s = 0; while i < n; s += h.m90; i += 1; end; s } t("hash_filter_map", N) { |n| i = 0; s = 0; while i < n; s += h.m91; i += 1; end; s } t("hash_flat_map", N) { |n| i = 0; s = 0; while i < n; s += h.m92; i += 1; end; s } +t("hash_group_by", N) { |n| i = 0; s = 0; while i < n; s += h.m93; i += 1; end; s } +t("hash_each_w_obj", N) { |n| i = 0; s = 0; while i < n; s += h.m94; i += 1; end; s } +t("hash_uniq", N) { |n| i = 0; s = 0; while i < n; s += h.m95; i += 1; end; s } diff --git a/Util/hash-walk-matrix.rb b/Util/hash-walk-matrix.rb index 9c5807c48..d3425d240 100644 --- a/Util/hash-walk-matrix.rb +++ b/Util/hash-walk-matrix.rb @@ -28,6 +28,9 @@ def h = { a: 3, b: 1, c: 2 } 'max_by(2)': ->(r, &b) { r.max_by(2, &b) }, flat_map: ->(r, &b) { r.flat_map(&b) }, collect_concat: ->(r, &b) { r.collect_concat(&b) }, + group_by: ->(r, &b) { r.group_by(&b) }, + uniq: ->(r, &b) { r.uniq(&b) }, + each_with_object: ->(r, &b) { $ewo = []; [r.each_with_object($ewo) { |*a| $ewo << b.(a[0]) }, r.each_with_object([], &b).size] }, } # ---------------------------------------------------------------- 1. what the block is given @@ -98,10 +101,6 @@ def x.each = yield(:single, 5) end t("#{name} throw") { catch(:t) { m.(h) { |k, v| throw :t, k } } } end -using RefineEach -t('min_by under a refined Hash#each') { h.min_by { |k, v| v } } -t('sort_by under a refined Hash#each') { h.sort_by { |k, v| v } } -t('flat_map under a refined Hash#each') { h.flat_map { |k, v| [v] } } # ---------------------------------------------------------------- 3. Hash#each redefined, then restored t('a redefined Hash#each') do @@ -134,3 +133,93 @@ class Hash; alias each __saved_each__; remove_method :__saved_each__; end t('max_by ties: the first') { { a: 1, b: 1 }.max_by { 0 } } t('no block: enumerator sizes') { [h.min_by.size, h.sort_by.size, h.filter_map.size, h.flat_map.size, h.max_by(2).size] } t('enumerator, then each') { h.min_by.each { |k, v| v } } + +# ---------------------------------------------------------------- 5. any?, all?, none? (any? is Hash's own in CRuby: rb_hash_any_p) +PRED = { + 'any?': ->(r, *a, &b) { r.any?(*a, &b) }, + 'all?': ->(r, *a, &b) { r.all?(*a, &b) }, + 'none?': ->(r, *a, &b) { r.none?(*a, &b) }, +} +PBLOCKS = { + '|x|' => proc { |x| x[1] > 2 }, + '|k, v|' => proc { |k, v| v > 2 }, + '|k|' => proc { |k| k.is_a?(Array) }, + '|*a|' => proc { |*a| a.size == 1 && a[0][1] > 2 }, + '|(k, v)|' => proc { |(k, v)| v > 2 }, + '|x, *r|' => proc { |x, *r| r.empty? && x == :c }, + 'lambda (x)' => ->(x) { x[1] > 2 }, + 'lambda (k, v)' => ->(k, v) { v > 2 }, + '&:frozen?' => :frozen?.to_proc, + 'method(2 args)' => Object.new.tap { |o| def o.m(k, v) = v > 2 }.method(:m).to_proc, + 'method(1 arg)' => Object.new.tap { |o| def o.m(x) = x[1] > 2 }.method(:m).to_proc, +} +class EqqAll; def ===(x) = (($eqq ||= []) << x; false); end +PRED.each do |name, m| + PBLOCKS.each do |bname, b| + t("#{name} #{bname}") { m.(h, &b) } + end + t("#{name} no block") { [m.(h), m.({}), m.({ nil => nil })] } + t("#{name} empty with a block") { m.({}) { raise "called" } } + t("#{name} a pattern") { [m.(h, [:a, 3]), m.(h, Array), m.(h, [:z, 0])] } + t("#{name} a pattern sees the pair") { $eqq = []; m.(h, EqqAll.new); $eqq } + t("#{name} a pattern and a block") { m.(h, Array) { raise "called" } } + t("#{name} 2 arguments") { m.(h, 1, 2) } + t("#{name} subclass") { m.(SubHash[h]) { |k, v| v > 2 } } + t("#{name} subclass with its own #each") { m.(OwnEach[h]) { |k, v| v == 2 } } + t("#{name} a prepended #each") { m.(PrependedHash[h]) { |k, v| v == 0 } } + t("#{name} a singleton #each") { x = h; def x.each = yield(:single, 5); m.(x) { |k, v| v == 5 } } + t("#{name} compare_by_identity") { x = {}.compare_by_identity; x["a".dup] = 2; x["a".dup] = 1; m.(x) { |k, v| v == 1 } } + t("#{name} default proc not called") { x = Hash.new { |hh, k| raise "default #{k}" }; x[:q] = 1; m.(x) { |k, v| v == 1 } } + t("#{name} adding a key in the block") { x = h; m.(x) { |k, v| x[:"n#{v}"] = 0; false } } + t("#{name} deleting a later key") { x = h; seen = []; m.(x) { |k, v| x.delete(:c); seen << k; false }; seen } + t("#{name} replacing a later value") { x = h; seen = []; m.(x) { |k, v| x[:c] = 7; seen << v; false }; seen } + t("#{name} break") { m.(h) { |k, v| break [:broke, k] if v == 1; false } } + t("#{name} next") { m.(h) { |k, v| next v == 1 } } + t("#{name} raise, frames") do + m.(h) { raise "x" } + rescue => e + e.backtrace_locations.first(3).map(&:label) + end + t("#{name} throw") { catch(:t) { m.(h) { |k, v| throw :t, k } } } + t("#{name} walk order and stop") { seen = []; r = m.(h) { |k, v| seen << k; v == 1 }; [r, seen] } + t("#{name} a frozen Hash") { m.(h.freeze) { |k, v| v == 1 } } +end +t('any? owner, arity, parameters') { mm = {}.method(:any?); [mm.owner, mm.arity, mm.parameters] } +t('any? with a redefined Hash#each') do + class Hash; alias __saved_each__ each; def each = yield(:redef, 4); end + begin + [h.any? { |k, v| k == :redef }, h.all? { |k, v| k == :redef }] + ensure + class Hash; alias each __saved_each__; remove_method :__saved_each__; end + end +end +t('any? of ENV-like: a Struct, a Range') { [Struct.new(:a).new(1).any? { |x| x == 1 }, (1..3).any? { |x| x > 2 }] } + +# ---------------------------------------------------------------- 5b. each_with_object's own block shapes (the memo is the second value) +EWO = { + '|x, m|' => proc { |x, m| m << x }, + '|(k, v), m|' => proc { |(k, v), m| m << v }, + '|k, v|' => proc { |k, v| v << k }, + '|*a|' => proc { |*a| a[1] << a.size }, + '|x|' => proc { |x| $ewo2 << x }, + 'lambda (x, m)' => ->(x, m) { m << x }, + 'lambda ((k, v), m)' => ->((k, v), m) { m << k }, + 'lambda (x)' => ->(x) { $ewo2 << x }, + 'method(2 args)' => Object.new.tap { |o| def o.m(x, m) = m << x }.method(:m).to_proc, + '&:push' => :push.to_proc, +} +EWO.each do |bname, b| + t("each_with_object #{bname}") { $ewo2 = []; [h.each_with_object([], &b), $ewo2] } +end +t('each_with_object no block') { e = h.each_with_object([]); [e.size, e.next] } +t('each_with_object, a subclass with its own #each') { OwnEach[h].each_with_object([]) { |x, m| m << x } } +t('group_by and uniq, |*a| keys') { [h.group_by { |*a| a.size }, h.uniq { |*a| a.size }] } +t('uniq without a block') { { a: 1, b: 1 }.uniq } + +# ---------------------------------------------------------------- 6. a refined Hash#each (last: `using` reaches every later line of the file) +using RefineEach +t('min_by under a refined Hash#each') { h.min_by { |k, v| v } } +t('sort_by under a refined Hash#each') { h.sort_by { |k, v| v } } +t('flat_map under a refined Hash#each') { h.flat_map { |k, v| [v] } } +t('any? under a refined Hash#each') { h.any? { |k, v| k == :refined } } +t('all? under a refined Hash#each') { h.all? { |k, v| k == :refined } } From 3faf3dc8c8cedee00e24abfe6ac6e00b9a289349 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:16:15 +0000 Subject: [PATCH 253/439] Ledger: perf/hashany landed (clock only, not gated) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 53b408d4a..55875f91f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1901,6 +1901,21 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/hashany (/perf-step, 2026-11-28, on 540bdb0 + e9a8a9e) - `Hash#any?` is Hash's own + (rb_hash_any_p); `group_by`, `uniq`, `each_with_object` walk a plain Hash with a one-value + block** - clock only, not gated. `Hash#any? { |k, v| }` 695 -> 403 ns (CRuby 228; 0.58), + `group_by` 1334 -> 976 (0.73; CRuby 968), `each_with_object` 1208 -> 906 (0.75; 964), + `uniq { }` 1284 -> 924 (0.72; 837); Array rows within the noise. `Hash#any?` now matches CRuby + on owner, frames and a prepended, singleton or redefined #each (never called). Enumerable's + all?/any?/none? forwarders are NoInlining: R2R dropped their frame (already so before). + - `Util/hash-walk-matrix.rb` extended (any?/all?/none?, group_by, uniq, each_with_object): + CRuby's output but for two old tie orders, in five modes and R2R; IR_HASH_WALK=0 gives the + unchanged build's but for Hash#any? (not behind the switch). ruby/spec core/hash and + core/enumerable the same examples on both builds; 61 IronRuby.Tests pass. + - Left: `Hash#sum` (2.7x): the one-value walk would take a third off (the fold alone 1052 -> + 694 ns), but its compensated-sum body is written once against `|*values|`, so a prologue + means a second copy of it. `Hash#any?` itself is still 1.8x CRuby: the block call per entry. + - **perf/hashwalk (/perf-core, 2026-11-27, on 52f4f22) - the prelude's Enumerable methods walk a plain Hash with a one-value block (`__plain_each__?`, `IR_HASH_WALK`)** - clock only, not gated. The lever perf/hsortby named: filter_map, min_by, max_by, sort_by, min_by(n), From a996db2bbfb3a1023bbbc86758e0774abd95cf68 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:16:23 +0000 Subject: [PATCH 254/439] EndPark publishes the parked scope with a release write Stage 0's harness put the parked cycle's two atomics at about 16 ns of a literal block's 50 ns per call; one CompareExchange costs 10.4 ns on the measuring host against 2.5 for Volatile.Write. The park does not need an exchange: the object it publishes is held by this call alone (taken from the slot or from Spare by exchange, or new), the release write makes the scope, its tuple and the staged Procs visible to a taker whose exchange finds it, and the take, which stays an exchange, is what keeps one parked scope out of two frames. Overwriting a scope another call parked meanwhile drops it, as the old code dropped the newer one; a taker that had read it fails its exchange and makes a scope of its own. IR_PARK_WRITE=0 restores the compare-exchange. The harness shows take+park 24 -> 16 ns; end to end (ab.rb -r 10: nyl, eachl, each1, map1, times1, call, nb0) every row is within the spread. The parked-scope, block-scope-reuse and its race, block-nest-reuse, nested-proc and parked-iterator matrices pass in all modes and with the switch off; the race matrix ten times alone; 16 threads calling one parking method for several minutes produced no wrong result. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Ruby/Runtime/RubyOps.cs | 12 ++++++++++++ Util/perf/LEDGER.md | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index b8e5517bb..7c4b7d635 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -392,6 +392,9 @@ public static bool StageParkedProc(ParkedProcs/*!*/ parked, int index, Proc proc /// Parks the scope with the staged Procs, cleared of the call that ended; or, if a Proc may be held or another call /// parked first, keeps the emptied ParkedProcs for the next. /// + // IR_PARK_WRITE=0: EndPark publishes with a compare-exchange, as before round thirty-seven's perf/endpark. + internal static readonly bool ParkByWrite = Environment.GetEnvironmentVariable("IR_PARK_WRITE") != "0"; + [Emitted] public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, RubyScope/*!*/ scope, bool procsParkable) { if (procsParkable) { @@ -405,6 +408,15 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R methodScope.ClearCallState(); parked.Scope = methodScope; parked.ThreadId = Environment.CurrentManagedThreadId; + if (ParkByWrite) { + // A release write, not an exchange: everything above is visible to the taker whose exchange finds this + // object. What the slot held is dropped - a scope another call parked meanwhile, which nothing uses; a + // taker that read it before this write fails its exchange and makes a scope of its own - and cannot come + // back, since only a parker publishes, and only an object it holds alone (taken by exchange, from Spare by + // exchange, or new). The take stays an exchange: it is what keeps one parked scope out of two frames. + Volatile.Write(ref slot.Parked, parked); + return; + } if (Interlocked.CompareExchange(ref slot.Parked, parked, null) == null) { return; } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f603b9901..70a044462 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1212,6 +1212,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the call site, rule and frames around it 35-45, which the convention does not reach. Stage A pays most per round (up to ~50 ns of `e1`); the park's compare-exchange as a release write is a step of its own, about 8 ns per call (perf/iter3 could not see it end to end). + perf/endpark took that step (see Landed): the harness's take-and-park 24 -> 16 ns, end to end + within the noise. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per @@ -1948,6 +1950,27 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/endpark (round thirty-seven, 2026-11-28) - EndPark publishes the parked scope with a release + write, not a compare-exchange (gap 13)** - time, not gated. Stage 0 found the parked cycle's two atomics + about 16 ns of a literal's 50, one `CompareExchange` 10.4 ns here against a `Volatile.Write`'s 2.5. The + take stays an exchange; the park is now `Volatile.Write(ref slot.Parked, parked)`. Why it is sound: the + write is a release, so the scope, its tuple and the staged Procs written before it are visible to a + taker whose exchange finds the object. The object being published is held by this call alone (taken by + exchange from the slot or from Spare, or new), so no two parkers can publish the same one. What the + write overwrites is a scope another call parked meanwhile: it is dropped, and a taker that had read it + fails its exchange and makes a scope of its own - the old code dropped the newer one instead, the same + loss. A dropped object never comes back, since only its holder publishes. Exclusion was the take's + exchange all along: one parked object never reaches two frames. `IR_PARK_WRITE=0` is the old code. + Harness (`IronRuby.Tests /blockcost`), ns: take+park (P1) 24 -> 16, the `e1` steps together 50-52 -> + 40-42, `nyl`'s 67 -> 63-65. End to end, `ab.rb -r 10` off/on, ns per call: `nyl` 151.8/151.3, + `eachl` 135.8/131.6, `each1` 153.7/156.7, `map1` 174.2/175.4, `times1` 161.2/157.5, `call` (no literal) + 60.0/61.9, `nb0` 39.9/39.9 - all within the spread, as perf/iter3 found for 8 ns. Checked: parked-scope + (with its two-thread rows), block-scope-reuse (and its race), block-nest-reuse, nested-proc and + parked-iterator in the six modes and with the switch off: PASS, 42 same; block-scope-reuse-race ten runs + alone, stale 0 leaked 0 every time; sixteen threads calling one parking method (`each` and `map` + literals that read and write the frame's locals, a `Thread.pass` in the block) for 90 s with the JIT + and 90 s without, 104 million calls each, and 30 s with the switch off: every result right. + - **perf/literalsite (round thirty-seven, 2026-11-27) - a call with a block in a light frame whose literals are all narrow takes the light site (gaps 16 and 13)** - instructions not counted, time and bytes, not gated. Change A of `Docs/light-frame-literal-blocks.md`. In a light body with literal blocks From 203a6395f62fbf273652feccef5596443ea12a52 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:23:34 +0000 Subject: [PATCH 255/439] Pass `**h' as a dup: keep its default, default proc and compare_by_identity CRuby 4.0 gives the callee of `f(**h)' a dup of h: `def kr(**r)' called with `**Hash.new(5)' has r.default == 5, a default proc and compare_by_identity come along too, and so they do to a `**r' beside declared keywords and to a positional parameter that takes the hash. IronRuby's copy (Hash. TryCopyAsKeywordArguments, and KeywordSplatArgument's general copy for a hash with non-Symbol keys or another comparer) made a plain Hash, so all three were lost; the **rest built from it (CopyWithoutKeywords) already kept them. Both copies now carry the default and default proc, and the general one is `new Hash(source)', which keeps the comparer. A `**h' mixed with other keywords (`f(a: 1, **h)', `f(**h, **{})') builds a new hash, as before and as in CRuby. Checked against CRuby with probes of `**r', `k:, **r', positional, forwarded and mixed shapes (in Method_Ruby2KeywordsExplicitSplat1 and Util/kwsplat-forward-matrix.rb, next commit). An empty `**h' with a default still passes nothing, where CRuby gives a `**k' callee a dup of it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/Ruby/Builtins/Hash.Keywords.cs | 4 ++++ Src/Ruby/Runtime/RubyOps.cs | 11 ++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Src/Ruby/Builtins/Hash.Keywords.cs b/Src/Ruby/Builtins/Hash.Keywords.cs index bfc6e506a..b41d5db03 100644 --- a/Src/Ruby/Builtins/Hash.Keywords.cs +++ b/Src/Ruby/Builtins/Hash.Keywords.cs @@ -225,6 +225,10 @@ internal Hash TryCopyAsKeywordArguments(IEqualityComparer/*!*/ comparer) result._liveCount = n; result._version++; result._stamp++; + // `f(**h)' gives the callee a dup of h (CRuby 4.0): its default and default proc come along, as they do to the + // **rest that is made of it (CopyWithoutKeywords) + result._defaultProc = _defaultProc; + result._defaultValue = DefaultValue; return result; } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index b8e5517bb..9e554759e 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -2550,9 +2550,14 @@ public static Hash KeywordSplatArgument(RubyScope/*!*/ scope, object hash) { var source = dict as Hash; var copy = (source != null) ? source.TryCopyAsKeywordArguments(scope.RubyContext.EqualityComparer) : null; if (copy == null) { - copy = new Hash(scope.RubyContext.EqualityComparer, dict.Count); - foreach (var entry in dict) { - copy[entry.Key] = entry.Value; + if (source != null) { + // a dup, as CRuby passes it: its comparer (compare_by_identity), default and default proc with it + copy = new Hash(source); + } else { + copy = new Hash(scope.RubyContext.EqualityComparer, dict.Count); + foreach (var entry in dict) { + copy[entry.Key] = entry.Value; + } } copy.IsKeywordArguments = true; } From 03218bacab72139a3e83ec7ec287c286a5058384 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:23:34 +0000 Subject: [PATCH 256/439] Make a ruby2_keywords hash keywords only at a Ruby splat without `**' CRuby 4.0 turns a ruby2_keywords-marked hash ending a splatted list back into keywords only at a splat in Ruby source whose call has no kw_splat (vm_caller_setup_arg_splat). With an explicit `**' - `g(*a, **{})', `g(*a, **nil)', `super(*a, **{})' - it stays a positional argument, the same object with its mark, and a C method passing its arguments on (Class#new to #initialize, a Method's proc, Kernel#send, Proc#call) passes them as they came. `yield(*args)' converts as `f(*args)' does. IronRuby converted at every splatted call, library-made sites included, and never at `yield(*args)'. language/keyword_arguments' "works with yield(*ruby2_keyword_args)" passed only because the block's own `target(*args, **kwargs)' converted the hash, which is the first bug. RubyCallFlags.HasRuby2KeywordsSplat (4096; the signature keeps 13 flag bits) is set by CallSiteBuilder on a splat site without a `**' among its arguments and read wherever the mark was made keywords again: MetaObjectBuilder. AddSplattedArgumentTest, ArgsBuilder, RubyOverloadResolver, RubyMethodGroupBase and LibraryDispatcher (a field for ExpandSplat). It is a property of the site, so its rules decide it once and no call pays. A site a library method makes does not set it, but Symbol#to_proc's, whose proc keeps the keywords it is given marked in its rest list (IronRuby.Tests SymbolProcKeywords1 caught it). SuperCall's two keyword sites pass their keywords explicitly. Arguments.TransformToYield converts the splat of a yield without `**' (RubyOps.SplatRuby2Keywords). Checked: new IronRuby.Tests Method_Ruby2KeywordsExplicitSplat1 with CRuby 4.0's output (fails on the base build); Util/kwsplat-forward-matrix.rb's rows that differed now match, with new rows for yield, Method#to_proc, Class#new and send; the splat, keyword and forwarding matrices in every mode; specs language/keyword_arguments, send, def, super, method, block, yield and core/kernel/send, core/module/ruby2_keywords, core/symbol/to_proc, core/method/to_proc, core/proc/ruby2_keywords, core/struct/new as before; IronRuby.Tests in full on Debug. Timings unchanged (Util/perf/LEDGER.md). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 66 +++++++++++++++++++ Src/Ruby/Builtins/Proc.cs | 7 +- Src/Ruby/Compiler/Ast/Arguments.cs | 17 +++++ Src/Ruby/Compiler/Ast/CallSiteBuilder.cs | 8 +++ .../Compiler/Ast/Expressions/MethodCall.cs | 1 + .../Compiler/Ast/Expressions/SuperCall.cs | 6 +- Src/Ruby/Runtime/Calls/ArgsBuilder.cs | 1 + Src/Ruby/Runtime/Calls/LibraryDispatcher.cs | 16 ++++- Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs | 15 +++-- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 4 +- Src/Ruby/Runtime/Calls/RubyCallSignature.cs | 12 +++- Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs | 7 +- .../Runtime/Calls/RubyOverloadResolver.cs | 7 +- Util/kwsplat-forward-matrix.rb | 16 ++++- Util/perf/LEDGER.md | 41 ++++++++++++ 16 files changed, 202 insertions(+), 23 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fd1166bce..6087470d2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1180,6 +1180,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameMemberOpAssign1, Method_LightFrameKeywordRest1, Method_KeywordHashIntoRest1, + Method_Ruby2KeywordsExplicitSplat1, Method_KeywordPrologue1, Method_LightFrameGlobal1, Method_LightFrameLexical1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 5c960c00e..e1e0ba4bf 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8307,6 +8307,72 @@ p r2k(1, k: 2), r2k(1, {k: 2}), Hash.ruby2_keywords_hash?(r2k_last(k: 1)), Hash. "); } + /// + /// A call with an explicit `**' - even one that passes nothing - leaves a ruby2_keywords hash ending its splatted list + /// positional, the same object with its mark (RubyCallFlags.HasRuby2KeywordsSplat), and so does a library method + /// passing its arguments on, where `yield(*args)' makes it keywords as `f(*args)' does; and `**h' alone gives the callee a dup of h, its default, default proc and + /// compare_by_identity with it (RubyOps.KeywordSplatArgument). Expected output from CRuby 4.0. + /// + public void Method_Ruby2KeywordsExplicitSplat1() { + TestOutput(@" +require 'ruby4' +def g(*a, **k) = [a, k] +def g2(a, k: 0) = [a, k] +def rest(*a) = a +h = Hash.ruby2_keywords_hash({k: 1}) +a = [1, h] +e = {} +p g(*a), g(*a, **e), g(*a, **nil), g(*a, **{z: 2}) +r = rest(*a, **e) +p r.last.equal?(h), Hash.ruby2_keywords_hash?(r.last) +p((g2(*a, **e) rescue $!.class), g2(*a)) +p send(:g, *a, **e), method(:g).call(*a, **e), method(:g).to_proc.call(*a, **e) +p proc { |*x, **kk| [x, kk] }.call(*a, **e) +ruby2_keywords def fwd(*r) = g(*r, **{}) +p fwd(1, k: 2) +class P; def m(*x, **kk) = [x, kk]; end +class C < P; def m(*x) = super(*x, **{}); end +p C.new.m(1, h) +dp = Hash.new { :dp }; dp[:z] = 1 +dv = Hash.new(5); dv[:z] = 1 +ci = {}.compare_by_identity; ci[:z] = 1 +def kr(**r) = [r[:missing], r.default, r.compare_by_identity?] +def kn(k: 1, **r) = [k, r.default, r.compare_by_identity?] +def pos(x) = [x.default, x.compare_by_identity?] +p kr(**dp), kr(**dv), kr(**ci), kn(**dv), kn(**ci), pos(**dv) +p kr(a: 1, **dv), kr(**dv, **{}) +def y(args) = yield(*args) +def yk(args) = yield(*args, **{}) +p y([h]) { |*x, **kk| [x, kk] }, y([h], &-> *x, **kk { [x, kk] }), yk([h]) { |*x, **kk| [x, kk] } +", @" +[[1], {k: 1}] +[[1, {k: 1}], {}] +[[1, {k: 1}], {}] +[[1, {k: 1}], {z: 2}] +true +true +ArgumentError +[1, 1] +[[1, {k: 1}], {}] +[[1, {k: 1}], {}] +[[1, {k: 1}], {}] +[[1, {k: 1}], {}] +[[1, {k: 2}], {}] +[[1, {k: 1}], {}] +[:dp, nil, false] +[5, 5, false] +[nil, nil, true] +[1, 5, false] +[1, nil, true] +[5, false] +[nil, nil, false] +[nil, nil, false] +[[], {k: 1}] +[[], {k: 1}] +[[{k: 1}], {}] +"); + } + /// /// A method's keyword prologue (PrismAstBridge.LowerKeywords): which error wins when several things are wrong at once, /// and defaults run in order and only for omitted keywords (Util/kw-prologue-matrix.rb). diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index ba80774af..ee761311c 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -594,11 +594,14 @@ public object CallN(Proc procArg, object[]/*!*/ args) { // MRI 1.9.2 doesn't do so though (see http://redmine.ruby-lang.org/issues/show/3792). // the block a symbol proc is called with goes on to the method it invokes: - // [1, 2].map(&:foo) { ... } passes the block through to #foo + // [1, 2].map(&:foo) { ... } passes the block through to #foo. Keywords too: the proc keeps them in its rest list as a + // marked hash (Ruby2Keywords, below), which this site makes keywords again, as a Ruby splat site does - the one site + // a library method makes that does (RubyCallFlags.HasRuby2KeywordsSplat). var site = CallSite>.Create( RubyCallAction.Make( scope.RubyContext, methodName, - new RubyCallSignature(0, RubyCallFlags.HasScope | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasBlock) + new RubyCallSignature(0, RubyCallFlags.HasScope | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasBlock | + RubyCallFlags.HasRuby2KeywordsSplat) ) ); diff --git a/Src/Ruby/Compiler/Ast/Arguments.cs b/Src/Ruby/Compiler/Ast/Arguments.cs index 70c767458..8f1362766 100644 --- a/Src/Ruby/Compiler/Ast/Arguments.cs +++ b/Src/Ruby/Compiler/Ast/Arguments.cs @@ -60,7 +60,18 @@ public Arguments(Expression/*!*/[] expressions) { #region Transform to Call/Yield Expression + // A `**' among the arguments (see RubyCallFlags.HasRuby2KeywordsSplat). + private bool HasKeywordSplat() { + foreach (var expression in _expressions) { + if (expression is KeywordArgumentSplat) { + return true; + } + } + return false; + } + internal void TransformToCall(AstGenerator/*!*/ gen, CallSiteBuilder/*!*/ siteBuilder) { + siteBuilder.HasExplicitKeywords = HasKeywordSplat(); bool fresh; siteBuilder.SplattedArgument = TransformToCallInternal(gen, siteBuilder, out fresh); siteBuilder.SplattedArgumentIsFresh = fresh; @@ -69,6 +80,12 @@ internal void TransformToCall(AstGenerator/*!*/ gen, CallSiteBuilder/*!*/ siteBu internal MSA.Expression/*!*/ TransformToYield(AstGenerator/*!*/ gen, MSA.Expression/*!*/ bfcVariable, MSA.Expression/*!*/ selfExpression) { var args = new List(); var splatted = TransformToCallInternal(gen, args, out _); + // `yield(*args)' makes a ruby2_keywords hash ending the list keyword arguments again, as a call's splat does + // (RubyCallFlags.HasRuby2KeywordsSplat) - and as there, not when a `**' is given as well (CRuby 4.0). It did not, + // and a block taking `*a, **k' got the marked hash in a. + if (splatted != null && !HasKeywordSplat()) { + splatted = Methods.SplatRuby2Keywords.OpCall(AstUtils.Convert(splatted, typeof(IList))); + } // `yield x, **h': whether x may be auto-splatted depends on h being given at all (RubyOps.YieldKeywordSplat1) if (args.Count == 1 && _expressions.Length == 2 && _expressions[1] is KeywordArgumentSplat) { return Methods.YieldKeywordSplat1.OpCall( diff --git a/Src/Ruby/Compiler/Ast/CallSiteBuilder.cs b/Src/Ruby/Compiler/Ast/CallSiteBuilder.cs index 147a8a573..2dc44316f 100644 --- a/Src/Ruby/Compiler/Ast/CallSiteBuilder.cs +++ b/Src/Ruby/Compiler/Ast/CallSiteBuilder.cs @@ -38,6 +38,10 @@ internal sealed class CallSiteBuilder : ExpressionCollectionBuilder= 0) ? _restTakesListFrom + 1 : -1, + args.Signature.HasRuby2KeywordsSplat, out _listLength, out _listVariable); _actualArgumentCount += _listLength; } diff --git a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs index c6615504b..5d9f2a68a 100644 --- a/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs @@ -1217,6 +1217,10 @@ internal static object TryCreateSend(RubyCallAction/*!*/ binder, Type/*!*/ deleg // The length of the splatted list a call passes (see TryCreate, TryCreateRubyCall), -1 if the site splats none. private int _splatCount = -1; + // The site makes a ruby2_keywords hash ending its list keywords again (RubyCallFlags.HasRuby2KeywordsSplat): ExpandSplat + // does as its rule does. + private bool _ruby2Keywords; + // The arguments of a splatted call, the list's items in place of the list, as its rule makes them (MetaObjectBuilder. // AddSplattedArgumentTest, ArgsBuilder); null if the list is not of the length the rule was bound for. private object[] ExpandSplat(object[]/*!*/ args) { @@ -1224,7 +1228,9 @@ private object[] ExpandSplat(object[]/*!*/ args) { if (list == null) { return null; } - list = RubyOps.SplatRuby2Keywords(list); + if (_ruby2Keywords) { + list = RubyOps.SplatRuby2Keywords(list); + } if (list.Count != _splatCount) { return null; } @@ -1268,7 +1274,7 @@ internal static object TryCreateRubyCall(RubyCallAction/*!*/ binder, Type/*!*/ d if (list == null || signature.HasRhsArgument) { return null; } - splatCount = RubyOps.SplatRuby2Keywords(list).Count; + splatCount = (signature.HasRuby2KeywordsSplat ? RubyOps.SplatRuby2Keywords(list) : list).Count; argumentCount = count - 1 + splatCount; } @@ -1296,6 +1302,7 @@ internal static object TryCreateRubyCall(RubyCallAction/*!*/ binder, Type/*!*/ d dispatcher._context = targetClass.Context; dispatcher._rubyCall = plan; dispatcher._splatCount = splatCount; + dispatcher._ruby2Keywords = signature.HasRuby2KeywordsSplat; dispatcher._isRubyObject = isRubyObject; dispatcher._targetType = (target != null) ? target.GetType() : null; dispatcher._bool = (target is bool) ? (bool)target : false; @@ -1409,7 +1416,9 @@ internal static object TryCreate(RubyCallAction/*!*/ binder, Type/*!*/ delegateT if (list == null || signature.HasRhsArgument) { return null; } - list = RubyOps.SplatRuby2Keywords(list); + if (signature.HasRuby2KeywordsSplat) { + list = RubyOps.SplatRuby2Keywords(list); + } simpleCount = count - 1; splatCount = list.Count; var expanded = new object[simpleCount + splatCount]; @@ -1483,6 +1492,7 @@ internal static object TryCreate(RubyCallAction/*!*/ binder, Type/*!*/ delegateT dispatcher._context = targetClass.Context; dispatcher._plan = plan; dispatcher._splatCount = splatCount; + dispatcher._ruby2Keywords = signature.HasRuby2KeywordsSplat; dispatcher._hasBlock = signature.HasBlock; dispatcher._argTypes = argTypes; dispatcher._restricted = restricted; diff --git a/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs b/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs index b45817378..68baaee54 100644 --- a/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs +++ b/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs @@ -461,8 +461,8 @@ private void AddVersionTest(RubyClass/*!*/ cls, RuleVersionSet versionSet) { } } - internal void AddSplattedArgumentTest(IList/*!*/ value, Expression/*!*/ expression, out int listLength, out ParameterExpression/*!*/ listVariable) { - AddSplattedArgumentTest(value, expression, -1, out listLength, out listVariable); + internal void AddSplattedArgumentTest(IList/*!*/ value, Expression/*!*/ expression, bool ruby2Keywords, out int listLength, out ParameterExpression/*!*/ listVariable) { + AddSplattedArgumentTest(value, expression, -1, ruby2Keywords, out listLength, out listVariable); } /// @@ -470,15 +470,20 @@ internal void AddSplattedArgumentTest(IList/*!*/ value, Expression/*!*/ expressi /// callee takes the list's tail into its rest parameter, whatever its length (see ArgsBuilder.AddCallArguments). Without it a /// site whose list grows at every call - `f(n - 1, *a, n)' recursing - built a rule for each length and never hit one. /// - internal void AddSplattedArgumentTest(IList/*!*/ value, Expression/*!*/ expression, int minLength, out int listLength, out ParameterExpression/*!*/ listVariable) { + /// + /// Whether a ruby2_keywords hash ending the list is made keyword arguments again: only at a splat written in Ruby + /// source without a `**' (RubyCallFlags.HasRuby2KeywordsSplat). + /// + internal void AddSplattedArgumentTest(IList/*!*/ value, Expression/*!*/ expression, int minLength, bool ruby2Keywords, out int listLength, out ParameterExpression/*!*/ listVariable) { // Every splatted call comes through here, whoever built the list - `f(*args)' in Ruby // source, Kernel#send, an Enumerator replaying the arguments it was made with. A hash // a ruby2_keywords method is carrying goes back to being keyword arguments at exactly // this point, and nowhere else. The list keeps its length, so the rule below is // unaffected. listVariable = GetTemporary(typeof(IList), "#list"); - Expression assignment = Ast.Assign(listVariable, - Methods.SplatRuby2Keywords.OpCall(AstUtils.Convert(expression, typeof(IList))) + Expression assignment = Ast.Assign(listVariable, ruby2Keywords ? + Methods.SplatRuby2Keywords.OpCall(AstUtils.Convert(expression, typeof(IList))) : + AstUtils.Convert(expression, typeof(IList)) ); listLength = value.Count; diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index ad04cec5b..ce8d81d5f 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -121,7 +121,7 @@ protected override object BindPrecompiled(Type/*!*/ delegateType, object[]/*!*/ // binder. Leaving it out of the mask sent every bare `foo` to a rule of its own. if (Context == null || Signature.ResolveOnly || - (Signature.Flags & ~(RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasScope | RubyCallFlags.HasBlock | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasSourceBlock | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasLightScope)) != 0 || + (Signature.Flags & ~(RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasScope | RubyCallFlags.HasBlock | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasSourceBlock | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasLightScope | RubyCallFlags.HasRuby2KeywordsSplat)) != 0 || Signature.HasSplattedArgument && Signature.HasRhsArgument) { return null; } @@ -372,7 +372,7 @@ internal SharedRule(RubyMemberInfo/*!*/ member, bool isMissing, Type/*!*/ target private const RubyCallFlags SharableCallFlags = RubyCallFlags.HasScope | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasBlock | RubyCallFlags.HasImplicitSelf | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSourceBlock | - RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat; + RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasRuby2KeywordsSplat; private static readonly object _SharedRulesLock = new object(); private SharedRule[] _sharedRules; diff --git a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs index 0d880a199..1e3be7e16 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs @@ -77,13 +77,22 @@ public enum RubyCallFlags { // (ArgsBuilder.AddCallArguments). Not a site that splats an array of the program's own (`f(*a)'), which the callee // must not share. HasFreshSplat = 2048, + + // A splat written in Ruby source, in a call with no `**' among its arguments (`f(*a)', not `f(*a, **h)'): the one + // kind of call at which a ruby2_keywords hash ending the list is made keyword arguments again (RubyOps. + // SplatRuby2Keywords, read by MetaObjectBuilder.AddSplattedArgumentTest, ArgsBuilder, RubyOverloadResolver, + // RubyMethodGroupBase and LibraryDispatcher). CRuby 4.0 looks at the mark only there (vm_caller_setup_arg_splat, for + // a call without kw_splat): with an explicit `**' - even one that passes nothing - the hash stays a positional + // argument, the same object with its mark, and a C method passing its arguments on (Class#new to #initialize, a + // Method's proc, Kernel#send) passes them as they came. So a site a library method makes never converts. + HasRuby2KeywordsSplat = 4096, } /// /// RubyScope/RubyContext, (self), (argument){ArgumentCount}, (splatted-argument)?, (block)? /// public struct RubyCallSignature : IEquatable { - private const int FlagsCount = 12; + private const int FlagsCount = 13; private const int ResolveOnlyArgumentCount = (int)(UInt32.MaxValue >> FlagsCount); private const int MaxArgumentCount = ResolveOnlyArgumentCount - 1; @@ -104,6 +113,7 @@ public struct RubyCallSignature : IEquatable { public bool HasSourceBlock { get { return (_countAndFlags & (uint)RubyCallFlags.HasSourceBlock) != 0; } } public bool HasLightScope { get { return (_countAndFlags & (uint)RubyCallFlags.HasLightScope) != 0; } } public bool HasFreshSplat { get { return (_countAndFlags & (uint)RubyCallFlags.HasFreshSplat) != 0; } } + public bool HasRuby2KeywordsSplat { get { return (_countAndFlags & (uint)RubyCallFlags.HasRuby2KeywordsSplat) != 0; } } // defined? ignores arguments hence we can use one argument number (max) to represent resolve only sites: public bool ResolveOnly { get { return ArgumentCount == ResolveOnlyArgumentCount; } } diff --git a/Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs b/Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs index 147fc056d..f1482376a 100644 --- a/Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs +++ b/Src/Ruby/Runtime/Calls/RubyMethodGroupBase.cs @@ -578,7 +578,10 @@ private static bool TakesPositionalCount(MetaObjectBuilder/*!*/ metaBuilder, Cal int count = args.SimpleArgumentCount; IList list = null; if (args.Signature.HasSplattedArgument) { - list = RubyOps.SplatRuby2Keywords((IList)args.GetSplattedArgument()); + list = (IList)args.GetSplattedArgument(); + if (args.Signature.HasRuby2KeywordsSplat) { + list = RubyOps.SplatRuby2Keywords(list); + } count += list.Count; } @@ -592,7 +595,7 @@ private static bool TakesPositionalCount(MetaObjectBuilder/*!*/ metaBuilder, Cal if (list != null && (keywordsDecide || !takes)) { int listLength; ParameterExpression listVariable; - metaBuilder.AddSplattedArgumentTest((IList)args.GetSplattedArgument(), args.GetSplattedMetaArgument().Expression, out listLength, out listVariable); + metaBuilder.AddSplattedArgumentTest((IList)args.GetSplattedArgument(), args.GetSplattedMetaArgument().Expression, args.Signature.HasRuby2KeywordsSplat, out listLength, out listVariable); if (keywordsDecide && listLength > 0) { Expression test = Methods.IsKeywordArgumentsHash.OpCall( Ast.Call(listVariable, typeof(IList).GetMethod("get_Item"), AstUtils.Constant(listLength - 1)) diff --git a/Src/Ruby/Runtime/Calls/RubyOverloadResolver.cs b/Src/Ruby/Runtime/Calls/RubyOverloadResolver.cs index e1c9abcd2..d7c0bd4ec 100644 --- a/Src/Ruby/Runtime/Calls/RubyOverloadResolver.cs +++ b/Src/Ruby/Runtime/Calls/RubyOverloadResolver.cs @@ -448,7 +448,8 @@ internal static Hash GetKeywordArguments(CallArguments/*!*/ args) { var list = args.GetSplattedArgument(); keywords = (list.Count > 0) ? list[list.Count - 1] as Hash : null; // a hash a ruby2_keywords method carries is turned back into keywords when splatted: - if (keywords == null || !keywords.IsKeywordArguments && !keywords.IsRuby2KeywordsHash) { + // (at a splat written in Ruby without a `**' only: RubyCallFlags.HasRuby2KeywordsSplat) + if (keywords == null || !keywords.IsKeywordArguments && !(keywords.IsRuby2KeywordsHash && args.Signature.HasRuby2KeywordsSplat)) { return null; } } else { @@ -590,7 +591,7 @@ protected override void GetNamedArguments(out IList namedArgs var splatted = _args.GetSplattedMetaArgument(); int listLength; _list = (IList)splatted.Value; - _metaBuilder.AddSplattedArgumentTest(_list, splatted.Expression, out listLength, out _listVariable); + _metaBuilder.AddSplattedArgumentTest(_list, splatted.Expression, _args.Signature.HasRuby2KeywordsSplat, out listLength, out _listVariable); hash = (Hash)_list[listLength - 1]; } else { hash = (Hash)_args.GetSimpleArgument(_args.SimpleArgumentCount - 1); @@ -731,7 +732,7 @@ protected override ActualArguments CreateActualArguments(IList scoped.txt # diff mri.txt on.txt && diff mri.txt scoped.txt # -# Three probes differ from CRuby 4.0 on builds before and after this change and are kept to show it: a `**' copy loses -# the hash's default proc, and a ruby2_keywords hash ends the list before an explicit empty `**' (CRuby passes it -# positionally, flag and all; IronRuby's call sites take it as keywords whenever it is the last item splatted). +# The ruby2_keywords probes and the default-proc one differed from CRuby 4.0 until a call with an explicit `**' stopped +# making a marked hash keywords (RubyCallFlags.HasRuby2KeywordsSplat) and `**h' passed a dup of h (RubyOps. +# KeywordSplatArgument). # # Each probe runs 3000 times (interpreted, then compiled) and prints every distinct answer once. @@ -135,3 +135,13 @@ class SupE3 < SupP; def m(*, **) = [1].map { eval('super') }.first; end t("eval('super') from (a, *, d:)") { |i| SupE.new.m(1, 2, 3, d: 4) } t("eval('super') from (*, **)") { |i| i.even? ? SupE2.new.m(1, 2, k: 3) : SupE2.new.m } t("eval('super') in a block from (*, **)") { |i| SupE3.new.m(1, k: 2) } +def y_splat(args) = yield(*args) +def y_splat_kw(args) = yield(*args, **{}) +t("yield(*args) with a ruby2_keywords hash") { |i| y_splat([1, Hash.ruby2_keywords_hash({k: i % 2})]) { |*x, **k| [x, k] } } +t("yield(*args, **{}) keeps it positional") { |i| r = y_splat_kw([1, Hash.ruby2_keywords_hash({k: 1})]) { |*x, **k| [x, k] }; [r, Hash.ruby2_keywords_hash?(r[0].last)] } +t("yield(*args) to a lambda") { |i| y_splat([Hash.ruby2_keywords_hash({k: 1})], &->(*x, **k) { [x, k] }) } +t("Method#to_proc and Class#new pass it on positional") do |i| + h = Hash.ruby2_keywords_hash({k: 1}); a = [1, h]; e = {} + c = Class.new { attr_reader :v; def initialize(*x, **k) = @v = [x, k] } + [method(:kwr).to_proc.call(*a, **e), c.new(*a, **e).v, send(:kwr, *a, **e)] +end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a18bef337..12e57d62c 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1901,6 +1901,47 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/r2kflag (2026-11-28) - a ruby2_keywords hash stays positional at a call with an explicit + `**`, and at a library method's own call; `yield(*args)` makes it keywords; `**h` passes a dup** + (correctness, no switch). Built on aa82bf28 (claude/perf-lsite, which has f67ac44). + - **What CRuby 4.0 does.** A marked hash ending a splatted list is made keywords only at a + splat in Ruby source with no `**` (vm_caller_setup_arg_splat, a call without kw_splat): + `g(*a, **{})`, `g(*a, **nil)`, `super(*a, **{})` keep it positional, the same object with its + mark, and a C method passing its arguments on (Class#new to #initialize, a Method's proc, + Kernel#send, Proc#call) passes them as they came. `yield(*args)` converts as `f(*args)` does. + `**h` alone gives the callee a dup of h: its default, default proc and compare_by_identity + come along, to a `**r` (minus the declared keywords) and to a positional parameter alike. + - **What IronRuby did.** Every splatted call converted the marked hash (MetaObjectBuilder. + AddSplattedArgumentTest, ArgsBuilder, RubyOverloadResolver, RubyMethodGroupBase, + LibraryDispatcher), library sites included; `yield(*args)` never did (a block taking + `*a, **k` got the hash in `a`; language/keyword_arguments' "yield(*ruby2_keyword_args)" + passed only because the lambda's own `target(*args, **kwargs)` converted it - wrongly); and + KeywordSplatArgument's copy dropped the default, default proc and identity comparison. + - **What changed.** RubyCallFlags.HasRuby2KeywordsSplat (4096; FlagsCount 13): set by + CallSiteBuilder on a splat site with no `**` among its arguments, read wherever the mark was + turned back into keywords - a compile-time property of the site, so the rules decide it and + no call pays for it (LibraryDispatcher keeps it in a field for ExpandSplat). Library-made + sites never set it, but Symbol#to_proc's. SuperCall's two keyword sites pass explicitly. Arguments.TransformToYield + converts the splat of a yield without `**` (RubyOps.SplatRuby2Keywords). Hash. + TryCopyAsKeywordArguments and KeywordSplatArgument's general copy keep the default, default + proc and comparer. + - **Checks.** IronRuby.Tests Method_Ruby2KeywordsExplicitSplat1 (CRuby 4.0's output; fails on + the base build). Util/kwsplat-forward-matrix.rb: its three rows that differed now match, and + new rows for yield, Method#to_proc, Class#new and send; with the splat, keyword and forwarding + matrices in every mode: same as CRuby (the one difference is `IR_KWSPLAT_BY_REFERENCE=0`'s known row). Specs language/keyword_arguments, send, def, super, method, + block, yield and core/kernel/send, core/module/ruby2_keywords, core/hash/ruby2_keywords_hash, + core/struct/new, core/method/to_proc, core/proc/ruby2_keywords as before. IronRuby.Tests in + full (Debug): PASSED, 1,403 tests. SymbolProcKeywords1 caught one library site that does convert: + Symbol#to_proc's (Proc.CreateMethodInvoker), whose proc keeps keywords marked in its rest list. + - **Clock** (`ab.rb -r 10`, Release, base aa82bf28): splat-shapes, delegate-shapes (`N=1000000`) + and yield splats (`yield(*a)` 65.7 / 67.6 ns, `yield(*a, **k)` 108.0 / 106.6) unchanged within + their spreads; no instruction counter in this container. + - **Left.** `Struct.new(:x, :y).new(1, h)` stores a copy of a marked h even without a splat + (StructOps; CRuby stores h). An empty `**e` with a default gives a `**k` callee `{}`, where + CRuby gives a dup of e (default 7). `f(*a, k: 1, &g)`: the call convention passes one + trailing list, so `[*a, kw]` is built before the block's #to_proc either way - one array, + nothing to gain; only a #to_proc that changes `a` could tell. + - **perf/kwfwd (/perf-step, 2026-11-27) - `f(*a, **h)` passes `a` itself and no array for an empty `h`; `def m(*, **)` keeps no copy of its arguments for a `super`** (switch `IR_KWSPLAT_BY_REFERENCE` for the first, on unless `=0`). Built on f7ae738b (claude/perf-lsite, From 90dbc93b027cbd9b5c206aa09d788f039fd3e8de Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:24:50 +0000 Subject: [PATCH 257/439] Stage A of the block calling convention, simulated: not built Before writing its matrix or compiler work, the block-cost harness timed what e1's call (a.each { |x| }) would do with a block descriptor: the literal's Proc taken from its slot by the owning thread without an atomic, no scope made, a frame header filled so a scope can be made on demand, the [BlockNotKept] yield, and the Proc given back. e1's steps are 40-44 ns parked as now, 57-62 with the whole header, 41-47 storing only the fields that change per call, and 29-33 with no header (which is not sound). The header's fill is reference stores into a heap object, each a write barrier, the same work the parked scope's reinitialization does; the stage-0 bound took it as free. The tuple must stay, since a send(:binding) in a narrow literal shows the method's locals in CRuby. End to end, ept (ep with a narrow literal in a branch never taken) is 100-102 ns against ep's 90-92 and e1's 145-151: having a literal costs the frame 10 ns and evaluating it 45-49, of which the steps a descriptor would replace are about 29. The harness keeps the simulated rows, the ept shape and a bytes column; the ledger and the design document record the result. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Docs/block-calling-convention.md | 22 ++++ Src/IronRuby.Tests/Perf/BlockCostHarness.cs | 127 +++++++++++++++++++- Util/perf/LEDGER.md | 26 ++++ 3 files changed, 173 insertions(+), 2 deletions(-) diff --git a/Docs/block-calling-convention.md b/Docs/block-calling-convention.md index 163100ae5..185c16526 100644 --- a/Docs/block-calling-convention.md +++ b/Docs/block-calling-convention.md @@ -184,6 +184,28 @@ tried exactly this and saw nothing end to end, where the host's noise was larger shows it. It is a round of its own (the take must stay atomic: two threads may reach for the same parked scope). +### Stage A, simulated before it was built (perf/stagea) + +The harness times `e1`'s call as stage A would make it (the rows "e1: all steps (descriptor, ...)"): the +Proc taken from its slot by the thread that owns it, with no atomic, its scope never made, a frame header +filled for the scope to be made from on demand, the yield, and the Proc given back. ns per call, two runs: + +| `e1`'s steps | ns | bytes | +|---|---|---| +| parked, as now (after perf/endpark) | 40-44 | 24 (the tuple) | +| descriptor, the whole header stored per call | 57-62 | 24 | +| descriptor, only the fields that change per call stored (the tuple, the rfc) | 41-47 | 24 | +| descriptor, no header (not sound: a scope made on demand could not be made) | 29-33 | 0 | + +**Stage A does not pay.** Filling the header is a set of reference stores into a heap object, each a GC +write barrier, which is what the parked scope's reinitialization costs too; the stage-0 bound took the fill +as free. The tuple cannot be dropped (`Locals = null` above): a `send(:binding)` in a narrow literal shows the +method's locals, in CRuby too. And the end to end does not sit in the runtime steps alone: `ept` (`ep` with a +narrow literal in a branch never taken) is 100-102 ns against `ep`'s 90-92 and `e1`'s 145-151, so having a +literal costs the frame 10 ns and evaluating it 45-49, of which the steps a descriptor would replace are about +29. Stages B and D carry the same fill. What would pay is the block reaching the caller's state in place, as +CRuby's captured `ep` does, which objects passed through call sites cannot do. + ## 4. Stages Each behind a switch of its own, with its matrix before its code, keepable alone. diff --git a/Src/IronRuby.Tests/Perf/BlockCostHarness.cs b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs index 38579646b..5c16347a1 100644 --- a/Src/IronRuby.Tests/Perf/BlockCostHarness.cs +++ b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs @@ -27,6 +27,7 @@ namespace IronRuby.Tests.Perf { internal static class BlockCostHarness { + internal static long ProtoNew; private const string Source = @" PE = proc { |x| } PY = proc { 1 } @@ -38,6 +39,7 @@ def nyl(a) = ny { 1 } def e1(a); a.each { |x| }; 1; end def e0(a); 1; end def ep(a); a.each(&PE); 1; end + def ept(a); return a.each { |y| } if a.nil?; a.each(&PE); 1; end def nyp(a) = ny(&PY) def grab(&b) = b def lit1 = grab { 1 } @@ -49,6 +51,7 @@ def sc(a) = binding def bc_run_e1(o, a, n); i = 0; while i < n; o.e1(a); i += 1; end; end def bc_run_e0(o, a, n); i = 0; while i < n; o.e0(a); i += 1; end; end def bc_run_ep(o, a, n); i = 0; while i < n; o.ep(a); i += 1; end; end +def bc_run_ept(o, a, n); i = 0; while i < n; o.ept(a); i += 1; end; end def bc_run_nyp(o, a, n); i = 0; while i < n; o.nyp(a); i += 1; end; end "; @@ -295,9 +298,118 @@ internal static void Run(string[] args) { return last; }); + // ---- stage A, simulated: the literal as a descriptor - a Proc whose scope is made only on demand, taken from + // the slot by the thread that owns it with plain reads and writes, its frame header filled, given back at exit + var hdr = new ProtoHeader(); + var protoSlot = new ProtoSlot { Owner = Environment.CurrentManagedThreadId, Item = procE }; + Report("e1: all steps (descriptor, simulated)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + var locals = new MutableTuple(); + Proc proc = null; + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { proc = protoSlot.Item; protoSlot.Item = null; } + if (proc == null || !proc.TryReuse()) { ProtoNew++; proc = new Proc(ProcKind.Block, o, methodScope, litx.Dispatcher); } + proc.ReuseParked(o, false); + hdr.Shape = shape; hdr.DeclaringScope = declaringScope; hdr.DeclaringModule = declaringModule; hdr.Locals = locals; + hdr.Self = o; hdr.Block = null; hdr.Rfc = rfc0; hdr.Callee = null; + var bfc = RubyOps.CreateBfcForBlockNotKept(proc); + object r; + bfc.Yield(array[0], out r); + RubyOps.LeaveProcConverter(bfc); + RubyOps.LeaveLightMethodFrame(rfc0, null); + if (proc.IsReusableAndInactive) { + hdr.DeclaringScope = null; hdr.DeclaringModule = null; hdr.Locals = null; hdr.Self = null; hdr.Rfc = null; + proc.ClearForPark(); + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { protoSlot.Item = proc; } + } + last = r; + } + return last; + }); + + Report("e1: all steps (descriptor, no header)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + var locals = new MutableTuple(); + Proc proc = null; + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { proc = protoSlot.Item; protoSlot.Item = null; } + if (proc == null || !proc.TryReuse()) { ProtoNew++; proc = new Proc(ProcKind.Block, o, methodScope, litx.Dispatcher); } + proc.ReuseParked(o, false); + + + var bfc = RubyOps.CreateBfcForBlockNotKept(proc); + object r; + bfc.Yield(array[0], out r); + RubyOps.LeaveProcConverter(bfc); + RubyOps.LeaveLightMethodFrame(rfc0, null); + if (proc.IsReusableAndInactive) { + + proc.ClearForPark(); + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { protoSlot.Item = proc; } + } + last = r; + } + return last; + }); + + Report("e1: all steps (descriptor, header: changed only)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + var locals = new MutableTuple(); + Proc proc = null; + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { proc = protoSlot.Item; protoSlot.Item = null; } + if (proc == null || !proc.TryReuse()) { ProtoNew++; proc = new Proc(ProcKind.Block, o, methodScope, litx.Dispatcher); } + proc.ReuseParked(o, false); + if (hdr.Shape != shape) hdr.Shape = shape; if (hdr.DeclaringScope != declaringScope) hdr.DeclaringScope = declaringScope; if (hdr.DeclaringModule != declaringModule) hdr.DeclaringModule = declaringModule; hdr.Locals = locals; + hdr.Rfc = rfc0; + var bfc = RubyOps.CreateBfcForBlockNotKept(proc); + object r; + bfc.Yield(array[0], out r); + RubyOps.LeaveProcConverter(bfc); + RubyOps.LeaveLightMethodFrame(rfc0, null); + if (proc.IsReusableAndInactive) { + hdr.Locals = null; hdr.Rfc = null; + proc.ClearForPark(); + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { protoSlot.Item = proc; } + } + last = r; + } + return last; + }); + + Report("e1: all steps (descriptor, no header, no tuple)", n, k => { + object last = null; + var rfc0 = RubyOps.EnterLightMethod(null); + for (int i = 0; i < k; i++) { + + Proc proc = null; + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { proc = protoSlot.Item; protoSlot.Item = null; } + if (proc == null || !proc.TryReuse()) { ProtoNew++; proc = new Proc(ProcKind.Block, o, methodScope, litx.Dispatcher); } + proc.ReuseParked(o, false); + + + var bfc = RubyOps.CreateBfcForBlockNotKept(proc); + object r; + bfc.Yield(array[0], out r); + RubyOps.LeaveProcConverter(bfc); + RubyOps.LeaveLightMethodFrame(rfc0, null); + if (proc.IsReusableAndInactive) { + + proc.ClearForPark(); + if (protoSlot.Owner == Environment.CurrentManagedThreadId) { protoSlot.Item = proc; } + } + last = r; + } + return last; + }); + + Console.WriteLine(" (descriptor: {0} Procs made)", ProtoNew); // ---- end to end, through Ruby Console.WriteLine(); - foreach (var name in new[] { "nb0", "nyp", "nyl", "e0", "ep", "e1" }) { + foreach (var name in new[] { "nb0", "nyp", "nyl", "e0", "ep", "ept", "e1" }) { ReportRuby(engine, name, n); } } @@ -310,13 +422,15 @@ private static void Report(string label, int n, Func body) { body(n / 10); double best = Double.MaxValue; Taken = 0; + long bytes0 = GC.GetAllocatedBytesForCurrentThread(); for (int round = 0; round < 5; round++) { var sw = Stopwatch.StartNew(); GC.KeepAlive(body(n)); sw.Stop(); best = Math.Min(best, sw.Elapsed.TotalMilliseconds * 1e6 / n); } - Console.WriteLine(" {0,-80} {1,7:F1} ns{2}", label, best, Taken > 0 ? String.Format(" (parked: {0:P0})", Taken / (5.0 * n)) : ""); + Console.WriteLine(" {0,-80} {1,7:F1} ns {3,4} B{2}", label, best, Taken > 0 ? String.Format(" (parked: {0:P0})", Taken / (5.0 * n)) : "", + (GC.GetAllocatedBytesForCurrentThread() - bytes0) / (5 * n)); } private static void ReportRuby(ScriptEngine engine, string name, int n) { @@ -333,4 +447,13 @@ private static void ReportRuby(ScriptEngine engine, string name, int n) { Console.WriteLine(" {0,-80} {1,7:F1} ns", "end to end: " + name + " (the caller's while loop included)", best); } } + // perf/stagea's simulation of a block descriptor (Docs/block-calling-convention.md, "Stage A, simulated"): what the + // scope would be made from on demand, and the slot its Proc is taken from by the thread that owns it. + internal sealed class ProtoHeader { + internal object Shape, DeclaringScope, DeclaringModule, Locals, Self, Block, Rfc, Callee; + } + internal sealed class ProtoSlot { + internal int Owner; + internal Proc Item; + } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 70a044462..609a58014 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1214,6 +1214,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has write is a step of its own, about 8 ns per call (perf/iter3 could not see it end to end). perf/endpark took that step (see Landed): the harness's take-and-park 24 -> 16 ns, end to end within the noise. + perf/stagea simulated stage A in the harness before building it and found nothing to build (see + Rejected): the descriptor's per-call fill costs what the parked cycle costs, `e1`'s steps 44 ns + parked against 46-61 as a descriptor. The literal's 45-50 ns end to end is not in one runtime step. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per @@ -7457,6 +7460,29 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/stagea (round thirty-seven, 2026-11-28) - stage A of `Docs/block-calling-convention.md`, a narrow + literal given to a `[BlockNotKept]` iterator as a block descriptor: simulated, not built** (gap 13). + Before the matrix or the compiler work, the harness (`IronRuby.Tests /blockcost`, now with bytes per + iteration) timed what `e1`'s call would do with a descriptor: the literal's Proc taken from a slot by the + thread that owns it with plain reads and writes (no atomic), its scope never made, a frame header filled + with what the scope would be made from on demand (shape, declaring scope and module, the locals tuple, + self, block, rfc, callee), the `[BlockNotKept]` yield, and the Proc given back cleared. Best of five, + 3,000,000 iterations, two runs, ns per call: `e1`'s steps parked (as now, after perf/endpark) 40-44; + as a descriptor with the full header 57-62; with only the header fields that change per call stored + (the tuple and the rfc; the rest compared first) 41-47; with no header at all 29-33, and that floor + holds the yield's 15 alone. A header is needed (a `send(:binding)` in the block must see the method's + locals, so the tuple stays, and the scope made from it needs the rest), and filling it is reference + stores into a heap object, each a GC write barrier: the same work the parked scope's reinitialization + (`ReuseParkedScopeLazy`, 6 ns) and the cycle's clearing do. The stage-0 bound (~50 ns of `e1`) took the + descriptor's fill as free. End to end the literal's cost sits elsewhere too: `ept`, `ep` with a narrow + literal in a branch never taken, is 100-102 ns against `ep`'s 90-92 and `e1`'s 145-151, so having a + literal costs the frame 10 ns (its tuple, the park checks) and evaluating it 45-49, of which the + runtime steps the descriptor would replace are about 29 (44 less the yield's 15) and the rest the + compiled code around the instantiation. What would pay is the block reaching the caller's state where + it is, CRuby's captured `ep`, without copying it into a heap object per call; the DLR's call sites pass + objects, not references into a frame. Stages B and D carry the same fill (B: `nyl`'s steps 68-73 hold + the same cycle). Left as they were: the code; the harness keeps the simulated rows. + - **perf/procscope (round thirty-seven, 2026-11-28) - a literal's Proc over a scope made but not published as the frame's (change B of `Docs/light-frame-literal-blocks.md`): prototyped, measured, not kept** (gaps 16 and 13). A timing prototype (`IR_PROC_SCOPE=1`): for a body whose literals are all From 4b25733a4267ad3e1054424cf902374b68596241 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:24:53 +0000 Subject: [PATCH 258/439] Method JIT: is_a?, kind_of? and instance_of? of a constant as a class test `x.is_a?(C)` was refused by the method JIT's screen: the census's largest single refused call after `new`, 693 methods. In CRuby it is a walk of the receiver's ancestors with no frame. `x.is_a?(C)`, `kind_of?` and `instance_of?` with C a constant now compile to JitRuntime.IsKindOf: Kernel's test on x's immediate class (singleton included) or, for instance_of?, its class. C is the folded constant under the entry's constant version guard. KernelMethodSite checks that x's class resolves the name to Kernel's method under the global method version, for up to four classes; any other class, and a C that is no module, deopts to the generic call (NoMethodError, method_missing, a redefinition, TypeError). Not where a refinement is active. The ancestors are walked on every test, so a later include, prepend or extend is seen. IR_JIT_TYPE_TEST=0 turns it off. Util/bench/isa-shapes.rb: 14-36% faster than with the switch off (mono 72.9 -> 57.2 ns, poly4 143.6 -> 91.5; CRuby 46.9 and 62.9). Census: 180 methods never -> maybe, none down. Util/jit-isa-matrix.rb (new) and the jit, jit-calls, jit-const, hot-shapes, sdef and extend matrices print CRuby's output in every JIT mode; ruby/spec is_a, kind_of, instance_of and Module#=== and IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 51 +++++++++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 59 +++++++++++ Util/bench/isa-shapes.rb | 42 ++++++++ Util/jit-isa-matrix.rb | 146 ++++++++++++++++++++++++++ Util/perf/LEDGER.md | 36 +++++++ 5 files changed, 334 insertions(+) create mode 100644 Util/bench/isa-shapes.rb create mode 100644 Util/jit-isa-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 02dfdfee3..26867bc8d 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -2481,6 +2481,49 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { return Ast.Constant(false); } + // IR_JIT_TYPE_TEST=0 turns EmitTypeTest off + internal static readonly bool TypeTests = Environment.GetEnvironmentVariable("IR_JIT_TYPE_TEST") != "0"; + + /// `x.is_a?(C)', `x.kind_of?(C)', `x.instance_of?(C)' or the same on self, C a constant and no block. + internal static bool IsTypeTest(MethodCall/*!*/ node) { + if (!TypeTests || node.Block != null || node.Target == null && node.IsVariableCall) { return false; } + if (node.MethodName != "is_a?" && node.MethodName != "kind_of?" && node.MethodName != "instance_of?") { return false; } + var args = node.Arguments; + return args != null && args.Expressions.Length == 1 && args.Expressions[0] is ConstantVariable; + } + + /// + /// `x.is_a?(C)', `x.kind_of?(C)', `x.instance_of?(C)': Kernel's answer, a walk of the ancestors of x's class (its + /// singleton class, with the modules it was extended with, included) or a comparison with x's class + /// (JitRuntime.IsKindOf), with no frame and no call. C is the folded constant (EmitConstant), which the entry's + /// constant version guards. The site (JitRuntime.KernelMethodSite) checks that x's class resolves the name to + /// Kernel's method under the current global method version - which moves when a class is reopened with a method, + /// a module included, prepended or extended, or a singleton class made - and deopts otherwise: a redefined or + /// missing is_a? (a BasicObject, method_missing), and a C that is no module (TypeError) are the generic call's. + /// Ancestors are read when the test runs, so a module included after the body was compiled is seen. Not where a + /// refinement is active: a refined is_a? is what the call reaches. + /// + private MSA.Expression/*!*/ EmitTypeTest(MethodCall/*!*/ node, out JT type) { + if (!_refinements.IsEmpty) { throw Bail(node.MethodName + " with refinements active"); } + var site = new JitRuntime.KernelMethodSite(node.MethodName, LibraryMethods(node.MethodName, _context.ObjectClass)); + MSA.Expression receiver; + if (node.Target == null) { + receiver = _self; + } else { + JT rt; + receiver = Coerce(Emit(node.Target, out rt), rt, JT.Obj); + } + JT ct; + var module = Coerce(Emit(node.Arguments.Expressions[0], out ct), ct, JT.Obj); + // a constant folded to something that is no module would deopt on every call (the TypeError is the generic call's) + var folded = module as MSA.ConstantExpression; + if (folded != null && !(folded.Value is RubyModule)) { throw Bail(node.MethodName + " of a constant that is no module"); } + _canDeopt = true; + type = JT.Bool; + return Ast.Call(JitRuntime.M("IsKindOf"), Ast.Constant(_context), receiver, module, Ast.Constant(site), + Ast.Constant(node.MethodName == "instance_of?")); + } + private MSA.Expression/*!*/ EmitCall(MethodCall/*!*/ node, out JT type) { if (node.Block != null && !PassesNoBlock(node)) { // an iterator with a literal block inside a core iterator's outlined loop: run in place (JitCompiler.Nest.cs) @@ -2500,6 +2543,9 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { // `raise ...' or `fail ...' (EmitRaise): a deopt, and the generic body raises. if (IsRaiseCall(node)) { return EmitRaise(node, out type); } + // `x.is_a?(C)', `kind_of?', `instance_of?' (EmitTypeTest) + if (IsTypeTest(node)) { return EmitTypeTest(node, out type); } + // Self-recursion: `fib(n - 1)' inside `def fib'. Sound because the entry stub pins // the receiver class and the global method version, so no override can slip in. if (_ast != null && _keywords == null && node.Target == null && !node.IsVariableCall && node.MethodName == _ast.Name && argc == _paramNames.Length) { @@ -4220,6 +4266,11 @@ private bool WalkCall(MethodCall/*!*/ node) { return WalkCondition(node.Target); } + if (JitCompiler.IsTypeTest(node)) { + // `x.is_a?(C)' and the like (JitCompiler.EmitTypeTest): x is any object, C a constant + return (node.Target == null || Walk(node.Target)) && (WalkConstant((ConstantVariable)args.Expressions[0]) || No(node)); + } + // `v.nil?', `v == w', `v != w', `v.equal?(w)' on any object (JitCompiler.EmitIdentityCall); `==' // and `!=' between numbers stay EmitBinary's, and `s == "lit"' is EmitStringLiteralComparison's, // which this must not pre-empt (a String literal is no operand Walk takes). diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index 3245b7b88..94ca9eb78 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -422,6 +422,65 @@ public static bool IsIdentical(RubyContext/*!*/ context, object value, object ot return (value is bool) ? value.Equals(other) : ReferenceEquals(value, other); } + /// + /// `x.is_a?(m)', `x.kind_of?(m)' (Kernel#is_a?: the ancestors of x's immediate class, its singleton class included), + /// or `x.instance_of?(m)' (x's class, not its singleton class), once the site found that class to resolve the name + /// to Kernel's method (JitCompiler.EmitTypeTest). A class that does not, and an m that is no module, deopt: the + /// generic call then raises NoMethodError or TypeError, calls method_missing or the method that replaced Kernel's, + /// or converts a CLR type group. The ancestors are walked on every test, as Kernel's method walks them: an include, + /// prepend or extend made after the site bound the class is seen whether or not it moved a method version. + /// + public static bool IsKindOf(RubyContext/*!*/ context, object value, object m, KernelMethodSite/*!*/ site, bool instanceOf) { + var module = m as RubyModule; + if (module == null) { throw Deopt(); } + if (!site.Resolves(ClassOf(context, value))) { throw Deopt(); } + return instanceOf ? module.Context.GetClassOf(value) == module : module.Context.IsKindOf(value, module); + } + + /// + /// Which receiver classes resolve a name to one of the library methods given (KernelMethodSite.Resolves), each under the + /// global method version it was found at, for a few classes at once: a type test (`x.is_a?(C)') sees receivers of + /// several classes far more often than an identity test does. The entries are immutable and replaced whole, so a + /// thread reads an old one or a new one; a lost write only means a class is resolved again. + /// + public sealed class KernelMethodSite { + internal readonly string/*!*/ Name; + private readonly Calls.RubyMemberInfo[]/*!*/ _expected; + private const int Size = 4; + private readonly Entry[]/*!*/ _entries = new Entry[Size]; + private int _next; + + private sealed class Entry { + internal readonly RubyClass/*!*/ Class; + internal readonly int Version; + internal Entry(RubyClass/*!*/ cls, int version) { Class = cls; Version = version; } + } + + internal KernelMethodSite(string/*!*/ name, Calls.RubyMemberInfo[]/*!*/ expected) { + Name = name; + _expected = expected; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal bool Resolves(RubyClass/*!*/ cls) { + int version = RubyModule.GlobalMethodVersion; + for (int i = 0; i < Size; i++) { + var e = System.Threading.Volatile.Read(ref _entries[i]); + if (e != null && e.Class == cls && e.Version == version) { return true; } + } + return Bind(cls, version); + } + + private bool Bind(RubyClass/*!*/ cls, int version) { + var resolved = cls.ResolveMethod(Name, Calls.VisibilityContext.AllVisible); + if (!resolved.Found || cls.GetMethodLookup(Name).Visibility != RubyMethodVisibility.Public || Array.IndexOf(_expected, resolved.Info) < 0) { + return false; + } + System.Threading.Volatile.Write(ref _entries[(_next++ & 0x7fffffff) % Size], new Entry(cls, version)); + return true; + } + } + /// /// `v == nil' (JitCompiler.EmitCollectionEqualsNil): false for an Array or a Hash itself (not a /// subclass; a singleton == is ruled out when compiling) when or diff --git a/Util/bench/isa-shapes.rb b/Util/bench/isa-shapes.rb new file mode 100644 index 000000000..179646f34 --- /dev/null +++ b/Util/bench/isa-shapes.rb @@ -0,0 +1,42 @@ +# is_a?, kind_of? and instance_of? in hot methods (JitCompiler.EmitTypeTest): one receiver class, two, four, a module +# argument, instance_of?, on self. Every line prints the sum of its results next to its time; it must be CRuby's. +# ruby Util/perf/ab.rb Util/bench/isa-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ../ironruby/ir.sh" "new=env IR_CONFIG=Release ./ir.sh" +$stdout.sync = true +class IBase; end +class IDerived < IBase; end +class IS + def isa(x) = x.is_a?(IBase) ? 1 : 0 + def cmp(x) = x.is_a?(Comparable) ? 1 : 0 + def inst(x) = x.instance_of?(IBase) ? 1 : 0 + def num(x) + if x.is_a?(Integer) then 1 + elsif x.is_a?(Float) then 2 + else 3 + end + end + def me = is_a?(IS) ? 1 : 0 +end +def cpu; Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID); end +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times do + t0 = cpu; sum = yield n; d = cpu - t0 + best = d if d < best + end + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +o = IS.new +d = IDerived.new; b = IBase.new +two = [d, b] +four = [d, 1, "s", nil] +mixed = [1, 1.5, "s", 2] +N = (ENV["N"] || 1_000_000).to_i +t("mono", N) { |n| i = 0; r = 0; while i < n; r += o.isa(d); i += 1; end; r } +t("poly2", N) { |n| i = 0; r = 0; while i < n; r += o.isa(two[i & 1]); i += 1; end; r } +t("poly4", N) { |n| i = 0; r = 0; while i < n; r += o.isa(four[i & 3]); i += 1; end; r } +t("module", N) { |n| i = 0; r = 0; while i < n; r += o.cmp(i); i += 1; end; r } +t("instance_of", N) { |n| i = 0; r = 0; while i < n; r += o.inst(b); i += 1; end; r } +t("num", N) { |n| i = 0; r = 0; while i < n; r += o.num(mixed[i & 3]); i += 1; end; r } +t("self", N) { |n| i = 0; r = 0; while i < n; r += o.me; i += 1; end; r } diff --git a/Util/jit-isa-matrix.rb b/Util/jit-isa-matrix.rb new file mode 100644 index 000000000..4f7c78051 --- /dev/null +++ b/Util/jit-isa-matrix.rb @@ -0,0 +1,146 @@ +# Differential matrix for `x.is_a?(C)', `x.kind_of?(C)' and `x.instance_of?(C)' in methods the method JIT +# compiles (JitCompiler.EmitTypeTest, JitRuntime.IsKindOf). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-isa-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-isa-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-isa-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-isa-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep TT +# The traps: a module included, prepended or extended after the body is hot, a singleton class, a class reopened, +# is_a? redefined in a class, a singleton or a refinement, a BasicObject (no is_a?), method_missing, an argument that +# is no module (TypeError), the constant reassigned, Comparable and Enumerable, instance_of? with a singleton class. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +module Mixed; end +module Late; end +module Pre; end +class Base; end +class Derived < Base; end +class Other; end +NotAModule = 5 +Swapped = Base + +class TT + def isa_base(x) = x.is_a?(Base) ? 1 : 0 + def kind_base(x) = x.kind_of?(Base) ? 1 : 0 + def inst_base(x) = x.instance_of?(Base) ? 1 : 0 + def isa_mixed(x) = x.is_a?(Mixed) + def isa_late(x) = x.is_a?(Late) + def isa_pre(x) = x.is_a?(Pre) + def isa_cmp(x) = x.is_a?(Comparable) + def isa_enum(x) = x.is_a?(Enumerable) + def isa_int(x) = x.is_a?(Integer) + def isa_num(x) = x.is_a?(Numeric) + def isa_str(x) = x.is_a?(String) + def isa_mod(x) = x.is_a?(Module) + def isa_class(x) = x.is_a?(Class) + def isa_bad(x) = x.is_a?(NotAModule) + def isa_swapped(x) = x.is_a?(Swapped) + def isa_basic(x) = x.is_a?(BasicObject) + def inst_obj(x) = x.instance_of?(Object) + def self_isa = is_a?(TT) + def self_kind = kind_of?(Comparable) + def branch(x) + if x.is_a?(Integer) + x + 1 + elsif x.is_a?(Float) + x * 2 + else + 0 + end + end +end + +o = TT.new +d = Derived.new +b = Base.new +t("is_a?(Base), hot") { warm { |i| o.isa_base(i.odd? ? d : b) } } +t("is_a?, other receivers") { [o.isa_base(Other.new), o.isa_base(1), o.isa_base(nil), o.isa_base("s"), o.isa_base(:s), o.isa_base(1.5), o.isa_base([1]), o.isa_base({}), o.isa_base(true)] } +t("kind_of?") { warm { |i| o.kind_base(d) }; [o.kind_base(b), o.kind_base(Other.new), o.kind_base(Base)] } +t("instance_of?") { warm { |i| o.inst_base(b) }; [o.inst_base(b), o.inst_base(d), o.inst_base(Base)] } +t("instance_of?, singleton class") { s = Base.new; def s.x = 1; [o.inst_base(s), o.isa_base(s), s.singleton_class.instance_of?(Class)] } +t("instance_of?(Object)") { warm { o.inst_obj(Object.new) }; [o.inst_obj(Object.new), o.inst_obj(b), o.inst_obj(1), o.inst_obj(nil)] } +t("is_a?(Comparable)") { warm { |i| o.isa_cmp(i) }; [o.isa_cmp(1), o.isa_cmp("s"), o.isa_cmp(1.5), o.isa_cmp([]), o.isa_cmp(b), o.isa_cmp(nil)] } +t("is_a?(Enumerable)") { warm { |i| o.isa_enum([i]) }; [o.isa_enum([]), o.isa_enum({}), o.isa_enum(1..2), o.isa_enum("s"), o.isa_enum(Struct.new(:a).new(1))] } +t("is_a?(Integer)") { warm { |i| o.isa_int(i) }; [o.isa_int(2**70), o.isa_int(1.0), o.isa_int(nil)] } +t("is_a?(Numeric)") { warm { |i| o.isa_num(i * 1.5) }; [o.isa_num(1r), o.isa_num(1i), o.isa_num("1")] } +t("is_a?(String)") { warm { |i| o.isa_str("a#{i}") }; [o.isa_str(:a), o.isa_str(Class.new(String).new("x"))] } +t("is_a?(Module), classes") { warm { o.isa_mod(String) }; [o.isa_mod(Comparable), o.isa_mod(1), o.isa_mod(Class.new.singleton_class)] } +t("is_a?(Class), singleton classes") { warm { o.isa_class(Base) }; [o.isa_class(Base.singleton_class), o.isa_class(Mixed), o.isa_class(b.singleton_class)] } +t("is_a?(BasicObject)") { warm { |i| o.isa_basic(i) }; [o.isa_basic(nil), o.isa_basic(BasicObject)] } +t("self is_a?") { warm { o.self_isa }; [o.self_isa, o.self_kind] } +t("branch") { warm { |i| o.branch(i) }; [o.branch(2**70), o.branch(1.5), o.branch("x"), o.branch(nil)] } + +# included, prepended and extended after the body is hot +t("is_a?(Mixed) before") { warm { o.isa_mixed(b) } } +class Base; include Mixed; end +t("include after hot") { [o.isa_mixed(b), o.isa_mixed(d), o.isa_mixed(Other.new)] } +t("is_a?(Pre) before") { warm { o.isa_pre(d) } } +class Derived; prepend Pre; end +t("prepend after hot") { [o.isa_pre(d), o.isa_pre(b)] } +t("is_a?(Late) before") { x = Other.new; warm { o.isa_late(x) } } +t("extend after hot") { x = Other.new; r1 = o.isa_late(x); x.extend(Late); [r1, o.isa_late(x), o.isa_late(Other.new)] } +t("extend a String") { s = +"str"; warm { o.isa_late(s) }; s.extend(Late); [o.isa_late(s), o.isa_late("other")] } +t("Integer includes after hot") { warm { |i| o.isa_late(i) }; class Integer; include Late; end; [o.isa_late(1), o.isa_late(2**70), o.isa_late(1.5)] } + +# an argument that is no module, and a constant reassigned +t("is_a?(5)") { o.isa_bad(1) } +t("is_a?(5), hot") { warm { |i| (o.isa_bad(i) rescue $!.class) } } +t("constant swapped") { warm { o.isa_swapped(d) }; Object.send(:remove_const, :Swapped); Object.const_set(:Swapped, Other); [o.isa_swapped(d), o.isa_swapped(Other.new)] } +t("constant swapped to a non-module") { Object.send(:remove_const, :Swapped); Object.const_set(:Swapped, :sym); (o.isa_swapped(d) rescue $!.class) } + +# receivers without Kernel's is_a? +class Bare < BasicObject; end +class Ghost < BasicObject + def method_missing(name, *args) = [:missing, name, args.size] +end +t("BasicObject receiver") { warm { o.isa_base(b) }; o.isa_base(Bare.new) } +t("method_missing receiver") { warm { o.isa_mixed(b) }; [o.isa_mixed(Ghost.new), o.isa_base(Ghost.new)] } + +# is_a? redefined +class Liar + def is_a?(c) = :lies + def kind_of?(c) = :lies_too +end +t("is_a? redefined in a class") { warm { o.isa_base(b) }; [o.isa_base(Liar.new), o.kind_base(Liar.new)] } +t("is_a? in a singleton") { x = Base.new; warm { o.isa_base(x) }; def x.is_a?(c) = 7; o.isa_base(x) } +t("is_a? redefined on Base later") { warm { o.isa_base(d) }; class Base; def is_a?(c) = false; end; [o.isa_base(d), o.isa_base(b)] } +class Base; remove_method :is_a?; end +t("is_a? restored") { [o.isa_base(d), o.isa_base(b)] } +t("Kernel#is_a? redefined") { warm { o.isa_cmp(1) }; module Kernel; alias_method :__orig_is_a, :is_a?; def is_a?(c) = :kernel; end; o.isa_cmp(1) } +module Kernel; alias_method :is_a?, :__orig_is_a; end +t("Kernel#is_a? restored") { o.isa_cmp(1) } + +module IsARefinement + refine Object do + def is_a?(c) = :refined + end +end +class TT + using IsARefinement + def isa_refined(x) = x.is_a?(Base) +end +t("refined") { warm { o.isa_refined(b) } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8ed1a4b99..555f59ad6 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1901,6 +1901,42 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitisa (2026-11-28, census and timed, not gated) - `is_a?`, `kind_of?` and `instance_of?` in the method JIT's + typed body** (the census's "MethodCall (screen)": is_a? 693; switch `IR_JIT_TYPE_TEST`). Built on happy-gauss + f67ac44 merged with perf/jitbody e19f454. + - **What.** `x.is_a?(C)`, `x.kind_of?(C)` and `x.instance_of?(C)` (or on self), with C a constant and no block, + compile to `JitRuntime.IsKindOf`. It does Kernel's test with no frame or call: the ancestors of x's immediate + class, its singleton class included (`RubyContext.IsKindOf`), or `GetClassOf(x) == C` for instance_of?. + - **Guards.** C is the folded constant, guarded by the entry's constant version. A constant folded to something + that is no module bails at compile time. The new `JitRuntime.KernelMethodSite` checks that x's class resolves + the name to Kernel's method (public) under the current global method version. It keeps four entries + (class, version), each immutable, so a racing write only loses an entry. A class that resolves to anything + else deopts, and the generic call handles it: a BasicObject's NoMethodError, method_missing, a redefinition in + the class, a singleton or Kernel, a non-module C's TypeError, a CLR type group's conversion. Not compiled where + a refinement is active. The ancestors are walked on every test, so an include, prepend or extend after compile + is seen whether or not it moved a method version. + - **The polymorphic site.** IdentityCallSite holds one class and resolves again on every change: an `is_a?` fed + two classes in turn was no faster than the generic call (poly2 89.4 vs 89.3 ns). Four entries fix that. + - **Census** (Src/StdLib, Util/bench, AWFY): 180 methods up, none down, all never -> maybe. 154 are maybe only + because the census resolves no constant without a scope; 26 are behind a call. + - **Hot methods.** AWFY calls none of the three. app-shapes: 118 -> 121 specialized (`Set#__core_set__?`, + `check_refused` twice); declines 29 -> 32. The three new declines are existing screen optimism that the + `is_a?` refusal used to hide: `v.to_i` and `n.call` taken as possible attribute reads (URI::Generic#set_port, + Enumerator::Lazy#size) and a deopt after an effect at `[]` (CSV::Parser#prepare_variable). By clock + (ab.rb -r 7), app-shapes' rules and set overlap the switch off (1.01 each). + - **Clock** (ab.rb -r 3, `Util/bench/isa-shapes.rb`, ns, off -> new, CRuby): mono 72.9 -> 57.2 (46.9), poly2 + 89.8 -> 71.8 (63.5), poly4 143.6 -> 91.5 (62.9), a module argument 76.0 -> 65.7 (51.8), instance_of 67.3 -> + 54.3 (46.1), an Integer/Float/else chain 150.6 -> 126.2 (75.3), on self 71.4 -> 52.3 (42.6); no overlap. + - **Checks.** `Util/jit-isa-matrix.rb` (new, 38 rows): receivers of every kind; Comparable, Enumerable, Module + and Class arguments; instance_of? with a singleton class; include, prepend and extend (an Object, a String, + Integer) after the body is hot; a constant swapped to another class and to a non-module; is_a?(5); a + BasicObject; method_missing; is_a? redefined in a class, a singleton, a class reopened and Kernel, then + restored; refined. It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, + IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, jit-const, hot-shapes, sdef and extend in the same + five modes: CRuby's output on both builds. One sdef run with the JIT on exited 1 with the right output; 19 + more runs (11 on this build, 8 on the base) exited 0. ruby/spec core/kernel is_a, kind_of, instance_of and + core/module/case_compare: no failures on either build. IronRuby.Tests (Debug), all 1,402: PASSED. + - **perf/jitrescue (2026-11-28, census and timed, not gated) - `begin`/`rescue`/`else`/`ensure` in the method JIT's typed body** (gap 22's remainder; switch `IR_JIT_RESCUE`). Built on happy-gauss 4320d4a, perf/jitbody 238d994 and perf/lsite f7ae738 (lazy `$!`, IR_LAZY_ERRINFO). From f1dc7982e1dbae2f7b56b802f1280de6d15da88a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:25:02 +0000 Subject: [PATCH 259/439] LEDGER: perf/jitisa's matrix has 37 rows Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 555f59ad6..ec493fb26 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1927,7 +1927,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **Clock** (ab.rb -r 3, `Util/bench/isa-shapes.rb`, ns, off -> new, CRuby): mono 72.9 -> 57.2 (46.9), poly2 89.8 -> 71.8 (63.5), poly4 143.6 -> 91.5 (62.9), a module argument 76.0 -> 65.7 (51.8), instance_of 67.3 -> 54.3 (46.1), an Integer/Float/else chain 150.6 -> 126.2 (75.3), on self 71.4 -> 52.3 (42.6); no overlap. - - **Checks.** `Util/jit-isa-matrix.rb` (new, 38 rows): receivers of every kind; Comparable, Enumerable, Module + - **Checks.** `Util/jit-isa-matrix.rb` (new, 37 rows): receivers of every kind; Comparable, Enumerable, Module and Class arguments; instance_of? with a singleton class; include, prepend and extend (an Object, a String, Integer) after the body is hot; a constant swapped to another class and to a non-module; is_a?(5); a BasicObject; method_missing; is_a? redefined in a class, a singleton, a class reopened and Kernel, then From 348fde154c744c91babc699a6295fcd42288d899 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:26:25 +0000 Subject: [PATCH 260/439] Ledger: round 6's gate passes (540bdb0 against master) IronRuby.Tests on Debug, the matrices in seven modes and the JIT matrices again on the fixed build, the probes, all five ruby/spec suites, the timing and start-up pass on 540bdb0, after the two fixes the gate made (havlak2's unlocked method-table reads, json's case dispatch of Symbol whens). AWFY is about 9% faster than master in both orders (Sieve 0.45, Json 0.92). Round 6's entries are marked gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 88 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 68 insertions(+), 20 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 74b2740b6..9d4b8e3b4 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -916,7 +916,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has objects, two Integers and two Strings (05a31f0a, merged into this branch after round nine): the cases this session's perf/neq1 found faster, without the Integer-against- Float one it found slower. - Round of 2026-11-27 (see Landed, perf/neqrule, not gated): the negated-builtin rule for plain objects is + Round of 2026-11-27 (see Landed, perf/neqrule): the negated-builtin rule for plain objects is shared by every class whose `==` is BasicObject's: a site over 2-60 classes no longer has a rule per class. 11. **The method JIT refuses a constant whose value is nil** ("constant without a value": it cannot tell nil from an autoload that has not run). Richards' `NO_WORK = nil` and @@ -1025,7 +1025,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has allocates), 0.51-0.70 of the time. Left: `any?`, `find` and `each_with_index` (Enumerable's C# goes through `each` and a SplattingBlock: the bytes are its own, not the parking's) and the literal given to a core iterator outside the parked list. - perf/iter2 (see Landed, not gated) took `find` and `any?`: Array's own, as in CRuby 4.0, and + perf/iter2 (see Landed) took `find` and `any?`: Array's own, as in CRuby 4.0, and parked - `find1` 298 ns / 885 B -> 113 / 69 (CRuby 66), `any1` 172 / 397 -> 107 / 69 (CRuby 55). `upto` and `downto` were tried the same way and left out: a parked slot around them takes Permute from 124.5 to 53.9 MB per iteration and costs 3.8% more instructions, its time @@ -1901,6 +1901,54 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-28 for round 6 of round thirty-seven** (perf/crubydiff's third and fourth rounds, + perf/sieve and gap 39's analysis, perf/evallocals, perf/evalscreen, perf/evalboxes, perf/hsortby, + perf/arymin, perf/rescuelight and perf/splatpos with castcheck's, nilblock's and dotsfwd's findings, + perf/iter2 with the yieldloop and yieldresume designs, perf/nbody2, perf/fiberbound, perf/loopconst, + perf/loopnear, perf/json, perf/jitblockparam with delegate's findings, perf/neqrule, perf/lightmember, + perf/havlak2): the branch `claude/happy-gauss-95wm2j` at 540bdb0 against master f81fc19, Release + net10.0, four cores: **PASS, after two fixes the gate made** (8828a02 is the merge; see "Caught by the + gate (round thirty-seven, round 6)"): + - f67ac44: perf/havlak2 read class method tables outside the class hierarchy lock; the Debug build's + assertion aborted 11 IronRuby.Tests processes. + - 540bdb0: perf/json's case dispatch took Symbol `when`s for Strings (`case "all" when :all`); three + library/matrix specs failed in the sweep. + The merge itself: JitLoopCompiler's IR_LOOP_EXITS and IR_LOOP_CONSTANTS fields (both kept), and one entry + the ledger merges doubled (dropped). ReflectionCache.Generated.cs as merged is what ClassInitGenerator + writes. No new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,403 tests, every one executed, none failed, on 540bdb0 + (and 1,402 on f67ac44; the first run, on 8828a02, aborted 11 processes on the havlak2 assertion). + `gate-matrices.rb --all` in 7 modes (the six default ones, and every round 6 switch off at once: + IR_BLOCK_LOOP_SCOPED, IR_CASE_DISPATCH, IR_CONST_OWN_FIRST, IR_EVAL_LITERALS, IR_EVAL_LOCAL_CACHE, + IR_EVAL_SHARE_DEFINED, IR_FIBER_BOUND, IR_JIT_BLOCK_PARAM, IR_JIT_NESTED, IR_LAZY_ERRINFO, + IR_LIGHT_MEMBER_OPASSIGN, IR_LOOP_CONSTANTS, IR_LOOP_EXITS, IR_LOOP_NEAR, IR_PARKED_FIND, IR_SHARED_NEQ, + IR_SPLAT_BY_REFERENCE; each experiment ran its own switch off alone), on 8828a02: 1,235 same, 115 + baseline, 1 flaky, 21 DIFF, each explained: callable-parameters the prelude line of `Kernel#puts` + again; regexp-binary-ctype 18 lines from CRuby against master's 50, its rows' ISO-8859-1 column now + CRuby's and their UTF-8 column wrong as on master (left by perf/crubydiff for its cost), so whole lines + differ in a new way; string-race-matrix, which races on purpose, compared over five runs of each tree + (rows not always ok 108 -> 86, lost writes 106 -> 0, as at round 5). The JIT matrices (jit, jit-calls, + unsampled, inline, hot-shapes, jit-blockparam, loop-const) again on f67ac44: 330 same, 6 baseline. + A probe file for the experiments' named hot spots - fifteen ways of assigning a local inside an outlined + block loop read after it (perf/nbody2's AssignsVariable: masgn, op-assign, ||=, &&=, binding, eval, an + inner block, a named capture, pattern matching, a rescue variable, `for`, a lambda, a while, a thread), + `!=` on objects with singleton methods as `==` is defined later (perf/singleton with perf/neqrule), an + eval'd text's regexp identity through dup, curry and a method (perf/evalboxes), `case` before and after + `using`, send frames, Module#name encodings and Kernel#binding through a Method - prints CRuby's output + with the JIT on and off and with IR_LOOP_EXITS=0. perf/fiberbound with two runtimes abandoning 1,500 + enumerators each at once: both right, under 300 threads, as on master. + ruby/spec, all five suites (32,285 examples): no failure the known list does not name on 540bdb0 (on + 8828a02 the three Matrix examples above). + Census against master (Src/StdLib, Util/bench, AWFY): light frames 91.7% -> 94.3% (708 up, one down: + Math.__ir_log__, as at round 5), method JIT 243 up, none down. + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.920 and 0.899; none + more than 5% slower in both. Alone, five rounds in each order, medians new/base: Sieve 0.433 / 0.470, + Json 0.930 / 0.914, NBody 0.929 / 0.972, List 1.005 / 1.018. micro-table in both orders: no line more + than 5% slower in either. + Start-up on the R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 497 -> 506 and + 502 -> 471, `gem --version` 590 -> 572 and 577 -> 590, `gem list` 1006 -> 989 and 977 -> 982, + `require "irb"` 1029 -> 1005 and 984 -> 992, irb 1+1 1133 -> 1071 and 1065 -> 1066: level. + - **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, perf/twospeed and its note, perf/extiter4 and 5, perf/fiberstart, perf/iter, perf/strsearch3 and 4, @@ -1950,7 +1998,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 477 -> 467, `gem --version` 532 -> 547 and 552 -> 551, `gem list` 935 -> 921 and 950 -> 955, `require "irb"` 953 -> 958 and 974 -> 932, irb 1+1 1063 -> 1037 and 1091 -> 1047: round 4's `-e 1` loss is won back (perf/startup3 and 4). -- **perf/sieve (2026-11-27, not gated) - a block-local first assigned inside an `if` branch or a +- **perf/sieve (2026-11-27, gated 2026-11-28 (round 6's gate entry)) - a block-local first assigned inside an `if` branch or a `while` body no longer keeps the block from being outlined** (switch `IR_BLOCK_LOOP_SCOPED`). AWFY Sieve allocated 100.3 MB per iteration (alloc.rb). Bytes per `sieve` call, by variants: the `while` loops alone 1 KB beyond the 40 KB flags Array; `(2..size).each` with the real block 296 KB, @@ -1977,7 +2025,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has R2R row as the base); spec/core/array 2,898 examples, the one known error on both. Base 9c4f953 (4320d4a with 8c31db5); the base needed DLR patches 0111 and 0112 applied by hand. - **perf/arymin (/perf-step, 2026-11-27, on ed49c52) - `Array#take` is Array's own, as MRI's - `rb_ary_take`** - clock only, not gated. Array inherited Enumerable's C# take, a walk of + `rb_ary_take`** - clock only, gated 2026-11-28 (round 6's gate entry). Array inherited Enumerable's C# take, a walk of #each through a Proc: `[1, 2, 3, 4].take(2)` 248.0 -> 83.1 ns (CRuby 71.5), `first_n`, `min`, `max`, `minmax` within the noise. Six cases of `Util/array-take-matrix.rb` (new) now print CRuby's output: the owner, the backtrace label, a subclass's own #each and a redefined @@ -1989,7 +2037,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has was left: its Fixnum path is there, what remains is the call. - **perf/hsortby (/perf-core, 2026-11-27, on 5472a50) - `sort_by`, `min_by(n)` and - `max_by(n)` of a Hash, a Range or an Enumerator through the C# merge sort** (the gap 15 survey's + `max_by(n)` of a Hash, a Range or an Enumerator through the C# merge sort** (gated 2026-11-28, round 6's gate entry) (the gap 15 survey's largest Ruby row in nanoseconds over CRuby: `Hash#sort_by` +1250 ns). The generic walk made [key, index, element] triples and sorted them with a Ruby comparison block; now the elements it gathers go to `__list_sort_by__` (the C# stable merge sort, as an Array's already did) with @@ -2013,7 +2061,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/evalboxes (/perf-step, 2026-11-27, on 4320d4a + perf/lexical 779d87c) - an eval'd text with regexp or range literals shares its compiled code, the literals' objects kept per - eval (`IR_EVAL_LITERALS`, gap 31)** - instructions only, not gated. The commonest refusal left + eval (`IR_EVAL_LITERALS`, gap 31)** - instructions only, gated 2026-11-28 (round 6's gate entry). The commonest refusal left by perf/evalscreen (6 of the 11 refused stdlib templates; 2.7 times a shared render). - What CRuby does, checked first (CRuby 4.0): a regexp literal of the text's top level is a new object per eval and the same one for every pass of one eval's `while`; one in a block, the @@ -2057,7 +2105,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/evalscreen (/perf-step, 2026-11-27, on 4320d4a + perf/lexical b45360c) - an eval'd text with `defined?` shares its compiled code (`IR_EVAL_SHARE_DEFINED`, gap 31)** - - instructions only, not gated. Measured first, which refusals of perf/erb36's screen real + instructions only, gated 2026-11-28 (round 6's gate entry). Measured first, which refusals of perf/erb36's screen real templates hit (ERB.new(...).src of every `.erb`, `.rhtml` and `.tt` of Src/StdLib and erb-shapes' page, parsed with Prism under CRuby): 80 templates, 69 shared, 11 refused - a regexp literal in 6 (4 alone: `/^\w+\./m`, `%r{\A[^/]+(?=/)}`), `defined?` in 5 (3 alone, all @@ -2100,7 +2148,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/evallocals (/perf-step, 2026-11-27, on b887bc1 + perf/lexical a87b5dc) - a site of eval'd code remembers where a local it knows by name resolved (`IR_EVAL_LOCAL_CACHE`, gap - 31)** - instructions only, not gated. Eval'd code reads a local the text does not declare + 31)** - instructions only, gated 2026-11-28 (round 6's gate entry). Eval'd code reads a local the text does not declare (the binding's, or one an earlier eval defined - an eval's own top-level locals are such, ERB's `_erbout` among them) through `RubyOps.GetLocalVariable(scope, name)`: a walk up the scopes, at each a string lookup in its static mapping and, where an eval or Binding defined @@ -2145,7 +2193,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `ReflectionCache.Generated.cs` from ClassInitGenerator, identical to the entries written by hand. Not run: R2R. - **perf/splatpos (/perf-step, 2026-11-27) - `f(*a, &b)' passes `a' itself, not a copy, when - `b' is a variable, a constant or a literal** (switch `IR_SPLAT_BY_REFERENCE`, on unless `=0`). + `b' is a variable, a constant or a literal** (gated 2026-11-28, round 6's gate entry) (switch `IR_SPLAT_BY_REFERENCE`, on unless `=0`). Built on 288cc13 (claude/perf-lsite, which has 4320d4a). - **What the round asked, and where the cost was.** A splat into a fixed-arity Ruby callee already costs what the call written out does (`two(*a)` 46 ns, `two(a[0], a[1])` 51, @@ -2188,7 +2236,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has copies where CRuby does not (the splat is not trailing there; pre-existing). - **perf/rescuelight (/perf-frame, 2026-11-27) - `$!` left alone in a begin/rescue/ensure that - raises nothing** (switch `IR_LAZY_ERRINFO`, on unless `=0`) - timed, not gated. Built on + raises nothing** (switch `IR_LAZY_ERRINFO`, on unless `=0`) - timed, gated 2026-11-28 (round 6's gate entry). Built on 4320d4a with claude/perf-lsite merged (d83116b). - **What gap 22 is now.** Its 80 ns predate b72da7b: `resc` and `ens` of zjit-post-shapes are light frames (`IR_LIGHT_FRAMES=why`), and the method JIT refuses them (`screen rejected @@ -2234,7 +2282,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the read of `$!` at a rescue's entry. - **perf/loopnear (round thirty-nine, 2026-11-27) - a running loop sees a nearer constant appear; a - module's own constants before its prepends (gap 29)** - not gated. A compiled loop that folded a + module's own constants before its prepends (gap 29)** - gated 2026-11-28 (round 6's gate entry). A compiled loop that folded a constant (an outlined loop, or a typed method body's) went on answering it after another thread made a constant of that name nearer to the lookup (lexically, in a superclass, through an include or a prepend): a new constant moves `ConstantAccessVersion` only, which a running loop's safe point does @@ -2272,7 +2320,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has either build. The census cannot see this. - **perf/loopconst (round thirty-eight, 2026-11-27) - an outlined loop looks its folded constants up - again at its entry (gap 29)** - not gated. A loop outlined by OSR (`JitLoopCompiler`) that folded a + again at its entry (gap 29)** - gated 2026-11-28 (round 6's gate entry). A loop outlined by OSR (`JitLoopCompiler`) that folded a constant guarded its entry on the runtime's constant version as it was when the copy was compiled, which every new constant, `extend`, singleton class and `require` moves: the copy handed itself back (`OsrVersionStale`), the site rebuilt it after `StaleRebuildSpacing` of the generic loop, and so on @@ -2306,7 +2354,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has PASS, 63 same, 9 baseline (hot-shapes in every mode, block-loop under R2R, as the baseline). ruby/spec language/constants, core/module const_set, remove_const, autoload, core/kernel autoload: no failures on either build. The census cannot see this (no method changes verdict). -- **perf/jitblockparam (2026-11-27, census and timed, not gated) - a typed body for a call without a block** +- **perf/jitblockparam (2026-11-27, census and timed, gated 2026-11-28 (round 6's gate entry)) - a typed body for a call without a block** (switch `IR_JIT_BLOCK_PARAM`). A method whose block parameter is only passed on, `def w(a, b, &k) = @t.two(a, b, &k)`, was never wrapped (`JitStub.ParameterShape`: "block parameter"), and one passing `&nil` was refused at the screen (a call with a block). Now `JitStub.BlockParameterOnlyPassed` takes a method whose @@ -2340,7 +2388,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and hot-shapes in the same five modes: the same as the base (forward-rest's six bind_call-of-binding rows differ from CRuby on both). ruby/spec language block, send, yield, super, def and proc: the same as the base (send's one error is the known `into`). IronRuby.Tests, all 1,377: PASSED. -- **perf/lightmember (2026-11-27) - `recv.m op= v` in a light frame (gap 9)** - not gated. Chosen by the census of +- **perf/lightmember (2026-11-27) - `recv.m op= v` in a light frame (gap 9)** - gated 2026-11-28 (round 6's gate entry). Chosen by the census of 4320d4a + perf/neqrule: what keeps methods out of light frames is now mostly a regular expression whose method sets the caller's `$~` (gsub 273, `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54 - about 880 methods, which perf/regexlight found need a cheaper late scope or second call, not a filter change), a Range in a body with literal @@ -2373,7 +2421,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (CRuby does); the matrix traces only the method's own `:call`. - **perf/neqrule (2026-11-27) - `a != b` on plain objects is one rule for every class (gaps 10 and 12)** - - not gated. `DispatchIntrinsics.TryBuildNotEquals` (#215) binds `a != b` as `!a.equal?(b)` when the + gated 2026-11-28 (round 6's gate entry). `DispatchIntrinsics.TryBuildNotEquals` (#215) binds `a != b` as `!a.equal?(b)` when the receiver's `==` is BasicObject's, and `MaySpecialize` kept such rules out of IronRuby's shared rules, so a site saw a rule per receiver class: over two to eight classes it missed its target on every other call into the DLR's `UpdateAndExecute`, whose speed the CLR's dynamic PGO decided (gap 12, perf/twospeed2), and over @@ -2735,7 +2783,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the stub's lock on the light compiler's thread. - **perf/fiberbound (2026-11-27) - fibers abandoned while suspended are bounded: a collection when the fibers holding a thread have grown by 256, the reclaimed threads parked for the next ones - (gap 35)** - not gated. Base 78bbfb1 (the round-38 branch at 15285eb with perf/fiberstart). A + (gap 35)** - gated 2026-11-28 (round 6's gate entry). Base 78bbfb1 (the round-38 branch at 15285eb with perf/fiberstart). A suspended fiber holds a thread until a collection finds its handle, and the collector knows nothing of the thread: 3,000 abandoned generators were three collections and 3,017 threads. Now `ThreadOps.FiberCore.Run` counts the fibers that hold a thread, and a fiber about to start @@ -3053,7 +3101,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Kernel#binding through Method#call/bind_call/to_proc raises; RubyRegex.MatchWindow has an allowBroken overload. - **perf/json (2026-11-27) - `case` over String literals looks its subject up once while String#=== - is the library's (gap 7)** - not gated. Commit 0a78877 on `claude/perf-strsearch`, based on + is the library's (gap 7)** - gated 2026-11-28 (round 6's gate entry). Commit 0a78877 on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j 15285eb with 0518f08 merged in. Measured first: a perf profile of AWFY Json at steady state put the one-character String comparisons at about 11% of self time and the Range of `@input[a..b]` under 1%; `@current = @input[@index]` escapes, so its String has to be @@ -3240,7 +3288,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has R2R run. - **perf/havlak2 (/perf-step, 2026-11-27, on e68ac13) - an attribute read or write on a local nothing samples, and the candidates of an unsampled call found in classes nested in modules (gaps 25, 1)** - - not gated. Two parts. (1) `UnsampledAttrVariable`: `x.a` and `x.a = v`, x a local of the method the + gated 2026-11-28 (round 6's gate entry). Two parts. (1) `UnsampledAttrVariable`: `x.a` and `x.a = v`, x a local of the method the profile has no sample of, read and write the variable through the sampled path's sites (`ReadSelfAttr`, `WriteAttr`: each checks the class it meets and deopts where the accessor is not that variable's, a write before storing anything); the name is the one the classes a call on x was inlined @@ -4028,7 +4076,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/iter2 (round thirty-seven, 2026-11-27) - Array#find, #detect, #any?, #all? and #none? are Array's own and, with #find_index and #index, let the method that gives them a literal park - (gap 13)** - instructions, bytes and time, not gated. An Array's `find` and `detect` were + (gap 13)** - instructions, bytes and time, gated 2026-11-28 (round 6's gate entry). An Array's `find` and `detect` were Enumerable's: a call site to `each`, a C# SplattingBlock (a Proc, a closure) and an Array per element - 885 bytes to find in `[1]` - and, being in `NeverParkedIterators`, no parked slot for the method that called them. CRuby 4.0 has them as Array's own (`rb_ary_find`), with `any?`, @@ -4135,7 +4183,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `InstantiateNestedParkedBlockSlow`, and the Proc[] cleared when another thread keeps); and any way a literal's Proc reaches Ruby without clearing its reusable flag. - **perf/nbody2 7621c60 (round thirty-nine, 2026-11-27) - an OSR loop's exits box Integers through - the cache and store back only what the copy changed and someone reads (gap 2)** - not gated. + the cache and store back only what the copy changed and someone reads (gap 2)** - gated 2026-11-28 (round 6's gate entry). What perf/nbody left of NBody (48 MB, 192 bytes per `advance`) was traced by variants of `advance` under the allocation-tick probe (the outer `each_index` alone; with the nested loop; with the inner body; the `each` loop; a block local), each subtracted from the next: the boxes were made at the From 22dcf95a5ed649fec570b76d69c3329d2e8a00aa Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:27:35 +0000 Subject: [PATCH 261/439] Ledger: drop the entries the merge of claude/perf-extiter doubled Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 35 ----------------------------------- 1 file changed, 35 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index b70310f66..3e3ade756 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2924,41 +2924,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - For the gate: a stub whose generic body is still interpreted now probes more (up to 16 short probes of 32 timed calls each in its first 100 ms after the compile); `GenericCompiled` now takes the stub's lock on the light compiler's thread. -- **perf/fiberbound (2026-11-27) - fibers abandoned while suspended are bounded: a collection when - the fibers holding a thread have grown by 256, the reclaimed threads parked for the next ones - (gap 35)** - gated 2026-11-28 (round 6's gate entry). Base 78bbfb1 (the round-38 branch at 15285eb with perf/fiberstart). A - suspended fiber holds a thread until a collection finds its handle, and the collector knows - nothing of the thread: 3,000 abandoned generators were three collections and 3,017 threads. Now - `ThreadOps.FiberCore.Run` counts the fibers that hold a thread, and a fiber about to start - (`__fiber_reuse__`) collects when the count has grown by 256 since the lowest it has been since - the last collection; the pool of parked fiber threads is as large as the bound (8 before), so - the threads the collection reclaims are the next fibers' instead of ending (a pool of 8 made the - bound cost 15-25% per abandoned enumerator: 862-927 against 748 us). A collection that reclaims - fewer than a quarter of the interval's fibers (counted as they unwind, an interval of starts - later) doubles the interval: a program whose fibers are alive, or held by a block on their own - thread that closes over them (`e = xs.lazy.map { |x| ... }; e.next`), which no collector sees - past, paid twice per enumerator when every 256 starts collected over 10,000 threads (1,073 -> - 1,918 us); a first try that judged by the lowest count since the collection doubled the interval - while the reclaimed threads were still unwinding and let 2,787 pile up. GC.AddMemoryPressure for - each fiber's stack, tried instead: 18-21 collections in 3,000, 608-742 threads at the peak. - `IR_FIBER_BOUND=0` turns it off (and the pool back to 8); bounds of 64-1024 measured, 256 kept. - `extiter-abandoned.rb`, 10,000 each, base -> new: a lazy made in a method 1,229 us, peak 1,066 - threads, 359 MB -> 689 us, 281, 174 MB; a generator 1,282 us, 513, 335 MB -> 700 us, 280, 165 MB; - the ones a block holds 1,073-1,126 us, 10,018 threads -> 1,119-1,145 us, 10,017 (unchanged: not - reachable while a fiber is a thread). `fiber-start.rb`: fibers that finish and threads level - (`fiber_complete` 13 / 18 us, `gen_drain` 136 / 142, `thread_join` 199 / 196), abandoned ones - 281-294 threads after 3,000 against 2,823-3,017. Cursor shapes level (`ab.rb -r 6`, 0.96-1.07, all - overlapping). With it, the cursor path's StopIteration when StopIteration#new or #initialize is the - program's: made in C# it was another object than the one rescued, so a later end's cause was not - the first, and `map`'s result was lost; now the cursor hands the end to the prelude's - __iter_stop__ as the fiber path does (`__iter_slow__` op 4). `Util/extiter-matrix.rb` (332 probes) - prints CRuby's output with the bound and without; base differs in that probe only, off - (IR_FAST_NEXT=0) in `flm_to_ary_next` only. fiber-reclaim-matrix passes in every mode; - enum-next- and raise-matrix the same on base, new, off and without the bound. spec/core/fiber, - enumerator, thread and kernel/loop_spec: 1,026 examples, 0 failures on base, new and without - the bound; the Enumerator*, Lazy*, Loop*, Fiber*, Thread*, Exception* and Raise* IronRuby.Tests - (60) pass in five plain runs on base and five on new. - - **perf/fiberstart (2026-11-27) - what a fiber's start costs, found; the end of an iteration on a fiber raised from C# and its stack walk deferred, as a cursor's is (gap 35)** - gated 2026-11-27 (round 5's gate entry). Base 8d7efda (the round-38 branch with perf/extiter5). Measured first (`Util/bench/fiber-start.rb`, From 9bb53b9663b8bb6859f5d7b81402a8a6d8a8de5c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:28:40 +0000 Subject: [PATCH 262/439] Ledger: perf/iter2's rejected downto, since taken by perf/permute perf/iter2 recorded [BlockNotKept] on Integer#downto as rejected (Permute's instructions up, time level); perf/permute takes it with parked scopes for each level of a recursion and measures Permute at 0.933. A line under iter2's entry says so, so the two entries do not contradict each other. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f48a035ae..ddd62b98d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -4414,6 +4414,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `instance_method`, `super` from a subclass, `Enumerable.instance_method(:find).bind_call(ary)`); a method parked around `h.find { }` on a Hash, which is still Enumerable's and keeps no Proc, until its slot gives up (`ParkedScopeSlot.MaxFailures`). + Since taken for #downto by perf/permute (2026-11-27, see Landed): with ParkedScopeSlot.Deeper serving each level of a + recursion (IR_PARKED_DEPTH), Permute's time went to 0.933 where `[BlockNotKept]` alone was level; #upto stays off. - **perf/iter (round thirty-seven, 2026-11-26) - a block that holds a block literal reuses its scope and the literal's Proc (gaps 13 and 6)** - instructions and bytes, gated 2026-11-27 (round 5's gate entry). A block whose From 58013a922f24202e103d4d4353cdec822ecee464 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:40:36 +0000 Subject: [PATCH 263/439] Store Integer instance variables raw in the typed code (IR_RAW_INTS), as measured The implementation perf/intivar measured; the next commit takes the runtime part out again (see Util/perf/LEDGER.md, Rejected, perf/intivar). It is kept in the history as the starting point for a later attempt. An Integer the method JIT holds as an int or a long goes into an IntLocation (a long and a cached box) in the raw shapes Float locations already use: SetIVarLong and WriteAttrLong store it, GetIVarInt/GetIVarLong and ReadSelfAttrInt/ReadSelfAttrLong read it without a box and deopt where GuardInt/GuardLong would, ValueOf boxes it for everything else. A typed store over an Int32 or Int64 promotes the object (its class's later instances are born raw) unless the value is one the small-integer cache boxes; a raw write of such a value stores the cached box. A Bignum is never in a location. RubyClass.FloatsRaw becomes BornRaw. The generic @x read and the JIT's GetIVar try a raw object's cached read inline before going out of line, as the attr_reader dispatcher already did. Util/ivar-matrix.rb and Util/jit-matrix.rb (section 21) get Integer rows: read back across the cache, Int32, Int64 and Bignum ranges, type changes, identity and hash, YAML, Marshal, inspect, instance_variable_get/set, remove, freeze, dup/clone, Ractor.make_shareable, binding, a subclass with more variables, promotion with plain and born-raw objects at one site, the raw tree's growth and removal, too complex, and two threads; Util/ivar-stress.rb's promotion part gets typed Integer updates. Util/bench/intivar-shapes.rb times the shapes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Ruby/Builtins/RubyClass.cs | 8 +- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 6 +- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 7 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 31 +++- Src/Ruby/Runtime/Jit/JitRuntime.cs | 169 +++++++++++++++++++- Src/Ruby/Runtime/RubyInstanceData.cs | 161 ++++++++++++++++--- Src/Ruby/Runtime/RubyOps.cs | 103 +++++++++++- Util/bench/intivar-shapes.rb | 112 +++++++++++++ Util/ivar-matrix.rb | 107 +++++++++++++ Util/ivar-stress.rb | 8 +- Util/jit-matrix.rb | 70 ++++++++ 11 files changed, 742 insertions(+), 40 deletions(-) create mode 100644 Util/bench/intivar-shapes.rb diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index 7cc4c7563..5f622556f 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -111,11 +111,11 @@ public void UndefineAllocator() { internal int InstanceVariableCapacity; /// - /// An instance of this class has been promoted to raw Float storage (RubyInstanceData, "Float - /// locations"): new instances start in the raw shape tree, so that they need no Move of their - /// own. Set once, never cleared; a racy read only costs one instance a Move. + /// An instance of this class has been promoted to raw Float or Integer storage (RubyInstanceData, + /// "Float locations"): new instances start in the raw shape tree, so that they need no Move of + /// their own. Set once, never cleared; a racy read only costs one instance a Move. /// - internal bool FloatsRaw; + internal bool BornRaw; // // Null if this class doesn't represent a CLR type, it represets a CLR type that implements IRubyObject or diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 26c39724c..e8c6391c3 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1972,6 +1972,10 @@ private static string AgreedAccessorVariable(IEnumerable/*!*/ classes // a Float stored raw (RubyInstanceData, "Float locations") ? Ast.Call(JitRuntime.M("WriteAttrDouble"), Ast.Constant(_context), receiverTemp, valueTemp, Ast.Constant(new JitRuntime.SelfAttrSite(node.Name, variableName, explicitReceiver, true))) + : (RawInts && IsInteger(valueType)) + // an Integer stored raw too + ? Ast.Call(JitRuntime.M("WriteAttrLong"), Ast.Constant(_context), receiverTemp, Coerce(valueTemp, valueType, JT.Lng), + Ast.Constant(new JitRuntime.SelfAttrSite(node.Name, variableName, explicitReceiver, true))) : Ast.Call(JitRuntime.M("WriteAttr"), Ast.Constant(_context), receiverTemp, BoxForStore(valueTemp, valueType), Ast.Constant(new JitRuntime.SelfAttrSite(node.Name, variableName, explicitReceiver, true))), valueTemp @@ -2197,7 +2201,7 @@ private static JT ElementType(RubyArray/*!*/ array) { switch (t) { case JT.Int: return e; case JT.Lng: return Coerce(e, JT.Lng, JT.Int); - case JT.Obj: _canDeopt = true; return Ast.Call(JitRuntime.M("GuardInt"), e); + case JT.Obj: _canDeopt = true; return GuardIVarRead("GuardInt", e); default: throw Bail("Array index of type " + t); } } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index b806de9fa..aae072d8d 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -102,7 +102,8 @@ private MSA.Expression TrySinkIVarWrite(SimpleAssignmentExpression/*!*/ node, st // An Integer written as an Int32 and as an Int64 is one Ruby class in two representations: held in one long, // and stored through NarrowLong, which boxes a value that fits an Int32 as the Int32 the generic body stores. // A Float and an Integer, or a number and an object, are not widened: a Float is stored raw (SetIVarDouble) - // and an Integer boxed, and one typed local cannot say which of the two classes the variable holds. + // and an Integer raw too (SetIVarLong) or boxed, and one typed local cannot say which of the two classes the + // variable holds. if (vt == JT.Int && _sinkWide != null && _sinkWide.Contains(name)) { v = Coerce(v, JT.Int, JT.Lng); vt = JT.Lng; @@ -227,6 +228,8 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { } storeOf[s] = (s.Type == JT.Dbl) ? Ast.Call(JitRuntime.M("SetIVarDouble"), Ast.Constant(_context), _self, s.Value, site) + : (RawInts && IsInteger(s.Type)) + ? Ast.Call(JitRuntime.M("SetIVarLong"), Ast.Constant(_context), _self, Coerce(s.Value, s.Type, JT.Lng), site) : Ast.Call(JitRuntime.M("SetIVar"), Ast.Constant(_context), _self, Coerce(s.Value, s.Type, JT.Obj), site); } var stores = new List(); @@ -274,7 +277,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { /// could read a held-back variable, of self or of an object that is self, and compiles the body without. /// private static readonly HashSet/*!*/ _sinkSafeHelpers = new HashSet { - "GetIVar", "GetIVarDouble", "GetIVarSpeculateDouble", "GuardInt", "GuardLong", "GuardDouble", "SpeculateDouble", "StringLength", "StringIndex", "StringEqualsLiteral", "StringEqualsString", "CaseString", + "GetIVar", "GetIVarDouble", "GetIVarSpeculateDouble", "GetIVarInt", "GetIVarLong", "GuardInt", "GuardLong", "GuardDouble", "SpeculateDouble", "StringLength", "StringIndex", "StringEqualsLiteral", "StringEqualsString", "CaseString", // Integer arithmetic that deopts on overflow, a zero divisor or a shift it cannot make "AddInt", "SubInt", "MulInt", "DivInt", "ModInt", "ShrInt", "AddLong", "SubLong", "MulLong", "DivLong", "ModLong", "ShlLong", "ShrLong", "AbsLong", "MathSqrt", diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index a825069ef..39e54b12b 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1631,6 +1631,15 @@ internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { Ast.Call(JitRuntime.M("SetIVarDouble"), Ast.Constant(_context), _self, raw, ivarSite), raw); } + if (RawInts && IsInteger(vt)) { + // an Integer stored raw, as a Float is; the value stays an int (a long) + var raw = Ast.Variable(ClrType(vt), "#value"); + type = vt; + return Ast.Block(ClrType(vt), new[] { raw }, + Ast.Assign(raw, v), + Ast.Call(JitRuntime.M("SetIVarLong"), Ast.Constant(_context), _self, Coerce(raw, vt, JT.Lng), ivarSite), + raw); + } type = JT.Obj; return Ast.Call(JitRuntime.M("SetIVar"), Ast.Constant(_context), _self, Coerce(v, vt, JT.Obj), ivarSite); } @@ -2694,8 +2703,8 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { } if (from == JT.Obj) { switch (to) { - case JT.Int: _canDeopt = true; return Ast.Call(JitRuntime.M("GuardInt"), e); - case JT.Lng: _canDeopt = true; return Ast.Call(JitRuntime.M("GuardLong"), e); + case JT.Int: _canDeopt = true; return GuardIVarRead("GuardInt", e); + case JT.Lng: _canDeopt = true; return GuardIVarRead("GuardLong", e); case JT.Dbl: _canDeopt = true; return GuardIVarRead("GuardDouble", e); } } @@ -2811,20 +2820,28 @@ private static bool IsNumeric(JT t) { } /// - /// The guarded unboxing of an instance variable read: GuardDouble (SpeculateDouble) of GetIVar or - /// ReadSelfAttr becomes their Double (SpeculateDouble) version, which reads a Float the typed code stored raw without boxing it - /// (RubyInstanceData, "Float locations"). Both deopt on the same values. + /// The guarded unboxing of an instance variable read: GuardDouble (SpeculateDouble, GuardInt, GuardLong) of GetIVar or + /// ReadSelfAttr becomes their Double (SpeculateDouble, Int, Long) version, which reads a Float (an Integer) the typed code + /// stored raw without boxing it (RubyInstanceData, "Float locations"). Both deopt on the same values. /// internal static MSA.Expression/*!*/ GuardIVarRead(string/*!*/ guard, MSA.Expression/*!*/ read) { var call = read as MSA.MethodCallExpression; - if ((guard == "GuardDouble" || guard == "SpeculateDouble") && call != null && call.Object == null) { - string suffix = (guard == "GuardDouble") ? "Double" : "SpeculateDouble"; + if ((guard == "GuardDouble" || guard == "SpeculateDouble" || (RawInts && (guard == "GuardInt" || guard == "GuardLong"))) + && call != null && call.Object == null) { + string suffix = (guard == "GuardDouble") ? "Double" : (guard == "GuardInt") ? "Int" : (guard == "GuardLong") ? "Long" : "SpeculateDouble"; if (call.Method == JitRuntime.M("GetIVar")) { return Ast.Call(JitRuntime.M("GetIVar" + suffix), call.Arguments); } if (call.Method == JitRuntime.M("ReadSelfAttr")) { return Ast.Call(JitRuntime.M("ReadSelfAttr" + suffix), call.Arguments); } } return Ast.Call(JitRuntime.M(guard), read); } + /// + /// An Integer the typed code holds as an int or a long is stored into an instance variable raw, and + /// read back without a box (RubyInstanceData, "Float locations"; JitRuntime.SetIVarLong). IR_RAW_INTS=0: + /// boxed, as before. + /// + internal static readonly bool RawInts = Environment.GetEnvironmentVariable("IR_RAW_INTS") != "0"; + /// The two representations of a Ruby Integer the specialized code carries. private static bool IsInteger(JT t) { return t == JT.Int || t == JT.Lng; diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 29e31fd20..dc4c54d6b 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -524,8 +524,15 @@ public static object SetGlobal(RubyContext/*!*/ context, GlobalVariableSite/*!*/ [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object GetIVar(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { object value; - if (self is RubyObject obj && RubyOps.TryReadCached(obj._instanceData, site, out value)) { - return value; + if (self is RubyObject obj) { + var data = obj._instanceData; + if (RubyOps.TryReadCached(data, site, out value)) { + return value; + } + // a raw object's read (RubyInstanceData, "Float locations"), as RubyOps.GetInstanceVariable's + if (RubyOps.TryReadCachedRaw(data, site, out value)) { + return value; + } } return GetIVarUncached(context, self, site); } @@ -953,7 +960,7 @@ public static object[] BeginInitialIVars(object self, InitialIVarsSite/*!*/ site int count = site.Shape.Count; var result = new object[Math.Max(count, obj.ImmediateClass.InstanceVariableCapacity) + 1]; // born raw if its class's instances get their Floats promoted (RubyInstanceData, "Float locations") - result[0] = obj.ImmediateClass.FloatsRaw ? (site.Shape.RawTwin ?? site.Shape) : site.Shape; + result[0] = obj.ImmediateClass.BornRaw ? (site.Shape.RawTwin ?? site.Shape) : site.Shape; return result; } @@ -1181,7 +1188,8 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* // a race the generic code has too (the rollback would then undo it) log.ReplacedFloat(data, variable.Name, location.Value); } else { - log.Replaced(data, variable.Name, old); + // a raw Integer is logged boxed, as WriteSelfAttr logs it + log.Replaced(data, variable.Name, RubyInstanceData.ValueOf(old)); } if (RubyInstanceData.TryWriteFloat(slots, shape, index, value)) { return; @@ -1201,6 +1209,159 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* data.SetInstanceVariable(variable.Name, value); } + // ---- Integer instance variables stored raw (RubyInstanceData, "Float locations") ----------- + // An Integer the typed code holds as an int or a long is stored raw in an IntLocation as a Float + // is in a FloatLocation: GuardInt / GuardLong of GetIVar / ReadSelfAttr become these, which read + // a raw Integer without boxing it and deopt on the values the guards deopt on, and a store of an + // int or a long is SetIVarLong / WriteAttrLong. IR_RAW_INTS=0: the compiler emits neither. + + /// GuardLong(GetIVar(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long GetIVarLong(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { + if (self is RubyObject obj) { + var data = obj._instanceData; + if (data != null) { + object[] slots = data._ivars; + var entry = site.Cache; + if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { + // a box first: a plain object's read is the shape compare and GuardLong's test, + // as before. A location is only ever in a raw array, so its type says it all. + object slot = RubyInstanceData.GetSlot(slots, entry.Index); + if (slot is int) { + return (int)slot; + } + if (slot is IntLocation location) { + return location.Value; + } + } + } + } + return GetIVarLongSlow(context, self, site); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static long GetIVarLongSlow(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { + // the site's second shape (RubyOps.TryReadCachedLong), then the object read + long value; + if (self is RubyObject obj && RubyOps.TryReadCachedLong(obj._instanceData, site, out value)) { + return value; + } + return GuardLong(GetIVar(context, self, site)); + } + + /// GuardInt(GetIVar(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetIVarInt(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { + if (self is RubyObject obj) { + var data = obj._instanceData; + if (data != null) { + object[] slots = data._ivars; + var entry = site.Cache; + if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { + object slot = RubyInstanceData.GetSlot(slots, entry.Index); + if (slot is int) { + return (int)slot; + } + // a raw Integer past an Int32 is one the generic code holds as an Int64: GuardInt's deopt + if (slot is IntLocation location && location.Value == (int)location.Value) { + return (int)location.Value; + } + } + } + } + return GetIVarIntSlow(context, self, site); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int GetIVarIntSlow(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { + long value; + if (self is RubyObject obj && RubyOps.TryReadCachedLong(obj._instanceData, site, out value) && value == (int)value) { + return (int)value; + } + return GuardInt(GetIVar(context, self, site)); + } + + /// GuardLong(ReadSelfAttr(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long ReadSelfAttrLong(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { + if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass)) { + var data = obj._instanceData; + if (data != null) { + object[] slots = data._ivars; + var entry = site.Variable.Cache; + if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { + object slot = RubyInstanceData.GetSlot(slots, entry.Index); + if (slot is int) { + return (int)slot; + } + if (slot is IntLocation location) { + return location.Value; + } + } + } + } + return ReadSelfAttrLongSlow(context, self, site); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static long ReadSelfAttrLongSlow(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { + long value; + if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass) && RubyOps.TryReadCachedLong(obj._instanceData, site.Variable, out value)) { + return value; + } + return GuardLong(ReadSelfAttr(context, self, site)); + } + + /// GuardInt(ReadSelfAttr(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadSelfAttrInt(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { + if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass)) { + var data = obj._instanceData; + if (data != null) { + object[] slots = data._ivars; + var entry = site.Variable.Cache; + if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { + object slot = RubyInstanceData.GetSlot(slots, entry.Index); + if (slot is int) { + return (int)slot; + } + if (slot is IntLocation location && location.Value == (int)location.Value) { + return (int)location.Value; + } + } + } + } + return ReadSelfAttrIntSlow(context, self, site); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int ReadSelfAttrIntSlow(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { + long value; + if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass) && RubyOps.TryReadCachedLong(obj._instanceData, site.Variable, out value) + && value == (int)value) { + return (int)value; + } + return GuardInt(ReadSelfAttr(context, self, site)); + } + + /// SetIVar of an Integer the body holds as an int or a long. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void SetIVarLong(RubyContext/*!*/ context, object self, long value, InstanceVariableSite/*!*/ site) { + if (self is RubyObject obj && RubyOps.TryWriteCachedLong(obj._instanceData, value, site, obj.ImmediateClass)) { + return; + } + SetIVarUncached(context, self, IntLocation.Box(value), site); + } + + /// WriteAttr of an Integer the body holds as an int or a long. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteAttrLong(RubyContext/*!*/ context, object self, long value, SelfAttrSite/*!*/ site) { + if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass) && RubyOps.TryWriteCachedLong(obj._instanceData, value, site.Variable, obj.ImmediateClass)) { + return; + } + WriteAttrUncached(context, self, IntLocation.Box(value), site); + } + // An instance variable used as a numeric operand of an outlined loop (JitCompiler.NumericIVar): // unboxed while it holds the type it held when the loop was compiled, a deopt once it does not. diff --git a/Src/Ruby/Runtime/RubyInstanceData.cs b/Src/Ruby/Runtime/RubyInstanceData.cs index 262984117..9fa4dc68e 100644 --- a/Src/Ruby/Runtime/RubyInstanceData.cs +++ b/Src/Ruby/Runtime/RubyInstanceData.cs @@ -52,6 +52,57 @@ internal object/*!*/ Boxed { } } + /// + /// An Integer instance variable stored raw, as a Float: see + /// RubyInstanceData, "Float locations". It holds an Integer the typed code carries as an int or a + /// long; a Bignum is never in one. Only ever in a slot array, never handed out as a value. + /// + internal sealed class IntLocation { + internal long Value; + + // The box the generic reads last handed out, as FloatLocation's: so that a value read many + // times between two raw writes is boxed once. The raw writes never touch it. + private object _box; + + internal IntLocation(long value) { + Value = value; + } + + internal object/*!*/ Boxed { + get { + long value = Value; + if (IsCached(value)) { + // the small-integer cache: what the generic body would have stored + return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject((int)value); + } + object box = Volatile.Read(ref _box); + if (box != null && (box is int ? (int)box : (long)box) == value) { + return box; + } + box = Box(value); + Volatile.Write(ref _box, box); + return box; + } + } + + /// + /// A value the small-integer cache has a box for: storing it boxed costs nothing, so it is + /// never what makes a location (RubyInstanceData.TryWriteLong). + /// + internal static bool IsCached(long value) { + return value >= -100 && value < 1000; + } + + /// + /// An Integer the typed code holds as a long, as the generic code holds it: an Int32 if it + /// fits (JitRuntime.NarrowLong's representation rule), else an Int64. + /// + internal static object/*!*/ Box(long value) { + return (value >= Int32.MinValue && value <= Int32.MaxValue) + ? Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject((int)value) : (object)value; + } + } + /// /// Stores the per-instance data that all Ruby objects need (frozen?, instance_variables, etc) /// Stored in a lookaside weak hashtable for types that don't implement IRubyObject (i.e. .NET types). @@ -113,7 +164,11 @@ internal object/*!*/ Boxed { /// /// A slot may hold a instead of a value: a Float stored raw, so that /// the typed code of the method JIT and the loop tiers, which carries Floats as doubles, updates - /// one without boxing it (JitRuntime.SetIVarDouble and the other *Double helpers). + /// one without boxing it (JitRuntime.SetIVarDouble and the other *Double helpers). An Integer the + /// typed code carries as an int or a long is stored raw the same way, in an + /// (JitRuntime.SetIVarLong and the *Int and *Long reads; IR_RAW_INTS=0 leaves Integers boxed): + /// what is said here of a FloatLocation and a Float holds of an IntLocation and an Integer that + /// fits a long, and a long field is as atomic as a double one on the platforms named below. /// /// Rawness belongs to the shape. Every shape has a raw twin (: /// same names, same slots, IsRaw), every transition from a raw shape leads to a raw shape, and a @@ -128,8 +183,9 @@ internal object/*!*/ Boxed { /// boxing a location's Float - the same box again while the value has not changed. /// /// Policy: a typed store promotes the object when it overwrites a slot that already holds a Float - /// (the variable is being updated); a store that adds the variable or replaces anything else - /// stores a box, so Floats set once (constructors) never cost a Move and a location. + /// (an Integer, for an Integer store: the variable is being updated); a store that adds the + /// variable or replaces anything else stores a box, so values set once (constructors) never + /// cost a Move and a location. /// /// In a raw array the first raw store into a slot allocates its location and later ones write its /// field; every other write stores the value itself, which replaces the location (a type change @@ -231,12 +287,13 @@ public void Freeze() { #region Instance Variables: layout /// - /// The value a slot holds: the slot itself, or the Float of a , boxed. + /// The value a slot holds: the slot itself, or the Float of a or the + /// Integer of an , boxed. /// [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] internal static object ValueOf(object slot) { - // inlined into every cached read: a type check, and the boxing out of line - return (slot is FloatLocation) ? BoxedValueOf(slot) : slot; + // inlined into every cached read: two exact type checks, and the boxing out of line + return (slot is FloatLocation || slot is IntLocation) ? BoxedValueOf(slot) : slot; } /// @@ -250,7 +307,8 @@ internal static object ValueOf(InstanceVariableShape/*!*/ shape, object slot) { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static object BoxedValueOf(object slot) { - return ((FloatLocation)slot).Boxed; + var location = slot as FloatLocation; + return (location != null) ? location.Boxed : ((IntLocation)slot).Boxed; } /// @@ -405,7 +463,7 @@ internal void CopyInstanceVariablesTo(RubyInstanceData/*!*/ dup, object copy) { var slots = new object[s.Length]; for (int i = 1; i <= shape.Count; i++) { - // a FloatLocation is the original's: the copy gets the Float boxed + // a FloatLocation (IntLocation) is the original's: the copy gets the value boxed var value = ValueOf(shape, s[i]); var state = value as IPerObjectState; slots[i] = state != null ? state.CopyFor(copy) : value; @@ -644,7 +702,7 @@ internal void SetInstanceVariable(string/*!*/ name, object value, RubyClass hint if (s.Length == 1) { // the first variable: nothing to copy, nobody writing Debug.Assert(index == 1); - if (hintClass != null && hintClass.FloatsRaw) { + if (hintClass != null && hintClass.BornRaw) { // born raw: its class's instances get their Floats promoted next = next.RawTwin ?? next; } @@ -724,8 +782,8 @@ internal bool TrySetCached(InstanceVariableSite.Entry/*!*/ entry, object value, // born raw if and only if its class's instances get their Floats promoted: the site's // Next may be of either tree, since a site sees the instances of several classes var next = entry.Next; - if (ownerClass != null && ownerClass.FloatsRaw != next.IsRaw) { - next = (ownerClass.FloatsRaw ? next.RawTwin : next.PlainTwin) ?? next; + if (ownerClass != null && ownerClass.BornRaw != next.IsRaw) { + next = (ownerClass.BornRaw ? next.RawTwin : next.PlainTwin) ?? next; } first[0] = next; first[1] = value; @@ -768,12 +826,12 @@ internal InstanceVariableShape TryWriteFloatPlain(object[]/*!*/ s, InstanceVaria RubyClass ownerClass) { Debug.Assert(!shape.IsRaw); if (GetSlot(s, index) is double) { - var raw = TryPromote(s, shape, index, value); + var raw = TryPromote(s, shape, index, new FloatLocation(value)); if (raw != null) { - if (ownerClass != null && !ownerClass.FloatsRaw) { + if (ownerClass != null && !ownerClass.BornRaw) { // its later instances are born raw and need no Move (a Move's process-wide // barrier costs a few hundred ns) - ownerClass.FloatsRaw = true; + ownerClass.BornRaw = true; } return raw; } @@ -784,6 +842,73 @@ internal InstanceVariableShape TryWriteFloatPlain(object[]/*!*/ s, InstanceVaria return (ShapeOf(s) == shape) ? shape : null; } + /// + /// of an Integer the typed code holds as a long (an int widened): + /// into the variable's , or a new one - unless the slot has none and the + /// value is one the small-integer cache boxes, which is stored boxed: a short-lived object whose + /// variables stay small (AWFY's Bounce makes thousands) would pay a location for nothing. + /// + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal static bool TryWriteLong(object[]/*!*/ slots, object shape, int index, long value) { + Debug.Assert(((InstanceVariableShape)shape).IsRaw); + var location = GetSlot(slots, index) as IntLocation; + if (location != null) { + location.Value = value; + } else { + SetSlot(slots, index, IntLocation.IsCached(value) + ? Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject((int)value) : new IntLocation(value)); + } + return ShapeOf(slots) == shape; + } + + /// + /// of an Integer the typed code holds as a long: a slot that + /// holds an Integer already (an Int32 or an Int64, not a Bignum) gets its object promoted when the + /// value would need a box of its own (see ), every other one gets the + /// Integer boxed as the generic code boxes it. + /// + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + internal InstanceVariableShape TryWriteLongPlain(object[]/*!*/ s, InstanceVariableShape/*!*/ shape, int index, long value, + RubyClass ownerClass) { + Debug.Assert(!shape.IsRaw); + object old = GetSlot(s, index); + if ((old is int || old is long) && !IntLocation.IsCached(value)) { + var raw = TryPromote(s, shape, index, new IntLocation(value)); + if (raw != null) { + if (ownerClass != null && !ownerClass.BornRaw) { + ownerClass.BornRaw = true; + } + return raw; + } + return null; + } + SetSlot(s, index, IntLocation.Box(value)); + return (ShapeOf(s) == shape) ? shape : null; + } + + /// + /// The Integer a slot holds - raw in an or boxed as an Int32 or an + /// Int64 - for the typed code's reads; false if it holds anything else (a Bignum included). + /// + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal static bool TryReadLong(object slot, out long value) { + var location = slot as IntLocation; + if (location != null) { + value = location.Value; + return true; + } + if (slot is int) { + value = (int)slot; + return true; + } + if (slot is long) { + value = (long)slot; + return true; + } + value = 0; + return false; + } + private static int _Promotions; /// @@ -797,14 +922,14 @@ public static int Promotions { /// /// Makes the object raw: a Move (under lock(this), the old array retired as for any Move) to a /// new array whose element 0 is the raw twin of , the slots copied after - /// the barrier and stored at in a new - /// FloatLocation before the array is published. A FloatLocation is therefore never in an array + /// the barrier and (a new FloatLocation or IntLocation) stored at + /// before the array is published. A FloatLocation is therefore never in an array /// whose element 0 is not raw: a reader of the old array sees the old shape and the old values, /// and a writer that stored into the old array is copied or meets Moved and redoes its write. /// Null if it did not happen: no raw twin, or is not the current array of /// that shape any more. /// - private InstanceVariableShape TryPromote(object[]/*!*/ s, InstanceVariableShape/*!*/ shape, int index, double value) { + private InstanceVariableShape TryPromote(object[]/*!*/ s, InstanceVariableShape/*!*/ shape, int index, object/*!*/ location) { var raw = shape.RawTwin; if (raw == null) { return null; @@ -815,7 +940,7 @@ private InstanceVariableShape TryPromote(object[]/*!*/ s, InstanceVariableShape/ } var slots = new object[s.Length]; Array.Copy(s, 1, slots, 1, shape.Count); - slots[index] = new FloatLocation(value); + slots[index] = location; slots[0] = raw; if (!Publish(s, slots)) { throw Assert.Unreachable; diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 28138d4b1..e72eaf21f 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -5843,8 +5843,16 @@ public static int ConvertDoubleToFixnum(double value) { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object GetInstanceVariable(RubyScope/*!*/ scope, object self, InstanceVariableSite/*!*/ site) { object value; - if (self is RubyObject obj && TryReadCached(obj._instanceData, site, out value)) { - return value; + if (self is RubyObject obj) { + var data = obj._instanceData; + if (TryReadCached(data, site, out value)) { + return value; + } + // an object with raw Floats or Integers (RubyInstanceData, "Float locations"), which the read + // above leaves out: here and not a call away (an Integer counter makes its class's objects raw) + if (TryReadCachedRaw(data, site, out value)) { + return value; + } } return GetInstanceVariableUncached(scope, self, site); } @@ -5991,6 +5999,97 @@ private static bool TryWriteCachedFloatPlain(RubyInstanceData/*!*/ data, object[ return now != null; } + // ---- the same for an Integer the typed code holds as an int or a long (RubyInstanceData, + // "Float locations": an IntLocation is to an Integer what a FloatLocation is to a Float) + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TryReadCachedLongSlow(object[]/*!*/ slots, InstanceVariableSite/*!*/ site, InstanceVariableSite.Entry/*!*/ entry, out long value) { + object shape = RubyInstanceData.ShapeOf(slots); + if (shape == entry.Shape) { + // a plain object: a boxed Integer or nothing for us + return RubyInstanceData.TryReadLong(RubyInstanceData.GetSlot(slots, entry.Index), out value); + } else if (shape == entry.OtherShape) { + object slot = RubyInstanceData.GetSlot(slots, entry.OtherIndex); + if (entry.OtherRaw) { + site.Update(entry.Remember(entry.OtherShape, entry.OtherIndex)); + } + return RubyInstanceData.TryReadLong(slot, out value); + } + value = 0; + return false; + } + + // TryReadCached of a variable that holds an Integer that fits a long, for the typed code: the + // long, without boxing a raw one. False for a miss or a variable that holds anything else. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryReadCachedLong(RubyInstanceData data, InstanceVariableSite/*!*/ site, out long value) { + if (data != null) { + object[] slots = data._ivars; + var entry = site.Cache; + if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { + return RubyInstanceData.TryReadLong(RubyInstanceData.GetSlot(slots, entry.Index), out value); + } + return TryReadCachedLongSlow(slots, site, entry, out value); + } + value = 0; + return false; + } + + // TryWriteCached of an Integer the typed code holds raw: into the variable's IntLocation + // (RubyInstanceData.TryWriteLong). False for a miss, an add, a frozen object or a shape + // changed under it: the caller boxes the Integer and takes the ordinary path. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryWriteCachedLong(RubyInstanceData data, long value, InstanceVariableSite/*!*/ site, RubyClass ownerClass) { + if (data != null && !data._frozen) { + object[] slots = data._ivars; + var entry = site.Cache; + object shape = RubyInstanceData.ShapeOf(slots); + if (shape == entry.Shape && entry.Next == null) { + if (entry.Raw) { + return RubyInstanceData.TryWriteLong(slots, shape, entry.Index, value); + } + if (IntLocation.IsCached(value)) { + // a plain object and a value the cache boxes: TryWriteCached's store (no promotion for it) + RubyInstanceData.SetSlot(slots, entry.Index, ScriptingRuntimeHelpers.Int32ToObject((int)value)); + return RubyInstanceData.ShapeOf(slots) == shape; + } + } + return TryWriteCachedLongSlow(data, slots, shape, value, site, ownerClass); + } + return false; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TryWriteCachedLongSlow(RubyInstanceData/*!*/ data, object[]/*!*/ slots, object shape, long value, + InstanceVariableSite/*!*/ site, RubyClass ownerClass) { + var entry = site.Cache; + if (shape == entry.Shape && entry.Next == null) { + return TryWriteCachedLongPlain(data, slots, entry.Shape, entry.Index, value, site, ownerClass); + } + if (shape == entry.Shape) { + // adding the variable (a constructor's `@n = 0'): boxed, by the cached add + return data.TrySetCached(entry, IntLocation.Box(value), ownerClass); + } + if (shape == entry.OtherShape) { + if (entry.OtherRaw) { + site.Update(entry.Remember(entry.OtherShape, entry.OtherIndex)); + return RubyInstanceData.TryWriteLong(slots, shape, entry.OtherIndex, value); + } + return TryWriteCachedLongPlain(data, slots, entry.OtherShape, entry.OtherIndex, value, site, ownerClass); + } + return false; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TryWriteCachedLongPlain(RubyInstanceData/*!*/ data, object[]/*!*/ slots, InstanceVariableShape/*!*/ shape, + int index, long value, InstanceVariableSite/*!*/ site, RubyClass ownerClass) { + var now = data.TryWriteLongPlain(slots, shape, index, value, ownerClass); + if (now != null && now != shape) { + site.Update(site.Cache.Remember(now, index)); + } + return now != null; + } + [MethodImpl(MethodImplOptions.NoInlining)] private static object GetInstanceVariableUncached(RubyScope/*!*/ scope, object self, InstanceVariableSite/*!*/ site) { RubyInstanceData data; diff --git a/Util/bench/intivar-shapes.rb b/Util/bench/intivar-shapes.rb new file mode 100644 index 000000000..3c87f08e3 --- /dev/null +++ b/Util/bench/intivar-shapes.rb @@ -0,0 +1,112 @@ +# Integer instance variables stored raw (perf/intivar; RubyInstanceData, "Float locations"): what the +# typed code's writes and reads of an Integer variable cost, and what raw storage costs the generic +# code that reads the same objects. Format of Util/perf/ab.rb: ` ns ` per shape; +# shape names as arguments, N from the environment. BYTES=1 (IronRuby only): bytes allocated per +# operation instead of ns. INSTR=1 (ab.rb -i): instructions per operation as well. +# +# ruby Util/perf/ab.rb -r 5 Util/bench/intivar-shapes.rb cruby=ruby \ +# "base=env IR_CONFIG=Release ../base/ir.sh" "off=env IR_RAW_INTS=0 IR_CONFIG=Release ./ir.sh" \ +# "new=env IR_CONFIG=Release ./ir.sh" +# +# counter `@n += 1' in a method the JIT types, above the small-integer cache (a write each call) +# counter_s the same, the value staying in the cache (0..511) +# seed AWFY's Random#next (som.rb): `@seed = ((@seed * 1309) + 13849) & 65535' +# bounce AWFY's Ball#bounce: four Integer variables read and written +# bounce_new AWFY's Bounce as it is: 100 new Balls, each bounced 50 times (ns per bounce) +# attr `o.w = o.w + 1' in a typed method (WriteAttr) +# read_typed `@n * 2' of a raw variable in a typed method +# read_raw a generic read (a method the JIT refuses) of an object whose class is born raw +# read_plain the same of an object of a class never promoted: the control for read_raw +# read_chg a generic read after every typed write: the box a raw value costs its generic reader +$stdout.sync = true +N = (ENV['N'] || 2_000_000).to_i +BYTES = ENV['BYTES'] == '1' +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) + +class Cnt + attr_accessor :w + def initialize(n) = (@n = n; @w = n; @k = 0) + def inc = (@n += 1; nil) + def inc_s = (@n = (@n + 1) & 511; nil) + def twice = (@n * 2) + def n = @n + def gread = (begin; @n; rescue; nil; end) # refused by the JIT (rescue): the generic read +end +class Plain + def initialize(n) = (@n = n; @w = n; @k = 0) + def gread = (begin; @n; rescue; nil; end) +end +def bump(o) = (o.w = o.w + 1; nil) + +class Rnd + def initialize = (@seed = 74755) + def next = (@seed = ((@seed * 1309) + 13849) & 65535; @seed) +end +class Ball + def initialize(r) + @x = r.next % 500; @y = r.next % 500 + @x_vel = (r.next % 300) - 150; @y_vel = (r.next % 300) - 150 + end + def bounce + x_limit = 500; y_limit = 500; bounced = false + @x += @x_vel; @y += @y_vel + if @x > x_limit then @x = x_limit; @x_vel = 0 - @x_vel.abs; bounced = true end + if @x < 0 then @x = 0; @x_vel = @x_vel.abs; bounced = true end + if @y > y_limit then @y = y_limit; @y_vel = 0 - @y_vel.abs; bounced = true end + if @y < 0 then @y = 0; @y_vel = @y_vel.abs; bounced = true end + bounced + end + def pos = @x * 1000 + @y +end + +# the typed methods hot, and Cnt born raw (on a build that stores Integers raw), before anything is timed +warm = Cnt.new(5000) +3000.times { warm.inc; warm.inc_s; warm.twice; bump(warm) } + +SHAPES = %w[counter counter_s seed bounce bounce_new attr read_typed read_raw read_plain read_chg] + +def run_once(name) + i = 0 + case name + when 'counter' then o = Cnt.new(5000); while i < N; o.inc; i += 1; end; o.n + when 'counter_s' then o = Cnt.new(0); while i < N; o.inc_s; i += 1; end; o.n + when 'seed' then r = Rnd.new; s = 0; while i < N; s += r.next; i += 1; end; s + when 'bounce' then r = Rnd.new; b = Ball.new(r); c = 0; while i < N; c += 1 if b.bounce; i += 1; end; c * 1_000_000 + b.pos + when 'bounce_new' + r = Rnd.new; c = 0 + while i < N + balls = Array.new(100) { Ball.new(r) } + k = 0 + while k < 50; j = 0; while j < 100; c += 1 if balls[j].bounce; j += 1; end; k += 1; end + i += 5000 + end + c + when 'attr' then o = Cnt.new(5000); while i < N; bump(o); i += 1; end; o.w + when 'read_typed' then o = Cnt.new(5000); o.inc; o.inc; s = 0; while i < N; s += o.twice; i += 1; end; s + when 'read_raw' then o = Cnt.new(5000); o.inc; o.inc; s = 0; while i < N; s += o.gread; i += 1; end; s + when 'read_plain' then o = Plain.new(5002); s = 0; while i < N; s += o.gread; i += 1; end; s + when 'read_chg' then o = Cnt.new(5000); s = 0; while i < N; o.inc; s += o.gread; i += 1; end; s + end +end + +def run_shape(name) + best = nil + fewest = nil + r = nil + 6.times do + c0 = INSTR && INSTR.read + t = BYTES ? System::GC.get_total_allocated_bytes(true) : Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) + r = run_once(name) + d = BYTES ? System::GC.get_total_allocated_bytes(true) - t : Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) - t + c1 = INSTR && INSTR.read + fewest = c1 - c0 if c0 && c1 && (fewest.nil? || c1 - c0 < fewest) + best = d if best.nil? || d < best + end + if BYTES + puts format('%s %.1f B %s', name, best.to_f / N, r) + else + puts format('%s %.1f ns %s%s', name, best * 1e9 / N, r, fewest ? format(' %.1f instr', fewest.to_f / N) : '') + end +end + +(ARGV.empty? ? SHAPES : ARGV).each { |s| run_shape(s) } diff --git a/Util/ivar-matrix.rb b/Util/ivar-matrix.rb index f6e6303ec..b53866c24 100644 --- a/Util/ivar-matrix.rb +++ b/Util/ivar-matrix.rb @@ -169,6 +169,113 @@ def fl_pro_read(o) = o.a * 1.0 [o.a, d.a, c.a, m.a, d.b, Marshal.dump(o) == Marshal.dump(FlPro.new(3.0, 2))] end +# ---------------------------------------------------------------- Integer variables stored raw +# The method JIT stores an Integer it holds as an int or a long raw (RubyInstanceData, "Raw +# locations"), as it does a Float: a counter's `@n += 1' then updates the variable in place. An +# Integer past a long, or anything else, is stored boxed, and nothing below may tell the two apart. +# (The writers end with a read: a write that is a method's value is stored boxed, its box returned.) + +class InRaw + attr_accessor :v + def initialize; @n = 0; @v = 0; end + def put(i) = (@n = i + 0; @n) + def inc(i) = (@n += i; @n) + def big = (@n = @n * 4_000_000_000; @n) + def n = @n +end +def in_raw_attr(o, i) = (o.v = o.v + i; o.v) +inr = InRaw.new +300.times { |i| inr.put(i * 1000); inr.inc(1); in_raw_attr(inr, 1) } +def in_raw(i) + o = InRaw.new; o.put(i); o.inc(0); in_raw_attr(o, 1); o +end +t("int: read back, small, cached, int, long") { [0, 5, 1023, 1024, 70_000, 2**31 - 1, -2**31, -129].map { |i| o = in_raw(i); [o.n, o.inc(1), o.n.class] } } +t("int: past an int") { o = in_raw(2**31 - 2); [o.inc(1), o.inc(1), o.inc(1), o.n.class, o.inc(-3), o.inc(2**40), o.n] } +t("int: past a long, to Bignum and back") { o = in_raw(2**62); r = [o.inc(2**62), o.inc(2**62), o.n.class]; r << o.inc(-(2**64)) << o.inc(1) << o.n.class } +t("int: overflow by *") { o = in_raw(3); [o.big, o.big, o.big, o.n.class, o.put(7), o.inc(1)] } +t("int: type changes") { o = in_raw(5000); r = [o.inc(1)]; o.instance_variable_set(:@n, 'str'); r << o.n << (o.inc(1) rescue $!.class); o.put(nil.to_i); r << o.inc(9) << o.n; o.instance_variable_set(:@n, nil); r << o.n << (o.inc(1) rescue $!.class); o.instance_variable_set(:@n, 2.5); r << o.inc(1) << o.put(8) << o.inc(1) } +t("int: identity, hash, eql?, object_id") { o = in_raw(5000); a = o.n; b = o.n; [a.equal?(b), a.eql?(5000), a.hash == 5000.hash, {5000 => :k}[a], a.object_id == 5000.object_id, o.inc(1).equal?(o.n)] } +t("int: YAML round trip") { require 'yaml'; o = in_raw(123_456); y = YAML.dump(o); [y.lines.grep(/n:|v:/), YAML.unsafe_load(y).n] } +t("int: Marshal round trip") { m = Marshal.load(Marshal.dump(in_raw(2**30 + 5))); [m.n, m.v, m.inc(1), m.n.class] } +t("int: Marshal of a long and a Bignum") { o = in_raw(2**40); m = Marshal.load(Marshal.dump(o)); o.inc(2**70); [m.n, Marshal.load(Marshal.dump(o)).n] } +t("int: inspect, instance_variables") { o = in_raw(77_777); [o.inspect.sub(/0x\h+/, ''), o.instance_variables] } +t("int: instance_variable_get/set") { o = in_raw(2500); r = [o.instance_variable_get(:@n)]; o.instance_variable_set(:@n, 'str'); r << o.n << (o.inc(1) rescue $!.class); o.instance_variable_set(:@n, 10**20); r << o.inc(1) << o.instance_variable_get(:@n) } +t("int: remove") { o = in_raw(2500); [o.remove_instance_variable(:@n), o.instance_variables, o.put(1500), o.inc(1), o.instance_variables, o.remove_instance_variable(:@n), (o.n rescue $!.class)] } +t("int: defined?, instance_variable_defined?") { o = in_raw(9000); [o.instance_variable_defined?(:@n), o.instance_eval { defined?(@n) }] } +t("int: dup/clone/initialize_copy") { o = in_raw(2500); d = o.dup; c = o.clone; d.inc(1); c.inc(2); o.inc(3); [o.n, d.n, c.n] } +t("int: freeze") { o = in_raw(2500); o.freeze; [(o.put(1) rescue $!.class), (o.inc(1) rescue $!.class), (in_raw_attr(o, 2) rescue $!.class), o.n, o.v] } +t("int: Ractor.make_shareable") { o = in_raw(3500); Ractor.make_shareable(o); [Ractor.shareable?(o), o.frozen?, o.n] } +t("int: binding sees the value") { o = in_raw(4500); o.instance_eval { binding }.eval('@n') } +t("int: Comparable, Range, Array index") { o = in_raw(2000); a = (0..2010).to_a; [o.n > 1999, (1990..2005).include?(o.n), a[o.n], 'x' * (o.n - 1995)] } +t("int: Float mixed in") { o = in_raw(2000); r = [o.inc(0.5), o.n.class, o.inc(1), o.put(4), o.inc(1), o.n.class]; r } + +class InSub < InRaw + def initialize; super; @s1 = 1; @s2 = 2; @s3 = 3; end + def bump = (@s3 += 1000; @n += 1; @s1 += @s3; nil) + def all = [@n, @v, @s1, @s2, @s3] +end +t("int: subclass with more variables") { o = InSub.new; 50.times { o.bump; o.inc(1) }; [o.all, o.instance_variables, Marshal.load(Marshal.dump(o)).all] } + +# Promotion: a typed store over an Integer moves the object to the raw twin of its shape, and +# its class's later instances are born raw. Plain and raw objects at one site, the raw tree's +# removal and growth, a raw object made too complex, and copies. +class InPro + attr_accessor :a, :b + def initialize(a, b) = (@a = a; @b = b) + def step(d) = (@a += d; @a) + def get = @a +end +def in_pro_read(o) = o.get * 2 +iplain = InPro.new(1500, :p) +300.times { |i| o = InPro.new(i * 100, i); o.step(1); o.step(2); in_pro_read(o) } +t("int promote: plain and born-raw objects at one site") do + born = InPro.new(2500, :b) + r = [] + 4.times { iplain.step(1000); born.step(1000); r << in_pro_read(iplain) << in_pro_read(born) } + r + [iplain.a, born.a, iplain.instance_variables, born.instance_variables] +end +t("int promote: generic reads and writes of born-raw objects") do + o = InPro.new(1000, 2); o.step(1) + o.b = 3; o.a = :sym + r = [o.a, o.b, (o.step(1) rescue $!.class)] + o.a = 4000; o.step(1); r << o.a << o.instance_variable_get(:@a) << o.inspect.sub(/0x\h+/, '') +end +t("int promote: remove and grow in the raw tree") do + o = InPro.new(1000, 2); o.step(1) + o.remove_instance_variable(:@b); o.step(1) + 10.times { |i| o.instance_variable_set(:"@g#{i}", i * 5000) } + o.step(1) + [o.a, o.instance_variables.size, o.instance_variable_get(:@g9), o.remove_instance_variable(:@a), o.instance_variables.first(2)] +end +t("int promote: raw object made too complex") do + o = InPro.new(1000, 2); o.step(1) + 300.times { |i| o.instance_variable_set(:"@z#{rand(1 << 30)}_#{i}", i) } + o.step(1) + [o.a, in_pro_read(o), o.instance_variables.size] +end +t("int promote: dup, clone, Marshal of raw objects") do + o = InPro.new(1000, 2); o.step(1); o.step(1) + d = o.dup; c = o.clone; m = Marshal.load(Marshal.dump(o)) + d.step(10); c.step(20); m.step(30) + [o.a, d.a, c.a, m.a, d.b, Marshal.dump(o) == Marshal.dump(InPro.new(1002, 2))] +end +t("int promote: Integer and Float in one variable, by object") do + f = InPro.new(1.5, 0); f.step(1.0); f.step(1.0) + i = InPro.new(1500, 0); i.step(1); i.step(1) + [f.a, i.a, f.step(1), i.step(0.5), f.a.class, i.a.class] +end +t("int promote: two threads write one object") do + o = InPro.new(0, 0) + t1 = Thread.new { 20_000.times { o.step(1) } } + t2 = Thread.new { 20_000.times { |k| o.b = (k.even? ? 'str' : k * 3) } } + t1.join; t2.join + r = [o.a.class, o.a.between?(1, 20_000), o.b] + t3 = Thread.new { 5_000.times { o.a = 'x'; o.a = 7 } } + 5_000.times { o.step(1) rescue nil } + t3.join + r << [Integer, String].include?(o.a.class) +end + # ---------------------------------------------------------------- basic operations targets.each do |name, obj| diff --git a/Util/ivar-stress.rb b/Util/ivar-stress.rb index 85f7b16af..19658d145 100644 --- a/Util/ivar-stress.rb +++ b/Util/ivar-stress.rb @@ -67,11 +67,14 @@ def initialize = (@a = 0.5; @b = 1.5) def ga = @a def gb = @b def setb(d) = (@b = d * 1.0) + def setbi(i) = (@b = i + 1; nil) # an Integer stored raw (perf/intivar) end def p_upd(o) = (o.a = o.a + 1.0) +def i_upd(o) = (o.a = o.a + 1; nil) PKINDS = [Float, Integer, NilClass] pwarm = Class.new(PBase) 300.times { o = pwarm.new; p_upd(o); p_upd(o); o.setb(2.5); o.setb(3.5); o.ga; o.gb } +300.times { |k| o = pwarm.new; o.a = k; i_upd(o); i_upd(o); o.setbi(k); o.setbi(k + 5000); o.ga; o.gb } # IronRuby's count of promotions (0 elsewhere, and on a build without it) def promotions return 0 unless defined?(System::Type) @@ -96,8 +99,9 @@ def promotions when 2 then o.a = 0.25 when 3 then o.setb(0.5) else - p_upd(o) if o.a.is_a?(Float) - o.setb(i * 0.5) + a = o.a + if a.is_a?(Float) then p_upd(o) elsif a.is_a?(Integer) then i_upd(o) end + i.even? ? o.setb(i * 0.5) : o.setbi(i * 1000) end if i % 11 == 0 name = :"@w#{t}_#{i % 3}" diff --git a/Util/jit-matrix.rb b/Util/jit-matrix.rb index 9af86ef3f..cb0f11079 100644 --- a/Util/jit-matrix.rb +++ b/Util/jit-matrix.rb @@ -4774,3 +4774,73 @@ def get_x = @x # In Util/jit-scan-matrix.rb, run the same way: its rows need String#length, #[] and #== to be the # library methods, and the sections above leave them aliased (13, and the redefinitions of section 3), # which keeps the method JIT from compiling `read' here at all. + +# ---------------------------------------------------------------- 21. Integer instance variables stored raw +# As section 19, for an Integer the typed code holds as an int or a long: `@n = i', `@n op= i', +# `o.n = i' store it into an IntLocation (JitRuntime.SetIVarLong, WriteAttrLong), and its guarded +# Integer reads (GuardInt, GuardLong) read the location raw. A value past a long is a Bignum, boxed. +# The writers end with a read: a write that is a method's value is stored boxed, its box returned. +class InObj + attr_accessor :w + def initialize; @n = 0; @y = 1; @w = 0; end + def sp_in_add(d) = (@n += d; @n) + def sp_in_put(i) = (@n = i + 0; @n) + def sp_in_get = @n + 0 + def sp_in_mul(k) = (@n = @n * k; @n) + def sp_in_idx(a) = a[@n] + def get_n = @n +end +def sp_in_attr(o, d) = (o.w = o.w + d; o.w) +inobj = InObj.new +warm { |i| inobj.sp_in_add(1); inobj.sp_in_put(i * 1000); inobj.sp_in_get; inobj.sp_in_mul(1); inobj.sp_in_idx([1, 2]); sp_in_attr(inobj, 1) } +t('int: raw state seen by everything') do + o = InObj.new; o.sp_in_put(5000); 5.times { o.sp_in_add(1); sp_in_attr(o, 2000) } + [o.get_n, o.sp_in_get, o.instance_variable_get(:@n), o.w, o.instance_variables, o.instance_variable_defined?(:@n), + o.inspect.sub(/0x\h+/, ''), o.instance_variables.map { |v| o.instance_variable_get(v) }] +end +t('int: dup and clone get copies') do + o = InObj.new; o.sp_in_put(1500); o.sp_in_add(1); d = o.dup; c = o.clone + 3.times { d.sp_in_add(1000); c.sp_in_add(2000) } + o.sp_in_add(25) + [o.get_n, d.get_n, c.get_n] +end +t('int: frozen refuses a raw store') do + o = InObj.new; o.sp_in_put(1500); o.sp_in_add(1); o.freeze + [(o.sp_in_add(1) rescue $!.class), (o.sp_in_put(2) rescue $!.class), (sp_in_attr(o, 1) rescue $!.class), o.get_n] +end +t('int: Marshal same bytes as boxed') do + o = InObj.new; o.sp_in_put(70_000); o.sp_in_add(1); g = InObj.new; g.instance_variable_set(:@n, 70_001) + m = Marshal.load(Marshal.dump(o)) + [Marshal.dump(o) == Marshal.dump(g), m.get_n, m.instance_variables] +end +t('int: past an Int32, a long, and back') do + o = InObj.new; o.sp_in_put(2147483646); o.sp_in_add(1) + r = [o.sp_in_add(1), o.sp_in_add(1), o.get_n, o.sp_in_get, o.instance_variable_get(:@n)] + r << o.sp_in_mul(2**31) << o.sp_in_mul(2**31) << o.get_n.class << o.sp_in_add(1) << o.sp_in_get + o.sp_in_put(-5); r << o.sp_in_add(2**62) << o.sp_in_add(2**62) << o.sp_in_add(-(2**63)) << o.get_n +end +t('int: flip to nil, Float, String and back') do + o = InObj.new; o.sp_in_put(1500); o.sp_in_add(1) + r = [] + o.instance_variable_set(:@n, nil); r << (o.sp_in_add(1) rescue $!.class) << o.get_n + o.instance_variable_set(:@n, 2.5); r << o.sp_in_add(1) << o.sp_in_get + o.instance_variable_set(:@n, 'str'); r << (o.sp_in_get rescue $!.class) << (o.sp_in_idx([1]) rescue $!.class) + o.sp_in_put(3000); r << o.sp_in_add(1) << o.get_n + o.sp_in_put(7500); o.instance_variable_set(:@n, 9); r << o.get_n << o.sp_in_add(1) + o.instance_variable_set(:@n, 10**30); r << o.sp_in_add(1) << (o.sp_in_idx([1]) rescue $!.class) + r +end +t('int: removed and re-added') do + o = InObj.new; o.sp_in_put(4500); o.sp_in_add(1) + r = [o.remove_instance_variable(:@n), o.instance_variables, (o.sp_in_get rescue $!.class), o.get_n] + o.sp_in_put(5500); r << o.instance_variables << o.get_n << o.sp_in_add(1) + o.remove_instance_variable(:@y); o.sp_in_add(1); r << o.instance_variables << o.get_n +end +t('int: identity and hash') do + o = InObj.new + [5, 999, 1000, 70_000, 2147483647, 2**40, -(2**40)].map do |v| + o.sp_in_put(v); o.sp_in_add(0); n = o.get_n + [n.equal?(o.get_n), n.object_id == v.object_id, n.hash == v.hash, { v => 1 }[n], n.eql?(v), o.instance_variable_get(:@n).equal?(n)] + end +end +t('int: as an index and a count') { o = InObj.new; o.sp_in_put(2); o.sp_in_add(1); [o.sp_in_idx([0, 1, 2, 3, 4]), 'ab' * o.get_n, Array.new(o.get_n, 0)] } From 0bf359838a94797796e1fb744e43bbc359aafd45 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:41:56 +0000 Subject: [PATCH 264/439] Take raw Integer instance variables out again; ledger: perf/intivar rejected perf/intivar (58013a9) stored an Integer the method JIT holds as an int or a long in an IntLocation, as Float instance variables are stored. It saved the 24-byte box of a typed write past the small-integer cache (a counter 0.91, an attr write 0.89, Random#next 0.93 by clock, alloc.rb Json -17%), but AWFY's Bounce, whose class becomes born raw, ran 31% slower over ten alternating rounds (36,702 -> 48,136 us, no overlap), a generic read of a raw object 14% slower, and no AWFY benchmark faster. Most of AWFY's Integer ivar writes are not in typed code at all (methods the JIT refuses, writes in loops neither tier compiles, writes that are the method's value). The runtime goes back to the base; the matrix rows (ivar-matrix, jit-matrix section 21), the stress part and Util/bench/intivar-shapes.rb stay for the next attempt, their comments pointing at 58013a9. Both matrices print CRuby's output on the base. The ledger entry (Rejected, perf/intivar) has the measurements, why it lost, and what would make it pay; gap 2 and perf/permute's entry point at it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- Src/Ruby/Builtins/RubyClass.cs | 8 +- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 6 +- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 7 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 31 +--- Src/Ruby/Runtime/Jit/JitRuntime.cs | 169 +------------------- Src/Ruby/Runtime/RubyInstanceData.cs | 161 +++---------------- Src/Ruby/Runtime/RubyOps.cs | 103 +----------- Util/bench/intivar-shapes.rb | 6 +- Util/ivar-matrix.rb | 7 +- Util/ivar-stress.rb | 2 +- Util/jit-matrix.rb | 7 +- Util/perf/LEDGER.md | 62 ++++++- 12 files changed, 111 insertions(+), 458 deletions(-) diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index 5f622556f..7cc4c7563 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -111,11 +111,11 @@ public void UndefineAllocator() { internal int InstanceVariableCapacity; /// - /// An instance of this class has been promoted to raw Float or Integer storage (RubyInstanceData, - /// "Float locations"): new instances start in the raw shape tree, so that they need no Move of - /// their own. Set once, never cleared; a racy read only costs one instance a Move. + /// An instance of this class has been promoted to raw Float storage (RubyInstanceData, "Float + /// locations"): new instances start in the raw shape tree, so that they need no Move of their + /// own. Set once, never cleared; a racy read only costs one instance a Move. /// - internal bool BornRaw; + internal bool FloatsRaw; // // Null if this class doesn't represent a CLR type, it represets a CLR type that implements IRubyObject or diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index e8c6391c3..26c39724c 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1972,10 +1972,6 @@ private static string AgreedAccessorVariable(IEnumerable/*!*/ classes // a Float stored raw (RubyInstanceData, "Float locations") ? Ast.Call(JitRuntime.M("WriteAttrDouble"), Ast.Constant(_context), receiverTemp, valueTemp, Ast.Constant(new JitRuntime.SelfAttrSite(node.Name, variableName, explicitReceiver, true))) - : (RawInts && IsInteger(valueType)) - // an Integer stored raw too - ? Ast.Call(JitRuntime.M("WriteAttrLong"), Ast.Constant(_context), receiverTemp, Coerce(valueTemp, valueType, JT.Lng), - Ast.Constant(new JitRuntime.SelfAttrSite(node.Name, variableName, explicitReceiver, true))) : Ast.Call(JitRuntime.M("WriteAttr"), Ast.Constant(_context), receiverTemp, BoxForStore(valueTemp, valueType), Ast.Constant(new JitRuntime.SelfAttrSite(node.Name, variableName, explicitReceiver, true))), valueTemp @@ -2201,7 +2197,7 @@ private static JT ElementType(RubyArray/*!*/ array) { switch (t) { case JT.Int: return e; case JT.Lng: return Coerce(e, JT.Lng, JT.Int); - case JT.Obj: _canDeopt = true; return GuardIVarRead("GuardInt", e); + case JT.Obj: _canDeopt = true; return Ast.Call(JitRuntime.M("GuardInt"), e); default: throw Bail("Array index of type " + t); } } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index aae072d8d..b806de9fa 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -102,8 +102,7 @@ private MSA.Expression TrySinkIVarWrite(SimpleAssignmentExpression/*!*/ node, st // An Integer written as an Int32 and as an Int64 is one Ruby class in two representations: held in one long, // and stored through NarrowLong, which boxes a value that fits an Int32 as the Int32 the generic body stores. // A Float and an Integer, or a number and an object, are not widened: a Float is stored raw (SetIVarDouble) - // and an Integer raw too (SetIVarLong) or boxed, and one typed local cannot say which of the two classes the - // variable holds. + // and an Integer boxed, and one typed local cannot say which of the two classes the variable holds. if (vt == JT.Int && _sinkWide != null && _sinkWide.Contains(name)) { v = Coerce(v, JT.Int, JT.Lng); vt = JT.Lng; @@ -228,8 +227,6 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { } storeOf[s] = (s.Type == JT.Dbl) ? Ast.Call(JitRuntime.M("SetIVarDouble"), Ast.Constant(_context), _self, s.Value, site) - : (RawInts && IsInteger(s.Type)) - ? Ast.Call(JitRuntime.M("SetIVarLong"), Ast.Constant(_context), _self, Coerce(s.Value, s.Type, JT.Lng), site) : Ast.Call(JitRuntime.M("SetIVar"), Ast.Constant(_context), _self, Coerce(s.Value, s.Type, JT.Obj), site); } var stores = new List(); @@ -277,7 +274,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { /// could read a held-back variable, of self or of an object that is self, and compiles the body without. /// private static readonly HashSet/*!*/ _sinkSafeHelpers = new HashSet { - "GetIVar", "GetIVarDouble", "GetIVarSpeculateDouble", "GetIVarInt", "GetIVarLong", "GuardInt", "GuardLong", "GuardDouble", "SpeculateDouble", "StringLength", "StringIndex", "StringEqualsLiteral", "StringEqualsString", "CaseString", + "GetIVar", "GetIVarDouble", "GetIVarSpeculateDouble", "GuardInt", "GuardLong", "GuardDouble", "SpeculateDouble", "StringLength", "StringIndex", "StringEqualsLiteral", "StringEqualsString", "CaseString", // Integer arithmetic that deopts on overflow, a zero divisor or a shift it cannot make "AddInt", "SubInt", "MulInt", "DivInt", "ModInt", "ShrInt", "AddLong", "SubLong", "MulLong", "DivLong", "ModLong", "ShlLong", "ShrLong", "AbsLong", "MathSqrt", diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 39e54b12b..a825069ef 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1631,15 +1631,6 @@ internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { Ast.Call(JitRuntime.M("SetIVarDouble"), Ast.Constant(_context), _self, raw, ivarSite), raw); } - if (RawInts && IsInteger(vt)) { - // an Integer stored raw, as a Float is; the value stays an int (a long) - var raw = Ast.Variable(ClrType(vt), "#value"); - type = vt; - return Ast.Block(ClrType(vt), new[] { raw }, - Ast.Assign(raw, v), - Ast.Call(JitRuntime.M("SetIVarLong"), Ast.Constant(_context), _self, Coerce(raw, vt, JT.Lng), ivarSite), - raw); - } type = JT.Obj; return Ast.Call(JitRuntime.M("SetIVar"), Ast.Constant(_context), _self, Coerce(v, vt, JT.Obj), ivarSite); } @@ -2703,8 +2694,8 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { } if (from == JT.Obj) { switch (to) { - case JT.Int: _canDeopt = true; return GuardIVarRead("GuardInt", e); - case JT.Lng: _canDeopt = true; return GuardIVarRead("GuardLong", e); + case JT.Int: _canDeopt = true; return Ast.Call(JitRuntime.M("GuardInt"), e); + case JT.Lng: _canDeopt = true; return Ast.Call(JitRuntime.M("GuardLong"), e); case JT.Dbl: _canDeopt = true; return GuardIVarRead("GuardDouble", e); } } @@ -2820,28 +2811,20 @@ private static bool IsNumeric(JT t) { } /// - /// The guarded unboxing of an instance variable read: GuardDouble (SpeculateDouble, GuardInt, GuardLong) of GetIVar or - /// ReadSelfAttr becomes their Double (SpeculateDouble, Int, Long) version, which reads a Float (an Integer) the typed code - /// stored raw without boxing it (RubyInstanceData, "Float locations"). Both deopt on the same values. + /// The guarded unboxing of an instance variable read: GuardDouble (SpeculateDouble) of GetIVar or + /// ReadSelfAttr becomes their Double (SpeculateDouble) version, which reads a Float the typed code stored raw without boxing it + /// (RubyInstanceData, "Float locations"). Both deopt on the same values. /// internal static MSA.Expression/*!*/ GuardIVarRead(string/*!*/ guard, MSA.Expression/*!*/ read) { var call = read as MSA.MethodCallExpression; - if ((guard == "GuardDouble" || guard == "SpeculateDouble" || (RawInts && (guard == "GuardInt" || guard == "GuardLong"))) - && call != null && call.Object == null) { - string suffix = (guard == "GuardDouble") ? "Double" : (guard == "GuardInt") ? "Int" : (guard == "GuardLong") ? "Long" : "SpeculateDouble"; + if ((guard == "GuardDouble" || guard == "SpeculateDouble") && call != null && call.Object == null) { + string suffix = (guard == "GuardDouble") ? "Double" : "SpeculateDouble"; if (call.Method == JitRuntime.M("GetIVar")) { return Ast.Call(JitRuntime.M("GetIVar" + suffix), call.Arguments); } if (call.Method == JitRuntime.M("ReadSelfAttr")) { return Ast.Call(JitRuntime.M("ReadSelfAttr" + suffix), call.Arguments); } } return Ast.Call(JitRuntime.M(guard), read); } - /// - /// An Integer the typed code holds as an int or a long is stored into an instance variable raw, and - /// read back without a box (RubyInstanceData, "Float locations"; JitRuntime.SetIVarLong). IR_RAW_INTS=0: - /// boxed, as before. - /// - internal static readonly bool RawInts = Environment.GetEnvironmentVariable("IR_RAW_INTS") != "0"; - /// The two representations of a Ruby Integer the specialized code carries. private static bool IsInteger(JT t) { return t == JT.Int || t == JT.Lng; diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index dc4c54d6b..29e31fd20 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -524,15 +524,8 @@ public static object SetGlobal(RubyContext/*!*/ context, GlobalVariableSite/*!*/ [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object GetIVar(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { object value; - if (self is RubyObject obj) { - var data = obj._instanceData; - if (RubyOps.TryReadCached(data, site, out value)) { - return value; - } - // a raw object's read (RubyInstanceData, "Float locations"), as RubyOps.GetInstanceVariable's - if (RubyOps.TryReadCachedRaw(data, site, out value)) { - return value; - } + if (self is RubyObject obj && RubyOps.TryReadCached(obj._instanceData, site, out value)) { + return value; } return GetIVarUncached(context, self, site); } @@ -960,7 +953,7 @@ public static object[] BeginInitialIVars(object self, InitialIVarsSite/*!*/ site int count = site.Shape.Count; var result = new object[Math.Max(count, obj.ImmediateClass.InstanceVariableCapacity) + 1]; // born raw if its class's instances get their Floats promoted (RubyInstanceData, "Float locations") - result[0] = obj.ImmediateClass.BornRaw ? (site.Shape.RawTwin ?? site.Shape) : site.Shape; + result[0] = obj.ImmediateClass.FloatsRaw ? (site.Shape.RawTwin ?? site.Shape) : site.Shape; return result; } @@ -1188,8 +1181,7 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* // a race the generic code has too (the rollback would then undo it) log.ReplacedFloat(data, variable.Name, location.Value); } else { - // a raw Integer is logged boxed, as WriteSelfAttr logs it - log.Replaced(data, variable.Name, RubyInstanceData.ValueOf(old)); + log.Replaced(data, variable.Name, old); } if (RubyInstanceData.TryWriteFloat(slots, shape, index, value)) { return; @@ -1209,159 +1201,6 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* data.SetInstanceVariable(variable.Name, value); } - // ---- Integer instance variables stored raw (RubyInstanceData, "Float locations") ----------- - // An Integer the typed code holds as an int or a long is stored raw in an IntLocation as a Float - // is in a FloatLocation: GuardInt / GuardLong of GetIVar / ReadSelfAttr become these, which read - // a raw Integer without boxing it and deopt on the values the guards deopt on, and a store of an - // int or a long is SetIVarLong / WriteAttrLong. IR_RAW_INTS=0: the compiler emits neither. - - /// GuardLong(GetIVar(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static long GetIVarLong(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { - if (self is RubyObject obj) { - var data = obj._instanceData; - if (data != null) { - object[] slots = data._ivars; - var entry = site.Cache; - if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { - // a box first: a plain object's read is the shape compare and GuardLong's test, - // as before. A location is only ever in a raw array, so its type says it all. - object slot = RubyInstanceData.GetSlot(slots, entry.Index); - if (slot is int) { - return (int)slot; - } - if (slot is IntLocation location) { - return location.Value; - } - } - } - } - return GetIVarLongSlow(context, self, site); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static long GetIVarLongSlow(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { - // the site's second shape (RubyOps.TryReadCachedLong), then the object read - long value; - if (self is RubyObject obj && RubyOps.TryReadCachedLong(obj._instanceData, site, out value)) { - return value; - } - return GuardLong(GetIVar(context, self, site)); - } - - /// GuardInt(GetIVar(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int GetIVarInt(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { - if (self is RubyObject obj) { - var data = obj._instanceData; - if (data != null) { - object[] slots = data._ivars; - var entry = site.Cache; - if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { - object slot = RubyInstanceData.GetSlot(slots, entry.Index); - if (slot is int) { - return (int)slot; - } - // a raw Integer past an Int32 is one the generic code holds as an Int64: GuardInt's deopt - if (slot is IntLocation location && location.Value == (int)location.Value) { - return (int)location.Value; - } - } - } - } - return GetIVarIntSlow(context, self, site); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static int GetIVarIntSlow(RubyContext/*!*/ context, object self, InstanceVariableSite/*!*/ site) { - long value; - if (self is RubyObject obj && RubyOps.TryReadCachedLong(obj._instanceData, site, out value) && value == (int)value) { - return (int)value; - } - return GuardInt(GetIVar(context, self, site)); - } - - /// GuardLong(ReadSelfAttr(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static long ReadSelfAttrLong(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { - if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass)) { - var data = obj._instanceData; - if (data != null) { - object[] slots = data._ivars; - var entry = site.Variable.Cache; - if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { - object slot = RubyInstanceData.GetSlot(slots, entry.Index); - if (slot is int) { - return (int)slot; - } - if (slot is IntLocation location) { - return location.Value; - } - } - } - } - return ReadSelfAttrLongSlow(context, self, site); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static long ReadSelfAttrLongSlow(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { - long value; - if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass) && RubyOps.TryReadCachedLong(obj._instanceData, site.Variable, out value)) { - return value; - } - return GuardLong(ReadSelfAttr(context, self, site)); - } - - /// GuardInt(ReadSelfAttr(...)) without boxing a raw Integer (JitCompiler.GuardIVarRead). - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int ReadSelfAttrInt(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { - if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass)) { - var data = obj._instanceData; - if (data != null) { - object[] slots = data._ivars; - var entry = site.Variable.Cache; - if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { - object slot = RubyInstanceData.GetSlot(slots, entry.Index); - if (slot is int) { - return (int)slot; - } - if (slot is IntLocation location && location.Value == (int)location.Value) { - return (int)location.Value; - } - } - } - } - return ReadSelfAttrIntSlow(context, self, site); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static int ReadSelfAttrIntSlow(RubyContext/*!*/ context, object self, SelfAttrSite/*!*/ site) { - long value; - if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass) && RubyOps.TryReadCachedLong(obj._instanceData, site.Variable, out value) - && value == (int)value) { - return (int)value; - } - return GuardInt(ReadSelfAttr(context, self, site)); - } - - /// SetIVar of an Integer the body holds as an int or a long. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void SetIVarLong(RubyContext/*!*/ context, object self, long value, InstanceVariableSite/*!*/ site) { - if (self is RubyObject obj && RubyOps.TryWriteCachedLong(obj._instanceData, value, site, obj.ImmediateClass)) { - return; - } - SetIVarUncached(context, self, IntLocation.Box(value), site); - } - - /// WriteAttr of an Integer the body holds as an int or a long. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void WriteAttrLong(RubyContext/*!*/ context, object self, long value, SelfAttrSite/*!*/ site) { - if (self is RubyObject obj && site.IsBoundTo(obj.ImmediateClass) && RubyOps.TryWriteCachedLong(obj._instanceData, value, site.Variable, obj.ImmediateClass)) { - return; - } - WriteAttrUncached(context, self, IntLocation.Box(value), site); - } - // An instance variable used as a numeric operand of an outlined loop (JitCompiler.NumericIVar): // unboxed while it holds the type it held when the loop was compiled, a deopt once it does not. diff --git a/Src/Ruby/Runtime/RubyInstanceData.cs b/Src/Ruby/Runtime/RubyInstanceData.cs index 9fa4dc68e..262984117 100644 --- a/Src/Ruby/Runtime/RubyInstanceData.cs +++ b/Src/Ruby/Runtime/RubyInstanceData.cs @@ -52,57 +52,6 @@ internal object/*!*/ Boxed { } } - /// - /// An Integer instance variable stored raw, as a Float: see - /// RubyInstanceData, "Float locations". It holds an Integer the typed code carries as an int or a - /// long; a Bignum is never in one. Only ever in a slot array, never handed out as a value. - /// - internal sealed class IntLocation { - internal long Value; - - // The box the generic reads last handed out, as FloatLocation's: so that a value read many - // times between two raw writes is boxed once. The raw writes never touch it. - private object _box; - - internal IntLocation(long value) { - Value = value; - } - - internal object/*!*/ Boxed { - get { - long value = Value; - if (IsCached(value)) { - // the small-integer cache: what the generic body would have stored - return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject((int)value); - } - object box = Volatile.Read(ref _box); - if (box != null && (box is int ? (int)box : (long)box) == value) { - return box; - } - box = Box(value); - Volatile.Write(ref _box, box); - return box; - } - } - - /// - /// A value the small-integer cache has a box for: storing it boxed costs nothing, so it is - /// never what makes a location (RubyInstanceData.TryWriteLong). - /// - internal static bool IsCached(long value) { - return value >= -100 && value < 1000; - } - - /// - /// An Integer the typed code holds as a long, as the generic code holds it: an Int32 if it - /// fits (JitRuntime.NarrowLong's representation rule), else an Int64. - /// - internal static object/*!*/ Box(long value) { - return (value >= Int32.MinValue && value <= Int32.MaxValue) - ? Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject((int)value) : (object)value; - } - } - /// /// Stores the per-instance data that all Ruby objects need (frozen?, instance_variables, etc) /// Stored in a lookaside weak hashtable for types that don't implement IRubyObject (i.e. .NET types). @@ -164,11 +113,7 @@ internal static bool IsCached(long value) { /// /// A slot may hold a instead of a value: a Float stored raw, so that /// the typed code of the method JIT and the loop tiers, which carries Floats as doubles, updates - /// one without boxing it (JitRuntime.SetIVarDouble and the other *Double helpers). An Integer the - /// typed code carries as an int or a long is stored raw the same way, in an - /// (JitRuntime.SetIVarLong and the *Int and *Long reads; IR_RAW_INTS=0 leaves Integers boxed): - /// what is said here of a FloatLocation and a Float holds of an IntLocation and an Integer that - /// fits a long, and a long field is as atomic as a double one on the platforms named below. + /// one without boxing it (JitRuntime.SetIVarDouble and the other *Double helpers). /// /// Rawness belongs to the shape. Every shape has a raw twin (: /// same names, same slots, IsRaw), every transition from a raw shape leads to a raw shape, and a @@ -183,9 +128,8 @@ internal static bool IsCached(long value) { /// boxing a location's Float - the same box again while the value has not changed. /// /// Policy: a typed store promotes the object when it overwrites a slot that already holds a Float - /// (an Integer, for an Integer store: the variable is being updated); a store that adds the - /// variable or replaces anything else stores a box, so values set once (constructors) never - /// cost a Move and a location. + /// (the variable is being updated); a store that adds the variable or replaces anything else + /// stores a box, so Floats set once (constructors) never cost a Move and a location. /// /// In a raw array the first raw store into a slot allocates its location and later ones write its /// field; every other write stores the value itself, which replaces the location (a type change @@ -287,13 +231,12 @@ public void Freeze() { #region Instance Variables: layout /// - /// The value a slot holds: the slot itself, or the Float of a or the - /// Integer of an , boxed. + /// The value a slot holds: the slot itself, or the Float of a , boxed. /// [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] internal static object ValueOf(object slot) { - // inlined into every cached read: two exact type checks, and the boxing out of line - return (slot is FloatLocation || slot is IntLocation) ? BoxedValueOf(slot) : slot; + // inlined into every cached read: a type check, and the boxing out of line + return (slot is FloatLocation) ? BoxedValueOf(slot) : slot; } /// @@ -307,8 +250,7 @@ internal static object ValueOf(InstanceVariableShape/*!*/ shape, object slot) { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static object BoxedValueOf(object slot) { - var location = slot as FloatLocation; - return (location != null) ? location.Boxed : ((IntLocation)slot).Boxed; + return ((FloatLocation)slot).Boxed; } /// @@ -463,7 +405,7 @@ internal void CopyInstanceVariablesTo(RubyInstanceData/*!*/ dup, object copy) { var slots = new object[s.Length]; for (int i = 1; i <= shape.Count; i++) { - // a FloatLocation (IntLocation) is the original's: the copy gets the value boxed + // a FloatLocation is the original's: the copy gets the Float boxed var value = ValueOf(shape, s[i]); var state = value as IPerObjectState; slots[i] = state != null ? state.CopyFor(copy) : value; @@ -702,7 +644,7 @@ internal void SetInstanceVariable(string/*!*/ name, object value, RubyClass hint if (s.Length == 1) { // the first variable: nothing to copy, nobody writing Debug.Assert(index == 1); - if (hintClass != null && hintClass.BornRaw) { + if (hintClass != null && hintClass.FloatsRaw) { // born raw: its class's instances get their Floats promoted next = next.RawTwin ?? next; } @@ -782,8 +724,8 @@ internal bool TrySetCached(InstanceVariableSite.Entry/*!*/ entry, object value, // born raw if and only if its class's instances get their Floats promoted: the site's // Next may be of either tree, since a site sees the instances of several classes var next = entry.Next; - if (ownerClass != null && ownerClass.BornRaw != next.IsRaw) { - next = (ownerClass.BornRaw ? next.RawTwin : next.PlainTwin) ?? next; + if (ownerClass != null && ownerClass.FloatsRaw != next.IsRaw) { + next = (ownerClass.FloatsRaw ? next.RawTwin : next.PlainTwin) ?? next; } first[0] = next; first[1] = value; @@ -826,12 +768,12 @@ internal InstanceVariableShape TryWriteFloatPlain(object[]/*!*/ s, InstanceVaria RubyClass ownerClass) { Debug.Assert(!shape.IsRaw); if (GetSlot(s, index) is double) { - var raw = TryPromote(s, shape, index, new FloatLocation(value)); + var raw = TryPromote(s, shape, index, value); if (raw != null) { - if (ownerClass != null && !ownerClass.BornRaw) { + if (ownerClass != null && !ownerClass.FloatsRaw) { // its later instances are born raw and need no Move (a Move's process-wide // barrier costs a few hundred ns) - ownerClass.BornRaw = true; + ownerClass.FloatsRaw = true; } return raw; } @@ -842,73 +784,6 @@ internal InstanceVariableShape TryWriteFloatPlain(object[]/*!*/ s, InstanceVaria return (ShapeOf(s) == shape) ? shape : null; } - /// - /// of an Integer the typed code holds as a long (an int widened): - /// into the variable's , or a new one - unless the slot has none and the - /// value is one the small-integer cache boxes, which is stored boxed: a short-lived object whose - /// variables stay small (AWFY's Bounce makes thousands) would pay a location for nothing. - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - internal static bool TryWriteLong(object[]/*!*/ slots, object shape, int index, long value) { - Debug.Assert(((InstanceVariableShape)shape).IsRaw); - var location = GetSlot(slots, index) as IntLocation; - if (location != null) { - location.Value = value; - } else { - SetSlot(slots, index, IntLocation.IsCached(value) - ? Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject((int)value) : new IntLocation(value)); - } - return ShapeOf(slots) == shape; - } - - /// - /// of an Integer the typed code holds as a long: a slot that - /// holds an Integer already (an Int32 or an Int64, not a Bignum) gets its object promoted when the - /// value would need a box of its own (see ), every other one gets the - /// Integer boxed as the generic code boxes it. - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] - internal InstanceVariableShape TryWriteLongPlain(object[]/*!*/ s, InstanceVariableShape/*!*/ shape, int index, long value, - RubyClass ownerClass) { - Debug.Assert(!shape.IsRaw); - object old = GetSlot(s, index); - if ((old is int || old is long) && !IntLocation.IsCached(value)) { - var raw = TryPromote(s, shape, index, new IntLocation(value)); - if (raw != null) { - if (ownerClass != null && !ownerClass.BornRaw) { - ownerClass.BornRaw = true; - } - return raw; - } - return null; - } - SetSlot(s, index, IntLocation.Box(value)); - return (ShapeOf(s) == shape) ? shape : null; - } - - /// - /// The Integer a slot holds - raw in an or boxed as an Int32 or an - /// Int64 - for the typed code's reads; false if it holds anything else (a Bignum included). - /// - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - internal static bool TryReadLong(object slot, out long value) { - var location = slot as IntLocation; - if (location != null) { - value = location.Value; - return true; - } - if (slot is int) { - value = (int)slot; - return true; - } - if (slot is long) { - value = (long)slot; - return true; - } - value = 0; - return false; - } - private static int _Promotions; /// @@ -922,14 +797,14 @@ public static int Promotions { /// /// Makes the object raw: a Move (under lock(this), the old array retired as for any Move) to a /// new array whose element 0 is the raw twin of , the slots copied after - /// the barrier and (a new FloatLocation or IntLocation) stored at - /// before the array is published. A FloatLocation is therefore never in an array + /// the barrier and stored at in a new + /// FloatLocation before the array is published. A FloatLocation is therefore never in an array /// whose element 0 is not raw: a reader of the old array sees the old shape and the old values, /// and a writer that stored into the old array is copied or meets Moved and redoes its write. /// Null if it did not happen: no raw twin, or is not the current array of /// that shape any more. /// - private InstanceVariableShape TryPromote(object[]/*!*/ s, InstanceVariableShape/*!*/ shape, int index, object/*!*/ location) { + private InstanceVariableShape TryPromote(object[]/*!*/ s, InstanceVariableShape/*!*/ shape, int index, double value) { var raw = shape.RawTwin; if (raw == null) { return null; @@ -940,7 +815,7 @@ private InstanceVariableShape TryPromote(object[]/*!*/ s, InstanceVariableShape/ } var slots = new object[s.Length]; Array.Copy(s, 1, slots, 1, shape.Count); - slots[index] = location; + slots[index] = new FloatLocation(value); slots[0] = raw; if (!Publish(s, slots)) { throw Assert.Unreachable; diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index e72eaf21f..28138d4b1 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -5843,16 +5843,8 @@ public static int ConvertDoubleToFixnum(double value) { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static object GetInstanceVariable(RubyScope/*!*/ scope, object self, InstanceVariableSite/*!*/ site) { object value; - if (self is RubyObject obj) { - var data = obj._instanceData; - if (TryReadCached(data, site, out value)) { - return value; - } - // an object with raw Floats or Integers (RubyInstanceData, "Float locations"), which the read - // above leaves out: here and not a call away (an Integer counter makes its class's objects raw) - if (TryReadCachedRaw(data, site, out value)) { - return value; - } + if (self is RubyObject obj && TryReadCached(obj._instanceData, site, out value)) { + return value; } return GetInstanceVariableUncached(scope, self, site); } @@ -5999,97 +5991,6 @@ private static bool TryWriteCachedFloatPlain(RubyInstanceData/*!*/ data, object[ return now != null; } - // ---- the same for an Integer the typed code holds as an int or a long (RubyInstanceData, - // "Float locations": an IntLocation is to an Integer what a FloatLocation is to a Float) - - [MethodImpl(MethodImplOptions.NoInlining)] - private static bool TryReadCachedLongSlow(object[]/*!*/ slots, InstanceVariableSite/*!*/ site, InstanceVariableSite.Entry/*!*/ entry, out long value) { - object shape = RubyInstanceData.ShapeOf(slots); - if (shape == entry.Shape) { - // a plain object: a boxed Integer or nothing for us - return RubyInstanceData.TryReadLong(RubyInstanceData.GetSlot(slots, entry.Index), out value); - } else if (shape == entry.OtherShape) { - object slot = RubyInstanceData.GetSlot(slots, entry.OtherIndex); - if (entry.OtherRaw) { - site.Update(entry.Remember(entry.OtherShape, entry.OtherIndex)); - } - return RubyInstanceData.TryReadLong(slot, out value); - } - value = 0; - return false; - } - - // TryReadCached of a variable that holds an Integer that fits a long, for the typed code: the - // long, without boxing a raw one. False for a miss or a variable that holds anything else. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static bool TryReadCachedLong(RubyInstanceData data, InstanceVariableSite/*!*/ site, out long value) { - if (data != null) { - object[] slots = data._ivars; - var entry = site.Cache; - if (RubyInstanceData.ShapeOf(slots) == entry.Shape) { - return RubyInstanceData.TryReadLong(RubyInstanceData.GetSlot(slots, entry.Index), out value); - } - return TryReadCachedLongSlow(slots, site, entry, out value); - } - value = 0; - return false; - } - - // TryWriteCached of an Integer the typed code holds raw: into the variable's IntLocation - // (RubyInstanceData.TryWriteLong). False for a miss, an add, a frozen object or a shape - // changed under it: the caller boxes the Integer and takes the ordinary path. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static bool TryWriteCachedLong(RubyInstanceData data, long value, InstanceVariableSite/*!*/ site, RubyClass ownerClass) { - if (data != null && !data._frozen) { - object[] slots = data._ivars; - var entry = site.Cache; - object shape = RubyInstanceData.ShapeOf(slots); - if (shape == entry.Shape && entry.Next == null) { - if (entry.Raw) { - return RubyInstanceData.TryWriteLong(slots, shape, entry.Index, value); - } - if (IntLocation.IsCached(value)) { - // a plain object and a value the cache boxes: TryWriteCached's store (no promotion for it) - RubyInstanceData.SetSlot(slots, entry.Index, ScriptingRuntimeHelpers.Int32ToObject((int)value)); - return RubyInstanceData.ShapeOf(slots) == shape; - } - } - return TryWriteCachedLongSlow(data, slots, shape, value, site, ownerClass); - } - return false; - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static bool TryWriteCachedLongSlow(RubyInstanceData/*!*/ data, object[]/*!*/ slots, object shape, long value, - InstanceVariableSite/*!*/ site, RubyClass ownerClass) { - var entry = site.Cache; - if (shape == entry.Shape && entry.Next == null) { - return TryWriteCachedLongPlain(data, slots, entry.Shape, entry.Index, value, site, ownerClass); - } - if (shape == entry.Shape) { - // adding the variable (a constructor's `@n = 0'): boxed, by the cached add - return data.TrySetCached(entry, IntLocation.Box(value), ownerClass); - } - if (shape == entry.OtherShape) { - if (entry.OtherRaw) { - site.Update(entry.Remember(entry.OtherShape, entry.OtherIndex)); - return RubyInstanceData.TryWriteLong(slots, shape, entry.OtherIndex, value); - } - return TryWriteCachedLongPlain(data, slots, entry.OtherShape, entry.OtherIndex, value, site, ownerClass); - } - return false; - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static bool TryWriteCachedLongPlain(RubyInstanceData/*!*/ data, object[]/*!*/ slots, InstanceVariableShape/*!*/ shape, - int index, long value, InstanceVariableSite/*!*/ site, RubyClass ownerClass) { - var now = data.TryWriteLongPlain(slots, shape, index, value, ownerClass); - if (now != null && now != shape) { - site.Update(site.Cache.Remember(now, index)); - } - return now != null; - } - [MethodImpl(MethodImplOptions.NoInlining)] private static object GetInstanceVariableUncached(RubyScope/*!*/ scope, object self, InstanceVariableSite/*!*/ site) { RubyInstanceData data; diff --git a/Util/bench/intivar-shapes.rb b/Util/bench/intivar-shapes.rb index 3c87f08e3..8a89ed6bf 100644 --- a/Util/bench/intivar-shapes.rb +++ b/Util/bench/intivar-shapes.rb @@ -1,6 +1,6 @@ -# Integer instance variables stored raw (perf/intivar; RubyInstanceData, "Float locations"): what the -# typed code's writes and reads of an Integer variable cost, and what raw storage costs the generic -# code that reads the same objects. Format of Util/perf/ab.rb: ` ns ` per shape; +# Integer instance variables stored raw (perf/intivar, commit 58013a9, taken out again: Util/perf/LEDGER.md, +# Rejected): what the typed code's writes and reads of an Integer variable cost, and what raw storage +# costs the generic code that reads the same objects. IR_RAW_INTS exists only in that commit. Format of Util/perf/ab.rb: ` ns ` per shape; # shape names as arguments, N from the environment. BYTES=1 (IronRuby only): bytes allocated per # operation instead of ns. INSTR=1 (ab.rb -i): instructions per operation as well. # diff --git a/Util/ivar-matrix.rb b/Util/ivar-matrix.rb index b53866c24..aca43aa9b 100644 --- a/Util/ivar-matrix.rb +++ b/Util/ivar-matrix.rb @@ -170,9 +170,10 @@ def fl_pro_read(o) = o.a * 1.0 end # ---------------------------------------------------------------- Integer variables stored raw -# The method JIT stores an Integer it holds as an int or a long raw (RubyInstanceData, "Raw -# locations"), as it does a Float: a counter's `@n += 1' then updates the variable in place. An -# Integer past a long, or anything else, is stored boxed, and nothing below may tell the two apart. +# perf/intivar stored an Integer the method JIT holds as an int or a long raw, as a Float is +# (commit 58013a9; taken out again, Util/perf/LEDGER.md, Rejected): a counter's `@n += 1' then +# updated the variable in place. An Integer past a long, or anything else, was stored boxed, and +# nothing below may tell the two apart. The rows stay for the next attempt. # (The writers end with a read: a write that is a method's value is stored boxed, its box returned.) class InRaw diff --git a/Util/ivar-stress.rb b/Util/ivar-stress.rb index 19658d145..b6260e728 100644 --- a/Util/ivar-stress.rb +++ b/Util/ivar-stress.rb @@ -67,7 +67,7 @@ def initialize = (@a = 0.5; @b = 1.5) def ga = @a def gb = @b def setb(d) = (@b = d * 1.0) - def setbi(i) = (@b = i + 1; nil) # an Integer stored raw (perf/intivar) + def setbi(i) = (@b = i + 1; nil) # a typed Integer store (perf/intivar stored it raw) end def p_upd(o) = (o.a = o.a + 1.0) def i_upd(o) = (o.a = o.a + 1; nil) diff --git a/Util/jit-matrix.rb b/Util/jit-matrix.rb index cb0f11079..3398ac6d4 100644 --- a/Util/jit-matrix.rb +++ b/Util/jit-matrix.rb @@ -4776,9 +4776,10 @@ def get_x = @x # which keeps the method JIT from compiling `read' here at all. # ---------------------------------------------------------------- 21. Integer instance variables stored raw -# As section 19, for an Integer the typed code holds as an int or a long: `@n = i', `@n op= i', -# `o.n = i' store it into an IntLocation (JitRuntime.SetIVarLong, WriteAttrLong), and its guarded -# Integer reads (GuardInt, GuardLong) read the location raw. A value past a long is a Bignum, boxed. +# As section 19, for an Integer the typed code holds as an int or a long. perf/intivar (commit +# 58013a9, taken out again: Util/perf/LEDGER.md, Rejected) stored it into an IntLocation from +# `@n = i', `@n op= i' and `o.n = i' and read it raw behind GuardInt and GuardLong; the rows stay +# for the next attempt. A value past a long is a Bignum, boxed. # The writers end with a read: a write that is a method's value is stored boxed, its box returned. class InObj attr_accessor :w diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 154fdcaed..4f5d05d7b 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -689,6 +689,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has generic read of a raw object is a call (about 3 ns) because putting it into the inlined read cost every program 2-4% (see "Caught by the measurement (round sixteen)"). + Round perf/intivar (2026-11-28) stored the Integer variables raw too: rejected, Bounce + 31% slower and nothing faster by clock (see Rejected). Round thirty-eight looked at the 152 MB (see Landed, perf/nbody): 608 bytes per `advance`, of which a method scope (160), two Procs (2 x 80) and two BlockParams (2 x 48) were made on every call because a block literal with a literal nested in @@ -1925,7 +1927,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has osr-array, hot-shapes, jit, jit-calls and ivar matrices in every mode and with each switch off: PASS; block-scope-reuse-race 10 of 10 as CRuby; spec/core/integer, core/proc and language block/yield/break as on the base. Left: the `@count` boxes (an Integer instance variable is held - boxed, raw only for Floats) and the locals tuple per scoped call. + boxed, raw only for Floats) and the locals tuple per scoped call. (perf/intivar then tried raw Integer variables: + rejected; `permute` is not typed code, so they would not have reached `@count` anyway.) - **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, @@ -7390,6 +7393,63 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/intivar (/perf-step, 2026-11-28) - Integer instance variables stored raw in the typed + code, as Float ones are: Bounce 31% slower by clock, nothing else faster** (switch `IR_RAW_INTS`; + the implementation is commit 58013a9, the next commit takes its runtime part out again; on + 0af3c4f, which is f67ac44 merged with ae0f0c6). + - **How common, and what it costs.** AWFY's Integer `@x op= ...` writes: Permute `@count` + (in `permute`, which the JIT refuses: `downto`), DeltaBlue `@current_mark` and Towers + `@moves_done` (the method's value), Storage `@count`, Havlak `@loop_counter`, Json `@index`, + Richards `@hold_count` and `@queue_count` (`queue_packet` refused), Bounce `@x`/`@y` and + som.rb's Random#next `@seed`. Only a few are in methods the JIT types: Random#next (values up to + 65,535, a box per call; Storage calls it per Array), Ball#bounce (positions below the cache), + Richards `hold_self`. A write inside a loop is compiled by neither tier ("instance variable write + in an outlined loop" for OSR, "a deopt after an effect" for the method JIT), so `while ...; + @n += 1; ...; end` stays generic. A GC allocation-tick probe put boxed Int32 at 20% of Permute's + ticks, 16% of Richards', 7% of Bounce's, 6% of Queens' (most of them from the generic `+`, + not from the write). app-shapes.rb has none (its counters are Hash values); the stdlib has + 61 `@x += 1` sites. Cost in typed code: `def inc = (@count += 1; nil)` at 5,000 allocates 24 + bytes per call (the Int32 box; `Ast.Convert`, not the cache, for an int), Random#next 48. + - **What it did.** An IntLocation (a long and a cached box) in the raw shapes Float locations use + (RubyInstanceData, "Float locations"): SetIVarLong/WriteAttrLong store it, GetIVarInt/Long and + ReadSelfAttrInt/Long read it raw and deopt where GuardInt/GuardLong would, ValueOf boxes it for + everything else; a typed store over an Int32/Int64 promotes the object and makes its class + born raw (RubyClass.FloatsRaw renamed BornRaw), a Bignum stays boxed. A write that is the + method's value stays boxed (its box is the return value). Bytes per call + (`Util/bench/intivar-shapes.rb`): counter 40 -> 16, Random#next 87 -> 64, `o.w = o.w + 1` 40 -> 16. + alloc.rb: Json 26.9 -> 22.2 MB, Richards 0.70 -> 0.65, DeltaBlue 14.5 -> 14.0, Bounce 5.47 -> 6.18 + (an IntLocation for each new Ball's variable), the rest equal. Then a value the small-integer cache + boxes was stored as that box, never as a location (Bounce 38.3 -> 32.7 KB per `benchmark`). + - **Why not.** By clock (ab.rb, 5 rounds, against the switch off): counter 0.91, attr 0.89, + Random#next 0.93 (overlap); but a generic read of a born-raw object 1.14, a typed write and + read of a small value 1.11, Ball#bounce 1.16 (overlap), the control 1.06 (overlap). AWFY, 10 + alternating rounds of the same build with the switch off and on: **Bounce 36,702 -> 48,136 us + (1.31, no overlap)**, DeltaBlue 1.022, Json 1.024, Richards 0.995, Permute 0.998, Queens 1.002 + (all overlap). Bounce makes 100 Balls an iteration; some get a velocity past the cache, which + makes the class born raw, and then every Ball's typed writes take the raw path - under + callgrind about 37 instructions more a write: TryWriteCachedLong, TryWriteLong and SetIVarLong + are calls, as GetIVar, TryReadCached and GuardInt are (nothing is inlined into the JIT's + dynamic methods). Not making a class born raw for an Integer was worse (Bounce 418 -> 819 us + an iteration: a Move per Ball, and two shapes at each site). Putting the raw read into the + inlined generic `@x` read (as the attr_reader dispatcher has it) is what round sixteen found + cost every program 2-4% ("Caught by the measurement (round sixteen)"). So a raw Integer saves a + 24-byte box (about 3 ns) per typed write past the cache, and costs every other access to the + objects of its class more than that. + - **What would make it pay**: Integer ivar writes in compiled loops (both tiers refuse them + today), and the ivar helpers inlined into the typed code. Then retry from 58013a9. + - **Checks** (on the implementation before its last two changes - the inline store of a cached + value and `is` back in ValueOf - which were then only timed; all passed, the rows kept): `Util/ivar-matrix.rb` and `Util/jit-matrix.rb` + (section 21) Integer rows (cache, Int32, Int64 and Bignum ranges, type changes, identity and + hash, YAML, Marshal, inspect, instance_variable_get/set, remove, freeze, dup/clone, + make_shareable, binding, a subclass with more variables, promotion with plain and born-raw + objects at one site, growth and removal in the raw tree, too complex, two threads) print CRuby's + output on the base and on 58013a9; gate-matrices (ivar, jit, jit-calls, jit-scan, loop-exit, + osr-array, hot-shapes, marshal, block-loop, parked-scope, struct) in every mode and with + `IR_RAW_INTS=0`: PASS; `Util/ivar-stress.rb` (typed Integer updates added to its promotion + part) OK four times; spec core/kernel instance_variable_*, instance_variables, + remove_instance_variable, dup, clone, freeze, inspect, core/basicobject, core/marshal and + language/variables as on the base; IronRuby.Tests (Debug) PASSED. + - **perf/dotsfwd (/perf-frame, 2026-11-27) - `...` forwarding without the rest Array: stopped before building, the forwarded values are reachable after the call** (no code; on bbe4b1a, 4320d4a with claude/perf-lsite and perf/delegate's shape files). The target was the callee's From 658195a125f19727f30b50b4ccd180486b0b3fa6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:45:04 +0000 Subject: [PATCH 265/439] Startup library: an eval text that names the tree is claimed wherever the tree is Forwardable's delegators put the location that defined them into their text (the warning about forwarding to a private method), so 36 of the 56 evals reline makes name the tree's root: they were recorded with the tree startup-files.rb ran in, and only that tree's runs claimed them. The release image (and every build from another checkout) compiled them from text, and so did perf/bootparse's own base in another worktree. startup-files.rb now writes the tree's root in a text as ${ROOT}, as it already did in the path; IronRuby.Aot puts the tree it compiles for in its place, and PrecompiledCode.HashEvalCode hashes a text with the tree's root (the compiled-for root ahead of time, the tree the library runs from at run time) as RootMarker. The compiled code's frozen strings that name the tree are rebased like its other strings (PrecompiledCode.Rooted), so the warning names the tree the code runs in. An eval that would still tie the library to its tree (a symbol naming it) is left out rather than making the whole library unusable in a moved tree. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Src/Ruby/Runtime/PrecompiledCode.cs | 27 ++++++++-- Util/aot/IronRuby.Aot/AotCompiler.cs | 29 +++++++++- Util/aot/IronRuby.Aot/StartupCommand.cs | 19 ++++++- Util/aot/startup-evals.txt | 72 ++++++++++++------------- Util/aot/startup-files.rb | 4 ++ 5 files changed, 109 insertions(+), 42 deletions(-) diff --git a/Src/Ruby/Runtime/PrecompiledCode.cs b/Src/Ruby/Runtime/PrecompiledCode.cs index 4a50b7815..5a83451be 100644 --- a/Src/Ruby/Runtime/PrecompiledCode.cs +++ b/Src/Ruby/Runtime/PrecompiledCode.cs @@ -607,8 +607,29 @@ internal PrecompiledEval(string/*!*/ hash, int index) { } } - /// The SHA-256 of an eval's text, hex: what tells the text the library was compiled from. - public static string/*!*/ HashEvalCode(byte[]/*!*/ code) { + /// + /// The SHA-256 of an eval's text, hex: what tells the text the library was compiled from. The tree's root in it + /// (, with its trailing separator) counts as : a text made from a + /// location (Forwardable's delegators name the file that defined them in a warning) is the same text in a tree that + /// has moved, and the compiled code's strings move with the tree (as a file's do). + /// + public static string/*!*/ HashEvalCode(byte[]/*!*/ code, string root) { + if (!String.IsNullOrEmpty(root)) { + byte[] rootBytes = System.Text.Encoding.UTF8.GetBytes(root); + if (code.AsSpan().IndexOf(rootBytes) >= 0) { + byte[] marker = System.Text.Encoding.UTF8.GetBytes(RootMarker.ToString()); + var rooted = new System.Collections.Generic.List(code.Length); + var rest = code.AsSpan(); + int i; + while ((i = rest.IndexOf(rootBytes)) >= 0) { + rooted.AddRange(rest.Slice(0, i).ToArray()); + rooted.AddRange(marker); + rest = rest.Slice(i + rootBytes.Length); + } + rooted.AddRange(rest.ToArray()); + code = rooted.ToArray(); + } + } return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(code)); } @@ -636,7 +657,7 @@ internal static Func TryClaimEval(R if (!_evals.TryGetValue(key, out candidates)) { return null; } - string hash = HashEvalCode(code); + string hash = HashEvalCode(code, _runtimeRoot ?? _compiledRoot); PrecompiledEval eval = null; foreach (var candidate in candidates) { if (candidate.Hash == hash) { diff --git a/Util/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index a4a0753a3..f331d3b61 100644 --- a/Util/aot/IronRuby.Aot/AotCompiler.cs +++ b/Util/aot/IronRuby.Aot/AotCompiler.cs @@ -77,6 +77,8 @@ internal sealed class AotCompiler { // a path under Root in something other than a string constant (a symbol, a frozen string's bytes): the library // then only runs from where it was compiled private bool _unrelocatable; + // compiling an eval's text (CompileEvals), not a file + private bool _compilingEval; private readonly Dictionary _rootedStrings = new(); private string RootPrefix => Root == null ? null : Root + "/"; @@ -618,16 +620,31 @@ private void CompileEvals(int firstClass, HashSet extended) { _rootedStrings.Clear(); _boxedLiterals.Clear(); var method = _type.DefineMethod(lambda.Name, MethodAttributes.Public | MethodAttributes.Static); - ExpressionCompiler.CompileToMethod((LambdaExpression)Rewrite(lambda), method); + bool unrelocatable = _unrelocatable; + _compilingEval = true; + try { + ExpressionCompiler.CompileToMethod((LambdaExpression)Rewrite(lambda), method); + } finally { + _compilingEval = false; + } DefineLineTable(_lines[_lines.Count - 1]); _type.CreateType(); _evalEntryMethods.Add(method); + // an eval that would tie the library to this tree (a symbol naming it) is not worth the library's other code + // in a tree that has moved: it stays in the assembly, under a key no eval computes + if (_unrelocatable && !unrelocatable) { + _unrelocatable = false; + Console.Error.WriteLine($"left out eval at {e.Path}:{e.Line}: it names the tree where it cannot move with it"); + _evalKeys.Add("\u0003"); + _evalCodes.Add(""); + continue; + } // the key the runtime computes for the eval (PrecompiledCode.EvalKey), with the tree's root as the marker that // PrecompiledCode.Rooted replaces by the tree the library runs from string path = RootPrefix != null ? e.Path.Replace(RootPrefix, PrecompiledCode.RootMarker.ToString()) : e.Path; _evalKeys.Add(PrecompiledCode.EvalKey(e.Encoding, path, e.Line, e.Verbosity, e.InMethod, e.BaseLabel, e.BlockLevels, e.MethodName, e.ParameterNames, e.HasUnsplat, e.LocalNames, e.ModuleNames, e.Module)); - _evalCodes.Add(PrecompiledCode.HashEvalCode(e.Code)); + _evalCodes.Add(PrecompiledCode.HashEvalCode(e.Code, RootPrefix)); Count("evals compiled"); Console.Error.WriteLine($"compiled eval at {e.Path}:{e.Line} ({e.Code.Length} bytes)"); } @@ -1108,6 +1125,14 @@ private Expression Serialize(object value, out string hint) { // literal parts of an interpolated string: frozen, only ever copied from; made of what the compiler // made them of, characters or bytes (appending one kind to the other converts) hint = "str"; + // An eval's text that names the tree was made from a location in it (Forwardable's delegators), and + // it is claimed only by the same text in the tree the library runs from (PrecompiledCode.HashEvalCode): + // its strings name that tree. + if (_compilingEval && !str.IsBinary && IsRooted(str.ToString())) { + Count("eval strings moved with the tree"); + return Expression.Call(typeof(PrecompiledCode).GetMethod("FrozenString", new[] { typeof(string), typeof(RubyEncoding) }), + StringExpression(str.ToString()), ConstantField(str.Encoding, typeof(RubyEncoding))); + } CheckUnrelocatable("string literal", str.ToString()); if (!str.IsBinary) { Count("frozen strings (characters)"); diff --git a/Util/aot/IronRuby.Aot/StartupCommand.cs b/Util/aot/IronRuby.Aot/StartupCommand.cs index 8a246ead6..0bbfb07f0 100644 --- a/Util/aot/IronRuby.Aot/StartupCommand.cs +++ b/Util/aot/IronRuby.Aot/StartupCommand.cs @@ -48,6 +48,22 @@ internal static class StartupCommand { /// The marker startup-evals.txt has for the tree's root in a path: the tree the library is compiled for replaces it. private const string EvalRootMarker = "${ROOT}"; + private static byte[] ReplaceBytes(byte[] bytes, string marker, string value) { + var m = System.Text.Encoding.ASCII.GetBytes(marker); + if (bytes.AsSpan().IndexOf(m) < 0) return bytes; + var v = System.Text.Encoding.UTF8.GetBytes(value); + var result = new List(bytes.Length); + var rest = bytes.AsSpan(); + int i; + while ((i = rest.IndexOf(m)) >= 0) { + result.AddRange(rest.Slice(0, i).ToArray()); + result.AddRange(v); + rest = rest.Slice(i + m.Length); + } + result.AddRange(rest.ToArray()); + return result.ToArray(); + } + // one JSON object a line, as PrecompiledCode.RecordEval writes them private static List ReadEvals(string file, string root) { var result = new List(); @@ -56,7 +72,8 @@ internal static class StartupCommand { var o = System.Text.Json.Nodes.JsonNode.Parse(line).AsObject(); string[] Names(string name) => o[name] is System.Text.Json.Nodes.JsonArray a ? a.Select(n => (string)n).ToArray() : null; result.Add(new AotCompiler.EvalUnit { - Code = Convert.FromBase64String((string)o["code"]), + // the text with this tree for the marker (startup-files.rb puts it in for a text made from a location) + Code = ReplaceBytes(Convert.FromBase64String((string)o["code"]), EvalRootMarker, root), Encoding = (string)o["encoding"], Path = ((string)o["path"]).Replace(EvalRootMarker, root), Line = (int)o["line"], diff --git a/Util/aot/startup-evals.txt b/Util/aot/startup-evals.txt index cc913a6f1..873c404e5 100644 --- a/Util/aot/startup-evals.txt +++ b/Util/aot/startup-evals.txt @@ -208,60 +208,60 @@ {"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYWtyZWYgMC4xLjQgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYWtyZWYiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjEuNCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIkFsbG93cyBhIHJlZmVyZW5jZWQgb2JqZWN0IHRvIGJlIGdhcmJhZ2UtY29sbGVjdGVkIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi93ZWFrcmVmLnJiIi5mcmVlemUsCiAgXQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/weakref-0.1.4.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} {"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHdlYnNvY2tldC1kcml2ZXIgMC44LjIgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gIndlYnNvY2tldC1kcml2ZXIiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjguMiIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIldlYlNvY2tldCBwcm90b2NvbCBoYW5kbGVyOyBXZWJTb2NrZXQ6Ok1hc2sgaW4gQyMuICBQcm92aWRlZCBieSBJcm9uUnVieSBpdHNlbGYuIi5mcmVlemUKICBzLnN1bW1hcnkgPSAiV2ViU29ja2V0IHByb3RvY29sIGhhbmRsZXI7IFdlYlNvY2tldDo6TWFzayBpbiBDIyIuZnJlZXplCiAgcy5ob21lcGFnZSA9ICJodHRwczovL2dpdGh1Yi5jb20vSXJvbkxhbmd1YWdlcy9pcm9ucnVieSIuZnJlZXplCiAgcy5saWNlbnNlcyA9IFsiUnVieSIuZnJlZXplLCAiQlNELTItQ2xhdXNlIi5mcmVlemVdCiAgcy5tZXRhZGF0YSA9IHsgImlyb25ydWJ5X3Bpbm5lZCIuZnJlZXplID0+ICJ0cnVlIi5mcmVlemUgfQogIHMuZmlsZXMgPSBbCiAgICAibGliL3dlYnNvY2tldF9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9jbGllbnQucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9kcmFmdDc1LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvZHJhZnQ3Ni5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2V2ZW50X2VtaXR0ZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oZWFkZXJzLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9kcml2ZXIvaHliaS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL2h5YmkvZnJhbWUucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9oeWJpL21lc3NhZ2UucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2RyaXZlci9wcm94eS5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3NlcnZlci5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvZHJpdmVyL3N0cmVhbV9yZWFkZXIucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAucmIiLmZyZWV6ZSwKICAgICJsaWIvd2Vic29ja2V0L2h0dHAvaGVhZGVycy5yYiIuZnJlZXplLAogICAgImxpYi93ZWJzb2NrZXQvaHR0cC9yZXF1ZXN0LnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9odHRwL3Jlc3BvbnNlLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC9tYXNrLnJiIi5mcmVlemUsCiAgICAibGliL3dlYnNvY2tldC93ZWJzb2NrZXRfbWFzay5yYiIuZnJlZXplLAogIF0KCiAgcy5hZGRfcnVudGltZV9kZXBlbmRlbmN5KCJ3ZWJzb2NrZXQtZXh0ZW5zaW9ucyIuZnJlZXplLCBbIj49IDAuMS4wIi5mcmVlemVdKQplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/websocket-driver-0.8.2.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} {"code":"IyAtKi0gZW5jb2Rpbmc6IHV0Zi04IC0qLQojIHN0dWI6IHlhbWwgMC40LjAgcnVieSBsaWIKIwojIEdlbmVyYXRlZCBieSBVdGlsL2dlbi1kZWZhdWx0LWdlbXNwZWNzLnJiLiAgRG8gbm90IGVkaXQgYnkgaGFuZC4KCkdlbTo6U3BlY2lmaWNhdGlvbi5uZXcgZG8gfHN8CiAgcy5uYW1lID0gInlhbWwiLmZyZWV6ZQogIHMudmVyc2lvbiA9ICIwLjQuMCIKCiAgcy5yZXF1aXJlZF9ydWJ5Z2Vtc192ZXJzaW9uID0gR2VtOjpSZXF1aXJlbWVudC5uZXcoIj49IDAiLmZyZWV6ZSkKICBzLnJlcXVpcmVfcGF0aHMgPSBbImxpYiIuZnJlZXplXQogIHMuYXV0aG9ycyA9IFsiSXJvblJ1YnkiLmZyZWV6ZV0KICBzLmRlc2NyaXB0aW9uID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlLiAgUHJvdmlkZWQgYnkgSXJvblJ1YnkgaXRzZWxmLiIuZnJlZXplCiAgcy5zdW1tYXJ5ID0gIllBTUwgQWluJ3QgTWFya3VwIExhbmd1YWdlIi5mcmVlemUKICBzLmhvbWVwYWdlID0gImh0dHBzOi8vZ2l0aHViLmNvbS9Jcm9uTGFuZ3VhZ2VzL2lyb25ydWJ5Ii5mcmVlemUKICBzLmxpY2Vuc2VzID0gWyJSdWJ5Ii5mcmVlemUsICJCU0QtMi1DbGF1c2UiLmZyZWV6ZV0KICBzLmZpbGVzID0gWwogICAgImxpYi95YW1sLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvZGJtLnJiIi5mcmVlemUsCiAgICAibGliL3lhbWwvc3RvcmUucmIiLmZyZWV6ZSwKICBdCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/gems/4.0.0/specifications/default/yaml-0.4.0.gemspec","line":1,"verbosity":1,"inMethod":true,"baseLabel":"Gem::Specification.load","blockLevels":0,"methodName":"load","parameterNames":["file"],"hasUnsplat":false,"localNames":["file","spec","code","e"],"moduleNames":["Gem::Specification","Gem::Specification"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID0oY29uZmlnKCkpCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lOjpDb3JlI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoxNTkgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvY29tcGxldGlvbicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbiwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID0oY29uZmlnKCkpCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lOjpDb3JlI2F1dG9jb21wbGV0aW9uIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoxNTkgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvY29tcGxldGlvbicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbiwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgKGNvbmZpZygpKQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIpCiAgXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9hcHBlbmRfY2hhcmFjdGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIpCiAgXy5jb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9hcHBlbmRfY2hhcmFjdGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRpb25fYXBwZW5kX2NoYXJhY3RlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2FwcGVuZF9jaGFyYWN0ZXI9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9hcHBlbmRfY2hhcmFjdGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMpCiAgXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYmFzaWNfd29yZF9icmVha19jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMpCiAgXy5iYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycyBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYmFzaWNfd29yZF9icmVha19jaGFyYWN0ZXJzJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJhc2ljX3dvcmRfYnJlYWtfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBiYXNpY193b3JkX2JyZWFrX2NoYXJhY3RlcnM9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6YmFzaWNfd29yZF9icmVha19jaGFyYWN0ZXJzPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uY29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycykKICBfLmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uY29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycykKICBfLmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2NvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6Y29tcGxldGVyX3dvcmRfYnJlYWtfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfd29yZF9icmVha19jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmNvbXBsZXRlcl93b3JkX2JyZWFrX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYmFzaWNfcXVvdGVfY2hhcmFjdGVycykKICBfLmJhc2ljX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YmFzaWNfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYmFzaWNfcXVvdGVfY2hhcmFjdGVycykKICBfLmJhc2ljX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2Jhc2ljX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YmFzaWNfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBiYXNpY19xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmJhc2ljX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzKQogIF8uY29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzKQogIF8uY29tcGxldGVyX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRlcl9xdW90ZV9jaGFyYWN0ZXJzIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0ZXJfcXVvdGVfY2hhcmFjdGVycz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycykKICBfLmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycykKICBfLmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2ZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZmlsZW5hbWVfcXVvdGVfY2hhcmFjdGVycywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBmaWxlbmFtZV9xdW90ZV9jaGFyYWN0ZXJzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmZpbGVuYW1lX3F1b3RlX2NoYXJhY3RlcnM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uc3BlY2lhbF9wcmVmaXhlcykKICBfLnNwZWNpYWxfcHJlZml4ZXMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3NwZWNpYWxfcHJlZml4ZXMgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3NwZWNpYWxfcHJlZml4ZXMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6c3BlY2lhbF9wcmVmaXhlcywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uc3BlY2lhbF9wcmVmaXhlcykKICBfLnNwZWNpYWxfcHJlZml4ZXMoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3NwZWNpYWxfcHJlZml4ZXMgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3NwZWNpYWxfcHJlZml4ZXMnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6c3BlY2lhbF9wcmVmaXhlcywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBzcGVjaWFsX3ByZWZpeGVzPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOnNwZWNpYWxfcHJlZml4ZXM9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX3Byb2MpCiAgXy5jb21wbGV0aW9uX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcHJvYyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRpb25fcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5jb21wbGV0aW9uX3Byb2MpCiAgXy5jb21wbGV0aW9uX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcHJvYyBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjY29tcGxldGlvbl9wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmNvbXBsZXRpb25fcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3Byb2M9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6Y29tcGxldGlvbl9wcm9jPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLm91dHB1dF9tb2RpZmllcl9wcm9jKQogIF8ub3V0cHV0X21vZGlmaWVyX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI291dHB1dF9tb2RpZmllcl9wcm9jIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNvdXRwdXRfbW9kaWZpZXJfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpvdXRwdXRfbW9kaWZpZXJfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLm91dHB1dF9tb2RpZmllcl9wcm9jKQogIF8ub3V0cHV0X21vZGlmaWVyX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI291dHB1dF9tb2RpZmllcl9wcm9jIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNvdXRwdXRfbW9kaWZpZXJfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpvdXRwdXRfbW9kaWZpZXJfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBvdXRwdXRfbW9kaWZpZXJfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpvdXRwdXRfbW9kaWZpZXJfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByb21wdF9wcm9jKQogIF8ucHJvbXB0X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3Byb21wdF9wcm9jIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNwcm9tcHRfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpwcm9tcHRfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByb21wdF9wcm9jKQogIF8ucHJvbXB0X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3Byb21wdF9wcm9jIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNwcm9tcHRfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpwcm9tcHRfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBwcm9tcHRfcHJvYz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcm9tcHRfcHJvYz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYXV0b19pbmRlbnRfcHJvYykKICBfLmF1dG9faW5kZW50X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9faW5kZW50X3Byb2MgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2F1dG9faW5kZW50X3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YXV0b19pbmRlbnRfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uYXV0b19pbmRlbnRfcHJvYykKICBfLmF1dG9faW5kZW50X3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9faW5kZW50X3Byb2MgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2F1dG9faW5kZW50X3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6YXV0b19pbmRlbnRfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBhdXRvX2luZGVudF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmF1dG9faW5kZW50X3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vayguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByZV9pbnB1dF9ob29rKQogIF8ucHJlX2lucHV0X2hvb2soLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ByZV9pbnB1dF9ob29rIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNwcmVfaW5wdXRfaG9vaycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpwcmVfaW5wdXRfaG9vaywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vayguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnByZV9pbnB1dF9ob29rKQogIF8ucHJlX2lucHV0X2hvb2soLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ByZV9pbnB1dF9ob29rIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNwcmVfaW5wdXRfaG9vaycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpwcmVfaW5wdXRfaG9vaywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBwcmVfaW5wdXRfaG9vaz0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpwcmVfaW5wdXRfaG9vaz0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYykKICBfLmRpZ19wZXJmZWN0X21hdGNoX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYykKICBfLmRpZ19wZXJmZWN0X21hdGNoX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2RpZ19wZXJmZWN0X21hdGNoX3Byb2MnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGlnX3BlcmZlY3RfbWF0Y2hfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBkaWdfcGVyZmVjdF9tYXRjaF9wcm9jPSguLi4pCiAgICBjb3JlCiAgICAuX19zZW5kX18oOmRpZ19wZXJmZWN0X21hdGNoX3Byb2M9LCAuLi4pCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBpbnB1dD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDppbnB1dD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBvdXRwdXQ9KC4uLikKICAgIGNvcmUKICAgIC5fX3NlbmRfXyg6b3V0cHV0PSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy52aV9lZGl0aW5nX21vZGUpCiAgXy52aV9lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjdmlfZWRpdGluZ19tb2RlJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnZpX2VkaXRpbmdfbW9kZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5lbWFjc19lZGl0aW5nX21vZGUpCiAgXy5lbWFjc19lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW1hY3NfZWRpdGluZ19tb2RlJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVtYWNzX2VkaXRpbmdfbW9kZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZG11bHRpbGluZSkKICBfLnJlYWRtdWx0aWxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRtdWx0aWxpbmUgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRtdWx0aWxpbmUnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVhZG11bHRpbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnJlYWRsaW5lKQogIF8ucmVhZGxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRsaW5lIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNyZWFkbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fY2FzZV9mb2xkKQogIF8uY29tcGxldGlvbl9jYXNlX2ZvbGQoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fY2FzZV9mb2xkIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0aW9uX2Nhc2VfZm9sZCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX2Nhc2VfZm9sZCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy52aV9lZGl0aW5nX21vZGUpCiAgXy52aV9lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZSBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjdmlfZWRpdGluZ19tb2RlJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnZpX2VkaXRpbmdfbW9kZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5lbWFjc19lZGl0aW5nX21vZGUpCiAgXy5lbWFjc19lZGl0aW5nX21vZGUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZSBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW1hY3NfZWRpdGluZ19tb2RlJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVtYWNzX2VkaXRpbmdfbW9kZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZG11bHRpbGluZSkKICBfLnJlYWRtdWx0aWxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRtdWx0aWxpbmUgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRtdWx0aWxpbmUnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVhZG11bHRpbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLnJlYWRsaW5lKQogIF8ucmVhZGxpbmUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3JlYWRsaW5lIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNyZWFkbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbGluZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fY2FzZV9mb2xkKQogIF8uY29tcGxldGlvbl9jYXNlX2ZvbGQoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fY2FzZV9mb2xkIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0aW9uX2Nhc2VfZm9sZCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX2Nhc2VfZm9sZCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX2Nhc2VfZm9sZD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpjb21wbGV0aW9uX2Nhc2VfZm9sZD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyKQogIF8uY29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlcicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1SZWxpbmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZGxpbmUpCiAgXy5yZWFkbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZGxpbmUgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjE1OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnJlYWRsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBnZXRfc2NyZWVuX3NpemUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5nZXRfc2NyZWVuX3NpemUpCiAgXy5nZXRfc2NyZWVuX3NpemUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2dldF9zY3JlZW5fc2l6ZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZ2V0X3NjcmVlbl9zaXplJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmdldF9zY3JlZW5fc2l6ZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPWxpbmVfZWRpdG9yCiAgICBpZiBkZWZpbmVkPyhfLmVvZj8pCiAgXy5lb2Y/KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNlb2Y/IGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNlb2Y/JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVvZj8sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5lb2Y/KQogIF8uZW9mPyguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjZW9mPyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW9mPycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDplb2Y/LCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBkZWxldGVfdGV4dCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5kZWxldGVfdGV4dCkKICBfLmRlbGV0ZV90ZXh0KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNkZWxldGVfdGV4dCBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZGVsZXRlX3RleHQnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGVsZXRlX3RleHQsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBsaW5lX2J1ZmZlciguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5saW5lKQogIF8ubGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjbGluZV9idWZmZXIgYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL3JlbGluZS5yYjo0NjggZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmxpbmUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBwb2ludCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5ieXRlX3BvaW50ZXIpCiAgXy5ieXRlX3BvaW50ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3BvaW50IGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDY5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYnl0ZV9wb2ludGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJ5dGVfcG9pbnRlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmNvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyKQogIF8uY29tcGxldGlvbl9xdW90ZV9jaGFyYWN0ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2NvbXBsZXRpb25fcXVvdGVfY2hhcmFjdGVyIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlcicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpjb21wbGV0aW9uX3F1b3RlX2NoYXJhY3RlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbGluZSguLi4pCiAgICBfID1SZWxpbmUKICAgIGlmIGRlZmluZWQ/KF8ucmVhZGxpbmUpCiAgXy5yZWFkbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZGxpbmUgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjE1OSBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3JlYWRsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOnJlYWRsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBnZXRfc2NyZWVuX3NpemUoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5nZXRfc2NyZWVuX3NpemUpCiAgXy5nZXRfc2NyZWVuX3NpemUoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2dldF9zY3JlZW5fc2l6ZSBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZ2V0X3NjcmVlbl9zaXplJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmdldF9zY3JlZW5fc2l6ZSwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPWxpbmVfZWRpdG9yCiAgICBpZiBkZWZpbmVkPyhfLmVvZj8pCiAgXy5lb2Y/KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNlb2Y/IGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNlb2Y/JywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmVvZj8sIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlb2Y/KC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5lb2Y/KQogIF8uZW9mPyguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjZW9mPyBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZW9mPycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDplb2Y/LCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBkZWxldGVfdGV4dCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5kZWxldGVfdGV4dCkKICBfLmRlbGV0ZV90ZXh0KC4uLikKZWxzZQogIDo6S2VybmVsLndhcm4gIlJlbGluZSNkZWxldGVfdGV4dCBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjZGVsZXRlX3RleHQnLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZGVsZXRlX3RleHQsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBsaW5lX2J1ZmZlciguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5saW5lKQogIF8ubGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjbGluZV9idWZmZXIgYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL3JlbGluZS5yYjo0NjggZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNsaW5lJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmxpbmUsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBwb2ludCguLi4pCiAgICBfID1saW5lX2VkaXRvcgogICAgaWYgZGVmaW5lZD8oXy5ieXRlX3BvaW50ZXIpCiAgXy5ieXRlX3BvaW50ZXIoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3BvaW50IGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDY5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYnl0ZV9wb2ludGVyJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmJ5dGVfcG9pbnRlciwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBwb2ludD0oLi4uKQogICAgbGluZV9lZGl0b3IKICAgIC5fX3NlbmRfXyg6Ynl0ZV9wb2ludGVyPSwgLi4uKQogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiByZWRpc3BsYXkoLi4uKQogICAgXyA9bGluZV9lZGl0b3IKICAgIGlmIGRlZmluZWQ/KF8ucmVyZW5kZXIpCiAgXy5yZXJlbmRlciguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVkaXNwbGF5IGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDc4IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVyZW5kZXInLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVyZW5kZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8udmlfZWRpdGluZ19tb2RlPykKICBfLnZpX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3ZpX2VkaXRpbmdfbW9kZT8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6dmlfZWRpdGluZ19tb2RlPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZW1hY3NfZWRpdGluZ19tb2RlPykKICBfLmVtYWNzX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZT8gYXQgL2hvbWUvdXNlci93dC1yZXF1aXJlY29sZC9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2VtYWNzX2VkaXRpbmdfbW9kZT8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZW1hY3NfZWRpdGluZ19tb2RlPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBhbWJpZ3VvdXNfd2lkdGgoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hbWJpZ3VvdXNfd2lkdGgpCiAgXy5hbWJpZ3VvdXNfd2lkdGgoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FtYmlndW91c193aWR0aCBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYW1iaWd1b3VzX3dpZHRoJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmFtYmlndW91c193aWR0aCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmxhc3RfaW5jcmVtZW50YWxfc2VhcmNoKQogIF8ubGFzdF9pbmNyZW1lbnRhbF9zZWFyY2goLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2xhc3RfaW5jcmVtZW50YWxfc2VhcmNoIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNsYXN0X2luY3JlbWVudGFsX3NlYXJjaCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpsYXN0X2luY3JlbWVudGFsX3NlYXJjaCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWRpc3BsYXkoLi4uKQogICAgXyA9bGluZV9lZGl0b3IKICAgIGlmIGRlZmluZWQ/KF8ucmVyZW5kZXIpCiAgXy5yZXJlbmRlciguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVkaXNwbGF5IGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9yZWxpbmUucmI6NDc4IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVyZW5kZXInLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6cmVyZW5kZXIsIC4uLikKZW5kCiAgZW5kCmVuZAo=","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiB2aV9lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8udmlfZWRpdGluZ19tb2RlPykKICBfLnZpX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI3ZpX2VkaXRpbmdfbW9kZT8gYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI3ZpX2VkaXRpbmdfbW9kZT8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6dmlfZWRpdGluZ19tb2RlPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBlbWFjc19lZGl0aW5nX21vZGU/KC4uLikKICAgIF8gPWNvcmUKICAgIGlmIGRlZmluZWQ/KF8uZW1hY3NfZWRpdGluZ19tb2RlPykKICBfLmVtYWNzX2VkaXRpbmdfbW9kZT8oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2VtYWNzX2VkaXRpbmdfbW9kZT8gYXQgJHtST09UfS9TcmMvU3RkTGliL3J1YnkvNC4wL2ZvcndhcmRhYmxlLnJiOjI5NCBmb3J3YXJkaW5nIHRvIHByaXZhdGUgbWV0aG9kICIiI3tfLmNsYXNzfSInI2VtYWNzX2VkaXRpbmdfbW9kZT8nLCB1cGxldmVsOiAxCiAgXy5fX3NlbmRfXyg6ZW1hY3NfZWRpdGluZ19tb2RlPywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhbWJpZ3VvdXNfd2lkdGgoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hbWJpZ3VvdXNfd2lkdGgpCiAgXy5hbWJpZ3VvdXNfd2lkdGgoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FtYmlndW91c193aWR0aCBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYW1iaWd1b3VzX3dpZHRoJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmFtYmlndW91c193aWR0aCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaCguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmxhc3RfaW5jcmVtZW50YWxfc2VhcmNoKQogIF8ubGFzdF9pbmNyZW1lbnRhbF9zZWFyY2goLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2xhc3RfaW5jcmVtZW50YWxfc2VhcmNoIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNsYXN0X2luY3JlbWVudGFsX3NlYXJjaCcsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpsYXN0X2luY3JlbWVudGFsX3NlYXJjaCwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDpsYXN0X2luY3JlbWVudGFsX3NlYXJjaD0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBhZGRfZGlhbG9nX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hZGRfZGlhbG9nX3Byb2MpCiAgXy5hZGRfZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FkZF9kaWFsb2dfcHJvYyBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYWRkX2RpYWxvZ19wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmFkZF9kaWFsb2dfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBkaWFsb2dfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmRpYWxvZ19wcm9jKQogIF8uZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpYWxvZ19wcm9jIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNkaWFsb2dfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpkaWFsb2dfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9jb21wbGV0aW9uIGF0IC9ob21lL3VzZXIvd3QtcmVxdWlyZWNvbGQvU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvY29tcGxldGlvbicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbiwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhZGRfZGlhbG9nX3Byb2MoLi4uKQogICAgXyA9Y29yZQogICAgaWYgZGVmaW5lZD8oXy5hZGRfZGlhbG9nX3Byb2MpCiAgXy5hZGRfZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2FkZF9kaWFsb2dfcHJvYyBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6Mjk0IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjYWRkX2RpYWxvZ19wcm9jJywgdXBsZXZlbDogMQogIF8uX19zZW5kX18oOmFkZF9kaWFsb2dfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBkaWFsb2dfcHJvYyguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmRpYWxvZ19wcm9jKQogIF8uZGlhbG9nX3Byb2MoLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2RpYWxvZ19wcm9jIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNkaWFsb2dfcHJvYycsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpkaWFsb2dfcHJvYywgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbiguLi4pCiAgICBfID1jb3JlCiAgICBpZiBkZWZpbmVkPyhfLmF1dG9jb21wbGV0aW9uKQogIF8uYXV0b2NvbXBsZXRpb24oLi4uKQplbHNlCiAgOjpLZXJuZWwud2FybiAiUmVsaW5lI2F1dG9jb21wbGV0aW9uIGF0ICR7Uk9PVH0vU3JjL1N0ZExpYi9ydWJ5LzQuMC9mb3J3YXJkYWJsZS5yYjoyOTQgZm9yd2FyZGluZyB0byBwcml2YXRlIG1ldGhvZCAiIiN7Xy5jbGFzc30iJyNhdXRvY29tcGxldGlvbicsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbiwgLi4uKQplbmQKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"cHJvYyBkbwogIGRlZiBhdXRvY29tcGxldGlvbj0oLi4uKQogICAgY29yZQogICAgLl9fc2VuZF9fKDphdXRvY29tcGxldGlvbj0sIC4uLikKICBlbmQKZW5kCg==","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} -{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5yZWFkbXVsdGlsaW5lKQogIF8ucmVhZG11bHRpbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZG11bHRpbGluZSBhdCAvaG9tZS91c2VyL3d0LXJlcXVpcmVjb2xkL1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVhZG11bHRpbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbXVsdGlsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} +{"code":"cHJvYyBkbwogIGRlZiByZWFkbXVsdGlsaW5lKC4uLikKICAgIF8gPVJlbGluZQogICAgaWYgZGVmaW5lZD8oXy5yZWFkbXVsdGlsaW5lKQogIF8ucmVhZG11bHRpbGluZSguLi4pCmVsc2UKICA6Oktlcm5lbC53YXJuICJSZWxpbmUjcmVhZG11bHRpbGluZSBhdCAke1JPT1R9L1NyYy9TdGRMaWIvcnVieS80LjAvZm9yd2FyZGFibGUucmI6MTU5IGZvcndhcmRpbmcgdG8gcHJpdmF0ZSBtZXRob2QgIiIje18uY2xhc3N9IicjcmVhZG11bHRpbGluZScsIHVwbGV2ZWw6IDEKICBfLl9fc2VuZF9fKDpyZWFkbXVsdGlsaW5lLCAuLi4pCmVuZAogIGVuZAplbmQK","encoding":"UTF-8","path":"${ROOT}/Src/StdLib/ruby/4.0/forwardable.rb","line":227,"verbosity":1,"inMethod":true,"baseLabel":"Forwardable._delegator_method","blockLevels":0,"methodName":"_delegator_method","parameterNames":["obj","accessor","method","ali"],"hasUnsplat":false,"localNames":["obj","accessor","method","ali","args","method_call","loc","pre","mesg"],"moduleNames":["Forwardable","Forwardable"],"module":null} {"code":"c2VsZg==","encoding":"UTF-8","path":"(eval at ${ROOT}/Src/StdLib/ruby/4.0/irb/workspace.rb:71)","line":1,"verbosity":1,"inMethod":false,"baseLabel":"","blockLevels":0,"methodName":null,"parameterNames":null,"hasUnsplat":false,"localNames":[],"moduleNames":[],"module":null} diff --git a/Util/aot/startup-files.rb b/Util/aot/startup-files.rb index 822a1d6c4..5f52e159f 100644 --- a/Util/aot/startup-files.rb +++ b/Util/aot/startup-files.rb @@ -77,6 +77,10 @@ def recorded_evals(args, stdin) File.readlines(record, chomp: true).map do |l| e = JSON.parse(l) e["path"] = e["path"].gsub(tree + "/", "${ROOT}/") + # a text made from a location (Forwardable's delegators) names the tree too: the library hashes it with the tree's + # root as a marker (PrecompiledCode.HashEvalCode), so that it is the same text wherever the tree is + code = e["code"].unpack1("m0").b + e["code"] = [code.gsub((tree + "/").b, "${ROOT}/".b)].pack("m0") JSON.generate(e) end end From a22b068fccfafd4eb8157285823e24fda0f265ad Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:46:10 +0000 Subject: [PATCH 266/439] Let a lambda literal in a branch run in a light frame LambdaDefinition (`->(x) { }') kept 73 methods out of light frames, for no reason but that IsScopeFree had no case for it. A lambda literal is a literal block made into a lambda over the scope variable, which a light frame with literal blocks makes on demand when the literal runs; its return, next and break leave the lambda (its own LambdaUnwinder filter), and its arity is its own. Letting every literal in was measured first (Util/bench/lambda-shapes.rb, callgrind): a lambda made on no call 0.840, on one call in eight 0.901, but on every call 1.042 and returned 1.033 - the scope is made either way, later. So only a method none of whose lambda literals is on the path every call takes (HasUnconditionalLambda: not in a statement, condition, loop body, case value or the left of &&/||/||=) is let in. IR_LIGHT_LAMBDA=0 turns it off. Census +19 light frames, none lost; 47 stay out as "made on every call". Checked with the new Util/light-lambda-matrix.rb plus light-entry, hot-shapes, block-pass and jit in the gate's modes and with the switch off; specs language/lambda, core/proc, core/kernel/lambda; new test Method_LightFrameLambda1 and 164 named IronRuby.Tests pass both ways. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 31 +++ .../Ast/Definitions/MethodDefinition.cs | 114 ++++++++++-- Util/bench/lambda-shapes.rb | 59 ++++++ Util/light-lambda-matrix.rb | 176 ++++++++++++++++++ Util/perf/LEDGER.md | 33 ++++ 6 files changed, 403 insertions(+), 11 deletions(-) create mode 100644 Util/bench/lambda-shapes.rb create mode 100644 Util/light-lambda-matrix.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fe1f68c14..fc6aac9ed 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1179,6 +1179,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGiven1, Method_LightFrameRest1, Method_LightFrameMemberOpAssign1, + Method_LightFrameLambda1, Method_LightFrameMatchSink1, Method_LightFrameMatchSinkRetention1, Method_LightFrameKeywordRest1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 2f519ffc7..91c381c8e 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8241,6 +8241,37 @@ puts refs.count { |r| r.IsAlive } "); } + /// + /// IR_LIGHT_LAMBDA: a method whose lambda literals are in a branch runs in a light frame, which makes its scope when the + /// literal runs (MethodDefinition.HasUnconditionalLambda): the lambda's `return' is its own, it keeps the method's locals + /// past its return, and it checks its arity. + /// + public void Method_LightFrameLambda1() { + TestOutput(@" +def pick(x) = x > 0 ? ->(y) { return y * x if y; :never } : x +def counter(x) + if x + n = x + [-> { n += 1 }, -> { n }] + end +end +def arity(x) = x ? (l = ->(a, b) { a + b }; begin; l.(1); rescue ArgumentError => e; e.message; end) : nil +p 30.times.map { |i| pick(i - 2) }.uniq.size, pick(3).(4), pick(-1) +inc, get = counter(5) +inc.(); inc.() +p get.(), counter(nil), arity(1) +p 40.times.map { |i| [pick(i + 1).(2), counter(i)[1].()] }.last +", @" +30 +12 +-1 +7 +nil +""wrong number of arguments (given 1, expected 2)"" +[80, 39] +"); + } + /// /// `recv.m op= v' in a light frame (IR_LIGHT_MEMBER_OPASSIGN): the read of m, the operator and the write of m= are calls of /// the frame's light sites; the value is the right-hand side whatever m= returns; a private accessor on self; `&.'; binding. diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 5fb30e2d2..f5c5ec791 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -618,6 +618,11 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// internal static readonly bool LightKeywordSplatEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_KEYWORD_SPLAT") != "0"; + /// + /// IR_LIGHT_LAMBDA=0 keeps every method with a lambda literal (`->(x) { }') out of light frames (see IsScopeFree). + /// + internal static readonly bool LightLambdaEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_LAMBDA") != "0"; + /// /// IR_LIGHT_MEMBER_OPASSIGN=0 keeps a method with `recv.m op= v' (`o.x += 1', `o.x ||= v', `self.x &&= v'; a /// MemberAssignmentExpression) out of light frames, as it was: it is a read of m, the operator and a write of m=, three @@ -699,6 +704,68 @@ private sealed class MatchObserverFinder : Walker { public override bool Enter(MethodCall/*!*/ node) { Found |= MatchObserverMethods.Contains(node.MethodName); return !Found; } } + // Set while the body of a method none of whose lambda literals is on the path every call takes is checked + // (IsBodyScopeFree): a lambda literal does not then keep it out of light frames. + [ThreadStatic] + private static bool t_conditionalLambdas; + + /// + /// Whether a lambda literal of the method is made on every call that returns normally: one in a statement of the body or + /// its ensure clause, in a condition, the left of `&&', `||' or `||=', the value of a `case' or the body of a loop. + /// Not one in a branch - the body of an `if', `unless', `when' or `else', either side of `?:', the right of `&&', `||' or + /// `||=', a rescue clause, a block. A light frame makes its scope when the literal runs (perf/lightlambda: a method that + /// makes its lambda on every call took 1.03-1.04 times the instructions light, one that makes it on no call 0.84). + /// + private bool HasUnconditionalLambda() { + var finder = new UnconditionalLambdaFinder(); + foreach (var optional in _parameters.Optional) { + optional.Walk(finder); + } + finder.WalkBody(Body); + return finder.Found; + } + + private sealed class UnconditionalLambdaFinder : Walker { + internal bool Found; + + internal void WalkStatements(Statements statements) { + if (statements != null) { + foreach (var statement in statements) { + statement.Walk(this); + } + } + } + + internal void WalkBody(Body/*!*/ body) { + WalkStatements(body.Statements); + WalkStatements(body.EnsureStatements); + } + + public override bool Enter(LambdaDefinition/*!*/ node) { Found = true; return false; } + public override bool Enter(BlockDefinition/*!*/ node) { return false; } + public override bool Enter(MethodDefinition/*!*/ node) { return false; } + public override bool Enter(Body/*!*/ node) { WalkBody(node); return false; } + public override bool Enter(IfExpression/*!*/ node) { node.Condition.Walk(this); return false; } + public override bool Enter(UnlessExpression/*!*/ node) { node.Condition.Walk(this); return false; } + public override bool Enter(ConditionalExpression/*!*/ node) { node.Condition.Walk(this); return false; } + public override bool Enter(AndExpression/*!*/ node) { node.Left.Walk(this); return false; } + public override bool Enter(OrExpression/*!*/ node) { node.Left.Walk(this); return false; } + public override bool Enter(RescueExpression/*!*/ node) { node.GuardedExpression.Walk(this); return false; } + public override bool Enter(CaseExpression/*!*/ node) { + if (node.Value != null) { + node.Value.Walk(this); + } + return false; + } + public override bool Enter(SimpleAssignmentExpression/*!*/ node) { + if (node.Operation == Symbols.Or || node.Operation == Symbols.And) { + node.Left.Walk(this); + return false; + } + return true; + } + } + private static bool HasRegexLiteral(Expression target, Arguments arguments) { if (target is RegularExpression) { return true; @@ -855,12 +922,14 @@ private static bool HasHandling(Body/*!*/ body) { // The body's statements and its rescue, else and ensure clauses are scope-free (blockLiterals: with literal blocks). private bool IsBodyScopeFree(bool blockLiterals) { - bool saved = t_matchSink; + bool saved = t_matchSink, savedLambdas = t_conditionalLambdas; t_matchSink = !blockLiterals && IsMatchSink(); + t_conditionalLambdas = blockLiterals && LightLambdaEnabled && !HasUnconditionalLambda(); try { return FirstNotScopeFree(blockLiterals) == null && AreClausesScopeFree(Body, blockLiterals, null); } finally { t_matchSink = saved; + t_conditionalLambdas = savedLambdas; } } @@ -1023,16 +1092,23 @@ private string WhyNotLightFrameCandidate() { if (body == null || HasHandling(body) && !LightRescueEnabled) { return "rescue, else or ensure (IR_LIGHT_RESCUE=0)"; } - if (!IsBodyScopeFree(false)) { - var statement = FirstNotScopeFree(LightBlocksEnabled); - if (statement != null) { - return String.Format("{0} at line {1}: {2}", statement.GetType().Name, statement.Location.Start.Line, - WhyNotScopeFree(statement, LightBlocksEnabled)); - } - var why = new StrongBox(); - if (!AreClausesScopeFree(body, LightBlocksEnabled, why)) { - return "rescue, else or ensure clause: " + why.Value; + // (with the lambda literals IsBodyScopeFree would let in) + bool savedLambdas = t_conditionalLambdas; + t_conditionalLambdas = LightBlocksEnabled && LightLambdaEnabled && !HasUnconditionalLambda(); + try { + if (!IsBodyScopeFree(false)) { + var statement = FirstNotScopeFree(LightBlocksEnabled); + if (statement != null) { + return String.Format("{0} at line {1}: {2}", statement.GetType().Name, statement.Location.Start.Line, + WhyNotScopeFree(statement, LightBlocksEnabled)); + } + var why = new StrongBox(); + if (!AreClausesScopeFree(body, LightBlocksEnabled, why)) { + return "rescue, else or ensure clause: " + why.Value; + } } + } finally { + t_conditionalLambdas = savedLambdas; } if (IsLargeWithMultipleAssignment()) { return "multiple assignment in a body of more than " + MaxMultipleAssignmentCalls + " calls"; @@ -1115,12 +1191,14 @@ private bool HasBlockGuard { // A statement of a block's body (BlockDefinition.IsLightCallBody): not one with exception handling, which the rewriter // takes only in a method's frame (LightFrameRewriter.Handling). internal static bool IsScopeFree(Expression/*!*/ node) { - bool saved = t_matchSink; + bool saved = t_matchSink, savedLambdas = t_conditionalLambdas; t_matchSink = false; + t_conditionalLambdas = false; try { return IsScopeFree(node, false, null) && !HandlingFinder.Has(node); } finally { t_matchSink = saved; + t_conditionalLambdas = savedLambdas; } } @@ -1384,6 +1462,20 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong } return true; } + // `->(x) { }': a literal block made into a lambda (BlockDefinition.Transform), as `f { }' makes a Proc of one - over the + // scope, made on demand when the literal runs (blockLiterals, TransformLightFrame). Its `return' and `break' are the + // lambda's own (a LambdaUnwinder its frame catches), not this frame's. Only one the method makes on some calls and + // not others (HasUnconditionalLambda): one made on every call makes the scope on every call, later and dearer. + var lambda = node as LambdaDefinition; + if (lambda != null) { + if (!LightLambdaEnabled) { + return Refuse(why, "LambdaDefinition (IR_LIGHT_LAMBDA=0)"); + } + if (!t_conditionalLambdas) { + return Refuse(why, "LambdaDefinition made on every call"); + } + return blockLiterals || Refuse(why, "LambdaDefinition"); + } var loop = node as WhileLoopExpression; if (loop != null) { return IsScopeFree(loop.Condition, blockLiterals, why) && AreScopeFree(loop.Statements, blockLiterals, why); diff --git a/Util/bench/lambda-shapes.rb b/Util/bench/lambda-shapes.rb new file mode 100644 index 000000000..93bf45a3a --- /dev/null +++ b/Util/bench/lambda-shapes.rb @@ -0,0 +1,59 @@ +# What a method with a lambda literal costs, light frame or not (MethodDefinition.IsScopeFree, IR_LIGHT_LAMBDA): ns per +# call of the method, the caller a `while` loop. +# +# ruby Util/perf/ab.rb -r 10 Util/bench/lambda-shapes.rb "off=env IR_LIGHT_LAMBDA=0 IR_CONFIG=Release ./ir.sh" \ +# "on=env IR_CONFIG=Release ./ir.sh" +# +# rare and branch make their lambda on no call (or one in eight): the light frame makes no scope then. always makes and +# calls one on every call, kept returns one: the scope is made either way, the light frame later. size is a control +# without a lambda. +$stdout.sync = true + +class H + def rare(x) = x < 0 ? ->(y) { y - x }.call(1) : x + 1 + def branch(x) = (x & 7) == 0 ? ->(y) { y + x }.call(1) : x - 1 + def always(x) = ->(y) { y + x }.call(1) + def kept(x) = ->(y) { y + x } + def size(x) = x + 1 +end + +def cpu + File.read("/proc/thread-self/schedstat").to_i / 1e9 +rescue SystemCallError + Process.clock_gettime(Process::CLOCK_MONOTONIC) +end + +# INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the seven sections as the +# time is. See Util/perf/instructions.rb. +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9 + fewest = nil + counted = !!INSTR + sum = nil + 7.times do + c0 = INSTR && INSTR.read + t0 = cpu + sum = yield n + d = cpu - t0 + c1 = INSTR && INSTR.read + best = d if d < best + if c0 && c1 + c = c1 - c0 + fewest = c if fewest.nil? || c < fewest + else + counted = false + end + end + printf "%-12s %9.1f ns %d%s\n", name, best * 1e9 / n, sum, counted ? format(' %.1f instr', fewest.to_f / n) : '' +end +h = H.new +N = (ENV['N'] || 500_000).to_i + +t("rare", N) { |n| i = 0; c = 0; while i < n; c += h.rare(i); i += 1; end; c } +t("branch", N) { |n| i = 0; c = 0; while i < n; c += h.branch(i); i += 1; end; c } +t("always", N) { |n| i = 0; c = 0; while i < n; c += h.always(i); i += 1; end; c } +t("kept", N) { |n| i = 0; c = 0; while i < n; c += h.kept(i).call(1); i += 1; end; c } +t("size", N) { |n| i = 0; c = 0; while i < n; c += h.size(i); i += 1; end; c } diff --git a/Util/light-lambda-matrix.rb b/Util/light-lambda-matrix.rb new file mode 100644 index 000000000..8ef9412ea --- /dev/null +++ b/Util/light-lambda-matrix.rb @@ -0,0 +1,176 @@ +# Differential matrix for a method with a lambda literal (`->(x) { }') in a light frame (MethodDefinition.IsScopeFree, +# IR_LIGHT_LAMBDA): the lambda is made over the method's scope, which the frame makes on demand when the literal runs, +# as for a block literal. Each row runs its methods hot, then once more for the row. CRuby's rules the rows check: +# +# - `return' and `next' in a lambda leave the lambda; `break' too; `return' in a block inside a lambda leaves the lambda; +# - a lambda kept past its method's return still reads and writes the method's locals; +# - a lambda checks its arity (ArgumentError), `lambda(&blk)' of a non-lambda Proc stays a proc; +# - binding, eval, local_variables in a lambda see the method's locals; self, __method__, block_given? and yield are +# the method's; +# - curry, arity, parameters, lambda?; +# - a lambda made only on a rare path; lambdas made in a loop, each over the same scope; threads. +# +# ruby Util/light-lambda-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/light-lambda-matrix.rb > /tmp/ir.txt && diff /tmp/mri.txt /tmp/ir.txt +# IR_LIGHT_LAMBDA=0 ./ir.sh Util/light-lambda-matrix.rb > /tmp/off.txt && diff /tmp/mri.txt /tmp/off.txt +# +# Every row must match, and the last line be `end'. + +$stdout.sync = true +N = 2000 + +def row(name, value) + puts "#{name}: #{value.inspect}" +end + +def err + yield +rescue Exception => e + [e.class, e.message] +end + +def hot(n = N) + r = nil + n.times { r = yield } + r +end + +class L + def ret(x) = (l = ->(y) { return y * 2 if y; :never }; [l.(x), :after]) + def nxt(x) = (l = ->(y) { next y + 1 if y > 0; :neg }; [l.(x), l.(-x)]) + def brk(x) = (l = ->(y) { break y * 3 }; [l.(x), :after]) + def ret_in_block(x) + l = ->(a) { a.each { |e| return e if e > x }; :none } + [l.([1, 5, 9]), :after] + end + def ret_in_loop(x) + r = [] + i = 0 + while i < 3 + r << ->(v) { return v + i }.call(x) + i += 1 + end + r + end + def kept(x) + count = x + [-> { count += 1 }, -> { count }] + end + def arity_err(x) = (l = ->(a, b) { a + b }; [l.(x, 1), err { l.(x) }, err { l.(1, 2, 3) }]) + def opt(x) = ->(a, b = 2, *r, k: 1, &blk) { [a, b, r, k, blk&.call] }.call(x, 3, 4, k: 5) { :blk } + def bind(x) = (z = x * 10; l = -> { binding.local_variable_get(:z) + eval("z") + z }; [l.(), local_variables.sort]) + def lv(x) = (q = x; -> { [q, local_variables.sort] }.call) + def slf(x) = -> { [self.class, __method__, x] }.call + def bg(x) = -> { [block_given?, (yield x if block_given?)] }.call + def sets(x) = (v = 0; ->(n) { v = n * x }.call(4); v) + def curry(x) = ->(a, b, c) { a + b + c }.curry[x][2][3] + def meta(x) = (l = ->(a, b = 1) { }; [l.arity, l.parameters, l.lambda?, ->(*a) { }.arity, x]) + def from_proc(x) = (pr = proc { |a, b| [a, b] }; err { l = lambda(&pr); [l.lambda?, l.call(x), l.call(x, 2, 3)] }) + def rare(x) + return x + 1 if x < 1_000_000 + ->(y) { y }.call(x) + end + def rare_hit(x) = (x > 5 ? ->(y) { y * x }.(2) : x) + def many(x) = Array.new(3) { |i| ->(y) { y + i + x } }.map { |l| l.(1) } + def nested(x) = ->(a) { ->(b) { a + b + x } }.(1).(2) + def call_with_block(x) = ->(&b) { b.call(x) }.call { |v| v * 7 } + def raise_in(x) = (l = -> { raise ArgumentError, "in lambda #{x}" }; err { l.() }) + def to_proc_lam(x) = [1, 2].map(&->(v) { v * x }) + def super_like(x) = -> { __method__ }.call + def defined_yield(x) = -> { defined?(yield) }.call +end + +# the same methods, each lambda in a branch: these are light frames (HasUnconditionalLambda) +class LC + def ret(x) = x ? ((l = ->(y) { return y * 2 if y; :never }; [l.(x), :after])) : :none + def nxt(x) = x ? ((l = ->(y) { next y + 1 if y > 0; :neg }; [l.(x), l.(-x)])) : :none + def brk(x) = x ? ((l = ->(y) { break y * 3 }; [l.(x), :after])) : :none + def ret_in_block(x) + if x + l = ->(a) { a.each { |e| return e if e > x }; :none } + [l.([1, 5, 9]), :after] + end + end + def ret_in_loop(x) + if x + r = [] + i = 0 + while i < 3 + r << ->(v) { return v + i }.call(x) + i += 1 + end + r + end + end + def kept(x) + if x + count = x + [-> { count += 1 }, -> { count }] + end + end + def arity_err(x) = x ? ((l = ->(a, b) { a + b }; [l.(x, 1), err { l.(x) }, err { l.(1, 2, 3) }])) : :none + def opt(x) = x ? (->(a, b = 2, *r, k: 1, &blk) { [a, b, r, k, blk&.call] }.call(x, 3, 4, k: 5) { :blk }) : :none + def bind(x) = x ? ((z = x * 10; l = -> { binding.local_variable_get(:z) + eval("z") + z }; [l.(), local_variables.sort])) : :none + def lv(x) = x ? ((q = x; -> { [q, local_variables.sort] }.call)) : :none + def slf(x) = x ? (-> { [self.class, __method__, x] }.call) : :none + def bg(x) = x ? (-> { [block_given?, (yield x if block_given?)] }.call) : :none + def sets(x) = x ? ((v = 0; ->(n) { v = n * x }.call(4); v)) : :none + def curry(x) = x ? (->(a, b, c) { a + b + c }.curry[x][2][3]) : :none + def meta(x) = x ? ((l = ->(a, b = 1) { }; [l.arity, l.parameters, l.lambda?, ->(*a) { }.arity, x])) : :none + def from_proc(x) = x ? ((pr = proc { |a, b| [a, b] }; err { l = lambda(&pr); [l.lambda?, l.call(x), l.call(x, 2, 3)] })) : :none + def rare(x) + if x + return x + 1 if x < 1_000_000 + ->(y) { y }.call(x) + end + end + def rare_hit(x) = x ? ((x > 5 ? ->(y) { y * x }.(2) : x)) : :none + def many(x) = x ? (Array.new(3) { |i| ->(y) { y + i + x } }.map { |l| l.(1) }) : :none + def nested(x) = x ? (->(a) { ->(b) { a + b + x } }.(1).(2)) : :none + def call_with_block(x) = x ? (->(&b) { b.call(x) }.call { |v| v * 7 }) : :none + def raise_in(x) = x ? ((l = -> { raise ArgumentError, "in lambda #{x}" }; err { l.() })) : :none + def to_proc_lam(x) = x ? ([1, 2].map(&->(v) { v * x })) : :none + def super_like(x) = x ? (-> { __method__ }.call) : :none + def defined_yield(x) = x ? (-> { defined?(yield) }.call) : :none +end + +class LSub < L + def ret(x) = ->(v) { super(v) }.call(x) +end + +class LCSub < LC + def ret(x) = x ? ->(v) { super(v) }.call(x) : :none +end + +o = L.new +%i[ret nxt brk ret_in_block ret_in_loop arity_err opt bind lv slf sets curry meta from_proc rare rare_hit many nested + call_with_block raise_in to_proc_lam super_like defined_yield].each do |name| + row name, [hot { o.send(name, 3) }, o.send(name, 7)] +end +row "bg", [hot { o.bg(2) }, o.bg(2) { |v| v * 5 }] +inc, get = o.kept(10) +row "kept", [inc.(), inc.(), get.(), hot { o.kept(1)[0].call }] +row "super in lambda", [hot { LSub.new.ret(4) }] +row "defined_yield with block", [o.defined_yield(1) { }] +row "rare hit", [o.rare(2_000_000)] +ths = 4.times.map { |t| Thread.new { r = nil; 500.times { r = [o.many(t), o.kept(t)[0].call, o.ret_in_loop(t)] }; r } } +row "threads", ths.map(&:value) +def deep(n) = n == 0 ? -> { :bottom } : ->(l) { l }.call(deep(n - 1)) +row "recursion", [deep(50).call] +o = LC.new +%i[ret nxt brk ret_in_block ret_in_loop arity_err opt bind lv slf sets curry meta from_proc rare rare_hit many nested + call_with_block raise_in to_proc_lam super_like defined_yield].each do |name| + row "c.#{name}", [hot { o.send(name, 3) }, o.send(name, 7)] +end +row "c.bg", [hot { o.bg(2) }, o.bg(2) { |v| v * 5 }] +cinc, cget = o.kept(10) +row "c.kept", [cinc.(), cinc.(), cget.(), hot { o.kept(1)[0].call }] +row "c.super in lambda", [hot { LCSub.new.ret(4) }] +row "c.defined_yield with block", [o.defined_yield(1) { }] +row "c.rare hit", [o.rare(2_000_000)] +cths = 4.times.map { |t| Thread.new { r = nil; 500.times { r = [o.many(t), o.kept(t)[0].call, o.ret_in_loop(t)] }; r } } +row "c.threads", cths.map(&:value) +def cdeep(n) = n == 0 ? -> { :bottom } : ->(l) { l }.call(cdeep(n - 1)) +row "c.recursion", [cdeep(50).call] +row "c.branch not taken", %i[ret nxt brk ret_in_block ret_in_loop bind sets many kept].map { |n| hot { LC.new.send(n, nil) } } +puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 369d4dc93..a86fb2b58 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1907,6 +1907,39 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/lightlambda (2026-11-28) - a lambda literal in a branch no longer keeps its method out of light frames** - not + gated. Chosen by the census of 50b07b5 + 8092170: LambdaDefinition, 73 methods, the next light-frame refusal after + the `$~` family. + - Why it had the scope: no reason but the filter's - `IsScopeFree` had no case for a LambdaDefinition (`->(x) { }`; + `lambda { }` is a call with a literal block, light already). A lambda literal is a literal block made into a lambda + (BlockDefinition.Transform: InstantiateLambda / DefineLambda over the scope variable, which the rewriter makes the + scope made on demand when the body has literal blocks), so it is made as a block literal's Proc is. Its `return`, + `next` and `break` leave the lambda (its own frame's LambdaUnwinder filter), not the method's frame; its arity is + the lambda's; kept past the return, it holds the scope it was made over, made by then. + - Measured first, with every lambda literal let in (`Util/bench/lambda-shapes.rb`, callgrind, off / on): a method + whose lambda is made on no call (`rare`) 2,572 / 2,161 (0.840), on one call in eight (`branch`) 2,902 / 2,615 + (0.901), but on every call (`always`, called there) 3,594 / 3,746 (1.042) and returned (`kept`) 3,697 / 3,820 + (1.033): the scope is made either way, later and dearer - the literal-block story. So only a lambda the method + does not make on every call lets it in (`HasUnconditionalLambda`): not one in a statement of the body or its ensure + clause, a condition, the left of `&&`, `||`, `||=`, a `case` value or a loop body; one in the body of an `if`, + `unless`, `when` or `else`, either side of `?:`, the right of `&&`, `||`, `||=`, or a rescue clause does. Switch: + `IR_LIGHT_LAMBDA=0`. + - Census (Src/StdLib + AWFY, 28,377 methods): light frames 27,291 -> 27,310 (+19), none down, the JIT's counts + unchanged. 47 methods stay out as "LambdaDefinition made on every call" (+61 if they were let in, at 1.03-1.04). + - Instructions as built (callgrind, off / on): rare 0.846, branch 0.901, always and kept 1.000 (refused), size + 1.001. Time (`ab.rb -r 10`, load about 1): rare 0.66, branch 0.64, always 0.98, kept 1.10, size 0.75 - all + overlapping (spreads 16-85% on shapes of a few ns), so the clock says nothing here. + - Checks: the new `Util/light-lambda-matrix.rb` (return, next and break in a lambda, return from a block in a lambda + and from a lambda in a loop, a lambda kept past its method and called after, arity errors, optional/rest/keyword/ + block parameters, binding, eval and local_variables in a lambda, self, `__method__`, block_given?, yield and + `defined?(yield)` in one, super in one, curry, arity, parameters, lambda?, `lambda(&proc)`, a lambda made only on a + rare path, lambdas made in a loop, nested, `&->(){}`, raise, threads, recursion; each method on every path and in a + branch, the branch taken and not), light-entry, hot-shapes, block-pass and jit: CRuby's output in the six gate + modes and with the switch off, on both trees (35 same). ruby/spec language/lambda, core/proc, core/kernel/lambda: + 334 examples, no failures on either. IronRuby.Tests (Debug): the new Method_LightFrameLambda1 and 164 tests named + for blocks, lambdas, procs, closures, yield, return, break and next pass with the switch on and off; the whole + suite was refused by the session's permission check and not run. + - **perf/sinkcarrier (2026-11-28) - the frame's own sink carries a match sink's `$~`: `IR_LIGHT_MATCH_SINK` on by default (gap 16, the `$~` family)** - not gated. perf/lightmatch (below) was sound but off: its hand-over (a stack of sink scopes per thread, entered, left and taken on every call, with a fault block in the rule) cost about what From 67940bddd1a13dbdd761bb14199c19ac47d6528c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:48:07 +0000 Subject: [PATCH 267/439] Kernel#String converts a plain object by its #to_s from C# String(5), String(nil) and String(:sym) took about 1 us against CRuby's 120-210 ns. Everything that was not a String went to the prelude's __ir_string__, which asks what MRI's rb_check_funcall asks the long way round: #respond_to?(:to_str), method(:respond_to?).owner (a Method object per call), Kernel#respond_to? through bind_call, then #to_s through __send__. __ir_plain_to_s__ (KernelOps) answers what rb_String does in C for an object whose class has no #to_str in any visibility, the built-in #respond_to? and #respond_to_missing?, BasicObject's #method_missing and a public #to_s: rb_check_string_type then finds nothing to call, and rb_convert_type calls #to_s. The class's answer is kept per class against the global method version, as IListOps.IsBuiltinMethod's is; #to_s is called through a call site, so a class's own #to_s, a redefined Integer#to_s and a singleton #to_s are what is called, and, as in MRI, no refinement is seen. A #to_s that gives something other than a String is the TypeError rb_convert_type raises; anything else answers nil and goes to __ir_string__ unchanged, nothing called yet. IR_PLAIN_TO_S=0 turns it off. The message for a #to_s or #to_str that gives nil, true or false now names its class, as MRI's conversion_mismatch does: "can't convert X to String (X#to_s gives NilClass)", where it said "gives nil" - in both paths. Clock (Util/perf/ab.rb, four rounds, ns, CRuby / unchanged / this): String(5) 181 / 1036 / 147, String(nil) 124 / 912 / 119, String(:sym) 213 / 1048 / 151, String(1.5) 380 / 1199 / 300, String("a") 41 / 104 / 99. Two rows are new in core-small.rb. Util/kernel-string-matrix.rb (new: Strings and their subclasses, nil, true, false, Integers, Bignums, Floats, NaN, Symbols, Rationals, Arrays, Hashes, Structs, classes, main; to_str first, to_str nil then to_s, to_str and to_s giving an Integer, nil, true, false, a Symbol or a String subclass; private and protected to_str and to_s, no to_s, respond_to? saying no or yes, respond_to_missing?, method_missing, to_s raising and called once, anonymous classes, singleton to_s and to_str; BasicObjects; Integer#to_s, NilClass#to_s and TrueClass#to_s redefined, Symbol#to_str defined, Float#respond_to? and Integer#method_missing defined, to_str, private to_s and a module added after a first call; Kernel.String, method(:String), arity, threads, backtrace; refined to_s): five lines move to CRuby's output (the messages) and none away; the four left (a private to_str and a method_missing for to_str, which MRI calls; Rational's, Complex's and main's #to_s encodings) are as before. The same by default, IR_PLAIN_TO_S=0, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. numeric-conversion, coerce, io-conversion, string-methods, caller and hot-shapes print what they did in those modes, callable-parameters too but for a prelude line number. ruby/spec core/kernel (String_spec, Integer_spec and Float_spec among its 118 files): the same examples on both builds. IronRuby.Tests: the 36 tests that call String() or check conversion messages pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/Libraries/Builtins/KernelOps.cs | 66 +++++++++ Src/StdLib/ironruby/ruby4.rb | 10 +- Util/bench/core-small.rb | 4 + Util/kernel-string-matrix.rb | 212 ++++++++++++++++++++++++++++ 4 files changed, 289 insertions(+), 3 deletions(-) create mode 100644 Util/kernel-string-matrix.rb diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index c2b23af81..528069500 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1757,6 +1757,72 @@ public static bool RespondsTo(ConversionStorage/*!*/ stringCast, Respond Protocols.IsTrue(respondToSite.Target(respondToSite, obj, methodName)); } + // IR_PLAIN_TO_S=0 sends every Kernel#String through the prelude's __ir_string__. + private static readonly bool _plainToS = Environment.GetEnvironmentVariable("IR_PLAIN_TO_S") != "0"; + + // Per class, held weakly, as IListOps.IsBuiltinMethod's: the method version at which the class was last found to + // convert plainly (see IsPlainToSClass). A class is not kept alive by having been asked about. + private static readonly ConditionalWeakTable>/*!*/ _plainToSClasses = + new ConditionalWeakTable>(); + + /// + /// Kernel#String's common case, what MRI's rb_String does in C for an object whose class has no #to_str: with the + /// built-in #respond_to? and #respond_to_missing?, rb_check_string_type finds nothing to call (rb_check_funcall + /// asks neither, and method_missing is not tried), and rb_convert_type calls the public #to_s. The prelude's + /// __ir_string__ answered the same through respond_to?, method(:respond_to?).owner, bind_call and __send__: 870 ns + /// for String(nil) against MRI's 100. Answers nil - nothing called - for any other class; a #to_s that gives + /// something else than a String is the TypeError rb_convert_type raises. Like MRI's, the call sees no refinement. + /// + [RubyMethod("__ir_plain_to_s__", RubyMethodAttributes.PrivateInstance)] + public static object PlainToS(UnaryOpStorage/*!*/ toSStorage, object self, object obj) { + var context = toSStorage.Context; + if (!_plainToS || !IsPlainToSClass(context, context.GetImmediateClassOf(obj))) { + return null; + } + var site = toSStorage.GetCallSite("to_s"); + object converted = site.Target(site, obj); + if (converted is MutableString) { + return converted; + } + // MRI's conversion_mismatch names the class of what #to_s gave, nil's included ("gives NilClass") + string className = context.GetClassMessageName(obj); + throw RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_s gives {1})", className, + context.GetClassMessageName(converted)); + } + + private static bool IsPlainToSClass(RubyContext/*!*/ context, RubyClass/*!*/ cls) { + int version = RubyModule.GlobalMethodVersion; + StrongBox check; + if (_plainToSClasses.TryGetValue(cls, out check) && Volatile.Read(ref check.Value) == version) { + return true; + } + // to_str in any visibility: rb_check_funcall calls a private one too + // to_str in any visibility: rb_check_funcall calls a private one too; and a method_missing of the class's own is + // asked for to_str when the method is not there (check_funcall_missing) + if (cls.GetMethodLookup("to_str").Found || + !IsKernelLibraryMethod(context, cls, "respond_to?") || !IsKernelLibraryMethod(context, cls, "respond_to_missing?") || + !IsBuiltinMethodMissing(context, cls)) { + return false; + } + var toS = cls.GetMethodLookup("to_s"); + if (!toS.Found || toS.Info.IsNotImplemented || toS.Visibility != RubyMethodVisibility.Public) { + return false; + } + _plainToSClasses.AddOrUpdate(cls, new StrongBox(version)); + return true; + } + + private static bool IsBuiltinMethodMissing(RubyContext/*!*/ context, RubyClass/*!*/ cls) { + var method = cls.GetMethodLookup("method_missing"); + return method.Found && method.Info is RubyLibraryMethodInfo && + (ReferenceEquals(method.Info.DeclaringModule, context.BasicObjectClass) || ReferenceEquals(method.Info.DeclaringModule, context.KernelModule)); + } + + private static bool IsKernelLibraryMethod(RubyContext/*!*/ context, RubyClass/*!*/ cls, string/*!*/ name) { + var method = cls.GetMethodLookup(name); + return method.Found && method.Info is RubyLibraryMethodInfo && ReferenceEquals(method.Info.DeclaringModule, context.KernelModule); + } + private static RubyMethodVisibility GetDefinedVisibility(RubyClass/*!*/ cls, string/*!*/ name) { var method = cls.GetMethodLookup(name); if (!method.Found) { diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 12bad2c43..259c3902f 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -13553,9 +13553,12 @@ module Kernel # A String is answered here and everything else in __ir_string__: with that body in it - # a rescue, a singleton class, a dozen locals - this method made a scope on every call, # 220 ns for String("a") where CRuby takes 40. + # A String is itself; an object whose class has no #to_str and the built-in #respond_to? and + # #respond_to_missing? is converted by its #to_s from C# (__ir_plain_to_s__, nil for any other); + # the rest by __ir_string__, which asks what MRI's rb_check_funcall asks. def String(object) return object if ::String === object - __ir_string__(object) + __ir_plain_to_s__(object) || __ir_string__(object) end module_function :String @@ -13568,7 +13571,7 @@ def __ir_string__(object) # rb_check_string_type: nil means "no conversion" and #to_s is tried; anything else is wrong unless converted.nil? ::Kernel.raise(::TypeError, - "can't convert #{object.class} to String (#{object.class}#to_str gives #{__ir_conversion_result_name__(converted)})") + "can't convert #{object.class} to String (#{object.class}#to_str gives #{__ir_message_type_name__(converted)})") end end # rb_check_funcall: a user-defined respond_to? can veto the call; otherwise a missing @@ -13587,9 +13590,10 @@ def __ir_string__(object) ::Kernel.raise(::TypeError, no_conversion) end end + # MRI's conversion_mismatch names the class of what the method gave, nil's included ("gives NilClass") unless converted.is_a?(::String) ::Kernel.raise(::TypeError, - "can't convert #{object.class} to String (#{object.class}#to_s gives #{__ir_conversion_result_name__(converted)})") + "can't convert #{object.class} to String (#{object.class}#to_s gives #{__ir_message_type_name__(converted)})") end converted end diff --git a/Util/bench/core-small.rb b/Util/bench/core-small.rb index a04df55ed..f1e45ffaf 100644 --- a/Util/bench/core-small.rb +++ b/Util/bench/core-small.rb @@ -108,6 +108,8 @@ def m92; @h.flat_map { |k, v| [v] }.size; end def m93; @h.group_by { |k, v| v & 1 }.size; end def m94; @h.each_with_object([]) { |(k, v), a| a << v }.size; end def m95; @h.uniq { |k, v| v & 1 }.size; end + def m96; String(:sym).size; end + def m97; String(1.5).size; end end def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end # INSTR=1 (Util/perf/ab.rb -i) adds a column: the instructions of a call, from the least of the @@ -221,3 +223,5 @@ def t(name, n) t("hash_group_by", N) { |n| i = 0; s = 0; while i < n; s += h.m93; i += 1; end; s } t("hash_each_w_obj", N) { |n| i = 0; s = 0; while i < n; s += h.m94; i += 1; end; s } t("hash_uniq", N) { |n| i = 0; s = 0; while i < n; s += h.m95; i += 1; end; s } +t("String(sym)", N) { |n| i = 0; s = 0; while i < n; s += h.m96; i += 1; end; s } +t("String(float)", N) { |n| i = 0; s = 0; while i < n; s += h.m97; i += 1; end; s } diff --git a/Util/kernel-string-matrix.rb b/Util/kernel-string-matrix.rb new file mode 100644 index 000000000..3ea77281f --- /dev/null +++ b/Util/kernel-string-matrix.rb @@ -0,0 +1,212 @@ +# Differential matrix for Kernel#String (rb_String: rb_check_string_type, then #to_s through rb_convert_type): +# which conversion it calls, what it answers, the errors and their messages. A receiver whose class has no #to_str +# and the built-in #respond_to? and #respond_to_missing? is converted by its #to_s from C# (__ir_plain_to_s__, +# IR_PLAIN_TO_S); everything else by the prelude's __ir_string__. Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/kernel-string-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/kernel-string-matrix.rb > /tmp/on.txt 2>&1 +# IR_PLAIN_TO_S=0 ./ir.sh Util/kernel-string-matrix.rb > /tmp/off.txt 2>&1 +# diff /tmp/mri.txt /tmp/on.txt && diff /tmp/mri.txt /tmp/off.txt + +def t(label) + print label.ljust(48), ' => ' + begin + puts yield.inspect.gsub(/0x\h+/, '0x') + rescue Exception => e + puts "#{e.class}: #{e.message.gsub(/0x\h+/, '0x')}" + end +end + +def r(x) + s = String(x) + [s, s.class, s.frozen?, s.encoding.to_s, s.equal?(x)] +end + +# ---------------------------------------------------------------- 1. the common receivers +class SubString < String; end +Point = Struct.new(:x) +t('a String') { r("s") } +t('a frozen String') { r("f".freeze) } +t('a String subclass') { r(SubString.new("u")) } +t('a binary String') { r("\xff".b) } +t('nil') { r(nil) } +t('nil twice, the same object') { String(nil).equal?(String(nil)) } +t('true, false') { [r(true), r(false)] } +t('an Integer') { r(5) } +t('a negative Integer, 0') { [r(-12), r(0)] } +t('a Bignum') { r(2**70) } +t('a Float') { [r(1.5), r(1e20), r(-0.0), r(1.0 / 3)] } +t('NaN, Infinity') { [r(Float::NAN), r(-Float::INFINITY)] } +t('a Symbol') { r(:sym) } +t('a Symbol twice, new Strings') { String(:s).equal?(String(:s)) } +t('an operator Symbol') { r(:+) } +t('a Rational, a Complex') { [r(3r), r(1i)] } +t('an Array') { r([1, "a", nil]) } +t('a Hash') { r({ a: 1 }) } +t('a Range') { r(1..2) } +t('a Struct') { r(Point.new(1)) } +t('a Class, a Module') { [r(Integer), r(Kernel)] } +t('an Object') { String(Object.new).sub(/0x\h+/, '') } +t('a Proc') { String(proc {}).sub(/0x\h+ .*>/, '>') } +t('an Encoding, a Regexp') { [r(Encoding::UTF_8), r(/a/i)] } +t('main') { r(self) } + +# ---------------------------------------------------------------- 2. #to_str and #to_s of a class of its own +class ToStr; def to_str = "via to_str"; def to_s = "via to_s"; end +class ToStrNil; def to_str = nil; def to_s = "to_s after nil"; end +class ToStrBad; def to_str = 5; end +class ToStrPrivate; private def to_str = "private to_str"; end +class ToS; def to_s = "plain"; end +class ToSPrivate; private def to_s = "private to_s"; end +class ToSProtected; protected def to_s = "protected to_s"; end +class ToSInt; def to_s = 5; end +class ToSNil; def to_s = nil; end +class ToSFalse; def to_s = false; end +class ToSSym; def to_s = :sym; end +class ToSSub; def to_s = SubString.new("sub"); end +class NoToS; undef_method :to_s; end +class RespondNo; def respond_to?(m, priv = false) = m == :to_s ? false : super; end +class RespondYes; def respond_to?(m, priv = false) = m == :to_str ? true : super; def method_missing(m, *a) = m == :to_str ? "mm to_str" : super; end +class MissingToStr; def respond_to_missing?(m, priv = false) = m == :to_str || super; def method_missing(m, *a) = m == :to_str ? "rtm to_str" : super; end +class OnlyMissing; def method_missing(m, *a) = m == :to_str ? "mm only" : super; end +class MissingToS; undef_method :to_s; def method_missing(m, *a) = m == :to_s ? "mm to_s" : super; end +class RaisingToS; def to_s = raise(ArgumentError, "from to_s"); end +class CountToS; attr_reader :n; def to_s = (@n = (@n || 0) + 1; 7); end +Anon = Class.new { def to_s = 5 } + +t('to_str first') { r(ToStr.new) } +t('to_str nil, then to_s') { r(ToStrNil.new) } +t('to_str an Integer') { String(ToStrBad.new) } +t('a private to_str') { r(ToStrPrivate.new) } +t('a to_s of its own') { r(ToS.new) } +t('a private to_s') { r(ToSPrivate.new) } +t('a protected to_s') { r(ToSProtected.new) } +t('to_s an Integer') { String(ToSInt.new) } +t('to_s nil') { String(ToSNil.new) } +t('to_s false') { String(ToSFalse.new) } +t('to_s a Symbol') { String(ToSSym.new) } +t('to_s a String subclass') { r(ToSSub.new) } +t('no to_s') { String(NoToS.new) } +t('respond_to? says no to to_s') { String(RespondNo.new) } +t('respond_to? says yes to to_str') { String(RespondYes.new) } +t('respond_to_missing? and method_missing') { String(MissingToStr.new) } +t('method_missing only') { String(OnlyMissing.new).sub(/0x\h+/, '') } +t('method_missing for to_s') { String(MissingToS.new) } +t('to_s raises') { String(RaisingToS.new) } +t('to_s is called once') { c = CountToS.new; begin; String(c); rescue TypeError; end; c.n } +t('an anonymous class, to_s an Integer') { String(Anon.new) } +t('a singleton to_s') { o = Object.new; def o.to_s = "single"; r(o) } +t('a singleton to_str') { o = Object.new; def o.to_str = "single str"; r(o) } + +# ---------------------------------------------------------------- 3. BasicObject +class BasicToS < BasicObject; def to_s = "basic"; end +class BasicMissing < BasicObject; def method_missing(m, *a) = m == :to_s ? "bm" : super; end +t('a BasicObject') { String(BasicObject.new) } +t('a BasicObject with to_s') { String(BasicToS.new) } +t('a BasicObject with method_missing') { String(BasicMissing.new) } + +# ---------------------------------------------------------------- 4. the core classes changed, and back +t('Integer#to_s redefined') do + class Integer; alias __saved_to_s__ to_s; def to_s(*) = "int!"; end + begin + [String(5), String(2**70)] + ensure + class Integer; alias to_s __saved_to_s__; remove_method :__saved_to_s__; end + end +end +t('restored') { [String(5), String(2**70)] } +t('NilClass#to_s redefined to an Integer') do + class NilClass; alias __saved_to_s__ to_s; def to_s = 0; end + begin + String(nil) + ensure + class NilClass; alias to_s __saved_to_s__; remove_method :__saved_to_s__; end + end +end +t('Symbol#to_str defined') do + class Symbol; def to_str = "sym str"; end + begin + r(:q) + ensure + class Symbol; remove_method :to_str; end + end +end +t('Float#respond_to? redefined') do + class Float; def respond_to?(m, priv = false) = m == :to_s ? false : super; end + begin + String(1.5) + ensure + class Float; remove_method :respond_to?; end + end +end +t('Integer#respond_to_missing? and method_missing') do + class Integer + def respond_to_missing?(m, priv = false) = m == :to_str || super + def method_missing(m, *a) = m == :to_str ? "int str" : super + end + begin + String(9) + ensure + class Integer; remove_method :respond_to_missing?, :method_missing; end + end +end +t('to_str added after a first call') do + k = Class.new { def to_s = "s1" } + o = k.new + first = String(o) + k.define_method(:to_str) { "now to_str" } + [first, String(o)] +end +t('to_s made private after a first call') do + k = Class.new { def to_s = "s2" } + o = k.new + first = String(o) + k.send(:private, :to_s) + [first, String(o)] +end +t('a module with to_str included later') do + k = Class.new { def to_s = "s3" } + o = k.new + first = String(o) + k.include(Module.new { def to_str = "mod str" }) + [first, String(o)] +end + +# ---------------------------------------------------------------- 5. the method +t('Kernel.String, method(:String)') { [Kernel.String(5), method(:String).call(:a), Kernel.method(:String).call(nil)] } +t('arity, owner, parameters') { m = Kernel.instance_method(:String); [m.arity, m.owner, m.parameters.map(&:first)] } +t('String()') { String() } +t('String(1, 2)') { String(1, 2) } +t('from a thread') { 4.times.map { |i| Thread.new { String(i) } }.map(&:value) } +t('backtrace from to_s') do + String(RaisingToS.new) +rescue => e + e.backtrace_locations.first(3).map(&:label) +end + +# ---------------------------------------------------------------- 6. a refinement of #to_s is not seen (rb_String calls it from C) +module RefineToS + refine Integer do + def to_s(*) = "refined" + end + refine ToS do + def to_s = "refined ToS" + end +end +using RefineToS +t('a refined Integer#to_s') { [String(5), 5.to_s] } +t('a refined to_s of a class of its own') { String(ToS.new) } +class ToStrTrue; def to_str = true; end +class ToSTrue; def to_s = true; end +class ToStrNilToSNil; def to_str = nil; def to_s = nil; end +t('to_str true') { String(ToStrTrue.new) } +t('to_s true') { String(ToSTrue.new) } +t('to_str nil, then to_s nil') { String(ToStrNilToSNil.new) } +t('TrueClass#to_s redefined to an Integer') do + class TrueClass; alias __saved_to_s__ to_s; def to_s = 0; end + begin + String(true) + ensure + class TrueClass; alias to_s __saved_to_s__; remove_method :__saved_to_s__; end + end +end From 51f5637c8459ff8741fbc3e8979df2b83db90750 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:48:07 +0000 Subject: [PATCH 268/439] Ledger: perf/kstring landed (clock only, not gated); gap 15: String() done Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 55875f91f..5c0c6fc39 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1080,10 +1080,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `String#strip`/`lstrip`/`rstrip` cost 145 ns over the C# method they wrap. `inject` and `reduce` are done (2.0 -> 1.3, `inject(:+)` 6.7 -> 4.0), and so is `Array#dig` (15.1 -> 6.1, see Landed), and `Array#sum` with a block (6.5 -> 3.3), and `String("a")` - (5.2 -> 2.4). Next: `String(5)`, `String(nil)` - about 1.6 us each against CRuby's 180, - in `Kernel#__ir_string__`, which asks whether #respond_to? is Kernel's - (`method(:respond_to?).owner`) and calls #to_s through `bind_call`; CRuby decides that in - C (rb_check_funcall). Probably needs a C# helper, which is /perf-step's, not /perf-core's. + (5.2 -> 2.4). `String(5)`, `String(nil)`, `String(:sym)` are done too (perf/kstring, see + Landed: about 1 us -> 120-150 ns, under CRuby's), by a C# helper for a class with no + #to_str and the built-in respond_to?, respond_to_missing? and method_missing. `Hash#sort_by` (2.4 -> 1.9), `Range#sort_by` (2.9 -> 2.3) and `Hash#max_by(2)` (3.1 -> 2.6) are done too (perf/hsortby, see Landed). Survey of 2026-11-27 (one round): the Ruby rows above 4x CRuby are `Array#dig` into a Hash (9.2), `String(nil)`/`String(5)` (8.8, 6.7), @@ -1901,6 +1900,21 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kstring (/perf-step, 2026-11-28, on 3faf3dc) - `Kernel#String` converts a plain object + by its #to_s from C# (`__ir_plain_to_s__`, `IR_PLAIN_TO_S`)** - clock only, not gated. For a + class with no #to_str (any visibility), the built-in respond_to?, respond_to_missing? and + method_missing and a public #to_s - checked per class against the global method version - + #to_s is called through a call site; anything else goes to `__ir_string__` as before. + `String(5)` 1036 -> 147 ns (CRuby 181), `String(nil)` 912 -> 119 (124), `String(:sym)` 1048 -> + 151 (213), `String(1.5)` 1199 -> 300 (380). The to_s/to_str TypeError for nil, true or false + now names the class ("gives NilClass"), as MRI's conversion_mismatch. + - `Util/kernel-string-matrix.rb` (new): five lines to CRuby's, none away, in five modes, R2R + and with the switch off; numeric-conversion, coerce, io-conversion, string-methods, caller, + hot-shapes unchanged; ruby/spec core/kernel the same examples; 36 IronRuby.Tests pass. + - Left from CRuby (as before): a private #to_str and a #method_missing for to_str are not + called by __ir_string__ (MRI's rb_check_funcall calls both). `Integer()` (3.5x) is a + String parse, already C# with direct overloads - not this shape. + - **perf/hashany (/perf-step, 2026-11-28, on 540bdb0 + e9a8a9e) - `Hash#any?` is Hash's own (rb_hash_any_p); `group_by`, `uniq`, `each_with_object` walk a plain Hash with a one-value block** - clock only, not gated. `Hash#any? { |k, v| }` 695 -> 403 ns (CRuby 228; 0.58), From 85acffca5893940682e5e4e9a026dbcd72d2ed64 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:57:16 +0000 Subject: [PATCH 269/439] Kernel#String asks for #to_str as rb_check_funcall does __ir_string__ asked object.respond_to?(:to_str) and called #to_str publicly, so String() of an object with a private or protected #to_str, or with a #method_missing that answers to_str, went straight to #to_s; and a private #respond_to? of the object's own was a NoMethodError. MRI's rb_check_string_type asks rb_check_funcall: a #respond_to? of the object's own is called whatever its visibility (with priv = true) and vetoes the call; otherwise #to_str in any visibility is called; otherwise a #method_missing of the object's own is tried (check_funcall_missing), and any NoMethodError it raises means "no conversion" unless the object answers #to_str by then (check_funcall_failed). __ir_check_to_str__ asks in that order. The #to_s step had the same two faults: its custom #respond_to? is now called with __send__, and its NoMethodError rescue follows check_funcall_failed instead of reading e.receiver, which a NoMethodError made without one cannot answer ("no receiver is available"). Util/kernel-string-matrix.rb gains thirteen probes (method_missing raising NoMethodError for to_str, for another name, an ArgumentError, answering nil or an Integer; private respond_to?; protected to_str; the same for #to_s); ten lines move to CRuby 4.0's output and none away, by default and with IR_PLAIN_TO_S=0. What is left (Rational's, Complex's and main's #to_s encodings) is not String()'s. IronRuby.Tests Kernel_StringCheckFuncall1 (new) has CRuby 4.0's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 37 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 33 ++++++++++++++++++---- Util/kernel-string-matrix.rb | 22 +++++++++++++++ 4 files changed, 88 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index db4473910..72adbb33a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1097,6 +1097,7 @@ public Tests(Driver/*!*/ driver) { Module_CopyInvalidatesConstantLookups1, Kernel_PutsToStdoutWriter1, Prelude_HiddenHelpers1, + Kernel_StringCheckFuncall1, Prelude_HiddenState1, Prelude_HiddenState2, SyntaxError_MessageLocation1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index e6a25d8be..e75b2c2b1 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -4467,6 +4467,43 @@ p sleep(0), sleep(0.001r).class "); } + /// + /// Kernel#String asks for #to_str as MRI's rb_check_funcall does: a private or protected #to_str is called, a + /// #method_missing of the object's own is tried when there is none, and any NoMethodError from it means "no + /// conversion" (check_funcall_failed); a private #respond_to? of the object's own is asked too. + /// + public void Kernel_StringCheckFuncall1() { + TestOutput(@" +require 'ruby4' +class PrivToStr; private def to_str = ""private to_str""; end +class ProtToStr; protected def to_str = ""protected to_str""; end +class MmOnly; def method_missing(m, *a) = m == :to_str ? ""mm to_str"" : super; end +class MmNil; def method_missing(m, *a) = m == :to_str ? nil : super; def to_s = ""to_s after nil""; end +class MmInt; def method_missing(m, *a) = m == :to_str ? 3 : super; end +class MmNoMethod; def method_missing(m, *a) = m == :to_str ? raise(NoMethodError.new(""x"", :other)) : super; def to_s = ""to_s after NoMethodError""; end +class MmArg; def method_missing(m, *a) = m == :to_str ? raise(ArgumentError, ""from method_missing"") : super; end +class PrivRespond; private def respond_to?(m, priv = false) = m == :to_str; def method_missing(m, *a) = m == :to_str ? ""asked privately"" : super; end +class NoToS; undef_method :to_s; def method_missing(m, *a) = m == :to_s ? raise(NoMethodError.new(""y"", :other)) : super; end +[PrivToStr, ProtToStr, MmOnly, MmNil, MmInt, MmNoMethod, MmArg, PrivRespond, NoToS].each do |c| + begin + puts String(c.new) + rescue => e + puts ""#{e.class}: #{e.message}"" + end +end +", @" +private to_str +protected to_str +mm to_str +to_s after nil +TypeError: can't convert MmInt to String (MmInt#to_str gives Integer) +to_s after NoMethodError +ArgumentError: from method_missing +asked privately +TypeError: can't convert NoToS into String +"); + } + /// /// The state the Ruby-written core keeps in @__name__ ivars is not the object's state to Ruby, as /// MRI keeps it in C: a Rational's numerator, a Complex's parts, the errno tables and Process.argv0 diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 177c0c7cf..5b823f3b0 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -13573,8 +13573,8 @@ def String(object) def __ir_string__(object) # a BasicObject has neither respond_to? nor to_s: only its #to_s (through method_missing) can help basic = !(::Kernel === object) - if !basic && object.respond_to?(:to_str) - converted = object.to_str + unless basic + converted = __ir_check_to_str__(object) return converted if converted.is_a?(::String) # rb_check_string_type: nil means "no conversion" and #to_s is tried; anything else is wrong unless converted.nil? @@ -13587,14 +13587,15 @@ def __ir_string__(object) class_name = basic ? (class << object; self; end).superclass : (object.nil? ? 'nil' : object.class) no_conversion = "can't convert #{class_name} into String" custom_respond_to = !basic && !object.method(:respond_to?).owner.equal?(::Kernel) - ::Kernel.raise(::TypeError, no_conversion) if custom_respond_to && !object.respond_to?(:to_s, true) + ::Kernel.raise(::TypeError, no_conversion) if custom_respond_to && !object.__send__(:respond_to?, :to_s, true) if !basic && ::Kernel.instance_method(:respond_to?).bind_call(object, :to_s, true) converted = object.__send__(:to_s) else begin converted = object.__send__(:to_s) - rescue ::NoMethodError => e - ::Kernel.raise if e.name != :to_s || !e.receiver.equal?(object) + rescue ::NoMethodError + # check_funcall_failed: any NoMethodError means "cannot", unless the object answers #to_s by now + ::Kernel.raise if ::Kernel.instance_method(:respond_to?).bind_call(object, :to_s) ::Kernel.raise(::TypeError, no_conversion) end end @@ -13607,6 +13608,28 @@ def __ir_string__(object) end private :__ir_string__ + # #to_str as MRI's rb_check_string_type asks for it (rb_check_funcall): a #respond_to? of the + # object's own is asked, private methods included, and vetoes the call; otherwise #to_str in any + # visibility is called, a private one too; otherwise a #method_missing of the object's own is + # tried (check_funcall_missing), and a NoMethodError from it means "no conversion". + # nil for no conversion, as for a #to_str that answers nil. + def __ir_check_to_str__(object) + unless object.method(:respond_to?).owner.equal?(::Kernel) + return object.__send__(:respond_to?, :to_str, true) ? object.__send__(:to_str) : nil + end + return object.__send__(:to_str) if __ir_responds_to__(object, :to_str) + return nil unless __ir_conversion_callable__(object, :to_str) + begin + object.__send__(:to_str) + rescue ::NoMethodError + # check_funcall_failed: any NoMethodError means "no conversion", unless the object answers + # #to_str by now + ::Kernel.raise if object.respond_to?(:to_str) + nil + end + end + private :__ir_check_to_str__ + # rb_f_puts forwards to $stdout.puts, so a redefined or mocked #puts on $stdout is what # runs (Kernel#print and #p write to it directly instead). It forwards with rb_funcallv, # which does not mind that an object only inherits this private #puts - and then, with diff --git a/Util/kernel-string-matrix.rb b/Util/kernel-string-matrix.rb index 3ea77281f..68c2082c6 100644 --- a/Util/kernel-string-matrix.rb +++ b/Util/kernel-string-matrix.rb @@ -210,3 +210,25 @@ class TrueClass; alias __saved_to_s__ to_s; def to_s = 0; end class TrueClass; alias to_s __saved_to_s__; remove_method :__saved_to_s__; end end end + +# ---------------------------------------------------------------- 7. rb_check_funcall for to_str: a private one, method_missing +class MissingRaises; def method_missing(m, *a) = m == :to_str ? raise(NoMethodError.new("no", :to_str)) : super; def to_s = "after mm"; end +class MissingOther; def method_missing(m, *a) = m == :to_str ? raise(NoMethodError.new("other", :other)) : super; end +class MissingArg; def method_missing(m, *a) = m == :to_str ? raise(ArgumentError, "from mm") : super; end +class MissingNil; def method_missing(m, *a) = m == :to_str ? nil : super; def to_s = "mm nil then to_s"; end +class MissingInt; def method_missing(m, *a) = m == :to_str ? 3 : super; end +class PrivRespond; private def respond_to?(m, priv = false) = m == :to_str; def method_missing(m, *a) = m == :to_str ? "pr" : super; end +class ProtToStr; protected def to_str = "protected to_str"; end +t('method_missing raises NoMethodError for to_str') { String(MissingRaises.new) } +t('method_missing raises NoMethodError for another') { String(MissingOther.new) } +t('method_missing raises ArgumentError') { String(MissingArg.new) } +t('method_missing answers nil') { String(MissingNil.new) } +t('method_missing answers an Integer') { String(MissingInt.new) } +t('a private respond_to?') { String(PrivRespond.new) } +t('a protected to_str') { String(ProtToStr.new) } +class NoToSMissingRaises < BasicObject; def method_missing(m, *a) = m == :to_s ? ::Kernel.raise(::NoMethodError.new("x", :to_s)) : super; end +class NoToSMissingOther; undef_method :to_s; def method_missing(m, *a) = m == :to_s ? raise(NoMethodError.new("y", :other)) : super; end +class PrivRespondToS; undef_method :to_s; private def respond_to?(m, priv = false) = false; end +t('BasicObject, method_missing raises for to_s') { String(NoToSMissingRaises.new) } +t('no to_s, method_missing raises for another') { String(NoToSMissingOther.new) } +t('no to_s, a private respond_to? says no') { String(PrivRespondToS.new) } From 5b98b17fd7a8061414fd6bf43b3a2a7ba83bdf48 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:59:04 +0000 Subject: [PATCH 270/439] Ledger: a typed body for each/map/times with a literal block, screened and rejected The census counts of `MethodCall each' (716 first, 567 alone) and `map' (402, 301) are the screen's first refusal; it never walks the block. Walking the block as a while body moved 2 methods off `never'; letting the block's own locals in too, 87 of 28,377, all to `maybe', none to `compiles'. AWFY's hot iteration is SOM's own Vector#each and each_index; app-shapes changed 2 of 922 methods. The emitter was not written; the code is not kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Util/perf/LEDGER.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 28a8fe04c..88f1b39a5 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -8107,6 +8107,27 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jiteach (2026-11-28) - a typed body that takes `recv.each { }`, `recv.map { }` and `n.times { }` as a + loop: screened, not built.** Chosen from the census of 33818f7 + a22b068, where `MethodCall each` refuses 716 + methods first and `map` 402, with "alone" counts of 567 and 301. Those counts are the screen's first refusal: + it stops at the call and never walks the block, so they say nothing about the block bodies. The step measured + them before writing an emitter. A screen-only change (IR_JIT_EACH; JitScreen.WalkCall walked a literal block of + at most one plain parameter as a `while` body, `break` and bare `next` the loop's) moved 2 methods off `never` + (`HTTPPool#setup_queue`, AWFY's `inner_benchmark_loop`, both `times`). With the block's own locals let in too + (the screen's `DefinitionLexicalDepth == _scopeDepth` tests widened to the blocks' depths), 87 of 28,377: never + 21,724 -> 21,637, every one to `maybe`, none to `compiles`; 3 AWFY methods went the other way (DeltaBlue's + `Variable#remove_constraint`, Havlak's `SimpleLoop#add_node` and `#add_child_loop`, maybe -> never, not + chased). In AWFY the iterators that matter are not these: the benchmarks iterate over SOM's own `Vector#each` + (`each (self)`) and `each_index`, and only `Queens#place_queen` (`times`) and the harness's loop would pass. In + app-shapes' run 2 of the 922 methods it called changed, both to `maybe`. What keeps the rest out is inside the + blocks: ordinary calls the typed body cannot make (it takes operators, attribute reads, type tests and leaf + methods it can inline). An emitter (guarded Array/Integer receiver and unredefined iterator, a loop by index + re-reading the length, `break` with its value, `next`, the map result, block-local variables fresh per + iteration, the backtrace's `block in` and iterator frames, deopt only before the first effect) would serve + about 90 methods at best, so it was not written. Not worth trying again until the typed body can make + general calls; the block loop the generic code already runs in place (BlockLoopSite) is what these + methods have. + - **perf/stagea (round thirty-seven, 2026-11-28) - stage A of `Docs/block-calling-convention.md`, a narrow literal given to a `[BlockNotKept]` iterator as a block descriptor: simulated, not built** (gap 13). Before the matrix or the compiler work, the harness (`IronRuby.Tests /blockcost`, now with bytes per From 44d5286bde8d091cb02a1f37fa383eecebb07987 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:03:33 +0000 Subject: [PATCH 271/439] A call on a later line of a multi-line statement reports its own line MRI reports each call at its own line - that of its name, for a chained `.m` on the next line - in a backtrace, caller, binding and an eval's default file name ("(eval at f.rb:42)"). IronRuby kept a line per statement, so a call on a later line of a statement that spans lines reported the statement's first line: [1,\n eval('__FILE__')].last named line 41, and so did caller from such a call, a raise inside it, and the outer call of a nested call on another line. The bridge now gives a call node the line of its name (prism's message_loc), and the generator tracks the line the frame is at while it transforms (ScopeBuilder.CurrentLine: a statement's, set before its children; the definition's at a method's or block's start; unknown after a statement nested in an expression). A MethodCall whose line differs from a known current line is wrapped in a sequence point and SourceLineMarker for its line before it and for the current line after it (AstGenerator.AddCallLine), so the call it is an argument of reports its own line again. A statement on one line has no such call and gets nothing; nor does a call where the line is unknown. The interpreter maps instructions to sequence points and pays nothing at run time; compiled code stores the line in its frame record, in multi-line statements only. The method JIT and the light frames report the right lines with it (checked hot and with -X:NoJIT and IR_LIGHT_FRAMES=0). IR_CALL_LINES=0 turns it off. Measured by clock against the same merge without the change (ab.rb -r 8, base / new / IR_CALL_LINES=0): frame-cost new/base 0.93-1.09 on every shape, app-shapes json_parse, invoice_build, render, rules, query_aggregate, set, time and pp within 0.96-1.06, the rest (optparse, erb_result, uri, csv_parse, spreads of 70-450% on a loaded machine) overlapping - level within the noise. Backtrace_CallLine1 holds CRuby's output (arguments, chains with the name on a later line, `.` at the end of a line, &., nested calls, blocks, default arguments, a raise, TracePoint :line events unchanged). All matrices, jit and nojit, against the same merge: caller-matrix's eval row now agrees with CRuby 4.0; nothing else moved (string-race, a race of threads without a GVL, differs from run to run). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 160 ++++++++++++++++++ Src/Prism/PrismAstBridge.cs | 12 +- Src/Ruby/Compiler/Ast/BlockDefinition.cs | 3 +- .../Ast/Definitions/MethodDefinition.cs | 3 +- .../Ast/Definitions/ModuleDefinition.cs | 2 +- .../Ast/Expressions/CallExpression.cs | 10 ++ .../Compiler/Ast/Expressions/Expression.cs | 31 +++- .../Compiler/Ast/Expressions/MethodCall.cs | 15 ++ .../Ast/JumpStatements/JumpStatement.cs | 3 +- Src/Ruby/Compiler/Ast/ScopeBuilder.cs | 4 + Src/Ruby/Compiler/AstGenerator.cs | 39 +++++ 12 files changed, 273 insertions(+), 10 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 359a9d7b2..42e21bfab 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1058,6 +1058,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_RedefinedSetBacktrace1, Backtrace_ArityCalleeFrame1, Backtrace_SendHidden1, + Backtrace_CallLine1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index baf09f466..a291b6bf1 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -342,6 +342,166 @@ load file "); } + /// + /// A call on a later line of a statement that spans lines reports its own line, as MRI's does - the line of its + /// name (a chained .m on the next line) - to caller, eval's file name, binding and a backtrace, and the call it is an + /// argument of goes back to its own; :line events are the statements' only. + /// + public void Backtrace_CallLine1() { + TestOutput(@" +require 'ruby4'; def l = caller_locations(1, 1)[0].lineno +def f(*a) = [l, *a] +p [1, + l].last +p f(1, + l) +p f( + l, + 2) +p [3] + .map { l } + .first +x = f(l, + f(l)) +p x +p((l if + true)) +p [l, l, + l] +y = [1, 2].map do |v| + v + l +end +p y +p(f 1, + 2) +p [0].sum( + l) +def k(&) = yield +p k { + l +} +p k { l +} +r = [0] + .map { |_| + l + } +p r +def g(*) = caller_locations(1, 1)[0].lineno +p g(1, + 2) +p g(1, + l) +p g( + 1) +p [1] + .map { 2 } + .then { |*| g } +a = [1] +p a.push(l, + l).then { g } +p g(g( + 1), g) +p(g(1) + + g(2)) +p( + g) +z = g(l, + 2); p z +p eval(""__LINE__"", + nil) +def h = binding +b = [1, + h].last +p b.source_location[1] +class Object; def ln(*) = caller_locations(1, 1)[0].lineno; end +p [1] + .ln +p [1]. + ln +p [1] + .then { 1 } + .ln +p 1 + + 2.ln +x = [1] +x + .ln +p x.ln( + 1) +p(x + .ln(2) + .ln) +p x. + ln.ln +p x&. + ln +p [x.ln, + x + .ln] +def m + x = [1, + l].last + y = [l, + l, + l] + x + y.size +end +lines = [] +tp = TracePoint.new(:line) { |t| lines << t.lineno if t.path == __FILE__ } +tp.enable { m } +p lines +def boom = raise(""x"") +def n + [1, + boom].last +end +begin; n; rescue => e; p e.backtrace_locations.first(2).map(&:lineno); end +def q(a, + b = l) + b +end +p q(1) +", @" +5 +[3, 1, 7] +[3, 9, 2] +12 +[3, 14, [3, 15]] +17 +[19, 19, 20] +[23, 24] +[3, 1, 2] +28 +31 +33 +[37] +41 +43 +45 +49 +52 +53 +111 +58 +59 +1 +63 +69 +71 +74 +77 +80 +84 +86 +88 +[89, 91] +[102, 93, 95, 98] +[104, 107] +111 +"); + } + /// /// Kernel#send and BasicObject#__send__ leave no frame of their own in a backtrace, with a String name too (as with a /// Symbol, whose call the binder makes in place); Kernel#public_send keeps its frame. LEDGER gap 27. diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index acfcda485..3025a81cd 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -806,7 +806,13 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.InterpolatedMatchLastLineNode interpMatchLast: return new RegularExpression(RegexParts(interpMatchLast.Parts, RegexOptions(interpMatchLast)), RegexOptions(interpMatchLast), true, span); - case Pm.CallNode call: return Call(call, span); + case Pm.CallNode call: { + var result = Call(call, span); + if (call.MessageLoc.HasValue && result is CallExpression callExpression && callExpression.Location == span) { + callExpression.MessageLine = Span(call.MessageLoc.Value).Start.Line; + } + return result; + } case Pm.LocalVariableReadNode read: return CurrentScope.ResolveOrAddVariable(read.Name, span); @@ -1834,7 +1840,9 @@ private Expression MergeHash(Expression result, List/*!*/ maplets, bool HasFlag(node, Pm.CallNodeFlags.AttributeWrite) ? AttributeWrite(node, temp, node.Name, span) : new MethodCall(temp, node.Name, - node.Arguments != null ? BuildArguments(node.Arguments) : null, OptionalBlock(node.Block), span), + node.Arguments != null ? BuildArguments(node.Arguments) : null, OptionalBlock(node.Block), span) { + MessageLine = node.MessageLoc.HasValue ? Span(node.MessageLoc.Value).Start.Line : 0 + }, span); } diff --git a/Src/Ruby/Compiler/Ast/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index d9815f0bd..3d543785d 100644 --- a/Src/Ruby/Compiler/Ast/BlockDefinition.cs +++ b/Src/Ruby/Compiler/Ast/BlockDefinition.cs @@ -186,7 +186,8 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St Environment.GetEnvironmentVariable("IR_PARKED_BLOCK_SCOPES") != "0"; private ScopeBuilder/*!*/ DefineLocals(ScopeBuilder/*!*/ parentBuilder) { - return new ScopeBuilder(_definedScope.AllocateClosureSlotsForLocals(0), parentBuilder, _definedScope); + // a block's frame starts at its first line + return new ScopeBuilder(_definedScope.AllocateClosureSlotsForLocals(0), parentBuilder, _definedScope) { CurrentLine = Location.Start.Line }; } internal override MSA.Expression/*!*/ Transform(AstGenerator/*!*/ gen) { diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 33dde4d81..3da011ed3 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -141,7 +141,8 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin // allocate closure slots for locals: int localCount = DefinedScope.AllocateClosureSlotsForLocals(closureIndex); - return new ScopeBuilder(parameters, firstClosureParam, localCount, null, DefinedScope); + // a method's frame starts at its `def' line (CompiledFrameExpression) + return new ScopeBuilder(parameters, firstClosureParam, localCount, null, DefinedScope) { CurrentLine = Location.Start.Line }; } /// diff --git a/Src/Ruby/Compiler/Ast/Definitions/ModuleDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/ModuleDefinition.cs index 2712d6b0a..f58fdc079 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/ModuleDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/ModuleDefinition.cs @@ -85,7 +85,7 @@ private string/*!*/ FrameLabel { } private ScopeBuilder/*!*/ DefineLocals() { - return new ScopeBuilder(DefinedScope.AllocateClosureSlotsForLocals(0), null, DefinedScope); + return new ScopeBuilder(DefinedScope.AllocateClosureSlotsForLocals(0), null, DefinedScope) { CurrentLine = Location.Start.Line }; } internal sealed override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { diff --git a/Src/Ruby/Compiler/Ast/Expressions/CallExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/CallExpression.cs index 2b8af88d3..172631502 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/CallExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/CallExpression.cs @@ -19,6 +19,16 @@ namespace IronRuby.Compiler.Ast { public abstract class CallExpression : Expression { + /// + /// The line of the method's name, where it is not the call's first line (`a\n .b', `a.\n b'): the line MRI + /// reports for the call (prism's message_loc). 0: the call's first line. + /// + internal int MessageLine; + + internal int CallLine { + get { return MessageLine > 0 ? MessageLine : Location.Start.Line; } + } + // null means no parameters, not even empty parenthesis private readonly Arguments _args; private Block _block; diff --git a/Src/Ruby/Compiler/Ast/Expressions/Expression.cs b/Src/Ruby/Compiler/Ast/Expressions/Expression.cs index f14f46b0a..bb101aa7a 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/Expression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/Expression.cs @@ -66,7 +66,27 @@ protected Expression(SourceSpan location) /// Transform as expression (value is read) and mark sequence point. /// internal MSA.Expression/*!*/ TransformReadStep(AstGenerator/*!*/ gen) { - return gen.AddDebugInfo(TransformRead(gen), Location); + EnterLine(gen); + return LeaveLine(gen, gen.AddDebugInfo(TransformRead(gen), Location)); + } + + /// + /// A statement's sequence point makes its first line the frame's before any of its code runs (see + /// AstGenerator.AddCallLine, which compares a call's line with it). + /// + internal void EnterLine(AstGenerator/*!*/ gen) { + if (Location.IsValid) { + gen.CurrentLine = Location.Start.Line; + } + } + + /// + /// After the statement the line is the one its last code left, which a statement nested in an expression (an + /// `if' in an argument) may have changed on some paths only: unknown to whatever follows in the expression. + /// + internal static MSA.Expression/*!*/ LeaveLine(AstGenerator/*!*/ gen, MSA.Expression/*!*/ result) { + gen.CurrentLine = -1; + return result; } /// @@ -84,7 +104,8 @@ protected Expression(SourceSpan location) if (!StackGuard.IsSufficient) { return StackGuard.RunOnFreshStack(() => TransformCondition(gen, positive)); } - return gen.AddDebugInfo(TransformReadBoolean(gen, positive), Location); + EnterLine(gen); + return LeaveLine(gen, gen.AddDebugInfo(TransformReadBoolean(gen, positive), Location)); } @@ -92,13 +113,15 @@ protected Expression(SourceSpan location) /// Transform as statement (value is not read). Marks sequnce point. /// internal virtual MSA.Expression/*!*/ Transform(AstGenerator/*!*/ gen) { - return gen.AddDebugInfo(TransformRead(gen), Location); + EnterLine(gen); + return LeaveLine(gen, gen.AddDebugInfo(TransformRead(gen), Location)); } /// /// Transform and handle the result according to the specified result operation. Marks sequence point. /// internal virtual MSA.Expression/*!*/ TransformResult(AstGenerator/*!*/ gen, ResultOperation resultOperation) { + EnterLine(gen); MSA.Expression resultExpression = TransformRead(gen); MSA.Expression statement; @@ -108,7 +131,7 @@ protected Expression(SourceSpan location) statement = gen.Return(resultExpression); } - return gen.AddDebugInfo(statement, Location); + return LeaveLine(gen, gen.AddDebugInfo(statement, Location)); } // Condition under which the expression is considered "defined?". diff --git a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs index b6e52098b..d1cfaaaee 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs @@ -67,6 +67,21 @@ public MethodCall(Expression target, string/*!*/ methodName, Arguments args, Blo } internal override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { + // MRI reports a call at its own line (that of its name): one on a line the frame is not at - a later line + // of a statement that spans lines - marks its line, and the frame's back after it (AstGenerator.AddCallLine). + // A line the frame may or may not be at (-1, after a nested statement) is left as it is. + int outer = gen.CurrentLine; + int line = CallLine; + if (!AstGenerator.CallLines || outer <= 0 || line == outer || !Location.IsValid) { + return TransformReadCall(gen); + } + gen.CurrentLine = line; + var call = TransformReadCall(gen); + gen.CurrentLine = outer; + return gen.AddCallLine(call, line, outer); + } + + private MSA.Expression/*!*/ TransformReadCall(AstGenerator/*!*/ gen) { var literal = _target as StringLiteral; if (literal != null && _methodName == "freeze" && (Arguments == null || Arguments.IsEmpty) && Block == null) { return literal.TransformReadFrozen(gen); diff --git a/Src/Ruby/Compiler/Ast/JumpStatements/JumpStatement.cs b/Src/Ruby/Compiler/Ast/JumpStatements/JumpStatement.cs index 095f524c3..386b852ea 100644 --- a/Src/Ruby/Compiler/Ast/JumpStatements/JumpStatement.cs +++ b/Src/Ruby/Compiler/Ast/JumpStatements/JumpStatement.cs @@ -42,7 +42,8 @@ public JumpStatement(Arguments arguments, SourceSpan location) // Marks the sequence point like any other statement does, so that caller/backtraces taken // while evaluating `return caller` report the line of the return. internal sealed override MSA.Expression/*!*/ Transform(AstGenerator/*!*/ gen) { - return gen.AddDebugInfo(TransformJump(gen), Location); + EnterLine(gen); + return LeaveLine(gen, gen.AddDebugInfo(TransformJump(gen), Location)); } internal override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { diff --git a/Src/Ruby/Compiler/Ast/ScopeBuilder.cs b/Src/Ruby/Compiler/Ast/ScopeBuilder.cs index ada21ff64..acf152af7 100644 --- a/Src/Ruby/Compiler/Ast/ScopeBuilder.cs +++ b/Src/Ruby/Compiler/Ast/ScopeBuilder.cs @@ -43,6 +43,10 @@ internal sealed class ScopeBuilder { // How many ensure clauses of this scope the statements being transformed are in (see SourceLineMarker.InEnsure). internal int EnsureDepth; + // The line the frame reports at the point being transformed: the last statement's, or a call's within a statement + // that spans lines (AstGenerator.AddCallLine); -1 when control flow has made it unknown. + internal int CurrentLine = -1; + // constant access site cache variables: private MSA.ParameterExpression _csCacheVariable; private MSA.ParameterExpression _csValueVariable; diff --git a/Src/Ruby/Compiler/AstGenerator.cs b/Src/Ruby/Compiler/AstGenerator.cs index fb842a6dd..f19e58834 100644 --- a/Src/Ruby/Compiler/AstGenerator.cs +++ b/Src/Ruby/Compiler/AstGenerator.cs @@ -1261,6 +1261,45 @@ internal MSA.Expression ClearDebugInfo() { return _sequencePointClearance; } + /// + /// IR_CALL_LINES=0: a call on a later line of a statement that spans lines reports the statement's first line, as + /// it used to (see AddCallLine). + /// + internal static readonly bool CallLines = Environment.GetEnvironmentVariable("IR_CALL_LINES") != "0"; + + /// The line the frame reports at the point being transformed (ScopeBuilder.CurrentLine); -1 if unknown. + internal int CurrentLine { + get { return CurrentScope.CurrentLine; } + set { CurrentScope.CurrentLine = value; } + } + + /// + /// A call on a line other than the one the frame is at (a statement that spans lines: `[1,\n eval(s)]'): MRI reports + /// a call at its own line - in its backtrace, caller, binding, an eval's file name - so the frame's line becomes the + /// call's before it and goes back to after it, for the code of the statement that + /// follows on that line (not when that is unknown, -1). A sequence point and a SourceLineMarker each, as a statement + /// has: the interpreter maps its instructions to the sequence points and pays nothing at run time, compiled code + /// stores the line in its frame record. A statement on one line has no call to mark. + /// + internal MSA.Expression/*!*/ AddCallLine(MSA.Expression/*!*/ call, int line, int restoreLine) { + if (_document == null) { + return call; + } + var loop = _currentLoop; + var loopLineVariable = (loop != null && loop.LoopLineScope == CurrentScope) ? loop.LoopLineVariable : null; + bool inEnsure = CurrentScope.EnsureDepth > 0; + var before = Ast.Block(Ast.DebugInfo(_document, line, 1, line, 1), SourceLineMarker.Create(line, loopLineVariable, inEnsure)); + if (restoreLine <= 0) { + return Ast.Block(before, call); + } + var after = Ast.Block(Ast.DebugInfo(_document, restoreLine, 1, restoreLine, 1), SourceLineMarker.Create(restoreLine, loopLineVariable, inEnsure)); + if (call.Type == typeof(void)) { + return Ast.Block(before, call, after); + } + var result = Ast.Variable(call.Type, "#callLine"); + return Ast.Block(new[] { result }, before, Ast.Assign(result, call), after, result); + } + internal MSA.Expression/*!*/ AddDebugInfo(MSA.Expression/*!*/ expression, SourceSpan location) { var loop = _currentLoop; return AddDebugInfo(expression, location, (loop != null && loop.LoopLineScope == CurrentScope) ? loop.LoopLineVariable : null); From 3f23ee3ef12c1f25e9c2d0262c69264420cfeca8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:04:07 +0000 Subject: [PATCH 272/439] Store a ruby2_keywords Hash given to a Struct as it came `Struct.new(:x, :y).new(1, h)', h marked by Hash.ruby2_keywords_hash, stored a copy of h in CRuby's place of h itself. A Hash among the values sends Struct#initialize to the prelude's __struct_initialize_slow__, whose `__struct_initialize__(*args)' is a Ruby splat without `**' and so made the marked hash keywords again (RubyCallFlags.HasRuby2KeywordsSplat) - a copy. MRI's C rb_struct_initialize_m stores the values as they came. The slow path's three stores splat with `**nil', which passes nothing and keeps the list as it is. Checked: new IronRuby.Tests Struct_Ruby2KeywordsHash1 with CRuby 4.0's output (plain, splatted with `**{}', fewer values than members, keyword_init, a re-initialize); core/struct specs and the struct matrices as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 35 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 9 ++++--- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e9d3b231a..a2860a36c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1194,6 +1194,7 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameKeywordRest1, Method_KeywordHashIntoRest1, Method_Ruby2KeywordsExplicitSplat1, + Struct_Ruby2KeywordsHash1, Method_KeywordPrologue1, Method_LightFrameGlobal1, Method_LightFrameLexical1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 27984327b..11ab0ca6b 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8509,6 +8509,41 @@ p y([h]) { |*x, **kk| [x, kk] }, y([h], &-> *x, **kk { [x, kk] }), yk([h]) { |*x "); } + /// + /// A Struct stores a ruby2_keywords Hash given as a member value as it came, as MRI's C rb_struct_initialize_m does: the + /// prelude's slow path splats the values with `**nil' (RubyCallFlags.HasRuby2KeywordsSplat). Expected output from CRuby 4.0. + /// + public void Struct_Ruby2KeywordsHash1() { + TestOutput(@" +require 'ruby4' +h = Hash.ruby2_keywords_hash({k: 1}) +S = Struct.new(:x, :y) +s = S.new(1, h) +p s.y.equal?(h), Hash.ruby2_keywords_hash?(s.y) +s = S.new(*[1, h], **{}) +p s.y.equal?(h), s.to_a +S3 = Struct.new(:x, :y, :z) +s = S3.new(1, h) +p s.y.equal?(h), s.to_a +K = Struct.new(:x, :y, keyword_init: true) +p K.new(x: 1, y: h).y.equal?(h) +s = S.new(1, 2); s.send(:initialize, 3, h) +p s.y.equal?(h) +p S.new(x: 1, y: 2).to_a, S.new({x: 1}).to_a +", @" +true +true +true +[1, {k: 1}] +true +[1, {k: 1}, nil] +true +true +[1, 2] +[{x: 1}, nil] +"); + } + /// /// A method's keyword prologue (PrismAstBridge.LowerKeywords): which error wins when several things are wrong at once, /// and defaults run in order and only for omitted keywords (Util/kw-prologue-matrix.rb). diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index ec062e087..eebaa6a31 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -12540,9 +12540,12 @@ def __struct_initialize_slow__(args, kwargs, keyword_init = nil) # self.class.members, not members: a struct may have a member called "members" names = self.class.members + # The stores splat with `**nil': the values are stored as they came, as MRI's C rb_struct_initialize_m stores them - + # a ruby2_keywords Hash among them too, which a splat without `**' would make keywords (RubyCallFlags. + # HasRuby2KeywordsSplat). # The overwhelmingly common call: one positional value per member. if kwargs.empty? && !keyword_init && args.size == names.size - return __struct_initialize__(*args) + return __struct_initialize__(*args, **nil) end # Since 3.2 a struct built without keyword_init: takes keywords as well as @@ -12577,12 +12580,12 @@ def __struct_initialize_slow__(args, kwargs, keyword_init = nil) # MRI's wording is plural whatever the count raise ArgumentError, "unknown keywords: #{unknown.join(', ')}" end - __struct_initialize__(*values) + __struct_initialize__(*values, **nil) else # pad with nil so that a partial re-initialize clears the remaining members values = args.dup values.concat([nil] * (names.size - values.size)) if values.size < names.size - __struct_initialize__(*values) + __struct_initialize__(*values, **nil) end end private :__struct_initialize_slow__ From d45083a0c161308b71d68609a12497ec5b14d6d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:04:08 +0000 Subject: [PATCH 273/439] Let a light frame make `f(k: v, **h)' and `f(**a, **b)' A `**h' beside other keywords is a KeywordSplatMerge, which IsScopeFree had no case for: the census found 24 methods kept out of light frames by it in Src/StdLib (Pathname#glob, File.binwrite, Exception.__detailed__, mkmf's try_*, optparse's getopts, Prism's desugar compilers, Tempfile.create, Net::IMAP...). Its helpers, RubyOps.MergeKeywordSplat and MergeKeywordHash, take the scope for its runtime only, as the lone `f(**h)''s helpers do, which IR_LIGHT_KEYWORD_SPLAT already lets a light frame call. The node is now scope-free when its parts are (its temporaries are locals, and the `hash.merge(h || {})' that converts anything but a Hash or nil is a call like any other), and the two helpers are among the rewriter's runtime-only ones, both under IR_LIGHT_KEYWORD_SPLAT. Census: 20 more light frames (27,997 -> 28,017 of 29,102), no JIT verdict changed. By clock `g(k: 1, **o)' 419 -> 370 ns, `g(**o, **o)' 429 -> 377 (CRuby 188, 212). New rows in Util/kwsplat-forward-matrix.rb (merged keywords, `**nil' and #to_hash in a merge, non-Symbol keys, keys with a Ruby #hash, deep recursion, errors in a merge's operand) and the keyword, splat, forwarding and struct matrices match CRuby in every mode and with the switch off; specs and IronRuby.Tests as recorded in Util/perf/LEDGER.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- .../Ast/Definitions/MethodDefinition.cs | 15 ++++++- Util/kwsplat-forward-matrix.rb | 28 +++++++++++++ Util/perf/LEDGER.md | 41 +++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 7b95136e0..d05cd139d 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -1494,6 +1494,18 @@ private static bool IsScopeFree(Expression/*!*/ node, bool blockLiterals, Strong if (splat != null) { return (LightSplatEnabled || why != null && Refuse(why, node.GetType().Name + " (IR_LIGHT_SPLAT=0)")) && IsScopeFree(splat.Argument, blockLiterals, why); } + // `f(k: v, **h)', `f(**a, **b)': h's entries go into the call's keyword hash by a helper that takes the scope only + // for its runtime (RubyOps.MergeKeywordSplat, MergeKeywordHash; LightFrameRewriter.ScopeOperandIndex), and + // anything but a Hash or nil through `hash.merge(h || {})', a call like any other; the temporaries are locals + // (IR_LIGHT_KEYWORD_SPLAT) + var merge = node as KeywordSplatMerge; + if (merge != null) { + if (!LightKeywordSplatEnabled) { + return Refuse(why, "KeywordSplatMerge (IR_LIGHT_KEYWORD_SPLAT=0)"); + } + return IsScopeFree(merge.Hash, blockLiterals, why) && IsScopeFree(merge.Splatted, blockLiterals, why) && + (merge.Converted == null || IsScopeFree(merge.Converted, blockLiterals, why)); + } // `super', `super(a, *r)', `super(&b)': the site is given the module and the name the body was compiled for, // which is what it read from the scope, and self (LightFrameRewriter.LightScopeCall); a parameterless super // passes the parameters, which are locals, and the method's block, which the frame then converts as a method's @@ -1963,7 +1975,8 @@ private static int ScopeOperandIndex(MethodInfo/*!*/ method) { // one-or-zero element array for a splatted call, or the call's own keyword hash passed on by a parameterless // `super' (IR_LIGHT_KEYWORD_SPLAT) if (LightKeywordSplatEnabled && (method == Methods.SplatKeywordHash || method == Methods.SplatKeywordHashIfHash || - method == Methods.KeywordSplatArgument || method == Methods.PassOnKeywordRest)) { + method == Methods.KeywordSplatArgument || method == Methods.PassOnKeywordRest || + method == Methods.MergeKeywordSplat || method == Methods.MergeKeywordHash)) { return 0; } if (LightKeywordsEnabled && (method == Methods.GetOmittedKeywordArguments || method == Methods.MakeOmittedKeywordArguments)) { diff --git a/Util/kwsplat-forward-matrix.rb b/Util/kwsplat-forward-matrix.rb index a15a6b2ff..96d177a3b 100644 --- a/Util/kwsplat-forward-matrix.rb +++ b/Util/kwsplat-forward-matrix.rb @@ -145,3 +145,31 @@ def y_splat_kw(args) = yield(*args, **{}) c = Class.new { attr_reader :v; def initialize(*x, **k) = @v = [x, k] } [method(:kwr).to_proc.call(*a, **e), c.new(*a, **e).v, send(:kwr, *a, **e)] end + +# ---------------------------------------------------------------- 7. keyword splats merged with other keywords, in light frames +# (MethodDefinition.IsScopeFree takes a KeywordSplatMerge; IR_LIGHT_KEYWORD_SPLAT=0 refuses it) +class KeyHash; attr_reader :n; def initialize(n) = @n = n; def hash = @n.hash; def eql?(o) = o.is_a?(KeyHash) && o.n == @n; end +def mg_kw(**o) = kwr(k: 1, **o) +def mg_two(a, **o) = kwr(**o, **a) +def mg_after(**o) = kwr(**o, z: 9) +def mg_lead(x, **o) = kwr(x, k: x, **o) +t("k: 1, **o") { |i| i.even? ? mg_kw(z: i % 3) : mg_kw } +t("k: 1, **o overriding k") { |i| mg_kw(k: 2) } +t("**o, **a") { |i| mg_two({a: 1}, b: 2) } +t("**o, **a, both empty") { |i| mg_two({}) } +t("**o, **nil") { |i| mg_two(nil, b: 2) } +t("**o, z: 9 after") { |i| mg_after(z: 1, y: 2) } +t("positional and merged keywords") { |i| mg_lead(i % 2, q: 1) } +t("merged **obj: to_hash") { |i| log = []; [mg_two(ToHash.new(log, {t: 1}), b: 2), log] } +t("merged **obj: to_hash returning a non-Hash") { |i| (mg_two(BadHash.new, b: 2) rescue [$!.class, $!.message]) } +t("merged **obj with no to_hash") { |i| (mg_two(Object.new) rescue [$!.class]) } +t("merged non-Symbol keys") { |i| mg_two({"s" => 1}) } +t("merged keys with a Ruby #hash") { |i| r = mg_two({KeyHash.new(1) => 1, KeyHash.new(1) => 2}); [r[0], r[1].size, r[1].values] } +t("merged hash's default is not kept") { |i| r = mg_two(Hash.new(5).merge(a: 1)); [r[1].default, r[1].default_proc] } +t("merged frozen hash") { |i| mg_two({a: 1}.freeze, b: 2) } +def mg_deep(n, **o) = n == 0 ? o.size : mg_deep(n - 1, k: n, **o) +t("deep recursion through a merged call") { |i| mg_deep(100, a: 1) } +def mg_raise(**o) = kwr(k: 1, **o.fetch(:h)) +t("error raised inside a merge's operand") { |i| (mg_raise rescue [$!.class, $!.message]) } +# (whether the merging method is in the backtrace: IronRuby's top frame is the Hash#merge #to_hash goes through, MRI's the method) +t("backtrace of an error in a merged call") { |i| begin; mg_two(BadHash.new); rescue TypeError => e; e.backtrace_locations.map(&:label).include?("Object#mg_two"); end } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 56016751d..8843dda72 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1995,6 +1995,47 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kwsplatlight (/perf-frame, 2026-11-28) - `f(k: v, **h)` and `f(**a, **b)` in light frames; + a Struct stores a ruby2_keywords Hash as given** (switch `IR_LIGHT_KEYWORD_SPLAT`, which already + covered the lone `f(**h)`). Built on 33818f7 (claude/happy-gauss-95wm2j) with 78a731ca merged; + RubyCallFlags.HasRuby2KeywordsSplat moved to 8192 (FlagsCount 14) beside round 7's HasMatchSink. + - **Census** (`Util/perf/census.rb -d`, Src/StdLib and Util/bench, 29,102 methods): light frames + 27,997 -> 28,017 (+20), every one refused before for `KeywordSplatMerge` (Pathname#glob, + File.binwrite, Exception.__detailed__, mkmf's try_*, optparse's getopts, Prism's desugar + compilers, Tempfile.create, Net::IMAP...); JIT verdicts unchanged; no method still refused + for it first. + - **Why it was refused.** IsScopeFree had no case for the node the bridge makes of a `**h` + beside other keywords (KeywordSplatMerge), and its helpers (RubyOps.MergeKeywordSplat, + MergeKeywordHash) take the scope - for its runtime only, as the lone splat's helpers do, which + IR_LIGHT_KEYWORD_SPLAT already let through. Now the node is scope-free when its parts are (the + temporaries are locals; the `hash.merge(h || {})` that converts anything but a Hash or nil is + a call like any other), and the two helpers are in the rewriter's runtime-only list. + - **Clock** (`ab.rb -r 8`, Release, ns; CRuby / `IR_LIGHT_KEYWORD_SPLAT=0` / on): `g(k: 1, **o)` + 188 / 419 / 370, with no keywords 153 / 292 / 252, `g(**o, **o)` 212 / 429 / 377, + `g(k: a, **o)` 200 / 424 / 380; `def w(**o) = g(**o)` (light already; the switch turns it + off too) 148 / 344 / 304, empty 160 / 202 / 163. Still twice CRuby: the merge's hash and the + callee's `k:, **o` binding, not the frame. + - **Struct.** `Struct.new(:x, :y).new(1, h)`, h ruby2_keywords-marked: a Hash value goes to + the prelude's __struct_initialize_slow__, whose `__struct_initialize__(*args)` made it + keywords (a copy) - a Ruby splat without `**` (RubyCallFlags.HasRuby2KeywordsSplat). Its three + stores splat with `**nil` now, which passes nothing and leaves the values as they came, as + MRI's C rb_struct_initialize_m does. IronRuby.Tests Struct_Ruby2KeywordsHash1 (CRuby's + output). + - **Not done.** An empty `**e` with a default gives a `**k` callee `{}`; CRuby gives it a dup + of e (default 7), through procs and send too but not Method#call. IronRuby passes nothing for + any empty `**`; matching needs an empty keyword hash that every binder drops for a callee + without `**k` - not a contained change. + - **Checks.** kwsplat-forward (new rows: merged keywords, `**nil` and to_hash in a merge, + non-Symbol keys, keys with a Ruby #hash, deep recursion, errors in a merge's operand), + keyword-light, keyword-rest-light, splat-pass, kwrest-call, anon-forward, block-pass, + light-entry, hot-shapes, struct and hash-struct matrices: same as CRuby in default, + `IR_LIGHT_KEYWORD_SPLAT=0`, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls`, and + `IR_KWSPLAT_BY_REFERENCE=0` but for its known row. A backtrace probe showed IronRuby's top + frame for a #to_hash TypeError in a merge is Hash#merge (CRuby: the method) in every mode, + frames off too - before this change as well; the row checks the method is in the backtrace. + Specs language/keyword_arguments, send, def, super and core/struct as on the base build. + IronRuby.Tests in full (Debug): PASSED, 1,417 tests. + - **perf/r2kflag (2026-11-28) - a ruby2_keywords hash stays positional at a call with an explicit `**`, and at a library method's own call; `yield(*args)` makes it keywords; `**h` passes a dup** (correctness, no switch). Built on aa82bf28 (claude/perf-lsite, which has f67ac44). From c0c3335a7029cb7385504b6957daf56f0097ec50 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:08:51 +0000 Subject: [PATCH 274/439] Ledger: Module#=== with a constant receiver in a typed body, measured and rejected Of the 304 methods `===' refuses first, 141 call it on a constant (the prelude's Complex/Rational helpers, Socket, `C === other' in == methods), 152 on a call (prism's Node#===). Built as perf/jitbody's is_a? is: 39 methods never -> maybe, none to compiles; nothing hot among them (AWFY 0, app-shapes 0 of 922 called, Complex arithmetic unchanged). respond_to?(:lit) counted only: 72 alone, 7 in app-shapes. Not kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Util/perf/LEDGER.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 88f1b39a5..ecc740b73 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -8107,6 +8107,24 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jiteqq (2026-11-28) - `C === x` (Module#===, a constant receiver) in a typed body; `respond_to?(:lit)` + counted: built, census-measured, nothing hot moved, not kept.** From the census of 33818f7 + 5b98b17, where + `MethodCall ===` refuses 304 methods first (426 at all, 170 alone). By receiver (prism over each refused method's + def): 141 methods call `===` on a constant, 152 on a call - almost all prism's generated `Node#===`, comparing + fields (`(name === other.name)`) - 16 on a local, 4 on a Range, 2 on a Regexp literal; `case ... when` adds + 9 methods. The constant ones are the prelude's Complex and Rational helpers (`::Integer === x`, `::Float`, + `::Rational`), Socket's `Addrinfo === addr`, and `==` methods of the form `C === other && ...`. Built as + perf/jitbody's is_a? is (IR_JIT_MODULE_EQQ): JitScreen took `C === x` with C a constant, JitCompiler emitted + `JitRuntime.ModuleCaseCompare` - Module#=== is `IsKindOf(x, C)` (rb_obj_is_kind_of; x's is_a? is not asked) + under a KernelMethodSite on C's class resolving `===` to Module's, deopting otherwise, and declining with + refinements active. Census: 39 methods never -> maybe, none to compiles (most stop at "constant without a + scope", which only a run can fold). Nothing hot among them: AWFY 0 methods changed; app-shapes' run (`census + -u`) 0 of the 922 methods it called; a Complex arithmetic loop (`s + a * b - b`, 300,000 times) the same 52 + screen rejections in both builds - Complex's operators do not reach the helpers that moved on their hot path. + `respond_to?(:lit)` was only counted: the first refusal of 361 methods and the only one of 72, none in AWFY, + 7 among app-shapes' called methods - the same order, not built. Both are what the census can win and the + clock cannot see; worth doing only together with whatever lets the methods around them compile. + - **perf/jiteach (2026-11-28) - a typed body that takes `recv.each { }`, `recv.map { }` and `n.times { }` as a loop: screened, not built.** Chosen from the census of 33818f7 + a22b068, where `MethodCall each` refuses 716 methods first and `map` 402, with "alone" counts of 567 and 301. Those counts are the screen's first refusal: From 744b83e4db50e78aa06f970f444a98036f29f149 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:09:19 +0000 Subject: [PATCH 275/439] Ledger: perf/kinteger - String's to_str as rb_check_funcall; Integer("1234") rejected (1.21x, nothing to win) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 4703e4ae8..170c6ae52 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1994,6 +1994,26 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kinteger (2026-11-28, on 33818f7 + 51f5637) - `Kernel#String` asks for #to_str as + rb_check_funcall does; `Integer("1234")` rejected, nothing to win** - not gated. + - Part 1 (correctness, from perf/kstring's leftovers): `__ir_check_to_str__` calls a private + or protected #to_str, tries a #method_missing of the object's own when there is none + (check_funcall_missing), takes any NoMethodError from it as "no conversion" unless the + object answers #to_str by then (check_funcall_failed), and asks a private #respond_to? of + the object's own; the #to_s step's rescue and respond_to? call likewise (its `e.receiver` + raised for a NoMethodError made without one). Ten lines of `Util/kernel-string-matrix.rb` + move to CRuby's output, none away, in five modes, with `IR_PLAIN_TO_S=0` and R2R; the two + left are Rational's/Complex's and main's #to_s encodings. IronRuby.Tests + `Kernel_StringCheckFuncall1` (new, CRuby's output); ruby/spec core/kernel and + core/string/to_i the same examples on both builds. + - Part 2, rejected before any code: the survey's `Integer()` at 3.5x CRuby was one round's + noise. Four rounds: `Integer("1234")` 71.8 ns against CRuby's 59.5 (1.21x), with `Array(@a)` + - a C# Kernel call that does next to nothing - at 67.5: the parse is about 4 ns over the + call. KernelOps.ToInteger(MutableString) already has its own overload, and TryParseRubyInteger + folds digits into a long; an ASCII decimal fast path has nothing left to take. What is left + of these rows is the cost of calling a Kernel method at all (`String("a")` 108 against 44, + `Array()` 68 against 40). + - **perf/kstring (/perf-step, 2026-11-28, on 3faf3dc) - `Kernel#String` converts a plain object by its #to_s from C# (`__ir_plain_to_s__`, `IR_PLAIN_TO_S`)** - clock only, not gated. For a class with no #to_str (any visibility), the built-in respond_to?, respond_to_missing? and @@ -2005,9 +2025,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - `Util/kernel-string-matrix.rb` (new): five lines to CRuby's, none away, in five modes, R2R and with the switch off; numeric-conversion, coerce, io-conversion, string-methods, caller, hot-shapes unchanged; ruby/spec core/kernel the same examples; 36 IronRuby.Tests pass. - - Left from CRuby (as before): a private #to_str and a #method_missing for to_str are not - called by __ir_string__ (MRI's rb_check_funcall calls both). `Integer()` (3.5x) is a - String parse, already C# with direct overloads - not this shape. + - A private #to_str and a #method_missing for to_str, left at first, are called since + perf/kinteger's first part, as MRI's rb_check_funcall calls them. - **Gate of 2026-11-28 for round 6 of round thirty-seven** (perf/crubydiff's third and fourth rounds, perf/sieve and gap 39's analysis, perf/evallocals, perf/evalscreen, perf/evalboxes, perf/hsortby, From d0a90db9ee39e69280992690b0d1202151bd7317 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:14:26 +0000 Subject: [PATCH 276/439] Ledger: perf/havlakalloc, Havlak's bytes and what is left Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/perf/LEDGER.md | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e6ee8905c..965e5a246 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1358,6 +1358,15 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has effect rule ("a deopt after an effect (call next)": the next iteration's read can deopt after this one's write), and it is called 459 times an iteration against `at`'s 799,304, so it is not worth a body that could take that. + Round forty-one looked at its bytes (see Landed, perf/havlakalloc): of 1.9 GB an + iteration, method scopes 25%, Procs 15%, BlockParams 6% - callers that pass a literal + block to som.rb's `Vector#each`, `has_some` and through them `SomSet#contains`, `add`, + and `UnionFindNode#find_set`, none of which could park its scope because the callee's + scope cleared the caller's Proc's reuse for good. Now 1.44 GB, 0.96 of the time. Left: + `SomSet`'s `def each(&block); @items.each(&block); end` (a named block is a Proc for + good), `Object[]` 20% (the instance-variable slot arrays of new objects and the + Vectors' storage), `Range` 8% (`(a..b).each` makes one per call), and the light + `Vector#each` costs 3-4% more instructions per call than the scope-ful one did. 26. **Start-up: `gem` and `irb` answer in 0.7 to 2.2 s, CRuby in 0.1 to 0.2** (the one thing that has to stay fast while the tiers stay on by default, and it is not fast). 2026-11-18, a7060a27, the ReadyToRun host (`IR_CONFIG=R2R`, what `ir.sh` runs when @@ -1904,6 +1913,48 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/havlakalloc 56526b1 c8010fb (round forty-one, 2026-11-28) - a light frame's scope holds its + block until it is parked, not for good (gap 25)** - not gated. Havlak allocated 1.77 GB per iteration; + the allocation-tick probe gave method scopes 25%, `Object[]` 16%, Procs 14.5%, Range 6%, BlockParams 6%. + Bytes per call of its hot helpers, method by method: a caller passing a literal to som.rb's + `Vector#each` 374 B (its method scope, its Proc, a BlockParam, the Range), `SomSet#contains` 406, + `UnionFindNode#find_set` 462. Every method that `yield`s from inside its own block literal kept its + caller from parking (`IR_PARKED_SCOPES` diagnostics: the caller's staged Proc not reusable): a + light-frame callee that makes its scope cleared its block's ReusableFlag for good + (`CreateMethodScopeLazy`, `ReuseParkedScopeLazy`: "whatever asked for the scope may keep it"). Now + the scope only holds the block (`Proc.HeldFlag`: not reusable while set) and `EndPark` releases it when + it parks the scope - parking proves that nothing captured the scope and that its own Procs are + reusable and inactive, so nothing that outlived the call reaches the block through it. A call that does + not park, an exception, and every other ClearReusable (a captured block scope, a retry) leave the block + not reusable, as before. And `Vector#each`/`has_some`, `(a..b).each { |i| yield @s[i] }`, were kept + out of light frames by `RangeExpression in a body with literal blocks` (measured 5-7% slower per call + as light frames when their callers could not park anyway); with the hold they are let in, so their + callers park. Switch for both: IR_SCOPE_HELD_BLOCKS=0. Census: 130 methods more are light frames (all + by the Range rule), none moved down. + Bytes (alloc.rb against 186fb0e): Havlak 1,774,355,834 -> 1,436,289,102 (0.81), DeltaBlue 14,559,508 + -> 9,697,205 (0.67), Towers 181 -> 146 KB, the rest level (Richards 636-810 KB on the base and + 733-834 on the new in three runs: noise); geomean 0.957. Per call (probe): a caller of `Vector#each` + 374 -> 134 B, `find_set` 462 -> 222, a caller of a light `@a.each { |x| yield x }` 334 -> 94. + Time: ten alternating AWFY processes against the base, medians: Havlak 0.959 (ranges 2.83-3.09 s + and 2.85-3.01 s), DeltaBlue 1.011, CD 1.026 (one outlier of 557 ms in the new; CD's changed methods are + called once per iteration); in one tree with the switch off and on: Havlak 0.964, DeltaBlue 0.995. + Instructions (callgrind, switch off -> on, three runs, steady to 0.1%): per call of the Havlak + helpers `vec_each` +2.8%, `has_some` +4.4%, `contains` +2.7%, `find_set` +3.7% - the light + `Vector#each` costs more per call than the scope-ful one, as measured when it was kept out; the time + saved is the collector's. + Checks: Util/held-block-matrix.rb (new: the callee's binding kept and yielded through later, a Proc of + the callee kept that yields to the caller's block, an exception after the callee's scope is made, a + fiber, threads, block_given?, break; with the hold a no-op three rows go wrong) and the parked-scope, + block-scope-reuse, block-nest-reuse, nested-proc, loop-exit, osr-array, jit, hot-shapes, block-given, + block-pass, binding-lvar, light-entry, loop-light, super-light, rescue-light matrices in the gate's six + modes and IR_SCOPE_HELD_BLOCKS=0: 112 same. ruby/spec language/block, def, yield, break, range, + core/binding, core/proc, core/range/each, core/kernel/block_given: no failures on either build. + IronRuby.Tests on Debug net10.0 (Util/parallel-tests.sh): 1,403 tests, none failed or flaky, as on the + base (both report the driver's "Current culture:" line as a test never run). + For the gate: the per-call instruction rise above, on code that has no use for the parking; every way + a method's block can escape through its scope without capturing it or keeping a Proc of the method + (the hold is released on that proof alone). + - **Gate of 2026-11-27 for round 5 of round thirty-seven** (perf/crubydiff's first two rounds, perf/dupcost, perf/strcow, perf/strswitch, perf/jitstr, perf/jitaref, perf/timeout, perf/forward, perf/jitprobe, perf/twospeed and its note, perf/extiter4 and 5, perf/fiberstart, perf/iter, perf/strsearch3 and 4, From 4405475933bc8cfb80bcb674290306cb22f1d97c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:14:50 +0000 Subject: [PATCH 277/439] Ledger: perf/requirecold landed, not gated (gap 26) Kernel#require's first-call compile already gone with perf/bootparse; module_evals and the eval texts that name the tree precompiled instead: what was measured and checked, and the next leads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Util/perf/LEDGER.md | 54 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 7faf1a68a..e3c2a377a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1567,6 +1567,16 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has image; best-of-10 wall -2 to -11% and -0 to -14%. Not taken: the JIT's re-parses of start-up methods (2-3 ms of `-e 1`), and Kernel#require's first-call body compile (~10 ms, 4 ms of it the first def-body transform's cold path), the next leads. + 2026-11-28, perf/requirecold (Landed, not gated): Kernel#require's first-call compile was + already gone. perf/bootparse precompiled the kernel_require.rb eval, and with it the def bodies + in it (`def body: transform` 9.0 ms -> 0 in `-e 1`). What was left to parse at start-up were + module_evals (FileUtils' 92, which `require "irb"` loads; Date::Format::Bag's 22) and the + 36 reline delegators whose text names the tree (claimed only in the tree they were recorded in). + Both are now in the library: -1.4 to -2.1% main-thread instructions on `require "irb"` and irb; + the other three +0.05 to +0.14% (registering more keys). Next leads: the first top-level + transform of a process (4.1 ms for `-e 1`'s one character, a cold path), the JIT's re-parses + of library methods (140 `def body: AST bridge` in irb), and fileutils.rb, tmpdir.rb and + irb/completion.rb, still compiled from source (rescue re-raise frames, refinements). 27. **Closed (perf/crubydiff, third round): `send` frames are hidden.** Was: **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a @@ -2422,6 +2432,50 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - For the gate: the shared rule's set now decides `!=` for every plain-object class a program has; the cases above are the ones that must leave a class out. +- **perf/requirecold (2026-11-28) - module_evals in the startup library; eval texts that name the tree (gap 26)** + - not gated. Base 50b07b5 (claude/happy-gauss-95wm2j) merged with 516fb7c (perf/bootparse). + The brief: Kernel#require's body, compiled at its first call (~10 ms on the R2R host before + perf/bootparse, ~4 ms of it the cold path of the first def-body transform). Measured on the base + (IR_PHASE_TIMES, R2R host): that compile is gone. The kernel_require.rb eval comes from the library + since perf/bootparse, with its def bodies (`def body: transform` 9.0 ms / 1 -> 0 in `-e 1`, + `def body: LightCompile` 3.0 ms -> 0). So the transformer's cold path, R2R coverage and warming it + off the main thread were not pursued: what is left of it is the one top-level transform of each + command's own script (4.1 ms for `-e 1`). Taken instead, the largest parse left at start-up: + - aea43ac: module_evals. RubyUtils.Evaluate left `module_eval`/`class_eval` strings out of the + precompiled evals (with the eval code cache). FileUtils makes Verbose, NoWrite and DryRun with 92 + `module_eval <<-EOS def #{name}...` (`require "irb"` loads fileutils through tmpdir) and + Date::Format::Bag 22 accessors; irb `1+1` parsed and transformed 135 texts. A module_eval of a named + module that is not a singleton class is now recorded and claimed, with the module's name in the key. + The compiler walks its text as that module's body, so its defs' frame labels name the module + (FileUtils::Verbose#mkdir) and their bodies are not compiled again from source at their first call. + FactoryKind.ModuleEval, as CreateCompilerOptionsForEval. instance_eval (a singleton class) and an + anonymous module's module_eval compile from text; the code cache still takes plain evals only. + startup-evals.txt 150 -> 264 evals; irb claims 212 (84), top-level transforms 135 -> 7. + - 658195a: Forwardable writes the location that defined a delegator into its text (the + private-method warning), so 36 of reline's 56 delegators name the tree's root. They were claimed + only in the tree startup-files.rb recorded them in: the release image, a build from any other + checkout, and perf/bootparse's measured base claimed 20 of 56. The recorder writes the root as + ${ROOT} in a text as in a path; HashEvalCode hashes a text with the root as RootMarker; and an + eval's frozen strings that name the tree are rebased as the library's other strings are. A copy of + the release image moved elsewhere claims all 56, and the warning names the moved tree. An eval that + would still tie the library to its tree (a symbol) is left out rather than the library unused. + Numbers (base / new, one batch each): + - Main-thread instructions (callgrind, TieredCompilation=0), R2R host: `-e 1` +0.08%, `gem --version` + +0.08%, `gem list` +0.07%, `require "irb"` -1.42%, irb -1.82%. Release image: +0.05%, +0.05%, +0.14%, + -2.09%, -1.79%. The +0.1% is the attribute's 114 more keys and hashes read at every start: 264 entries + share 99 keys, so a key table would take most of it back. + - Wall, best of 10 alternating, two batches: within noise (the spread between batches was +-9% on + the release image, against a ~2% effect). + Checked: FileUtils::Verbose/NoWrite/DryRun output, frame labels, owner, source_location, parameters and + an ArgumentError's backtrace as the base and as CRuby 4.0; Date's parsers as the base; the bootparse + probe (second load, changed byte, other file and line, threads) as the base. The five commands print what + the base prints (R2R host; release image moved). `startup-files.rb --check` passes. Matrices eval, + eval-locals, eval-defined, eval-literals, erb-escape, forwardable, binding-lvar, caller, sdef, + refinement, error-message, super-light in the gate's modes, r2r and r2r with IR_STARTUP_DLL=none: PASS + (70 same, 14 baseline). IronRuby.Tests and ruby/spec not run this round. + For the gate: that a module_eval's compiled code depends on nothing of its module but the name (the + key's), and labels; the root replacement in HashEvalCode and in eval strings (an eval text naming the + tree is now relocated, where a file's literal naming it still makes the library unrelocatable). - **perf/bootparse (2026-11-27) - the string evals of start-up precompiled in the startup library (gap 26)** - not gated. Base 4703cb5 (f67ac44 with perf/clrlookup). What start-up parses at run time (R2R host, IR_PHASE_TIMES, IR_STARTUP_DLL_TRACE): the string evals, From fa82365fddf9f2d681ace4397d0b2f67fff4e7e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:15:39 +0000 Subject: [PATCH 278/439] Design: general calls in typed bodies, the tail slice counted and not built (gap 1) Docs/jit-resume-deopt.md gets "Stage 2 again": what a typed body needs to make a call of any method (an Obj result, no re-run of the call on a later deopt, the method/constant/tracing/ivar-shape checks after it, the backtrace frame and scope through stage 1's machinery), the narrowest slice that is sound now (the call as the body's last operation), and its reach counted from the census with prism: 3,574 wrappers whose body is only the call, 343 with a typed prefix. The gap's shapes are already at CRuby's speed where the slice applies (queue_packet 1.00, add_input 0.99); what is left is a call in a loop (schedule 1.12) and a raise guard (find_task 1.60). Not built; the ledger's Rejected entry says what is next on the gap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Docs/jit-resume-deopt.md | 81 +++++++++++++++++++++++++++++++++++++++- Util/perf/LEDGER.md | 12 ++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md index 33891b2fe..cf8224691 100644 --- a/Docs/jit-resume-deopt.md +++ b/Docs/jit-resume-deopt.md @@ -2,7 +2,7 @@ Status: stage 1 is implemented behind `-X:JITResume` (off by default; `Src/Ruby/Runtime/Jit/JitResume.cs`, `JitCompiler.Resume.cs`, matrix section 11 of `Util/jit-matrix.rb`), narrowed as its section says; the rest -is design only, including stage 3a at the end (a yield in an outlined loop, gap 18), whose matrix is +is design only, including a second look at stage 2 (round thirty-seven: the slices counted, not built) and stage 3a at the end (a yield in an outlined loop, gap 18), whose matrix is `Util/yield-loop-matrix.rb`. It answers gap 1 of `Util/perf/LEDGER.md` ("Calls of other methods from hot bodies"): `CallSite.Target` is 24-32% of every benchmark, and Richards, Towers, DeltaBlue, Bounce and CD's `tree_insert` all wait on one rule of the @@ -379,6 +379,85 @@ the first's index, which would run an iteration whose condition nobody evaluated `-X:JITResume` on by default, after a full sweep and the benchmark suite, if stages 1-4 measured as faster. +## Stage 2 again (round thirty-seven, 2026-11-28): what a general call needs, the slices, their reach + +Asked again after perf/jiteach and perf/jiteqq: both found that taking one more construct past the screen only moves +a method to its next refusal, which is usually an ordinary call. So: what would a typed body need to make a call of +any method, and is there a slice of that which is sound in one step and reaches something hot? This section answers +from the code as it stands and from counts; nothing was built. + +### What a general call needs + +A call of an arbitrary method is an effect that can do anything: redefine methods, reassign constants, enable a +TracePoint, write the caller's locals through a binding, raise, re-enter the method. Four things follow. + +- **Its result.** `Obj`, always: no profile of a callee's result makes a typed value without a guard, and a guard + after the call is a deopt after an effect. Code after it that consumes the value takes it as an object (the + self-guarded tail of stage 1, or nothing speculative at all). +- **A deopt after it.** It must never re-run the call. Restarting the generic body does (that is the current rule's + whole reason), so a deopt after a call must continue in generic code: a per-operation fallback (A) where the + operation's result is an object, or a resume at the next statement boundary with the frame state written into the + scope (B, stage 3) where it is typed or the world changed. Until B exists, nothing that can deopt may follow a + call. +- **What it invalidates.** The entry checked the method version, the constant version and tracing once, on the way + in. After a call every one may have moved: each later speculative operation re-checks what it depends on itself + (A's rule: `GlobalMethodVersion`, the constant version, `TracePoint.ActiveEvents`), or the body is handed to the + resumable generic body at the next statement (B). Self's class and the shape of its instance variables can change + too (`extend`, `instance_variable_set`, `remove_instance_variable`), which the typed body's unguarded ivar slots + assume; an ivar read after a call has to be the generic read or a re-guarded one. +- **Exceptions and frames.** The callee's backtrace must show this method at the call's line, once: stage 1's + `JitResumeInfo.Slow` (a lambda named as the generic body's frame, keeping the line in `PrecompiledFrames` while the + call runs) does that without a frame on the fast path. A `rescue` around the call is the generic body's; a typed body + with one around a call is declined. The callee may need the caller's scope (a protected or missing method, a refined + name, a library method that reads it): the light-scope site answers `LightScopeRequired` and the call is made again + through the full site with the scope made once, with the method's block in it (`CreateMethodScopeLazy`, which takes + the block off the reusable list), in the light frame's try/filter/finally so `return` from a proc made there and + LocalJumpError after the method returned are right. Once that scope exists the locals live in it (see "Once the + scope exists"): the call that made it must be the last thing the typed body does, or the body resumes (B). + +### The narrowest slice that is sound now + +A typed body whose one general call is its **last** operation: the call's result is the method's value, nothing +after it can deopt or read a local, so nothing has to be resumed, re-checked or written back; a scope the call makes +is made with the final values of the locals. Everything above reduces to: stage 1's fallback site as the primary +path, the light frame's try/filter/finally, `blk` into the scope, the stack check, the line for the backtrace. +Slightly wider and as sound: the call followed only by things that speculate on nothing and read no local (a +literal, `self`, an instance variable read whose slot is re-guarded). + +### Reach, counted before building + +From the census of 33818f7 + c0c3335 (`census.rb -l -a`, Src/StdLib and AWFY, 28,377 methods), the methods whose one +and only screen refusal is a `MethodCall`, each def read with prism: + +| Where the refused call is | Methods | +|---|---| +| the body's last statement, the name nowhere else, and the body that one statement (a wrapper: `def a(x) = b(x)`) | 3,574 | +| the last statement, after a prefix of 1 / 2 / 3 or more statements | 219 / 81 / 43 | +| the last statement, but the same name called elsewhere in the body too | 142 | +| followed only by a literal, self or a local or instance variable read | 96 | +| not a statement of the body (inside a condition, an argument, a loop) | 5,736 | + +A wrapper's typed body would be the call and nothing else: what the generic light frame already is, a site and no +scope (perf/jcall and perf/resume2 measured exactly that and found nothing). What could gain is the 343 with a typed +prefix. Among AWFY's: Richards' `run_task` and DeltaBlue's `AbstractConstraint#add_constraint` (a prefix of self +calls), `queue_packet` (its prefix writes `@queue_count` and then two attributes of another object: a deopt after an +effect, declined by the slice before its call is reached), Havlak's `SimpleLoop#set_parent`, SOM's +`Dictionary#resize`, `Queens#queens`, the harnesses' loops. And the ceiling, `Util/bench/jit-resume2-shapes.rb` by +clock against CRuby 4.0 (`ab.rb -r 5`, load 1.6-2.2): `queue_packet` 1.00, `add_input` 0.99 - already level, nothing +for any form of this to win - `schedule` 1.12 (a `while` whose body calls `t.step`: a call in a loop, which the slice +does not take) and `find_task` 1.60 (an element read and `raise ... if t.nil?`: no general call at all). + +### So + +Not built. The tail slice is sound and wide on paper, but it is perf/jcall's shape with the frame cost gone, and its +methods are either wrappers (nothing to gain) or ones already at CRuby's speed on the measured shapes; the time left +in gap 1's shapes is in a loop of calls (`schedule`) and in a raise guard (`find_task`). What would move `schedule` is +not a general call from a typed body but a call *into* a typed body: `t.step` on a receiver whose class the profile +saw, entering the callee's typed body directly with unboxed arguments (`-X:JITCalls` for other receivers than self, +the callee's own deopts absorbed at the boundary, stage 4), inside a loop the typed body owns - which needs stage 3's +resume for the loop as soon as the callee is not known pure. That, or stage 3 itself, is the next step on this gap; +another slice of stage 2 is not. + ## Stage 3a: a yield in an outlined loop (gap 18) Status: design, with its matrix (`Util/yield-loop-matrix.rb`, which CRuby and the unchanged build print diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index ecc740b73..67fc35991 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -8107,6 +8107,18 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitcalls (2026-11-28) - general calls in typed bodies, the narrowest slice: designed and counted, not + built** (gap 1). The design and the counts are in `Docs/jit-resume-deopt.md`, "Stage 2 again". The slice sound in + one step is a typed body whose one general call is its last operation (nothing after it to deopt, re-check or + write back). Of the methods whose only screen refusal is one call, 3,574 are wrappers whose whole body is that call + (what a light frame already is: perf/jcall and perf/resume2 measured nothing there), 343 have a typed prefix before + it, 96 more follow it only with literals or reads. AWFY's among them are `run_task`, `add_constraint`, + `set_parent`, `Dictionary#resize`, `Queens#queens`; Richards' `queue_packet` is declined before its call by an + attribute write after an ivar write. The ceiling, `Util/bench/jit-resume2-shapes.rb` against CRuby 4.0: + `queue_packet` 1.00, `add_input` 0.99, `schedule` 1.12 (a call in a loop), `find_task` 1.60 (a raise guard, no call). + Next on gap 1: a call into a typed body from a loop the typed body owns (`-X:JITCalls` on other receivers, with + stage 3's resume), not another slice of stage 2. + - **perf/jiteqq (2026-11-28) - `C === x` (Module#===, a constant receiver) in a typed body; `respond_to?(:lit)` counted: built, census-measured, nothing hot moved, not kept.** From the census of 33818f7 + 5b98b17, where `MethodCall ===` refuses 304 methods first (426 at all, 170 alone). By receiver (prism over each refused method's From 2eda4afdc5a08d8c2e0db95468ac0a30f57b129d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:40:05 +0000 Subject: [PATCH 279/439] A body that evaluates a literal block on every call is not a light frame The light frame makes a method's scope only when something asks for it, which saves the scope when a literal block sits behind a return or a condition. When a literal is reached on every call, the frame makes the scope anyway, from inside the literal's instantiation (LightScopeInLoop over the parked take, the register locals copied into a tuple), then leaves through LeaveLightMethodFrame's slow path. The same body as an ordinary frame takes its parked scope at entry and is faster: e1 (a.each { |x| }) 136 -> 124 ns, each { |x| s += x } 151 -> 135, map 168 -> 152, times 154 -> 141, ny { 1 } 149 -> 139 (ab.rb -r 10); controls level, and a literal behind a return (nbx, nby, nbz) still runs light. EvaluatesLiteralOnEveryCall: some statement evaluates a literal block (a call with one, as a receiver or argument, or the right-hand side of an assignment other than ||= and &&=) and no statement before it holds a return. IR_LIGHT_STRAIGHT_LITERAL=0 restores the old choice. The dump of e1's code found nothing else to cut: moving InitializeBlock to the retry path, or dropping the EvalUnwinder try/catch (unsound, as a bound), measured nothing. iter-shapes.rb gains e1, ep and ept; the block-cost harness reports bytes end to end, and its ept no longer calls nil?, which had made a literal look like it cost a light frame 10 ns. Checked: thirteen block and frame matrices in every mode and with the switch off (91 same); ruby/spec language on both builds (same); the IronRuby.Tests suite on Debug (passed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/IronRuby.Tests/Perf/BlockCostHarness.cs | 6 +- .../Ast/Definitions/MethodDefinition.cs | 71 ++++++++++++++++++- Util/bench/iter-shapes.rb | 8 +++ Util/perf/LEDGER.md | 27 +++++++ 4 files changed, 109 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/Perf/BlockCostHarness.cs b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs index 5c16347a1..17577c900 100644 --- a/Src/IronRuby.Tests/Perf/BlockCostHarness.cs +++ b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs @@ -39,7 +39,7 @@ def nyl(a) = ny { 1 } def e1(a); a.each { |x| }; 1; end def e0(a); 1; end def ep(a); a.each(&PE); 1; end - def ept(a); return a.each { |y| } if a.nil?; a.each(&PE); 1; end + def ept(a); return a.each { |y| } unless a; a.each(&PE); 1; end def nyp(a) = ny(&PY) def grab(&b) = b def lit1 = grab { 1 } @@ -438,13 +438,15 @@ private static void ReportRuby(ScriptEngine engine, string name, int n) { engine.Execute(String.Format("bc_run_{0}(BcO.new, [1], {1})", name, n / 10)); double best = Double.MaxValue; string code = String.Format("bc_run_{0}(BcO.new, [1], {1})", name, n); + long bytes0 = GC.GetAllocatedBytesForCurrentThread(); for (int round = 0; round < 5; round++) { var sw = Stopwatch.StartNew(); engine.Execute(code); sw.Stop(); best = Math.Min(best, sw.Elapsed.TotalMilliseconds * 1e6 / n); } - Console.WriteLine(" {0,-80} {1,7:F1} ns", "end to end: " + name + " (the caller's while loop included)", best); + Console.WriteLine(" {0,-80} {1,7:F1} ns {2,4} B", "end to end: " + name + " (the caller's while loop included)", best, + (GC.GetAllocatedBytesForCurrentThread() - bytes0) / (5L * n)); } } // perf/stagea's simulation of a block descriptor (Docs/block-calling-convention.md, "Stage A, simulated"): what the diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 70e99d6b7..d2aeb49ef 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -305,7 +305,8 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin optionalsInitialization = AstUtils.Empty(); } if (allowLightFrame && LightFramesEnabled && definitionRefinements == null && gen.Profiler == null && !gen.TraceEnabled && - !gen.CompilerOptions.IsEval && !scope.HasClosures && IsLightFrameCandidate()) { + !gen.CompilerOptions.IsEval && !scope.HasClosures && IsLightFrameCandidate() && + !(LightStraightLiteralEnabled && EvaluatesLiteralOnEveryCall())) { light = TransformLightFrame(gen, scope, scopeVariable, selfParameter, blockParameter, declaringScope, declaringModule, visiblePrameterCountAndSignatureFlags, parkSlot, ref statements); } @@ -525,6 +526,12 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// internal static readonly bool LightLiteralCallsEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_LITERAL_CALLS") != "0"; + /// + /// IR_LIGHT_STRAIGHT_LITERAL=0 lets a body that evaluates a literal block on every call run in a light frame, as before round + /// thirty-seven's perf/literalcode (see EvaluatesLiteralOnEveryCall). + /// + internal static readonly bool LightStraightLiteralEnabled = Environment.GetEnvironmentVariable("IR_LIGHT_STRAIGHT_LITERAL") != "0"; + /// /// IR_LIGHT_SPLAT=0 keeps every method that splats a value (`inner(*args)', `[*a]', `yield(*a)') out of light frames /// (see IsScopeFree and LightFrameRewriter.VisitExtension). @@ -994,6 +1001,68 @@ private static bool IsBlockGuard(Expression/*!*/ node) { return yieldCall != null && yieldCall.Arguments == null && yieldCall.Block == null; } + /// + /// A statement of the body evaluates a literal block, and no statement before it can return: every call that returns + /// normally makes the literal's Proc, and with it the scope. Such a body runs faster with its scope made at entry (taken + /// parked) than in a light frame that makes it on demand from the literal: `def e1(a); a.each { |x| }; 1; end' 139 ns + /// against 116 a call, `each { |x| s += x }', map, times, `nb { }' 8-19% (perf/literalcode). The light frame stays for + /// a body whose literal is behind a return or a condition (`return nb(&P) if a; nb { }'), where it saves the scope. + /// + private bool EvaluatesLiteralOnEveryCall() { + var statements = (Body != null) ? Body.Statements : null; + if (statements == null) { + return false; + } + foreach (var statement in statements) { + if (EvaluatesLiteral(statement)) { + return true; + } + var returns = new ReturnFinder(); + statement.Walk(returns); + if (returns.Found) { + return false; + } + } + return false; + } + + // Whether evaluating the expression evaluates a literal block whatever its values: a call with one, or such a call as the + // receiver or an argument of a call, or the right-hand side of an assignment that always evaluates it. + private static bool EvaluatesLiteral(Expression expression) { + switch (expression) { + case MethodCall call: + if (call.Block is BlockDefinition) { + return true; + } + if (call.Target != null && EvaluatesLiteral(call.Target)) { + return true; + } + if (call.Arguments != null) { + foreach (var argument in call.Arguments.Expressions) { + if (EvaluatesLiteral(argument)) { + return true; + } + } + } + return false; + case SimpleAssignmentExpression assignment: + return assignment.Operation != Symbols.And && assignment.Operation != Symbols.Or && + EvaluatesLiteral(assignment.Right); + default: + return false; + } + } + + private sealed class ReturnFinder : Walker { + internal bool Found; + public override bool Enter(ReturnStatement/*!*/ node) { Found = true; return false; } + // (the walker does not visit a call's block, where a return would leave the method too) + public override bool Enter(MethodCall/*!*/ node) { + if (node.Block is BlockDefinition) { node.Block.Walk(this); } + return true; + } + } + // Some statement of a light-frame candidate is scope-free only with its literal blocks (see LightFrameRewriter.BlockLiterals). private bool HasLightBlockLiteral() { return !IsBodyScopeFree(false); diff --git a/Util/bench/iter-shapes.rb b/Util/bench/iter-shapes.rb index 90c1377bf..0d240928d 100644 --- a/Util/bench/iter-shapes.rb +++ b/Util/bench/iter-shapes.rb @@ -9,12 +9,14 @@ # nb0, nbp, nbl: a light method that ignores its block called with none, with a stored Proc (`&P') and with a literal # `{ }'; eachp, eachl: Array#each over one element with `&P' and with `{ }'. A literal costs its caller what a stored # Proc does not: the method's scope made (or taken parked) and the Proc made over it (round thirty-seven, perf/iter3). +# e1, ep, ept: `a.each { |x| }', `a.each(&PX)', and ep with a literal in a branch never taken (perf/stagea, perf/literalcode). # nbx, nby, nbz: a body that has a literal (never evaluated here) calling with a stored Proc, without a block, and not at # all: in such a body a call with a block takes the full site with the scope made on demand (perf/lazyproc, # Docs/light-frame-literal-blocks.md). $stdout.sync = true P = proc { } +PX = proc { |x| } class O def nb; 1; end def ny; yield; end @@ -32,6 +34,9 @@ def times(k); s = 0; k.times { |j| s += j }; s; end def map(a) = a.map { |x| x + 1 }.size def empty(a); a.each { }; 1; end def call(a); s = 0; s += a[0]; s; end + def e1(a); a.each { |x| }; 1; end + def ep(a); a.each(&PX); 1; end + def ept(a); return a.each { |y| } if a.nil?; a.each(&PX); 1; end end def cpu @@ -89,4 +94,7 @@ def t(name, n) t("nbx", N) { |n| i = 0; s = 0; while i < n; s += o.nbx(a1); i += 1; end; s } t("nby", N) { |n| i = 0; s = 0; while i < n; s += o.nby(a1); i += 1; end; s } t("nbz", N) { |n| i = 0; s = 0; while i < n; s += o.nbz(a1); i += 1; end; s } +t("e1", N) { |n| i = 0; s = 0; while i < n; s += o.e1(a1); i += 1; end; s } +t("ep", N) { |n| i = 0; s = 0; while i < n; s += o.ep(a1); i += 1; end; s } +t("ept", N) { |n| i = 0; s = 0; while i < n; s += o.ept(a1); i += 1; end; s } t("nyl", N) { |n| i = 0; s = 0; while i < n; s += o.nyl(a1); i += 1; end; s } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 609a58014..77b1bff47 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1217,6 +1217,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has perf/stagea simulated stage A in the harness before building it and found nothing to build (see Rejected): the descriptor's per-call fill costs what the parked cycle costs, `e1`'s steps 44 ns parked against 46-61 as a descriptor. The literal's 45-50 ns end to end is not in one runtime step. + perf/literalcode found where it is (see Landed): the light frame making the scope on demand + for a literal it always reaches; such a body now takes its scope at entry, 7-11% on those shapes. 17. **The prelude calls its C# helpers as methods**: about 230 private `__x__` methods, called 1,928 times in `ruby4.rb` through call sites (8-12 ns each, a rule to bind per @@ -1953,6 +1955,31 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/literalcode (round thirty-seven, 2026-11-28) - a body that evaluates a literal block on every call is not made a + light frame (gap 13)** - time, not gated. Asked to find the compiled code around a literal's instantiation (the 16-20 ns + perf/stagea left unattributed), the round dumped `e1`'s expression tree and its JIT code. The call with a literal in a light + frame does: the scope made on demand inside the literal's instantiation (`LightScopeInLoop` over `TakeParkedScope` and + `ReuseParkedScopeLazy`, the register locals copied into a tuple first), `InitializeBlock`, a try/catch for `EvalUnwinder` + around the call and a `BlockReturnResult` test after it, `LeaveLightMethodFrame` then taking its slow path because a scope + was made, and `BeginPark`/`EndPark`; the scope-making tree is inlined at every place that may need the scope (6 KB of code + against `ep`'s 3.4). Neither `InitializeBlock` moved to the retry path nor the try/catch removed (an upper bound, not sound) + showed anything in eight alternating rounds. What did: the same body as an ordinary frame, whose scope is taken parked at + entry, is faster than the light frame that makes it on demand - the light frame saves the scope only when the literal is not + reached. So `EvaluatesLiteralOnEveryCall` (a statement evaluates a literal block - a call with one, as a receiver or an + argument, the right-hand side of an assignment other than `||=`/`&&=` - and no statement before it holds a `return`) keeps + such a body out of light frames. `IR_LIGHT_STRAIGHT_LITERAL=0` is the old choice. `ab.rb -r 10`, off/on, ns per call: + `e1` 136.0/123.7, `eachl` 131.5/118.0, `empty1` 139.7/129.4, `each1` 151.1/135.0, `each4` 216.0/205.8, `map1` 167.9/151.6, + `times1` 153.7/140.6, `times4` 227.4/211.8, `nyl` 148.9/139.2, `nbl` 115.9/103.9; controls level (`ep` 90.7/88.0, `ept` + 99.9/100.0, `nbx` 52.0/55.6, `nby`, `nbz`, `call` 59.0/59.4). Eight rounds of more shapes: a wrapper yielding from its + literal (`wrapc`) 280.6/252.5, a literal followed by four calls 179.6/156.9, `block_given?` after it 145.8/131.4, keywords + 211.8/192.0, an optional 176.0/167.6, two literals 223.0/203.8. The harness's single end to end: `e1` 127.6 -> 123.3, `nyl` + 134.3 -> 128.9, bytes the same. Correction to perf/stagea: `ept` there called `a.nil?`; without it `ept` is `ep` (84-91 ns, + 95 B), so having a literal costs a light frame nothing, and `e1` - `ep` (about 40-48 ns) is all the literal's evaluation. + Checked: literal-block-light, block-pass, block-given, parked-scope (its two-thread rows), block-scope-reuse and its race, + block-nest-reuse, nested-proc, parked-iterator, hot-shapes, jit, light-entry and light-rest in the six modes and with the + switch off: PASS, 91 same. ruby/spec language in full on both builds: 2935 examples, the same one error (send_spec's + `into`/`to`). IronRuby.Tests in full on a Debug build: PASSED, no failure. + - **perf/endpark (round thirty-seven, 2026-11-28) - EndPark publishes the parked scope with a release write, not a compare-exchange (gap 13)** - time, not gated. Stage 0 found the parked cycle's two atomics about 16 ns of a literal's 50, one `CompareExchange` 10.4 ns here against a `Volatile.Write`'s 2.5. The From 5cc8bd07d723e3bc2aec7b03208dac7e78d5d4f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:40:33 +0000 Subject: [PATCH 280/439] Design: stage 3's first step, resume at a top-level statement, as 3a's generic tail's second user The hot methods the JIT declines in AWFY are all declined by the effect rule; none waits for a pure typed callee, so stage 4's slice reaches nothing hot. Docs/jit-resume-deopt.md gets the resume step precisely (per-statement purity, the generic suffix shared with stage 3a's tail, the frame-state write-back through stage 1's frame, per-statement undo marks, frames, tracing, accounting) and its matrix rows. Alone it unlocks about 2% of Richards, so it is ordered after 3a's yield loop. Not built. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Docs/jit-resume-deopt.md | 80 ++++++++++++++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 10 +++++ 2 files changed, 90 insertions(+) diff --git a/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md index cf8224691..ee47835da 100644 --- a/Docs/jit-resume-deopt.md +++ b/Docs/jit-resume-deopt.md @@ -458,6 +458,86 @@ the callee's own deopts absorbed at the boundary, stage 4), inside a loop the ty resume for the loop as soon as the callee is not known pure. That, or stage 3 itself, is the next step on this gap; another slice of stage 2 is not. +## Stage 3, first step: resume at a top-level statement, sharing 3a's generic tail (round thirty-seven, design) + +Chosen over stage 4's narrow slice (a typed loop calling a pure typed callee) by what the JIT declines in AWFY +(`IR_JIT_VERBOSE=1`, Richards, DeltaBlue, Havlak, CD, Json, Bounce, Towers, List on c0c3335): every hot method it +turns away after the screen is turned away by the effect rule - Richards' `append`, `release` and `hold_self` +("a deopt after an effect"), DeltaBlue's and Havlak's `Vector#remove_first`, Havlak's `split_bucket`, Json's +`read_required_char`, and Json's `skip_white_space` ("a loop in a body that can deopt and has an effect"). None +is a loop waiting for a call into a pure typed callee; Richards' `schedule` calls `run_task`, which is the +benchmark's work and not pure. + +### The step + +A typed body may deopt after an effect when the failing operation stands in a **top-level statement** of the +method body (or in the condition or body of a top-level `while`) and nothing observable happened in that +statement before the guard. It then **resumes at the start of that statement** in generic code, with its frame +state written into the scope, instead of restarting the body. + +- **Per-statement purity.** The compiler tracks `_pure` per top-level statement as it does per body now. A deopt + after an effect *within the same statement* still declines the body. For a top-level `while`, the statement is + re-entered at its head: sound only if the failing guard is in the condition or before the first effect of the + iteration (the OSR copy's rule), since the iterations already run left their effects and their locals. +- **The generic suffix.** Statements `k..n` of the body, compiled by the AstGenerator exactly as the generic body + compiles them (the same sites, line markers, TraceLineExpressions, `return` as `gen.Return`), as a lambda over the + method's scope: `Func` (scope, self, block -> the method's value). Built the + first time statement `k` resumes, cached on the specialization, cold code. This is stage 3a's "generic tail" + (way 2) with a different start: 3a's tail is the suffix of a loop body after the yield, run for one iteration and + then handed back to the loop; this one is the suffix of the method body, run to the end. One compiler serves both: + `GenericSuffix.Compile(Statements list, int start, MethodDeclaration ast, bool endsIteration)`. +- **The frame state.** The typed body throws `JitResumeException(k, object[] locals)` with its live typed locals + boxed through the representation funnel (`NarrowLong`, booleans as `true`/`false`, never-assigned as nil). The + entry, already wrapped in the light frame's try/filter/finally by stage 1 (`WrapResumeBody`), catches it, + makes the scope once (stage 1's `JitFrame.Scope`: `CreateMethodScopeLazy` with the generic body's + `MethodFrameShape`, which the generic compile records for the stub, and `blk`), stores the locals into its + tuple by the generic body's slot order, takes element writes made since statement `k` began back + (`JitUndoLog` gets a mark per top-level statement, not per entry), and calls the suffix. A scope already made + by a call in the typed body is that scope: by the rule of "Once the scope exists", the call that made it was the + typed body's last act, so the resume is right after it and the tuple is already authoritative. +- **Exceptions, flow, frames.** The suffix runs inside the entry's light-frame try/filter/finally, so `return` + from a proc made there, LocalJumpError after the method returned and `ensure` are the generic body's. Its lambda + is named as the generic body's frame (`JitStub.Named`) and carries the line markers, so a backtrace from it shows + the method once, at its line. Tracing: the suffix has the generic hooks. Stack: the resume checks it, as + `CreateMethodScope` would. +- **Accounting.** A resume counts as a deopt for retiring the specialization (`OnDeopt`), or a body that resumes + on every call stays in place and is slower than the generic one. + +### What it unlocks, and what it is worth alone + +`append` (its deopt is `mouse.link` in the condition of the top-level `while`, after `packet.link = NO_WORK` in +statement 1: it resumes at the `while` head with `mouse` written back), `add_input_and_check_priority` and +`release` (Richards), `remove_first` (DeltaBlue, Havlak), `read_required_char` (Json). Not `skip_white_space`: its +effect and its deopt are in the same iteration (3a's handback or stage 5). By the ledger's profiles that is +`append` 2.1% and `add_input_and_check_priority` 2.7% of Richards, `remove_first` under 1.4% of DeltaBlue; stage 1, +the same kind of gain, measured 13-14% on its shape and nothing on a benchmark. Alone, this step does not pay for +its code. + +### So: build it as 3a's second user, not first + +Stage 3a's yield loop has a measured target (`ueach100`: about 40 ns per element against CRuby's 28, about 23 for +a typed copy) and needs the same suffix compiler for its way 2. Order: + +1. 3a step 1 (perf/iter's): Handback and MethodReturned in `OsrLoopSite`. +2. `GenericSuffix` with 3a step 2 as its first user (the generic tail after the yield), gated by + `Util/yield-loop-matrix.rb` and measured on `Util/bench/yield-shapes.rb`. +3. This step, as `GenericSuffix`'s second user, behind `-X:JITResume=3`, gated by the rows below, measured on + Richards and on a shape of `append`. + +### Its matrix rows (to add to `Util/jit-matrix.rb` section 11 with the step) + +| Row | Checks | +|---|---| +| `append` shape: effect in statement 1, receiver of another class in the loop's condition on iteration 1, 3, n | resume at the `while` head, the statement-1 write not repeated, `mouse` the loop's value | +| deopt in statement k after effects in statements < k, with locals of each representation (Int, Lng past 2**31, Dbl, Bool, nil, never assigned) | the write-back funnel | +| element write in statement k, then a deopt in statement k | the per-statement undo mark: the write taken back, the statement re-run once | +| a call in statement j that makes the scope (`binding`), a deopt in statement j+1 | the scope's tuple is the state; `local_variable_set` from the callee is seen | +| `ensure` around the body, `return` in the suffix, a proc made by `binding.eval("proc { return 7 }")` called after the resume and after the method returned | flow and the frame's try/filter/finally | +| an exception in the suffix | the backtrace has the method once, at the suffix's line | +| a TracePoint enabled by a call in statement j | `:line` for statements after j, `:return` once | +| a deopt in statement k on every call | the specialization retires (`OnDeopt`) | +| four threads, receivers of two classes | per-invocation state | + ## Stage 3a: a yield in an outlined loop (gap 18) Status: design, with its matrix (`Util/yield-loop-matrix.rb`, which CRuby and the unchanged build print diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 67fc35991..011fb3a79 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -8107,6 +8107,16 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitcalls, second round (2026-11-28) - stage 3's first step or stage 4's slice: measured, designed, not + built** (gap 1). Chosen by what the JIT declines in eight AWFY benchmarks: every hot method turned away after the + screen is turned away by the effect rule (`append`, `release`, `hold_self`, `remove_first`, `split_bucket`, + `read_required_char`, `skip_white_space`); none is a loop waiting for a call into a pure typed callee, so stage 4's + slice reaches nothing hot. The step, resuming at a top-level statement with the state written into the scope, + is designed in `Docs/jit-resume-deopt.md` ("Stage 3, first step"): its generic suffix is the same compiler as stage + 3a's generic tail. Alone it would unlock methods worth about 2% of Richards and under 1.4% of DeltaBlue (the + profiles of gap 11), stage 1's kind of gain, which measured nothing on a benchmark. So it is to be built as the + suffix compiler's second user, after 3a's yield loop, which has a measured target. + - **perf/jitcalls (2026-11-28) - general calls in typed bodies, the narrowest slice: designed and counted, not built** (gap 1). The design and the counts are in `Docs/jit-resume-deopt.md`, "Stage 2 again". The slice sound in one step is a typed body whose one general call is its last operation (nothing after it to deopt, re-check or From d32ac04518a5fed194f510042e52bd92affb6be2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:46:32 +0000 Subject: [PATCH 281/439] A fiber's block keeps its own $~ and $_, as MRI's does $~ and $_ in a block belong to the frame the block was written in, but MRI keeps those of a block running as a fiber in the fiber's own root svar (ec->root_svar), as it does a thread's: two fibers made from one top-level lambda that each match and yield answer their own $~[1] ("x", "y"), and a fiber does not see or set its creator's $~. IronRuby shared the defining frame's, so the second fiber's match overwrote the first's (["y", "y"]). Threads were already right: their block's BlockParam is marked IsThreadRoot, which makes its scope keep its own. The prelude's Fiber runs its block through Proc#__ir_call_as_root__ (Proc.CallAsRoot), which calls it as #call does - the lambda arity check, a lambda's one argument unsplatted, keywords received as keywords - with a fresh BlockParam marked as a root. Fiber_OwnSpecialVariables1 holds CRuby's output (fibers and threads, Enumerator#next, arguments, a lambda's arity, break/return); core/fiber, core/enumerator and core/thread specs pass, the enum, enum-next, fiber-reclaim, eval and regex matrices are unchanged, and 118 fiber, thread, enumerator, proc and keyword IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/FiberTests.cs | 47 ++++++++++++++++++++++++ Src/Libraries/Builtins/ProcOps.cs | 14 +++++++ Src/Ruby/Builtins/Proc.cs | 27 ++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 3 +- 5 files changed, 91 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 42e21bfab..8806d6a43 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1235,6 +1235,7 @@ public Tests(Driver/*!*/ driver) { Block_ReturnTraceFrameCleanup1, Thread_SetTraceFunc1, Fiber_ReclamationClrBoundary1, + Fiber_OwnSpecialVariables1, Fiber_Keywords1, WeakMap_NoBlock1, Fiber_ThreadRaiseReachesRunningFiber1, diff --git a/Src/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index a0f7de3da..7186197ca 100644 --- a/Src/IronRuby.Tests/Runtime/FiberTests.cs +++ b/Src/IronRuby.Tests/Runtime/FiberTests.cs @@ -83,6 +83,53 @@ set_trace_func nil } } + /// + /// A fiber's block keeps its own $~ and $_ (MRI's ec->root_svar), as a thread's does, rather than sharing the frame + /// it was written in; its arguments, a lambda's arity and break/return behave as Proc#call's. + /// + public void Fiber_OwnSpecialVariables1() { + TestOutput(@" +require 'ruby4' +f = ->(s) { Fiber.new { s =~ /(\w)/; Fiber.yield; $~[1] } } +a, b = f.(""x""), f.(""y""); a.resume; b.resume +p [a.resume, b.resume] +q = Queue.new +ts = %w[p q].map { |s| Thread.new { s =~ /(\w)/; q.pop; $~[1] } } +sleep 0.2; 2.times { q << 1 } +p ts.map(&:value) +""m"" =~ /(\w)/ +p Thread.new { $~ }.value, Fiber.new { $~ }.resume, $~[1] +def meth = Fiber.new { ""k"" =~ /k/; $~ }.resume.to_s + ($~ ? ""set"" : ""nil"") +p meth +p Fiber.new(&->(a) { a }).resume([1, 2]), Fiber.new { |a, b| [a, b] }.resume([1, 2]), Fiber.new { |*a| a }.resume(1, 2, 3, 4, 5) +p((Fiber.new(&->(a, b) { a }).resume(1) rescue $!.class)) +e = Enumerator.new { |y| ""a"" =~ /(a)/; y << $1; y << $~[1] } +p e.next, e.next +""z"" =~ /z/ +p [1, 2].each_slice(1).next, $~[0] +f = Fiber.new { r = (return 5 rescue $!.class); r } +p f.resume +p Fiber.new { break 3 }.resume rescue p $!.class +", @" +[""x"", ""y""] +[""p"", ""q""] +nil +nil +""m"" +""knil"" +[1, 2] +[1, 2] +[1, 2, 3, 4, 5] +ArgumentError +""a"" +""a"" +[1] +""z"" +LocalJumpError +LocalJumpError +"); + } + public void Fiber_ReclamationClrBoundary1() { FiberReclaimInterop.Reset(); Context.ObjectClass.SetConstant("FiberReclaimInterop", Context.GetClass(typeof(FiberReclaimInterop))); diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index 7510e4516..839a24767 100644 --- a/Src/Libraries/Builtins/ProcOps.cs +++ b/Src/Libraries/Builtins/ProcOps.cs @@ -218,6 +218,20 @@ public static RubyArray GetSourceLocation(Proc/*!*/ self) { #region call, [], ===, yield + /// The prelude's Fiber runs its block through this: see Proc.CallAsRoot. + [RubyMethod("__ir_call_as_root__", RubyMethodAttributes.PrivateInstance)] + [RubyStackTraceHidden] + [ReceivesKeywords] + public static object CallAsRoot(Proc/*!*/ self, params object[]/*!*/ args) { + // a lambda's arity, as #call checks it + if (args.Length == 0) { + RubyOps.RequireLambdaArity(self, 0); + } else { + RubyOps.RequireLambdaArity(self, args.Length, args[args.Length - 1]); + } + return self.CallAsRoot(args); + } + [RubyMethod("==="), RubyMethod("[]"), RubyMethod("yield"), RubyMethod("call")] [RubyStackTraceHidden] public static object Call(BlockParam block, Proc/*!*/ self) { diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index ba80774af..2af73719a 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -535,6 +535,33 @@ public object Call(Proc procArg, params object[]/*!*/ args) { return result; } + /// + /// Calls the proc as the root of a fiber: like #call, but the block's frame keeps its own $~ and $_ (the fiber's + /// root svar in MRI), as a thread's block does, instead of sharing the frame it was written in. + /// + public object CallAsRoot(object[]/*!*/ args) { + var blockParam = RubyOps.CreateBfcForProcCall(this); + blockParam.IsThreadRoot = true; + try { + object result; + switch (args.Length) { + case 0: result = RubyOps.Yield0(null, _self, blockParam); break; + // as #call: a lambda does not splat its one argument + case 1: result = (Kind == ProcKind.Lambda) ? RubyOps.YieldNoAutoSplat1(args[0], null, _self, blockParam) : + RubyOps.Yield1(args[0], null, _self, blockParam); break; + case 2: result = RubyOps.Yield2(args[0], args[1], null, _self, blockParam); break; + case 3: result = RubyOps.Yield3(args[0], args[1], args[2], null, _self, blockParam); break; + case 4: result = RubyOps.Yield4(args[0], args[1], args[2], args[3], null, _self, blockParam); break; + default: result = RubyOps.YieldN(args, null, _self, blockParam); break; + } + return RubyOps.MethodProcCall(blockParam, result); + } catch (LambdaUnwinder unwinder) when (unwinder.Target == blockParam) { + return unwinder.ReturnValue; + } finally { + blockParam.IsActiveLambdaCall = false; + } + } + public object CallN(Proc procArg, object[]/*!*/ args) { Debug.Assert(args.Length > 4); var blockParam = RubyOps.TakeBfcForProcCall(this); diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 02162dc71..8d33ba931 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3318,7 +3318,8 @@ def __run__ ::Thread.handle_interrupt(::Object => :immediate) do case msg.kind when MSG_RESUME, MSG_TRANSFER - result = @block.call(*msg.payload) + # as the fiber's root: the block keeps its own $~ and $_, as MRI's fiber does (ec->root_svar) + result = @block.__send__(:__ir_call_as_root__, *msg.payload) else __act__(msg) end From ba596fa593e188fefee634ce1202599032a56e35 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:46:49 +0000 Subject: [PATCH 282/439] LEDGER: perf/crubydiff's seventh round Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8a9e097c7..36ae3c1a8 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -3094,6 +3094,22 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has FloatDomainError); sort_by no longer calls Array#<<; Method#unbind's owner for a visibility forwarder; Proc#source_location of a method's to_proc; Method#source_location and #inspect of core methods (C# ones now have CRuby's location; prelude ones CRuby's line). + Seventh round (2026-11-28, on claude/happy-gauss-95wm2j 50b07b5 + the sixth): + - A string instance_eval/class_eval shares its caller's $~ and $_ (RubyClosureScope.ShareSpecialVariablesOf on + the module-eval scope). Eval_InstanceEvalSpecialVariables1. + - A call on a later line of a multi-line statement reports its own line (the line of its name, prism's + message_loc): the generator tracks the frame's line (ScopeBuilder.CurrentLine) and wraps a MethodCall on another + line in a sequence point and SourceLineMarker before it and back after it (AstGenerator.AddCallLine); a statement + on one line gets nothing, nor does a call where the line is unknown. Free in the interpreter; a store per such call + in compiled frames, multi-line statements only; the method JIT and light frames report the lines with it. + IR_CALL_LINES=0 turns it off. ab.rb -r 8, base / new / off: frame-cost new/base 0.93-1.09, app-shapes' steady shapes + (json_parse, invoice_build, render, rules, query_aggregate, set, time, pp) 0.96-1.06, the noisy ones overlapping. + caller-matrix's eval row now same. Backtrace_CallLine1. + - A fiber's block keeps its own $~ and $_ (ec->root_svar), as a thread's: the prelude's Fiber calls its block through + Proc#__ir_call_as_root__ with a BlockParam marked as a root. Fiber_OwnSpecialVariables1. + For the gate: $~/$_ inside string instance_eval/class_eval are the caller's; backtrace, caller, binding and eval + file lines of calls in multi-line statements; fibers' $~/$_ are their own (a fiber no longer sees or sets its + creator's). - **perf/json (2026-11-27) - `case` over String literals looks its subject up once while String#=== is the library's (gap 7)** - not gated. Commit 0a78877 on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j 15285eb with 0518f08 merged in. Measured first: a perf profile of AWFY From e0ec29f520e78f242401ceadf1e302c8414b17d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:47:25 +0000 Subject: [PATCH 283/439] Ledger: perf/jitreparse measured, rejected (gap 26) The method JIT's re-parses of the startup library's methods: what they cost on the R2R host, why the parse is at the first call (the runtime screen and the profile need the AST), how often the stubs are called, and why none of the cheap fixes is worth it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3UZ2No6CbZeXnCbPA --- Util/perf/LEDGER.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a0273f587..2b0aa4fd3 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1652,6 +1652,14 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has transform of a process (4.1 ms for `-e 1`'s one character, a cold path), the JIT's re-parses of library methods (140 `def body: AST bridge` in irb), and fileutils.rb, tmpdir.rb and irb/completion.rb, still compiled from source (rescue re-raise frames, refinements). + 2026-11-28, perf/jitreparse (Rejected, measured only): the method JIT's re-parses of the startup + library's methods cost ~6 ms of `-e 1`'s parse phases (11 parses; -X:NoJIT 5.9 ms against 12.5) and + ~11 ms of irb's (133 parses), most of `-e 1`'s the cold first run of parser and bridge paths. The + parse is at the method's first call because the runtime screen needs the AST (its callees resolved + on the declaring module), and the profile the stub keeps from that call on needs the screen's + results. A third of the stubs are called once, so deferring to the second call saves at most ~2 ms + and ~4-5 ms, against a rework of the profiling path the JIT's decisions rest on. Not taken; see + Rejected. The first top-level transform's cold path is still the larger lead. 27. **Closed (perf/crubydiff, third round): `send` frames are hidden.** Was: **`send` with a String name leaves a `Kernel#send` frame in backtraces** that CRuby does not show (`[1].send("sum") { raise }`: IronRuby "Array#sum < Kernel#send", CRuby "Array#sum < "); with a Symbol it is right. Found by /perf-core's probes, not a @@ -8128,6 +8136,42 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitreparse (2026-11-28) - the method JIT's re-parses of the startup library's methods: measured, + no change** (gap 26). Base 33818f7 merged with 4405475 (perf/requirecold). + A method of the startup library that the JIT may specialize keeps its def's source (AotCompiler.JitSource, + only for a method the static screen takes). RubyMethodBody parses it at the method's first call + (PrecompiledCode.ParseJitSource) and hands the AST to JitStub.Wrap. + - Cost, R2R host, IR_PHASE_TIMES (prism parse, load, AST bridge, def-body bridge; five runs): + | | JIT parses | parse phases | with -X:NoJIT | + |---|---|---|---| + | `-e 1` | 11 | 12.5 ms | 5.9 ms | + | `gem --version` | 51 | | | + | `gem list` | 78 | | | + | `require "irb"` | 69 | | | + | irb `1+1` | 133 | 33-35 ms | 20-25 ms | + A warm re-parse is ~0.08 ms. `-e 1`'s ~0.5 ms each is the first run of the parser's and bridge's paths + for defs, which nothing after pays in `-e 1`. + - What the AST is for at the first call: Wrap's Screen, whose verdict depends on the running program + (IsLeafMethod and IsCallableMethod resolve the body's callees on the declaring module, constant guards + are folded). It cannot be computed ahead of time: irb screens out 33 of its 133 at run time, all + accepted by the static screen. And the screen's results (keywords, literal defaults, per-count + bodies, the typed arity) are what Profile needs from the first call on. + - Of the stubs made, how often each was called while profiling (a throwaway counter, Release build): + `-e 1` 8 stubs, 4 once; `gem --version` 36, 22 once; `gem list` 53, 17 once; `require "irb"` 50, 19 + once; irb 92, 31 once (12 reached the threshold of 40). + - The candidates: + - Deferring the parse to the second call: Observe needs only a CLR type, an immediate class and a + numeric kind per argument, so the first call could be kept as tokens and replayed. But it skips only + the once-called methods' parses, ~2 ms of `-e 1` and ~4-5 ms of irb (the cold costs fall on whichever + parse comes first), for a rework of the trampolines (a stub without an AST, per arity) and of Profile. + Those decide what the JIT specializes. Not worth it. + - Wrapping without screening: a method the screen would decline would keep the trampoline for life, in + the call sites' rules (Wrap's own comment): slower code, and other decisions. + - Parsing each file once: ruby4.rb's methods are among the parsed, and the file is 11,000 lines. + - A serialized AST in the library: a serializer for every node kind, to save at most ~1-2% of start-up. + Next lead instead: the cold path of the first top-level transform (4.1-4.8 ms for `-e 1`'s one-character + script). + - **perf/stagea (round thirty-seven, 2026-11-28) - stage A of `Docs/block-calling-convention.md`, a narrow literal given to a `[BlockNotKept]` iterator as a block descriptor: simulated, not built** (gap 13). Before the matrix or the compiler work, the harness (`IronRuby.Tests /blockcost`, now with bytes per From 4e87b11393af0c10e8fac95713afb9fc6ed4745a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:47:53 +0000 Subject: [PATCH 284/439] A named block that a method only passes on stays reusable `def each(&b) = @items.each(&b)' (som.rb's SomSet#each, has_some, get_one; some 320 methods of the standard library) converted its block for good (EnterLightMethodNamingBlock: ConvertAsMethodFrame), since a method that names its block can keep it. So no caller passing a literal to such a method could make its Proc again or park its scope: Havlak's `SomSet#contains', `add' and their callers made a method scope, a Proc and BlockParams on every call. A method whose block parameter is only passed on (JitStub.BlockParameterOnlyPassed: `&b' arguments and nothing else, no yield, no super) now converts a literal block as it did but reusable (Proc.ConvertAsPassingMethodFrame, RubyOps.EnterLightMethodPassingBlock), and each call it passes the block to holds it (Proc.PassHeldFlag: not reusable while set; RubyOps.HoldPassedBlock). The receivers known to keep nothing lift the hold as they take the block: a light frame that only yields (EnterLightMethodWithBlock), a [BlockNotKept] library method (CreateBfcForBlockNotKept), and another method that only passes it on. When the call returns, a hold that is still set means the receiver was something else - a method that names or stores the block, a library method that may keep it (Hash.new, define_method, Enumerator.new), a CLR method, anything the binder hands a Proc to - and the block is made not reusable for good (RubyOps.EndPassedBlock). An exception or a break out of the call leaves the hold set: not reusable. A light frame that makes its scope holds the block until the scope is parked, as before. IR_PASSED_BLOCKS=0 converts it for good as before. Util/passed-block-matrix.rb (new) prints what CRuby 4.0 prints with the switch on and off, IR_PARKED_SCOPES=0, -X:NoJIT -X:NoOSR and on the base. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Builtins/Proc.cs | 41 ++++- .../Ast/Definitions/MethodDefinition.cs | 14 +- .../Compiler/Ast/Expressions/MethodCall.cs | 26 +++ Src/Ruby/Compiler/AstGenerator.cs | 4 + Src/Ruby/Runtime/BlockParam.cs | 2 + Src/Ruby/Runtime/RubyOps.cs | 37 +++++ Util/passed-block-matrix.rb | 151 ++++++++++++++++++ 7 files changed, 273 insertions(+), 2 deletions(-) create mode 100644 Util/passed-block-matrix.rb diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index 004a87698..c96f1e924 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -81,7 +81,17 @@ public partial class Proc : RuntimeFlowControl, IDuplicable { // reusable when its callee's scope is parked (`c.each { }' where `def each; (a..b).each { |i| yield @s[i] }; end'). // A call that does not park, an exception, any other clear of ReusableFlag leave the proc not reusable, as they did. private const int HeldFlag = 32; - private const int ReusableMask = ReusableFlag | HeldFlag; + + // A method that only passes its named block on (`def each(&b) = @items.each(&b)', JitStub.BlockParameterOnlyPassed) is + // handing it to a call (RubyOps.HoldPassedBlock): not reusable while set. A receiver known to keep nothing - a light frame + // that only yields, a [BlockNotKept] library method, another method that only passes it on - lifts it as it takes the + // block (ConfirmPass); any other receiver leaves it, and the passing method then clears ReusableFlag for good once the + // call returns (RubyOps.EndPassedBlock). An exception out of the call leaves it set: not reusable. + private const int PassHeldFlag = 64; + private const int ReusableMask = ReusableFlag | HeldFlag | PassHeldFlag; + + /// IR_PASSED_BLOCKS=0: a method's named block is converted for good, as it was, even if the method only passes it on. + internal static readonly bool PassedBlocksEnabled = Environment.GetEnvironmentVariable("IR_PASSED_BLOCKS") != "0"; /// IR_SCOPE_HELD_BLOCKS=0: a light-frame method's scope clears its block's ReusableFlag for good, as it did. internal static readonly bool ScopeHeldBlocksEnabled = Environment.GetEnvironmentVariable("IR_SCOPE_HELD_BLOCKS") != "0"; @@ -152,6 +162,35 @@ internal void ConvertAsMethodFrame() { _activeFlowControlScope = this; } + /// + /// ConvertAsMethodFrame of a literal block for a light-frame method that only passes it on (RubyOps.EnterLightMethodPassingBlock): + /// reusable as a light frame's literal is (ConvertAsLightFrame) unless a call it is passed to may keep it (PassHeldFlag). + /// + internal void ConvertAsPassingMethodFrame() { + _kind = ((_dispatcher.ReusesProc && TracePoint.ActiveEvents == 0) + ? (int)ProcKind.Proc | SelfConverterFlag | MethodConverterFlag | ReusableFlag + : (int)ProcKind.Proc | SelfConverterFlag | MethodConverterFlag) | (_kind & HeldFlag); + _activeFlowControlScope = this; + } + + /// The block is being passed to a call by a method that only passes it on (see PassHeldFlag). + internal void HoldForPass() { + _kind |= PassHeldFlag; + } + + /// The receiver of a passed block keeps nothing (see PassHeldFlag). + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + internal void ConfirmPass() { + _kind &= ~PassHeldFlag; + } + + /// The call a passed block was given to returned: if its receiver did not confirm the pass, it may keep the block. + internal void EndPass() { + if ((_kind & PassHeldFlag) != 0) { + _kind &= ~(PassHeldFlag | ReusableFlag); + } + } + /// /// True if a Ruby method's light frame converted this proc (ConvertAsMethodFrame), rather than a library method's call. /// diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index ca6f57acd..adad49fa8 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -238,6 +238,8 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin gen.CurrentMethod.FrameLabel = frameLabel; gen.CurrentMethod.HasOwnCompiledFrame = true; gen.CurrentMethod.ForwardedRestSplat = ForwardedRest.Find(_parameters, Body); + gen.CurrentMethod.PassedBlock = (IronRuby.Builtins.Proc.PassedBlocksEnabled && _parameters.Block != null && + IronRuby.Runtime.Jit.JitStub.BlockParameterOnlyPassed(this)) ? _parameters.Block : null; // The literals of the body take their Procs from this slot if the body turns out to park its scope (below). if (ParkedScopesEnabled && allowLightFrame && _parameters.Block == null && definitionRefinements == null && gen.Profiler == null && @@ -801,8 +803,16 @@ private sealed class LightFrame { /// internal bool NamesBlock; + // The method only passes its named block on (AstGenerator.MethodScope.PassedBlock). + internal bool PassesBlock; + + private static readonly MethodInfo/*!*/ _EnterLightMethodPassingBlock = typeof(RubyOps).GetMethod("EnterLightMethodPassingBlock"); + private MSA.Expression/*!*/ EnterMethod { - get { return NamesBlock ? Ast.Call(_EnterLightMethodNamingBlock, _blockParameter) : Methods.EnterLightMethod.OpCall(_blockParameter); } + get { + return PassesBlock ? Ast.Call(_EnterLightMethodPassingBlock, _blockParameter) : + NamesBlock ? Ast.Call(_EnterLightMethodNamingBlock, _blockParameter) : Methods.EnterLightMethod.OpCall(_blockParameter); + } } private MSA.Expression/*!*/ StackCheck { @@ -1744,6 +1754,8 @@ private LightFrame TransformLightFrame(AstGenerator/*!*/ gen, ScopeBuilder/*!*/ light._blockParameter = blockParameter; // super hands the method's block on as `&b' would (SuperCall.TransformReadCore) light.NamesBlock = _parameters.Block != null || gen.CurrentMethod.HasSuperCall; + // (a block it only passes on may stay reusable: RubyOps.EnterLightMethodPassingBlock) + light.PassesBlock = gen.CurrentMethod.PassedBlock != null && !gen.CurrentMethod.HasSuperCall; var shape = Ast.Constant(new MethodFrameShape((string[])names.Value, visibleParameterCountAndSignatureFlags, _name)); Func make = (method, locals) => method.OpCall(new AstExpressions { diff --git a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs index e414457cc..21bb05efe 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs @@ -163,6 +163,12 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { blockArgVariable = transformedBlock = null; } + // `&b' of a method that only passes its block b on: held for the call (RubyOps.HoldPassedBlock, Proc.PassHeldFlag) + bool passesBlock = block != null && !block.IsDefinition && IsPassedBlock(gen, ((BlockReference)block).Expression); + if (passesBlock) { + transformedBlock = Ast.Call(_HoldPassedBlock, AstUtils.Convert(transformedBlock, typeof(Proc))); + } + var siteBuilder = new CallSiteBuilder(gen, transformedTarget, blockArgVariable); // `recv.m(args, &blk)': MRI evaluates the receiver and the arguments - expanding a @@ -246,6 +252,16 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { "#RB: method call with a block ('" + methodName + "')"); } + if (passesBlock) { + // the receiver took the block and the call returned: unless the receiver confirmed it, the block is not reusable + var passResult = gen.CurrentScope.DefineHiddenVariable("#pass-result", typeof(object)); + result = Ast.Block( + Ast.Assign(passResult, AstUtils.Convert(result, typeof(object))), + Ast.Call(_EndPassedBlock, AstUtils.Convert(blockArgVariable, typeof(Proc))), + passResult + ); + } + if (assignmentRhsArgument != null) { result = Ast.Block(result, rhsVariable); } @@ -253,6 +269,16 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { return result; } + private static readonly System.Reflection.MethodInfo/*!*/ _HoldPassedBlock = typeof(RubyOps).GetMethod("HoldPassedBlock"); + private static readonly System.Reflection.MethodInfo/*!*/ _EndPassedBlock = typeof(RubyOps).GetMethod("EndPassedBlock"); + + // `&b' where b is the block parameter of a method that only passes it on (AstGenerator.MethodScope.PassedBlock) + private static bool IsPassedBlock(AstGenerator/*!*/ gen, Expression/*!*/ expression) { + var passed = gen.CurrentMethod.PassedBlock; + var local = expression as LocalVariable; + return passed != null && local != null && local.Name == passed.Name && local.DefinitionLexicalDepth == passed.DefinitionLexicalDepth; + } + /// /// A block argument whose evaluation runs no Ruby code, so that a splatted list cannot change before its #to_proc: /// CRuby 4.0 passes such a call's trailing splat uncopied (prism_compile.c, pm_setup_args_dup_rest_p, which also counts diff --git a/Src/Ruby/Compiler/AstGenerator.cs b/Src/Ruby/Compiler/AstGenerator.cs index fb842a6dd..8c2a1a924 100644 --- a/Src/Ruby/Compiler/AstGenerator.cs +++ b/Src/Ruby/Compiler/AstGenerator.cs @@ -476,6 +476,10 @@ public Parameters Parameters { // The slot the method's literals take their parked Procs from (BlockDefinition), set by MethodDefinition before the // body is transformed if the method may have one at all; it is disabled afterwards if the body turns out not to qualify. internal ParkedScopeSlot ParkSlot; + + // The method's block parameter, if the method only passes it on (JitStub.BlockParameterOnlyPassed, IR_PASSED_BLOCKS): + // each call it is passed to holds it until the receiver confirms that it keeps nothing (MethodCall, RubyOps.HoldPassedBlock). + internal LocalVariable PassedBlock; internal readonly List ParkProcVariables = new List(); // the ParkedProcs the call took (RubyOps.TakeParkedScope), or null internal MSA.ParameterExpression ParkedVariable; diff --git a/Src/Ruby/Runtime/BlockParam.cs b/Src/Ruby/Runtime/BlockParam.cs index 902623393..ecd0770e1 100644 --- a/Src/Ruby/Runtime/BlockParam.cs +++ b/Src/Ruby/Runtime/BlockParam.cs @@ -527,6 +527,8 @@ public static bool IsProcConverterTarget(BlockParam/*!*/ bfc, MethodUnwinder/*!* public static BlockParam/*!*/ CreateBfcForBlockNotKept(Proc/*!*/ proc) { Assert.NotNull(proc); if (proc.Kind != ProcKind.Block) { + // a block another method passes on is not kept here either (Proc.PassHeldFlag) + proc.ConfirmPass(); return new BlockParam(proc, BlockCallerKind.Yield, false); } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index b1539fc42..a651ad564 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -515,9 +515,46 @@ private static bool TryParkDeeper(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ pa blockParameter.ConvertAsLightFrame(); return blockParameter; } + // and one another method passed on to it is not kept by it either (Proc.PassHeldFlag) + blockParameter.ConfirmPass(); return InactiveRfc; } + /// + /// EnterLightMethodNamingBlock of a method that only passes its block on (JitStub.BlockParameterOnlyPassed, IR_PASSED_BLOCKS): + /// a literal block stays reusable unless a call it is passed to may keep it (Proc.PassHeldFlag, HoldPassedBlock, + /// EndPassedBlock); one another method passed on to it is confirmed, as this one passes it on in the same way. + /// + public static RuntimeFlowControl/*!*/ EnterLightMethodPassingBlock(Proc blockParameter) { + RubyUtils.SafePoint(); + if (blockParameter != null) { + if (blockParameter.Kind == ProcKind.Block) { + blockParameter.ConvertAsPassingMethodFrame(); + return blockParameter; + } + blockParameter.ConfirmPass(); + } + return InactiveRfc; + } + + /// + /// The block argument `&b' of a call in a method that only passes its block b on: held until the receiver confirms that it + /// keeps nothing (Proc.PassHeldFlag). + /// + public static Proc HoldPassedBlock(Proc block) { + if (block != null) { + block.HoldForPass(); + } + return block; + } + + /// The call HoldPassedBlock passed the block to returned (Proc.EndPass). + public static void EndPassedBlock(Proc block) { + if (block != null) { + block.EndPass(); + } + } + /// /// The name the method was called by when that was an alias (CreateMethodScope keeps it in the /// scope; a light frame keeps it for the scope it may make). Taken either way, as CreateMethodScope does. diff --git a/Util/passed-block-matrix.rb b/Util/passed-block-matrix.rb new file mode 100644 index 000000000..dd8ed0aed --- /dev/null +++ b/Util/passed-block-matrix.rb @@ -0,0 +1,151 @@ +# Differential matrix for a named block that a method only passes on (IR_PASSED_BLOCKS: RubyOps.EnterLightMethodPassingBlock, +# HoldPassedBlock, EndPassedBlock; Proc.PassHeldFlag): `def each(&b) = @items.each(&b)'. The caller's literal stays reusable - +# made again for the caller's next call, and its scope parked - unless a call it was passed to may keep it. Each case runs a +# caller hot, so that its literal is reused when it may be, around the call that keeps the block, and then looks at what was +# kept: it must be the block of the call that kept it - its locals, its self, its identity. Run it under CRuby and under ./ir.sh +# with the switch on and off and with the tiers off, and diff: +# +# ruby Util/passed-block-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/passed-block-matrix.rb > /tmp/on.txt +# IR_PASSED_BLOCKS=0 ./ir.sh Util/passed-block-matrix.rb > /tmp/off.txt +# IR_PARKED_SCOPES=0 ./ir.sh Util/passed-block-matrix.rb > /tmp/noparked.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/passed-block-matrix.rb > /tmp/notiers.txt + +def t(label) + print label.ljust(64), ' => ' + begin + v = yield + puts "#{v.inspect} (#{v.class})" + rescue Exception => e + puts "#{e.class}: #{e.message}" + end +end + +N = 3000 + +class Store + def initialize; @items = [1, 2, 3]; @saved = []; end + attr_reader :saved + def each_yield; @items.each { |x| yield x }; end # a light frame that only yields + def keep(&b); @saved << b; nil; end # keeps it + def given?; block_given?; end + def ident(&b); b; end +end + +class Pass + def initialize(s); @s = s; end + def each(&b) = @s.each_yield(&b) # passes it to one that only yields + def each_lib(&b) = [1, 2].each(&b) # to a [BlockNotKept] library method + def keep(&b) = @s.keep(&b) # to one that keeps it + def maybe_keep(k, &b); k ? @s.keep(&b) : @s.each_yield(&b); end # to one or the other + def given(&b) = @s.given?(&b) + def ident(&b) = @s.ident(&b) + def hash_default(&b) = Hash.new(&b) # a library method that keeps it + def define(name, &b) = self.class.send(:define_method, name, &b) + def enum(&b) = Enumerator.new(&b) + def chain(&b) = Pass.new(@s).each(&b) # through another method that only passes it on + def chain_keep(&b) = Pass.new(@s).keep(&b) +end + +class Caller + def initialize(p); @p = p; @n = 0; end + def sum; c = 0; @p.each { |x| c += x }; c; end + def sum_lib; c = 0; @p.each_lib { |x| c += x }; c; end + def keep(n); @p.keep { [n, self.class] }; end + def maybe(n); c = 0; @p.maybe_keep(n % 1000 == 7) { |*x| c += 1; [n, c] }; c; end + def given; @p.given { 1 }; end + def ident(n); @p.ident { n }; end + def hdef(n); @p.hash_default { |h, k| [n, k] }; end + def enum(n); @p.enum { |y| y << n; y << n + 1 }; end + def chain; c = 0; @p.chain { |x| c += x }; c; end + def chain_keep(n); @p.chain_keep { n * 2 }; end + def brk; @p.each { |x| break x * 100 if x == 2 }; end +end + +t('passed to a light frame that only yields, hot') { s = Store.new; c = Caller.new(Pass.new(s)); r = 0; N.times { r += c.sum }; r } +t('passed to a [BlockNotKept] library method, hot') { c = Caller.new(Pass.new(Store.new)); r = 0; N.times { r += c.sum_lib }; r } +t('passed through two methods, hot') { c = Caller.new(Pass.new(Store.new)); r = 0; N.times { r += c.chain }; r } + +t('kept by the receiver: every kept block is its own call\'s') { + s = Store.new + c = Caller.new(Pass.new(s)) + N.times { |n| c.keep(n) } + s.saved.map(&:call).values_at(0, 1, 1500, -1) + [s.saved.map(&:object_id).uniq.size] +} +t('kept on some calls only') { + s = Store.new + c = Caller.new(Pass.new(s)) + N.times { |n| c.maybe(n) } + s.saved.map { |b| b.call(:z) } +} +t('kept through a chain of passing methods') { + s = Store.new + c = Caller.new(Pass.new(s)) + N.times { |n| c.chain_keep(n) if n % 500 == 0; c.chain } + s.saved.map(&:call) +} +t('a Hash default proc kept by Hash.new') { + c = Caller.new(Pass.new(Store.new)) + hs = [] + N.times { |n| h = c.hdef(n); hs << h if n % 1000 == 1; c.sum } + hs.map { |h| h[:k] } +} +t('define_method with a passed block') { + pa = Pass.new(Store.new) + c = Caller.new(pa) + N.times { c.sum } + pa.define(:dm1) { |a| a * 3 } + N.times { c.sum } + [pa.dm1(4), Pass.instance_method(:dm1).arity] +} +t('Enumerator.new with a passed block') { + c = Caller.new(Pass.new(Store.new)) + es = [] + N.times { |n| es << c.enum(n) if n % 1000 == 2; c.sum } + es.map(&:to_a) +} +t('the block is the same object in both methods') { + pa = Pass.new(Store.new) + bl = proc { 1 } + [pa.ident(&bl).equal?(bl), Caller.new(pa).ident(5).call] +} +t('identity of a literal passed through, kept: distinct per call') { + c = Caller.new(Pass.new(Store.new)) + ids = Array.new(5) { |n| c.ident(n) } + [ids.map(&:call), ids.map(&:object_id).uniq.size, ids.map(&:lambda?).uniq] +} +t('block_given? in the receiver') { c = Caller.new(Pass.new(Store.new)); [c.given, Pass.new(Store.new).given] } +t('break from a passed block') { c = Caller.new(Pass.new(Store.new)); r = nil; N.times { r = c.brk }; r } +t('a Method passed as a block') { + pa = Pass.new(Store.new) + m = 10.method(:+) + r = [] + pa.each(&m) rescue r << :err + r << [1, 2].map(&m) + r +} +t('a lambda passed through') { + pa = Pass.new(Store.new) + l = ->(x) { x * 2 } + out = [] + pa.each { |x| out << x } + [pa.ident(&l).lambda?, (pa.each(&l) rescue :argerr), out] +} +t('an exception while the block is held') { + c = Caller.new(Pass.new(Store.new)) + errs = 0 + N.times { |n| begin; c.instance_variable_get(:@p).each { |x| raise 'x' if x == 3 && n % 500 == 0 }; rescue RuntimeError; errs += 1; end; c.sum } + [errs, c.sum] +} +t('threads passing blocks through one method') { + pa = Pass.new(Store.new) + ths = Array.new(4) { |ti| Thread.new { c = Caller.new(pa); r = 0; 2000.times { r += c.sum }; [ti, r] } } + ths.map(&:value) +} +t('threads: kept blocks while others pass') { + s = Store.new + pa = Pass.new(s) + ths = Array.new(4) { |ti| Thread.new { c = Caller.new(pa); 1000.times { |n| c.keep(n * 4 + ti) if n % 250 == 0; c.sum } } } + ths.each(&:join) + s.saved.map { |b| b.call[0] }.sort +} From de51cf89f0bcb7794c153c88d06f40636fe44bcc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:52:57 +0000 Subject: [PATCH 285/439] Make a **rest parameter the call's own keyword hash, not a copy of it A keyword call into a method with `**o' that the method JIT declines (its screen leaves out a keyword match that accepts a rest) cost about twice what CRuby pays: `def krest(k:, **o)' called `(k: 1)' 165 ns against 80. Besides the caller's hash and the interpreted prologue, RubyOps.MakeKeywordRest made the rest a new hash: a copy of the call's keyword hash without the declared keywords, on every call. The call's keyword hash is made for that one call - every hash marked as keyword arguments is (MakeKeywordArgumentsHash, `**h''s copy, the ruby2_keywords copies; a hash a library method stores comes out unmarked) - and the prologue has read the declared keywords from it before binding the rest. So MakeKeywordRest now takes it over when it is a plain, unfrozen, marked hash laid out as a keyword call's is (no bucket array): the entries of the declared keys are taken out in place (Hash.TryRemoveKeywordsInPlace) and the marks come off. Anything else is copied as before; IR_KWREST_TAKE=0 always copies. A parameterless super already copies a rest that is the given hash. By clock krest 144 -> 108 ns, onlyrest(**o) 140 -> 100 (CRuby 67, 77). Checked: new IronRuby.Tests Method_KeywordRestTakeover1 with CRuby 4.0's output; new rows in Util/kwsplat-forward-matrix.rb; the keyword, prologue, splat and entry matrices match CRuby in every mode and with the switches off (48 of 48); specs as on the base build; IronRuby.Tests in full on Debug. Util/perf/LEDGER.md has the profile and the numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 50 +++++++++++++++++++++++++ Src/Ruby/Builtins/Hash.Keywords.cs | 41 ++++++++++++++++++++ Src/Ruby/Runtime/RubyOps.cs | 16 ++++++++ Util/kwsplat-forward-matrix.rb | 24 ++++++++++++ Util/perf/LEDGER.md | 36 ++++++++++++++++++ 6 files changed, 168 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a2860a36c..5bfb23519 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1195,6 +1195,7 @@ public Tests(Driver/*!*/ driver) { Method_KeywordHashIntoRest1, Method_Ruby2KeywordsExplicitSplat1, Struct_Ruby2KeywordsHash1, + Method_KeywordRestTakeover1, Method_KeywordPrologue1, Method_LightFrameGlobal1, Method_LightFrameLexical1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 11ab0ca6b..63cf8bf81 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8544,6 +8544,56 @@ p S.new(x: 1, y: 2).to_a, S.new({x: 1}).to_a "); } + /// + /// A **rest parameter is the keyword hash the call made for itself, the declared keywords taken out in place + /// (RubyOps.MakeKeywordRest, IR_KWREST_TAKE): never a hash the caller holds - `**h' passes a copy - nor one another call + /// gets; its default and comparer as the copy had them. Expected output from CRuby 4.0. + /// + public void Method_KeywordRestTakeover1() { + TestOutput(@" +def kt_mut(k: 0, **o) = (o[:added] = k; o.delete(:z); o) +def kt_keep(**o) = o +class KtP; def m(k: 0, **o) = [k, o]; end +class KtZ < KtP; def m(k: 0, **o) = (o[:local] = 1; super); end +class KtE < KtP; def m(k: 0, **o) = (o[:local] = 1; eval('super')); end +h = {k: 1, z: 2} +p kt_mut(**h), h +p kt_mut(k: 3, z: 4, y: 5) +a = kt_keep(a: 1); b = kt_keep(a: 1); a[:x] = 1 +p a, b, a.equal?(b) +p send(:kt_mut, k: 1, z: 2, y: 3), method(:kt_mut).call(k: 1, y: 2) +p proc { |k: 0, **o| o[:p] = 1; o }.call(k: 1, y: 2) +p KtZ.new.m(k: 1, y: 2), KtE.new.m(k: 1, y: 2) +d = Hash.new(5).compare_by_identity; d[:y] = 1 +o = kt_keep(**d) +p o.default, o.compare_by_identity?, o.equal?(d) +f = {k: 1, y: 2}.freeze +p kt_mut(**f), f.frozen? +p kt_mut, kt_keep +p kt_mut(**{""s"" => 1, k: 2}) +", @" +{added: 1} +{k: 1, z: 2} +{y: 5, added: 3} +{a: 1, x: 1} +{a: 1} +false +{y: 3, added: 1} +{y: 2, added: 1} +{y: 2, p: 1} +[1, {y: 2, local: 1}] +[1, {y: 2, local: 1}] +5 +true +false +{y: 2, added: 1} +true +{added: 0} +{} +{""s"" => 1, added: 2} +"); + } + /// /// A method's keyword prologue (PrismAstBridge.LowerKeywords): which error wins when several things are wrong at once, /// and defaults run in order and only for omitted keywords (Util/kw-prologue-matrix.rb). diff --git a/Src/Ruby/Builtins/Hash.Keywords.cs b/Src/Ruby/Builtins/Hash.Keywords.cs index b41d5db03..f2e4dc678 100644 --- a/Src/Ruby/Builtins/Hash.Keywords.cs +++ b/Src/Ruby/Builtins/Hash.Keywords.cs @@ -127,6 +127,47 @@ internal void AppendUnlinked(object/*!*/ key, object value) { return result; } + /// + /// done to this hash itself, a keyword call's own (, + /// no bucket array yet): the entries whose keys are among (by identity) are taken out and the + /// rest slid down, keeping their order and hash codes. False, and nothing done, for a hash that has buckets. + /// + internal bool TryRemoveKeywordsInPlace(object/*!*/[]/*!*/ names) { + if (_buckets != null) { + return false; + } + Entry[] entries = _entries; + int count = _count; + int dst = 0; + for (int src = _start; src < count; src++) { + ref Entry e = ref entries[src]; + if (e.Next == TombstoneNext) { + continue; + } + object key = e.Key; + int j = 0; + while (j < names.Length && names[j] != key) { + j++; + } + if (j < names.Length) { + continue; + } + if (dst != src) { + entries[dst] = e; + } + dst++; + } + if (dst != count || _start != 0) { + Array.Clear(entries, dst, count - dst); + _count = dst; + _liveCount = dst; + _start = 0; + _version++; + _stamp++; + } + return true; + } + private bool AllKeysAreSymbols() { Entry[] entries = _entries; int count = _count; diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 89cee34b0..250b79750 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -2957,9 +2957,25 @@ public static object ShiftOptionalSplatArgument(object args, int postCount) { hash.IsKeywordArguments = false; return hash; } + // The keywords a call passed are a hash made for that one call (see NormalizeRestKeywords), which the prologue has + // read the declared keywords from already: it becomes the **rest itself, the declared keys taken out in place, + // rather than a copy of it - one allocation and copy fewer for every keyword call into a method with **rest + // (gap 38). Not the runtime's shared, frozen empty hash, a subclass's, or one with buckets (made otherwise). + if (KwRestTakeEnabled && hash.IsKeywordArguments && hash.GetType() == typeof(Hash) && !hash.IsFrozen && + hash.TryRemoveKeywordsInPlace(names)) { + hash.IsKeywordArguments = false; + hash.IsRuby2KeywordsHash = false; + return hash; + } return hash.CopyWithoutKeywords(names); } + /// + /// IR_KWREST_TAKE=0 makes a **rest parameter a copy of the call's keyword hash again, without the declared keywords, + /// instead of that hash itself (see MakeKeywordRest). + /// + internal static readonly bool KwRestTakeEnabled = Environment.GetEnvironmentVariable("IR_KWREST_TAKE") != "0"; + /// /// The argument a parameter of a method that declares no keyword parameters is about to /// be given. `f(a: 1)` there is a call that passes a positional Hash - Ruby 3 has no diff --git a/Util/kwsplat-forward-matrix.rb b/Util/kwsplat-forward-matrix.rb index 96d177a3b..0565b5952 100644 --- a/Util/kwsplat-forward-matrix.rb +++ b/Util/kwsplat-forward-matrix.rb @@ -173,3 +173,27 @@ def mg_raise(**o) = kwr(k: 1, **o.fetch(:h)) t("error raised inside a merge's operand") { |i| (mg_raise rescue [$!.class, $!.message]) } # (whether the merging method is in the backtrace: IronRuby's top frame is the Hash#merge #to_hash goes through, MRI's the method) t("backtrace of an error in a merged call") { |i| begin; mg_two(BadHash.new); rescue TypeError => e; e.backtrace_locations.map(&:label).include?("Object#mg_two"); end } + +# ---------------------------------------------------------------- 8. a **rest parameter is the call's own keyword hash (RubyOps.MakeKeywordRest, +# IR_KWREST_TAKE): it must never be a hash the caller, or anything else, still holds +def kt_mut(k: 0, **o) = (o[:added] = k; o.delete(:z); o) +def kt_keep(**o) = ($kept ||= []) << o +def kt_super_base(**o) = o +class KtP; def m(k: 0, **o) = [k, o]; end +class KtZ < KtP; def m(k: 0, **o) = (o[:local] = 1; super); end +class KtE < KtP; def m(k: 0, **o) = (o[:local] = 1; eval('super')); end +t("caller's **h is not the callee's o") { |i| h = {k: 1, z: 2}; r = kt_mut(**h); [r, h] } +t("caller's **h, no declared keys") { |i| h = {z: 2}; r = kt_keep(**h); r[-1][:x] = 1; $kept = nil; h } +t("literal keywords: o mutated, declared key gone") { |i| kt_mut(k: 3, z: 4, y: 5) } +t("each call's o is its own") { |i| $kept = nil; a = kt_keep(a: 1)[-1]; b = kt_keep(a: 1)[-1]; a[:x] = 1; [a, b, a.equal?(b)] } +t("o through send and method_missing") { |i| [send(:kt_mut, k: 1, z: 2, y: 3), MM.new.ghost(k: 1)] } +t("o through Method#call and a proc") { |i| [method(:kt_mut).call(k: 1, y: 2), proc { |k: 0, **o| o[:p] = 1; o }.call(k: 1, y: 2)] } +t("o through define_method") { |i| self.class.send(:define_method, :kt_dm) { |k: 0, **o| o[:d] = k; o } if i == 0; kt_dm(k: 2, y: 3) } +t("zsuper after o changed") { |i| KtZ.new.m(k: 1, y: 2) } +t("eval('super') after o changed") { |i| KtE.new.m(k: 1, y: 2) } +t("o keeps compare_by_identity and default") { |i| h = Hash.new(5).compare_by_identity; h[:y] = 1; o = kt_keep(**h)[-1]; $kept = nil; [o.default, o.compare_by_identity?, o] } +t("o from a frozen **h") { |i| h = {k: 1, y: 2}.freeze; [kt_mut(**h), h.frozen?] } +ruby2_keywords def r2k_fwd_mut(*a) = kt_mut(*a) +t("o from ruby2_keywords") { |i| r = r2k_fwd_mut(k: 1, y: 2); r } +t("o when no keywords given") { |i| [kt_mut, kt_keep[-1].tap { $kept = nil }] } +t("o with non-Symbol keys") { |i| kt_mut(**{"s" => 1, k: 2}) } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8843dda72..5e7cd6559 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1995,6 +1995,42 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kwbind (/perf-step, 2026-11-28) - a `**rest` parameter is the call's own keyword hash, the + declared keywords taken out in place** (gap 38; switch `IR_KWREST_TAKE`, on unless `=0`). Built on + 33818f7 (claude/happy-gauss-95wm2j) with d45083a0 merged. + - **Profile** (clock, Release, ns; CRuby in brackets): `def kopt(k: 0)` called `(k: 1)` 44 [30], + `def kreq(k:)` 44 [31] - the method JIT takes both, and what is left is the call (`pos(1)` 40 + [27]); so a declared-keywords-only callee already reads the call's pairs without paying for + them, and the round's first candidate has nothing to win. A callee with `**o` is what pays: + `krest(k:, **o)` 165 [80], `onlyrest(**o)` 155 [89] - the JIT's screen rejects them + (KeywordArgumentsTest; JitKeywords leaves out a Match that accepts a rest). Of `onlyrest`'s + 155: the caller's keyword hash ~43 (`poh({k: 1})` 83 against `pos` 40), the callee ~72 - its + prologue, and RubyOps.MakeKeywordRest's copy of the hash without the declared keywords. + - **What changed.** MakeKeywordRest takes the call's hash itself when it is one a keyword call + made (marked, a plain Hash, not frozen, no bucket array yet - CreateKeywordArguments' layout): + Hash.TryRemoveKeywordsInPlace slides the undeclared entries down over the declared ones, and the + marks come off. Every marked hash is made for one call (MakeKeywordArgumentsHash, `**h`'s copy, + the ruby2_keywords copies, a library's own; probed: a hash a library method stores, `[].push(k: + 1)`, comes out unmarked), and the prologue has read the declared keywords before it binds the + rest, so nothing else sees the hash change. PassOnKeywordRest already copies when rest is the + given hash (zsuper), and eval('super') reads rest. + - **Clock** (`ab.rb -r 8`, ns; CRuby / `IR_KWREST_TAKE=0` / on): `krest(k: 1)` 66.6 / 143.7 / + 108.0 (0.75), with an extra key 83.7 / 154.9 / 120.0 (0.77), `onlyrest(k: 1)` 76.6 / 140.0 / + 99.7 (0.71), `krest_u` (reads o) 72.3 / 147.4 / 127.9 (0.87, overlapping); the controls + unchanged within their spreads. + - **Checks.** IronRuby.Tests Method_KeywordRestTakeover1 (CRuby 4.0's output: the caller's `**h` + untouched, each call's own o, send, Method#call, a proc, zsuper and eval('super') after o + changed, default and compare_by_identity kept, a frozen `**h`, no keywords, non-Symbol keys). + New rows in Util/kwsplat-forward-matrix.rb (the same, plus method_missing, define_method, + ruby2_keywords). kwsplat-forward, keyword-light, keyword-rest-light, kw-prologue, splat-pass, + kwrest-call, light-entry and hot-shapes: same as CRuby in default, `IR_KWREST_TAKE=0`, + `IR_LIGHT_KEYWORD_SPLAT=0`, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` (48 of + 48). Specs language/keyword_arguments, def, send, super, method, core/hash and + core/kernel/send as on the base build. IronRuby.Tests in full (Debug): PASSED, 1,418. + - **Left.** Still ~1.5x CRuby: the caller's keyword hash, and the interpreted prologue of a + method the JIT declines. Next: let JitKeywords take a Match that accepts a rest, binding the + rest with the same take-over. + - **perf/kwsplatlight (/perf-frame, 2026-11-28) - `f(k: v, **h)` and `f(**a, **b)` in light frames; a Struct stores a ruby2_keywords Hash as given** (switch `IR_LIGHT_KEYWORD_SPLAT`, which already covered the lone `f(**h)`). Built on 33818f7 (claude/happy-gauss-95wm2j) with 78a731ca merged; From 715610ff30ca75bbd1c942b4b2659de8a037dba9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:54:34 +0000 Subject: [PATCH 286/439] parked-scope-matrix: two threads passing literals through a method that only passes its block on Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/parked-scope-matrix.rb | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Util/parked-scope-matrix.rb b/Util/parked-scope-matrix.rb index ca6b03773..8aa5e0faa 100644 --- a/Util/parked-scope-matrix.rb +++ b/Util/parked-scope-matrix.rb @@ -208,4 +208,30 @@ def big(n); s = 0; (2**64 + n).downto(2**64) { |i| s += 1 }; s; end t('downto over Bignums') { |i| pdt.big(3) } t('two threads recurse in the same method') { |i| a = PsPerm.new; b = PsPerm.new; [Thread.new { a.permute(4); a.count }, Thread.new { b.permute(4); b.count }].map(&:value) } t('downto without a block') { |i| 3.downto(1).to_a } + +# a caller whose literal goes through a method that only passes it on (IR_PASSED_BLOCKS), on two threads at once +class PsPassVec + def initialize(n); @a = Array.new(n) { |k| k + 1 }; end + def each = @a.each { |x| yield x } +end +class PsPassSet + def initialize(n); @v = PsPassVec.new(n); end + def each(&b) = @v.each(&b) +end +class PsPassCaller + def initialize(s, tag); @s = s; @tag = tag; @kept = []; end + attr_reader :kept + def sum(k); c = 0; @s.each { |x| c += x * k }; c; end + def keep(k); @s.each { |x| @kept << proc { [@tag, k, x] } if x == 1 }; @kept.size; end +end +t('two threads pass literals through one passing method') { |i| + s = PsPassSet.new(4) + [Thread.new { c = PsPassCaller.new(s, :a); (1..500).sum { |k| c.sum(k) } }, Thread.new { c = PsPassCaller.new(s, :b); (1..500).sum { |k| c.sum(k + 1) } }].map(&:value) +} +t('two threads, Procs kept inside the passed literal') { |i| + s = PsPassSet.new(3) + cs = [PsPassCaller.new(s, :a), PsPassCaller.new(s, :b)] + cs.each_with_index.map { |c, ti| Thread.new { 300.times { |k| c.keep(k * 2 + ti) } } }.each(&:join) + cs.map { |c| [c.kept.size, c.kept.first.call, c.kept.last.call] } +} puts 'end' From 4d5cfd45c5cf9c1e4e7bc41377dee9eb430ffa3f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:02:07 +0000 Subject: [PATCH 287/439] Method JIT: take to_i, empty? and ! of objects; refuse x.call; hold back writes past index reads perf/jitisa let three methods past the screen that the compiler then declined in app-shapes: a wrap, a profile and a decline each. - `n.call` (Enumerator::Lazy#size): the screen took a no-argument `x.call` for a possible attribute read. Calling a Proc runs Ruby code, which a typed body never does, so the screen refuses it. (IR_JIT_SCREEN_CALL=0 lets it through again.) - `v.to_i`, `v.empty?` and `!v` of an untyped value (URI::Generic#set_port) now compile. `x.to_i` of an object is the Integer itself, 0 for nil, or the value of a plain ASCII-digit String of up to 18 digits, under a KernelMethodSite that checks the receiver's class resolves to the library method; anything else deopts. `x.empty?` answers for a String too, and `!x` is false for any object whose class resolves `!` to BasicObject's: it used to deopt for everything but true, false and nil (Gem::Dependency#runtime?, 304 deopts and nine retirements in app-shapes). (IR_JIT_OBJECT_OPS=0) - A deopt after an effect (CSV::Parser#prepare_variable): the index reads, type and identity tests throw nothing but a deopt and run no Ruby code, so a body may hold its instance-variable writes back past them; and a variable written as an object and as a boolean is held as an object on a second round. (IR_JIT_SINK_BOXED=0) app-shapes: specialized 121 -> 123, declined 32 -> 29, deopts 304 -> 0. Census: 9 methods maybe -> compiles, 4 maybe -> never (the x.call refusal, methods that could only be declined). Clock: no measurable change on app-shapes. Util/jit-objops-matrix.rb (new) and the jit, jit-calls, jit-const, jit-isa, unsampled, hot-shapes, hash-literal, jit-scan and inline matrices print what CRuby or the base does in every JIT mode; the touched ruby/specs and IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs | 13 +- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 20 +++ Src/Ruby/Runtime/Jit/JitCompiler.cs | 36 +++++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 45 ++++++ Src/Ruby/Runtime/Jit/JitRuntime.cs | 12 ++ Util/jit-objops-matrix.rb | 144 ++++++++++++++++++++ Util/perf/LEDGER.md | 45 ++++++ 7 files changed, 314 insertions(+), 1 deletion(-) create mode 100644 Util/jit-objops-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs index 793eef87a..75c53637a 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Objects.cs @@ -1341,7 +1341,7 @@ private bool IsLibraryHashFetch() { string name = node.MethodName; if (args.Length == 0) { - if (name != "empty?" && ObservedType(node.Target) == typeof(MutableString)) { + if (ObservedType(node.Target) == typeof(MutableString) && (name != "empty?" || ObjectOps)) { // `s.size', `s.length' on a parameter or instance variable the profile saw hold a String // (Json's `s.size', `@input.length'): String#length, the characters in the String's // encoding (JitRuntime.StringLength); a receiver that is not a plain String deopts. @@ -1349,6 +1349,11 @@ private bool IsLibraryHashFetch() { if (!IsPlainLibraryMethod(stringClass, name) || !IsPublic(stringClass, name)) { throw Bail("String#" + name + " is not the built-in one"); } + if (name == "empty?") { + // String#empty? (URI::Generic#set_port's `v.empty?'): no characters (JitRuntime.StringEmpty) + type = JT.Bool; + return Ast.Call(JitRuntime.M("StringEmpty"), recv); + } type = JT.Int; return Ast.Call(JitRuntime.M("StringLength"), recv); } @@ -1357,6 +1362,12 @@ private bool IsLibraryHashFetch() { RequireCollectionReceiver(node.Target, arrays, hashes, name); if (name == "empty?") { type = JT.Bool; + var stringClass = KindClass(JitRuntime.KindString); + if (ObjectOps && ObservedType(node.Target) == MixedTypes && IsPlainLibraryMethod(stringClass, name) && IsPublic(stringClass, name)) { + // a receiver the profile saw hold several types (a String, nil and an Integer in turn): a String + // answers as StringEmpty does, an Array or a Hash as IsEmpty does (JitRuntime.IsEmptyOrString) + return Ast.Call(JitRuntime.M("IsEmptyOrString"), recv, Ast.Constant(arrays), Ast.Constant(hashes)); + } return Ast.Call(JitRuntime.M("IsEmpty"), recv, Ast.Constant(arrays), Ast.Constant(hashes)); } type = JT.Int; diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index a39582636..cd943c6cd 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -76,6 +76,11 @@ private sealed class SunkIVar { // since each adds a name; a body that can never hold its writes may still spend one on a name first. internal HashSet _sinkWide; internal List _sinkWiden; + // Variables written as an object and as true or false (CSV::Parser#prepare_variable's `@backslash_quote = + // liberal_parsing[:backslash_quote]' and `= false'): held as an object, the boolean boxed as the generic body's + // SetIVar stores it, on another round (TryCompile), as _sinkWide holds an Integer as a long. + internal HashSet _sinkBoxed; + internal List _sinkBox; private SunkIVar FindSunk(string/*!*/ name) { if (_sunk != null) { @@ -109,6 +114,11 @@ private MSA.Expression TrySinkIVarWrite(SimpleAssignmentExpression/*!*/ node, st vt = JT.Lng; type = JT.Lng; } + if (vt == JT.Bool && _sinkBoxed != null && _sinkBoxed.Contains(name)) { + v = Coerce(v, JT.Bool, JT.Obj); + vt = JT.Obj; + type = JT.Obj; + } var sunk = FindSunk(name); if (sunk == null) { sunk = new SunkIVar { @@ -133,6 +143,11 @@ private MSA.Expression TrySinkIVarWrite(SimpleAssignmentExpression/*!*/ node, st } return null; } + if ((sunk.Type == JT.Obj && vt == JT.Bool || sunk.Type == JT.Bool && vt == JT.Obj) && JitCompiler.SinkBoxedBooleans && + (_sinkBoxed == null || !_sinkBoxed.Contains(name))) { + if (_sinkBox == null) { _sinkBox = new List(); } + if (!_sinkBox.Contains(name)) { _sinkBox.Add(name); } + } _sinkObstacle = "writes of " + name + " as " + sunk.Type + " and " + vt; return null; } @@ -289,6 +304,11 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { // an Array's or a Hash's count, a deopt on anything else (JitRuntime.SizeOf): no Ruby code and no instance // variable read; its receiver, read from self, is GetIVar's or a held write's "SizeOf", + // An Array's or a Hash's element (a key whose hash or eql? could be Ruby code, a default proc, a subclass + // deopt), a type or identity test (a class that resolves the method to anything but the library's deopts) and + // `x.to_i' of an Integer, nil or a plain decimal String: no Ruby code, no instance variable, nothing but a deopt + "IndexInt", "IndexLong", "IndexObj", "IndexIntChecked", "IndexLongChecked", "IndexObjChecked", "HashKeyInt", + "IsKindOf", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", }; // Integer#abs of an Int32 (widened, so it cannot overflow) and Float#abs (JitCompiler.EmitCall) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 26867bc8d..41ff6043a 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -595,6 +595,7 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ // such a body failed to compile and was declined where it used to be specialized. bool sinkStores = !HasWhileLoop(ast) && keywords == null && ast.Parameters.Optional.Length == 0; HashSet sinkWide = null; + HashSet sinkBoxed = null; bool initialIVarsOff = false; for (int round = 0; round < 5; round++) { var c = new JitCompiler(ast, context, paramTypes, keywords, supplied, constantScope); @@ -609,6 +610,7 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ c._noUnloggedEarlyWrites = !unloggedEarlyWrites; c._sinkStores = sinkStores; c._sinkWide = sinkWide; + c._sinkBoxed = sinkBoxed; c._noInitialIVars = initialIVarsOff; c._firstRound = (guess == JT.None); c._selfReturn = c._firstRound ? JT.Int : guess; @@ -658,6 +660,17 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ round--; continue; } + // a variable written as an object and as a boolean: another round holding it as an object + if (c._sinkBox != null) { + if (sinkBoxed == null) { sinkBoxed = new HashSet(); } + int known = sinkBoxed.Count; + sinkBoxed.UnionWith(c._sinkBox); + if (sinkBoxed.Count > known) { + if (JitRuntime.Verbose) { Console.Error.WriteLine("[jit] held as an object in {0}: {1}, written as an Obj and as a Bool", ast.Name, String.Join(" ", c._sinkBox)); } + round--; + continue; + } + } if (JitRuntime.Verbose) { Console.Error.WriteLine("[jit] stores not held back in {0}: {1}", ast.Name, c._sinkObstacle); } sinkStores = false; round--; @@ -2405,6 +2418,11 @@ private static JT Unify(JT a, JT b) { RequireBuiltin(JT.Bool, "!"); if (!IsPublicBuiltin(_context.NilClass, "!")) { throw Bail("operator ! on nil is not the built-in one"); } _canDeopt = true; + if (ObjectOps && _refinements.IsEmpty) { + // any other object: BasicObject#!, false, while its class resolves `!' to it (JitRuntime.NotObject) + var site = new JitRuntime.KernelMethodSite("!", LibraryMethods("!", _context.BasicObjectClass)); + return Ast.Call(JitRuntime.M("NotObject"), Ast.Constant(_context), value, Ast.Constant(site)); + } return Ast.Call(JitRuntime.M("NotBoolean"), value); } RequireBuiltin(operandType, "!"); @@ -2481,6 +2499,13 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { return Ast.Constant(false); } + // IR_JIT_OBJECT_OPS=0 leaves `x.to_i', `x.empty?' and `!x' of an object that is no number, Array, Hash, true, false or nil + // to the generic call, and IR_JIT_SCREEN_CALL=0 lets the screen take `x.call' for an attribute read, as they used to + internal static readonly bool ObjectOps = Environment.GetEnvironmentVariable("IR_JIT_OBJECT_OPS") != "0"; + // IR_JIT_SINK_BOXED=0: a variable written as an object and as a boolean is not held back (JitCompiler.Sink.cs) + internal static readonly bool SinkBoxedBooleans = Environment.GetEnvironmentVariable("IR_JIT_SINK_BOXED") != "0"; + internal static readonly bool ScreenRefusesCall = Environment.GetEnvironmentVariable("IR_JIT_SCREEN_CALL") != "0"; + // IR_JIT_TYPE_TEST=0 turns EmitTypeTest off internal static readonly bool TypeTests = Environment.GetEnvironmentVariable("IR_JIT_TYPE_TEST") != "0"; @@ -2697,6 +2722,13 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { type = JT.Lng; return Ast.Call(JitRuntime.M("FloatToLong"), t); } + // an object: Integer#to_i, String#to_i of a plain decimal String, NilClass#to_i (JitRuntime.ToIntegerObject) + if (tt == JT.Obj && _refinements.IsEmpty && ObjectOps) { + var site = new JitRuntime.KernelMethodSite("to_i", LibraryMethods("to_i", _context.IntegerClass, KindClass(JitRuntime.KindString), _context.NilClass)); + _canDeopt = true; + type = JT.Obj; + return Ast.Call(JitRuntime.M("ToIntegerObject"), Ast.Constant(_context), t, Ast.Constant(site)); + } throw Bail("to_i on " + tt); } @@ -4280,6 +4312,10 @@ private bool WalkCall(MethodCall/*!*/ node) { return Walk(node.Target) && (argc == 0 || Walk(args.Expressions[0])); } + // `x.call' (a Proc's, a Method's): no attribute reader is named so, and the call runs Ruby code, which a typed body + // does not; taken for a read, it made a method wrapped only to be declined (Enumerator::Lazy#size's `n.call'). + if (argc == 0 && node.Target != null && node.MethodName == "call" && JitCompiler.ScreenRefusesCall) { return No(node); } + if (argc == 0 && (node.Target == null || node.Target is SelfReference || node.Target is InstanceVariable || node.Target is LocalVariable) && !(node.Target == null && node.MethodName == _methodName && _arity == 0)) { // `x', `self.x', `@o.x', `o.x': an attr_reader read if the profile finds one (JitCompiler.EmitMethodAttrRead) diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index 94ca9eb78..7fdb23f7f 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -437,6 +437,39 @@ public static bool IsKindOf(RubyContext/*!*/ context, object value, object m, Ke return instanceOf ? module.Context.GetClassOf(value) == module : module.Context.IsKindOf(value, module); } + /// + /// `x.to_i' of an x the body holds as an object (JitCompiler, the `to_i' case): once the site found x's class (its + /// singleton class included) to resolve to_i to Integer's, String's or NilClass's library method, an Integer is + /// itself, nil is 0 and a String of class String in an ASCII-compatible encoding that is 1 to 18 ASCII digits is + /// their decimal value, as String#to_i makes it. Every other String (a sign, blanks, underscores, a long one, one + /// String#to_i raises for) and every other receiver deopt, to the generic call. A String another thread changes + /// while it is read deopts as well: nothing but a deopt leaves this helper. + /// + public static object ToIntegerObject(RubyContext/*!*/ context, object value, KernelMethodSite/*!*/ site) { + if (!site.Resolves(ClassOf(context, value))) { throw Deopt(); } + if (value is int || value is long || value is BigInteger) { return value; } + if (value == null) { return ScriptingRuntimeHelpers.Int32ToObject(0); } + if (value.GetType() == typeof(MutableString)) { + long result = 0; + try { + var str = (MutableString)value; + if (str.Encoding.IsAsciiIdentity) { + int count = str.GetCharCount(); + if (count >= 1 && count <= 18) { + for (int i = 0; i < count; i++) { + char c = str.GetChar(i); + if (c < '0' || c > '9') { result = -1; break; } + result = result * 10 + (c - '0'); + } + if (result >= 0) { return NarrowLong(result); } + } + } + } catch (Exception e) when (!(e is JitDeoptException)) { + } + } + throw Deopt(); + } + /// /// Which receiver classes resolve a name to one of the library methods given (KernelMethodSite.Resolves), each under the /// global method version it was found at, for a few classes at once: a type test (`x.is_a?(C)') sees receivers of @@ -765,6 +798,18 @@ public static int StringLength(object recv) { throw Deopt(); } + /// Array#empty?, Hash#empty?, and String#empty? of a String whose class is String itself; anything else deopts. + public static bool IsEmptyOrString(object recv, bool arrays, bool hashes) { + if (recv != null && recv.GetType() == typeof(MutableString)) { return ((MutableString)recv).IsEmpty; } + return SizeOf(recv, arrays, hashes) == 0; + } + + /// String#empty? of a String whose class is String itself, under StringLength's conditions; anything else deopts. + public static bool StringEmpty(object recv) { + if (recv != null && recv.GetType() == typeof(MutableString)) { return ((MutableString)recv).IsEmpty; } + throw Deopt(); + } + /// /// `a == b', `a != b' between two Strings whose class is String itself (a subclass may override ==, and /// an instance with a singleton == is ruled out when compiling): String#== compares the contents, as diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 29e31fd20..958754c7d 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1211,6 +1211,18 @@ public static bool NotBoolean(object value) { throw Deopt(); } + /// + /// `!x' of any x (JitCompiler.EmitNot): true, false and nil as NotBoolean, and anything else false - BasicObject#!, + /// rb_obj_not - once the site found x's class (its singleton class included) to resolve `!' to it; a class with a #! + /// of its own deopts. + /// + public static bool NotObject(RubyContext/*!*/ context, object value, KernelMethodSite/*!*/ site) { + if (value == null) { return true; } + if (value is bool) { return !(bool)value; } + if (!site.Resolves(ClassOf(context, value))) { throw Deopt(); } + return false; + } + // The guards are inlined into the body; the deopt is thrown out of line. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GuardInt(object value) { diff --git a/Util/jit-objops-matrix.rb b/Util/jit-objops-matrix.rb new file mode 100644 index 000000000..707b82128 --- /dev/null +++ b/Util/jit-objops-matrix.rb @@ -0,0 +1,144 @@ +# Differential matrix for operations on an object in methods the method JIT compiles: `x.to_i' (JitRuntime.ToIntegerObject), +# `x.empty?' of a String or of a receiver of several types (StringEmpty, IsEmptyOrString), `!x' of any object (NotObject), +# writes of an instance variable as an object and as a boolean held back (JitCompiler.Sink.cs, _sinkBoxed), and `x.call' +# refused by the screen. Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-objops-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-objops-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-objops-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-objops-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep OO +# The traps: Strings to_i parses other than as plain digits (signs, blanks, underscores, a Bignum, other digits, an +# ASCII-incompatible encoding), receivers without the method, a String subclass, singleton methods, to_i, empty? and ! +# redefined or refined, a frozen self after held-back writes, the order of a held-back object's first writes. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class OO + def to_i_of(x) = x.to_i + def empty_of(x) = x.empty? + def not_of(x) = !x + def set_port(v) + v = v.empty? ? nil : v.to_i unless !v || v.kind_of?(Integer) + @port = v + end + attr_reader :port, :a, :b, :c + def held(h) + @a = h[:a] + if h[:flag] + @b = true + @c = h[:c].is_a?(Hash) ? h[:c][:x] : false + else + @b = false + @c = false + end + @a + end + def calls(x) = x.call +end + +o = OO.new +t("to_i of a String, hot") { warm { |i| o.to_i_of(i.to_s) } } +t("to_i of Strings") { ["007", "", " 12", "-5", "+5", "1_000", "12abc", "9" * 18, "9" * 19, "9" * 30, "0x1A", "12", "12\n"].map { |s| o.to_i_of(s) } } +t("to_i of other encodings") { ["12".b, "12".encode("US-ASCII"), "12".force_encoding("Shift_JIS")].map { |s| o.to_i_of(s) } } +t("to_i, UTF-16LE") { o.to_i_of("12".encode("UTF-16LE")) } +t("to_i of non-Strings") { [o.to_i_of(nil), o.to_i_of(5), o.to_i_of(2**70), o.to_i_of(1.9), o.to_i_of(-1.9), o.to_i_of(3r)] } +t("to_i of a Symbol") { o.to_i_of(:a) } +t("to_i of an Object") { o.to_i_of(Object.new) } +t("to_i of a String subclass") { c = Class.new(String) { def to_i = 99 }; [o.to_i_of(c.new("5")), o.to_i_of(Class.new(String).new("6"))] } +t("to_i, singleton") { s = +"7"; def s.to_i = 70; [o.to_i_of(s), o.to_i_of("7")] } +t("to_i, frozen and chilled") { [o.to_i_of("42".freeze), o.to_i_of("43")] } +t("to_i, value kinds") { r = o.to_i_of("123"); [r, r.class, r.equal?(123)] } + +t("empty? of a String, hot") { warm { |i| o.empty_of(i.even? ? "" : "x") } } +t("empty? of others") { [o.empty_of([]), o.empty_of([1]), o.empty_of({}), o.empty_of({a: 1}), o.empty_of(+""), o.empty_of("\0")] } +t("empty? of nil") { o.empty_of(nil) } +t("empty? of 5") { o.empty_of(5) } +t("empty?, String subclass") { c = Class.new(String) { def empty? = :sub }; o.empty_of(c.new("")) } +t("empty?, singleton") { s = +""; def s.empty? = :single; o.empty_of(s) } + +t("! of objects, hot") { warm { |i| o.not_of(i.even? ? "s" : Object.new) } } +t("! of everything") { [nil, false, true, 0, "", [], :s, 1.5, Object.new].map { |x| o.not_of(x) } } +t("!, a class with its own !") { c = Class.new { def ! = :bang }; o.not_of(c.new) } +t("!, singleton") { x = Object.new; def x.! = :single; o.not_of(x) } +t("!, BasicObject") { o.not_of(BasicObject.new) } + +t("set_port, mixed, hot") { warm { |i| o.set_port(["80", nil, 443, "", "8080"][i % 5]) } } +t("set_port values") { ["80", nil, 443, "", "8080", " 8", "0x10"].map { |v| o.set_port(v); o.port } } +t("set_port, false") { o.set_port(false); o.port } +t("set_port, Array") { o.set_port([]); o.port } +t("set_port, Symbol") { o.set_port(:x) } + +t("held, hot") { q = OO.new; warm { |i| q.held({ a: i, flag: i.odd?, c: (i % 3 == 0) ? { x: i } : 1 }) }; [q.a, q.b, q.c] } +t("held, order of first writes") { q = OO.new; q.held({ a: 1, flag: false }); q.instance_variables } +t("held, then frozen") { q = OO.new; warm { |i| q.held({ a: i, flag: true, c: {} }) }; q.freeze; [(q.held({ a: 9 }) rescue $!.class), q.a] } +t("held, a default proc") { q = OO.new; h = Hash.new { |_, k| k == :a ? :dflt : nil }; [q.held(h), q.a, q.b] } +t("held, a deopt after the writes") { q = OO.new; warm { |i| q.held({ a: i, flag: true, c: {} }) }; h = { a: 1, flag: true, c: Class.new(Hash).new }; [q.held(h), q.c] } + +t("call, hot") { pr = proc { 1 }; warm { o.calls(pr) } } +t("call of a lambda and a Method") { [o.calls(-> { 2 }), o.calls(1.method(:to_s))] } + +class String + alias_method :__orig_to_i, :to_i + def to_i = -1 +end +t("String#to_i redefined") { [o.to_i_of("5"), o.set_port("80"), o.port] } +class String + alias_method :to_i, :__orig_to_i + alias_method :__orig_empty, :empty? + def empty? = true +end +t("String#empty? redefined") { [o.empty_of("x"), o.set_port("80"), o.port] } +class String + alias_method :empty?, :__orig_empty +end +class NilClass + alias_method :__orig_to_i, :to_i + def to_i = -2 +end +t("NilClass#to_i redefined") { o.to_i_of(nil) } +class NilClass + alias_method :to_i, :__orig_to_i +end +class BasicObject + alias_method :__orig_not, :! + def ! = :redefined +end +t("BasicObject#! redefined") { [o.not_of("s"), o.not_of(nil), o.not_of(Object.new)] } +class BasicObject + alias_method :!, :__orig_not +end +t("restored") { [o.to_i_of("5"), o.empty_of(""), o.not_of("s"), o.set_port("80"), o.port] } + +module ToIRefinement + refine String do + def to_i = :refined + end +end +class OO + using ToIRefinement + def to_i_refined(x) = x.to_i +end +t("refined") { warm { o.to_i_refined("5") } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 2fefb66de..6ab3dc6bf 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1901,6 +1901,51 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitoptimism (2026-11-28, census and timed, not gated) - what the screen let through and the compiler declined** + (switches `IR_JIT_OBJECT_OPS`, `IR_JIT_SCREEN_CALL`, `IR_JIT_SINK_BOXED`). Built on happy-gauss 348fde1 merged with + perf/jitbody f1dc798. perf/jitisa left three new declines in app-shapes, methods `is_a?` used to keep out of the + screen. Each was either taken by the compiler or refused up front: + - **`n.call` (Enumerator::Lazy#size): refused.** The screen took `x.call` for a possible attribute read. A Proc's + or Method's call runs Ruby code, which no typed body does, so the screen now refuses a no-argument `x.call`. + Census: 4 methods maybe -> never, all ones that could only be wrapped to be declined. + - **`v.to_i`, `v.empty?` and `!v` on an untyped value (URI::Generic#set_port): taken.** + - `x.to_i` of an object: `JitRuntime.ToIntegerObject`. An Integer is itself, nil is 0, and a String of class + String in an ASCII-compatible encoding made of 1 to 18 ASCII digits is its value. Anything else deopts, as + does an exception while the String is read. A `KernelMethodSite` checks that the receiver's class (singleton + included) resolves to_i to Integer's, String's or NilClass's library method. + - `x.empty?` of a String (`StringEmpty`), and of a receiver the profile saw hold several types + (`IsEmptyOrString`). + - `!x` of any object: `NotObject`, false once the site finds the class resolves `!` to BasicObject's. It used to + deopt for anything but true, false and nil (Gem::Dependency#runtime?: 304 deopts and 9 retirements in + app-shapes, now none). + - **A deopt after an effect (CSV::Parser#prepare_variable): taken.** The body writes instance variables from + `@options[...]` reads. The writes were not held back: the index reads, type tests and identity tests were + missing from the sinking allow-list, though they throw nothing but a deopt and run no Ruby code. They are added + there, with the new helpers. `@backslash_quote`, written as an object and as `false`, is held as an object on + a second round (`_sinkBoxed`, as `_sinkWide` holds an Integer as a long). + - **app-shapes, traced:** specialized 121 -> 123 (set_port, prepare_variable), declined 32 -> 29, deopts 304 -> + 0, retirements 9 -> 0. + - **Census:** 13 methods changed. 9 maybe -> compiles (marshal_load and initialize methods that read a Hash + into instance variables, Psych::Coder#[], ErrorHighlight's fetch_line, CSV::Writer#rewind); 4 maybe -> never + (the `x.call` refusal). + - **Clock** (ab.rb -r 5, app-shapes, new/off): uri 1.14, csv_parse 0.95, gem_version 1.01, gem_requirement + 0.91, gem_spec 0.99, every one overlapping. uri alone, 9 rounds: 1.07, spreads 59% and 76% on a busy machine. + No measurable change. A callgrind count of app-shapes failed on one build and was not retried. + - **Checks:** + - `Util/jit-objops-matrix.rb` (new, 40 rows): to_i of Strings it must leave to the generic call (signs, + blanks, underscores, 19 or more digits, fullwidth digits, UTF-16LE), of nil, Integers, Floats, Rationals, + Symbols and Objects, a String subclass, a singleton to_i; empty? of Strings, Arrays, Hashes, nil, Integers; + ! of everything, of a class or singleton with its own !; set_port's mixed values; held-back object and + boolean writes with a default proc, a frozen self, a Hash subclass; `x.call`; String#to_i, String#empty?, + NilClass#to_i and BasicObject#! redefined, then restored; a refined to_i. It prints CRuby's output with the + JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, IR_LIGHT_FRAMES=0 and the three switches off. + - jit, jit-calls, jit-const, jit-isa, unsampled, hot-shapes, hash-literal, jit-scan and inline in the same five + modes: the same as the base. inline's tree_int_key row says `Object must be of type Int32.` where CRuby + raises NoMethodError, on both builds. + - ruby/spec core/string/to_i, nil/to_i, integer/to_i, string/empty?, array/empty?, hash/empty?, + basicobject/!, proc/call: no failures on either build. + - IronRuby.Tests (Debug), all 1,403: PASSED. + - **perf/jitisa (2026-11-28, census and timed, not gated) - `is_a?`, `kind_of?` and `instance_of?` in the method JIT's typed body** (the census's "MethodCall (screen)": is_a? 693; switch `IR_JIT_TYPE_TEST`). Built on happy-gauss f67ac44 merged with perf/jitbody e19f454. From 1d48430e7cf19e1e53bf5e194e0bb39b778527a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:02:33 +0000 Subject: [PATCH 288/439] A call of another shape gets a shared rule of its own, not a rule per class version A shared rule is one per method, receiver type and delegate type. Two sites calling one method with arguments of different types - OpenStruct's define_singleton_method!(name, ...) with a Symbol and ("#{name}=", ...) with a String - share the key: the first shape's rule holds each new class version, the second fails its argument test and got a rule of its own, which tests the one class version, so on objects that each have a singleton class it was built and compiled again for every object (~200 us, IR_BIND_TRACE "shared-new"): 207-209 binds in a process's first 300 OpenStructs, until the interpreted method was recompiled. BindShared now takes the first rule of the method that does not hold the call's class version yet (one that holds it has not matched this call), and when every one holds it and the call got a rule of its own, the next call of its kind on another class version builds a shared rule for its shape (BindSharedRule), up to four per method. IR_SHARED_SHAPES=0 turns it off. First 300 OpenStructs of a process (8 alternating processes): 237 -> 146 ms mean (base 207-261, new 133-193); 3000: 724 -> 632. Binds of define_singleton_method! in the first 300: 230 -> 20. Steady state level (ostr36-shapes, count.sh: 1.000-1.004). Util/sdef-matrix.rb section 13: one method called from several sites with a Symbol, a String, more arguments, keywords, define_singleton_method by Symbol, String and Method, the method redefined after the rules are shared, singleton overrides on some objects, threads. CRuby 4.0's output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 32 ++++++++++++++++++++++-- Util/sdef-matrix.rb | 20 +++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index bfd46c5b6..1eec4d652 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -376,6 +376,12 @@ internal SharedRule(RubyMemberInfo/*!*/ member, bool isMissing, Type/*!*/ target private const int MaxSharedRules = 16; + // Shared rules of one method for calls of different shapes (see BindShared). + private const int MaxShapesPerMethod = 4; + + // IR_SHARED_SHAPES=0: one shared rule per method, receiver type and delegate type; a call it does not match gets a rule of its own. + private static readonly bool _ShareShapes = Environment.GetEnvironmentVariable("IR_SHARED_SHAPES") != "0"; + private const RubyCallFlags SharableCallFlags = RubyCallFlags.HasScope | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasRhsArgument | RubyCallFlags.HasBlock | RubyCallFlags.HasImplicitSelf | RubyCallFlags.IsVariableCall | RubyCallFlags.HasSourceBlock | RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat; @@ -573,12 +579,20 @@ internal override T BindShared(object[]/*!*/ args, bool beforeDispatcher, out } SharedRule shared = null; + int sameMethod = 0; var sharedRules = _sharedRules; if (sharedRules != null) { foreach (var rule in sharedRules) { if (rule.Member == member && rule.IsMissing == isMissing && rule.TargetType == targetType && rule.DelegateType == typeof(T)) { - shared = rule; - break; + if (shared == null) { shared = rule; } + if (!_ShareShapes) { break; } + // A rule that holds this version already has not matched this call - its arguments are of other types + // (see below): a later rule of the method, made for calls of another shape, may. + sameMethod++; + if (rule.Rule == null || !rule.Versions.Contains(version)) { + shared = rule; + break; + } } } } @@ -633,6 +647,20 @@ internal override T BindShared(object[]/*!*/ args, bool beforeDispatcher, out } } else { CacheTarget(compiled); + // Every shared rule of the method holds the version and none matched: a call of another shape - OpenStruct's + // define_singleton_method!(name, ...) with a Symbol at one site and a String at the next. Its rule of its own + // tests the one class version, so on objects that each have a singleton class it was built and compiled again + // for every object (~200 us, 220-240 binds in a process's first OpenStructs). The next call of its kind on + // another class version builds a shared rule for its shape (BindSharedRule), which takes in later versions in + // its test as the first one does. + if (_ShareShapes && sameMethod < MaxShapesPerMethod) { + lock (_SharedRulesLock) { + sharedRules = _sharedRules; + if (sharedRules.Length < MaxSharedRules) { + _sharedRules = ArrayUtils.Append(sharedRules, new SharedRule(member, isMissing, targetType, typeof(T), version)); + } + } + } } return compiled; } diff --git a/Util/sdef-matrix.rb b/Util/sdef-matrix.rb index ca5a424bb..7a4bc1db4 100644 --- a/Util/sdef-matrix.rb +++ b/Util/sdef-matrix.rb @@ -336,5 +336,25 @@ def self.go(o) = [o.a, o.respond_to?(:a)] t12 << Thread.new { bad = 0; 6000.times { bad += 1 unless s12.respond_to?(:a) && s12.a == :a && !s12.respond_to?(:pv) }; bad } row "threads define while one asks", t12.map(&:value) +# ---------------------------------------------------------------- 13. one method called with arguments of different shapes from several sites +# A shared rule serves the receivers of many classes (here, one singleton class per object) for calls of one shape; calls of +# another shape (a String where the first site passes a Symbol, a block, more arguments) get shared rules of their own. +class C13 + def m(a, b = nil) = [a.class, b.class] + def k(a, x: 1) = [a.class, x] + alias_method :dsm13!, :define_singleton_method +end +def c13_object(i) = C13.new.tap { |o| o.singleton_class if i % 3 != 0 } +row "two sites, Symbol and String", tally12(600) { |i| o = c13_object(i); [o.m(:a), o.m("a"), o.m(1, 2.0)] } +row "define_singleton_method by Symbol, String, Method", tally12(400) { |i| o = c13_object(i); pr = proc { i } + o.dsm13!(:"s13_#{i % 7}", &pr); o.dsm13!("t13_#{i % 7}", &pr); o.dsm13!(:u13, o.method(:m)) + [o.public_send(:"s13_#{i % 7}") == i, o.public_send(:"t13_#{i % 7}") == i, o.u13(:z)] } +row "keywords and not", tally12(400) { |i| o = c13_object(i); [o.k(1), o.k("s", x: 2), o.k(:y, **{ x: 3 })] } +row "redefined after the rules are shared", tally12(600) { |i| C13.class_eval { def m(a, b = nil) = :redefined } if i == 300; o = c13_object(i); [o.m(:a), o.m("a")] } +row "singleton overrides on some", tally12(600) { |i| o = c13_object(i); (def o.m(a, b = nil) = :own) if i % 5 == 0; [o.m(:a), o.m("a")] } +t13 = 3.times.map { |t| Thread.new { bad = 0; 2000.times { |i| o = c13_object(i + t); v = [o.m(:a), o.m("a"), o.m(1, 2.0)] + bad += 1 unless v == [[Symbol, NilClass], [String, NilClass], [Integer, Float]] || v == [:redefined, :redefined, :redefined] }; bad } } +row "threads", t13.map(&:value) + $stderr.puts "jit=#{defined?(IronRuby) ? 'ironruby' : 'cruby'}" puts "end" From 6a9a81f660ecbc04ff3de5bc01723ef94e485365 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:02:33 +0000 Subject: [PATCH 289/439] Ledger: perf/sharedargs (round forty-one, gap 32) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf76e1VwJqEa1rzDxC4 --- Util/perf/LEDGER.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 08b5f4c1b..f2bd35084 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1811,7 +1811,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 90K and 65K an object - some thirty fills per object, each walking the ancestors and copying the singleton class's whole cache table to file one name, because each definition empties it. `os_new` 0.77 of its instructions, `os_app` 0.84. - Left, measured but not taken: (1) a shared rule is one per (method, receiver type, delegate + Left, measured but not taken (the first taken in round forty-one, perf/sharedargs, see Landed): + (1) a shared rule is one per (method, receiver type, delegate type), so two sites calling one method with arguments of different types share it, and the second gets a rule of its own built for each object (~200 us, `IR_BIND_TRACE` "shared-new"): OpenStruct's `define_singleton_method!(name, ...)` (a Symbol) and `("#{name}=", ...)` (a @@ -1995,6 +1996,29 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/sharedargs (round forty-one, 2026-11-28) - a call of another shape gets a shared rule of its + own (gap 32)** - not gated. A shared rule is one per method, receiver type and delegate type; OpenStruct's + `define_singleton_method!(name, ...)` (a Symbol) and `("#{name}=", ...)` (a String) share the key, and + the second shape's call, failing the first's argument test, got a rule of its own, which tests one + class version: built and compiled again for each object's singleton class (~200 us), 207-209 times in + a process's first 300 OpenStructs. `BindShared` now takes the first rule of the method that does not + hold the call's version yet, and when every one holds it and the call got a rule of its own, the next + call of its kind on another class version builds a shared rule for its shape, up to four per method. + `IR_SHARED_SHAPES=0` turns it off. + `warm.rb` (the first N OpenStructs of a process: new, a writer, two readers; 8 alternating processes, + ms): 300 - base mean 237.3 (206.5-261.4), new 145.7 (133.4-193.4); 3000 - 724.4 (572.4-829.9) / + 631.8 (579.5-729.4). Binds of `define_singleton_method!` in the first 300 (`IR_BIND_TRACE`): 230 / 20, + "shared-new" 207 / 5; round thirty-seven's `r2.rb` 124-132 / 5. Steady state (`ostr36-shapes.rb`, + count.sh, N=200): os_new 1.004, os_app 1.002, dsm_blk_call 1.001, dsm_tbl_call 1.000. + `Util/sdef-matrix.rb` section 13 (new): one method from several sites with a Symbol, a String, more + arguments, keywords; define_singleton_method by Symbol, String and Method; the method redefined after + the rules are shared; singleton overrides on some objects; three threads. `gate-matrices.rb` on + hot-shapes, sdef, shared-rule-light, jit-calls, jit, respond-to, dmeth, struct, extend, delegate, + forwardable and refinement in eight modes (the gate's six, `IR_SHARED_SHAPES=0`, + `IR_SINGLETON_LOOKUP=0`): PASS, 96 same. ruby/spec library/openstruct, kernel define_singleton_method, + respond_to, public_send, send, basicobject method_missing: no failures; language/send and + module/define_method one error each on both builds (the known `into`/`to` messages). + - **Gate of 2026-11-28 for round 6 of round thirty-seven** (perf/crubydiff's third and fourth rounds, perf/sieve and gap 39's analysis, perf/evallocals, perf/evalscreen, perf/evalboxes, perf/hsortby, perf/arymin, perf/rescuelight and perf/splatpos with castcheck's, nilblock's and dotsfwd's findings, From 977e0476711c4614ca66fcb9dd407a9653b080fc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:08:33 +0000 Subject: [PATCH 290/439] Passed blocks: a Ruby method that may keep a block it is passed makes it not reusable The first version lifted the pass hold when any receiver known to keep nothing took the block, but that receiver need not be the one it was passed to: Richards' TaskControlBlock#initialize stores its `&block' and calls `super()', which passes the block on to TaskState#initialize, a light frame that only yields - and that confirmed the pass, so the caller's literal, kept by the task, was made again for the next task (NullReferenceException in the stored block). Now a Ruby method that may keep a block that is not its call's literal - one that names it (EnterLightMethodNamingBlock) or has a scope (CreateRfcForMethod) - clears its ReusableFlag for good as it takes it; a later confirmation lifts only the hold. Util/passed-block-matrix.rb gets both shapes: a receiver that calls super with the block, and one that stores it and passes it on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Runtime/RubyOps.FlowControl.cs | 11 ++++++-- Src/Ruby/Runtime/RubyOps.cs | 11 ++++++-- Util/passed-block-matrix.rb | 37 +++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 6 deletions(-) diff --git a/Src/Ruby/Runtime/RubyOps.FlowControl.cs b/Src/Ruby/Runtime/RubyOps.FlowControl.cs index 75a7893e3..9af50d2ea 100644 --- a/Src/Ruby/Runtime/RubyOps.FlowControl.cs +++ b/Src/Ruby/Runtime/RubyOps.FlowControl.cs @@ -34,9 +34,14 @@ public static partial class RubyOps { // AggressiveOptimization: see RubyOps.Yield0. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)] public static RuntimeFlowControl/*!*/ CreateRfcForMethod(Proc proc) { - if (proc != null && proc.Kind == ProcKind.Block) { - proc.ConvertAsFrame(); - return proc; + if (proc != null) { + if (proc.Kind == ProcKind.Block) { + proc.ConvertAsFrame(); + return proc; + } + // A block another method passed on (Proc.PassHeldFlag): this method's scope holds it and may keep it, and may pass + // it on to a receiver that confirms the pass - which must not make it reusable again. + proc.ClearReusable(); } return InactiveRfc; } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index a651ad564..11756468c 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -502,9 +502,14 @@ private static bool TryParkDeeper(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ pa /// public static RuntimeFlowControl/*!*/ EnterLightMethodNamingBlock(Proc blockParameter) { RubyUtils.SafePoint(); - if (blockParameter != null && blockParameter.Kind == ProcKind.Block) { - blockParameter.ConvertAsMethodFrame(); - return blockParameter; + if (blockParameter != null) { + if (blockParameter.Kind == ProcKind.Block) { + blockParameter.ConvertAsMethodFrame(); + return blockParameter; + } + // a block another method passed on (Proc.PassHeldFlag): this method may keep it - or pass it on, by `super' too, to + // a receiver that confirms the pass, which must not make it reusable again + blockParameter.ClearReusable(); } return InactiveRfc; } diff --git a/Util/passed-block-matrix.rb b/Util/passed-block-matrix.rb index dd8ed0aed..2e28444de 100644 --- a/Util/passed-block-matrix.rb +++ b/Util/passed-block-matrix.rb @@ -149,3 +149,40 @@ def brk; @p.each { |x| break x * 100 if x == 2 }; end ths.each(&:join) s.saved.map { |b| b.call[0] }.sort } + +# A receiver that keeps the block and then hands it on to one that only yields (Richards' TaskControlBlock#initialize +# stores it and calls `super()', which passes it too): the keeping must win over the later receiver's confirmation. +class KBase + def initialize; end +end +class KKeep < KBase + attr_reader :fn + def initialize(tag, &fn); super(); @tag = tag; @fn = fn; end +end +class KStore + def initialize; @items = [1]; @saved = []; end + attr_reader :saved + def each_yield; @items.each { |x| yield x }; end + def keep_then_yield(&b); @saved << b; each_yield(&b); end +end +class KPass + def initialize(s); @s = s; end + def make(tag, &b) = KKeep.new(tag, &b) + def keep_yield(&b) = @s.keep_then_yield(&b) +end +class KCaller + def initialize(kp); @kp = kp; end + def make(n); data = n; @kp.make(:a) { |x| [data, x] }; end + def keep_yield(n); c = 0; @kp.keep_yield { |x| c += x; [n, c] }; c; end +end +t('kept by a receiver that calls super with it') { + kc = KCaller.new(KPass.new(KStore.new)) + ks = Array.new(N) { |n| kc.make(n) } + ks.values_at(0, 1, 1500, -1).map { |k| k.fn.call(:x) } +} +t('kept by a receiver that passes it on to one that only yields') { + s = KStore.new + kc = KCaller.new(KPass.new(s)) + N.times { |n| kc.keep_yield(n) } + s.saved.values_at(0, 1, 1500, -1).map { |b| b.call(5) } +} From 4ef49aecb143d50301b02f5c577b09a784150363 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:23:00 +0000 Subject: [PATCH 291/439] Let an outlined while loop write self's instance variables (IR_LOOP_IVAR_WRITES=1, off by default) The OSR loop compiler bailed on `@x = v' and `@x op= v' in a while loop's body ("instance variable write in an outlined loop"). With IR_LOOP_IVAR_WRITES=1 the store is a logged one into self's variable (JitRuntime.WriteSelfIVar, WriteSelfAttr's store without the attr_writer check): it deopts before storing on a frozen self, a variable self does not have yet, self not a plain Ruby object or a full log, and a deopt later in the iteration takes it back, so the generic code re-runs the iteration from the loop's snapshot and the writes and any FrozenError happen as in CRuby. Floats are stored boxed (a raw store would make the class born raw); block loops (WhileLoopExpression.IsBlockLoop, set by BlockLoopSite) still refuse the write. Off by default: while loops that count into an instance variable got faster (0.57-0.80 by clock, 24 bytes less per iteration), but after such a loop had run, a later generic block loop in the same process ran 2x slower, every time, and the cause was not found. Util/perf/LEDGER.md has the numbers and what is owed. No AWFY loop stops first at this write (each stops at a call); app-shapes has one. Util/loop-ivar-matrix.rb (new) prints CRuby's output on the base and with the switch off and on; the gate matrices passed in every mode with it on and off; Util/ivar-stress.rb gains a loop part (OK both ways); Util/bench/loopivar-shapes.rb times the shapes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- .../Ast/Expressions/WhileLoopExpression.cs | 5 + Src/Ruby/Runtime/Jit/JitCompiler.cs | 68 ++++++++- Src/Ruby/Runtime/Jit/JitRuntime.cs | 19 ++- Src/Ruby/Runtime/Osr/BlockLoopSite.cs | 2 +- Util/bench/loopivar-shapes.rb | 65 ++++++++ Util/ivar-stress.rb | 33 ++++ Util/loop-ivar-matrix.rb | 142 ++++++++++++++++++ Util/perf/LEDGER.md | 55 +++++++ 8 files changed, 385 insertions(+), 4 deletions(-) create mode 100644 Util/bench/loopivar-shapes.rb create mode 100644 Util/loop-ivar-matrix.rb diff --git a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs index 1b2169237..8b161033f 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs @@ -41,6 +41,11 @@ public partial class WhileLoopExpression : Expression { private readonly bool _isWhileLoop; // while or until private readonly bool _isPostTest; // do-while or while-do + // A loop BlockLoopSite made of a block and its iterator (`n.times { ... }', `a.each { ... }'), not one + // the source wrote: the method JIT's loop tier refuses an instance variable write in it + // (JitCompiler.EmitLoopIVarWrite). + internal bool IsBlockLoop; + public Expression Condition { get { return _condition; } } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index b259dc98f..5b1634b96 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1759,6 +1759,66 @@ internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { return EmitAndOr(node.Left, node, node.Operation == "&&", out type); } + /// + /// With IR_LOOP_IVAR_WRITES=1, outlined `while' loops store into self's instance variables (`@x = v', `@x op= v'). + /// Off by default: the loops get faster (a counter 0.57-0.80), but once one has run, the process's other code + /// ran up to 2x slower in the measurements (a generic `n.times { @n += 1 }' afterwards, diagnosed no further + /// than the logged stores; Util/perf/LEDGER.md, perf/loopivar). A block loop (BlockLoopSite: `n.times { @n += 1 }', `a.each { |x| @last = x }') + /// still refuses them: there the logged store cost as much as the generic block call it replaced, or more + /// (`each { |x| @last = x }' 1.25x), and its last statement is followed by the loop's counter step, so it + /// cannot go unlogged either (Util/perf/LEDGER.md, perf/loopivar). + /// + internal static readonly bool LoopIVarWrites = Environment.GetEnvironmentVariable("IR_LOOP_IVAR_WRITES") == "1"; + + /// + /// `@x = v' / `@x op= v' in an outlined loop: the store `o.x = v' makes there (EmitAttributeWrite), into self's + /// variable (JitRuntime.WriteSelfIVar). It logs the value it replaces, so that a deopt later in the iteration + /// takes it back and the iteration restarts in the generic code as if it had not been made (the loop's + /// snapshot; JitUndoLog); what the store cannot make without raising or changing self's shape - a frozen self, + /// a variable self does not have yet, self not a plain Ruby object - deopts before it, and the generic code + /// makes the write, or raises, in the iteration the source does. The value is v. + /// + private MSA.Expression/*!*/ EmitLoopIVarWrite(InstanceVariable/*!*/ target, string op, RExpr/*!*/ right, out JT type) { + JT vt; + MSA.Expression v; + if (op != null) { + // `@x op= v' -> `@x = @x op v', the read and the operator first, as in a method + JT ct; + var current = NumericIVar(target, Emit(target, out ct), ref ct); + var operand = Emit(right, out vt); + operand = NumericIVar(right, operand, ref vt); + if (IsNumeric(ct) && IsNumeric(vt)) { + v = EmitBinary(op, current, ct, operand, vt, out vt); + } else if ((ct == JT.Obj && IsNumeric(vt)) || (IsNumeric(ct) && vt == JT.Obj)) { + v = EmitSpeculatedBinary(op, current, ct, target, operand, vt, right, out vt); + } else { + throw Bail("instance variable op-assign on " + ct + ", " + vt); + } + } else { + v = Emit(right, out vt); + } + if (vt == JT.Never || vt == JT.None) { throw Bail("instance variable write of a value that jumps away"); } + _canDeopt = true; + _hashWrite = true; + if (_undoLog == null) { + // in loop mode the entry sets both up + _undoLog = Ast.Variable(typeof(JitUndoLog), "#undo"); + _undoMark = Ast.Variable(typeof(int), "#undo-mark"); + } + var site = Ast.Constant(new InstanceVariableSite(target.Name)); + var value = Ast.Variable(ClrType(vt), "#value"); + type = vt; + // A Float is stored boxed, not raw as typed method bodies store one (WriteSelfAttrDouble): a raw store + // over a Float promotes the object, and its class's later instances are born raw, which makes every + // generic read and write of their variables slower (`n.times { @n += 1 }' 2x, after a loop of the same + // class stored a Float raw), for a loop no faster than the generic one (Util/perf/LEDGER.md, perf/loopivar). + return Ast.Block(ClrType(vt), new[] { value }, + Ast.Assign(value, v), + Ast.Call(JitRuntime.M("WriteSelfIVar"), _self, BoxForStore(value, vt), site, _undoLog), + value + ); + } + private MSA.Expression/*!*/ EmitAssignment(SimpleAssignmentExpression/*!*/ node, string op, bool conditional, out JT type) { var element = node.Left as ArrayItemAccess; @@ -1767,8 +1827,12 @@ internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { var ivarTarget = node.Left as InstanceVariable; if (ivarTarget != null) { // A write can raise (FrozenError), and an exception leaving an outlined loop - // part way through would leave the scope's locals as they were on entry. - if (_loop != null) { throw Bail("instance variable write in an outlined loop"); } + // part way through would leave the scope's locals as they were on entry: in a loop + // the write is a logged store that deopts instead (EmitLoopIVarWrite). + if (_loop != null) { + if (!LoopIVarWrites || _loop.IsBlockLoop) { throw Bail("instance variable write in an outlined loop"); } + return EmitLoopIVarWrite(ivarTarget, op, node.Right, out type); + } JT vt; MSA.Expression v; if (op != null) { diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index cb1d5a4c0..2e00ff819 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -779,13 +779,30 @@ public static void WriteSelfAttr(object self, object value, SelfAttrSite/*!*/ si if (obj == null || (!site.IsBoundTo(obj.ImmediateClass) && !site.Bind(obj.ImmediateClass))) { throw Deopt(); } + WriteLoggedIVar(obj, value, site.Variable, log); + } + + /// + /// `@x = v' in an outlined loop (JitCompiler.EmitLoopIVarWrite): WriteSelfAttr's store into self's variable, + /// with no writer method to check - the same undo log entry, and the same deopts before anything is written + /// (self not a plain Ruby object, frozen, the variable not there yet, a full log), so that a deopt later in + /// the iteration takes the write back and the generic code makes it once. + /// + public static void WriteSelfIVar(object self, object value, InstanceVariableSite/*!*/ site, JitUndoLog/*!*/ log) { + var obj = self as RubyObject; + if (obj == null) { + throw Deopt(); + } + WriteLoggedIVar(obj, value, site, log); + } + + private static void WriteLoggedIVar(RubyObject/*!*/ obj, object value, InstanceVariableSite/*!*/ variable, JitUndoLog/*!*/ log) { var data = obj._instanceData; if (data == null || data._frozen || log.IsFull) { throw Deopt(); } object[] slots = data._ivars; var shape = RubyInstanceData.ShapeOf(slots); - var variable = site.Variable; var entry = variable.Cache; int index; if (shape == entry.Shape && entry.Next == null) { diff --git a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs index f936aa5e2..81f9fb796 100644 --- a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs @@ -612,7 +612,7 @@ private void Retire() { statements.Add(new SimpleAssignmentExpression(counter, Literal.Integer(1, location), kind == BlockLoopKind.DownTo ? "-" : "+", location)); - return new WhileLoopExpression(condition, true, false, statements, location); + return new WhileLoopExpression(condition, true, false, statements, location) { IsBlockLoop = true }; } /// diff --git a/Util/bench/loopivar-shapes.rb b/Util/bench/loopivar-shapes.rb new file mode 100644 index 000000000..ce4975d28 --- /dev/null +++ b/Util/bench/loopivar-shapes.rb @@ -0,0 +1,65 @@ +# Instance variable writes inside loops (perf/loopivar): `while' loops that write self's variables, which the +# OSR tier outlines with IR_LOOP_IVAR_WRITES=1 (JitCompiler.EmitLoopIVarWrite; off by default), and +# block loops that do, which it still does not (times_count, each_last: controls with while_plain). Format of +# Util/perf/ab.rb: ` ns ` per shape, ns per iteration of the loop; shape names as +# arguments, N from the environment. BYTES=1 (IronRuby only): bytes allocated per +# iteration instead. INSTR=1 (ab.rb -i): instructions per iteration as well. +# +# ruby Util/perf/ab.rb -r 5 Util/bench/loopivar-shapes.rb cruby=ruby \ +# "base=env IR_CONFIG=Release ../base/ir.sh" "off=env IR_CONFIG=Release ./ir.sh" \ +# "new=env IR_LOOP_IVAR_WRITES=1 IR_CONFIG=Release ./ir.sh" +# +# while_count `@n += 1' past the small-integer cache in a `while' +# while_small `@n = (@n + 1) & 511' (cached boxes) +# while_float `@f += 0.5' +# while_two `@a = i; @b = @a + @b' (a read of a variable the iteration wrote) +# times_count `n.times { @n += 1 }' +# each_last `arr.each { |x| @last = x }' +# while_plain a `while' with no instance variable write: the control +$stdout.sync = true +N = (ENV['N'] || 1_000_000).to_i +BYTES = ENV['BYTES'] == '1' +INSTR = ENV['INSTR'] && (require_relative '../perf/instructions'; Instructions.open || warn('no instruction counter (perf_event_open)')) + +class L + def initialize; @n = 5000; @f = 0.0; @a = 0; @b = 0; @last = nil; end + def while_count(n) = (i = 0; while i < n; @n += 1; i += 1; end; @n) + def while_small(n) = (i = 0; while i < n; @n = (@n + 1) & 511; i += 1; end; @n) + def while_float(n) = (i = 0; while i < n; @f += 0.5; i += 1; end; @f) + def while_two(n) = (i = 0; while i < n; @a = i; @b = (@a + @b) & 65535; i += 1; end; @b) + def times_count(n) = (n.times { @n += 1 }; @n) + def each_last(arr) = (arr.each { |x| @last = x }; @last.size) + def while_plain(n) = (i = 0; s = 0; while i < n; s = (s + i) & 65535; i += 1; end; s) +end +ARR = (%w[alpha beta gamma delta] * (N / 4 + 1)).first(N).freeze +SHAPES = %w[while_count while_small while_float while_two times_count each_last while_plain] + +def run_once(o, name) + name == 'each_last' ? o.each_last(ARR) : o.send(name, N) +end + +def run_shape(name) + best = nil + fewest = nil + r = nil + # the loop hot before anything is timed + 3.times { run_once(L.new, name) } + 6.times do + o = L.new + c0 = INSTR && INSTR.read + t = BYTES ? System::GC.get_total_allocated_bytes(true) : Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) + r = run_once(o, name) + d = BYTES ? System::GC.get_total_allocated_bytes(true) - t : Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) - t + c1 = INSTR && INSTR.read + fewest = c1 - c0 if c0 && c1 && (fewest.nil? || c1 - c0 < fewest) + best = d if best.nil? || d < best + end + r = r.round(6) if r.is_a?(Float) + if BYTES + puts format('%s %.1f B %s', name, best.to_f / N, r) + else + puts format('%s %.1f ns %s%s', name, best * 1e9 / N, r, fewest ? format(' %.1f instr', fewest.to_f / N) : '') + end +end + +(ARGV.empty? ? SHAPES : ARGV).each { |s| run_shape(s) } diff --git a/Util/ivar-stress.rb b/Util/ivar-stress.rb index b6260e728..f4dd7c5a1 100644 --- a/Util/ivar-stress.rb +++ b/Util/ivar-stress.rb @@ -347,6 +347,39 @@ def fbody_read(list) = list.map { |b| b.x * 1.0 } record.("final @f#{t}/x of body #{t} #{got.inspect}, owner last read #{flast[t].inspect}") unless got == flast[t] end +# Loops that write instance variables (perf/loopivar: with IR_LOOP_IVAR_WRITES=1 the OSR tier outlines a `while' one, each store logged +# and taken back by a deopt later in its iteration). Thread t runs a `while' loop and a block loop that count +# into its own @l of one shared object, while the others add and remove variables of that object (its +# slots move under the stores) and read every @l: a value read is an Integer no greater than its owner +# has counted to, and each owner's final count is exactly the number of iterations it ran. +class LoopW + THREADS.times do |t| + class_eval "def lw#{t}(n) = (i = 0; while i < n; @l#{t} += 1; i += 1; end; @l#{t})" + class_eval "def lb#{t}(n) = (n.times { @l#{t} += 1 }; @l#{t})" + class_eval "def lr#{t} = @l#{t}" + end +end +lw = LoopW.new +THREADS.times { |t| lw.instance_variable_set(:"@l#{t}", 0) } +LROUNDS = [ITERS / 5000, 4].max +lthreads = THREADS.times.map do |t| + Thread.new do + total = 0 + LROUNDS.times do |r| + total = lw.__send__(:"lw#{t}", 2000) + total = lw.__send__(:"lb#{t}", 2000) + u = (t + r) % THREADS + v = lw.__send__(:"lr#{u}") + record.("loop @l#{u} read #{v.inspect}") unless v.is_a?(Integer) && v >= 0 && v <= LROUNDS * 4000 + name = :"@m#{t}_#{r % 4}" + lw.instance_variable_set(name, r) + lw.remove_instance_variable(name) if r.odd? + end + record.("loop @l#{t} ended at #{total}, counted #{LROUNDS * 4000}") unless total == LROUNDS * 4000 + end +end +lthreads.each(&:join) + if failures.empty? puts "OK (#{THREADS} threads x #{ITERS} iterations, #{objects.size} shared objects)" else diff --git a/Util/loop-ivar-matrix.rb b/Util/loop-ivar-matrix.rb new file mode 100644 index 000000000..4a6c3ca55 --- /dev/null +++ b/Util/loop-ivar-matrix.rb @@ -0,0 +1,142 @@ +# Differential matrix for instance variable writes inside loops (perf/loopivar): `@x = v' and +# `@x op= v' in a `while' loop, which the OSR tier outlines and compiles to a logged store into self's +# variable (JitCompiler.EmitLoopIVarWrite, JitRuntime.WriteSelfIVar) when IR_LOOP_IVAR_WRITES=1 (off +# by default; run it both ways). A block loop (`times', `each') still refuses them; its rows are here for when it +# does not. Run under CRuby and under ./ir.sh and diff: +# +# ruby Util/loop-ivar-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/loop-ivar-matrix.rb > /tmp/ir.txt +# diff /tmp/mri.txt /tmp/ir.txt +# +# Every method is run hot first (HOT calls with long loops) so that its loop is outlined before +# the row's call, and each row then does something the compiled store must get right: Integer, +# Float and String values, an Integer that grows into a Bignum, a type change, a variable the +# object does not have yet, one removed, a frozen self (the FrozenError at the iteration the +# source raises it in, with exactly the writes before it made), a loop left by break and by an +# exception after k writes, a subclass's object with more variables, and other threads reading +# the variable or adding variables to the object while the loop writes. + +def t(label) + print label.ljust(60), ' => ' + begin + v = yield + puts v.inspect.gsub(/0x\h+/, '0xXX') + rescue Exception => e + puts "#{e.class}: #{e.message.gsub(/0x\h+/, '0xXX')}" + end +end + +HOT = 40 +N = 2_000 + +class W + attr_reader :c, :f, :s, :a, :b, :z + def initialize; @c = 0; @f = 0.0; @s = nil; @a = 0; @b = 0; end + def count_up(n) = (i = 0; while i < n; @c += 1; i += 1; end; @c) + def add_float(n) = (i = 0; while i < n; @f += 0.5; i += 1; end; @f) + def last_of(arr) = (i = 0; while i < arr.size; @s = arr[i]; i += 1; end; @s) + def pair(n) = (i = 0; while i < n; @a = i; @b = @a * 2; i += 1; end; [@a, @b]) + def set_z(n) = (i = 0; while i < n; @z = i; i += 1; end; @z) + def step_by(n, d) = (i = 0; while i < n; @c += d; i += 1; end; @c) + def from(n, k) = (i = 0; while i < n; @c += 1 if i >= k; i += 1; end; @c) + def from_rescued(n, k) + i = 0 + begin + while i < n; @c += 1 if i >= k; i += 1; end + [:done, i, @c] + rescue => e + [e.class, i, @c] + end + end + def until_k(k) = (i = 0; while true; @c += 1; i += 1; break if i == k; end; [i, @c]) + def raise_at(n, k) + i = 0 + begin + while i < n; @c += 1; x = 100 / (k - i); i += 1; end + [:done, i, @c, x] + rescue ZeroDivisionError => e + [e.class, i, @c] + end + end + def times_up(n) = (n.times { @c += 1 }; @c) + def each_last(arr) = (arr.each { |x| @s = x }; @s) + def each_break(arr, k) = (arr.each { |x| @c += 1; break if x == k }; @c) + def each_float(arr) = (arr.each { |x| @f += x }; @f) +end + +class WSub < W + def initialize; @p = :p; @q = :q; super; @r = :r; end +end + +STRS = %w[alpha beta gamma delta] +def warm + HOT.times do + w = W.new + w.count_up(N); w.add_float(N); w.last_of(STRS * 200); w.pair(N); w.set_z(N); w.step_by(N, 3) + w.from(N, 10); w.from_rescued(N, 10); w.until_k(N); w.raise_at(N, N + 5); w.times_up(N) + w.each_last(STRS * 200); w.each_break((0...N).to_a, N - 1); w.each_float([0.25] * N) + end +end +warm + +t("count_up") { w = W.new; [w.count_up(N), w.count_up(N), w.c] } +t("add_float") { w = W.new; [w.add_float(N), w.f] } +t("last_of strings") { w = W.new; [w.last_of(STRS * 300), w.s, w.s.frozen?] } +t("pair: read after write in the iteration") { w = W.new; [w.pair(N), w.a, w.b] } +t("a variable not there yet") { w = W.new; [w.instance_variable_defined?(:@z), w.set_z(N), w.instance_variables] } +t("removed, then written again") { w = W.new; w.set_z(N); w.remove_instance_variable(:@z); [w.set_z(N), w.instance_variables] } +t("removed in the middle of the shape") { w = W.new; w.remove_instance_variable(:@f); [w.count_up(N), w.instance_variables] } +t("Integer to Bignum") { w = W.new; w.instance_variable_set(:@c, 2**62); [w.step_by(N, 2**52), w.c.class] } +t("Bignum step") { w = W.new; [w.step_by(N, 2**70), w.c.class] } +t("type change: Float step") { w = W.new; [w.step_by(N, 0.25), w.step_by(N, 1), w.c.class] } +t("type change: String in the variable") { w = W.new; w.instance_variable_set(:@c, 'x'); w.step_by(N, 1) } +t("type change: nil in the variable") { w = W.new; w.instance_variable_set(:@c, nil); w.count_up(N) } +t("frozen before the loop") { w = W.new; w.freeze; [(w.count_up(N) rescue $!.class), w.c] } +t("frozen, the first write at iteration k") { w = W.new; w.freeze; w.from_rescued(N, 1500) } +t("frozen, first write at k, outside rescue") { w = W.new; w.freeze; [(w.from(N, 1500) rescue $!.class), w.c] } +t("break after k writes") { w = W.new; [w.until_k(1234), w.c] } +t("raise after k writes") { w = W.new; [w.raise_at(N, 1234), w.c] } +t("no raise") { w = W.new; w.raise_at(N, N + 7) } +t("subclass object, more variables") { s = WSub.new; [s.count_up(N), s.add_float(N), s.pair(N), s.instance_variables] } +t("singleton class object") { w = W.new; def w.extra = 1; [w.count_up(N), w.extra] } +t("times block") { w = W.new; [w.times_up(N), w.c] } +t("each block, strings") { w = W.new; [w.each_last(STRS * 300), w.s] } +t("each block, break after k") { w = W.new; [w.each_break((0...N).to_a, 777), w.c] } +t("each block, Float") { w = W.new; [w.each_float([0.125] * N), w.f] } +t("each block, frozen") { w = W.new; w.freeze; [(w.each_float([0.125] * N) rescue $!.class), w.f] } +t("instance_variable_get/inspect after") { w = W.new; w.count_up(N); w.add_float(N); [w.instance_variable_get(:@c), w.inspect.sub(/0x\h+/, '')] } +t("Marshal and dup after") { w = W.new; w.count_up(N); d = w.dup; m = Marshal.load(Marshal.dump(w)); [d.c, m.c, d.count_up(N), w.c] } + +t("another thread reads while the loop writes") do + w = W.new + seen = [] + stop = false + reader = Thread.new { until stop; v = w.c; seen << v.class unless v.is_a?(Integer) && v >= 0 && v <= 50 * N; end } + r = 50.times.map { w.count_up(N) }.last + stop = true + reader.join + [r, seen.uniq] +end +t("another thread adds variables while the loop writes") do + w = W.new + adder = Thread.new { 300.times { |k| w.instance_variable_set(:"@x#{k}", k) } } + r = 20.times.map { w.count_up(N) }.last + adder.join + [r, w.c, w.instance_variables.size, w.instance_variable_get(:@x299)] +end +t("instance_variable_set from a callee inside the loop") do + class W + def bump_by_callee(n) = (i = 0; while i < n; @c += 1; instance_variable_set(:@c, @c + 1) if i % 100 == 0; i += 1; end; @c) + end + w = W.new + 5.times { W.new.bump_by_callee(N) } + [w.bump_by_callee(N), w.c] +end +t("a callee freezes self inside the loop") do + class W + def freeze_at(n, k) = (i = 0; while i < n; @c += 1; freeze if i == k; i += 1; end; @c) + end + 5.times { W.new.freeze_at(N, N + 1) } + w = W.new + [(w.freeze_at(N, 600) rescue $!.class), w.c, w.frozen?] +end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 9ab388a9f..7baf4c3d7 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1997,6 +1997,61 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/loopivar (/perf-step, 2026-11-28, not gated) - an outlined `while' loop may write self's + instance variables: OFF by default (`IR_LOOP_IVAR_WRITES=1`)**, on 4b928db (33818f7 merged with + 0bf3598). The OSR loop compiler bailed on `@x = v' ("instance variable write in an outlined loop") + and the method JIT declines a method whose loop writes one ("a deopt after an effect"). + - **How common.** No AWFY loop stops first at the write: the OSR tier tried 17 AWFY loops and each + stops at a call before it (Richards' `schedule` loop, the one that writes `@current_task`, at + `is_task_holding_or_waiting`). app-shapes: 1 of the 53 loops tried (prettyprint.rb:292, a block + that also calls). So the target is the shape itself (`while i < n; @c += 1; i += 1; end`), not AWFY. + - **What it does.** `@x = v' / `@x op= v' in the outlined copy of a `while' is a logged store into + self's variable (JitCompiler.EmitLoopIVarWrite, JitRuntime.WriteSelfIVar: WriteSelfAttr's store + without the attr_writer check). It deopts before storing on what it cannot do without raising or + changing self's shape (self not a plain Ruby object, frozen, the variable not there yet, a full + log); a deopt later in the iteration takes the store back from the log and the generic code re-runs + the iteration from the loop's snapshot, so the writes the source makes are made once, in its order, + and a FrozenError or other exception comes from the iteration the source raises it in. Not the + brief's hold-back (store at the end of the iteration), which Sink.cs does for method bodies: a + thread racing a deopt can see the variable go back by one write and forward again, as it already + can for the Array and Hash stores and `o.x = v' the loop tier logs. A Float is stored boxed (a raw + store promotes the object and makes its class born raw: `n.times { @n += 1 }' on later objects of + that class ran 2x slower). Block loops (BlockLoopSite's `times'/`each' copies, marked + WhileLoopExpression.IsBlockLoop) still refuse the write: there the logged store was no faster than + the generic block call (`each { |x| @last = x }' 1.25x slower), and the counter step after the + block's last statement keeps it from going unlogged. + - **Numbers** (Util/bench/loopivar-shapes.rb, switch off -> on). Bytes per iteration: `@n += 1' + 32.9 -> 24.0 (the Integer box left), a cached-value counter 16 -> 0, a Float 40 -> 24 (boxed), the + controls equal. Instructions (callgrind, before Floats were boxed and block loops excluded): + while_count 0.46, while_small 0.35, while_float 0.42, while_two 0.75, control 1.000. Clock + (ab.rb, 8 rounds, least): while_count 0.80 (overlap), while_small 0.57, while_float 0.77, while_two + 0.97 (overlap), each_last 1.01, the control 1.06 (overlap) - **but times_count 1.39, no overlap**, + and that block loop compiles the same either way: run alone it is 30.6 against 29.9; run after + while_count's compiled loop 66-69 ns against 31, every time (taskset 2 CPUs, two rounds), and in + another run while_count itself was 47 against 30. Something the logged stores leave behind slows + the process's other code; not found (the per-thread JitUndoLog, long-lived and so in gen 2, + taking a young box reference on every store is a guess, not a finding). Hence off by default. + alloc.rb (switch on, block loops then included): flat (geomean 0.995, Richards -5%). AWFY, 10 + alternating rounds, switch off/on, then with block loops included: Bounce 0.974, Richards 0.976, + Towers 0.964, DeltaBlue 0.945, all overlapping, as expected with no AWFY loop changed. + - **Checks**: `Util/loop-ivar-matrix.rb` (new: Integer, Float and String values, a read after a write + in the iteration, a variable not there yet, removed, Bignum growth, type changes, frozen before + the loop and at iteration k inside and outside a rescue, break and an exception after k writes, + a subclass's object and a singleton's, times and each blocks, Marshal/dup/inspect after, a reader + thread, a thread adding variables, a callee's instance_variable_set and freeze) prints CRuby's + output on the base and on the branch with the switch off and on (24 loops outlined, 22 deopts + taken back in the run with it on). gate-matrices (loop-ivar, ivar, loop-exit, osr-array, block-loop, + jit, hot-shapes, jit-scan, marshal) in every mode, run while the switch was on by default, and with + it off: PASS, twice (before and after block loops were excluded). `Util/ivar-stress.rb` gains a + part where eight threads count into their own variable of one object in a `while' and a block loop + while adding and removing others: OK with the switch off and on (17 loops outlined). spec + language/while, until, loop, variables, core/kernel instance_variable_set/get, + remove_instance_variable, core/integer/times, core/array/each: as on the base. IronRuby.Tests + (Debug, switch then on): PASSED. + - **Next**: find what slows the rest of the process (a longer run with the GC's event counters on + the two orders), then hold the stores back to the end of the iteration (Sink.cs's scheme per + iteration) so that they need no log at all, which also answers the racing reader. + - **Gate of 2026-11-28 for round 6 of round thirty-seven** (perf/crubydiff's third and fourth rounds, perf/sieve and gap 39's analysis, perf/evallocals, perf/evalscreen, perf/evalboxes, perf/hsortby, perf/arymin, perf/rescuelight and perf/splatpos with castcheck's, nilblock's and dotsfwd's findings, From 83ddb0d93924dfdcec23b85a8104dcdd89dc8e06 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:40:41 +0000 Subject: [PATCH 292/439] Ledger: round 7's gate, PASS; its entries marked gated Round 7 of round thirty-seven (the branch at 33818f7, against master f81fc19) passed the gate with no fix needed: IronRuby.Tests 1,415 run, none failed; the matrices in seven modes, every DIFF explained (the regexp-binary-ctype lines as at round 6, and string-race-matrix compared over five runs of each tree); a probe file for the round's hot spots as CRuby but for the fiber $~ row master shares; ruby/spec's five suites with no unlisted failure; the census with no method down; AWFY 12 at a geomean of 0.919 and 0.909 with none more than 5% slower in both orders; start-up 2-11% faster. The round's entries now say they were gated. Two entries that merges had doubled are dropped: perf/sieve's (the marked header sat orphaned above perf/permute's entry, the unmarked copy below it) and perf/jitblockparam's. perf/fiberbound's, gated at round 6, is marked so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 120 +++++++++++++++++++++++--------------------- 1 file changed, 64 insertions(+), 56 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 08b5f4c1b..c294dd7fc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1188,7 +1188,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has site; B, its Proc's scope made but not published as the frame's (no slow exit, no parking, the frame's calls still light), with one scope per invocation and the frame's exit marking it left when the Proc escaped. - perf/literalsite (see Landed, not gated) built A and with it the attribution: where the + perf/literalsite (see Landed, gated 2026-11-28 (round 7's gate entry)) built A and with it the attribution: where the literal runs, its Proc makes the scope anyway and A changes nothing (`nbl` 118 -> 114, overlapping); where it does not, A takes the whole 45 ns (`nbx` 100 -> 56, `nbp`'s 56). So the full site costs about nothing, and the literal's own ~60 ns is the scope made and @@ -1628,14 +1628,14 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and the R2R host's JIT. rbconfig.rb no longer uses CLR interop: -0.3 to -0.9% main-thread instructions on all five commands. Next leads: the 4,989 CLR member lookups of ruby4.rb in `-e 1` (5.9 ms), and eval'd strings in the startup library. - 2026-11-27, perf/clrlookup (Landed, not gated): the 7,230 CLR member lookups of `-e 1` are + 2026-11-27, perf/clrlookup (Landed, gated 2026-11-28 (round 7's gate entry)): the 7,230 CLR member lookups of `-e 1` are method resolution falling back to the CLR types of Object, Class, Module and their singleton classes; the hooks of the prelude's definitions (`const_added`, `method_added`...) are most of them. They cost little: failures are cached and names checked against metadata. The time is the first lookup on each of ~67 types. Taken: Random's interop call made lazy, field and event names read from metadata, and the failure cache keyed by a class. -0.75 to -1.97% main-thread instructions on the R2R host, -0.10 to -1.13% on the release image. - 2026-11-27, perf/bootparse (Landed, not gated): the string evals start-up runs are compiled + 2026-11-27, perf/bootparse (Landed, gated 2026-11-28 (round 7's gate entry)): the string evals start-up runs are compiled into the startup library: specification.rb's and kernel_require.rb's (2.3 ms each on the R2R host before their first call), every gemspec RubyGems loads (93 in `gem list`), Forwardable's delegators. Main-thread instructions -2.1 to -6.8% on the R2R host and -2.7 to -8.6% on the release @@ -1995,6 +1995,50 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-28 for round 7 of round thirty-seven** (perf/crubydiff's fifth and sixth rounds, + perf/literalsite, perf/endpark, perf/stage0 and perf/stagea with the block-cost harness and the procscope + design, perf/primitive (rejected), perf/clrlookup, perf/bootparse, perf/permute, perf/parkedtuple + (rejected), perf/kwfwd, perf/jitrescue, perf/jitisa, perf/hashwalk, perf/hashany, perf/cdtree, + perf/lightmatch, perf/sinkcarrier, perf/loopreassign): the branch `claude/happy-gauss-95wm2j` at 33818f7 + against master f81fc19, Release net10.0, four cores: **PASS**, with no fix needed. + The merge itself: RubyOps.EndPark, where perf/endpark's release write (IR_PARK_WRITE) met perf/permute's + deeper slots (IR_PARKED_DEPTH) - the write publishes into an empty slot and otherwise falls to + TryParkDeeper, as the compare-exchange path does; MethodDefinition's IsNeverParkedIterator (`downto` parks + under IR_PARK_DOWNTO) and the light rewriter's LiteralCalls and MatchSlot (both kept); perf/iter2's + rejected `downto` reconciled with perf/permute (9bb53b9). Ledger entries doubled by merges, dropped: the + ones from perf/extiter's merge (22dcf95), and two found now - perf/sieve's, whose marked header had been + left above perf/permute's entry, and perf/jitblockparam's. ReflectionCache.Generated.cs is what + ClassInitGenerator writes, and InternalMethods.Generated.cs what gen-internal-methods.rb writes with + CRuby 4.0.10. No new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,415 tests, every one executed, none failed. + `gate-matrices.rb --all` in 7 modes (the six default ones, and every round 7 switch off at once: + IR_HASH_WALK, IR_JIT_RESCUE, IR_JIT_TYPE_TEST, IR_KWSPLAT_BY_REFERENCE, IR_LIGHT_LITERAL_CALLS, + IR_LIGHT_MATCH_SINK, IR_LOOP_KEEP, IR_PARK_DOWNTO and IR_PARK_WRITE at 0, IR_PARKED_DEPTH=1): 1,274 same, + 119 baseline, 14 DIFF, each explained: regexp-binary-ctype prints what it printed at round 6 (9 lines + from CRuby); string-race-matrix, compared over five runs of each tree (rows not always ok 110 -> 87, lost + writes 106 -> 0, no row failing only on the new build). callable-parameters, a DIFF at round 6, is the + same now. + A probe file for the round's named hot spots - perf/endpark with perf/permute's deeper slots (a recursive + method parking around `downto` from 8 threads at once, every result checked; a block kept from a parked + level), the match sink's `$~` through a TracePoint, a fiber and a raise, a hot method-level + rescue/else/ensure's value, `is_a?` after an include and on a BasicObject, Hash#any? shapes and a key + added in its block, anonymous forwarding with empty and full keywords, a TracePoint `c_call` on an + attribute - prints CRuby's output with the JIT on and off and with the round's switches off, but for one + row, as on master: two fibers suspended in a method that matched share their `$~` (perf/crubydiff's + d32ac04, in round 8, gives a fiber's block its own). + ruby/spec, all five suites (32,285 examples): no failure the known list does not name (two TCPSocket + timeout examples failed under the sweep's load and passed alone). + Census against master (Src/StdLib, Util/bench, AWFY): light frames 91.7% -> 96.2% (+1,748 with the new + methods; of the methods in both, 1,234 up and none down), method JIT compiles 11.7% -> 12.2% and maybe + 10.4% -> 11.9% (466 up, none down). + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.919 and 0.909; none + more than 5% slower in both (Towers 1.068 and 1.035). Alone, five rounds in each order, medians new/base: + Permute 0.918 / 0.881, Sieve 0.448 / 0.466, Json 0.958 / 0.975, CD 0.999 / 0.988. micro-table in both + orders: `cmp` (`@x < o`) 1.06 and 1.15 slower, then by ab.rb alone, 16 rounds in each order, 1.04 and 1.00 + with the rounds overlapping: noise; no other line more than 5% slower in both. + Start-up on the R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 509 -> 497 and + 514 -> 475, `gem --version` 601 -> 591 and 584 -> 562, `gem list` 1043 -> 952 and 1040 -> 929, + `require "irb"` 1100 -> 995 and 1080 -> 977, irb 1+1 1186 -> 1086 and 1167 -> 1075: 2-11% faster. - **Gate of 2026-11-28 for round 6 of round thirty-seven** (perf/crubydiff's third and fourth rounds, perf/sieve and gap 39's analysis, perf/evallocals, perf/evalscreen, perf/evalboxes, perf/hsortby, perf/arymin, perf/rescuelight and perf/splatpos with castcheck's, nilblock's and dotsfwd's findings, @@ -2043,7 +2087,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 502 -> 471, `gem --version` 590 -> 572 and 577 -> 590, `gem list` 1006 -> 989 and 977 -> 982, `require "irb"` 1029 -> 1005 and 984 -> 992, irb 1+1 1133 -> 1071 and 1065 -> 1066: level. - **perf/endpark (round thirty-seven, 2026-11-28) - EndPark publishes the parked scope with a release - write, not a compare-exchange (gap 13)** - time, not gated. Stage 0 found the parked cycle's two atomics + write, not a compare-exchange (gap 13)** - time, gated 2026-11-28 (round 7's gate entry). Stage 0 found the parked cycle's two atomics about 16 ns of a literal's 50, one `CompareExchange` 10.4 ns here against a `Volatile.Write`'s 2.5. The take stays an exchange; the park is now `Volatile.Write(ref slot.Parked, parked)`. Why it is sound: the write is a release, so the scope, its tuple and the staged Procs written before it are visible to a @@ -2065,7 +2109,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/literalsite (round thirty-seven, 2026-11-27) - a call with a block in a light frame whose literals are all narrow takes the light site (gaps 16 and 13)** - instructions not counted, time and - bytes, not gated. Change A of `Docs/light-frame-literal-blocks.md`. In a light body with literal blocks + bytes, gated 2026-11-28 (round 7's gate entry). Change A of `Docs/light-frame-literal-blocks.md`. In a light body with literal blocks every call with a block took the full site with the scope made on demand (`blockPass = ... && !BlockLiterals`), so `return nb(&P) if a; nb { }` made a scope on the hot path, which never reaches the literal. Now, when every literal of the body is of the narrow shape (`HasOnlyNarrowLiterals`: no @@ -2093,7 +2137,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/kwfwd (/perf-step, 2026-11-27) - `f(*a, **h)` passes `a` itself and no array for an empty `h`; `def m(*, **)` keeps no copy of its arguments for a `super`** (switch `IR_KWSPLAT_BY_REFERENCE` for the first, on unless `=0`). Built on f7ae738b (claude/perf-lsite, - which has 4320d4a). + which has 4320d4a). Gated 2026-11-28 (round 7's gate entry). - **Where the cost was.** `rest_kw` (`(*a, **k) = two(*a, **k)`) 174 ns against `rest_fwd`'s 71 (CRuby 109, 84), `anon` (`(*, **, &)`) 264 (CRuby 88). Splitting it: binding `**k` costs almost nothing (`kw_recv` = `rest_only`); passing an empty one on costs ~55 ns. Arguments. @@ -2136,7 +2180,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **Left.** `anon` and `rest_kw` are still ~40 ns over CRuby. The ruby2_keywords case above needs a call-site flag ("keywords given explicitly") that every dispatcher reads. `f(*a, k: 1, &g)` (named keywords, not a `**`) still copies. -- **perf/jitisa (2026-11-28, census and timed, not gated) - `is_a?`, `kind_of?` and `instance_of?` in the method JIT's +- **perf/jitisa (2026-11-28, census and timed, gated 2026-11-28 (round 7's gate entry)) - `is_a?`, `kind_of?` and `instance_of?` in the method JIT's typed body** (the census's "MethodCall (screen)": is_a? 693; switch `IR_JIT_TYPE_TEST`). Built on happy-gauss f67ac44 merged with perf/jitbody e19f454. - **What.** `x.is_a?(C)`, `x.kind_of?(C)` and `x.instance_of?(C)` (or on self), with C a constant and no block, @@ -2172,7 +2216,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has more runs (11 on this build, 8 on the base) exited 0. ruby/spec core/kernel is_a, kind_of, instance_of and core/module/case_compare: no failures on either build. IronRuby.Tests (Debug), all 1,402: PASSED. -- **perf/jitrescue (2026-11-28, census and timed, not gated) - `begin`/`rescue`/`else`/`ensure` in the method JIT's +- **perf/jitrescue (2026-11-28, census and timed, gated 2026-11-28 (round 7's gate entry)) - `begin`/`rescue`/`else`/`ensure` in the method JIT's typed body** (gap 22's remainder; switch `IR_JIT_RESCUE`). Built on happy-gauss 4320d4a, perf/jitbody 238d994 and perf/lsite f7ae738 (lazy `$!`, IR_LAZY_ERRINFO). - **Approach.** The handler is not emitted in the typed body. The typed body takes a begin, or a method-level @@ -2216,43 +2260,9 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (call: fetch/0). The test now expects that, plus a new `Point#jump` (a return through an ensure) that is still never (Body); it passes. -- **perf/jitblockparam (2026-11-27, census and timed, not gated) - a typed body for a call without a block** - (switch `IR_JIT_BLOCK_PARAM`). A method whose block parameter is only passed on, `def w(a, b, &k) = - @t.two(a, b, &k)`, was never wrapped (`JitStub.ParameterShape`: "block parameter"), and one passing `&nil` - was refused at the screen (a call with a block). Now `JitStub.BlockParameterOnlyPassed` takes a method whose - block parameter is never read except as `&k`, never assigned, with no yield and no super, and only - mandatory parameters. Its typed body is compiled for a call without a block: there k is nil and `&k` - passes none, as `&nil` always does (`JitScreen.PassesNoBlock`; the screen, `EmitCall` and `TryInlineCall` - take such a call as one without a block). `block_given?` in a method body (not in an outlined loop, not - with optional or keyword parameters, Kernel's and unrefined) compiles to false on the same terms - (`EmitBlockGiven`). Such a body sets `JitCode.AssumesNoBlock`, and the entry adds `block == null` to its - test, so a call with a block runs the generic body, which passes it on. A method the profile saw called - with a block is declined ("called with a block"), at that call if it has a block parameter, before - anything is compiled. Inlined and directly called bodies are only ever called without a block. - Census (Src/StdLib, Util/bench, AWFY): 62 methods up, none down. 61 left "never (block parameter)" - (2 now compile, the rest are maybe), and `FW#pass_nil` left "never (MethodCall two)". Compiles 3,579 -> - 3,583, maybe 3,180 -> 3,238. Traced runs: forward-shapes specialized 4 -> 7, declines 1 -> 1; - delegate-shapes 3 -> 3, 1 -> 1; app-shapes 120 -> 120 specialized, declines 28 -> 29. The new decline, - `CSV::FieldsConverter#each` (`@converters.each(&block)`), is always called with a block; it declines at - its first call. Most of the methods let through pass `&k` to an iterator, so they win nothing: the gain - is a forwarder to a leaf called without a block. Instructions per call (`callgrind/count.sh`, - `Util/bench/forward-shapes.rb`): fixed_blk 2,254 -> 1,703, param_only 2,094 -> 1,699, pass_nil - 2,232 -> 1,697, the same as fixed (1,701). rest, rest_blk, dots and anon are unchanged (rest and dots - read +69 once and 0 on a rerun). Delegate-shapes is unchanged, row for row (its forwarders take a rest - or a block). Clock (ab.rb -r 3, noisy): param_only 54 -> 38 ns against the switch off; the other rows - overlap. `Util/jit-blockparam-matrix.rb` (new: `&k`, `&nil`, block_given? in the caller and callee, - break and next through the passed block, a lambda's return, `&obj` with to_proc once, `&:sym`, send and - Method#call with a block, two layers, anonymous `&`, an inlined callee's block_given?, k read, assigned, - through a binding, super with the implicit block, a deopt with a block in flight, a method always - called with a block, a block every third call, block_given? redefined, refined and in a loop, a - singleton, the callee redefined): CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, - IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, dmeth-jit, block-pass, block-given, forward-rest - and hot-shapes in the same five modes: the same as the base (forward-rest's six bind_call-of-binding rows - differ from CRuby on both). ruby/spec language block, send, yield, super, def and proc: the same as the - base (send's one error is the known `into`). IronRuby.Tests, all 1,377: PASSED. - **perf/hashany (/perf-step, 2026-11-28, on 540bdb0 + e9a8a9e) - `Hash#any?` is Hash's own (rb_hash_any_p); `group_by`, `uniq`, `each_with_object` walk a plain Hash with a one-value - block** - clock only, not gated. `Hash#any? { |k, v| }` 695 -> 403 ns (CRuby 228; 0.58), + block** - clock only, gated 2026-11-28 (round 7's gate entry). `Hash#any? { |k, v| }` 695 -> 403 ns (CRuby 228; 0.58), `group_by` 1334 -> 976 (0.73; CRuby 968), `each_with_object` 1208 -> 906 (0.75; 964), `uniq { }` 1284 -> 924 (0.72; 837); Array rows within the noise. `Hash#any?` now matches CRuby on owner, frames and a prepended, singleton or redefined #each (never called). Enumerable's @@ -2267,7 +2277,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/hashwalk (/perf-core, 2026-11-27, on 52f4f22) - the prelude's Enumerable methods walk a plain Hash with a one-value block (`__plain_each__?`, `IR_HASH_WALK`)** - clock only, - not gated. The lever perf/hsortby named: filter_map, min_by, max_by, sort_by, min_by(n), + gated 2026-11-28 (round 7's gate entry). The lever perf/hsortby named: filter_map, min_by, max_by, sort_by, min_by(n), max_by(n), flat_map and collect_concat walked a Hash with `|*values|` and __enum_item__, though Hash#each yields one [key, value] pair per entry to that block and to `|item|` alike. A Hash whose #each resolves to the built-in one now takes the Array's one-value walk. @@ -2284,7 +2294,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has per method is the price of the same trick there. Hash#any? (3.8x) is C#, /perf-step's. - **perf/cdtree (/perf-step, 2026-11-27, on f67ac44) - CD's `Node#successor` compiles (an identity `==` on a local nothing samples), and a body bound to a callee that was compiled again is compiled - again instead of being put back (gap 3)** - not gated. (1) `x = self; ...; while y && x == y.right`: + again instead of being put back (gap 3)** - gated 2026-11-28 (round 7's gate entry). (1) `x = self; ...; while y && x == y.right`: `TrySampleOfLocal` takes a local whose first value is `self` from self's sample, as it does one from another local or an instance variable; and the `==`/`equal?` decision takes a method local (not a parameter) for an object of a Ruby class when its sample is one or an unsampled attribute access or @@ -2328,7 +2338,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Not done: `tree_insert`'s four changes (see gap 3). - **perf/sinkcarrier (2026-11-28) - the frame's own sink carries a match sink's `$~`: `IR_LIGHT_MATCH_SINK` on by - default (gap 16, the `$~` family)** - not gated. perf/lightmatch (below) was sound but off: its hand-over (a stack + default (gap 16, the `$~` family)** - gated 2026-11-28 (round 7's gate entry). perf/lightmatch (below) was sound but off: its hand-over (a stack of sink scopes per thread, entered, left and taken on every call, with a fault block in the rule) cost about what the late scope did. - The carrier: the frame's sink - a RubyTopLevelScope that holds nothing but `$~` - is the light site's scope @@ -2365,7 +2375,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has does), with or without the switch. - **perf/lightmatch (2026-11-27) - a light frame keeps its `$~` in a CLR variable for its String and Regexp calls (gap - 16, the `$~` family): off by default, `IR_LIGHT_MATCH_SINK=1`** - not gated. Chosen by the census of c1045a0: the + 16, the `$~` family): off by default, `IR_LIGHT_MATCH_SINK=1`** - gated 2026-11-28 (round 7's gate entry). Chosen by the census of c1045a0: the regex lines were its largest refusal (gsub 273, `=~` 230, sub 104, `when` 86, scan 71, split 63, match 54). - CRuby's rules, the matrix's rows: `$~` is the frame's own - a method's match never sets its caller's, which keeps what it had (nil or a match); a block and a lambda see and set their method's; per thread too; `$1`..`$9`, `$&`, @@ -2416,7 +2426,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - Found on the way, not fixed: `instance_eval("$~")` does not see its caller's `$~` (CRuby does), on base too. - **perf/loopreassign (round forty, 2026-11-28) - an outlined loop handed back by an epoch move that - changed nothing it was built on is kept (gap 29)** - not gated. Every constant reassignment anywhere + changed nothing it was built on is kept (gap 29)** - gated 2026-11-28 (round 7's gate entry). Every constant reassignment anywhere moves the code epoch; an outlined loop's safe point compared the safe-point word with the epoch it was compiled at, so the copy handed itself back and the site rebuilt it (after StaleRebuildSpacing), whatever was reassigned. Now `OsrLoopSite.Run` asks `JitLoopGuard.TryKeep` first (the method version @@ -2491,9 +2501,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 477 -> 467, `gem --version` 532 -> 547 and 552 -> 551, `gem list` 935 -> 921 and 950 -> 955, `require "irb"` 953 -> 958 and 974 -> 932, irb 1+1 1063 -> 1037 and 1091 -> 1047: round 4's `-e 1` loss is won back (perf/startup3 and 4). -- **perf/sieve (2026-11-27, gated 2026-11-28 (round 6's gate entry)) - a block-local first assigned inside an `if` branch or a - -- **perf/permute (2026-11-27, not gated) - Integer#downto parks its caller's scope, and a recursive +- **perf/permute (2026-11-27, gated 2026-11-28 (round 7's gate entry)) - Integer#downto parks its caller's scope, and a recursive method parks one scope per level** (switches `IR_PARK_DOWNTO`, `IR_PARKED_DEPTH`). alloc.rb on 9b588fc: Permute 124.5 MB per iteration, 1.45 MB per `permute(6)` (8,660 calls), for an algorithm that needs a 6-element Array. Variants: with `while` in place of `downto` 208 KB (`@count += 1` boxes an Integer @@ -2519,7 +2527,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has block/yield/break as on the base. Left: the `@count` boxes (an Integer instance variable is held boxed, raw only for Floats) and the locals tuple per scoped call. -- **perf/sieve (2026-11-27, not gated) - a block-local first assigned inside an `if` branch or a +- **perf/sieve (2026-11-27, gated 2026-11-28 (round 6's gate entry)) - a block-local first assigned inside an `if` branch or a `while` body no longer keeps the block from being outlined** (switch `IR_BLOCK_LOOP_SCOPED`). AWFY Sieve allocated 100.3 MB per iteration (alloc.rb). Bytes per `sieve` call, by variants: the `while` loops alone 1 KB beyond the 40 KB flags Array; `(2..size).each` with the real block 296 KB, @@ -2979,7 +2987,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has cases above are the ones that must leave a class out. - **perf/fiberbound (2026-11-27) - fibers abandoned while suspended are bounded: a collection when the fibers holding a thread have grown by 256, the reclaimed threads parked for the next ones - (gap 35)** - not gated. Base 78bbfb1 (the round-38 branch at 15285eb with perf/fiberstart). A + (gap 35)** - gated 2026-11-28 (round 6's gate entry). Base 78bbfb1 (the round-38 branch at 15285eb with perf/fiberstart). A suspended fiber holds a thread until a collection finds its handle, and the collector knows nothing of the thread: 3,000 abandoned generators were three collections and 3,017 threads. Now `ThreadOps.FiberCore.Run` counts the fibers that hold a thread, and a fiber about to start @@ -3013,7 +3021,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (60) pass in five plain runs on base and five on new. - **perf/bootparse (2026-11-27) - the string evals of start-up precompiled in the startup library (gap 26)** - - not gated. Base 4703cb5 (f67ac44 with perf/clrlookup). + - gated 2026-11-28 (round 7's gate entry). Base 4703cb5 (f67ac44 with perf/clrlookup). What start-up parses at run time (R2R host, IR_PHASE_TIMES, IR_STARTUP_DLL_TRACE): the string evals, each a prism parse, a transform and a lambda compile on the main thread. They are specification.rb's `set_nil_attributes_to_nil` and kernel_require.rb's Kernel#require (~2.3 ms each, @@ -3051,7 +3059,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has which compiles the same either way. - **perf/clrlookup (2026-11-27) - what makes the CLR member lookups of start-up; Random's class found on first use; field and event names from metadata; a class key for the lookup failure cache (gap 26)** - - not gated. Base 4320d4a. + - gated 2026-11-28 (round 7's gate entry). Base 4320d4a. The finding (a throwaway build that logged each lookup with its module, name, result, caller and time; `ir -e 1`, R2R host): a Ruby method name a module lacks is looked up as a CLR member of each CLR-backed module up the hierarchy (`RubyModule.TryGetClrMember`). That covers Object @@ -3551,7 +3559,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated when merged; gated 2026-11-27 (round 5's gate entry); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope From fcbc67ba20ce44615c11629220b7d43800b9a185 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:42:59 +0000 Subject: [PATCH 293/439] Ledger: drop two entries round 8's merge doubled again The merge of claude/perf-jitbody carried perf/jitisa's and perf/jitblockparam's entries as they were before they were marked gated, so each stood twice, word for word apart from the header. The unmarked copies go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 71 --------------------------------------------- 1 file changed, 71 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 82124b711..09f9bd71a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2115,42 +2115,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has basicobject/!, proc/call: no failures on either build. - IronRuby.Tests (Debug), all 1,403: PASSED. -- **perf/jitisa (2026-11-28, census and timed, not gated) - `is_a?`, `kind_of?` and `instance_of?` in the method JIT's - typed body** (the census's "MethodCall (screen)": is_a? 693; switch `IR_JIT_TYPE_TEST`). Built on happy-gauss - f67ac44 merged with perf/jitbody e19f454. - - **What.** `x.is_a?(C)`, `x.kind_of?(C)` and `x.instance_of?(C)` (or on self), with C a constant and no block, - compile to `JitRuntime.IsKindOf`. It does Kernel's test with no frame or call: the ancestors of x's immediate - class, its singleton class included (`RubyContext.IsKindOf`), or `GetClassOf(x) == C` for instance_of?. - - **Guards.** C is the folded constant, guarded by the entry's constant version. A constant folded to something - that is no module bails at compile time. The new `JitRuntime.KernelMethodSite` checks that x's class resolves - the name to Kernel's method (public) under the current global method version. It keeps four entries - (class, version), each immutable, so a racing write only loses an entry. A class that resolves to anything - else deopts, and the generic call handles it: a BasicObject's NoMethodError, method_missing, a redefinition in - the class, a singleton or Kernel, a non-module C's TypeError, a CLR type group's conversion. Not compiled where - a refinement is active. The ancestors are walked on every test, so an include, prepend or extend after compile - is seen whether or not it moved a method version. - - **The polymorphic site.** IdentityCallSite holds one class and resolves again on every change: an `is_a?` fed - two classes in turn was no faster than the generic call (poly2 89.4 vs 89.3 ns). Four entries fix that. - - **Census** (Src/StdLib, Util/bench, AWFY): 180 methods up, none down, all never -> maybe. 154 are maybe only - because the census resolves no constant without a scope; 26 are behind a call. - - **Hot methods.** AWFY calls none of the three. app-shapes: 118 -> 121 specialized (`Set#__core_set__?`, - `check_refused` twice); declines 29 -> 32. The three new declines are existing screen optimism that the - `is_a?` refusal used to hide: `v.to_i` and `n.call` taken as possible attribute reads (URI::Generic#set_port, - Enumerator::Lazy#size) and a deopt after an effect at `[]` (CSV::Parser#prepare_variable). By clock - (ab.rb -r 7), app-shapes' rules and set overlap the switch off (1.01 each). - - **Clock** (ab.rb -r 3, `Util/bench/isa-shapes.rb`, ns, off -> new, CRuby): mono 72.9 -> 57.2 (46.9), poly2 - 89.8 -> 71.8 (63.5), poly4 143.6 -> 91.5 (62.9), a module argument 76.0 -> 65.7 (51.8), instance_of 67.3 -> - 54.3 (46.1), an Integer/Float/else chain 150.6 -> 126.2 (75.3), on self 71.4 -> 52.3 (42.6); no overlap. - - **Checks.** `Util/jit-isa-matrix.rb` (new, 37 rows): receivers of every kind; Comparable, Enumerable, Module - and Class arguments; instance_of? with a singleton class; include, prepend and extend (an Object, a String, - Integer) after the body is hot; a constant swapped to another class and to a non-module; is_a?(5); a - BasicObject; method_missing; is_a? redefined in a class, a singleton, a class reopened and Kernel, then - restored; refined. It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, - IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, jit-const, hot-shapes, sdef and extend in the same - five modes: CRuby's output on both builds. One sdef run with the JIT on exited 1 with the right output; 19 - more runs (11 on this build, 8 on the base) exited 0. ruby/spec core/kernel is_a, kind_of, instance_of and - core/module/case_compare: no failures on either build. IronRuby.Tests (Debug), all 1,402: PASSED. - - **perf/lightlambda (2026-11-28) - a lambda literal in a branch no longer keeps its method out of light frames** - not gated. Chosen by the census of 50b07b5 + 8092170: LambdaDefinition, 73 methods, the next light-frame refusal after the `$~` family. @@ -2184,41 +2148,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has for blocks, lambdas, procs, closures, yield, return, break and next pass with the switch on and off; the whole suite was refused by the session's permission check and not run. -- **perf/jitblockparam (2026-11-27, census and timed, not gated) - a typed body for a call without a block** - (switch `IR_JIT_BLOCK_PARAM`). A method whose block parameter is only passed on, `def w(a, b, &k) = - @t.two(a, b, &k)`, was never wrapped (`JitStub.ParameterShape`: "block parameter"), and one passing `&nil` - was refused at the screen (a call with a block). Now `JitStub.BlockParameterOnlyPassed` takes a method whose - block parameter is never read except as `&k`, never assigned, with no yield and no super, and only - mandatory parameters. Its typed body is compiled for a call without a block: there k is nil and `&k` - passes none, as `&nil` always does (`JitScreen.PassesNoBlock`; the screen, `EmitCall` and `TryInlineCall` - take such a call as one without a block). `block_given?` in a method body (not in an outlined loop, not - with optional or keyword parameters, Kernel's and unrefined) compiles to false on the same terms - (`EmitBlockGiven`). Such a body sets `JitCode.AssumesNoBlock`, and the entry adds `block == null` to its - test, so a call with a block runs the generic body, which passes it on. A method the profile saw called - with a block is declined ("called with a block"), at that call if it has a block parameter, before - anything is compiled. Inlined and directly called bodies are only ever called without a block. - Census (Src/StdLib, Util/bench, AWFY): 62 methods up, none down. 61 left "never (block parameter)" - (2 now compile, the rest are maybe), and `FW#pass_nil` left "never (MethodCall two)". Compiles 3,579 -> - 3,583, maybe 3,180 -> 3,238. Traced runs: forward-shapes specialized 4 -> 7, declines 1 -> 1; - delegate-shapes 3 -> 3, 1 -> 1; app-shapes 120 -> 120 specialized, declines 28 -> 29. The new decline, - `CSV::FieldsConverter#each` (`@converters.each(&block)`), is always called with a block; it declines at - its first call. Most of the methods let through pass `&k` to an iterator, so they win nothing: the gain - is a forwarder to a leaf called without a block. Instructions per call (`callgrind/count.sh`, - `Util/bench/forward-shapes.rb`): fixed_blk 2,254 -> 1,703, param_only 2,094 -> 1,699, pass_nil - 2,232 -> 1,697, the same as fixed (1,701). rest, rest_blk, dots and anon are unchanged (rest and dots - read +69 once and 0 on a rerun). Delegate-shapes is unchanged, row for row (its forwarders take a rest - or a block). Clock (ab.rb -r 3, noisy): param_only 54 -> 38 ns against the switch off; the other rows - overlap. `Util/jit-blockparam-matrix.rb` (new: `&k`, `&nil`, block_given? in the caller and callee, - break and next through the passed block, a lambda's return, `&obj` with to_proc once, `&:sym`, send and - Method#call with a block, two layers, anonymous `&`, an inlined callee's block_given?, k read, assigned, - through a binding, super with the implicit block, a deopt with a block in flight, a method always - called with a block, a block every third call, block_given? redefined, refined and in a loop, a - singleton, the callee redefined): CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, - IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, dmeth-jit, block-pass, block-given, forward-rest - and hot-shapes in the same five modes: the same as the base (forward-rest's six bind_call-of-binding rows - differ from CRuby on both). ruby/spec language block, send, yield, super, def and proc: the same as the - base (send's one error is the known `into`). IronRuby.Tests, all 1,377: PASSED. - - **perf/kwbind (/perf-step, 2026-11-28) - a `**rest` parameter is the call's own keyword hash, the declared keywords taken out in place** (gap 38; switch `IR_KWREST_TAKE`, on unless `=0`). Built on 33818f7 (claude/happy-gauss-95wm2j) with d45083a0 merged. From e3803638a87ca4ab997c3085c3051e7c74317405 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:47:36 +0000 Subject: [PATCH 294/439] An Array without instance data is answered its class without the instance data table The premise of the round was that calling a C# Kernel method costs ~28 ns over CRuby whatever it does. Counted (callgrind, instructions a call over an empty method in the same harness), it does not: Integer(5) costs what @i.gcd(4) costs, implicit and explicit self the same, and the rows' gap to CRuby is the harness's call of a Ruby method, which every row pays. What the counts did show: a Kernel method called on an Array in a compiled (method JIT) body cost ~370 instructions more than on a Hash or a String - @a.nil? 1043 over the floor, @h.nil? 673 - and the same body without the JIT did not (2189 against 2170). Every compiled call that asks a CLR object's class (JitRuntime.ClassOf, the identity, kind and attribute sites) goes to RubyContext.GetImmediateClassOfNonRubyObject. For a class with an instance that has a class of its own it then looks the object up in the instance data table (a ConditionalWeakTable) and resolves its class again. Array always has one: $LOAD_PATH, whose resolve_feature_path is a singleton method, as in MRI - so every array of every process took the slow path. RubyArray now keeps a bit, set (atomically, before the entry is added) when some runtime makes instance data for it - instance variables, an object id, a singleton class. An array without it has none: TryGetClrTypeInstanceData answers so without the table, and GetImmediateClassOfNonRubyObject answers its CLR type's class (unless the type has adopted instances). The bit only ever says "look in the table", for any runtime, so several runtimes in a process stay apart. Freeze sets its bit with Interlocked.Or too, so that the two cannot lose each other. IR_ARRAY_CLASS_FAST=0 turns it off. Instructions a call (count.sh, unchanged -> this): @a.nil? in a compiled body 2531 -> 2172 (@h.nil? 2161); @a.first 2246 -> 2228; @a.frozen?, Array(@a), @h.nil?, an object's nil? and the empty method unchanged. Clock (ab.rb, four rounds): @a.nil? 95.9 -> 75.7 ns (0.79), Array#dig 325.7 -> 284.3 (0.87); sum, min, take, first(n), include?, each, zip, Array(), frozen? within the noise. Util/array-class-matrix.rb (new: an array given a singleton class, a singleton nil?, extend, instance variables, object_id, freeze before and after, clone and dup, an Array subclass, $LOAD_PATH's singleton, threads giving arrays singleton classes and one defined while another thread calls through a compiled body; and Kernel functions with an implicit self: a class's own Array, private Kernel#Array, Kernel.Array, method_missing, BasicObject, Kernel#Array redefined, a refinement of Kernel) prints CRuby's output but for _id2ref (as before), by default, IR_ARRAY_CLASS_FAST=0, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. light-entry, shared-rule-light, kernel-string, numeric-conversion, jit, jit-calls, ivar and hot-shapes print what they did in those modes. ruby/spec core/kernel, core/array and core/objectspace: the same examples on both builds. IronRuby.Tests (Debug): the 331 Array, Singleton, Clone, Dup, Ivar, Object, Clr, Jit, Freeze, Kernel, Backtrace and Thread tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/Ruby/Builtins/RubyArray.cs | 21 +++++- Src/Ruby/Runtime/RubyContext.cs | 17 +++++ Util/array-class-matrix.rb | 126 ++++++++++++++++++++++++++++++++ 3 files changed, 163 insertions(+), 1 deletion(-) create mode 100644 Util/array-class-matrix.rb diff --git a/Src/Ruby/Builtins/RubyArray.cs b/Src/Ruby/Builtins/RubyArray.cs index 12344849d..7a5788a56 100644 --- a/Src/Ruby/Builtins/RubyArray.cs +++ b/Src/Ruby/Builtins/RubyArray.cs @@ -19,6 +19,7 @@ using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Diagnostics; +using System.Threading; using IronRuby.Runtime; using Microsoft.Scripting; using Microsoft.Scripting.Utils; @@ -40,6 +41,11 @@ public partial class RubyArray : IList, IList, IRubyObjectState, IDuplic private uint _flags; private const uint IsFrozenFlag = 1; + // Set once some runtime has made instance data for this array (RubyContext.GetInstanceData): its instance + // variables, object id or singleton class. Until then the array has none, and RubyContext.TryGetClrTypeInstanceData + // answers so without the weak table lookup - which every array paid, in GetImmediateClassOf, as soon as any one + // array of the process had a singleton class ($LOAD_PATH has one, as in MRI: resolve_feature_path). + private const uint MayHaveInstanceDataFlag = 2; [Conditional("DEBUG")] private void ObjectInvariant() { @@ -170,10 +176,23 @@ void IRubyObjectState.Freeze() { } public RubyArray/*!*/ Freeze() { - _flags |= IsFrozenFlag; + // atomic: MarkMayHaveInstanceData may set the other bit at the same time + Interlocked.Or(ref _flags, IsFrozenFlag); return this; } + // IR_ARRAY_CLASS_FAST=0: every array may have data, and its class is looked up as before + private static readonly bool _classFast = Environment.GetEnvironmentVariable("IR_ARRAY_CLASS_FAST") != "0"; + + internal bool MayHaveInstanceData { + get { return !_classFast || (Volatile.Read(ref _flags) & MayHaveInstanceDataFlag) != 0; } + } + + // before the data is published, so that a reader that finds the bit clear finds no data either + internal void MarkMayHaveInstanceData() { + Interlocked.Or(ref _flags, MayHaveInstanceDataFlag); + } + #endregion #region HashCode, Equality diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 9bb664dc1..10f1599f0 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -2444,6 +2444,12 @@ private RubyClass TryGetClassOfRubyObject(object obj) { if (!result.HasInstancesWithOwnClass) { return result; } + // an array no runtime has made instance data for has no class of its own (RubyArray.MayHaveInstanceData): + // $LOAD_PATH's singleton class sent every array of the process down the lookups below + var array = obj as RubyArray; + if (array != null && !array.MayHaveInstanceData && !result.HasAdoptedInstances) { + return result; + } } RubyInstanceData data = TryGetNonRubyObjectInstanceData(obj); if (data != null && (result = data.ImmediateClass) != null) { @@ -2951,6 +2957,12 @@ private bool MayHaveValueTypeInstanceData(Type/*!*/ type) { } internal bool TryGetClrTypeInstanceData(object/*!*/ obj, out RubyInstanceData result) { + // an array no runtime has made data for (RubyArray.MayHaveInstanceData): nothing to find in the table + var array = obj as RubyArray; + if (array != null && !array.MayHaveInstanceData) { + result = null; + return false; + } var owner = obj as IRubyInstanceDataOwner; if (owner != null && owner.TryGetInstanceData(this, out result)) { return result != null; @@ -3015,6 +3027,11 @@ public void ReplaceClrObjectClass(object/*!*/ obj, RubyClass/*!*/ cls) { if (_referenceTypeInstanceData.TryGetValue(obj, out result)) { return result; } + // marked before the entry is added: see TryGetClrTypeInstanceData + var array = obj as RubyArray; + if (array != null) { + array.MarkMayHaveInstanceData(); + } return _referenceTypeInstanceData.GetValue(obj, _CreateInstanceData); } diff --git a/Util/array-class-matrix.rb b/Util/array-class-matrix.rb new file mode 100644 index 000000000..ff1092927 --- /dev/null +++ b/Util/array-class-matrix.rb @@ -0,0 +1,126 @@ +# Differential matrix for the class of an Array that is not an IRubyObject (a plain RubyArray): its singleton class, +# instance variables, object id, frozen state, dup and clone, as compiled code and call sites find them. An array no +# runtime has made instance data for is answered its class without the instance data table +# (RubyArray.MayHaveInstanceData), even while some other array - $LOAD_PATH - has a singleton class. Also what a Kernel +# function called with an implicit self resolves to. Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/array-class-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/array-class-matrix.rb > /tmp/ir.txt 2>&1 +# diff /tmp/mri.txt /tmp/ir.txt + +def t(label) + print label.ljust(52), ' => ' + begin + puts yield.inspect + rescue Exception => e + puts "#{e.class}: #{e.message.gsub(/0x\h+/, '0x')}" + end +end + +class Probe + def initialize(a) = @a = a + def nil_p = @a.nil? + def cls = @a.class + def sc = @a.singleton_methods.sort + def kind = [@a.is_a?(Array), Array === @a, @a.instance_of?(Array)] + def eq(x) = @a == x + def hello = @a.respond_to?(:hello) ? @a.hello : :none +end + +# hot loops, so that the methods are compiled; then the receivers change under them +def hot(p, n = 3000) = n.times { p.nil_p; p.cls; p.kind; p.hello } + +# ---------------------------------------------------------------- 1. a plain array, then one given a singleton class +a = [1, 2] +p1 = Probe.new(a) +hot(p1) +t('plain: nil?, class, kind, hello') { [p1.nil_p, p1.cls, p1.kind, p1.hello] } +def a.hello = :singleton +t('after def a.hello') { [p1.hello, p1.cls, p1.kind, p1.sc, a.singleton_class.instance_methods(false)] } +hot(p1) +t('hot again') { [p1.hello, p1.nil_p] } +def a.nil? = :mine +t('a singleton nil?') { [p1.nil_p, a.nil?] } +b = [3] +pb = Probe.new(b) +hot(pb) +t('another array, unaffected') { [pb.nil_p, pb.hello, pb.sc] } + +# ---------------------------------------------------------------- 2. instance data without a singleton class +c = [4] +pc = Probe.new(c) +hot(pc) +c.instance_variable_set(:@iv, 5) +t('an instance variable') { [c.instance_variable_get(:@iv), c.instance_variables, pc.nil_p, pc.cls] } +d = [5] +id = d.object_id +t('object_id stays') { [d.object_id == id, ObjectSpace._id2ref(id).equal?(d)] rescue [d.object_id == id] } +e = [6].freeze +t('frozen') { [e.frozen?, (e << 1 rescue $!.class)] } +f = [7] +f.freeze +t('frozen later') { [f.frozen?, (f << 1 rescue $!.class), Probe.new(f).nil_p] } +g = [8] +g.instance_variable_set(:@x, 1) +g.freeze +t('ivar then frozen') { [g.frozen?, g.instance_variable_get(:@x), (g.instance_variable_set(:@y, 2) rescue $!.class)] } +h = [9] +h.extend(Module.new { def hello = :extended }) +t('extend') { [Probe.new(h).hello, h.singleton_class.ancestors.size > Array.ancestors.size] } + +# ---------------------------------------------------------------- 3. dup, clone +s = [1] +def s.hello = :s +s.instance_variable_set(:@v, 1) +t('clone keeps the singleton and ivars') { x = s.clone; [Probe.new(x).hello, x.instance_variable_get(:@v)] } +t('dup keeps ivars, not the singleton') { x = s.dup; [Probe.new(x).hello, x.instance_variable_get(:@v)] } +t('clone(freeze: true)') { x = [1].clone(freeze: true); [x.frozen?, Probe.new(x).nil_p] } +t('an Array subclass') { k = Class.new(Array); x = k.new; def x.hello = :sub; [Probe.new(x).hello, Probe.new(x).cls == k] } + +# ---------------------------------------------------------------- 4. $LOAD_PATH, threads +t('$LOAD_PATH.resolve_feature_path') { [$LOAD_PATH.singleton_methods.include?(:resolve_feature_path), $LOAD_PATH.resolve_feature_path('erb')&.first] } +t('threads give arrays singleton classes') do + arrays = Array.new(8) { [_1] } + probes = arrays.map { Probe.new(_1) } + ths = arrays.each_with_index.map { |x, i| Thread.new { 200.times { probes[i].hello }; x.define_singleton_method(:hello) { i }; probes[i].hello } } + ths.map(&:value) +end +t('a singleton defined while another thread calls') do + x = [0] + px = Probe.new(x) + th = Thread.new { r = nil; 20000.times { r = px.hello }; r } + def x.hello = :late + th.join + px.hello +end + +# ---------------------------------------------------------------- 5. Kernel functions called with an implicit self +class OwnArray + def Array(x) = :own + def call = Array([1]) +end +class Missing + def method_missing(m, *a) = m == :Zz ? :mm : super + def call = Zz(1) +end +module RefineKernel + refine Kernel do + def Array(x) = :refined + end +end +t('a class with its own Array') { OwnArray.new.call } +t('Kernel#Array is private') { Object.new.Array([1]) } +t('Kernel.Array') { Kernel.Array(nil) } +t('method_missing for a function call') { Missing.new.call } +t('BasicObject has no Array') { Class.new(BasicObject) { def call = Array(1) }.new.call } +t('Kernel#Array redefined, restored') do + module Kernel; alias __saved_array__ Array; private def Array(x) = :redefined; end + begin + [Array(1), OwnArray.new.call] + ensure + module Kernel; alias Array __saved_array__; remove_method :__saved_array__; private :Array; end + end +end +t('restored') { Array(nil) } +using RefineKernel +t('a refinement of Kernel#Array') { Array(1) } From 672867e4f8afe8a8990451ac7c8d8ab720305806 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:47:36 +0000 Subject: [PATCH 295/439] Ledger: perf/kernelcall landed (not gated) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 170c6ae52..f6e128585 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1994,6 +1994,24 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kernelcall (/perf-step, 2026-11-28, on 744b83e) - an Array without instance data is + answered its class without the instance data table (`RubyArray.MayHaveInstanceData`, + `IR_ARRAY_CLASS_FAST`)** - instructions and clock, not gated. The round's premise (a C# Kernel + call costs ~28 ns over CRuby whatever it does) did not hold when counted: over an empty + method in the same harness, `Integer(5)` costs what `@i.gcd(4)` costs, implicit and explicit + self alike, and the rows' gap to CRuby is the harness's Ruby call. The outlier the counts + found: a Kernel method on an Array in a compiled body, ~370 instructions over a Hash's, because + `$LOAD_PATH`'s singleton class (as in MRI) sent every array's class lookup + (GetImmediateClassOfNonRubyObject) to the weak instance data table. A bit set before any + runtime makes data for an array now skips it. `@a.nil?` compiled 2531 -> 2172 instructions + (`@h.nil?` 2161), 95.9 -> 75.7 ns; `Array#dig` 325.7 -> 284.3 ns; other Array rows within the + noise. `Util/array-class-matrix.rb` (new) CRuby's but for `_id2ref` (as before) in five modes, + switch off and R2R; light-entry, shared-rule-light, kernel-string, numeric-conversion, jit, + jit-calls, ivar, hot-shapes unchanged; ruby/spec core/kernel, array, objectspace the same + examples; 331 IronRuby.Tests on Debug pass. Left: the same table cost for any other CLR class + once one of its instances has a singleton class (a String's, a Hash's) - the bit is RubyArray's + alone; and the harness's own Ruby call (gap 13). + - **perf/kinteger (2026-11-28, on 33818f7 + 51f5637) - `Kernel#String` asks for #to_str as rb_check_funcall does; `Integer("1234")` rejected, nothing to win** - not gated. - Part 1 (correctness, from perf/kstring's leftovers): `__ir_check_to_str__` calls a private From b7959f6484c04430369577b0e9cc4b046d980801 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 11:33:44 +0000 Subject: [PATCH 296/439] Ledger: perf/namedblock Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/perf/LEDGER.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 2980300b8..8c87c2276 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1439,6 +1439,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has good), `Object[]` 20% (the instance-variable slot arrays of new objects and the Vectors' storage), `Range` 8% (`(a..b).each` makes one per call), and the light `Vector#each` costs 3-4% more instructions per call than the scope-ful one did. + Round forty-two took the first of those (see Landed, perf/namedblock): a block that a + method only passes on stays reusable. Havlak 1.33 -> 1.17 GB an iteration. 26. **Start-up: `gem` and `irb` answer in 0.7 to 2.2 s, CRuby in 0.1 to 0.2** (the one thing that has to stay fast while the tiers stay on by default, and it is not fast). 2026-11-18, a7060a27, the ReadyToRun host (`IR_CONFIG=R2R`, what `ir.sh` runs when @@ -2004,6 +2006,48 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/namedblock 4e87b11 977e047 (round forty-two, 2026-11-28) - a named block that a method only + passes on stays reusable (gap 25)** - not gated. `def each(&b) = @items.each(&b)` (som.rb's `SomSet#each`, + `has_some`, `get_one`; 5 of AWFY's 6 methods with a named block, about 320 of the standard library's + 800) converted its caller's literal for good (`EnterLightMethodNamingBlock`: ConvertAsMethodFrame), so no + caller passing a literal to it could make its Proc again or park its scope: a caller of `SomSet#each` 374 B + per call, `contains` 406. A method whose block parameter is only passed on (`JitStub.BlockParameterOnlyPassed`: + `&b` arguments, no other read, no yield, no super) now converts a literal block reusable + (`Proc.ConvertAsPassingMethodFrame`, `RubyOps.EnterLightMethodPassingBlock`), and each call it passes the + block to holds it (`Proc.PassHeldFlag`, not reusable while set; `HoldPassedBlock` around the call, + `EndPassedBlock` after it). Receivers known to keep nothing lift the hold as they take the block - a light + frame that only yields, a [BlockNotKept] library method, another method that only passes it on - and when + the call returns a hold still set (a receiver the binder hands a Proc to, a library method that may keep it, + a CLR method) makes the block not reusable for good, as does an exception or a break out of the call. A + Ruby method that may keep a block that is not its own call's literal - one naming it + (`EnterLightMethodNamingBlock`) or with a scope (`CreateRfcForMethod`) - clears its reuse for good as it + takes it: the first version had only the confirmations, and Richards' `TaskControlBlock#initialize`, which + stores its `&block` and calls `super()` (passing it to `TaskState#initialize`, a light frame that only + yields), had its block confirmed and the caller's literal made again for the next task - + NullReferenceException; alloc.rb's FAIL found it, the matrix had not. Switch: IR_PASSED_BLOCKS=0. + Bytes (alloc.rb against 5fe9f8a): Havlak 1,334,668,414 -> 1,172,432,918 (0.88), the rest level (Towers + 106-165 KB and Richards 754-793 KB swing on both builds); geomean 0.972. Per call (probe): a caller of + `SomSet#each` 374 -> 134 B, of `SomSet#contains` 406 -> 166. Time, ten alternating AWFY processes each, + medians: against the base Havlak 0.984 (ranges 2.51-2.96 and 2.41-2.87 s), DeltaBlue 1.002, CD 0.987; in + one tree with the switch off and on Havlak 0.948. Instructions (callgrind, switch off -> on): `set_each` + -0.4%, `set_contains` +0.7%, `find_set` -0.1%, `vec_each` level. + Checks: Util/passed-block-matrix.rb (new: passed to a light frame that only yields, to a [BlockNotKept] + method, through two passing methods; kept by the receiver, on some calls, through a chain, by Hash.new, + define_method and Enumerator.new; identity across the pass; block_given?; break; a Method and a lambda + passed through; an exception while held; threads; a receiver that calls super with the block and one + that stores it and passes it on) and two-thread rows in Util/parked-scope-matrix.rb; with EndPass made + not to clear the reuse flag 8 rows go wrong, and with the two clears of the fix taken out the last two + rows go wrong. passed-block, held-block, block-pass, block-given, parked-scope, jit-blockparam, + light-entry, hot-shapes, nested-proc, block-scope-reuse, super-light in the gate's six modes and + IR_PASSED_BLOCKS=0: 77 same. ruby/spec language/block, send, def, break, core/proc, + core/kernel/block_given, core/module/define_method: as on the base (send and define_method have their one + known `into`/`to` error on both). IronRuby.Tests, Debug net10.0: 1,416 tests, none failed or flaky, as on + the base. No AWFY benchmark fails. + For the gate: every receiver the binder can hand a Proc to without a Ruby entry or a BlockParam (the hold + stays set there, so the block is not reused, but a receiver that confirms after keeping would be wrong); + the receivers that confirm (`EnterLightMethodWithBlock`, `CreateBfcForBlockNotKept`, + `EnterLightMethodPassingBlock`), which must keep nothing. + - **perf/havlakalloc 56526b1 c8010fb (round forty-one, 2026-11-28) - a light frame's scope holds its block until it is parked, not for good (gap 25)** - not gated. Havlak allocated 1.77 GB per iteration; the allocation-tick probe gave method scopes 25%, `Object[]` 16%, Procs 14.5%, Range 6%, BlockParams 6%. From eead04ccc89a205d4cd6dc629b9a656b0ea67f13 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:37:50 +0000 Subject: [PATCH 297/439] Ledger: a thread-owned parking spot, measured and rejected perf/ownerpark gave each parking slot a spot that only the first thread to park uses, with plain loads and stores, so that thread's calls take and park their scope without an atomic. The harness showed 3 ns a call (take and park 11 -> 8 ns, e1's steps 39 -> 36), and ab.rb -r 10 showed nothing end to end on e1, eachl, each1, map1, times1, nyl and nbl, every row overlapping. Not kept; the census is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Util/perf/LEDGER.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 09f9bd71a..190f9c89d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -8527,6 +8527,21 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/ownerpark (round thirty-seven, 2026-11-28) - a parked scope the thread that parked first takes and parks with plain + loads and stores: measured, not kept** (gap 13). The take of a parked scope is the cycle's one atomic left after + perf/endpark. The prototype (`IR_PARK_OWNER`) gave `ParkedScopeSlot` an `Owner` (the first thread to park, set once by + compare-exchange) and an `Owned` spot only that thread reads and writes; every other thread, and the owner when `Owned` is + taken (a recursion) or full, used `Parked` and `Deeper` with their exchanges as before. Sound for the same reason the + exchanges are: an object is in one place at a time and each place is taken exclusively (`Owned` by the one thread that + uses it), a Fiber runs on a thread of its own, and a trap handler or finalizer running at a safe point inside a call finds + `Owned` taken. Harness (`IronRuby.Tests /blockcost`), ns, off/on: take and park (P1) 11.0/8.0, the parked cycle 37.7/33.3, + `e1`'s steps 38.8/35.8, `nyl`'s 43.6/39.7. End to end, `ab.rb -r 10` off/on, ns per call: `e1` 96.0/96.0, `eachl` + 92.0/92.0, `each1` 111.5/107.3, `map1` 123.5/127.1, `times1` 107.9/111.0, `nyl` 107.5/107.4, `nbl` 99.0/97.2, controls `ep`, + `call`, `nb0` level - every row overlapping. 3 ns a call is under the noise of a call that now costs 90-110 ns, as + perf/endpark's 8 ns was; not worth a second parking place and a thread that keeps one ParkedProcs after it ends. Census + (Src/StdLib and Util/bench): no method changed, as a runtime-only change. With perf/endpark, the parked cycle's atomics are + done: what is left of it is reinitializing the scope and the Procs. + - **perf/jitcalls, second round (2026-11-28) - stage 3's first step or stage 4's slice: measured, designed, not built** (gap 1). Chosen by what the JIT declines in eight AWFY benchmarks: every hot method turned away after the screen is turned away by the effect rule (`append`, `release`, `hold_self`, `remove_first`, `split_bucket`, From 6f29f0b0a175b0e2aa45e506191478e87fbb750b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:45:11 +0000 Subject: [PATCH 298/439] Method JIT: `C === x` of a class or module constant as Module#=== `C === x` was refused by the method JIT's screen: 304 methods, 170 by it alone. With C a class or a module it is Module#===, a walk of x's ancestors that asks x nothing. It now compiles to JitRuntime.ModuleCaseEquals, for a constant named as a class or module is (not SCREAMING_CASE, which holds a Regexp or the like). The constant is folded under the entry's constant version guard, and one that is no module bails. A KernelMethodSite checks that C's own class resolves === to Module's library method, else it deopts (a `def C.===`, Module#=== redefined). Not where a refinement is active. IR_JIT_CASE_EQ=0 turns it off. Util/bench/isa-shapes.rb: `IBase === x` 104.0 -> 73.8 ns, an Integer/ Float/else chain 119.9 -> 81.2 (CRuby 51.9 and 62.6). Census: 39 methods never -> maybe, none down. Util/jit-caseeq-matrix.rb (new) prints CRuby's output in every JIT mode; Module#=== and case specs pass. The other matrices and IronRuby.Tests are owed: the round was paused while they ran (LEDGER.md says which). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 2 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 48 +++++++++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 10 ++ Util/bench/isa-shapes.rb | 11 +- Util/jit-caseeq-matrix.rb | 131 +++++++++++++++++++++++ Util/perf/LEDGER.md | 28 +++++ 6 files changed, 228 insertions(+), 2 deletions(-) create mode 100644 Util/jit-caseeq-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index cd943c6cd..bb4d22e41 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -308,7 +308,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { // deopt), a type or identity test (a class that resolves the method to anything but the library's deopts) and // `x.to_i' of an Integer, nil or a plain decimal String: no Ruby code, no instance variable, nothing but a deopt "IndexInt", "IndexLong", "IndexObj", "IndexIntChecked", "IndexLongChecked", "IndexObjChecked", "HashKeyInt", - "IsKindOf", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", + "IsKindOf", "ModuleCaseEquals", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", }; // Integer#abs of an Int32 (widened, so it cannot overflow) and Float#abs (JitCompiler.EmitCall) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 0369fdd3b..94497e168 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -2590,6 +2590,46 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { internal static readonly bool SinkBoxedBooleans = Environment.GetEnvironmentVariable("IR_JIT_SINK_BOXED") != "0"; internal static readonly bool ScreenRefusesCall = Environment.GetEnvironmentVariable("IR_JIT_SCREEN_CALL") != "0"; + // IR_JIT_CASE_EQ=0 turns EmitModuleCaseEquality off + internal static readonly bool ModuleCaseEquality = Environment.GetEnvironmentVariable("IR_JIT_CASE_EQ") != "0"; + + /// + /// `C === x', C a constant named as a class or a module is (`Integer', `Foo::Bar'; not `PATTERN', which holds a value + /// whose === is its own - a Regexp's sets $~ - and would only be declined), with no block. + /// + internal static bool IsModuleCaseEquality(MethodCall/*!*/ node) { + if (!ModuleCaseEquality || node.MethodName != "===" || node.Block != null) { return false; } + var constant = node.Target as ConstantVariable; + var args = node.Arguments; + if (constant == null || args == null || args.Expressions.Length != 1 || args.Expressions[0] is SplattedArgument) { return false; } + foreach (char c in constant.Name) { + if (Char.IsLower(c)) { return true; } + } + return false; + } + + /// + /// `C === x' where C is a class or a module: Module#===, which is Kernel#is_a? turned around - whether x's class (its + /// singleton class included) has C among its ancestors - asked without x's is_a? (JitRuntime.ModuleCaseEquals). C is + /// the folded constant, which the entry's constant version guards, and a C that is no module bails here. The site + /// checks that C's own class (its singleton class, for a class or a module that has one) resolves === to Module's + /// library method under the current global method version, and deopts otherwise: a `def self.===' or a refinement of + /// it is the generic call's. Not where a refinement is active. + /// + private MSA.Expression/*!*/ EmitModuleCaseEquality(MethodCall/*!*/ node, out JT type) { + if (!_refinements.IsEmpty) { throw Bail("=== with refinements active"); } + JT ct; + var module = Coerce(Emit(node.Target, out ct), ct, JT.Obj); + var folded = module as MSA.ConstantExpression; + if (folded == null || !(folded.Value is RubyModule)) { throw Bail("=== of a constant that is no module"); } + var site = new JitRuntime.KernelMethodSite("===", LibraryMethods("===", _context.ModuleClass)); + JT vt; + var value = Coerce(Emit(node.Arguments.Expressions[0], out vt), vt, JT.Obj); + _canDeopt = true; + type = JT.Bool; + return Ast.Call(JitRuntime.M("ModuleCaseEquals"), Ast.Constant(_context), module, value, Ast.Constant(site)); + } + // IR_JIT_TYPE_TEST=0 turns EmitTypeTest off internal static readonly bool TypeTests = Environment.GetEnvironmentVariable("IR_JIT_TYPE_TEST") != "0"; @@ -2655,6 +2695,9 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { // `x.is_a?(C)', `kind_of?', `instance_of?' (EmitTypeTest) if (IsTypeTest(node)) { return EmitTypeTest(node, out type); } + // `C === x' (EmitModuleCaseEquality) + if (IsModuleCaseEquality(node)) { return EmitModuleCaseEquality(node, out type); } + // Self-recursion: `fib(n - 1)' inside `def fib'. Sound because the entry stub pins // the receiver class and the global method version, so no override can slip in. if (_ast != null && _keywords == null && node.Target == null && !node.IsVariableCall && node.MethodName == _ast.Name && argc == _paramNames.Length) { @@ -4391,6 +4434,11 @@ private bool WalkCall(MethodCall/*!*/ node) { return WalkCondition(node.Target); } + if (JitCompiler.IsModuleCaseEquality(node)) { + // `C === x' (JitCompiler.EmitModuleCaseEquality): C a constant, x any object + return (WalkConstant((ConstantVariable)node.Target) || No(node)) && Walk(args.Expressions[0]); + } + if (JitCompiler.IsTypeTest(node)) { // `x.is_a?(C)' and the like (JitCompiler.EmitTypeTest): x is any object, C a constant return (node.Target == null || Walk(node.Target)) && (WalkConstant((ConstantVariable)args.Expressions[0]) || No(node)); diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index 7fdb23f7f..997fa1668 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -470,6 +470,16 @@ public static object ToIntegerObject(RubyContext/*!*/ context, object value, Ker throw Deopt(); } + /// + /// `C === x' with C a module (JitCompiler.EmitModuleCaseEquality): Module#===, x's immediate class has C among its + /// ancestors, once the site found C's own class to resolve === to Module's library method; otherwise a deopt. + /// + public static bool ModuleCaseEquals(RubyContext/*!*/ context, object m, object value, KernelMethodSite/*!*/ site) { + var module = m as RubyModule; + if (module == null || !site.Resolves(ClassOf(context, module))) { throw Deopt(); } + return module.Context.IsKindOf(value, module); + } + /// /// Which receiver classes resolve a name to one of the library methods given (KernelMethodSite.Resolves), each under the /// global method version it was found at, for a few classes at once: a type test (`x.is_a?(C)') sees receivers of diff --git a/Util/bench/isa-shapes.rb b/Util/bench/isa-shapes.rb index 179646f34..e9939e467 100644 --- a/Util/bench/isa-shapes.rb +++ b/Util/bench/isa-shapes.rb @@ -1,5 +1,5 @@ # is_a?, kind_of? and instance_of? in hot methods (JitCompiler.EmitTypeTest): one receiver class, two, four, a module -# argument, instance_of?, on self. Every line prints the sum of its results next to its time; it must be CRuby's. +# argument, instance_of?, on self; and `C === x' (JitCompiler.EmitModuleCaseEquality). Every line prints the sum of its results next to its time; it must be CRuby's. # ruby Util/perf/ab.rb Util/bench/isa-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ../ironruby/ir.sh" "new=env IR_CONFIG=Release ./ir.sh" $stdout.sync = true class IBase; end @@ -15,6 +15,13 @@ def num(x) end end def me = is_a?(IS) ? 1 : 0 + def eqq(x) = IBase === x ? 1 : 0 + def eqq_num(x) + if Integer === x then 1 + elsif Float === x then 2 + else 3 + end + end end def cpu; Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID); end def t(name, n) @@ -40,3 +47,5 @@ def t(name, n) t("instance_of", N) { |n| i = 0; r = 0; while i < n; r += o.inst(b); i += 1; end; r } t("num", N) { |n| i = 0; r = 0; while i < n; r += o.num(mixed[i & 3]); i += 1; end; r } t("self", N) { |n| i = 0; r = 0; while i < n; r += o.me; i += 1; end; r } +t("eqq", N) { |n| i = 0; r = 0; while i < n; r += o.eqq(four[i & 3]); i += 1; end; r } +t("eqq_num", N) { |n| i = 0; r = 0; while i < n; r += o.eqq_num(mixed[i & 3]); i += 1; end; r } diff --git a/Util/jit-caseeq-matrix.rb b/Util/jit-caseeq-matrix.rb new file mode 100644 index 000000000..d4ae3c047 --- /dev/null +++ b/Util/jit-caseeq-matrix.rb @@ -0,0 +1,131 @@ +# Differential matrix for `C === x' with C a class or module constant in methods the method JIT compiles +# (JitCompiler.EmitModuleCaseEquality, JitRuntime.ModuleCaseEquals). Run under CRuby and under ./ir.sh in every mode: +# +# ruby Util/jit-caseeq-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-caseeq-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-caseeq-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-caseeq-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep CE +# The traps: Module#=== does not ask x (an is_a? of x's own, a BasicObject, method_missing), C's own === (a `def C.===', +# a singleton class reopened, Module#=== redefined or refined), modules included or extended after the body is hot, +# the constant reassigned to another class and to a Regexp, and a SCREAMING_CASE Regexp constant, whose === sets $~. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +module Tag; end +module LateTag; end +class Animal; end +class Dog < Animal; end +class Odd; end +Swapped = Animal +WORD = /\A[a-z]+\z/ + +class CE + def int(x) = Integer === x ? 1 : 0 + def str(x) = String === x + def num(x) = Numeric === x + def cmp(x) = Comparable === x + def animal(x) = Animal === x + def tag(x) = Tag === x + def late(x) = LateTag === x + def odd(x) = Odd === x + def mod(x) = Module === x + def klass(x) = Class === x + def basic(x) = BasicObject === x + def swapped(x) = Swapped === x + def word(x) = WORD === x ? $~[0] : nil + def kind(x) + if Integer === x then :int + elsif Float === x then :float + elsif String === x then :str + elsif Array === x then :ary + else :other + end + end +end + +o = CE.new +d = Dog.new +t("Integer ===, hot") { warm { |i| o.int(i) } } +t("Integer === others") { [o.int(2**70), o.int(1.5), o.int(nil), o.int("1"), o.int(Integer)] } +t("String ===") { warm { |i| o.str("s#{i}") }; [o.str(:s), o.str(Class.new(String).new("x")), o.str(nil)] } +t("Numeric ===") { warm { |i| o.num(i * 0.5) }; [o.num(1r), o.num(1i), o.num("1")] } +t("Comparable ===") { warm { |i| o.cmp(i) }; [o.cmp("s"), o.cmp([]), o.cmp(nil)] } +t("Animal ===") { warm { |i| o.animal(i.odd? ? d : Animal.new) }; [o.animal(Object.new), o.animal(Dog)] } +t("Module === and Class ===") { warm { o.mod(String); o.klass(Tag) }; [o.mod(Tag), o.mod(1), o.klass(String), o.klass(Tag), o.klass(String.singleton_class)] } +t("BasicObject ===") { warm { |i| o.basic(i) }; [o.basic(nil), o.basic(BasicObject.new)] } +t("a kind chain") { warm { |i| o.kind([1, 1.5, "s", [], nil][i % 5]) }; [o.kind(2**70), o.kind({})] } + +# Module#=== does not ask x +class Liar + def is_a?(c) = true + def kind_of?(c) = true +end +class Ghost < BasicObject + def method_missing(*) = :missing +end +t("x's is_a? is not asked") { warm { o.animal(d) }; [o.animal(Liar.new), o.int(Liar.new)] } +t("a BasicObject x") { warm { o.animal(d) }; o.animal(Ghost.new) } + +# included and extended after the body is hot +t("Tag === before") { warm { o.tag(d) } } +class Animal; include Tag; end +t("include after hot") { [o.tag(d), o.tag(Animal.new), o.tag(Odd.new)] } +t("extend after hot") { x = Odd.new; warm { o.late(x) }; x.extend(LateTag); [o.late(x), o.late(Odd.new)] } + +# C's own === +t("Odd === before") { warm { o.odd(Odd.new) } } +def Odd.===(x) = :own +t("def Odd.=== after hot") { [o.odd(Odd.new), o.odd(1)] } +class << Odd; remove_method :===; end +t("removed") { [o.odd(Odd.new), o.odd(1)] } +class Module + alias_method :__orig_eqq, :=== + def ===(x) = :module +end +t("Module#=== redefined") { [o.int(1), o.str("s"), o.tag(d)] } +class Module + alias_method :===, :__orig_eqq +end +t("Module#=== restored") { [o.int(1), o.str("s"), o.tag(d)] } + +module EqqRefinement + refine Module do + def ===(x) = :refined + end +end +class CE + using EqqRefinement + def refined(x) = Integer === x +end +t("refined") { warm { |i| o.refined(i) } } + +# the constant reassigned +t("Swapped ===") { warm { o.swapped(d) } } +Object.send(:remove_const, :Swapped); Object.const_set(:Swapped, Odd) +t("Swapped to another class") { [o.swapped(d), o.swapped(Odd.new)] } +Object.send(:remove_const, :Swapped); Object.const_set(:Swapped, /\Ad/) +t("Swapped to a Regexp") { [o.swapped("dog"), o.swapped("cat"), $~ && $~[0]] } +t("a Regexp constant sets $~") { warm { |i| o.word("w#{i % 2 == 0 ? 'a' : 'b'}") }; [o.word("hello"), o.word("Hi"), o.word(5)] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 09f9bd71a..332a7260a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2025,6 +2025,34 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitcaseeq (2026-11-28, census and timed, not gated; paused before its checks were complete) - `C === x` with + C a class or module constant in the method JIT's typed body** (the census's `MethodCall ===`: 304 methods refused, + 170 by it alone; switch `IR_JIT_CASE_EQ`). Built on happy-gauss fcbc67b. + - **What.** `C === x`, with C a constant whose name has a lower-case letter (`Integer`, `Foo::Bar`; not `PATTERN`, + which holds a value whose === is its own, a Regexp's sets $~), compiles to `JitRuntime.ModuleCaseEquals`. That + is Module#=== (`module.Context.IsKindOf(x, module)`): x's immediate class has C among its ancestors, without + asking x anything (x's own is_a?, a BasicObject, method_missing). C is the folded constant under the entry's + constant version guard, and a C that is no module bails at compile time. A `KernelMethodSite` checks that C's + own class (its singleton class) resolves === to Module's library method under the global method version; a + `def C.===`, a reopened singleton class or Module#=== redefined deopts. Not compiled where a refinement is + active. Added to the sinking allow-list. + - **Census** (Src/StdLib, Util/bench, AWFY, against fcbc67b): 39 methods up (never -> maybe), none down. + Compiles 3,631 -> 3,631, maybe 3,495 -> 3,534, never 22,406 -> 22,367. + - **app-shapes, traced:** specialized 123 -> 123, declined 29 -> 29 (nothing hot there writes `C === x`). AWFY + writes none. + - **Clock** (ab.rb -r 5, `Util/bench/isa-shapes.rb`, ns, off -> new, CRuby): `IBase === x` over four receiver + kinds 104.0 -> 73.8 (51.9), an Integer/Float/else chain of `===` 119.9 -> 81.2 (62.6). The is_a? row (num) + overlaps, as it should. + - **Checks done.** `Util/jit-caseeq-matrix.rb` (new, 24 rows): Integer, String, Numeric, Comparable, Module, + Class, BasicObject and user classes; a liar is_a? and a BasicObject x; include and extend after hot; `def + Odd.===` added and removed; Module#=== redefined and restored; refined; the constant swapped to another class + and to a Regexp; a SCREAMING_CASE Regexp constant setting $~. It prints CRuby's output with the JIT on, + -X:NoJIT -X:NoOSR, -X:NoJITCalls, IR_LIGHT_FRAMES=0 and the switch off. ruby/spec core/module/case_compare and + language/case: the same as the base, no failures. + - **Owed** (the round was paused, at the parent's request, while they ran): jit-isa (one mode done, the same), + jit-objops, jit, jit-calls, jit-const, unsampled, hot-shapes and case-string matrices in every mode, and + IronRuby.Tests on Debug. + - **Gate of 2026-11-28 for round 7 of round thirty-seven** (perf/crubydiff's fifth and sixth rounds, perf/literalsite, perf/endpark, perf/stage0 and perf/stagea with the block-cost harness and the procscope design, perf/primitive (rejected), perf/clrlookup, perf/bootparse, perf/permute, perf/parkedtuple From 029bacbf3801329aaf29deaf6d7be3605e87c036 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:49:34 +0000 Subject: [PATCH 299/439] Integer and Float: no snake_case names for their CLR methods CRuby's Integer has no compare_to, to_string, equals or get_hash_code, and a program that duck-types on one has to see NoMethodError: an Integer key in Util/perf/inline-matrix.rb's tree_int_key, whose tree calls key.compare_to(other), raised Int32#CompareTo's ArgumentError "Object must be of type Int32." instead, on master too. Integer and Float map no names otherwise (NoNameMapping), but their Int32 and Double CLR instance methods, and a Bignum's own BigInteger/Int64 members, also answered to snake_case spellings (IsUnmangledBuiltin, RubyCallAction.ResolveOwnClrMember). They are now reachable by their CLR names only - 5.ToString("X"), 5.CompareTo(3), (2**70).IsEven still work - and the snake_case names are NoMethodError, as in CRuby. Nothing changes for any other CLR type. inline-matrix (every tree_* case, jit and nojit) and the int, numeric, coerce, float, compare and respond-to matrices agree with CRuby 4.0 or are unchanged; ClrIntegerClrMembers1 now asserts the CLR names and the NoMethodError of the snake_case ones; the full Debug IronRuby.Tests suite passes (1,423). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/Runtime/ClrTests.cs | 18 +++++++++--------- Src/Ruby/Builtins/RubyModule.cs | 11 +---------- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 5 ++++- Util/perf/inline-matrix.rb | 4 ++-- 4 files changed, 16 insertions(+), 22 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/ClrTests.cs b/Src/IronRuby.Tests/Runtime/ClrTests.cs index 118648c59..494a90b53 100644 --- a/Src/IronRuby.Tests/Runtime/ClrTests.cs +++ b/Src/IronRuby.Tests/Runtime/ClrTests.cs @@ -3768,24 +3768,23 @@ p IO.method(:Pick).overload(I64).call(1), IO.Wide(2**40) } /// - /// A CLR member only an Int64's or a BigInteger's own type has is reachable on such an Integer, by its CLR or its - /// snake_case name. The CLR instance methods of Integer and Float (Int32's, Double's) take snake_case names too, - /// though, as Ruby built-ins, they stay out of the method lists. + /// A CLR member only an Int64's or a BigInteger's own type has is reachable on such an Integer by its CLR name, as the + /// CLR instance methods of Integer and Float (Int32's, Double's) are. Not by a snake_case name: CRuby's Integer has no + /// to_string or compare_to, and a program that duck-types on one must get NoMethodError. They stay out of the method lists. /// public void ClrIntegerClrMembers1() { TestOutput(@" big = 2**70 -p big.IsEven, big.is_even, (big + 1).IsEven, big.Sign, (-big).sign +p big.IsEven, (big + 1).IsEven, big.Sign p((2**40).IsEven) rescue p $!.class -p 5.to_string, 255.to_string('X'), (2**40).to_string, big.to_string, 5.compare_to(3), 1.5.to_string, 1.5.compare_to(2.0) -p 5.respond_to?(:to_string), 5.methods.include?(:to_string), Integer.instance_methods.include?(:compare_to) +p 5.ToString, 255.ToString('X'), (2**40).ToString, big.ToString, 5.CompareTo(3), 1.5.ToString, 1.5.CompareTo(2.0) +p 5.respond_to?(:to_string), 5.methods.include?(:ToString), Integer.instance_methods.include?(:compare_to) +p [5, 1.5, big, 2**40].map { |o| [:to_string, :compare_to, :is_even, :sign].map { |m| (o.send(m, *([1] * (m == :compare_to ? 1 : 0))) rescue $!.class) } } p((5.foo_bar rescue $!.class), (big.foo_bar rescue $!.class)) ", @" true -true false 1 --1 NoMethodError '5' 'FF' @@ -3794,9 +3793,10 @@ public void ClrIntegerClrMembers1() { 1 '1.5' -1 -true false false +false +[[NoMethodError, NoMethodError, NoMethodError, NoMethodError], [NoMethodError, NoMethodError, NoMethodError, NoMethodError], [NoMethodError, NoMethodError, NoMethodError, NoMethodError], [NoMethodError, NoMethodError, NoMethodError, NoMethodError]] NoMethodError NoMethodError "); diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 9c0399a27..3c3d0cd25 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -3449,7 +3449,7 @@ private bool TryGetClrMemberNoTiming(string/*!*/ name, bool virtualLookup, out R // Note: Do not allow mangling for CLR virtual lookups - we want to match the overridden name exactly as is, // so that it corresponds to the base method call the override stub performs. bool mapNames = (Restrictions & ModuleRestrictions.NoNameMapping) == 0; - bool unmangleNames = !virtualLookup && (mapNames || IsUnmangledBuiltin()); + bool unmangleNames = !virtualLookup && mapNames; if (IsModuleType(_typeTracker.Type) ? TryGetDefaultInterfaceMember(name, unmangleNames, out method) : @@ -3464,15 +3464,6 @@ private bool TryGetClrMemberNoTiming(string/*!*/ name, bool virtualLookup, out R return false; } - /// - /// Integer and Float map no names (), yet the CLR instance methods of - /// their Int32 and Double take snake_case names as any CLR type's do: 5.to_string("X"), 1.5.compare_to(2.0). Such a - /// member is still left out of the method lists (), and an operator or indexer is not mapped. - /// - private bool IsUnmangledBuiltin() { - return _typeTracker.Type.IsPrimitive && this is RubyClass cls && !cls.IsSingletonClass; - } - // The public instance members of an interface and its base interfaces that have a default implementation (C# 8), // or an empty array. private MethodInfo[] _defaultInterfaceMethods; diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index c9fffd071..90f26b48a 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -963,7 +963,10 @@ private static MethodResolutionResult ResolveOwnClrMember(MetaObjectBuilder/*!*/ object target = args.Target; var context = targetClass.Context; - if (!(target is long || target is BigInteger) || targetClass != context.IntegerClass || + // by its CLR name only, as Int32's members are: CRuby's Integer has no snake_case `is_even' or `to_string' (and + // a program that duck-types on `compare_to' must see NoMethodError, not Int32#CompareTo's ArgumentError) + if (methodName.Length == 0 || !Char.IsUpper(methodName[0]) || + !(target is long || target is BigInteger) || targetClass != context.IntegerClass || !(context.GetClrTypeModule(target.GetType()) is RubyClass ownClass) || ownClass == targetClass) { return notFound; } diff --git a/Util/perf/inline-matrix.rb b/Util/perf/inline-matrix.rb index eb7b3d81c..a9ec30971 100644 --- a/Util/perf/inline-matrix.rb +++ b/Util/perf/inline-matrix.rb @@ -338,8 +338,8 @@ def compare_to(o); 0; end kp = (0...200).map { |i| K.new((i * 7919) % 1009) } puts tree_run(t, probe, N / 2) + tree_run(kt, kp, N / 2) + tree_run(t, probe, N / 2) when 'tree_nil_key', 'tree_int_key', 'tree_sym_key' - # (an Integer key differs from CRuby on every tree and without the JIT: IronRuby's .NET interop answers - # `42.compare_to(o)' with Int32#CompareTo, an ArgumentError, where CRuby has no such method) + # (an Integer key: `42.compare_to(o)' is a NoMethodError, as in CRuby - Int32's CLR methods are reachable by their + # CLR names only, 42.CompareTo) odd = { 'tree_nil_key' => nil, 'tree_int_key' => 42, 'tree_sym_key' => :k }[c] puts tree_run(t, probe, N, ->(i) { probe[(N - 1) % probe.size] = odd }) when 'tree_poly', 'tree_poly3' From b6db7736ef998438c4be20ba3d796aebdde74046 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:49:43 +0000 Subject: [PATCH 300/439] LEDGER: perf/crubydiff's eighth round Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 09f9bd71a..f0b0742f4 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -4024,7 +4024,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (Proc.CalleeName in its rare state; RubyLambdaMethodInfo.GetLambdaFor), in the rule and the first-call dispatcher; such a call skips the method JIT's stub. light-entry-matrix (claude/perf-lsite) "define_method body by alias": CRuby's output. DefineMethodCallee1. - Not fixed: `42.compare_to(o)` in inline-matrix's `tree_int_key` answers Int32#CompareTo's + Not fixed (fixed in the eighth round, see below): `42.compare_to(o)` in inline-matrix's `tree_int_key` answers Int32#CompareTo's "Object must be of type Int32." where CRuby has no such method. That is IronRuby's interop (RubyModule.IsUnmangledBuiltin: snake_case CLR names on Integer and Float, `5.to_string("X")`, which ClrTests asserts), not a leak; matching CRuby means dropping those names, or mapping them @@ -4216,6 +4216,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has For the gate: $~/$_ inside string instance_eval/class_eval are the caller's; backtrace, caller, binding and eval file lines of calls in multi-line statements; fibers' $~/$_ are their own (a fiber no longer sees or sets its creator's). + Eighth round (2026-11-28, on claude/happy-gauss-95wm2j fcbc67b): Integer and Float answer their CLR methods by their + CLR names only (5.ToString("X"), 5.CompareTo(3), (2**70).IsEven); the snake_case spellings (compare_to, to_string, + equals, is_even) are NoMethodError, as in CRuby, so inline-matrix's tree_int_key is same. ClrIntegerClrMembers1. + For the gate: a program that called 5.to_string or 1.5.compare_to through IronRuby's interop must use the CLR names. - **perf/json (2026-11-27) - `case` over String literals looks its subject up once while String#=== is the library's (gap 7)** - gated 2026-11-28 (round 6's gate entry). Commit 0a78877 on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j 15285eb with 0518f08 merged in. Measured first: a perf profile of AWFY From e8a74f4b402ebf0b0944625c84b8a6bd735597d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:52:53 +0000 Subject: [PATCH 301/439] A method's scope holds its caller's literal block until it is parked Round thirty-seven's perf/literalcode takes a method that evaluates a literal block on every call out of light frames: its scope is made at entry (and parked), which measured faster per call. That includes som.rb's `Vector#each' and `has_some' and their callers, and a method with a scope converted its caller's literal for good - in the scope's InitializeRfc (Kind = Proc, the scope its frame) or at the call site's CreateRfcForMethod. So the callers of such methods could not park their own scope and Procs again, which perf/havlakalloc had made them do: at fcbc67b Havlak was back at 1.79 GB an iteration. Now a method's scope converts the literal as before but marks it reusable and held (Proc.HoldForMethodScope), and EndPark releases the hold when it parks the scope, dropping the Proc's frame, as it does for a light frame's scope (perf/havlakalloc): parking proves that nothing captured the scope nor kept a Proc of it, and a method that names its block or calls super has no parking slot. A block another method passed on that reaches a method with a scope is held by that scope the same way instead of being made not reusable for good (perf/namedblock's clear): a later receiver's confirmation lifts only the pass hold. IR_HELD_METHOD_BLOCKS=0 converts it for good, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Src/Ruby/Builtins/Proc.cs | 21 +++++++++++++++++++ Src/Ruby/Runtime/RubyOps.FlowControl.cs | 27 ++++++++++++++++++++++--- Src/Ruby/Runtime/RubyOps.cs | 2 +- Src/Ruby/Runtime/RubyScope.cs | 26 ++++++++++++++++++++++-- 4 files changed, 70 insertions(+), 6 deletions(-) diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index baedc1f2b..7689b14f7 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -223,6 +223,27 @@ internal void ReleaseHold() { _kind &= ~HeldFlag; } + /// + /// A literal block a method's scope converted (RubyMethodScope.InitializeMethodRfc, the scope its frame): reusable if its + /// literal allows it, and held by the scope (see HeldFlag). + /// + internal void HoldForMethodScope() { + if (ScopeHeldBlocksEnabled && _dispatcher.ReusesProc && TracePoint.ActiveEvents == 0) { + _kind |= ReusableFlag | HeldFlag; + } + } + + /// + /// ReleaseHold by the method scope that is being parked, which may be the proc's frame (HoldForMethodScope): that call has + /// returned, and the proc is inactive again. + /// + internal void ReleaseHold(RubyScope/*!*/ scope) { + _kind &= ~HeldFlag; + if (_activeFlowControlScope == scope) { + _activeFlowControlScope = null; + } + } + internal bool IsReusable { get { return (_kind & ReusableMask) == ReusableFlag; } } diff --git a/Src/Ruby/Runtime/RubyOps.FlowControl.cs b/Src/Ruby/Runtime/RubyOps.FlowControl.cs index 9af50d2ea..7d822ddcd 100644 --- a/Src/Ruby/Runtime/RubyOps.FlowControl.cs +++ b/Src/Ruby/Runtime/RubyOps.FlowControl.cs @@ -36,18 +36,39 @@ public static partial class RubyOps { public static RuntimeFlowControl/*!*/ CreateRfcForMethod(Proc proc) { if (proc != null) { if (proc.Kind == ProcKind.Block) { - proc.ConvertAsFrame(); + if (HeldMethodBlocksEnabled) { + // The method's scope holds the block, as a light frame's does once it is made (Proc.HeldFlag): reusable + // again if the scope is parked (EndPark), which a method that names its block or calls super never is. + proc.ConvertAsLightFrame(); + proc.HoldForScope(); + } else { + proc.ConvertAsFrame(); + } return proc; } // A block another method passed on (Proc.PassHeldFlag): this method's scope holds it and may keep it, and may pass - // it on to a receiver that confirms the pass - which must not make it reusable again. - proc.ClearReusable(); + // it on to a receiver that confirms the pass - which must not make it reusable again. So the scope holds it + // (Proc.HeldFlag), which only the parking of this scope releases (EndPark: nothing kept the scope); a method that + // names its block or calls super is never parked, and keeps it not reusable for good. + if (HeldMethodBlocksEnabled) { + proc.ConfirmPass(); + proc.HoldForScope(); + } else { + proc.ClearReusable(); + } } return InactiveRfc; } private static readonly RuntimeFlowControl/*!*/ InactiveRfc = new RuntimeFlowControl(); + /// + /// IR_HELD_METHOD_BLOCKS=0: a Ruby method with a scope converts a literal block for good (ConvertAsFrame), as it did, rather + /// than hold it until its scope is parked (see CreateRfcForMethod). A method that evaluates a literal block on every call + /// has its scope made at entry since round thirty-seven's perf/literalcode, and its caller could then never park. + /// + internal static readonly bool HeldMethodBlocksEnabled = Environment.GetEnvironmentVariable("IR_HELD_METHOD_BLOCKS") != "0"; + [Emitted] public static void EnterLoop(RubyScope/*!*/ scope) { scope.InLoop = true; diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 122659ff2..287d326db 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -423,7 +423,7 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R } var methodScope = (RubyMethodScope)scope; // nothing kept the scope (BeginPark) nor a Proc of it (StageParkedProc): nor the block it held (Proc.HeldFlag) - methodScope.BlockParameter?.ReleaseHold(); + methodScope.BlockParameter?.ReleaseHold(methodScope); methodScope.ClearCallState(); parked.Scope = methodScope; parked.ThreadId = Environment.CurrentManagedThreadId; diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 8f92dc2c4..788a7d4eb 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1674,7 +1674,29 @@ internal RubyMethodScope(MutableTuple locals, string/*!*/[]/*!*/ variableNames, _definitionName = definitionName; _blockParameter = blockParameter; - InitializeRfc(blockParameter); + InitializeMethodRfc(blockParameter); + } + + /// + /// InitializeRfc of a method's scope: the literal block given to the call is converted with this scope as its frame, and, + /// unless IR_HELD_METHOD_BLOCKS=0, held by it rather than made not reusable for good (Proc.HeldFlag): EndPark releases it + /// when it parks the scope, which proves that nothing kept the scope or a Proc of it - and a method that names its block + /// or calls super has no parking slot. A method that evaluates a literal block on every call has its scope made at entry + /// (perf/literalcode), so a caller that gives it a literal could otherwise never park. + /// + private void InitializeMethodRfc(Proc proc) { + if (proc != null) { + if (proc.Kind == ProcKind.Block) { + InitializeRfc(proc); + if (RubyOps.HeldMethodBlocksEnabled) { + proc.HoldForMethodScope(); + } + } else if (RubyOps.HeldMethodBlocksEnabled) { + // a block another method passed on: held by this scope as in RubyOps.CreateRfcForMethod + proc.ConfirmPass(); + proc.HoldForScope(); + } + } } #region Parked scopes (RubyOps.CreateMethodScopeParked) @@ -1706,7 +1728,7 @@ internal void Reinitialize(MutableTuple locals, object selfObject, Proc blockPar _activeFlowControlScope = rfc.IsActiveMethod ? rfc : this; } else { _activeFlowControlScope = this; - InitializeRfc(blockParameter); + InitializeMethodRfc(blockParameter); } } From f6bacb7c74141f4734558f9dea14905639edbaa5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:58:27 +0000 Subject: [PATCH 302/439] Let the method JIT take a keyword method with a **rest parameter JitKeywords recognized a keyword prologue only if its match refused keys it does not name, so a method with `**o' kept its prologue in the body and the JIT's screen rejected it (KeywordArgumentsTest): `def krest(k:, **o)' ran its interpreted prologue on every call. The rest binding that ends the prologue (`o = Rest(?kw?, names)') is now one more keyword slot, the last: the match accepts other keys, and a signature with `**o' and no required keyword - which has no match statement, having nothing to check - is recognized from its reads. The entry binds the rest last, once every guard has passed: the call's own hash taken over, as the generic body takes it (RubyOps.MakeKeywordRest), unless the typed body can deopt, when it is a copy - a failed guard or a deopt runs the generic body, which binds the parameters from that hash again. The one-call reads of one to three keywords and JitKeywordCall's direct entry leave a rest method out. IR_JIT_KWREST=0 recognizes no rest, as before. Census: JIT compiles +7, maybe +3, never -10, nothing down (Prism's desugar nodes, LexCompat, Ripper::Lexer#parse, two Net::IMAP authenticators). By clock krest 97 -> 76 ns (CRuby 66), onlyrest(**o) 87 -> 71 (CRuby 73); a body that can deopt keeps the copy and its time. Checked: new IronRuby.Tests Method_KeywordRestJit1 with CRuby 4.0's output, run hot (guards that fail after warm-up, a deopt, a missing keyword); new rows in Util/kwsplat-forward-matrix.rb whose methods are specialized; the keyword, prologue, splat, JIT and entry matrices match CRuby in every mode and with the switches off, and under -X:JITResume; specs as on the base build; IronRuby.Tests in full on Debug. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 37 +++++++ .../Ast/Expressions/KeywordParameterRead.cs | 1 + Src/Ruby/Runtime/Jit/JitKeywordCall.cs | 3 +- Src/Ruby/Runtime/Jit/JitKeywords.cs | 103 +++++++++++++++--- Src/Ruby/Runtime/Jit/JitRuntime.cs | 5 + Src/Ruby/Runtime/Jit/JitStub.cs | 16 ++- Util/kwsplat-forward-matrix.rb | 34 ++++++ Util/perf/LEDGER.md | 39 +++++++ 9 files changed, 219 insertions(+), 20 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a055c6629..505eea384 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1200,6 +1200,7 @@ public Tests(Driver/*!*/ driver) { Method_Ruby2KeywordsExplicitSplat1, Struct_Ruby2KeywordsHash1, Method_KeywordRestTakeover1, + Method_KeywordRestJit1, Method_KeywordPrologue1, Method_LightFrameGlobal1, Method_LightFrameLexical1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index e1c4d1d17..1a26d89ac 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8710,6 +8710,43 @@ p kt_mut(**{""s"" => 1, k: 2}) "); } + /// + /// Keyword methods with **rest in the method JIT (JitKeywords.HasRest, IR_JIT_KWREST), run hot: a guard that fails after + /// warm-up, a body that deopts (an overflow) and a missing keyword run the generic body, which binds from an intact + /// hash; the typed body's **rest is the call's own hash only when it cannot deopt. Expected output from CRuby 4.0. + /// + public void Method_KeywordRestJit1() { + TestOutput(@" +def jr_req(k:, **o) = k + o.size +def jr_opt(a, k: 1, **o) = [a + k, o] +def jr_only(**o) = o +def jr_mut(k: 0, **o) = (o[:added] = k; o) +def jr_def(a, k: a * 2, j: 5, **o) = [k, j, o] +seen = [] +3000.times do |i| + r = [ + (jr_req(k: i == 2900 ? ""s"" : 1, z: 1) rescue $!.class), + jr_req(k: i == 2950 ? 2**62 + 2**62 - 1 : 1), + ((i == 2990 ? jr_req(z: 1) : jr_req(k: 1)) rescue $!.message), + jr_opt(i == 2900 ? 1.5 : 1, k: 2, z: 3), + jr_only(**(i.even? ? {a: 1} : {})), + (jr_only({a: 1}) rescue $!.message), + jr_def(3), jr_def(3, k: 1, z: 9) + ] + h = {k: 1, z: 2}; m = jr_mut(**h); r << m << h + a = jr_only(a: 1); b = jr_only(a: 1); a[:x] = 1; r << b + seen << r unless seen.include?(r) +end +seen.each { |r| p r } +", @" +[2, 1, 1, [3, {z: 3}], {a: 1}, ""wrong number of arguments (given 1, expected 0)"", [6, 5, {}], [1, 5, {z: 9}], {z: 2, added: 1}, {k: 1, z: 2}, {a: 1}] +[2, 1, 1, [3, {z: 3}], {}, ""wrong number of arguments (given 1, expected 0)"", [6, 5, {}], [1, 5, {z: 9}], {z: 2, added: 1}, {k: 1, z: 2}, {a: 1}] +[TypeError, 1, 1, [3.5, {z: 3}], {a: 1}, ""wrong number of arguments (given 1, expected 0)"", [6, 5, {}], [1, 5, {z: 9}], {z: 2, added: 1}, {k: 1, z: 2}, {a: 1}] +[2, 9223372036854775807, 1, [3, {z: 3}], {a: 1}, ""wrong number of arguments (given 1, expected 0)"", [6, 5, {}], [1, 5, {z: 9}], {z: 2, added: 1}, {k: 1, z: 2}, {a: 1}] +[2, 1, ""missing keyword: :k"", [3, {z: 3}], {a: 1}, ""wrong number of arguments (given 1, expected 0)"", [6, 5, {}], [1, 5, {z: 9}], {z: 2, added: 1}, {k: 1, z: 2}, {a: 1}] +"); + } + /// /// A method's keyword prologue (PrismAstBridge.LowerKeywords): which error wins when several things are wrong at once, /// and defaults run in order and only for omitted keywords (Util/kw-prologue-matrix.rb). diff --git a/Src/Ruby/Compiler/Ast/Expressions/KeywordParameterRead.cs b/Src/Ruby/Compiler/Ast/Expressions/KeywordParameterRead.cs index 2b39ee462..d07ba1f19 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/KeywordParameterRead.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/KeywordParameterRead.cs @@ -58,6 +58,7 @@ public Expression DefaultValue { // What the method JIT (Runtime/Jit/JitKeywords.cs) needs to recognize a keyword prologue. internal bool IsMatch { get { return _kind == ReadKind.Match; } } internal bool IsValue { get { return _kind == ReadKind.Value; } } + internal bool IsRest { get { return _kind == ReadKind.Rest; } } internal string/*!*/[]/*!*/ Names { get { return _names; } } internal RubyEncoding/*!*/ Encoding { get { return _encoding; } } // Match: how many of the names are required; Value: where the keyword is declared diff --git a/Src/Ruby/Runtime/Jit/JitKeywordCall.cs b/Src/Ruby/Runtime/Jit/JitKeywordCall.cs index dd2c9ea5c..969a453e1 100644 --- a/Src/Ruby/Runtime/Jit/JitKeywordCall.cs +++ b/Src/Ruby/Runtime/Jit/JitKeywordCall.cs @@ -319,7 +319,8 @@ private void ResolveConstruction(State/*!*/ state, RubyClass target) { /// method whose prologue binds this call's arguments without complaint. /// private bool BindStub(State/*!*/ state, JitStub stub) { - if (stub == null || stub.Keywords == null) { return false; } + // a **rest is bound from the hash the call makes (JitKeywords.HasRest): no direct entry + if (stub == null || stub.Keywords == null || stub.Keywords.HasRest) { return false; } // The call passes every mandatory positional and, of the optional ones, a leading run; // the rest get their literal defaults here, as the entry would fill them in. diff --git a/Src/Ruby/Runtime/Jit/JitKeywords.cs b/Src/Ruby/Runtime/Jit/JitKeywords.cs index aab20f5d9..0c9ae9d5c 100644 --- a/Src/Ruby/Runtime/Jit/JitKeywords.cs +++ b/Src/Ruby/Runtime/Jit/JitKeywords.cs @@ -26,11 +26,18 @@ * the entry fills in. Any other default (`b: a + 1', `list: []') is left to the typed body: the * entry hands it RubyOps.DefaultArgument for an omitted one, and the body evaluates the default * itself, in declaration order, before its own statements (JitCompiler.EmitKeywordDefaults) - unless - * the default assigns a local, which could be a keyword bound after it. **rest is not recognized: - * such a method is never wrapped. + * the default assigns a local, which could be a keyword bound after it. + * + * A **rest after the keywords (`o = Rest(?kw?, names)' ending the prologue, IR_JIT_KWREST) is one + * more keyword slot, the last: the Match accepts keys it does not name, and the slot's value is a + * copy of the hash without the declared keywords - not the hash itself, as RubyOps.MakeKeywordRest + * takes it in the generic body: a guard that fails after it, or a deopt, runs the generic body, + * which binds the parameters from that hash again. The copy has no effect, so it is made with + * the other values, in the entry's guard. * * ***************************************************************************/ +using System; using System.Collections.Generic; using IronRuby.Builtins; using IronRuby.Compiler.Ast; @@ -66,6 +73,13 @@ internal bool HasDefaultExpr(int index) { internal int Count { get { return LocalNames.Length; } } + // A **rest parameter, bound in the last slot (its local is the last of LocalNames); its Symbols entry is null. + internal bool HasRest; + private RubyContext _context; + + /// IR_JIT_KWREST=0: a method with keywords and **rest is not recognized, and so never wrapped, as before. + internal static readonly bool KwRestEnabled = System.Environment.GetEnvironmentVariable("IR_JIT_KWREST") != "0"; + // The optional positional parameters before the keyword hash (Parameters.KeywordsAfterOptionals): // `def m(a, b = 1, k: 2)' has one. Each has a literal default (OptionalDefaults); a call that // leaves one out may have put its keyword hash there, which the entry moves into place first. @@ -130,25 +144,25 @@ internal static JitKeywords TryRecognize(MethodDeclaration/*!*/ ast, RubyContext break; } - // unless KeywordArgumentsMatch(?kw?, names, required, false) ... end + // unless KeywordArgumentsMatch(?kw?, names, required, false) ... end - which a signature with **rest and no + // required keyword has not: it has nothing to check (PrismAstBridge.BindKeywordsFrom) if (i >= n) { return null; } var matchStmt = statements[i] as UnlessExpression; - if (matchStmt == null || matchStmt.ElseClause != null) { return null; } - var match = matchStmt.Condition as KeywordParameterRead; - if (match == null || !match.IsMatch || match.AcceptsRest || !IsVar(match.Keywords, kwVar)) { return null; } - i++; - - var names = match.Names; - if (names.Length == 0 || names.Length > MaxKeywords) { return null; } + KeywordParameterRead match = null; + if (matchStmt != null) { + if (matchStmt.ElseClause != null) { return null; } + match = matchStmt.Condition as KeywordParameterRead; + if (match == null || !match.IsMatch || match.AcceptsRest && !KwRestEnabled || !IsVar(match.Keywords, kwVar)) { return null; } + i++; + } else if (!KwRestEnabled) { + return null; + } + bool acceptsRest = (match == null) || match.AcceptsRest; var result = new JitKeywords(); result.OptionalPositionals = optionalPositionals; result.OptionalDefaults = optionalDefaults; - result.RequiredCount = match.RequiredCountOrPosition; - result.MatchNames = new RubySymbol[names.Length]; - for (int j = 0; j < names.Length; j++) { - result.MatchNames[j] = context.CreateSymbol(names[j], match.Encoding); - } + result.RequiredCount = (match != null) ? match.RequiredCountOrPosition : 0; // k = , one per declared keyword, in declaration order var locals = new List(); @@ -193,12 +207,52 @@ internal static JitKeywords TryRecognize(MethodDeclaration/*!*/ ast, RubyContext defaultExprs.Add(defaultExpr); i++; } + // without a Match, the names are the ones the bindings read, none of them required + string[] names; + if (match != null) { + names = match.Names; + } else { + names = new string[locals.Count]; + for (int j = 0; j < names.Length; j++) { + if (required[j]) { return null; } + names[j] = symbols[j].ToString(); + } + } + if (names.Length > MaxKeywords || names.Length == 0 && !acceptsRest) { return null; } + result.MatchNames = new RubySymbol[names.Length]; + for (int j = 0; j < names.Length; j++) { + result.MatchNames[j] = (match != null) ? context.CreateSymbol(names[j], match.Encoding) : symbols[j]; + } if (locals.Count != names.Length) { return null; } + // o = Rest(?kw?, names): the **rest, after the keywords, of every declared name + if (acceptsRest) { + var restBind = (i < n) ? statements[i] as SimpleAssignmentExpression : null; + var restRead = (restBind != null && restBind.Operation == null) ? restBind.Right as KeywordParameterRead : null; + var restLocal = (restBind != null) ? restBind.Left as LocalVariable : null; + if (restRead == null || !restRead.IsRest || !IsVar(restRead.Keywords, kwVar) || restLocal == null || + restLocal.DefinitionLexicalDepth != ast.DefinedScope.Depth || restRead.Names.Length != names.Length) { + return null; + } + for (int j = 0; j < names.Length; j++) { + if (Array.IndexOf(result.MatchNames, context.CreateSymbol(restRead.Names[j], restRead.Encoding)) < 0) { return null; } + } + locals.Add(restLocal.Name); + symbols.Add(null); + positions.Add(-1); + defaults.Add(null); + required.Add(false); + defaultExprs.Add(null); + result.HasRest = true; + result._context = context; + i++; + } + // every name Match checks is one a binding reads, and vice versa for (int j = 0; j < names.Length; j++) { if (!symbols.Contains(result.MatchNames[j])) { return null; } } + if (!acceptsRest && i < n && statements[i] is SimpleAssignmentExpression tail && tail.Right is KeywordParameterRead) { return null; } result.PrologueLength = i; result.LocalNames = locals.ToArray(); @@ -242,11 +296,28 @@ private static bool IsVar(RExpr node, LocalVariable/*!*/ kwVar) { internal bool Matches(object kw) { if (kw == RubyOps.DefaultArgument) { return RequiredCount == 0; } var hash = kw as Hash; - return hash != null && hash.IsKeywordArguments && hash.HasKeywords(MatchNames, RequiredCount, false); + return hash != null && hash.IsKeywordArguments && hash.HasKeywords(MatchNames, RequiredCount, HasRest); + } + + /// + /// The **rest, given : what RubyOps.MakeKeywordRest binds. : the call's + /// own hash itself, as the generic body takes it - only once every guard of the entry has passed, for a typed body + /// that cannot deopt, since a failed guard or a deopt runs the generic body, which binds the parameters from that + /// hash again; otherwise a copy (see the top of this file). + /// + internal object Rest(object kw, bool take) { + var hash = kw as Hash; + if (hash == null) { + return new Hash(_context.EqualityComparer); + } + return take ? RubyOps.MakeKeywordRest(hash, MatchNames) : hash.CopyWithoutKeywords(MatchNames); } /// What the prologue binds keyword to, given . internal object Value(object kw, int index) { + if (HasRest && index == Count - 1) { + return Rest(kw, false); + } object v = RubyOps.GetKeywordArgument(kw, Symbols[index], Positions[index]); return (v == RubyOps.DefaultArgument) ? Defaults[index] : v; } diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index defece267..15457d52a 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -462,6 +462,11 @@ public static object KeywordValue(object/*!*/ keywords, object kw, int index) { return ((JitKeywords)keywords).Value(kw, index); } + /// The **rest of a method with keywords (JitKeywords.Rest). + public static object KeywordRest(object/*!*/ keywords, object kw, bool take) { + return ((JitKeywords)keywords).Rest(kw, take); + } + // KeywordsMatch and KeywordValue in one call, for a method with up to three keywords. public static bool KeywordsRead1(object/*!*/ keywords, object kw, out object v0) { diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 6e0913f52..6eed5d6a0 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -999,7 +999,7 @@ private bool TrySpecialize() { if (code.Resume != null) { code.Resume.Specialization = spec; } spec.Entry = CompileEntry(BuildEntry(code, callee, version, needsClassGuard ? _receiverClass : null, spec)); if (_keywords != null && !needsClassGuard && _positional <= JitKeywordCall.MaxPositional && - _keywords.Count <= JitKeywordCall.MaxKeywords) { + _keywords.Count <= JitKeywordCall.MaxKeywords && !_keywords.HasRest) { spec.Direct = BuildDirectEntry(code, callee, version, spec).Compile(); } @@ -1396,7 +1396,7 @@ private bool SelfCallResolvesHere(RubyClass/*!*/ cls, RefinementActivation/*!*/ values[_positional + j] = keywordValues[j] = Ast.Variable(typeof(object), "kw" + j); } var info = Ast.Constant(_keywords, typeof(object)); - if (keywordValues.Length <= 3) { + if (keywordValues.Length <= 3 && !_keywords.HasRest) { // match and bind in one call, the values coming back through out parameters var readArgs = new MSA.Expression[keywordValues.Length + 2]; readArgs[0] = info; @@ -1405,7 +1405,8 @@ private bool SelfCallResolvesHere(RubyClass/*!*/ cls, RefinementActivation/*!*/ test = And(test, Ast.Call(JitRuntime.M("KeywordsRead" + keywordValues.Length), readArgs)); } else { test = And(test, Ast.Call(JitRuntime.M("KeywordsMatch"), info, kw)); - for (int j = 0; j < keywordValues.Length; j++) { + // the **rest is bound once every guard has passed (below) + for (int j = 0; j < keywordValues.Length - (_keywords.HasRest ? 1 : 0); j++) { test = And(test, Ast.Block( Ast.Assign(keywordValues[j], Ast.Call(JitRuntime.M("KeywordValue"), info, kw, Ast.Constant(j))), Ast.Constant(true))); @@ -1438,6 +1439,15 @@ private bool SelfCallResolvesHere(RubyClass/*!*/ cls, RefinementActivation/*!*/ } MSA.Expression fast = Ast.Invoke(callee, typedArgs); + if (keywordValues != null && _keywords.HasRest) { + // The **rest, now that the typed body is going to run: the call's own hash taken over, as the generic body + // takes it, unless the body can deopt into the generic body, which binds the parameters from that hash again. + fast = Ast.Block( + Ast.Assign(keywordValues[keywordValues.Length - 1], Ast.Call(JitRuntime.M("KeywordRest"), + Ast.Constant(_keywords, typeof(object)), args[_positional], Ast.Constant(!code.CanDeopt))), + fast + ); + } if (code.ReturnType == JT.Lng) { // The one place a specialized method's value becomes a Ruby object: it leaves // through the representation funnel, so a result that fits in an Int32 is one. diff --git a/Util/kwsplat-forward-matrix.rb b/Util/kwsplat-forward-matrix.rb index 0565b5952..3bbc83e00 100644 --- a/Util/kwsplat-forward-matrix.rb +++ b/Util/kwsplat-forward-matrix.rb @@ -197,3 +197,37 @@ class KtE < KtP; def m(k: 0, **o) = (o[:local] = 1; eval('super')); end t("o from ruby2_keywords") { |i| r = r2k_fwd_mut(k: 1, y: 2); r } t("o when no keywords given") { |i| [kt_mut, kt_keep[-1].tap { $kept = nil }] } t("o with non-Symbol keys") { |i| kt_mut(**{"s" => 1, k: 2}) } + +# ---------------------------------------------------------------- 9. keyword methods with **rest in the method JIT (JitKeywords.HasRest, +# IR_JIT_KWREST): each probe runs hot, so the method is specialized; then a call the entry's guards refuse, or a body that deopts, +# runs the generic body, which must bind from an intact hash +def jr_req(k:, **o) = k + o.size +def jr_opt(a, k: 1, **o) = [a + k, o] +def jr_only(**o) = o +def jr_keep(**o) = ($jr_kept ||= []) << o +def jr_def(a, k: a * 2, j: (($jr_side ||= 0); $jr_side += 1; 5), **o) = [k, j, o] +t("hot: required keyword and rest, then a String k") { |i| (jr_req(k: i == 2900 ? "s" : i % 3, z: 1) rescue [$!.class]) } +t("hot: rest, then the positional's type changes") { |i| jr_opt(i == 2900 ? 1.5 : 1, k: 2, z: i % 2) } +t("hot: overflow deopts the typed body") { |i| jr_req(k: i == 2900 ? 2**62 + 2**62 - 1 : 1, z: 1) } +t("hot: missing required keyword after warm-up") { |i| (i == 2900 ? jr_req(z: 1) : jr_req(k: 1)) rescue [$!.class, $!.message] } +t("hot: rest only, varying keys") { |i| jr_only(**(i.even? ? {a: 1} : {b: 2, c: 3})) } +t("hot: rest only, no keywords, **nil, **{}") { |i| [jr_only, jr_only(**nil), jr_only(**{})] } +t("hot: positional Hash to a rest-only method") { |i| (jr_only({a: 1}) rescue [$!.class, $!.message]) } +t("hot: each call's o is its own, kept") { |i| $jr_kept = nil; a = jr_keep(a: 1)[-1]; b = jr_keep(a: 1)[-1]; a[:x] = 1; [a, b] } +t("hot: caller's **h untouched") { |i| h = {k: 2, z: 3}; r = jr_opt(1, **h); r[1][:w] = 1; [r, h] } +t("hot: defaults referencing a parameter, with side effects") { |i| $jr_side = 0; [jr_def(3), jr_def(3, k: 1, j: 2, z: 9), $jr_side] } +t("hot: through send and method_missing") { |i| [send(:jr_opt, 1, k: 2, z: 3), MM.new.ghost(k: 1, z: 2)] } +ruby2_keywords def r2k_into_rest(*a) = jr_opt(*a) +t("hot: ruby2_keywords into a rest method") { |i| r2k_into_rest(1, k: 2, z: 3) } +JR_SIDE = [] +def jr_ret(**o) = o +def jr_mut(k: 0, **o) = (o[:added] = k; o) +def jr_def2(a, k: a * 2, j: JR_SIDE.push(1).size, **o) = [k, j, o] +t("hot (typed): o returned, each call's own") { |i| a = jr_ret(a: 1); b = jr_ret(a: 1); a[:x] = 1; [a, b, a.equal?(b)] } +t("hot (typed): o mutated in the body") { |i| h = {k: 1, z: 2}; [jr_mut(**h), h, jr_mut(k: 2, y: 3)] } +t("hot (typed): defaults referencing a parameter, with side effects") { |i| JR_SIDE.clear; [jr_def2(3), jr_def2(3, k: 1, j: 2, z: 9), JR_SIDE.size] } +def jr_bump = JR_SIDE.push(1).size +def jr_def3(a, k: a * 2, j: jr_bump, **o) = [k, j, o] +t("hot (typed): a default calling a method, evaluated only when missing") { |i| JR_SIDE.clear; [jr_def3(3), jr_def3(3, k: 1, j: 2, z: 9), JR_SIDE.size] } +def jr_def4(a, k: a * 2, j: 5, **o) = [k, j, o] +t("hot (typed): a default referencing a parameter, with rest") { |i| [jr_def4(3), jr_def4(3, k: 1, z: i % 2), jr_def4(3, j: 0)] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 09f9bd71a..ea3ed0ca6 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2025,6 +2025,45 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kwjit (/perf-step, 2026-11-28) - the method JIT takes a keyword method with `**rest`** + (gap 38; switch `IR_JIT_KWREST`, on unless `=0`). Built on fcbc67b (claude/happy-gauss-95wm2j) + with de51cf89 merged. + - **What changed.** JitKeywords.TryRecognize took a prologue only if its keyword Match refused + other keys, so a method with `**o` kept the prologue in its body and the screen rejected it + (`KeywordArgumentsTest`). It now takes `o = Rest(?kw?, names)` after the keyword reads as one + more keyword slot, the last; the Match accepts other keys (HasKeywords' acceptsRest), and a + signature with `**o` and no required keyword, which has no Match statement at all + (PrismAstBridge.BindKeywordsFrom has nothing to check), is recognized from its reads. The + entry binds the rest last, once every guard has passed: the call's own hash taken over as the + generic body takes it (RubyOps.MakeKeywordRest), unless the typed body can deopt - a failed + guard or a deopt runs the generic body, which binds from that hash again - when it is a copy. + The 1-3 keyword one-call reads and JitKeywordCall's direct entry (literal keywords bound at the + call site, no hash) leave a rest method out. + - **Census** (`-d` against `IR_JIT_KWREST=0`, Src/StdLib and Util/bench, 29,141 methods): JIT + compiles 3,529 -> 3,536 (+7), maybe 3,396 -> 3,399 (+3), never 22,216 -> 22,206 (-10); light + frames unchanged; nothing moved down. Up: Prism's four Desugar*Node#initialize and + LexCompat#initialize (compiles), Ripper::Lexer#parse, Net::IMAP's Plain and XOAuth2 + authenticators' #initialize (maybe), and the bench shapes `krest`, `p_rest`. + - **Clock** (`ab.rb -r 8`, Release, ns; CRuby / `IR_JIT_KWREST=0` / on): `krest(k: 1)` into + `def krest(k:, **o) = k` 66.3 / 97.3 / 76.0 (0.78), with an extra key 80.9 / 115.1 / 90.7 + (0.79), `onlyrest(**o) = 1` 73.0 / 87.3 / 71.3 (0.82); `krest_u` (`k + o.size`, a body that + can deopt, so the rest is a copy) 73.1 / 107.1 / 107.3. With the copy everywhere (the first + try) the JIT was slower than the generic body with the takeover (1.07-1.23): the copy costs + what the typed body saves. + - **Checks.** IronRuby.Tests Method_KeywordRestJit1 (CRuby 4.0's output, run hot: a String + where an Integer was, an overflow that deopts, a missing keyword after warm-up, varying and + no keywords, a positional Hash, a body that mutates o, the caller's `**h` untouched, + defaults). Util/kwsplat-forward-matrix.rb section 9 (the same and more; checked that its + methods are specialized, IR_JIT_VERBOSE). kwsplat-forward, keyword-light, keyword-rest-light, + kw-prologue, kwrest-call, splat-pass, jit, jit-calls, light-entry and hot-shapes: same as CRuby + in default, `IR_JIT_KWREST=0`, `IR_KWREST_TAKE=0`, `IR_LIGHT_FRAMES=0`, `-X:NoJIT -X:NoOSR`, + `-X:NoJITCalls` (60 of 60), and kwsplat-forward and the test's script under `-X:JITResume`. + Specs language/keyword_arguments, def, send, super, method, core/hash, core/method, + core/struct, core/kernel/send as on the base build. IronRuby.Tests in full (Debug): PASSED, + 1,424. + - **Left.** The caller's keyword hash (about 40 ns of what remains over a positional call); + a body that can deopt still copies its rest. + - **Gate of 2026-11-28 for round 7 of round thirty-seven** (perf/crubydiff's fifth and sixth rounds, perf/literalsite, perf/endpark, perf/stage0 and perf/stagea with the block-cost harness and the procscope design, perf/primitive (rejected), perf/clrlookup, perf/bootparse, perf/permute, perf/parkedtuple From 4aa79313a34c4e108feed51922bed2d4e8b162ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:22:09 +0000 Subject: [PATCH 303/439] Decline a JIT'd keyword method with **rest whose body can deopt The method JIT binds a **rest as a copy when the typed body can deopt (a deopt runs the generic body, which binds from the call's hash again), and the copy costs more than the typed body saves: `def kro(k: 0, **o) = ($g = k)' called with `(k: 1, z: 2)' took 131 ns specialized against 104 in the generic body, which takes the call's hash over (IR_JIT_KWREST=0). The last commit's measurements had hidden it (a body that can deopt showed 1.00). JitStub.TrySpecialize now declines such a method once its body is compiled, and JitCensus.Probe counts it as declined. Bodies that cannot deopt keep the typed entry and its take-over. By clock kro 131 -> 103 ns (IR_JIT_KWREST=0: 100), krest_u level with the switch off; krest 104 -> 87, onlyrest 96 -> 77 kept. Census against IR_JIT_KWREST=0: JIT compiles +1, maybe +9, never -10, nothing down. The keyword, prologue, splat, JIT and entry matrices match CRuby in every mode (60 of 60), Method_KeywordRestJit1 also under -X:JITResume, IronRuby.Tests in full on Debug. Util/perf/LEDGER.md also records why the caller's keyword hash has nothing left to win. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf51pjcdT3614WLaYSx --- Src/Ruby/Runtime/Jit/JitCensus.cs | 4 +++- Src/Ruby/Runtime/Jit/JitStub.cs | 8 ++++++++ Util/perf/LEDGER.md | 23 +++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/Jit/JitCensus.cs b/Src/Ruby/Runtime/Jit/JitCensus.cs index a79ac91bd..a41b63ff1 100644 --- a/Src/Ruby/Runtime/Jit/JitCensus.cs +++ b/Src/Ruby/Runtime/Jit/JitCensus.cs @@ -354,7 +354,9 @@ private void Decide(Entry/*!*/ entry, out string/*!*/ verdict, out string stage, // Whether a typed body exists for parameters that are all of one type, the receiver unknown. private bool Probe(MethodDeclaration/*!*/ ast, JitKeywords keywords, JT type, int typedCount, int perCountMandatory) { if (perCountMandatory < 0) { - return JitCompiler.TryCompile(ast, _context, Typing(type, typedCount), keywords, RefinementActivation.Empty) != null; + var code = JitCompiler.TryCompile(ast, _context, Typing(type, typedCount), keywords, RefinementActivation.Empty); + // a **rest whose body can deopt is declined once compiled (JitStub.TrySpecialize) + return code != null && !(keywords != null && keywords.HasRest && code.CanDeopt); } // a body for each number of optional arguments a call passes (JitStub.TrySpecializePerCount): one of them will do for (int k = 0; perCountMandatory + k <= typedCount; k++) { diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index 6eed5d6a0..a21cb7e20 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -962,6 +962,14 @@ private bool TrySpecialize() { return false; } + // A **rest the typed body would bind as a copy, since it can deopt into the generic body, which binds from the call's + // hash again (JitKeywords.Rest): the copy costs more than the typed body saves - `def m(k: 0, **o) = ($g = k)' took + // 131 ns specialized against 104 in the generic body, which takes the call's hash over. That body stays. + if (_keywords != null && _keywords.HasRest && code.CanDeopt) { + _declineReason = "a **rest whose body can deopt (it would be a copy)"; + return false; + } + // (a body with direct calls was only compiled for a receiver class the profile pinned: Callees) bool needsClassGuard = code.EmittedSelfCall || code.InlinedSelfClass != null || code.DirectCalls; if (needsClassGuard) { diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index ea3ed0ca6..9697f94dc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2025,6 +2025,29 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/kwcall (/perf-step, 2026-11-28) - the caller's keyword hash: nothing to win; a JIT'd + `**rest` whose body can deopt is declined** (fixes a slowdown perf/kwjit brought in). + - **The caller's hash** (clock, ns; CRuby in brackets), bodies with a global variable assignment: + a declared-keywords call `kd(k: 1)` 39 [42], `kd2(k: 1, j: 2)` 64 [45], `kr(k: 1)` 32 [40] - + the method JIT binds them from the call's pairs (JitKeywordCall) without the hash, at CRuby's + level already. A `**o` callee needs a hash for o; with the take-over the caller's hash *is* o, + which CRuby allocates too. What is left of a hash literal: `{k: 1}` 59 [50]. So the round's + 40 ns is not the caller's to save. + - **What the profile found instead.** `kro(k: 1, z: 2)` into `def kro(k: 0, **o) = ($g = k)` + took 131 ns with perf/kwjit against 104 with `IR_JIT_KWREST=0`: the typed body can deopt, so + its rest was a copy, which costs more than the typed body saves (perf/kwjit's `krest_u`, + 1.00 there, had hidden it). JitStub.TrySpecialize now declines a **rest whose compiled body + can deopt - it runs the generic body, which takes the call's hash over - and JitCensus.Probe + counts it so. JitKeywords.Rest's copy is then only the profiler's. + - **Clock** (`ab.rb -r 8`, ns; CRuby / `IR_JIT_KWREST=0` / on): `kro` 89.9 / 100.4 / 103.3 + (overlap), `krest_u` 75.8 / 116.0 / 123.2 (overlap); still won: `krest` 69.7 / 104.0 / 87.2, + `krest_extra` 86.4 / 121.6 / 98.2, `onlyrest` 83.6 / 96.0 / 77.3. + - **Census** (`-d` against `IR_JIT_KWREST=0`, now counting the decline): JIT compiles +1, maybe +9, + never -10, nothing down (perf/kwjit's count said compiles +7, maybe +3: the Prism initializers + are `maybe (declined once typed)`). + - **Checks.** The 10 matrices in 6 modes (60 of 60), Method_KeywordRestJit1 under -X:JITResume, + IronRuby.Tests in full (Debug): PASSED, 1,424. + - **perf/kwjit (/perf-step, 2026-11-28) - the method JIT takes a keyword method with `**rest`** (gap 38; switch `IR_JIT_KWREST`, on unless `=0`). Built on fcbc67b (claude/happy-gauss-95wm2j) with de51cf89 merged. From 69f52fd5c7f71d36391aa9b9c661210789285e32 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:23:28 +0000 Subject: [PATCH 304/439] Run a while loop with a yield in its body in its compiled copy (gap 18) The OSR copy gave up at a YieldCall, so a `while ... yield' iterator written in Ruby ran its loop generic: about 22 ns an element around the yield. The copy now takes a loop with one yield in statement position directly in its body, in a method's own body (WhileLoopExpression.GetYieldIndex). Before the yield a deopt replays the iteration as before. The yield goes through the method's block, a new copy input, and a reused BlockParam. After it, if the block jumped, the code epoch moved, a TracePoint is on, or a statement after the yield deopts (locals restored to their post-yield values), the copy writes its locals home and answers an OsrYieldOutcome: the generic loop makes the post-yield test (break returns from the method), runs its own second transformation of the statements after the yield, and goes on at its head. An exception through the yield writes the locals home first. Stage 3a of Docs/jit-resume-deopt.md, narrower and simpler than planned (no Handback answer, no separate suffix compiler); IR_OSR_YIELD=0 turns it off. yield-shapes by clock (ab.rb -r 10): ueach100e 0.60 of the base, below CRuby; ueach100 0.70; ueach4n 0.72; controls level. Census unchanged. yield-loop-matrix (now warmed up so its rows run in the copies, plus two hot overflow rows) and block-loop, osr-array, jit, jit-calls, parked-iterator, hot-shapes and loop-ivar match CRuby in every gate mode and with the switch off; specs language yield/break/while/until/next/redo as the base; new test OsrYieldLoop1 and 110 named tests pass both ways. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Docs/jit-resume-deopt.md | 23 ++++ Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/LoopTests.cs | 55 ++++++++ .../Ast/Expressions/WhileLoopExpression.cs | 122 +++++++++++++++++ Src/Ruby/Runtime/Jit/JitCompiler.cs | 127 +++++++++++++++++- Src/Ruby/Runtime/Jit/JitLoopCompiler.cs | 26 +++- Src/Ruby/Runtime/Jit/JitRuntime.cs | 18 +++ Src/Ruby/Runtime/Osr/OsrLoopSite.cs | 42 +++++- Util/perf/LEDGER.md | 32 +++++ Util/yield-loop-matrix.rb | 40 ++++++ 10 files changed, 477 insertions(+), 9 deletions(-) diff --git a/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md index ee47835da..cd22cb84c 100644 --- a/Docs/jit-resume-deopt.md +++ b/Docs/jit-resume-deopt.md @@ -540,6 +540,29 @@ a typed copy) and needs the same suffix compiler for its way 2. Order: ## Stage 3a: a yield in an outlined loop (gap 18) +**Built (round thirty-seven, perf/yieldloop, `IR_OSR_YIELD`, on by default), narrower and simpler than the plan +below.** The shape is as designed (`WhileLoopExpression.GetYieldIndex`; in a method's own body, not a block's or an +eval's). What changed in the building: + +- No Handback answer: `Retry` already means "go on at the head with the tuple as the copy left it". One new answer, + `OsrYieldOutcome`, covers ways 2 and 3: the copy writes its locals home and returns it, with the BlockParam when the + block jumped (way 3: the glue makes the generic post-yield test, `MethodYield`, which the light frame's rewriter makes + `LightMethodYield`, and returns from the method) or without one (way 2, or a deopt in the tail). +- No separate suffix compiler: the generic loop transforms its tail statements a second time, in place, inside the + method's lambda (`MakeYieldHandBack`): the same scope, tuple layout, sites, line markers and hooks for free. That is + why the tail may hold no block, lambda, definition, loop, jump or exception handling (`YieldTailFinder`: their + transformation is not repeatable or leaves the tail). It also means the method-JIT resume of stage 3 does **not** + get its suffix from here: a method body has no generic loop around the resume point to hold a second copy, and still + needs B's dispatch or a suffix lambda. +- Way 1: the tail is emitted typed; if it can deopt, the locals are taken right after the yield and a deopt in the + tail restores them and leaves with `RunTail`; a tail that deopts after an effect of its own declines the loop. +- Way 4: the copy's body runs in a fault handler that writes its locals home. + +`Util/yield-loop-matrix.rb` warms every iterator up so that its rows run in the copies, and has two rows more (`big +counter hot`, `int overflow hot`). `IR_OSR_VERBOSE=1` prints `yield-jumps` and `yield-tails`. The prelude's `while ... +yield` methods (`take_while`, `sum`, `uniq`, `to_h`) are not reached: their yields are not statements +(`break unless yield(x)`) and their loops stop earlier, at `__ary_size__`. + Status: design, with its matrix (`Util/yield-loop-matrix.rb`, which CRuby and the unchanged build print alike). Written in round thirty-seven (perf/yieldresume) after perf/yieldloop measured the gap: `def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; self; end` costs about 40 ns per element diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a055c6629..3ca3f4fcf 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -423,6 +423,7 @@ public Tests(Driver/*!*/ driver) { FloatObjectId1, JitCensus1, BlockLoopEachIndex1, + OsrYieldLoop1, BlockLoopNested1, RangeConditionInclusive1, diff --git a/Src/IronRuby.Tests/Runtime/LoopTests.cs b/Src/IronRuby.Tests/Runtime/LoopTests.cs index 0d3def802..3ba49fb65 100644 --- a/Src/IronRuby.Tests/Runtime/LoopTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoopTests.cs @@ -353,6 +353,61 @@ p r "); } + /// + /// IR_OSR_YIELD (stage 3a of Docs/jit-resume-deopt.md): a `while' loop with a yield in its body runs in its compiled + /// copy once hot, and what the generic loop does after the yield is kept - the block's `break' returns from the method, + /// a raise leaves the loop's counter for the method's rescue, and a counter that outgrows Int32 in the statements + /// after the yield goes on in the generic loop from the locals as they were right after the yield. + /// + public void OsrYieldLoop1() { + TestOutput(@" +class Y + def initialize(a) = (@a = a) + def each + i = 0 + while i < @a.size + yield @a[i] + i += 1 + end + i + end + def each_rescue + i = 0 + begin + while i < @a.size + yield @a[i] + i += 1 + end + rescue => e + [e.message, i] + end + end + def each_step(lim, step) + i = 0 + while i < lim + yield i + i += step + end + i + end +end +y = Y.new((1..100).to_a) +s = 0 +300.times { y.each { |x| s += x }; y.each_rescue { } } +p s +p y.each { |x| break x * 2 if x == 77 } +p y.each_rescue { |x| raise ""at #{x}"" if x == 42 } +n = 0 +p y.each_step(17179869184, 1048576) { n += 1 }, n +", @" +1515000 +154 +[""at 42"", 41] +17179869184 +16384 +"); + } + /// /// A block loop whose block holds another core iterator with a literal block runs the inner loop in place /// (JitCompiler.Nest.cs): a Float crossing the inner block, a bound of another type on a late outer diff --git a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs index 8b161033f..f1955baf9 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs @@ -15,6 +15,7 @@ using MSA = System.Linq.Expressions; +using System; using System.Collections.Generic; using Microsoft.Scripting; using Microsoft.Scripting.Utils; @@ -74,6 +75,107 @@ public WhileLoopExpression(Expression/*!*/ condition, bool isWhileLoop, bool isP _statements = statements; } + /// + /// IR_OSR_YIELD=0: a loop with a yield in its body is never given to a compiled copy (the copy gives up at the yield). + /// + internal static readonly bool YieldLoopsEnabled = Environment.GetEnvironmentVariable("IR_OSR_YIELD") != "0"; + + /// + /// Stage 3a of Docs/jit-resume-deopt.md: the index of the one `yield' of the loop, if the loop is of the shape a compiled + /// copy may run a yield in - a `while'/`until' tested first, one yield in statement position directly in its body with + /// plain arguments, no other yield anywhere in it, and statements after it (its tail) that the generic loop can run + /// again on its own (OsrYieldOutcome): no block, lambda or definition, no loop, no jump and no exception handling. + /// -1 otherwise. + /// + internal int GetYieldIndex() { + if (_isPostTest || !YieldLoopsEnabled) { return -1; } + int index = -1; + for (int i = 0; i < _statements.Count; i++) { + var yieldCall = _statements[i] as YieldCall; + if (yieldCall != null) { + if (index >= 0 || !IsPlainYield(yieldCall)) { return -1; } + index = i; + } + } + if (index < 0) { return -1; } + var finder = new YieldTailFinder(); + _condition.Walk(finder); + for (int i = 0; i < _statements.Count && !finder.Refused; i++) { + if (i == index) { + var args = ((YieldCall)_statements[i]).Arguments; + if (args != null) { + foreach (var arg in args.Expressions) { arg.Walk(finder); } + } + } else { + finder.InTail = i > index; + _statements[i].Walk(finder); + } + } + return finder.Refused ? -1 : index; + } + + private static bool IsPlainYield(YieldCall/*!*/ node) { + var args = node.Arguments; + if (args == null) { return true; } + foreach (var arg in args.Expressions) { + var hash = arg as HashConstructor; + if (arg is SplattedArgument || hash != null && hash.IsKeywordArguments) { return false; } + } + return true; + } + + // Another yield anywhere in the loop, and in its tail anything whose transformation is not repeatable or that leaves it. + private sealed class YieldTailFinder : Walker { + internal bool Refused, InTail; + + public override bool Enter(YieldCall/*!*/ node) { Refused = true; return false; } + public override bool Enter(BlockDefinition/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(LambdaDefinition/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(MethodDefinition/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(WhileLoopExpression/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(ForLoopExpression/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(Body/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(RescueExpression/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(BreakStatement/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(NextStatement/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(RedoStatement/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(RetryStatement/*!*/ node) { Refused |= InTail; return !Refused; } + public override bool Enter(ReturnStatement/*!*/ node) { Refused |= InTail; return !Refused; } + } + + private static readonly System.Reflection.FieldInfo/*!*/ _OutcomeBfc = typeof(OsrYieldOutcome).GetField(nameof(OsrYieldOutcome.Bfc)); + private static readonly System.Reflection.FieldInfo/*!*/ _OutcomeResult = typeof(OsrYieldOutcome).GetField(nameof(OsrYieldOutcome.Result)); + + /// + /// The copy handed an iteration back after its yield (OsrYieldOutcome): the block's jump gets the generic yield's + /// post-yield test, which returns from the method on a `break' (MethodYield; a light frame's LightMethodYield, which + /// the frame's rewriter puts in its place), then the statements after the yield run here and the loop goes on at its + /// head, the next back edge asking the copy again. + /// + private static MSA.Expression/*!*/ MakeYieldHandBack(AstGenerator/*!*/ gen, MSA.Expression/*!*/ osrResult, MSA.Expression/*!*/ tail, + MSA.Expression/*!*/ osrCountdown, MSA.LabelTarget/*!*/ continueLabel) { + var outcome = Ast.Variable(typeof(OsrYieldOutcome), "#yield-outcome"); + var bfc = Ast.Field(outcome, _OutcomeBfc); + var result = Ast.Field(outcome, _OutcomeResult); + return Ast.Block(new[] { outcome }, + Ast.Assign(outcome, Ast.TypeAs(osrResult, typeof(OsrYieldOutcome))), + Ast.IfThen(Ast.NotEqual(outcome, AstUtils.Constant(null, typeof(OsrYieldOutcome))), + Ast.Block( + Ast.IfThen( + Ast.AndAlso( + Ast.NotEqual(bfc, AstUtils.Constant(null, typeof(BlockParam))), + Methods.MethodYield.OpCall(gen.CurrentScopeVariable, bfc, result) + ), + gen.Return(result) + ), + tail, + Ast.Assign(osrCountdown, AstUtils.Constant(1L)), + Ast.Continue(continueLabel) + ) + ) + ); + } + // break, next and redo in the loop's body are jumps to its labels (Break/Next/RedoStatement) private static readonly System.Reflection.MethodInfo/*!*/ _LeaveLoopLine = typeof(PrecompiledFrames).GetMethod(nameof(PrecompiledFrames.LeaveLoopLine)); @@ -111,10 +213,24 @@ public WhileLoopExpression(Expression/*!*/ condition, bool isWhileLoop, bool isP MSA.Expression loopLineVariable = ownsLoopLine ? gen.CurrentScope.DefineHiddenVariable("#loop-line", typeof(PrecompiledFrames.LoopLine)) : outerLoop.LoopLineVariable; + // A loop with a yield its compiled copy may run (GetYieldIndex): in a method's own body, not a block's or an eval's, + // whose yields answer the block's or the eval's post-yield test. + int yieldIndex = (osr && gen.CurrentBlock == null && !gen.CompilerOptions.IsEval && gen.CurrentMethod != null) ? GetYieldIndex() : -1; + gen.EnterLoop(redoVariable, resultVariable, breakLabel, continueLabel); gen.CurrentLoop.LoopLineVariable = loopLineVariable; gen.CurrentLoop.LoopLineScope = gen.CurrentScope; MSA.Expression transformedBody = gen.TransformStatements(_statements, ResultOperation.Ignore); + // The statements after the yield once more, which the generic loop runs when the copy hands an iteration back after + // its yield (OsrYieldOutcome): the same code, with the same line markers and :line hooks. + MSA.Expression transformedTail = null; + if (yieldIndex >= 0) { + var tail = new Statements(); + for (int i = yieldIndex + 1; i < _statements.Count; i++) { + tail.Add(_statements[i], _statements.GetStartLine(i)); + } + transformedTail = (tail.Count > 0) ? gen.TransformStatements(tail, ResultOperation.Ignore) : AstUtils.Empty(); + } MSA.Expression transformedCondition = _condition.TransformCondition(gen, true); gen.LeaveLoop(); @@ -148,6 +264,11 @@ public WhileLoopExpression(Expression/*!*/ condition, bool isWhileLoop, bool isP // the copy's operators are resolved under osrSite.ScopeArgIndex = tupleArguments.Count; tupleArguments.Add(AstUtils.Convert(gen.CurrentScopeVariable, typeof(object))); + // and the method's block, which a yield the copy makes yields to + if (yieldIndex >= 0) { + osrSite.BlockArgIndex = tupleArguments.Count; + tupleArguments.Add(AstUtils.Convert(gen.MakeMethodBlockParameterRead(), typeof(object))); + } osrArguments = Ast.NewArrayInit(typeof(object), tupleArguments); } @@ -167,6 +288,7 @@ public WhileLoopExpression(Expression/*!*/ condition, bool isWhileLoop, bool isP ), Ast.Block( Ast.Assign(osrResult, Ast.Call(Ast.Constant(osrSite, typeof(OsrLoopSite)), OsrLoopSite.RunMethod, osrArguments)), + (transformedTail == null) ? (MSA.Expression)AstUtils.Empty() : MakeYieldHandBack(gen, osrResult, transformedTail, osrCountdown, continueLabel), AstUtils.If( Ast.Not(Ast.ReferenceEqual(osrResult, Ast.Constant(OsrLoopSite.Retry, typeof(object)))), Ast.Assign(resultVariable, osrResult), diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 0369fdd3b..e6b1370f8 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -297,6 +297,12 @@ private JitCompiler(MethodDeclaration/*!*/ ast, RubyContext/*!*/ context, JT[]/* // the emitter meets them and loaded into typed CLR locals by the entry JitLoopCompiler // builds around this. Everything between those two edges is the same code. private readonly WhileLoopExpression _loop; + // Loop mode, a loop the generic code can finish an iteration of after its yield (OsrLoopSite.BlockArgIndex): the method's + // block, which its yield yields to; null otherwise, and a yield bails. The exit, outcome and BlockParam of the yield + // once EmitYieldLoopBody has emitted one (JitLoopFacts). + private MSA.ParameterExpression _yieldBlock; + private MSA.LabelTarget _yieldExit; + private MSA.ParameterExpression _yieldOutcome, _yieldBfc; private readonly Func _bindSlot; private readonly List _slots; private MSA.LabelTarget _breakLabel, _continueLabel; @@ -373,13 +379,19 @@ internal struct JitLoopFacts { internal List> Arrays; // what the loop's safe points check the versions against (EmitLoopSafePoint) internal JitLoopGuard Guard; + // a loop with a yield (EmitYieldLoopBody): where the body leaves after its yield, with the outcome for the generic + // loop in YieldOutcome, and the BlockParam its yields reuse; null for any other loop + internal MSA.LabelTarget YieldExit; + internal MSA.ParameterExpression YieldOutcome; + internal MSA.ParameterExpression YieldBfc; } internal static MSA.Expression TryCompileLoop(WhileLoopExpression/*!*/ loop, RubyContext/*!*/ context, int scopeDepth, Func/*!*/ bindSlot, MSA.ParameterExpression self, Func ivarProfile, Func attrProfile, Func?> peekLocal, RubyScope constantScope, ReceiverHints hints, - RefinementActivation/*!*/ refinements, out List slots, out bool canDeopt, out JitLoopFacts facts, long epoch = 0) { + RefinementActivation/*!*/ refinements, out List slots, out bool canDeopt, out JitLoopFacts facts, long epoch = 0, + MSA.ParameterExpression yieldBlock = null) { slots = null; canDeopt = false; @@ -389,6 +401,7 @@ internal static MSA.Expression TryCompileLoop(WhileLoopExpression/*!*/ loop, Rub for (bool arrayLocals = true; ; arrayLocals = false) { c = new JitCompiler(loop, context, scopeDepth, bindSlot, self, ivarProfile, attrProfile, peekLocal, constantScope); c._compileEpoch = epoch; + c._yieldBlock = yieldBlock; c._hints = hints; c._refinements = refinements; c._noArrayLocals = !arrayLocals; @@ -428,6 +441,9 @@ internal static MSA.Expression TryCompileLoop(WhileLoopExpression/*!*/ loop, Rub facts.UndoMark = c._undoMark; facts.Arrays = c._arrayLoads; facts.Guard = c._loopGuard; + facts.YieldExit = c._yieldExit; + facts.YieldOutcome = c._yieldOutcome; + facts.YieldBfc = c._yieldBfc; // the back-edge safe point hands the loop back through the deopt // catch, so the catch is always needed - but it fires at the top of an iteration, // before anything observable, so it does not make an impure body unspecializable. @@ -2108,7 +2124,8 @@ internal static bool ConstantGuard(RExpr/*!*/ node, out ConstantVariable guard, var test = EmitCondition(node.Condition); if (!node.IsWhileLoop) { test = Ast.Not(test); } JT ignored; - var body = EmitRegion(node.Statements, out ignored); + int yieldIndex = (node == _loop && _yieldBlock != null) ? node.GetYieldIndex() : -1; + var body = (yieldIndex >= 0) ? EmitYieldLoopBody(node.Statements, yieldIndex) : EmitRegion(node.Statements, out ignored); var result = _breakValue; _breakLabel = savedBreak; _continueLabel = savedContinue; @@ -2155,6 +2172,112 @@ internal static bool ConstantGuard(RExpr/*!*/ node, out ConstantVariable guard, ); } + /// + /// The body of an outlined loop with a yield (stage 3a of Docs/jit-resume-deopt.md): the statements before the yield, the + /// yield, the statements after it (the tail). Before the yield nothing observable has happened in the iteration, so a deopt + /// there restores the iteration's snapshot and the generic loop runs the iteration again, as in any outlined loop. The + /// yield is the iteration's effect: from then on the iteration is not run again. After it the copy goes on only if the + /// block did not jump (`break', a `return' or `retry' aimed at the caller) and nothing the copy was built on changed and + /// nothing is traced (G: the code epoch, TracePoint.ActiveEvents); otherwise, and when a statement of the tail deopts + /// (its locals put back as they were right after the yield), it leaves with an OsrYieldOutcome and the generic loop runs + /// the tail and goes on at its head (WhileLoopExpression.MakeYieldHandBack). The tail itself must not deopt after an + /// effect of its own, which the generic tail would repeat. + /// + private MSA.Expression/*!*/ EmitYieldLoopBody(Statements/*!*/ statements, int yieldIndex) { + PushScope(); + var before = new List(); + for (int i = 0; i < yieldIndex; i++) { + JT ignored; + before.Add(Emit(statements[i], out ignored)); + } + bool pureBefore = _pure, canDeoptBefore = _canDeopt; + + var yieldCall = (YieldCall)statements[yieldIndex]; + var args = new List(); + if (yieldCall.Arguments != null) { + foreach (var arg in yieldCall.Arguments.Expressions) { + JT at; + args.Add(Coerce(Emit(arg, out at), at, JT.Obj)); + } + } + + _pure = true; + _canDeopt = false; + var tail = new List(); + for (int i = yieldIndex + 1; i < statements.Count; i++) { + JT ignored; + tail.Add(Emit(statements[i], out ignored)); + } + if (_canDeopt && !_pure) { throw Bail("a deopt after an effect in the statements after a yield"); } + bool tailCanDeopt = _canDeopt; + // the iteration's own rule is the statements' before the yield: the yield and its tail answer for themselves + _pure = pureBefore; + _canDeopt = canDeoptBefore; + var declared = PopScope(); + + if (_yieldExit == null) { + _yieldExit = Ast.Label("#yield-exit"); + _yieldOutcome = Ast.Parameter(typeof(Osr.OsrYieldOutcome), "#yield-outcome"); + _yieldBfc = Ast.Parameter(typeof(BlockParam), "#yield-bfc"); + } + + // the locals as they are right after the yield, for a tail that deopts: every slot the body binds, the tail's too + var after = new List(); + var takeAfter = new List(); + var restoreAfter = new List(); + foreach (var slot in _slots) { + var v = Ast.Parameter(slot.Variable.Type, slot.Variable.Name + "#after-yield"); + after.Add(v); + takeAfter.Add(Ast.Assign(v, slot.Variable)); + restoreAfter.Add(Ast.Assign(slot.Variable, v)); + if (slot.Assigned != null) { + var a = Ast.Parameter(typeof(bool), slot.Variable.Name + "#after-yield-set"); + after.Add(a); + takeAfter.Add(Ast.Assign(a, slot.Assigned)); + restoreAfter.Add(Ast.Assign(slot.Assigned, a)); + } + } + declared.AddRange(after); + + MSA.Expression yieldValue; + var procSelf = Ast.Call(typeof(RubyOps).GetMethod("GetProcSelf"), _yieldBlock); + switch (args.Count) { + case 0: yieldValue = Ast.Call(typeof(RubyOps).GetMethod("Yield0"), _yieldBlock, procSelf, _yieldBfc); break; + case 1: yieldValue = Ast.Call(typeof(RubyOps).GetMethod("Yield1"), args[0], _yieldBlock, procSelf, _yieldBfc); break; + case 2: yieldValue = Ast.Call(typeof(RubyOps).GetMethod("Yield2"), args[0], args[1], _yieldBlock, procSelf, _yieldBfc); break; + case 3: yieldValue = Ast.Call(typeof(RubyOps).GetMethod("Yield3"), args[0], args[1], args[2], _yieldBlock, procSelf, _yieldBfc); break; + case 4: yieldValue = Ast.Call(typeof(RubyOps).GetMethod("Yield4"), args[0], args[1], args[2], args[3], _yieldBlock, procSelf, _yieldBfc); break; + default: + yieldValue = Ast.Call(typeof(RubyOps).GetMethod("YieldN"), Ast.NewArrayInit(typeof(object), args), _yieldBlock, procSelf, _yieldBfc); + break; + } + var value = Ast.Parameter(typeof(object), "#yielded"); + declared.Add(value); + + var parts = new List(before); + // as the generic yield: the BlockParam first (no block given raises here, before the arguments), then the call + parts.Add(Ast.Assign(_yieldBfc, Ast.Call(typeof(RubyOps).GetMethod("ReuseBfcForYield"), _yieldBfc, _yieldBlock))); + parts.Add(Ast.Assign(value, yieldValue)); + parts.Add(Ast.IfThen(Ast.Call(JitRuntime.M("YieldJumped"), _yieldBfc), + Ast.Block(Ast.Assign(_yieldOutcome, Ast.New(typeof(Osr.OsrYieldOutcome).GetConstructor(new[] { typeof(BlockParam), typeof(object) }), _yieldBfc, value)), + Ast.Goto(_yieldExit)))); + parts.Add(Ast.IfThen(Ast.Call(JitRuntime.M("YieldWorldChanged"), Ast.Constant(_compileEpoch)), + Ast.Block(Ast.Assign(_yieldOutcome, Ast.Field(null, typeof(Osr.OsrYieldOutcome).GetField("RunTail"))), Ast.Goto(_yieldExit)))); + if (tail.Count > 0) { + MSA.Expression tailBlock = Ast.Block(typeof(void), tail); + if (tailCanDeopt) { + if (takeAfter.Count > 0) { parts.Add(Ast.Block(typeof(void), takeAfter)); } + var restore = new List(restoreAfter); + restore.Add(Ast.Assign(_yieldOutcome, Ast.Field(null, typeof(Osr.OsrYieldOutcome).GetField("RunTail")))); + restore.Add(Ast.Goto(_yieldExit)); + tailBlock = Ast.TryCatch(tailBlock, Ast.Catch(typeof(JitDeoptException), Ast.Block(typeof(void), restore))); + } + parts.Add(tailBlock); + } + parts.Add(Ast.Constant(null, typeof(object))); + return Ast.Block(typeof(object), declared, parts); + } + /// /// `break' / `break v' in the innermost loop being emitted: v, boxed, goes into the loop's result, and the jump /// to its exit follows. An outlined loop (-X:OSR) takes only a bare `break', as it always has: its site hands diff --git a/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs index 51cb1af8a..457ac615f 100644 --- a/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs @@ -92,7 +92,8 @@ internal static class JitLoopCompiler { /// internal static Func TryCompile(WhileLoopExpression/*!*/ loop, RubyContext/*!*/ context, int scopeDepth, Dictionary/*!*/ tupleArgIndex, object[]/*!*/ args, int selfArgIndex, int scopeArgIndex, - out JitLoopGuard loopGuard, bool longRuns = false, bool lightFrame = false, ICollection deadAtExit = null) { + out JitLoopGuard loopGuard, bool longRuns = false, bool lightFrame = false, ICollection deadAtExit = null, + int blockArgIndex = -1) { loopGuard = null; @@ -228,8 +229,10 @@ internal static Func TryCompile(WhileLoopExpression/*!*/ loop, hints.Self = (args[selfArgIndex] == null) ? typeof(void) : args[selfArgIndex].GetType(); hints.LoopSelf = args[selfArgIndex]; } + // the method's block, which a yield in the loop's body yields to (OsrLoopSite.BlockArgIndex) + MSA.ParameterExpression yieldBlock = (blockArgIndex >= 0 && blockArgIndex < args.Length) ? Ast.Parameter(typeof(Proc), "#block") : null; MSA.Expression body = JitCompiler.TryCompileLoop(loop, context, scopeDepth, bind, self, ivarProfile, attrProfile, peek, scope, hints, - refinements, out slots, out canDeopt, out facts, epoch); + refinements, out slots, out canDeopt, out facts, epoch, yieldBlock); if (body == null || slots.Count == 0) { if (OsrLoopSite.Verbose) { Console.Error.WriteLine("[osr] emitter gave up (body={0} slots={1})", body != null, slots == null ? -1 : slots.Count); } return null; @@ -252,6 +255,11 @@ internal static Func TryCompile(WhileLoopExpression/*!*/ loop, locals.Add(facts.UndoLog); locals.Add(facts.UndoMark); } + if (facts.YieldExit != null) { + locals.Add(yieldBlock); + locals.Add(facts.YieldOutcome); + locals.Add(facts.YieldBfc); + } // The scope this loop belongs to always makes tuples of the same shape, but nothing // in the type system says so: check before the cast rather than let an unexpected @@ -380,6 +388,20 @@ internal static Func TryCompile(WhileLoopExpression/*!*/ loop, MSA.Expression run = Ast.Block(typeof(object), body, Ast.Block(storeCurrent.ToArray()), Ast.Constant(null, typeof(object)) ); + if (facts.YieldExit != null) { + // A loop with a yield (JitCompiler.EmitYieldLoopBody) leaves after its yield with an OsrYieldOutcome for the generic + // loop to finish the iteration, its locals at home; an exception through the yield - the block's raise or throw, + // a `return' from it, Thread#kill - takes them home too, for the method's rescue and ensure to read. + prologue.Add(Ast.Assign(yieldBlock, Ast.TypeAs(Ast.ArrayIndex(argsParameter, Ast.Constant(blockArgIndex)), typeof(Proc)))); + prologue.Add(Ast.Assign(facts.YieldOutcome, Ast.Constant(null, typeof(OsrYieldOutcome)))); + prologue.Add(Ast.Assign(facts.YieldBfc, Ast.Constant(null, typeof(BlockParam)))); + MSA.Expression goHome = (storeCurrent.Count > 0) ? (MSA.Expression)Ast.Block(typeof(void), storeCurrent.ToArray()) : Ast.Empty(); + run = Ast.Block(typeof(object), + Ast.TryFault(Ast.Block(typeof(void), body, Ast.Label(facts.YieldExit)), goHome), + goHome, + Ast.Convert(facts.YieldOutcome, typeof(object)) + ); + } if (canDeopt) { if (facts.UndoLog != null) { diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index defece267..ed06859c2 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -428,6 +428,24 @@ public static object OsrVersionStale() { return Osr.OsrLoopSite.Retry; } + /// + /// After a yield in an outlined loop (JitCompiler.EmitYieldLoopBody): whether the block left by a jump - `break', or a + /// `return' or `retry' aimed at the caller - which the generic loop's post-yield test (MethodYield) turns into what the + /// generic yield does. + /// + public static bool YieldJumped(BlockParam/*!*/ bfc) { + return bfc.ReturnReason != BlockReturnReason.Undefined; + } + + /// + /// After a yield in an outlined loop: whether something the copy was built on changed while the block ran (a method or + /// a constant: the code epoch it was compiled at moved) or a TracePoint is on, either of which the statements after the + /// yield must see as the generic code would (OsrYieldOutcome.RunTail). + /// + public static bool YieldWorldChanged(long epoch) { + return RubyUtils.CodeEpoch != epoch || TracePoint.ActiveEvents != 0; + } + /// An entry guard of an outlined loop did not hold; hand the loop back. public static object OsrGuardFailed(string/*!*/ what) { if (Osr.OsrLoopSite.Verbose) { Console.Error.WriteLine("[osr] guard failed: {0}", what); } diff --git a/Src/Ruby/Runtime/Osr/OsrLoopSite.cs b/Src/Ruby/Runtime/Osr/OsrLoopSite.cs index 56eaffc98..34cb7f283 100644 --- a/Src/Ruby/Runtime/Osr/OsrLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/OsrLoopSite.cs @@ -35,6 +35,28 @@ using IronRuby.Runtime.Jit; namespace IronRuby.Runtime.Osr { + /// + /// What a compiled copy of a loop with a yield in its body answers after the yield, when it does not go on itself + /// (stage 3a of Docs/jit-resume-deopt.md, IR_OSR_YIELD): the copy has written its locals into the tuples, and the generic + /// loop finishes the iteration - the statements after the yield - and goes on at its head (WhileLoopExpression). With + /// set, the block left by a jump (`break', a `return' or `retry' aimed at the caller), and the generic + /// loop first makes the post-yield test the generic yield makes (MethodYield), which may return from the method with + /// . Without it, the copy saw the world change after the yield (a method or constant redefined, a + /// TracePoint enabled) or a statement after the yield deopted, and the generic loop runs those statements as written. + /// + public sealed class OsrYieldOutcome { + public readonly BlockParam Bfc; + public readonly object Result; + + /// The statements after the yield are the generic loop's to run. + public static readonly OsrYieldOutcome/*!*/ RunTail = new OsrYieldOutcome(null, null); + + public OsrYieldOutcome(BlockParam bfc, object result) { + Bfc = bfc; + Result = result; + } + } + /// /// One per `while' loop in the compiled tree, shared by every execution of that loop. /// @@ -103,7 +125,7 @@ private static long ReadThreshold() { return (s != null && Int64.TryParse(s, out v) && v > 0) ? v : 2000; } - internal static int Specialized, Retired, Entered, Deopts, StaleRebuilds, Kept; + internal static int Specialized, Retired, Entered, Deopts, StaleRebuilds, Kept, YieldJumps, YieldTails; internal static long CompileTicks; /// @@ -130,6 +152,9 @@ private static long ReadThreshold() { internal Dictionary TupleArgIndex; // Where in the argument array the loop's self is; -1 if it is not passed. internal int SelfArgIndex = -1; + // Where in the argument array the method's block is, for a loop with a yield the generic loop can finish an iteration + // of (WhileLoopExpression.YieldIndex, OsrYieldOutcome); -1 if it is not passed, and the copy then declines the yield. + internal int BlockArgIndex = -1; // Where in the argument array the loop's RubyScope is: its constants resolve in it, and its // refinements resolve the copy's operators; -1 if it is not passed. internal int ScopeArgIndex = -1; @@ -208,7 +233,14 @@ public object Run(object[]/*!*/ tuples) { if (++_refinementRebuilds > MaxRefinementRebuilds) { Retire(); } else { Rebuild(); } return Retry; } - if (!ReferenceEquals(result, Retry)) { return result; } + if (!ReferenceEquals(result, Retry)) { + var outcome = result as OsrYieldOutcome; + if (outcome != null) { + // not a failure: the generic loop finishes the iteration after the yield (WhileLoopExpression.MakeYieldHandBack) + if (outcome.Bfc != null) { YieldJumps++; } else { YieldTails++; } + } + return result; + } if (RubyUtils.IsSafePointRequested) { // Not a failure: the copy stopped at an iteration boundary because a @@ -295,7 +327,7 @@ private Func Compile(object[]/*!*/ tuples) { long start = Stopwatch.GetTimestamp(); try { JitLoopGuard guard; - var typed = JitLoopCompiler.TryCompile(LoopAst, Context, ScopeDepth, TupleArgIndex, tuples, SelfArgIndex, ScopeArgIndex, out guard, LongRuns, InLightFrame, DeadAtExit); + var typed = JitLoopCompiler.TryCompile(LoopAst, Context, ScopeDepth, TupleArgIndex, tuples, SelfArgIndex, ScopeArgIndex, out guard, LongRuns, InLightFrame, DeadAtExit, BlockArgIndex); _guard = guard; _typed = typed; } catch (Exception e) { @@ -332,8 +364,8 @@ private Func Compile(object[]/*!*/ tuples) { internal static void HookStats() { if (!Verbose || System.Threading.Interlocked.Exchange(ref _statsHooked, 1) != 0) { return; } AppDomain.CurrentDomain.ProcessExit += (s, e) => { - Console.Error.WriteLine("[osr] specialized={0} retired={1} entries={2} deopts={3} stale={4} kept={5} compile={6:F1}ms", - Specialized, Retired, Entered, Deopts, StaleRebuilds, Kept, CompileTicks * 1000.0 / Stopwatch.Frequency); + Console.Error.WriteLine("[osr] specialized={0} retired={1} entries={2} deopts={3} stale={4} kept={5} yield-jumps={6} yield-tails={7} compile={8:F1}ms", + Specialized, Retired, Entered, Deopts, StaleRebuilds, Kept, YieldJumps, YieldTails, CompileTicks * 1000.0 / Stopwatch.Frequency); }; } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 09f9bd71a..5aca0d41a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2025,6 +2025,38 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/yieldloop (2026-11-28) - a `while` loop with a yield in its body runs in its compiled copy (gap 18, stage + 3a of `Docs/jit-resume-deopt.md`)** - not gated. The OSR copy gave up at the YieldCall (`[osr] emitter: node: + YieldCall`), so `def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; end` ran its loop generic: about 22 ns + an element of loop around the yield (`loop100` 29.8 generic, 8.0 typed). + - The copy now takes a loop of the shape `while C; S...; yield E...; T...; end` with one yield in statement position + directly in its body (`WhileLoopExpression.GetYieldIndex`; a method's own body; plain arguments; a tail `T` with no + block, definition, loop, jump or rescue). Before the yield, the iteration's rule is the old one: a deopt restores the + snapshot and the generic loop runs the iteration again. The yield goes through the method's block (a new copy input) + and a BlockParam the copy reuses, as the generic yield does. After it, if the block jumped, or the code epoch moved, + or a TracePoint is on, or a tail statement deopts (the locals put back as they were after the yield), the copy writes + its locals home and answers an `OsrYieldOutcome`. The generic loop then makes the post-yield test (`break` returns + from the method, its ensure and the light frame's finally running as for the generic yield), runs its own second + transformation of the tail, and goes on at its head (`MakeYieldHandBack`). An exception through the yield writes the + locals home first (a fault handler), so a rescue or ensure of the method reads the loop's counter. Switch: + `IR_OSR_YIELD=0`. + - Time (`Util/bench/yield-shapes.rb`, `ab.rb -r 10`, ns per element, CRuby / base / new): `ueach100e` 29.0 / 45.9 / + 27.6 (0.60, below CRuby), `ueach100` 35.3 / 59.9 / 42.1 (0.70), `ueach4n` 45.0 / 78.6 / 56.7 (0.72), `ueach4` and + `ueach1` 0.88-0.91 (overlapping), the C# `cyield4` 1.01. The prelude's `take_while`, `sum_blk`, `uniq_blk`, + `to_h_blk` are not touched (their yields are not statements, and their loops stop at `__ary_size__` first): every + one overlapped in a run of seven rounds; a run of ten under a load spike had `take_while` at 1.35 with a 103% spread. + AWFY has no such loop (SOM's `Vector#each` is `Range#each` with a block). + - Census: 0 methods changed (it counts methods, not loop copies). Seen while taking it: on fcbc67b light frames are + 23,460 (82.7%) against 27,313 three rounds before - 2eda4af ("a body that evaluates a literal block on every + call is not a light frame") on purpose; the same on base and branch. + - Checks: `Util/yield-loop-matrix.rb` with its iterators warmed up so that its rows run in the copies (`IR_OSR_VERBOSE=1`: + 10 loops specialized, `yield-jumps=6`, `yield-tails=3`, one of them a deopt in the tail) and two rows more (`big + counter hot`, `int overflow hot`), with block-loop, osr-array, jit, jit-calls, parked-iterator, hot-shapes and + loop-ivar: CRuby's output in the six gate modes and with the switch off, on both trees (55 same; block-loop under + R2R as on base). ruby/spec language yield, break, while, until, next, redo: 183 examples, none failing, on both. + IronRuby.Tests (Debug): the new OsrYieldLoop1 and 110 tests named for loops, yield, blocks, iterators, break, + next, redo pass with the switch on and off; the whole suite was not run. + - **Gate of 2026-11-28 for round 7 of round thirty-seven** (perf/crubydiff's fifth and sixth rounds, perf/literalsite, perf/endpark, perf/stage0 and perf/stagea with the block-cost harness and the procscope design, perf/primitive (rejected), perf/clrlookup, perf/bootparse, perf/permute, perf/parkedtuple diff --git a/Util/yield-loop-matrix.rb b/Util/yield-loop-matrix.rb index accf9e544..66daf8b91 100644 --- a/Util/yield-loop-matrix.rb +++ b/Util/yield-loop-matrix.rb @@ -89,6 +89,12 @@ def each_last l = L.new(A100.dup) hot = 0 400.times { l.each { |x| hot += x } } +# every iterator of L hot too, so that the rows below run in the loops' compiled copies (IR_OSR_VERBOSE=1: specialized, +# and the hazards' yield-jumps and yield-tails), not only in the generic loops +400.times do + l.each_last { }; l.map_like { |x| x }; l.each2 { }; l.each_block { } + L.new(A100.dup).each_ensure { }; L.new(A100.dup).each_rescue { } +end rows("hot") { hot } rows("sizes") { [[], [7], [1, 2, 3, 4], A100].map { |a| s = 0; L.new(a).each { |x| s += x }; s } } rows("returns self") { l.each { }.equal?(l) } @@ -173,3 +179,37 @@ def each }.new r = []; e = big.each { |x| r << x }; [r.size, e, e.class] } +# the same past Int64 once the copy runs the loop: its `i += 2**49' overflows in the statements after the yield, which +# then run in the generic loop from the locals as they were right after the yield (OsrYieldOutcome.RunTail) +rows("big counter hot") { + big2 = Class.new { + def each + i = 0 + while i < 2**64 + yield i + i += 2**49 + end + i + end + }.new + n = 0; last = nil + e = big2.each { |x| n += 1; last = x } + [n, last, e, e.class] +} +# an Integer counter that is still an Int32 when the copy is compiled (about 2,000 back edges) and outgrows it at the +# 2,048th: the overflow is a deopt in the statements after the yield, after the block ran for that element +rows("int overflow hot") { + ov = Class.new { + def each(lim, step) + i = 0 + while i < lim + yield i + i += step + end + i + end + }.new + n = 0; s = 0 + e = ov.each(17179869184, 1048576) { |x| n += 1; s += x } + [n, s, e] +} From 4bdfe19d4dec958f5287ded3af59641584dc3693 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:25:19 +0000 Subject: [PATCH 305/439] An interpolated local on a later line of a string reports its own line When the conversion of an interpolated part raises (its #to_s), MRI's backtrace names the part's line. For a part that reads a local variable IronRuby kept the line the frame was at - the statement's - because the variable's node is shared by every read and carries its declaration's span: a heredoc's `#{x}` three lines below `s = <<~E` reported the `s` line. The bridge now records the line of each such part beside the parts (StringConstructor.PartLines), and the conversion of one on a line other than the frame's current one is wrapped as a call on a later line of a statement is (AstGenerator.AddCallLine: its line before, the frame's after). A single-line string, and any part on the frame's line, gets nothing; IR_CALL_LINES=0 turns it off with the rest. Backtrace_InterpolatedLocalLine1 holds CRuby's output (a heredoc, a two-line string, a Symbol, an argument on a later line, a method the JIT compiled). The interpolation, string, caller and backtrace matrices are unchanged (string-race differs from run to run, the unchanged build from itself too); app-shapes render, invoice_render, erb_result and json_generate on/off within 0.99-1.05 (ab.rb -r 8); the full Debug IronRuby.Tests suite passes (1,424). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 49 +++++++++++++++ Src/Prism/PrismAstBridge.cs | 26 +++++++- .../Ast/Expressions/StringConstructor.cs | 59 ++++++++++++++----- 4 files changed, 116 insertions(+), 19 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a055c6629..e9506bbb3 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1060,6 +1060,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_ArityCalleeFrame1, Backtrace_SendHidden1, Backtrace_CallLine1, + Backtrace_InterpolatedLocalLine1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index a291b6bf1..512a8e5a7 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -502,6 +502,55 @@ p q(1) "); } + /// + /// The conversion of an interpolated local variable on a later line of a string (a heredoc's) reports that line, as + /// MRI's does: the variable's node carries its declaration's span, so the part's line comes from StringConstructor.PartLines. + /// + public void Backtrace_InterpolatedLocalLine1() { + TestOutput(@" +require 'ruby4'; class Bad; def to_s = raise(""no""); end +def bt = yield rescue $!.backtrace_locations[1].lineno +def m(x) + y = 1 + s = <<~E + a #{y} + b #{x} + E + s +end +p bt { m(Bad.new) } +def m2(x) = ""a +#{x}"" +p bt { m2(Bad.new) } +def m3(x) + ""#{x}"" +end +p bt { m3(Bad.new) } +def m4(x) + v = :""s +#{x}"" + v +end +p bt { m4(Bad.new) } +def m5(x) + [1, + ""#{x}""] +end +p bt { m5(Bad.new) } +r = nil +3000.times { r = m(1) } +p r, bt { m(Bad.new) } +", @" +8 +14 +17 +22 +28 +""a 1\nb 1\n"" +8 +"); + } + /// /// Kernel#send and BasicObject#__send__ leave no frame of their own in a backtrace, with a String name too (as with a /// Symbol, whose call the binder makes in place); Kernel#public_send keeps its frame. LEDGER gap 27. diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 94a4bdc97..8a33b6741 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -774,16 +774,16 @@ private int StatementLine(Pm.PmNode/*!*/ node) { // interpolated string with nothing interpolated; MRI treats it as the single // literal it looks like, frozen or chilled with the rest of the file's. var folded = TryFoldAdjacentLiterals(interp, span); - return folded ?? new StringConstructor(StringParts(interp.Parts), StringKind.Mutable, span) { SourceEncoding = _encoding }; + return folded ?? WithPartLines(new StringConstructor(StringParts(interp.Parts), StringKind.Mutable, span) { SourceEncoding = _encoding }, interp.Parts); } case Pm.InterpolatedSymbolNode interpSymbol: - return new StringConstructor(StringParts(interpSymbol.Parts), StringKind.Symbol, span); + return WithPartLines(new StringConstructor(StringParts(interpSymbol.Parts), StringKind.Symbol, span), interpSymbol.Parts); case Pm.XStringNode xstr: return new StringConstructor( new List { new StringLiteral(LiteralValue(xstr.Unescaped, LiteralEncoding(xstr)), LiteralEncoding(xstr), span) }, StringKind.Command, span); case Pm.InterpolatedXStringNode interpX: - return new StringConstructor(StringParts(interpX.Parts), StringKind.Command, span); + return WithPartLines(new StringConstructor(StringParts(interpX.Parts), StringKind.Command, span), interpX.Parts); case Pm.EmbeddedStatementsNode embedded: return StatementsAsExpression(embedded.Statements, span); @@ -1332,6 +1332,26 @@ private static bool MayHaveNestedQuantifier(string/*!*/ pattern) { } } + /// + /// The line of each part that reads a local variable (`#{x}`): the variable's node is shared by every read and carries + /// its declaration's span, so the conversion of such a part on a later line of the string (a heredoc) learns its own + /// line from here (StringConstructor.PartLines), as MRI reports it. + /// + private StringConstructor/*!*/ WithPartLines(StringConstructor/*!*/ ctor, Pm.PmNode/*!*/[]/*!*/ parts) { + var built = ctor.Parts; + if (built.Count != parts.Length) { + return ctor; + } + int[] lines = null; + for (int i = 0; i < parts.Length; i++) { + if (built[i] is LocalVariable && (parts[i] is Pm.EmbeddedStatementsNode || parts[i] is Pm.EmbeddedVariableNode)) { + (lines ??= new int[parts.Length])[i] = Span(parts[i]).Start.Line; + } + } + ctor.PartLines = lines; + return ctor; + } + private List/*!*/ StringParts(Pm.PmNode[]/*!*/ parts) { var result = new List(); foreach (var part in parts) { diff --git a/Src/Ruby/Compiler/Ast/Expressions/StringConstructor.cs b/Src/Ruby/Compiler/Ast/Expressions/StringConstructor.cs index 4684bc017..20840d651 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/StringConstructor.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/StringConstructor.cs @@ -44,6 +44,12 @@ public partial class StringConstructor : Expression { private readonly StringKind _kind; private readonly List/*!*/ _parts; + /// + /// The line of each part that reads a local variable, 0 for the others, or null (PrismAstBridge.WithPartLines): the + /// variable's node carries its declaration's span, not the part's. + /// + internal int[] PartLines; + public StringKind Kind { get { return _kind; } } @@ -67,13 +73,13 @@ public StringConstructor(List/*!*/ parts, StringKind kind, SourceSpa internal override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { switch (_kind) { case StringKind.Mutable: - return TransformConcatentation(gen, _parts, StringFactory.Instance); + return TransformConcatentation(gen, _parts, StringFactory.Instance, PartLines); case StringKind.Symbol: - return TransformConcatentation(gen, _parts, SymbolFactory.Instance); + return TransformConcatentation(gen, _parts, SymbolFactory.Instance, PartLines); case StringKind.Command: { - var command = TransformConcatentation(gen, _parts, StringFactory.Instance); + var command = TransformConcatentation(gen, _parts, StringFactory.Instance, PartLines); // `cmd` hands ` a frozen string, whatever the frozen_string_literal // setting; an interpolated `cmd #{x}` hands it a mutable one. The @@ -117,7 +123,7 @@ internal MSA.Expression TransformWithoutScope(Func/* var merged = new MSAst.ExpressionCollectionBuilder(); var concat = new LiteralConcatenation(encoding); - if (!ConcatLiteralsAndTransformRecursive(_parts, concat, merged, convert)) { + if (!ConcatLiteralsAndTransformRecursive(_parts, null, concat, merged, (part, line) => convert(part))) { return null; } if (concat.Count > 0) { @@ -135,6 +141,11 @@ internal MSA.Expression TransformWithoutScope(Func/* } internal static MSA.Expression/*!*/ MakeConversion(AstGenerator/*!*/ gen, Expression/*!*/ expression) { + return MakeConversion(gen, expression, 0); + } + + /// The part's own line when it reads a local variable (PartLines), or 0. + internal static MSA.Expression/*!*/ MakeConversion(AstGenerator/*!*/ gen, Expression/*!*/ expression, int partLine) { // an interpolation in a heredoc can be lines below the statement: a backtrace from it // names its own line // a to_s a refinement supplies is not visible to the conversion site - see RubyOps.TryConvertToSWithRefinements @@ -149,7 +160,13 @@ internal MSA.Expression TransformWithoutScope(Func/* // A local variable node is shared by every read of the variable and carries the span of // its declaration, which would move the statement's line back there (a call taking // "#{block_param}" reported the block's first line), so a read keeps the statement's. - return expression.Location.IsValid && !(expression is LocalVariable) ? gen.AddDebugInfo(conversion, expression.Location) : conversion; + if (expression is LocalVariable) { + // ... but a part on a later line of the string than the frame is at (a heredoc's) reports that line, as MRI's + // does, and the frame's line again after it (as a call on a later line of a statement does) + int current = gen.CurrentLine; + return (AstGenerator.CallLines && partLine > 0 && current > 0 && partLine != current) ? gen.AddCallLine(conversion, partLine, current) : conversion; + } + return expression.Location.IsValid ? gen.AddDebugInfo(conversion, expression.Location) : conversion; } #region Factories @@ -299,6 +316,11 @@ public bool Add(StringLiteral/*!*/ literal) { } internal static MSA.Expression/*!*/ TransformConcatentation(AstGenerator/*!*/ gen, List/*!*/ parts, IFactory/*!*/ factory) { + return TransformConcatentation(gen, parts, factory, null); + } + + internal static MSA.Expression/*!*/ TransformConcatentation(AstGenerator/*!*/ gen, List/*!*/ parts, IFactory/*!*/ factory, + int[] partLines) { // fast path for a single element: if (parts.Count == 1) { @@ -311,21 +333,21 @@ public bool Add(StringLiteral/*!*/ literal) { return factory.CreateExpression(gen, (byte[])literal.Value, literal.Encoding); } } else { - return factory.CreateExpressionM(gen, new MSAst.ExpressionCollectionBuilder { MakeConversion(gen, parts[0]) }); + return factory.CreateExpressionM(gen, new MSAst.ExpressionCollectionBuilder { MakeConversion(gen, parts[0], LineOf(partLines, 0)) }); } } var merged = new MSAst.ExpressionCollectionBuilder(); var concat = new LiteralConcatenation(gen.Encoding); - if (!ConcatLiteralsAndTransformRecursive(parts, concat, merged, part => MakeConversion(gen, part))) { + if (!ConcatLiteralsAndTransformRecursive(parts, partLines, concat, merged, (part, line) => MakeConversion(gen, part, line))) { // TODO: we should emit Append calls directly, and not create an array first // TODO: MRI reports a syntax error // we can't concatenate due to encoding incompatibilities, report error at runtime: // Each part is a MutableString here: a literal as itself, anything else converted by #to_s // (the parts' plain Transform is typed object, which the MutableString[] can't hold). var unmerged = new List(); - TransformPartsUnmerged(gen, parts, unmerged); + TransformPartsUnmerged(gen, parts, partLines, unmerged); return factory.CreateExpressionN(gen, unmerged); } @@ -356,16 +378,21 @@ public bool Add(StringLiteral/*!*/ literal) { return AstUtils.Constant(part.Freeze(), typeof(MutableString)); } - private static void TransformPartsUnmerged(AstGenerator/*!*/ gen, List/*!*/ parts, List/*!*/ result) { - foreach (Expression part in parts) { + private static int LineOf(int[] partLines, int index) { + return (partLines != null && index < partLines.Length) ? partLines[index] : 0; + } + + private static void TransformPartsUnmerged(AstGenerator/*!*/ gen, List/*!*/ parts, int[] partLines, List/*!*/ result) { + for (int i = 0; i < parts.Count; i++) { + Expression part = parts[i]; StringLiteral literal; StringConstructor ctor; if ((literal = part as StringLiteral) != null) { result.Add(TransformLiteralPart(literal.Value, literal.Encoding)); } else if ((ctor = part as StringConstructor) != null) { - TransformPartsUnmerged(gen, ctor.Parts, result); + TransformPartsUnmerged(gen, ctor.Parts, ctor.PartLines, result); } else { - result.Add(MakeConversion(gen, part)); + result.Add(MakeConversion(gen, part, LineOf(partLines, i))); } } } @@ -382,8 +409,8 @@ private static void TransformPartsUnmerged(AstGenerator/*!*/ gen, List/*!*/ parts, - LiteralConcatenation/*!*/ concat, MSAst.ExpressionCollectionBuilder/*!*/ result, Func/*!*/ convert) { + private static bool ConcatLiteralsAndTransformRecursive(List/*!*/ parts, int[] partLines, + LiteralConcatenation/*!*/ concat, MSAst.ExpressionCollectionBuilder/*!*/ result, Func/*!*/ convert) { for (int i = 0; i < parts.Count; i++) { Expression part = parts[i]; @@ -395,7 +422,7 @@ private static bool ConcatLiteralsAndTransformRecursive(List/*!*/ pa return false; } } else if ((ctor = part as StringConstructor) != null) { - if (!ConcatLiteralsAndTransformRecursive(ctor.Parts, concat, result, convert)) { + if (!ConcatLiteralsAndTransformRecursive(ctor.Parts, ctor.PartLines, concat, result, convert)) { return false; } } else { @@ -404,7 +431,7 @@ private static bool ConcatLiteralsAndTransformRecursive(List/*!*/ pa concat.Clear(); } - result.Add(convert(part)); + result.Add(convert(part, LineOf(partLines, i))); } } From 1ac8c2995b9c463d8733c2decf05e5484d3fbc84 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:25:19 +0000 Subject: [PATCH 306/439] LEDGER: perf/crubydiff's ninth round Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/perf/LEDGER.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f0b0742f4..2385116ca 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -4220,6 +4220,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has CLR names only (5.ToString("X"), 5.CompareTo(3), (2**70).IsEven); the snake_case spellings (compare_to, to_string, equals, is_even) are NoMethodError, as in CRuby, so inline-matrix's tree_int_key is same. ClrIntegerClrMembers1. For the gate: a program that called 5.to_string or 1.5.compare_to through IronRuby's interop must use the CLR names. + Ninth round (2026-11-28, on fcbc67b + the eighth): an interpolated local variable on a later line of a string (a + heredoc's `#{x}`) reports its own line when its conversion raises: the bridge records the part's line + (StringConstructor.PartLines) and the conversion is marked as a call on a later line is (AstGenerator.AddCallLine). + Backtrace_InterpolatedLocalLine1. For the gate: backtrace lines of such parts. - **perf/json (2026-11-27) - `case` over String literals looks its subject up once while String#=== is the library's (gap 7)** - gated 2026-11-28 (round 6's gate entry). Commit 0a78877 on `claude/perf-strsearch`, based on claude/happy-gauss-95wm2j 15285eb with 0518f08 merged in. Measured first: a perf profile of AWFY From 9ccae7979f18bae45fd998c8af7bcd115fdb7681 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:33:23 +0000 Subject: [PATCH 307/439] Outlined loops write self's instance variables by default, block loops included perf/loopivar left IR_LOOP_IVAR_WRITES off because a generic `n.times { @n += 1 }' timed after a compiled `while' loop that writes an ivar ran 2x slower in the same process. That was the GC: the slow runs are exactly those with a gen-1 or gen-2 collection in them, the process's first gen-1 collection after start-up (about 1.4 MB promoted, 75-100 ms), which a loop that allocates less moves into whatever allocates next. With the switch off and an allocation-free loop the base already compiles timed first, the later loop pays the same collection; clearing the undo log's references changed nothing. Timed one shape per process, nothing is slower (while_small 0.56, while_two 0.92, times_count with block loops 0.75, the others 0.97-1.01, all but while_small overlapping), so the switch is on (IR_LOOP_IVAR_WRITES=0 refuses), and block loops, excluded on the strength of the same artifact, write ivars too: WhileLoopExpression.IsBlockLoop is gone. Util/bench/loopivar-shapes.rb says to time one shape per process. Checked: loop-ivar-matrix prints CRuby's output on and off; gate-matrices (loop-ivar, ivar, loop-exit, osr-array, block-loop, jit, hot-shapes, jit-scan, marshal, parked-scope) in every mode and with the switch off: PASS; ivar-stress OK; specs as on the base; IronRuby.Tests (Debug) PASSED; census 0 methods changed; alloc.rb flat; AWFY 0.98-1.02, overlapping. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- .../Ast/Expressions/WhileLoopExpression.cs | 5 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 16 ++++---- Src/Ruby/Runtime/Osr/BlockLoopSite.cs | 2 +- Util/bench/loopivar-shapes.rb | 22 ++++++----- Util/ivar-stress.rb | 4 +- Util/loop-ivar-matrix.rb | 8 ++-- Util/perf/LEDGER.md | 39 +++++++++++++++++++ 7 files changed, 66 insertions(+), 30 deletions(-) diff --git a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs index 8b161033f..1b2169237 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs @@ -41,11 +41,6 @@ public partial class WhileLoopExpression : Expression { private readonly bool _isWhileLoop; // while or until private readonly bool _isPostTest; // do-while or while-do - // A loop BlockLoopSite made of a block and its iterator (`n.times { ... }', `a.each { ... }'), not one - // the source wrote: the method JIT's loop tier refuses an instance variable write in it - // (JitCompiler.EmitLoopIVarWrite). - internal bool IsBlockLoop; - public Expression Condition { get { return _condition; } } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 0369fdd3b..4d6280c87 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1773,15 +1773,13 @@ internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { } /// - /// With IR_LOOP_IVAR_WRITES=1, outlined `while' loops store into self's instance variables (`@x = v', `@x op= v'). - /// Off by default: the loops get faster (a counter 0.57-0.80), but once one has run, the process's other code - /// ran up to 2x slower in the measurements (a generic `n.times { @n += 1 }' afterwards, diagnosed no further - /// than the logged stores; Util/perf/LEDGER.md, perf/loopivar). A block loop (BlockLoopSite: `n.times { @n += 1 }', `a.each { |x| @last = x }') - /// still refuses them: there the logged store cost as much as the generic block call it replaced, or more - /// (`each { |x| @last = x }' 1.25x), and its last statement is followed by the loop's counter step, so it - /// cannot go unlogged either (Util/perf/LEDGER.md, perf/loopivar). + /// Outlined loops - a `while' and a block loop (BlockLoopSite: `n.times { @n += 1 }', `a.each { |x| @last = x }') - + /// store into self's instance variables (`@x = v', `@x op= v'); IR_LOOP_IVAR_WRITES=0 refuses them, as before. + /// (Off at first: a later generic loop in the same process measured 2x slower after one had run. That was the + /// process's first gen-1 collection after start-up, which a loop that allocates less moves into the next timed + /// run; an ordinary compiled loop moves it the same way. Util/perf/LEDGER.md, perf/loopivar2.) /// - internal static readonly bool LoopIVarWrites = Environment.GetEnvironmentVariable("IR_LOOP_IVAR_WRITES") == "1"; + internal static readonly bool LoopIVarWrites = Environment.GetEnvironmentVariable("IR_LOOP_IVAR_WRITES") != "0"; /// /// `@x = v' / `@x op= v' in an outlined loop: the store `o.x = v' makes there (EmitAttributeWrite), into self's @@ -1843,7 +1841,7 @@ internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { // part way through would leave the scope's locals as they were on entry: in a loop // the write is a logged store that deopts instead (EmitLoopIVarWrite). if (_loop != null) { - if (!LoopIVarWrites || _loop.IsBlockLoop) { throw Bail("instance variable write in an outlined loop"); } + if (!LoopIVarWrites) { throw Bail("instance variable write in an outlined loop"); } return EmitLoopIVarWrite(ivarTarget, op, node.Right, out type); } JT vt; diff --git a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs index 81f9fb796..f936aa5e2 100644 --- a/Src/Ruby/Runtime/Osr/BlockLoopSite.cs +++ b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs @@ -612,7 +612,7 @@ private void Retire() { statements.Add(new SimpleAssignmentExpression(counter, Literal.Integer(1, location), kind == BlockLoopKind.DownTo ? "-" : "+", location)); - return new WhileLoopExpression(condition, true, false, statements, location) { IsBlockLoop = true }; + return new WhileLoopExpression(condition, true, false, statements, location); } /// diff --git a/Util/bench/loopivar-shapes.rb b/Util/bench/loopivar-shapes.rb index ce4975d28..3b98b782c 100644 --- a/Util/bench/loopivar-shapes.rb +++ b/Util/bench/loopivar-shapes.rb @@ -1,13 +1,15 @@ -# Instance variable writes inside loops (perf/loopivar): `while' loops that write self's variables, which the -# OSR tier outlines with IR_LOOP_IVAR_WRITES=1 (JitCompiler.EmitLoopIVarWrite; off by default), and -# block loops that do, which it still does not (times_count, each_last: controls with while_plain). Format of -# Util/perf/ab.rb: ` ns ` per shape, ns per iteration of the loop; shape names as -# arguments, N from the environment. BYTES=1 (IronRuby only): bytes allocated per -# iteration instead. INSTR=1 (ab.rb -i): instructions per iteration as well. +# Instance variable writes inside loops (perf/loopivar): `while' loops and block loops that write self's +# variables, which the loop tiers outline (JitCompiler.EmitLoopIVarWrite; IR_LOOP_IVAR_WRITES=0 refuses +# them, as before); while_plain is the control. Format of Util/perf/ab.rb: ` ns ` per +# shape, ns per iteration of the loop; shape names as arguments, N from the environment. BYTES=1 (IronRuby +# only): bytes allocated per iteration instead. INSTR=1 (ab.rb -i): instructions per iteration as well. # -# ruby Util/perf/ab.rb -r 5 Util/bench/loopivar-shapes.rb cruby=ruby \ -# "base=env IR_CONFIG=Release ../base/ir.sh" "off=env IR_CONFIG=Release ./ir.sh" \ -# "new=env IR_LOOP_IVAR_WRITES=1 IR_CONFIG=Release ./ir.sh" +# Time ONE shape per process (`-- shape'): a loop that allocates less moves the process's first gen-1 +# collection after start-up (about 75 ms here) into the next shape's runs, which then look 2x slower +# (perf/loopivar2); the GC.start before each run does not settle it. +# +# for s in while_count times_count ...; do ruby Util/perf/ab.rb -r 6 Util/bench/loopivar-shapes.rb \ +# "off=env IR_LOOP_IVAR_WRITES=0 IR_CONFIG=Release ./ir.sh" "on=env IR_CONFIG=Release ./ir.sh" -- $s; done # # while_count `@n += 1' past the small-integer cache in a `while' # while_small `@n = (@n + 1) & 511' (cached boxes) @@ -46,6 +48,8 @@ def run_shape(name) 3.times { run_once(L.new, name) } 6.times do o = L.new + # a full collection first, so that a run starts with nothing young left over from the last one + GC.start c0 = INSTR && INSTR.read t = BYTES ? System::GC.get_total_allocated_bytes(true) : Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID) r = run_once(o, name) diff --git a/Util/ivar-stress.rb b/Util/ivar-stress.rb index f4dd7c5a1..c56240411 100644 --- a/Util/ivar-stress.rb +++ b/Util/ivar-stress.rb @@ -347,8 +347,8 @@ def fbody_read(list) = list.map { |b| b.x * 1.0 } record.("final @f#{t}/x of body #{t} #{got.inspect}, owner last read #{flast[t].inspect}") unless got == flast[t] end -# Loops that write instance variables (perf/loopivar: with IR_LOOP_IVAR_WRITES=1 the OSR tier outlines a `while' one, each store logged -# and taken back by a deopt later in its iteration). Thread t runs a `while' loop and a block loop that count +# Loops that write instance variables (perf/loopivar: the loop tiers outline them, each store logged and +# taken back by a deopt later in its iteration; IR_LOOP_IVAR_WRITES=0 refuses them). Thread t runs a `while' loop and a block loop that count # into its own @l of one shared object, while the others add and remove variables of that object (its # slots move under the stores) and read every @l: a value read is an Integer no greater than its owner # has counted to, and each owner's final count is exactly the number of iterations it ran. diff --git a/Util/loop-ivar-matrix.rb b/Util/loop-ivar-matrix.rb index 4a6c3ca55..450b97db0 100644 --- a/Util/loop-ivar-matrix.rb +++ b/Util/loop-ivar-matrix.rb @@ -1,8 +1,8 @@ # Differential matrix for instance variable writes inside loops (perf/loopivar): `@x = v' and -# `@x op= v' in a `while' loop, which the OSR tier outlines and compiles to a logged store into self's -# variable (JitCompiler.EmitLoopIVarWrite, JitRuntime.WriteSelfIVar) when IR_LOOP_IVAR_WRITES=1 (off -# by default; run it both ways). A block loop (`times', `each') still refuses them; its rows are here for when it -# does not. Run under CRuby and under ./ir.sh and diff: +# `@x op= v' in a `while' loop and in a block loop (`times', `each'), which the loop tiers outline and +# compile to a logged store into self's variable (JitCompiler.EmitLoopIVarWrite, JitRuntime.WriteSelfIVar); +# IR_LOOP_IVAR_WRITES=0 refuses them, as before (run it both ways). Run under CRuby and under ./ir.sh +# and diff: # # ruby Util/loop-ivar-matrix.rb > /tmp/mri.txt # ./ir.sh Util/loop-ivar-matrix.rb > /tmp/ir.txt diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 09f9bd71a..6df6335d5 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2025,6 +2025,43 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/loopivar2 (/perf-step, 2026-11-28, not gated) - outlined loops write self's instance + variables by default (`IR_LOOP_IVAR_WRITES=0` refuses them), block loops included: the 2x + "slowdown" that kept perf/loopivar off was the GC, not the stores** (on fcbc67b). + - **The cause.** In Util/bench/loopivar-shapes.rb, `times_count` timed after `while_count` in one + process ran 54-71 ns against 29 with the switch on, every time; alone it was the same both ways. + Per run, GC.CollectionCount and GC.GetTotalPauseDuration: the slow runs are exactly the ones with + a gen-1 or gen-2 collection in them (43-51 ms each, about 50 ns an iteration of a million), and + the switch-off runs had only gen-0 ones (about 1 ms). What happens is that the process owes the GC + its first gen-1 collection after start-up (about 1.4 MB promoted, 75-100 ms here). With the switch + off, `while_count' allocates a box per iteration and pays it there; compiled, it allocates less, and + the collection falls into the next thing that allocates. The control settles it: with the switch + off and `while_plain' (a loop the base already compiles, which allocates nothing) first, the + `times_count' phase pays the same collection (87-100 ms, 1,440 KB promoted) as with the switch on + and `while_count' first (77-79 ms, 1,434 KB). Clearing the undo log's references on every Commit + changed nothing (the guess in perf/loopivar), nor did a full GC.start before each run. So the + measurement was wrong: shape files that run several shapes in one process carry this debt from + one shape to the next. loopivar-shapes.rb now says to time one shape per process. + - **Measured right** (one shape per process, ab.rb, 6 rounds, least, switch off -> on): while_count + 1.01, while_small 0.56, while_float 0.99, while_two 0.92, times_count 0.75 (block loops admitted), + each_last 0.97, the control 1.00 - all overlapping but while_small. So perf/loopivar's exclusion + of block loops (from `each_last' 1.25, the same artifact) is undone: WhileLoopExpression.IsBlockLoop + is gone again. The hold-back to the end of the iteration is not needed for speed; it is still what + would answer the racing reader (a thread that reads the variable during a deopt can see it go back + one write and forward again, as for the loop tiers' logged Array, Hash and `o.x = v' stores). + - **Census** (Util/perf/census.rb over AWFY, Src/StdLib and app-shapes.rb): 0 methods changed, up or + down; it sees the method JIT and light frames, and this is the loop tiers only. + - **Numbers**: alloc.rb off -> on: Richards 801 -> 666 KB per iteration, Towers 70 -> 124 KB (its + small figure moved 102-206 KB between identical builds before), the rest flat. AWFY by clock, + 10 alternating rounds, medians off -> on: DeltaBlue 1.006, Richards 0.983, Bounce 1.018, Towers + 1.010, all overlapping (no AWFY loop stops first at an ivar write: perf/loopivar's count). + - **Checks**: Util/loop-ivar-matrix.rb CRuby's output with the switch on (24 loops outlined, 21 deopts + taken back) and off; gate-matrices (loop-ivar, ivar, loop-exit, osr-array, block-loop, jit, + hot-shapes, jit-scan, marshal, parked-scope) in every mode and with the switch off: PASS; + Util/ivar-stress.rb OK three times on, once off; spec language/while, until, loop, variables, + core/kernel instance_variable_set/get, remove_instance_variable, core/integer/times, + core/array/each as on the base; IronRuby.Tests (Debug) PASSED. + - **Gate of 2026-11-28 for round 7 of round thirty-seven** (perf/crubydiff's fifth and sixth rounds, perf/literalsite, perf/endpark, perf/stage0 and perf/stagea with the block-cost harness and the procscope design, perf/primitive (rejected), perf/clrlookup, perf/bootparse, perf/permute, perf/parkedtuple @@ -2354,6 +2391,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **Next**: find what slows the rest of the process (a longer run with the GC's event counters on the two orders), then hold the stores back to the end of the iteration (Sink.cs's scheme per iteration) so that they need no log at all, which also answers the racing reader. + - **Later** (perf/loopivar2): the slowdown was where a GC collection fell, not the stores; on by + default since, block loops included. - **Gate of 2026-11-28 for round 6 of round thirty-seven** (perf/crubydiff's third and fourth rounds, perf/sieve and gap 39's analysis, perf/evallocals, perf/evalscreen, perf/evalboxes, perf/hsortby, From 08274494a047742c0e23796ba4a1ed50fc0a2ae1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:44:19 +0000 Subject: [PATCH 308/439] A filter by identity hash keeps objects without instance data out of the instance data table perf/kernelcall found that every Array's class lookup went to the instance data table (a ConditionalWeakTable) because $LOAD_PATH has a singleton class, and gave RubyArray a bit to skip it. The same holds for any CLR class once one of its instances has a class of its own: after `def str.x` on one String and on one Hash, @s.nil? in a compiled body cost 2572 instructions against 2128 (+21%), @s.is_a?(String) 3314 against 2426 (+37%), and every other String and Hash of the process paid it. A bit per object is no option there: MutableString changes its _flags without atomics everywhere, so a concurrent change could lose the bit for good, and Hash has no flags. Each runtime now keeps a filter of 65,536 bits (8 KB) indexed by the object's identity hash (RuntimeHelpers.GetHashCode). GetInstanceData sets the object's bit, atomically, before it adds the object to the table or has an IRubyInstanceDataOwner make its own data; bits are never cleared. A clear bit means the object has no instance data for this runtime: TryGetClrTypeInstanceData answers so without the table, and GetImmediateClassOfNonRubyObject answers the CLR type's class (unless the type has adopted instances). A set bit - the object's or another's - goes to the table as before. The filter is the runtime's own, as the table is, so several runtimes in a process stay apart. IR_INSTANCE_DATA_FILTER=0 turns it off. Instructions a call with one String and one Hash given a singleton method (count.sh, unchanged -> this): @s.nil? 2572 -> 2335, @h.nil? 2626 -> 2371, @s.is_a?(String) 3314 -> 2840, @h.is_a?(Hash) 3404 -> 2894; without them unchanged (2128, 2164, 2426, 2480). What is left over the plain case, about 200 a lookup, is the identity hash, a call into the runtime. Clock (ab.rb, four rounds, with the singletons): @h.nil? 0.88, @s.is_a? 0.87, @h.is_a? 0.80, @s.nil? within its spread; without them, and core-small's hash_fetch, hash_each, strip, str_center, String(int) and dig_arr_hash, within the noise. Census (Src/StdLib + AWFY, 28,378 methods): 0 up, 0 down. Util/clr-class-matrix.rb (new: Strings, Hashes, Ranges, Procs, Regexps and Structs given singleton classes while compiled code calls through them, another one unaffected, a singleton nil?, instance variables, object_id, freeze, clone and dup, extend; subclasses; frozen literals and Symbols; 70,000 Strings with instance variables and 70,000 Hashes with object ids, which fill the filter; threads) prints CRuby's output on the unchanged build and on this one by default, IR_INSTANCE_DATA_FILTER=0, IR_LIGHT_FRAMES=0, -X:NoJIT -X:NoOSR, -X:NoJITCalls and R2R. array-class, ivar, jit, jit-calls, light-entry, shared-rule-light, kernel-string and hot-shapes print what they did in those modes. ruby/spec core/string, hash, kernel, objectspace and enumerator: the same examples on both builds. IronRuby.Tests (Debug): the 460 Array, Hash, String, Singleton, Clone, Ivar, Object, Clr, Jit, Freeze, Kernel, Backtrace, Thread, Enumerator, Hosting and Engine tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Src/Ruby/Runtime/RubyContext.cs | 49 +++++++++++++- Util/clr-class-matrix.rb | 109 ++++++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 Util/clr-class-matrix.rb diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 10f1599f0..0a68ecd5c 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -2450,6 +2450,13 @@ private RubyClass TryGetClassOfRubyObject(object obj) { if (array != null && !array.MayHaveInstanceData && !result.HasAdoptedInstances) { return result; } + // any other object of a CLR type that keeps its data in the table, the table never given any for it + // (MayHaveTableInstanceData): one String or Hash with a singleton class sent every other one down the + // lookups below + if (array == null && !result.HasAdoptedInstances && RubyUtils.HasObjectState(obj) && !(obj is BigInteger) && + !MayHaveTableInstanceData(obj)) { + return result; + } } RubyInstanceData data = TryGetNonRubyObjectInstanceData(obj); if (data != null && (result = data.ImmediateClass) != null) { @@ -2967,10 +2974,43 @@ internal bool TryGetClrTypeInstanceData(object/*!*/ obj, out RubyInstanceData re if (owner != null && owner.TryGetInstanceData(this, out result)) { return result != null; } + if (!MayHaveTableInstanceData(obj)) { + result = null; + return false; + } // lock-free: ConditionalWeakTable reads take no lock return _referenceTypeInstanceData.TryGetValue(obj, out result); } + // IR_INSTANCE_DATA_FILTER=0: every object may have data in the table, as before + private static readonly bool _instanceDataFilterEnabled = Environment.GetEnvironmentVariable("IR_INSTANCE_DATA_FILTER") != "0"; + + private const int InstanceDataFilterBits = 1 << 16; + + /// + /// A bit for each value of an object's identity hash (modulo the filter's size), set before this runtime adds the + /// object to _referenceTypeInstanceData, or has an IRubyInstanceDataOwner make its own (GetInstanceData), and never + /// cleared. A clear bit means the object has no instance data for this runtime, which a ConditionalWeakTable lookup costs some 200 instructions to find out; a set one - this + /// object's or another's - sends the reader to the table, as before. The object of a CLR type that has any instance + /// with a class of its own (a String or a Hash with a singleton method) was looked up there on every call + /// that asked its class (GetImmediateClassOf): every String once one String had one. 8 KB a runtime. + /// + private readonly int[]/*!*/ _instanceDataFilter = new int[InstanceDataFilterBits / 32]; + + private bool MayHaveTableInstanceData(object/*!*/ obj) { + if (!_instanceDataFilterEnabled) { + return true; + } + int bit = RuntimeHelpers.GetHashCode(obj) & (InstanceDataFilterBits - 1); + return (Volatile.Read(ref _instanceDataFilter[bit >> 5]) & (1 << (bit & 31))) != 0; + } + + // before the entry is added: a reader that finds the bit clear finds no entry either + private void NoteTableInstanceData(object/*!*/ obj) { + int bit = RuntimeHelpers.GetHashCode(obj) & (InstanceDataFilterBits - 1); + Interlocked.Or(ref _instanceDataFilter[bit >> 5], 1 << (bit & 31)); + } + /// /// Replaces the Ruby class associated with a CLR-backed object. IO#reopen uses this to /// give the receiver the source IO's class, as MRI does, while retaining its object id. @@ -3020,8 +3060,12 @@ public void ReplaceClrObjectClass(object/*!*/ obj, RubyClass/*!*/ cls) { } var owner = obj as IRubyInstanceDataOwner; - if (owner != null && (result = owner.GetInstanceData(this)) != null) { - return result; + if (owner != null) { + // the filter covers the data an owner keeps itself too (see MayHaveTableInstanceData) + NoteTableInstanceData(obj); + if ((result = owner.GetInstanceData(this)) != null) { + return result; + } } if (_referenceTypeInstanceData.TryGetValue(obj, out result)) { @@ -3032,6 +3076,7 @@ public void ReplaceClrObjectClass(object/*!*/ obj, RubyClass/*!*/ cls) { if (array != null) { array.MarkMayHaveInstanceData(); } + NoteTableInstanceData(obj); return _referenceTypeInstanceData.GetValue(obj, _CreateInstanceData); } diff --git a/Util/clr-class-matrix.rb b/Util/clr-class-matrix.rb new file mode 100644 index 000000000..16b781c6c --- /dev/null +++ b/Util/clr-class-matrix.rb @@ -0,0 +1,109 @@ +# Differential matrix for the class of a String, a Hash and other objects of CLR types that keep their instance data +# in the runtime's table (RubyContext._referenceTypeInstanceData): their singleton classes, instance variables, object +# ids and frozen state, as compiled code and call sites find them, while other objects of the same class have singleton +# classes. An object the table was never given data for is answered its class without the table lookup +# (RubyContext.MayHaveTableInstanceData, IR_INSTANCE_DATA_FILTER). Run it under CRuby and under ./ir.sh, and diff: +# +# ruby Util/clr-class-matrix.rb > /tmp/mri.txt 2>&1 +# ./ir.sh Util/clr-class-matrix.rb > /tmp/ir.txt 2>&1 +# diff /tmp/mri.txt /tmp/ir.txt + +def t(label) + print label.ljust(52), ' => ' + begin + puts yield.inspect + rescue Exception => e + puts "#{e.class}: #{e.message.gsub(/0x\h+/, '0x').gsub(/#]*>/, '#')}" + end +end + +class Probe + def initialize(o) = @o = o + def nil_p = @o.nil? + def cls = @o.class + def kind = [@o.is_a?(@o.class), @o.class === @o, @o.instance_of?(@o.class)] + def hello = @o.respond_to?(:hello) ? @o.hello : :none + def sm = @o.singleton_methods.sort +end + +def hot(p, n = 3000) = n.times { p.nil_p; p.cls; p.kind; p.hello } + +MAKERS = { + 'String' => -> { +"s" }, + 'Hash' => -> { { k: 1 } }, + 'Range' => -> { (1..2).dup }, + 'Proc' => -> { proc { 1 } }, + 'Regexp' => -> { Regexp.new("a") }, + 'Struct' => -> { Struct.new(:a).new(1) }, +} + +MAKERS.each do |name, make| + x = make.() + px = Probe.new(x) + hot(px) + t("#{name}: plain") { [px.nil_p, px.cls == x.class, px.kind, px.hello] } + def x.hello = :singleton + t("#{name}: after def x.hello") { [px.hello, px.cls == x.class, px.kind, px.sm] } + hot(px) + y = make.() + py = Probe.new(y) + hot(py) + t("#{name}: another one, unaffected") { [py.nil_p, py.hello, py.sm] } + def y.nil? = :mine + t("#{name}: a singleton nil? on it") { [py.nil_p, y.nil?] } + z = make.() + z.instance_variable_set(:@iv, 5) + pz = Probe.new(z) + hot(pz) + t("#{name}: an instance variable") { [z.instance_variable_get(:@iv), pz.nil_p, pz.hello] } + w = make.() + id = w.object_id + t("#{name}: object_id stays") { w.object_id == id } + v = make.() + v.freeze + t("#{name}: frozen") { [v.frozen?, Probe.new(v).nil_p, (def v.q = 1 rescue $!.class)] } + u = make.() + def u.hello = :u + u.instance_variable_set(:@v, 1) + t("#{name}: clone and dup") { [Probe.new(u.clone).hello, Probe.new(u.dup).hello, u.clone.instance_variable_get(:@v)] } + s = make.() + s.extend(Module.new { def hello = :extended }) + t("#{name}: extend") { Probe.new(s).hello } +end + +t('a frozen literal cannot have one') { s = "lit".freeze; def s.x = 1 } +t('a Symbol cannot have one') { s = :sym; def s.x = 1 } +t('a String subclass') { k = Class.new(String); x = k.new("a"); def x.hello = :sub; [Probe.new(x).hello, Probe.new(x).cls == k] } +t('a Hash subclass') { k = Class.new(Hash); x = k.new; def x.hello = :sub; [Probe.new(x).hello, Probe.new(x).cls == k] } + +# ---------------------------------------------------------------- many objects with data (the filter fills) +t('70000 Strings with instance variables, then lookups') do + many = Array.new(70_000) { |i| s = +"m#{i}"; s.instance_variable_set(:@i, i); s } + plain = Array.new(1000) { |i| +"p#{i}" } + one = many[12_345] + def one.hello = :one + [many.sum { |s| s.instance_variable_get(:@i) }, plain.count { |s| Probe.new(s).hello == :none }, + Probe.new(one).hello, many.count { |s| s.singleton_methods.empty? }] +end +t('70000 object_ids, then singleton classes on a few') do + many = Array.new(70_000) { |i| h = { i: i }; h.object_id; h } + few = many.each_slice(10_000).map(&:first) + few.each_with_index { |h, i| h.define_singleton_method(:hello) { i } } + [few.map { |h| Probe.new(h).hello }, Probe.new(many[1]).hello, Probe.new({}).hello] +end + +# ---------------------------------------------------------------- threads +t('threads give Strings singleton classes') do + strs = Array.new(8) { +"t#{_1}" } + probes = strs.map { Probe.new(_1) } + ths = strs.each_with_index.map { |x, i| Thread.new { 200.times { probes[i].hello }; x.define_singleton_method(:hello) { i }; probes[i].hello } } + ths.map(&:value) +end +t('a singleton defined while another thread calls') do + x = { a: 1 } + px = Probe.new(x) + th = Thread.new { r = nil; 20000.times { r = px.hello }; r } + def x.hello = :late + th.join + px.hello +end From 32757423f3e80a15759d0ea4f7db0b3b650d2a9d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:44:19 +0000 Subject: [PATCH 309/439] Ledger: perf/datafilter landed (not gated) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5ABnT4ogE8wHNcyDK --- Util/perf/LEDGER.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index d0b817055..e06b373e0 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2025,6 +2025,20 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/datafilter (/perf-step, 2026-11-28, on fcbc67b + 672867e) - a filter by identity hash + keeps objects without instance data out of the instance data table (`IR_INSTANCE_DATA_FILTER`)** + - instructions and clock, not gated. perf/kernelcall's lead: once one String and one Hash have a + singleton method, every String's and Hash's class lookup went to the ConditionalWeakTable + (`@s.nil?` compiled +21% instructions, `@s.is_a?(String)` +37%). A per-object bit is unsafe on + MutableString (non-atomic `_flags`) and absent on Hash, so each runtime keeps 65,536 bits (8 KB) + by `RuntimeHelpers.GetHashCode`, set before data is added, never cleared. With the singletons: + `@s.nil?` 2572 -> 2335, `@s.is_a?` 3314 -> 2840 instructions; clock `@h.nil?` 0.88, `@s.is_a?` + 0.87, `@h.is_a?` 0.80; without them unchanged. Census 0 up, 0 down. Left: ~200 instructions a + lookup over the plain case, the identity hash's runtime call. + `Util/clr-class-matrix.rb` (new) CRuby's output in five modes, switch off and R2R; eight other + matrices unchanged; ruby/spec core/string, hash, kernel, objectspace, enumerator the same; + 460 IronRuby.Tests on Debug pass. + - **perf/kernelcall (/perf-step, 2026-11-28, on 744b83e) - an Array without instance data is answered its class without the instance data table (`RubyArray.MayHaveInstanceData`, `IR_ARRAY_CLASS_FAST`)** - instructions and clock, not gated. The round's premise (a C# Kernel From 9aff9a7397785c7c6f0c9e4570ec583829078b95 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:05:39 +0000 Subject: [PATCH 310/439] Default object descriptions are BINARY strings, as in CRuby Object.new.to_s and Object.new.inspect are ASCII-8BIT in CRuby 4.0 (rb_any_to_s and rb_obj_inspect build them with rb_sprintf and rb_str_buf_new), and so is every core #inspect that starts with "# Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 28 ++++++++++++++++++ Src/Libraries/Builtins/ProcOps.cs | 19 +++++++++--- Src/Ruby/Runtime/RubyUtils.cs | 39 +++++++++++++++++++++---- 4 files changed, 77 insertions(+), 10 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e9506bbb3..cf0538d73 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -149,6 +149,7 @@ public Tests(Driver/*!*/ driver) { Scenario_Globals3, Scenario_InspectRecursive1, Scenario_InspectObjectId1, + Scenario_DescriptionEncoding1, Scenario_RubyMethodMissing1, Scenario_RubyMethodMissing2, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index e1c4d1d17..d1cb74103 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -64,6 +64,34 @@ public void Scenario_Globals3() { "); } + /// + /// The default descriptions (rb_any_to_s, rb_obj_inspect, and the core #inspect methods that + /// start with #<Foo:0x...) are BINARY strings in MRI; a class name, an instance variable name + /// or a part that is not ASCII takes them over to UTF-8. + /// + public void Scenario_DescriptionEncoding1() { + TestOutput(@" +require 'ruby4' +class Foo; def initialize(v); @v = v; end; end +class Café; end +o = Object.new +o.instance_variable_set(:@é, 1) +p Object.new.to_s.encoding, Object.new.inspect.encoding, Foo.new(1).inspect.encoding +p Café.new.to_s.encoding, Café.new.inspect.encoding, o.inspect.encoding +p proc {}.inspect.encoding, Thread::Mutex.new.inspect.encoding, binding.inspect.encoding +", @" +# +# +# +# +# +# +# +# +# +"); + } + /// /// Kernel#inspect of an object met again inside its own inspect: MRI's "#<Foo:0x... ...>". /// diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index 839a24767..5505165d0 100644 --- a/Src/Libraries/Builtins/ProcOps.cs +++ b/Src/Libraries/Builtins/ProcOps.cs @@ -160,7 +160,8 @@ public static RubyArray GetSourceLocation(Proc/*!*/ self) { /// by a space rather than by the '@' this used to print, omitted entirely when the proc has /// no Ruby source or comes from Method#to_proc, and replaced by "(&:name)" for a proc a /// Symbol produced. The result is - /// a binary string, as every #inspect-ish description in MRI is. + /// a binary string, as every #inspect-ish description in MRI is, unless the path or the symbol + /// name is not ASCII: then it is UTF-8. /// [RubyMethod("to_s"), RubyMethod("inspect")] public static MutableString/*!*/ ToS(Proc/*!*/ self) { @@ -169,11 +170,11 @@ public static RubyArray GetSourceLocation(Proc/*!*/ self) { var str = RubyUtils.ObjectToMutableStringPrefix(context, self); if (self.SymbolName != null) { str.Append("(&:"); - str.Append(self.SymbolName); + AppendDescriptionText(str, self.SymbolName); str.Append(')'); } else if (self.SourcePath != null && !self.Dispatcher.WrapsMethod) { str.Append(' '); - str.Append(self.SourcePath); + AppendDescriptionText(str, self.SourcePath); str.Append(':'); str.Append(self.SourceLine.ToString(CultureInfo.InvariantCulture)); } @@ -183,11 +184,21 @@ public static RubyArray GetSourceLocation(Proc/*!*/ self) { } str.Append('>'); - str.ForceEncoding(RubyEncoding.Binary); return str; } + // The description starts BINARY (RubyUtils.CreateObjectDescription), which cannot hold the + // characters of a path or a symbol name that is not ASCII as they are; appended as a UTF-8 + // string, it takes the description over to UTF-8, as it does in MRI. + private static void AppendDescriptionText(MutableString/*!*/ str, string/*!*/ text) { + if (text.IsAscii()) { + str.Append(text); + } else { + str.Append(MutableString.Create(text, RubyEncoding.UTF8)); + } + } + [RubyMethod("to_proc")] public static Proc/*!*/ ToProc(Proc/*!*/ self) { return self; diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index ec1424022..3e9294b81 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -284,9 +284,10 @@ public static bool HasSingletonClass(object obj) { var context = tosConversion.Context; using (IDisposable handle = RubyUtils.InfiniteInspectTracker.TrackObject(obj)) { - MutableString str = MutableString.CreateMutable(context.GetIdentifierEncoding()); + string className = context.GetClassDisplayName(obj); + MutableString str = CreateObjectDescription(context, className); str.Append("#<"); - str.Append(context.GetClassDisplayName(obj)); + str.Append(className); // Ruby prints 2*object_id for objects str.Append(':'); @@ -308,15 +309,18 @@ public static bool HasSingletonClass(object obj) { } else { str.Append(", "); } - // TODO (encoding): - str.Append(var.Key); + if (var.Key.IsAscii()) { + str.Append(var.Key); + } else { + AppendToObjectDescription(str, MutableString.Create(var.Key, context.GetIdentifierEncoding())); + } str.Append('='); var inspectSite = inspectStorage.GetCallSite("inspect"); object inspectedValue = inspectSite.Target(inspectSite, var.Value); var tosSite = tosConversion.GetSite(ConvertToSAction.Make(context)); - str.Append(tosSite.Target(tosSite, inspectedValue)); + AppendToObjectDescription(str, tosSite.Target(tosSite, inspectedValue)); } } str.Append(">"); @@ -325,8 +329,31 @@ public static bool HasSingletonClass(object obj) { } } + /// + /// MRI's default descriptions (rb_any_to_s, rb_obj_inspect, and the "#<Foo:0x...>" of most + /// core #inspect methods) are BINARY strings: Object.new.to_s.encoding is ASCII-8BIT. Only a + /// class name that is not ASCII gives the result its own encoding, as rb_sprintf's PRIsVALUE does. + /// + public static MutableString/*!*/ CreateObjectDescription(RubyContext/*!*/ context, string/*!*/ className) { + return MutableString.CreateMutable(className.IsAscii() ? RubyEncoding.Binary : context.GetIdentifierEncoding()); + } + + /// + /// Appends a part of an object's description the way rb_obj_inspect does: a part that is not ASCII + /// takes an ASCII-only description over to its encoding ("#<Foo @s=\"é\">" is UTF-8), and one + /// that would be incompatible with what the description already holds is added as bytes, leaving + /// it BINARY, where String#<< would raise Encoding::CompatibilityError. + /// + public static void AppendToObjectDescription(MutableString/*!*/ str, MutableString/*!*/ part) { + if (str.Encoding == RubyEncoding.Binary && !part.IsAscii() && !str.IsAscii()) { + str.Append(part.ToByteArray()); + } else { + str.Append(part); + } + } + public static MutableString/*!*/ FormatObjectPrefix(RubyContext/*!*/ context, string/*!*/ className, long objectId) { - MutableString str = MutableString.CreateMutable(context.GetIdentifierEncoding()); + MutableString str = CreateObjectDescription(context, className); str.Append("#<"); str.Append(className); From 7c0eb490fc13eb0368c853fd6a8a0ce998ff2870 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:09:33 +0000 Subject: [PATCH 311/439] Ledger: perf/heldrfc, and how perf/literalcode had undone perf/havlakalloc Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/perf/LEDGER.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 8ed74a924..009df4383 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1444,6 +1444,12 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Vector#each` costs 3-4% more instructions per call than the scope-ful one did. Round forty-two took the first of those (see Landed, perf/namedblock): a block that a method only passes on stays reusable. Havlak 1.33 -> 1.17 GB an iteration. + Round forty-three found both undone by round thirty-seven's perf/literalcode, merged + with them: it takes a method that evaluates a literal block on every call out of light + frames (`Vector#each`, `has_some` and their callers), and a method with a scope converted + its caller's literal for good, so at fcbc67b Havlak was back at 1.70-1.79 GB. Now a + method's scope holds the block as a light frame's does (see Landed, perf/heldrfc): + 1.18 GB. 26. **Start-up: `gem` and `irb` answer in 0.7 to 2.2 s, CRuby in 0.1 to 0.2** (the one thing that has to stay fast while the tiers stay on by default, and it is not fast). 2026-11-18, a7060a27, the ReadyToRun host (`IR_CONFIG=R2R`, what `ir.sh` runs when @@ -2027,6 +2033,43 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/heldrfc 708f407 (round forty-three, 2026-11-28) - a method's scope holds its caller's literal + block until it is parked (gap 25)** - not gated. At fcbc67b (rounds seven and eight merged) Havlak + allocated 1.79 GB an iteration again, method scopes 24% and Procs 13% as before perf/havlakalloc: round + thirty-seven's perf/literalcode (`2eda4af`, "a body that evaluates a literal block on every call is not a + light frame") made `Vector#each`, `has_some` and every method that calls them with a literal methods + with a scope made at entry (`IR_LIGHT_FRAMES=why`: "body needs its scope after the rewrite"), and a method + with a scope converted its caller's literal for good - not at the call site's CreateRfcForMethod, which + these calls do not go through, but in the scope's own InitializeRfc (Kind = Proc, the scope its frame, + never inactive again). Found by the GC allocation-tick probe and by printing what refused each park. + Now a method's scope converts the literal as before but marks it reusable and held + (`RubyMethodScope.InitializeMethodRfc`, `Proc.HoldForMethodScope`; CreateRfcForMethod likewise), and + EndPark releases the hold and drops the Proc's frame when it parks the scope (`Proc.ReleaseHold(scope)`) + - perf/havlakalloc's proof, which holds for a method with a scope as for a light frame: a method that + names its block or calls super has no parking slot, and parking means nothing captured the scope nor kept + a Proc of it. A block another method passed on (perf/namedblock) that reaches a method with a scope is + held by it the same way instead of being cleared for good. Switch: IR_HELD_METHOD_BLOCKS=0. + Census (Src/StdLib + AWFY, 28,378 methods): 0 methods changed - light frames 82.7%, JIT compiles 12.0%, + maybe 11.5%, never 76.6% on both (a runtime change); perf/literalcode had taken light frames from 94.7%. + Bytes (alloc.rb against 2e96b84, perf/namedblock merged with fcbc67b): Havlak 1,697,532,242 -> + 1,180,852,612 (0.70), DeltaBlue 14,605,880 -> 9,664,089 (0.66), Towers 135 -> 15 KB, the rest level; + geomean 0.808. Per call (probe): callers of `Vector#each` 383 -> 135 B, of `SomSet#each` 382 -> 134, + of `contains` 414 -> 166, `find_set` 470 -> 222. Time, ten alternating AWFY processes each (a run or two + of Havlak gave no figure), medians: against the base Havlak 0.961, DeltaBlue 0.972, CD 1.010 (ranges + overlapping); in one tree with the switch off and on Havlak 0.934. + Checks: Util/held-block-matrix.rb's callees are methods with a scope now, and it catches a release + without the proof (the hold released when a callee fails to park: three rows wrong, a kept binding's + `yield` meeting a parked caller); a hold that is only a reuse flag is not caught there, since the + Proc's frame (the callee's scope) keeps it active until the park in that path. held-block, + passed-block, parked-scope, block-pass, block-given, nested-proc, jit-blockparam, light-entry, + hot-shapes, block-scope-reuse, super-light, loop-exit in the gate's six modes and + IR_HELD_METHOD_BLOCKS=0: 84 same. ruby/spec language/block, yield, break, send, def, core/proc, + core/binding, core/kernel/block_given: as on the base (send's one known `into`/`to` error on both). + IronRuby.Tests, Debug net10.0: 1,424 tests, none failed or flaky, as on the base. No AWFY benchmark fails. + For the gate: perf/literalcode and perf/havlakalloc were each measured without the other; with this + they compose (a method with a scope made at entry, parked, whose callers park too). The frame a held + Proc keeps until the park (its converter, the callee's scope) is dropped only by that scope's park. + - **perf/namedblock 4e87b11 977e047 (round forty-two, 2026-11-28) - a named block that a method only passes on stays reusable (gap 25)** - not gated. `def each(&b) = @items.each(&b)` (som.rb's `SomSet#each`, `has_some`, `get_one`; 5 of AWFY's 6 methods with a named block, about 320 of the standard library's From fbf5f4f05e52e11e4a48509262443d3d920f987b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:09:40 +0000 Subject: [PATCH 312/439] Ledger: perf/heldrfc's commit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf37xmrFN8GYq5A7V6G --- Util/perf/LEDGER.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 009df4383..7ba7bb7cc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2033,7 +2033,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed -- **perf/heldrfc 708f407 (round forty-three, 2026-11-28) - a method's scope holds its caller's literal +- **perf/heldrfc e8a74f4 (round forty-three, 2026-11-28) - a method's scope holds its caller's literal block until it is parked (gap 25)** - not gated. At fcbc67b (rounds seven and eight merged) Havlak allocated 1.79 GB an iteration again, method scopes 24% and Procs 13% as before perf/havlakalloc: round thirty-seven's perf/literalcode (`2eda4af`, "a body that evaluates a literal block on every call is not a From 5f600405db40b18475aa7438f43a9db9b5068ca5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:20:06 +0000 Subject: [PATCH 313/439] Ledger: round 8's gate, PASS; its entries marked gated Round 8 of round thirty-seven (the branch at fcbc67b, against master f81fc19) passed the gate with no fix needed: IronRuby.Tests 1,423 run, none failed; the matrices in eight modes (with the round's switches off, and with IR_LOOP_IVAR_WRITES=1), every DIFF explained as at round 7; a probe file for the round's changes as CRuby in every mode; ruby/spec's five suites with no unlisted failure; AWFY 12 at a geomean of 0.927 and 0.905; start-up 0.82-1.01 of master's. One finding is recorded: perf/literalcode takes some 4,100 methods out of light frames, which the census shows and the clock barely does (AWFY with the switch off against on, 1.003), and it bypassed perf/havlakalloc's bytes win; perf/nbody's heldrfc, in round 9, makes the two compose. Towers leans slower than master (alone, 1.045 and 1.035) and is left as a lead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 79 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 14 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 09f9bd71a..c4b503a54 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1654,7 +1654,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has image; best-of-10 wall -2 to -11% and -0 to -14%. Not taken: the JIT's re-parses of start-up methods (2-3 ms of `-e 1`), and Kernel#require's first-call body compile (~10 ms, 4 ms of it the first def-body transform's cold path), the next leads. - 2026-11-28, perf/requirecold (Landed, not gated): Kernel#require's first-call compile was + 2026-11-28, perf/requirecold (Landed, gated 2026-11-28 (round 8's gate entry)): Kernel#require's first-call compile was already gone. perf/bootparse precompiled the kernel_require.rb eval, and with it the def bodies in it (`def body: transform` 9.0 ms -> 0 in `-e 1`). What was left to parse at start-up were module_evals (FileUtils' 92, which `require "irb"` loads; Date::Format::Bag's 22) and the @@ -2025,6 +2025,57 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-28 for round 8 of round thirty-seven** (perf/crubydiff's seventh round, perf/literalcode, + perf/lightlambda with the jitcalls and jitresume designs and two typed-body rejections, perf/jitoptimism, + perf/r2kflag, perf/kwsplatlight, perf/kwbind, perf/requirecold, perf/jitreparse (rejected), perf/kstring, + perf/kinteger, perf/havlakalloc, perf/intivar (rejected), perf/loopivar (off)): the branch + `claude/happy-gauss-95wm2j` at fcbc67b against master f81fc19, Release net10.0, four cores: **PASS**, with + no fix needed and one finding (below). + The merge itself: only the ledger conflicted; perf/jitbody's branch carried back perf/jitisa's and + perf/jitblockparam's entries from before they were marked gated, and the unmarked copies and an orphaned + jitisa header were dropped (fcbc67b). RubyCallFlags: HasMatchSink 4096 and HasRuby2KeywordsSplat 8192 + (FlagsCount 14). ReflectionCache.Generated.cs is what ClassInitGenerator writes. No new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,423 tests, every one executed, none failed. + `gate-matrices.rb --all` in 8 modes (the six default ones; every round 8 switch that is on by default off + at once: IR_CALL_LINES, IR_JIT_OBJECT_OPS, IR_JIT_SCREEN_CALL, IR_JIT_SINK_BOXED, IR_KWREST_TAKE, + IR_LIGHT_LAMBDA, IR_LIGHT_STRAIGHT_LITERAL, IR_PLAIN_TO_S, IR_SCOPE_HELD_BLOCKS; and IR_LOOP_IVAR_WRITES=1, + which is off by default): 1,495 same, 136 baseline, 1 flaky, 16 DIFF, each explained: regexp-binary-ctype + prints what it printed at round 7, in every mode; string-race-matrix, compared over five runs of each tree + (rows not always ok 109 -> 87, lost writes 105 -> 0, no row failing only on the new build); + thread-backtrace's IR_LIGHT_FRAMES=0 run flaky (BASE's output twice alone), as at round 6. + A probe file for the round's behaviour changes and hot spots - a string instance_eval/class_eval sharing the + caller's `$~`, `$_` and `$1`; the line a call on a later line of a statement reports, by caller_locations + and by a backtrace; a fiber's own `$~`; a body that evaluates a literal block on every call (break, next, + an early return, a binding, a Proc kept past the method); a lambda literal in a branch (its return, kept + past the method, an arity error); to_i, empty? and ! of objects, hot, then the classes that must deopt; + `**rest` as the callee's own hash, a literal's mutated, `**h` keeping its default and + compare_by_identity; ruby2_keywords forwarding and into a Struct; Kernel#String and Integer(); a caller's + block held by its callee; a `while` loop writing ivars, with a frozen self and a raise mid-loop - prints + CRuby's output with the JIT on and off and with IR_LOOP_IVAR_WRITES=1; with the round's switches off only + the two line rows differ (IR_CALL_LINES=0 is the old lines). Master differs in 12 lines (the evals' and + the fiber's `$~`, the lines, `**h`'s default). + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against master (Src/StdLib, Util/bench, AWFY): light frames 91.7% -> 82.5% (1,256 up, 3,938 down); + against round 7, 108 up and 4,082 down, every one of them perf/literalcode's (with + IR_LIGHT_STRAIGHT_LITERAL=0, 172 up and none down; the census names them "body needs its scope after the + rewrite", the change having no refusal of its own). Method JIT 476 up and 3 down against master, the 3 + perf/jitoptimism's `x.call` refusals. + The finding: perf/literalcode is a trade the census shows and the clock barely does. AWFY 12, the switch + off against on: geomean 1.003; alone, five rounds in each order, on/off medians Richards 0.964, Havlak + 0.955, Towers 1.037. Kept: nothing is slower beyond the noise, and its own shapes gain 8-12% a call. It + also bypassed perf/havlakalloc - a method with a scope converts its caller's literal for good in the + scope's own InitializeRfc - so Havlak's bytes are back at 1.7 GB; perf/nbody's heldrfc (round 9) makes the + two compose. + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.927 and 0.905; Towers + 1.078 and 1.074, then alone, five rounds in each order, medians 1.045 (base first) and 1.035 (new first), + rounds from 0.94 to 1.16: under 5% in both, but leaning slower since round 7 (1.068 and 1.035 there); a + lead, not a block. Alone medians new/base: Havlak 0.894 / 0.931, DeltaBlue 0.937 / 0.987, Richards + 1.086 / 0.997 (0.995 over ten more rounds), CD 0.923 / 0.904. micro-table in both orders: `ivar_rw` 1.08 + and 1.11, then ab.rb alone, 12 rounds, 1.02 with the rounds overlapping: noise; no other line more than 5% + slower in both. + Start-up on the R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 583 -> 508 and + 596 -> 560, `gem --version` 630 -> 639 and 627 -> 619, `gem list` 1191 -> 975 and 1161 -> 1010, + `require "irb"` 1141 -> 982 and 1097 -> 969, irb 1+1 1261 -> 1155 and 1288 -> 1182: 0.82-1.01. - **Gate of 2026-11-28 for round 7 of round thirty-seven** (perf/crubydiff's fifth and sixth rounds, perf/literalsite, perf/endpark, perf/stage0 and perf/stagea with the block-cost harness and the procscope design, perf/primitive (rejected), perf/clrlookup, perf/bootparse, perf/permute, perf/parkedtuple @@ -2070,7 +2121,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 514 -> 475, `gem --version` 601 -> 591 and 584 -> 562, `gem list` 1043 -> 952 and 1040 -> 929, `require "irb"` 1100 -> 995 and 1080 -> 977, irb 1+1 1186 -> 1086 and 1167 -> 1075: 2-11% faster. -- **perf/jitoptimism (2026-11-28, census and timed, not gated) - what the screen let through and the compiler declined** +- **perf/jitoptimism (2026-11-28, census and timed, gated 2026-11-28 (round 8's gate entry)) - what the screen let through and the compiler declined** (switches `IR_JIT_OBJECT_OPS`, `IR_JIT_SCREEN_CALL`, `IR_JIT_SINK_BOXED`). Built on happy-gauss 348fde1 merged with perf/jitbody f1dc798. perf/jitisa left three new declines in app-shapes, methods `is_a?` used to keep out of the screen. Each was either taken by the compiler or refused up front: @@ -2115,8 +2166,8 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has basicobject/!, proc/call: no failures on either build. - IronRuby.Tests (Debug), all 1,403: PASSED. -- **perf/lightlambda (2026-11-28) - a lambda literal in a branch no longer keeps its method out of light frames** - not - gated. Chosen by the census of 50b07b5 + 8092170: LambdaDefinition, 73 methods, the next light-frame refusal after +- **perf/lightlambda (2026-11-28) - a lambda literal in a branch no longer keeps its method out of light frames** - + gated 2026-11-28 (round 8's gate entry). Chosen by the census of 50b07b5 + 8092170: LambdaDefinition, 73 methods, the next light-frame refusal after the `$~` family. - Why it had the scope: no reason but the filter's - `IsScopeFree` had no case for a LambdaDefinition (`->(x) { }`; `lambda { }` is a call with a literal block, light already). A lambda literal is a literal block made into a lambda @@ -2150,7 +2201,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/kwbind (/perf-step, 2026-11-28) - a `**rest` parameter is the call's own keyword hash, the declared keywords taken out in place** (gap 38; switch `IR_KWREST_TAKE`, on unless `=0`). Built on - 33818f7 (claude/happy-gauss-95wm2j) with d45083a0 merged. + 33818f7 (claude/happy-gauss-95wm2j) with d45083a0 merged. Gated 2026-11-28 (round 8's gate entry). - **Profile** (clock, Release, ns; CRuby in brackets): `def kopt(k: 0)` called `(k: 1)` 44 [30], `def kreq(k:)` 44 [31] - the method JIT takes both, and what is left is the call (`pos(1)` 40 [27]); so a declared-keywords-only callee already reads the call's pairs without paying for @@ -2187,7 +2238,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/kwsplatlight (/perf-frame, 2026-11-28) - `f(k: v, **h)` and `f(**a, **b)` in light frames; a Struct stores a ruby2_keywords Hash as given** (switch `IR_LIGHT_KEYWORD_SPLAT`, which already covered the lone `f(**h)`). Built on 33818f7 (claude/happy-gauss-95wm2j) with 78a731ca merged; - RubyCallFlags.HasRuby2KeywordsSplat moved to 8192 (FlagsCount 14) beside round 7's HasMatchSink. + RubyCallFlags.HasRuby2KeywordsSplat moved to 8192 (FlagsCount 14) beside round 7's HasMatchSink. Gated 2026-11-28 (round 8's gate entry). - **Census** (`Util/perf/census.rb -d`, Src/StdLib and Util/bench, 29,102 methods): light frames 27,997 -> 28,017 (+20), every one refused before for `KeywordSplatMerge` (Pathname#glob, File.binwrite, Exception.__detailed__, mkmf's try_*, optparse's getopts, Prism's desugar @@ -2227,7 +2278,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/r2kflag (2026-11-28) - a ruby2_keywords hash stays positional at a call with an explicit `**`, and at a library method's own call; `yield(*args)` makes it keywords; `**h` passes a dup** - (correctness, no switch). Built on aa82bf28 (claude/perf-lsite, which has f67ac44). + (correctness, no switch). Built on aa82bf28 (claude/perf-lsite, which has f67ac44). Gated 2026-11-28 (round 8's gate entry). - **What CRuby 4.0 does.** A marked hash ending a splatted list is made keywords only at a splat in Ruby source with no `**` (vm_caller_setup_arg_splat, a call without kw_splat): `g(*a, **{})`, `g(*a, **nil)`, `super(*a, **{})` keep it positional, the same object with its @@ -2267,7 +2318,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has nothing to gain; only a #to_proc that changes `a` could tell. - **perf/kinteger (2026-11-28, on 33818f7 + 51f5637) - `Kernel#String` asks for #to_str as - rb_check_funcall does; `Integer("1234")` rejected, nothing to win** - not gated. + rb_check_funcall does; `Integer("1234")` rejected, nothing to win** - gated 2026-11-28 (round 8's gate entry). - Part 1 (correctness, from perf/kstring's leftovers): `__ir_check_to_str__` calls a private or protected #to_str, tries a #method_missing of the object's own when there is none (check_funcall_missing), takes any NoMethodError from it as "no conversion" unless the @@ -2287,7 +2338,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `Array()` 68 against 40). - **perf/kstring (/perf-step, 2026-11-28, on 3faf3dc) - `Kernel#String` converts a plain object - by its #to_s from C# (`__ir_plain_to_s__`, `IR_PLAIN_TO_S`)** - clock only, not gated. For a + by its #to_s from C# (`__ir_plain_to_s__`, `IR_PLAIN_TO_S`)** - clock only, gated 2026-11-28 (round 8's gate entry). For a class with no #to_str (any visibility), the built-in respond_to?, respond_to_missing? and method_missing and a public #to_s - checked per class against the global method version - #to_s is called through a call site; anything else goes to `__ir_string__` as before. @@ -2300,7 +2351,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - A private #to_str and a #method_missing for to_str, left at first, are called since perf/kinteger's first part, as MRI's rb_check_funcall calls them. -- **perf/loopivar (/perf-step, 2026-11-28, not gated) - an outlined `while' loop may write self's +- **perf/loopivar (/perf-step, 2026-11-28, gated 2026-11-28 (round 8's gate entry)) - an outlined `while' loop may write self's instance variables: OFF by default (`IR_LOOP_IVAR_WRITES=1`)**, on 4b928db (33818f7 merged with 0bf3598). The OSR loop compiler bailed on `@x = v' ("instance variable write in an outlined loop") and the method JIT declines a method whose loop writes one ("a deopt after an effect"). @@ -2404,7 +2455,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `require "irb"` 1029 -> 1005 and 984 -> 992, irb 1+1 1133 -> 1071 and 1065 -> 1066: level. - **perf/literalcode (round thirty-seven, 2026-11-28) - a body that evaluates a literal block on every call is not made a - light frame (gap 13)** - time, not gated. Asked to find the compiled code around a literal's instantiation (the 16-20 ns + light frame (gap 13)** - time, gated 2026-11-28 (round 8's gate entry). Asked to find the compiled code around a literal's instantiation (the 16-20 ns perf/stagea left unattributed), the round dumped `e1`'s expression tree and its JIT code. The call with a literal in a light frame does: the scope made on demand inside the literal's instantiation (`LightScopeInLoop` over `TakeParkedScope` and `ReuseParkedScopeLazy`, the register locals copied into a tuple first), `InitializeBlock`, a try/catch for `EvalUnwinder` @@ -2795,7 +2846,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has `IR_LOOP_NEAR=0`, that switch's own rows). ruby/spec language/constants: no failures on either build. - **perf/havlakalloc 56526b1 c8010fb (round forty-one, 2026-11-28) - a light frame's scope holds its - block until it is parked, not for good (gap 25)** - not gated. Havlak allocated 1.77 GB per iteration; + block until it is parked, not for good (gap 25)** - gated 2026-11-28 (round 8's gate entry). Havlak allocated 1.77 GB per iteration; the allocation-tick probe gave method scopes 25%, `Object[]` 16%, Procs 14.5%, Range 6%, BlockParams 6%. Bytes per call of its hot helpers, method by method: a caller passing a literal to som.rb's `Vector#each` 374 B (its method scope, its Proc, a BlockParam, the Range), `SomSet#contains` 406, @@ -3406,7 +3457,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has (60) pass in five plain runs on base and five on new. - **perf/requirecold (2026-11-28) - module_evals in the startup library; eval texts that name the tree (gap 26)** - - not gated. Base 50b07b5 (claude/happy-gauss-95wm2j) merged with 516fb7c (perf/bootparse). + - gated 2026-11-28 (round 8's gate entry). Base 50b07b5 (claude/happy-gauss-95wm2j) merged with 516fb7c (perf/bootparse). The brief: Kernel#require's body, compiled at its first call (~10 ms on the R2R host before perf/bootparse, ~4 ms of it the cold path of the first def-body transform). Measured on the base (IR_PHASE_TIMES, R2R host): that compile is gone. The kernel_require.rb eval comes from the library @@ -3988,7 +4039,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope From 51feb30c4c9618571aa5b6af08d95ff57aedd843 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:16:37 +0000 Subject: [PATCH 314/439] private/protected on an alias keep it an alias `ruby -w -e 'require "ostruct"; OpenStruct.new(a: 1)'` warned "ostruct.rb:481: warning: method redefined; discarding old table!" in IronRuby, and CRuby 4.0 is silent. ostruct.rb does `alias table! table; protected :table!` and later aliases every public method to its bang name, table! included. CRuby changes the visibility of the alias in place, so the entry is still an alias (VM_METHOD_TYPE_ALIAS), and rb_method_entry_make does not warn when an alias, or a method that has been aliased, is replaced. Module#private/protected/public on a method a module defines itself copied the entry and dropped what made it an alias: AliasOwner, OriginalName and the IsAliased mark. Redefining the name then warned, and #original_name and the UnboundMethod#inspect description lost the original name (`alias b a; private :b` gave :b where CRuby gives :a). SetVisibilityNoEventNoLock now carries the three over to the copy of an own entry. Checked with AliasVisibilityKeepsAlias1 (output from CRuby 4.0), probes of alias/visibility/redefinition orders side by side with CRuby, IronRuby.Tests, the language alias/def specs and the Module#alias_method/private/protected/public/define_method/attr_reader/ module_function, Warning, UnboundMethod, Method#owner/original_name and OpenStruct specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 31 +++++++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 12 ++++++++- 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index cf0538d73..8fbb65b53 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -893,6 +893,7 @@ public Tests(Driver/*!*/ driver) { DefineMethodVisibility1, DefineMethodVisibility2B, AliasedMethodVisibility1, + AliasVisibilityKeepsAlias1, AttributeAccessorsVisibility1, AttributeAccessorsVisibility2, ModuleFunctionVisibility1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 661c5c011..610b56df1 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1403,6 +1403,37 @@ p M.singleton_methods.sort "); } + /// + /// private/protected change the visibility of an alias in place, as MRI does: the entry stays the alias + /// (#original_name), and the method it aliased stays aliased, so neither name warns when it is redefined + /// or aliased again (ostruct.rb's alias_method of table! warned under -w). + /// + public void AliasVisibilityKeepsAlias1() { + TestOutput(@" +$w = [] +def Warning.warn(m, **) = $w << m[/:(\d+: warning: .*)/, 1] +class D + def a; end + alias b a + private :b + p instance_method(:b).original_name, instance_method(:b).owner + def u; end + alias v u + private :u + def u; end + def t; end + alias t! t + protected :t! + alias_method ""t!"", :t +end +p $w +", @" +:a +D +[] +"); + } + /// /// alias, alias_method ignore the current scope visibility flags and copy methods with their visibility unmodified. /// diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 3c3d0cd25..0ad50f8d5 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -2485,7 +2485,17 @@ public void SetVisibilityNoEventNoLock(RubyContext/*!*/ callerContext, string/*! // CLR members: Detaches the member from its underlying type (by creating a copy). // MRI changes the visibility of an own entry in place: not a new entry, so not "redefining". Mutate(); - SetMethodNoMutateNoEventNoLock(callerContext, name, redefined.Copy((RubyMemberFlags)visibility, this), !own); + var copy = redefined.Copy((RubyMemberFlags)visibility, this); + if (own) { + // The entry MRI changes in place stays the alias it was, or the method that was aliased: + // #owner and #original_name keep reporting the alias, and redefining either name later + // is not warned about (`alias table! table; protected :table!; alias_method "table!", :table' + // in ostruct.rb warned under -w). + copy.AliasOwner = existing.AliasOwner; + copy.OriginalName = existing.OriginalName; + copy.IsAliased = existing.IsAliased; + } + SetMethodNoMutateNoEventNoLock(callerContext, name, copy, !own); } else { SetMethodNoEventNoLock(callerContext, name, new SuperForwarderInfo((RubyMemberFlags)visibility, method.DeclaringModule, name)); } From 0a01d30cda400cfd0ed847cf3e526a42bd260543 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:16:37 +0000 Subject: [PATCH 315/439] An alias statement marks its own line `alias m n` that redefines m warns "method redefined; discarding old m" at the alias's line in CRuby. AliasStatement overrode Transform without the sequence point and line marker every other statement gets, so unless it was the last statement of its body (which goes through TransformResult) the warning named the line of the statement before it. It now enters and leaves its line as Expression.Transform does, the way UndefineStatement does; TransformReadCore builds the bare call, since TransformRead/TransformResult add the marker themselves. Checked with AliasRedefinitionWarningLine1 (output from CRuby 4.0; in a class_eval block, which tracks its line when compiled - a class body compiled with -X:NoAdaptiveCompilation, as IronRuby.Tests run, has no line of its own in IronRuby, and is left for another commit), interpreted and compiled, IronRuby.Tests and the same specs as the previous commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/AliasTests.cs | 21 +++++++++++++++++++ .../Compiler/Ast/Statements/AliasStatement.cs | 12 +++++++++-- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 8fbb65b53..b8ca86892 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -866,6 +866,7 @@ public Tests(Driver/*!*/ driver) { UnqualifiedConstants2, AliasMethodLookup1, + AliasRedefinitionWarningLine1, AliasMethodLookup3, UndefMethodLookup1, diff --git a/Src/IronRuby.Tests/Runtime/AliasTests.cs b/Src/IronRuby.Tests/Runtime/AliasTests.cs index 54ffba2ef..4a1b4f4e0 100644 --- a/Src/IronRuby.Tests/Runtime/AliasTests.cs +++ b/Src/IronRuby.Tests/Runtime/AliasTests.cs @@ -136,6 +136,27 @@ p String.method(:class_eval) == String.method(:module_eval), String.method(:clas "); } + /// + /// An alias statement marks its own line: the method redefinition warning it gives is reported there, + /// not at the line of the statement before it. + /// + public void AliasRedefinitionWarningLine1() { + TestOutput(@" +$w = [] +def Warning.warn(m, **) = $w << m.lines.first[/:(\d+: warning: .*)/, 1] +B = Class.new +B.class_eval do + def m; end + def n; end + alias m n + def o; end +end +p $w +", @" +[""8: warning: method redefined; discarding old m""] +", 0, 1); + } + /// /// Alias (unlike undef) looks up the method in Object. /// diff --git a/Src/Ruby/Compiler/Ast/Statements/AliasStatement.cs b/Src/Ruby/Compiler/Ast/Statements/AliasStatement.cs index d202f1076..94e797239 100644 --- a/Src/Ruby/Compiler/Ast/Statements/AliasStatement.cs +++ b/Src/Ruby/Compiler/Ast/Statements/AliasStatement.cs @@ -35,13 +35,21 @@ public AliasStatement(bool isMethodAlias, ConstructedSymbol newName, Constructed _isMethodAlias = isMethodAlias; } - internal override MSA.Expression/*!*/ Transform(AstGenerator/*!*/ gen) { + private MSA.Expression/*!*/ TransformAlias(AstGenerator/*!*/ gen) { return (_isMethodAlias ? Methods.AliasMethod : Methods.AliasGlobalVariable). OpCall(gen.CurrentScopeVariable, _newName.Transform(gen), _oldName.Transform(gen)); } + // A statement of its own, `alias' marks its line as every other statement does: the "method + // redefined; discarding old foo" warning it gives under -w is reported at that line, which was + // the line of whatever statement ran before it. + internal override MSA.Expression/*!*/ Transform(AstGenerator/*!*/ gen) { + EnterLine(gen); + return LeaveLine(gen, gen.AddDebugInfo(TransformAlias(gen), Location)); + } + internal override MSA.Expression/*!*/ TransformReadCore(AstGenerator/*!*/ gen) { - return Ast.Block(Transform(gen), AstUtils.Constant(null)); + return Ast.Block(TransformAlias(gen), AstUtils.Constant(null)); } } } From 14d608b408f5d62dda241726aec4d1a8505d81a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:16:37 +0000 Subject: [PATCH 316/439] Method redefinition warning reaches Warning.warn as one message CRuby 4.0 hands Warning.warn a single message for a method redefinition: "file:5: warning: method redefined; discarding old m\n file:4: warning: previous definition of m was here\n". IronRuby called it twice, one line each, so a hook that records or filters warnings one call at a time saw a lone "previous definition" warning. (The constant case, "already initialized constant" and its "previous definition", is two calls in CRuby too, and stays so.) RubyContext.ReportMethodRedefinitionWarning formats both lines - the first at the new definition, or at the running line when that is not known, as before - and dispatches them together; RubyModule's WarnMethodRedefinition uses it. A host's runtime warning count (RuntimeErrorSink.WarningCount, which IronRuby.Tests check) still counts the warning when the new definition's place is not known, as it did when that line went through the sink. Checked with MethodRedefinitionWarningMessage1 (output from CRuby 4.0), probes with and without a Warning.warn hook and with $stderr reassigned, IronRuby.Tests, and the same specs as the previous commits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 18 ++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 13 +++------- Src/Ruby/Runtime/RubyContext.cs | 29 +++++++++++++++++++++++ Src/Ruby/Runtime/RuntimeErrorSink.cs | 8 +++++++ 5 files changed, 59 insertions(+), 10 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index b8ca86892..f9a3e31a2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -895,6 +895,7 @@ public Tests(Driver/*!*/ driver) { DefineMethodVisibility2B, AliasedMethodVisibility1, AliasVisibilityKeepsAlias1, + MethodRedefinitionWarningMessage1, AttributeAccessorsVisibility1, AttributeAccessorsVisibility2, ModuleFunctionVisibility1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 610b56df1..0bd1ee103 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1434,6 +1434,24 @@ alias t! t "); } + /// + /// "method redefined; discarding old m" and "previous definition of m was here" reach Warning.warn + /// as one message, as in MRI. + /// + public void MethodRedefinitionWarningMessage1() { + TestOutput(@" +$n = [] +def Warning.warn(m, **) = $n << m.lines.map { |l| l[/:(\d+: warning: .*)/, 1] } +class B + def m; end + def m; end +end +p $n +", @" +[[""6: warning: method redefined; discarding old m"", ""5: warning: previous definition of m was here""]] +"); + } + /// /// alias, alias_method ignore the current scope visibility flags and copy methods with their visibility unmodified. /// diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 0ad50f8d5..4ae89c574 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -2457,16 +2457,9 @@ public void WarnMethodRedefinition(string/*!*/ name, string sourcePath = null, i return; } - if (sourcePath != null && sourceLine > 0) { - _context.ReportWarningAt(sourcePath, sourceLine, "method redefined; discarding old " + name); - } else { - _context.ReportWarning("method redefined; discarding old " + name, true); - } - - // a C# method, as a C one, has no previous definition to point at - if (file != null) { - _context.ReportWarningAt(file, line, "previous definition of " + name + " was here"); - } + // a C# method, as a C one, has no previous definition to point at (file is null) + _context.ReportMethodRedefinitionWarning("method redefined; discarding old " + name, sourcePath, sourceLine, + "previous definition of " + name + " was here", file, line); } // Module#module_function/private/protected/public: diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 9bb664dc1..71da959f2 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -4052,6 +4052,35 @@ public void ReportWarningAt(string/*!*/ path, int line, string/*!*/ message) { } } + /// + /// MRI's rb_method_entry_make under $VERBOSE: "method redefined; discarding old foo" at + /// : (the running line when that is not known) + /// and, when the old definition was written in Ruby, "previous definition of foo was here" at + /// . MRI's Warning.warn gets the two lines as one message, so a + /// hook that takes one line per warning sees them together. + /// + public void ReportMethodRedefinitionWarning(string/*!*/ message, string path, int line, + string/*!*/ previousMessage, string previousPath, int previousLine) { + + if (!(Verbose is bool verbose && verbose)) { + return; + } + if (path == null || line <= 0) { + // the runtime warning count a host reads (ErrorCounter.WarningCount) has always counted this one, + // which went through the sink, and not one written at a known definition + _runtimeErrorSink.CountWarning(); + if (!TryGetCurrentSourceLocation(out path, out line)) { + path = null; + line = 0; + } + } + string text = FormatWarning(message, path, line); + if (previousPath != null) { + text += FormatWarning(previousMessage, previousPath, previousLine); + } + DispatchWarning(MutableString.Create(text, RubyEncoding.UTF8), null); + } + #region Warning categories, chilled string literals /// diff --git a/Src/Ruby/Runtime/RuntimeErrorSink.cs b/Src/Ruby/Runtime/RuntimeErrorSink.cs index c04fc353a..ddb043e39 100644 --- a/Src/Ruby/Runtime/RuntimeErrorSink.cs +++ b/Src/Ruby/Runtime/RuntimeErrorSink.cs @@ -34,6 +34,14 @@ internal RuntimeErrorSink(RubyContext/*!*/ context) { _context = context; } + /// + /// Counts a warning that was written without going through , as one that did would have been + /// (RubyContext.ReportMethodRedefinitionWarning). + /// + internal void CountWarning() { + CountError(Severity.Warning); + } + private CallSite> _WriteSite; internal void WriteMessage(MutableString/*!*/ message) { From 4b2b9dcd18a7974e0f74be07a629e01267fbc1e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:41:34 +0000 Subject: [PATCH 317/439] Compiled class and module bodies keep their frame in backtraces A class or module body is a lambda of its own (ModuleDefinition) and a frame of its own in CRuby: caller(0) inside `class A` inside `module M` is "", "", "
". Compiled - with -X:NoAdaptiveCompilation, or a CompilationThreshold of 0 as IronRuby.Tests run - the frame was gone: caller(0) gave only "in '
'" at the line of the outermost `class' keyword, and so did every backtrace raised in the body and the line of every warning given from it ("already initialized constant", "method redefined"). The expression compiler compiles an Invoke of a lambda expression into the code it is written in, so the body has no CLR method of its own; it does push its frame record (CompiledFrameExpression), which the stack walk matches with CLR frames by name and passed over. Calling the body through a delegate instead gives it a CLR frame, but makes a delegate of a DynamicMethod on every run of the body - a loop that reopens a class went 3.4x slower - so the walk is taught instead: TakeCompiledFrameLine collects the module body records between the record it matches and the one matched before (bodies compiled into that CLR frame, innermost first), and AddBacktrace reports them, with their own lines, before the frame itself. The frame adding is moved to AddFrame so they take the deferred library frames, caller(n)'s skip and the frame limit as any frame does. Checked with Backtrace_CompiledModuleBody1 (output from CRuby 4.0: nested bodies, a method and a block called from a body, class << self, an exception's backtrace), a probe of those plus Class.new.class_eval, eval and a body in a block run interpreted, with -X:NoAdaptiveCompilation and with -X:CompilationThreshold 0 (the same as CRuby in all three, the base build only interpreted), IronRuby.Tests, the caller/backtrace/warning/TracePoint/class/module specs, spec/language run with -X:NoAdaptiveCompilation (no change from the base build), and the differential matrices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 33 ++++++ Src/Ruby/Runtime/RubyStackTraceBuilder.cs | 103 ++++++++++++------ 3 files changed, 106 insertions(+), 31 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f9a3e31a2..60562d978 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1065,6 +1065,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_SendHidden1, Backtrace_CallLine1, Backtrace_InterpolatedLocalLine1, + Backtrace_CompiledModuleBody1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index 512a8e5a7..29528dae9 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -502,6 +502,39 @@ p q(1) "); } + /// + /// A class or module body is a frame of its own when it is compiled too, as IronRuby.Tests compile + /// everything: the expression compiler compiles its call into the code around it, and the backtrace + /// reports its frame record there. It used to be left out, its lines going to the frame outside it. + /// + public void Backtrace_CompiledModuleBody1() { + TestOutput(@" +def show(t) = p(t.map { |l| l[/:(\d+:in .*)/, 1] }) +def m1 = caller(0) +module M + class A + show caller(0) + show m1 + class << self + show caller(0) + end + begin + raise ""x"" + rescue => e + show e.backtrace + end + [1].each { show caller(0) } + end +end +", @" +[""6:in ''"", ""5:in ''"", ""4:in '
'""] +[""3:in 'Object#m1'"", ""7:in ''"", ""5:in ''"", ""4:in '
'""] +[""9:in 'singleton class'"", ""8:in ''"", ""5:in ''"", ""4:in '
'""] +[""12:in ''"", ""5:in ''"", ""4:in '
'""] +[""16:in 'block in '"", ""16:in 'Array#each'"", ""16:in ''"", ""5:in ''"", ""4:in '
'""] +"); + } + /// /// The conversion of an interpolated local variable on a later line of a string (a heredoc's) reports that line, as /// MRI's does: the variable's node carries its declaration's span, so the part's line comes from StringConstructor.PartLines. diff --git a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs index 33697f760..7f9e798bf 100644 --- a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs +++ b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs @@ -37,6 +37,9 @@ public sealed class RubyStackTraceBuilder { // The lines of the compiled frames (see CompiledFrameExpression), outermost first; a compiled frame of the trace is // matched with the innermost one of its name not matched yet. private Precompiled.PrecompiledFrames.Frame[] _compiledFrames; + + // The compiled class and module bodies the frame the walk is at runs in itself (see TakeCompiledFrameLine). + private List _inlinedBodies; private int _compiledFrameIndex; // The lines of the interpreted frames that run a loop the interpreter has compiled, by depth (see PrecompiledFrames.SetLoopLine). private Precompiled.PrecompiledFrames.LoopLineInfo[] _loopLines; @@ -507,6 +510,15 @@ private void SetCompiledFrames(Precompiled.PrecompiledFrames.Frame[] frames) { private int TakeCompiledFrameLine(string/*!*/ encodedName) { for (int i = _compiledFrameIndex; i >= 0; i--) { if (String.Equals(_compiledFrames[i].Name, encodedName, StringComparison.Ordinal)) { + // A class or module body is called where it is written, and the expression compiler compiles that call + // into the code around it: the body's frame record has no CLR frame of its own. The records of such + // bodies between this frame's and the frame matched last are this frame's, innermost first (a record + // left by any other kind of frame is not one this walk has a frame for). + for (int j = _compiledFrameIndex; j > i; j--) { + if (IsModuleBodyName(_compiledFrames[j].Name)) { + (_inlinedBodies ??= new List()).Add(_compiledFrames[j]); + } + } _compiledFrameIndex = i - 1; _previousInEnsure = _compiledFrames[i].InEnsure; return _compiledFrames[i].Line; @@ -740,47 +752,76 @@ private void AddBacktrace(IEnumerable stackTrace, int skipFrames, bo continue; } - if (!_keepInternalFrames && IsInternalFrameFile(file)) { - // Above the first frame reported, the frames it drops still count for caller(n): a method of the prelude - // skips its own frame that way (Kernel#caller_locations calls caller(n + 1)), and Thread#backtrace, which - // calls caller_locations, dropped that frame - so its caller's went instead. - int dropped = AddInternalFrame(methodName); - if (_trace.Count == 0 && !skippedAny) { - skipFrames = Math.Max(0, skipFrames - dropped); + // the bodies of the classes and modules compiled into this frame (see TakeCompiledFrameLine) are frames + // of their own, inside it + if (_inlinedBodies != null && _inlinedBodies.Count > 0) { + bool full = false; + foreach (var body in _inlinedBodies) { + string bodyName = body.Name, bodyFile = null; + int bodyLine = body.Line; + if (TryParseRubyMethodName(ref bodyName, ref bodyFile, ref bodyLine)) { + Precompiled.PrecompiledCode.RebaseFrameFile(_previousMethod, ref bodyFile); + if (AddFrame(bodyFile, bodyLine, bodyName, false, ref skipFrames, ref skippedAny)) { + full = true; + break; + } + } } - continue; - } - - foreach (var deferred in _deferredMethodNames) { - if (skipFrames == 0) { - _trace.Add(CreateFrame(FormatFrame(file, line, deferred))); - } else { - skipFrames--; - skippedAny = true; + _inlinedBodies.Clear(); + if (full) { + break; } - // a library method's frame, reported where its caller is - _rubyFrameEnd = _trace.Count; } - _deferredMethodNames.Clear(); - _libraryRun = 0; - if (skipFrames == 0) { - _trace.Add(CreateFrame(FormatFrame(file, line, methodName))); - } else { - skipFrames--; - skippedAny = true; - } - if (!isClrFrame) { - _rubyFrameEnd = _trace.Count; - } - if (_rubyFrameEnd >= _maxFrames) { - // the first _maxFrames frames are what the whole walk would have reported first + if (AddFrame(file, line, methodName, isClrFrame, ref skipFrames, ref skippedAny)) { break; } } } } + /// + /// Adds a frame the walk went by, after the library frames deferred to it, unless it is one of the internal frames left + /// out. True when the trace has all the frames it was asked for. + /// + private bool AddFrame(string file, int line, string methodName, bool isClrFrame, ref int skipFrames, ref bool skippedAny) { + if (!_keepInternalFrames && IsInternalFrameFile(file)) { + // Above the first frame reported, the frames it drops still count for caller(n): a method of the prelude + // skips its own frame that way (Kernel#caller_locations calls caller(n + 1)), and Thread#backtrace, which + // calls caller_locations, dropped that frame - so its caller's went instead. + int dropped = AddInternalFrame(methodName); + if (_trace.Count == 0 && !skippedAny) { + skipFrames = Math.Max(0, skipFrames - dropped); + } + return false; + } + + foreach (var deferred in _deferredMethodNames) { + if (skipFrames == 0) { + _trace.Add(CreateFrame(FormatFrame(file, line, deferred))); + } else { + skipFrames--; + skippedAny = true; + } + // a library method's frame, reported where its caller is + _rubyFrameEnd = _trace.Count; + } + _deferredMethodNames.Clear(); + _libraryRun = 0; + + if (skipFrames == 0) { + _trace.Add(CreateFrame(FormatFrame(file, line, methodName))); + } else { + skipFrames--; + skippedAny = true; + } + if (!isClrFrame) { + _rubyFrameEnd = _trace.Count; + } + // the first _maxFrames frames are what the whole walk would have reported first + return _rubyFrameEnd >= _maxFrames; + } + /// /// On .NET 9 and later (its managed exception handling) an exception thrown from a catch or finally block has the method /// of the block twice in its own trace: the block - a funclet - and the method's body, which called it. A compiled Ruby From 6e6ba04a8579c7d094591609092c33bb3dbcbf71 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:41:34 +0000 Subject: [PATCH 318/439] A hosted top-level alias warns once A hosted runtime keeps the top level's methods in main's singleton class as well as in Object, and RubyOps.AliasMethod makes an alias in both. Each AddMethodAlias warned, so `alias m n` redefining m gave "method redefined; discarding old m" twice under -w, where CRuby has one module and one warning. The mirror's alias no longer warns when the owner's alias is made too (AddMethodAlias(newName, oldName, warn)). Checked with AliasTopLevelWarnsOnce1 (output from CRuby 4.0; IronRuby.Tests run hosted), IronRuby.Tests and the differential matrices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/AliasTests.cs | 18 ++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 10 +++++++++- Src/Ruby/Runtime/RubyOps.cs | 3 ++- 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 60562d978..e5db15f92 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -867,6 +867,7 @@ public Tests(Driver/*!*/ driver) { AliasMethodLookup1, AliasRedefinitionWarningLine1, + AliasTopLevelWarnsOnce1, AliasMethodLookup3, UndefMethodLookup1, diff --git a/Src/IronRuby.Tests/Runtime/AliasTests.cs b/Src/IronRuby.Tests/Runtime/AliasTests.cs index 4a1b4f4e0..e343437bd 100644 --- a/Src/IronRuby.Tests/Runtime/AliasTests.cs +++ b/Src/IronRuby.Tests/Runtime/AliasTests.cs @@ -157,6 +157,24 @@ alias m n ", 0, 1); } + /// + /// A top-level alias that redefines a method warns once, though a hosted top level makes it in two + /// modules, main's singleton class and Object (RubyOps.AliasMethod). + /// + public void AliasTopLevelWarnsOnce1() { + TestOutput(@" +$w = [] +def Warning.warn(m, **) = $w << m.lines.first[/:(\d+: warning: .*)/, 1] +def m; end +def n; end +alias m n +def o; end +p $w +", @" +[""6: warning: method redefined; discarding old m""] +", 0, 1); + } + /// /// Alias (unlike undef) looks up the method in Object. /// diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 4ae89c574..90f27a14b 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -2342,9 +2342,17 @@ public void ForEachInstanceMethod(bool inherited, Func + /// False for the second of two modules one `alias' is made in (a hosted top level's, RubyOps.AliasMethod): MRI has + /// one module there, and one warning. + /// + public void AddMethodAlias(string/*!*/ newName, string/*!*/ oldName, bool warn) { // `alias foo foo' discards nothing: the entry stays the same body (and, aliased, `def foo' // after it does not warn either) - if (newName != oldName) { + if (warn && newName != oldName) { WarnMethodRedefinition(newName); } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index aaaf0ba0d..53c40ca8b 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -1813,7 +1813,8 @@ public static void AliasMethod(RubyScope/*!*/ scope, string/*!*/ newName, string if (mirror != null) { bool inOwner = owner.ResolveMethod(oldName, VisibilityContext.AllVisible).Found; if (!inOwner || mirror.ResolveMethod(oldName, VisibilityContext.AllVisible).Found) { - mirror.AddMethodAlias(newName, oldName); + // the warning, if any, is the owner's alone when the owner has the alias too + mirror.AddMethodAlias(newName, oldName, !inOwner); } if (!inOwner) { return; From 419f23e0bf013362e15921e5625c18dfff952e7f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:42:16 +0000 Subject: [PATCH 319/439] thread-backtrace-matrix: wait until main is blocked before reading it Row 3 ("main, seen by child") raced: the child could read main.backtrace while main was still on the line before q3.pop, and round 9's gate saw that in 2 of 3 runs under -X:NoJITCalls. The child now waits with `Thread.pass until main.status == "sleep"`, so the row is always the backtrace of main blocked in Thread::Queue#pop. CRuby 4.0's output is the same but for the two comment lines; IronRuby matched it in 9 runs out of 9, default, -X:NoJITCalls and -X:NoAdaptiveCompilation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Util/thread-backtrace-matrix.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Util/thread-backtrace-matrix.rb b/Util/thread-backtrace-matrix.rb index ff8b064bf..9805bb1e6 100644 --- a/Util/thread-backtrace-matrix.rb +++ b/Util/thread-backtrace-matrix.rb @@ -84,7 +84,9 @@ def deep1(q); deep2(q); end # 3. The main thread, read from a child. q3 = Queue.new main = Thread.current -t3 = Thread.new { q3 << main.backtrace } +# The child waits until main is blocked in q3.pop: read while main was still on the line +# before, the backtrace raced (round 9's gate saw it in 2 of 3 runs under -X:NoJITCalls). +t3 = Thread.new { Thread.pass until main.status == "sleep"; q3 << main.backtrace } puts "main, seen by child: #{q3.pop.inspect}" t3.join From 666444cc8e537a3901585c046840ed46715f9a67 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:47:54 +0000 Subject: [PATCH 320/439] Method#inspect and UnboundMethod#inspect are BINARY when ASCII CRuby 4.0's method_inspect builds its description as a BINARY string: method(:p).inspect.encoding is ASCII-8BIT, and so is String.instance_method(:size).inspect. A part that is not ASCII takes it over to that part's encoding: a method named in UTF-8, or the inspected receiver of a singleton method that is not ASCII, gives UTF-8. IronRuby gave UTF-8 for all of them (the identifier encoding). UnboundMethod.ToS, which both use, now gives the result BINARY when it is ASCII only; one that is not stays UTF-8. This follows the # descriptions of the earlier commit. Checked with MethodInspect_Encoding1 (output from CRuby 4.0, the same under LANG=C and C.UTF-8), a probe with a non-ASCII method name, receiver, alias and file path side by side with CRuby, and the method/unboundmethod specs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 23 +++++++++++++++++++++++ Src/Libraries/Builtins/UnboundMethod.cs | 6 ++++++ 3 files changed, 30 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e5db15f92..3ca9b6075 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1277,6 +1277,7 @@ public Tests(Driver/*!*/ driver) { Methods1, MethodDef1, MethodInspect_LibraryParameters1, + MethodInspect_Encoding1, MethodArity_CoreMethods1, MethodArity_LibraryArguments1, MethodArity_PreludeMethods1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 0bd1ee103..31262546c 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1695,6 +1695,29 @@ foo i "); } + /// + /// Method#inspect and UnboundMethod#inspect are BINARY strings in MRI (method_inspect), unless a part of + /// them is not ASCII: a method named in UTF-8 gives UTF-8. + /// + public void MethodInspect_Encoding1() { + TestOutput(@" +class Foo; def a(x, y = 1, *r, k:, &b); end; def é; end; end +o = Object.new +def o.s; end +p method(:p).inspect.encoding, Foo.new.method(:a).inspect.encoding, Foo.instance_method(:a).inspect.encoding +p Foo.new.method(:é).inspect.encoding, o.method(:s).inspect.encoding +p 1.method(:+).inspect.encoding, [].method(:each).unbind.inspect.encoding +", @" +# +# +# +# +# +# +# +"); + } + /// /// Method#inspect shows the parameter list for library methods and attribute accessors /// too, as MRI does ("_" for a required parameter with no name); a rule-generator method diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index fdf08ea59..62edaa88c 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -282,6 +282,12 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet } result.Append('>'); + + // MRI's method_inspect builds a BINARY string, which a part that is not ASCII - a name, a path, the + // inspected receiver of a singleton method - takes over to its own encoding + if (result.IsAscii()) { + result.ForceEncoding(RubyEncoding.Binary); + } return result; } From bd7342a229ee5fc6d015d05ed8bd9a20c9c01ef6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:50:42 +0000 Subject: [PATCH 321/439] Rational and Complex strings are US-ASCII CRuby 4.0 makes Rational#to_s/#inspect and Complex#to_s/#inspect with rb_usascii_str_new (nurat_to_s, f_format): Rational(1, 2).to_s.encoding is US-ASCII. IronRuby's are interpolations in the prelude's rational.rb and complex.rb, UTF-8 sources, so they were UTF-8. The two files are now US-ASCII sources (`# encoding: us-ascii`): their literals and interpolations of the ASCII parts are US-ASCII with no work at run time. The exception messages they raise go from UTF-8 to US-ASCII; CRuby's (rb_raise) are BINARY, which neither was. Neither file has a character that is not ASCII. Checked with Rational_StringEncoding1 (output from CRuby 4.0), the encodings of to_s/inspect of each shape side by side with CRuby, and the rational, complex, Kernel#Rational/#Complex, String#to_r/#to_c, rationalize, numeric and bigdecimal specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 19 +++++++++++++++++++ Src/StdLib/ironruby/ironruby/complex.rb | 2 ++ Src/StdLib/ironruby/ironruby/rational.rb | 2 ++ 4 files changed, 24 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 3ca9b6075..aec9fb9e5 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1178,6 +1178,7 @@ public Tests(Driver/*!*/ driver) { Rational_CSharp1, Complex_CSharp1, Rational_ComplexConventions1, + Rational_StringEncoding1, Method_LightFrame1, Method_LightFrame2, Block_RegisterLocals1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index d1cb74103..03f5c53ca 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -6212,6 +6212,25 @@ public void Rational_ComplexConventions1() { "); } + /// + /// Rational#to_s/inspect and Complex#to_s/inspect are US-ASCII, as MRI makes them (rb_usascii_str_new): + /// rational.rb and complex.rb are US-ASCII sources. + /// + public void Rational_StringEncoding1() { + TestOutput(@" +require 'ruby4' +p Rational(1, 2).to_s.encoding, Rational(-1, 2).inspect.encoding, Complex(1, 2).to_s.encoding, Complex(1.5, -2r).inspect.encoding +p Rational(1, 3), Complex(1.5, -2r) +", @" +# +# +# +# +(1/3) +(1.5-(2/1)*i) +"); + } + /// /// Rational as a C# type (RubyRational) with its arithmetic, comparison, #to_f and #hash in C#, and /// Kernel#Rational: Integer, Float, Rational and big operands, coercion, division by zero, NaN, diff --git a/Src/StdLib/ironruby/ironruby/complex.rb b/Src/StdLib/ironruby/ironruby/complex.rb index dd0c0e433..95f1bf1bf 100644 --- a/Src/StdLib/ironruby/ironruby/complex.rb +++ b/Src/StdLib/ironruby/ironruby/complex.rb @@ -1,3 +1,5 @@ +# encoding: us-ascii +# The strings this file makes are US-ASCII, as the C ones are (nurat_to_s, f_format: rb_usascii_str_new). # Complex, ported from Ruby 4.0's complex.c, together with the methods complex.c defines # on Numeric, Float and String, and Kernel#Complex. Loaded by ruby4.rb as part of the # core prelude, after rational.rb. diff --git a/Src/StdLib/ironruby/ironruby/rational.rb b/Src/StdLib/ironruby/ironruby/rational.rb index 56c97fce3..c310fc3c1 100644 --- a/Src/StdLib/ironruby/ironruby/rational.rb +++ b/Src/StdLib/ironruby/ironruby/rational.rb @@ -1,3 +1,5 @@ +# encoding: us-ascii +# The strings this file makes are US-ASCII, as the C ones are (nurat_to_s, f_format: rb_usascii_str_new). # Rational, ported from Ruby 4.0's rational.c, together with the methods rational.c # defines on Integer, Float, Numeric and String, Kernel#Rational, and the Rational # branches of numeric.c's Integer#** and Float#**. From 6d62f204773473bdb53df6cc6cce1735fabba242 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 17:13:01 +0000 Subject: [PATCH 322/439] IO, File, Dir, Stat, MatchData, Process::Status, Exception inspect: BINARY CRuby 4.0 builds these descriptions with rb_sprintf or rb_str_buf_new, so they are BINARY strings while all of them is ASCII: $stdout.inspect, Dir.new(".").inspect, File::Stat#inspect, /(.)/.match("a").inspect, RuntimeError.new("x").inspect and Process::Status#to_s/#inspect are ASCII-8BIT. A part that is not ASCII - a path, a message, a matched string - gives the result that part's encoding. An exception with an empty message inspects as its class's name, rb_class_name's string, US-ASCII. IronRuby gave UTF-8, the path encoding or US-ASCII. RubyUtils.BinaryIfAscii gives an ASCII-only description BINARY and leaves any other as it is; IO, File, Dir, MatchData and Exception#inspect end with it. File::Stat and Process::Status, always ASCII, are made BINARY. Exception#inspect's bare class name is a US-ASCII copy. Left: under LANG=C, File#inspect of a path that is not ASCII is an invalid US-ASCII string (the path encoding), where CRuby keeps the path's UTF-8; the base build does the same. Checked with Scenario_DescriptionEncoding2 (output from CRuby 4.0, the same under LANG=C and C.UTF-8), probes with non-ASCII paths, messages and matches side by side with CRuby, and the exception, IO#inspect, Dir#inspect, File::Stat, MatchData, Process::Status, StringIO#inspect, Kernel#inspect and IO.pipe specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 21 +++++++++++++++++++++ Src/Libraries/Builtins/Dir.cs | 2 +- Src/Libraries/Builtins/ExceptionOps.cs | 9 +++++++-- Src/Libraries/Builtins/FileOps.cs | 9 +++++---- Src/Libraries/Builtins/IoOps.cs | 2 +- Src/Libraries/Builtins/MatchDataOps.cs | 2 +- Src/Libraries/Builtins/RubyProcess.cs | 10 ++++++---- Src/Ruby/Runtime/RubyUtils.cs | 12 ++++++++++++ 9 files changed, 55 insertions(+), 13 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index aec9fb9e5..139009d1b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -150,6 +150,7 @@ public Tests(Driver/*!*/ driver) { Scenario_InspectRecursive1, Scenario_InspectObjectId1, Scenario_DescriptionEncoding1, + Scenario_DescriptionEncoding2, Scenario_RubyMethodMissing1, Scenario_RubyMethodMissing2, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 03f5c53ca..6c787e372 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -92,6 +92,27 @@ class Café; end "); } + /// + /// Dir, File, File::Stat, MatchData and Exception#inspect are BINARY in MRI while they are ASCII; an + /// exception with a message that is not gives UTF-8, and one with an empty message gives its class's + /// name, US-ASCII. + /// + public void Scenario_DescriptionEncoding2() { + TestOutput(@" +p Dir.new(""."").inspect.encoding, File.open(IO::NULL).inspect.encoding, File::Stat.new(""."").inspect.encoding +p(/(.)/.match(""a"").inspect.encoding) +p RuntimeError.new(""x"").inspect.encoding, RuntimeError.new(""é"").inspect.encoding, RuntimeError.new("""").inspect.encoding +", @" +# +# +# +# +# +# +# +"); + } + /// /// Kernel#inspect of an object met again inside its own inspect: MRI's "#<Foo:0x... ...>". /// diff --git a/Src/Libraries/Builtins/Dir.cs b/Src/Libraries/Builtins/Dir.cs index e4c5de422..4d29458a1 100644 --- a/Src/Libraries/Builtins/Dir.cs +++ b/Src/Libraries/Builtins/Dir.cs @@ -700,7 +700,7 @@ public static MutableString GetPath(RubyContext/*!*/ context, RubyDir/*!*/ self) result.Append(self._dirName); } result.Append('>'); - return result; + return RubyUtils.BinaryIfAscii(result); } [RubyMethod("pos")] diff --git a/Src/Libraries/Builtins/ExceptionOps.cs b/Src/Libraries/Builtins/ExceptionOps.cs index 2d6b790ed..1ea818886 100644 --- a/Src/Libraries/Builtins/ExceptionOps.cs +++ b/Src/Libraries/Builtins/ExceptionOps.cs @@ -240,7 +240,12 @@ public static bool Equal(BinaryOpStorage/*!*/ equals, RubyContext/*!*/ context, var messageString = message as MutableString; if (message == null || (messageString != null && messageString.IsEmpty)) { - // MRI drops the "#<...>" wrapper entirely when #to_s is empty + // MRI drops the "#<...>" wrapper entirely when #to_s is empty, and returns the class's name + // (rb_class_name), which is US-ASCII when it is ASCII + if (className.IsAscii()) { + className = className.Clone(); + className.ForceEncoding(RubyEncoding.Ascii); + } return className; } @@ -258,7 +263,7 @@ public static bool Equal(BinaryOpStorage/*!*/ equals, RubyContext/*!*/ context, result.Append(KernelOps.Inspect(inspectStorage, tosConversion, message)); } result.Append('>'); - return result; + return RubyUtils.BinaryIfAscii(result); } #endregion diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index b0fc3c8f1..89703f9be 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1989,7 +1989,7 @@ public static object FileSize(RubyIO/*!*/ self) { } else { result.Append("fd ").Append(self.GetFileDescriptor().ToString(CultureInfo.InvariantCulture)); } - return result.Append('>'); + return RubyUtils.BinaryIfAscii(result.Append('>')); } [RubyMethod("path")] @@ -2741,9 +2741,10 @@ public static bool IsZeroLength(FileSystemInfo/*!*/ self) { public static MutableString/*!*/ Inspect(RubyContext/*!*/ context, FileSystemInfo/*!*/ self) { var si = self as StatInfo; if (si != null && !si.IsInitialized) { - return MutableString.CreateAscii("#<" + context.GetClassName(self) + ": uninitialized>"); + return MutableString.Create("#<" + context.GetClassName(self) + ": uninitialized>", RubyEncoding.Binary); } - return MutableString.CreateAscii(String.Format(CultureInfo.InvariantCulture, + // BINARY, as rb_str_buf_new makes it in MRI's rb_stat_inspect + return MutableString.Create(String.Format(CultureInfo.InvariantCulture, "#", FormatDev(DeviceId(self)), context.Inspect(Inode(self)), @@ -2758,7 +2759,7 @@ public static bool IsZeroLength(FileSystemInfo/*!*/ self) { context.Inspect(AccessTime(self)), context.Inspect(ModifiedTime(self)), context.Inspect(CreateTime(self)) - )); + ), RubyEncoding.Binary); } private static string FormatDev(object dev) { diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index f75e643e0..7c43aa370 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -1631,7 +1631,7 @@ public static bool Sync(RubyIO/*!*/ self, bool sync) { RubyUtils.AppendFormatHexObjectId(result, RubyUtils.GetObjectId(self.Context, self)); } result.Append('>'); - return result; + return RubyUtils.BinaryIfAscii(result); } #endregion diff --git a/Src/Libraries/Builtins/MatchDataOps.cs b/Src/Libraries/Builtins/MatchDataOps.cs index d521ca4b0..95a7252fd 100644 --- a/Src/Libraries/Builtins/MatchDataOps.cs +++ b/Src/Libraries/Builtins/MatchDataOps.cs @@ -298,7 +298,7 @@ public static bool Equals(RubyContext/*!*/ context, MatchData/*!*/ self, object result.Append(context.Inspect(self.GetGroupValue(i))); } result.Append('>'); - return result; + return RubyUtils.BinaryIfAscii(result); } [RubyMethod("to_s")] diff --git a/Src/Libraries/Builtins/RubyProcess.cs b/Src/Libraries/Builtins/RubyProcess.cs index 43aba68d7..4ea04b1f5 100644 --- a/Src/Libraries/Builtins/RubyProcess.cs +++ b/Src/Libraries/Builtins/RubyProcess.cs @@ -443,14 +443,16 @@ public static bool Equals(Status/*!*/ self, object other) { [RubyMethod("to_s")] public static MutableString/*!*/ ToStr(Status/*!*/ self) { - return MutableString.CreateAscii(String.Format(CultureInfo.InvariantCulture, "pid {0} {1}", - self._pid, Describe(self))); + // BINARY, as rb_sprintf makes it in MRI's pst_to_s + return MutableString.Create(String.Format(CultureInfo.InvariantCulture, "pid {0} {1}", + self._pid, Describe(self)), RubyEncoding.Binary); } [RubyMethod("inspect")] public static MutableString/*!*/ Inspect(Status/*!*/ self) { - return MutableString.CreateAscii(String.Format(CultureInfo.InvariantCulture, "#", - self._pid, Describe(self))); + // BINARY, as rb_sprintf makes it in MRI's pst_inspect + return MutableString.Create(String.Format(CultureInfo.InvariantCulture, "#", + self._pid, Describe(self)), RubyEncoding.Binary); } } diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 3e9294b81..a19672e07 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -352,6 +352,18 @@ public static void AppendToObjectDescription(MutableString/*!*/ str, MutableStri } } + /// + /// A description MRI builds with rb_sprintf or rb_str_buf_new - IO, File, Dir, MatchData, Exception#inspect - is BINARY + /// while all of it is ASCII; a part that is not (a path, a message, a matched string) gives it that part's encoding, + /// which already has then. + /// + public static MutableString/*!*/ BinaryIfAscii(MutableString/*!*/ description) { + if (description.IsAscii()) { + description.ForceEncoding(RubyEncoding.Binary); + } + return description; + } + public static MutableString/*!*/ FormatObjectPrefix(RubyContext/*!*/ context, string/*!*/ className, long objectId) { MutableString str = CreateObjectDescription(context, className); str.Append("#<"); From 37d9aa12357842e1e05ea3823eea926be059461a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 17:19:11 +0000 Subject: [PATCH 323/439] Enumerator, Data, Set, Fiber, TracePoint, main inspect: BINARY The rest of the descriptions CRuby 4.0 builds as BINARY strings while they are ASCII (rb_sprintf, rb_str_buf_new): Enumerator#inspect and Enumerator::Lazy, ::Chain, ::Product and ::ArithmeticSequence's, Data#inspect, Set#inspect, Fiber#inspect, ObjectSpace::WeakKeyMap#inspect, TracePoint#inspect and main's to_s/inspect. A part that is not ASCII gives the result its own encoding. A refinement's description is US-ASCII, as module names are. IronRuby gave UTF-8 (the prelude's are interpolations in a UTF-8 source) or US-ASCII. The prelude's end with __ir_binary_if_ascii__, a private Kernel method that returns a BINARY copy of an ASCII-only string and leaves any other as it is (a copy, since ArithmeticSequence#inspect hands out a text it keeps). TracePoint#inspect ends with RubyUtils.BinaryIfAscii; main's "main" is made BINARY; a refinement's description is US-ASCII when it is ASCII. Checked with Scenario_DescriptionEncoding3 (output from CRuby 4.0), a probe of 50 core #inspect/#to_s encodings (now all as CRuby's) and one with non-ASCII elements, members, events, fibers and refinements under LANG=C and C.UTF-8 (the same as CRuby), and the enumerator, set, data, fiber, tracepoint, refinement, WeakKeyMap, Range/Numeric#step, main and Kernel#inspect/#to_s specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 23 ++++++++++++++++++ Src/Libraries/Builtins/KernelOps.cs | 15 ++++++++++++ Src/Libraries/Builtins/RefinementOps.cs | 4 ++++ Src/Libraries/Builtins/SingletonOps.cs | 3 ++- Src/Libraries/Builtins/TracePointOps.cs | 6 ++--- Src/StdLib/ironruby/ruby4.rb | 31 +++++++++++++------------ Src/StdLib/ironruby/set.rb | 4 ++-- 8 files changed, 66 insertions(+), 21 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 139009d1b..d8f3f0d18 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -151,6 +151,7 @@ public Tests(Driver/*!*/ driver) { Scenario_InspectObjectId1, Scenario_DescriptionEncoding1, Scenario_DescriptionEncoding2, + Scenario_DescriptionEncoding3, Scenario_RubyMethodMissing1, Scenario_RubyMethodMissing2, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 6c787e372..90fa0ec8f 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -113,6 +113,29 @@ p RuntimeError.new(""x"").inspect.encoding, RuntimeError.new(""é"").inspect.enc "); } + /// + /// The descriptions the prelude builds - Enumerator and its kinds, Data, Set, Fiber - are BINARY while + /// they are ASCII, as MRI's; a refinement's is US-ASCII, as a module name is. + /// + public void Scenario_DescriptionEncoding3() { + TestOutput(@" +require 'ruby4' +p [1].each.inspect.encoding, [1].lazy.map { }.inspect.encoding, ([1].each + [2]).inspect.encoding, 1.step(10, 2).inspect.encoding +p Data.define(:a).new(a: 1).inspect.encoding, Set[1].inspect.encoding, Fiber.new { }.inspect.encoding +p Module.new { refine(String) { } }.refinements.first.inspect.encoding, TracePoint.new(:line) { }.inspect.encoding +", @" +# +# +# +# +# +# +# +# +# +"); + } + /// /// Kernel#inspect of an object met again inside its own inspect: MRI's "#<Foo:0x... ...>". /// diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index 528069500..9493e7ac7 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1648,6 +1648,21 @@ public static bool IsSameObject(object self, object other) { return BasicObjectOps.IsEqual(self, other); } + /// + /// For the descriptions the prelude builds (Enumerator, Set, Data, Fiber...#inspect), which MRI builds with rb_sprintf or + /// rb_str_buf_new: BINARY while all of the text is ASCII. A copy then, since the text may be one the caller keeps; + /// a text that is not ASCII is returned as it is, in its own encoding, as MRI's is. + /// + [RubyMethod("__ir_binary_if_ascii__", RubyMethodAttributes.PrivateInstance)] + public static MutableString/*!*/ BinaryIfAscii(object self, [NotNull]MutableString/*!*/ text) { + if (text.Encoding == RubyEncoding.Binary || !text.IsAscii()) { + return text; + } + var copy = text.Clone(); + copy.ForceEncoding(RubyEncoding.Binary); + return copy; + } + /// /// MRI's rb_inspect for the prelude: #inspect, escaped when its result is in an /// encoding the output cannot take (see RubyContext.Inspect). diff --git a/Src/Libraries/Builtins/RefinementOps.cs b/Src/Libraries/Builtins/RefinementOps.cs index 31e7b4675..36c6587d8 100644 --- a/Src/Libraries/Builtins/RefinementOps.cs +++ b/Src/Libraries/Builtins/RefinementOps.cs @@ -55,6 +55,10 @@ public static RubyModule GetTarget(RubyModule/*!*/ self) { ? context.Inspect(self.RefinementHolder) : MutableString.CreateAscii("nil")); result.Append('>'); + // US-ASCII while it is ASCII, as the module names MRI's rb_mod_to_s builds it from are + if (result.IsAscii()) { + result.ForceEncoding(RubyEncoding.Ascii); + } return result; } diff --git a/Src/Libraries/Builtins/SingletonOps.cs b/Src/Libraries/Builtins/SingletonOps.cs index 97448fd3d..01d999508 100644 --- a/Src/Libraries/Builtins/SingletonOps.cs +++ b/Src/Libraries/Builtins/SingletonOps.cs @@ -39,7 +39,8 @@ public static class MainSingletonOps { [RubyMethod("to_s", RubyMethodAttributes.PublicInstance)] [RubyMethod("inspect", RubyMethodAttributes.PublicInstance)] public static MutableString/*!*/ ToS(object/*!*/ self) { - return MutableString.CreateAscii("main"); + // BINARY, as MRI's main_to_s makes it (rb_str_new2) + return MutableString.Create("main", RubyEncoding.Binary); } // main's #public, #private and #include are private, as MRI's are: `self.include M` works, diff --git a/Src/Libraries/Builtins/TracePointOps.cs b/Src/Libraries/Builtins/TracePointOps.cs index e2ad65386..0bc1681b8 100644 --- a/Src/Libraries/Builtins/TracePointOps.cs +++ b/Src/Libraries/Builtins/TracePointOps.cs @@ -409,7 +409,7 @@ public static RubyArray GetParameters(TracePoint/*!*/ self) { public static MutableString/*!*/ Inspect(TracePoint/*!*/ self) { TraceEventInfo info = TracePoint.CurrentEvent; if (info == null) { - return MutableString.CreateAscii(self.IsEnabled ? "#" : "#"); + return MutableString.Create(self.IsEnabled ? "#" : "#", RubyEncoding.Binary); } var context = self.Context; @@ -420,7 +420,7 @@ public static RubyArray GetParameters(TracePoint/*!*/ self) { case TraceEvents.ThreadBegin: case TraceEvents.ThreadEnd: result.Append(' ').Append(context.Inspect(info.Self)); - return result.Append('>'); + return RubyUtils.BinaryIfAscii(result.Append('>')); case TraceEvents.Call: case TraceEvents.CCall: @@ -439,7 +439,7 @@ public static RubyArray GetParameters(TracePoint/*!*/ self) { result.Append(" in '").Append(info.MethodName).Append('\''); } } - return result.Append('>'); + return RubyUtils.BinaryIfAscii(result.Append('>')); } #endregion diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index aed410430..542fc8604 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3038,7 +3038,7 @@ def inspect loc = @block && (@block.source_location rescue nil) location = @location = loc ? "#{loc[0]}:#{loc[1]}" : false end - location ? "#" : "#" + __ir_binary_if_ascii__(location ? "#" : "#") end alias :to_s :inspect @@ -5826,10 +5826,11 @@ def __inspect_detail__(recv, meth, args, recv_text = nil) # MRI's inspect_enumerator (rb_exec_recursive) has it: [e] inside e. def inspect seen = (::Thread.current[:__ir_enumerator_inspect__] ||= {}.compare_by_identity) - return "#<#{self.class}: ...>" if seen.key?(self) + # BINARY while it is ASCII, as enumerator.c's inspect_enumerator builds it + return __ir_binary_if_ascii__("#<#{self.class}: ...>") if seen.key?(self) seen[self] = true begin - __inspect_unguarded__ + __ir_binary_if_ascii__(__inspect_unguarded__) ensure seen.delete(self) end @@ -6144,10 +6145,10 @@ def size def inspect if (info = @__inspect__) - return "#<#{self.class}: #{__inspect_detail__(*info)}>" + return __ir_binary_if_ascii__("#<#{self.class}: #{__inspect_detail__(*info)}>") end - return "#<#{self.class}: uninitialized>" if @__generator__.nil? - "#<#{self.class}: ...>" + return __ir_binary_if_ascii__("#<#{self.class}: uninitialized>") if @__generator__.nil? + __ir_binary_if_ascii__("#<#{self.class}: ...>") end alias :to_s :inspect @@ -6693,8 +6694,8 @@ def rewind end def inspect - return "#" if @__enums__.nil? - "#" + return __ir_binary_if_ascii__("#") if @__enums__.nil? + __ir_binary_if_ascii__("#") end alias :to_s :inspect @@ -6789,14 +6790,14 @@ def rewind def inspect enums = __enums_or_nil__ - return "#<#{self.class}: uninitialized>" if enums.nil? + return __ir_binary_if_ascii__("#<#{self.class}: uninitialized>") if enums.nil? seen = ::Thread.current[:__enumerator_product_inspect__] ||= [] - return "#<#{self.class}: ...>" if seen.any? { |o| o.equal?(self) } + return __ir_binary_if_ascii__("#<#{self.class}: ...>") if seen.any? { |o| o.equal?(self) } seen.push(self) begin - "#<#{self.class}: #{enums.inspect}>" + __ir_binary_if_ascii__("#<#{self.class}: #{enums.inspect}>") ensure seen.pop ::Thread.current[:__enumerator_product_inspect__] = nil if seen.empty? @@ -7696,7 +7697,7 @@ def hash # for, since building it was a good part of what making a sequence cost def inspect form = @__inspect_str__ - case form + __ir_binary_if_ascii__ case form when ::String then form when :step then "((#{@__source__.inspect}).step)" when ::Array @@ -8012,7 +8013,7 @@ def to_s path = ::Module.instance_method(:to_s).bind(self.class).call named = !path.start_with?("#") stack = (::Thread.current[:__data_inspect__] ||= []) - return "#" if stack.any? { |seen| seen.equal?(self) } + return __ir_binary_if_ascii__("#") if stack.any? { |seen| seen.equal?(self) } stack.push(self) begin out = +"#" + __ir_binary_if_ascii__(out << ">") ensure stack.pop end @@ -10295,7 +10296,7 @@ def clear end def inspect - "#" + __ir_binary_if_ascii__("#") end # MRI's map is native data Marshal cannot write; this one dumped its table. diff --git a/Src/StdLib/ironruby/set.rb b/Src/StdLib/ironruby/set.rb index f4f3d6be2..b01dbb89f 100644 --- a/Src/StdLib/ironruby/set.rb +++ b/Src/StdLib/ironruby/set.rb @@ -1083,13 +1083,13 @@ def inspect plain = __core_set__? if ids.include?(object_id) - return plain ? "#{self.class}[...]" : sprintf('#<%s: {...}>', self.class.name) + return __ir_binary_if_ascii__(plain ? "#{self.class}[...]" : sprintf('#<%s: {...}>', self.class.name)) end ids << object_id begin body = to_a.inspect[1..-2] - return plain ? "#{self.class}[#{body}]" : sprintf('#<%s: {%s}>', self.class, body) + return __ir_binary_if_ascii__(plain ? "#{self.class}[#{body}]" : sprintf('#<%s: {%s}>', self.class, body)) ensure ids.pop end From abc73d4bd7439882f108d8c2ff1724c8f4b972c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 17:20:30 +0000 Subject: [PATCH 324/439] Ledger: round 9's gate, PASS for what it computes; Towers open Round 9 of round thirty-seven (the branch at 597b8dc9, with master c4719ea merged and the baseline moved to it) computes what master does: IronRuby.Tests 1,427 run, none failed; the matrices in seven modes, every DIFF explained (the thread-backtrace one a race in the matrix, made deterministic in round 10); a probe file for the round's changes as CRuby in every mode; ruby/spec's five suites with no unlisted failure; the census with nothing down. AWFY 12 is at a geomean of 0.919 and 0.912, and start-up at 0.85-0.96 of master's on the composite R2R host. Towers is open: 2-7% slower than master, leaning so since round 7, and not caused by the round's switches. perf/struct is bisecting it before the branch goes to master. The round's entries are marked gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 70 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 60 insertions(+), 10 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1b9a3ddbe..58ead157d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,8 +2043,58 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-28 for round 9 of round thirty-seven** (master c4719ea with #301 and #302, perf/crubydiff's + eighth to tenth rounds, perf/ownerpark (rejected), perf/yieldloop, perf/kwjit with perf/kwcall's fix, + perf/kernelcall, perf/datafilter, perf/namedblock, perf/heldrfc, perf/loopivar2, perf/sharedargs): the branch + `claude/happy-gauss-95wm2j` at 597b8dc9 against master c4719ea (the baseline moved with the merge; its + census matches f81fc19's), Release net10.0, the composite R2R host on both, four cores: **PASS for what it + computes, with one timing item open: Towers** (below). + The merge itself: master's ledger and the branch's met in gap 26 (master's two paragraphs kept, the + branch's closed gap 27 heading kept) and at the top of Landed (both kept); perf/heldrfc's branch moved + perf/havlakalloc's entry, whose old copy went and whose gated mark the moved one took. No code conflict. + ReflectionCache.Generated.cs is what ClassInitGenerator writes. No new DLR patch; master's + check-dlr-patches refuses the branch's DLR checkout (its 0111 and 0112 overlap master's 0110), so the base + is built on a DLR with master's patches alone. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,427 tests, every one executed, none failed. + `gate-matrices.rb --all` in 7 modes (the six default ones, and every round 9 switch off at once: + IR_ARRAY_CLASS_FAST, IR_HELD_METHOD_BLOCKS, IR_INSTANCE_DATA_FILTER, IR_JIT_KWREST, IR_LOOP_IVAR_WRITES, + IR_OSR_YIELD, IR_PASSED_BLOCKS, IR_SHARED_SHAPES): 1,329 same, 119 baseline, 15 DIFF, each explained: + regexp-binary-ctype prints what it printed at round 8; string-race-matrix, compared over five runs of each + tree (rows not always ok 110 -> 88, lost writes 106 -> 0, no row failing only on the new build); + thread-backtrace's row 3 under -X:NoJITCalls, a race in the matrix (the child can read main's backtrace + before main blocks in `q3.pop`; one of three runs printed CRuby's output exactly, `Thread::Queue#pop` frame + and all, which master does not), made deterministic by perf/crubydiff's 419f23e (round 10). + A probe file for the round's changes - Integer and Float without snake_case CLR names (`5.to_string`, a + user's `compare_to` on an Integer key), an interpolated heredoc part's backtrace line, the encodings of + default descriptions, a `while` loop yielding once per iteration hot (break, next, a raise through the + yield, a tail statement that deopts), `**rest` methods hot with keys varying and a body that deopts, + singleton classes given to an Array, a String and a Hash while compiled code asks their class (from 8 + threads too, and 70,000 Strings with ivars), blocks passed on, stored by their callee and called later and + `&block` stored and passed to `super`, block loops writing ivars with a deopt and a frozen self, + define_singleton_method by Symbol and String and 300 OpenStructs - prints CRuby's output with the JIT on + and off and with the round's switches off. Master differs in 8 rows. Both print one `-w` warning CRuby + does not, from ostruct.rb ("method redefined; discarding old table!"), fixed by perf/crubydiff's round 11. + Read for the parts without a GVL: perf/datafilter sets its bit with `Interlocked.Or` before the table entry + is added and reads it with `Volatile.Read` before the table is, so a reader that finds the bit clear finds + no entry, and one that learned of the singleton class through any synchronisation finds the bit set; per + runtime, as the table is. + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against master (Src/StdLib, Util/bench, AWFY): as at round 8 (light frames 82.5%, method JIT + compiles 12.3%); against round 8, 10 method-JIT ups and nothing down. + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.919 and 0.912. Alone, + five rounds in each order, medians new/base: Havlak 0.869 / 0.866 (perf/heldrfc), DeltaBlue 0.978 / 1.014, + Richards 1.043 / 0.955, Towers 1.125 / 1.124. Towers again, three builds alternating: master, this tree + with the round's switches off (1.082) and as built (1.045) - the round's switches do not cause it; pinned + to two CPUs, ten rounds in each order: 1.074 (base first) and 1.017 (new first), least rounds 1.055 and + 1.036. Towers has leaned slower than master since round 7 (1.068 and 1.035 there, 1.045 and 1.035 alone at + round 8): open, bisected by perf/struct before the branch goes to master. micro-table in both orders: no + line more than 5% slower in both (attr 1.15 then 0.95, cmp 1.12 then 0.99). + Start-up on the composite R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 368 -> 352 and + 385 -> 343, `gem --version` 431 -> 437 and 440 -> 448, `gem list` 827 -> 702 and 829 -> 711, + `require "irb"` 812 -> 734 and 863 -> 765, irb 1+1 915 -> 784 and 926 -> 796: 0.85-0.96, `gem --version` + level (1.015 and 1.019). - **perf/yieldloop (2026-11-28) - a `while` loop with a yield in its body runs in its compiled copy (gap 18, stage - 3a of `Docs/jit-resume-deopt.md`)** - not gated. The OSR copy gave up at the YieldCall (`[osr] emitter: node: + 3a of `Docs/jit-resume-deopt.md`)** - gated 2026-11-28 (round 9's gate entry). The OSR copy gave up at the YieldCall (`[osr] emitter: node: YieldCall`), so `def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; end` ran its loop generic: about 22 ns an element of loop around the yield (`loop100` 29.8 generic, 8.0 typed). - The copy now takes a loop of the shape `while C; S...; yield E...; T...; end` with one yield in statement position @@ -2076,7 +2126,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has next, redo pass with the switch on and off; the whole suite was not run. - **perf/kwcall (/perf-step, 2026-11-28) - the caller's keyword hash: nothing to win; a JIT'd - `**rest` whose body can deopt is declined** (fixes a slowdown perf/kwjit brought in). + `**rest` whose body can deopt is declined** (fixes a slowdown perf/kwjit brought in). Gated 2026-11-28 (round 9's gate entry). - **The caller's hash** (clock, ns; CRuby in brackets), bodies with a global variable assignment: a declared-keywords call `kd(k: 1)` 39 [42], `kd2(k: 1, j: 2)` 64 [45], `kr(k: 1)` 32 [40] - the method JIT binds them from the call's pairs (JitKeywordCall) without the hash, at CRuby's @@ -2100,7 +2150,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/kwjit (/perf-step, 2026-11-28) - the method JIT takes a keyword method with `**rest`** (gap 38; switch `IR_JIT_KWREST`, on unless `=0`). Built on fcbc67b (claude/happy-gauss-95wm2j) - with de51cf89 merged. + with de51cf89 merged. Gated 2026-11-28 (round 9's gate entry). - **What changed.** JitKeywords.TryRecognize took a prologue only if its keyword Match refused other keys, so a method with `**o` kept the prologue in its body and the screen rejected it (`KeywordArgumentsTest`). It now takes `o = Rest(?kw?, names)` after the keyword reads as one @@ -2139,7 +2189,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/datafilter (/perf-step, 2026-11-28, on fcbc67b + 672867e) - a filter by identity hash keeps objects without instance data out of the instance data table (`IR_INSTANCE_DATA_FILTER`)** - - instructions and clock, not gated. perf/kernelcall's lead: once one String and one Hash have a + - instructions and clock, gated 2026-11-28 (round 9's gate entry). perf/kernelcall's lead: once one String and one Hash have a singleton method, every String's and Hash's class lookup went to the ConditionalWeakTable (`@s.nil?` compiled +21% instructions, `@s.is_a?(String)` +37%). A per-object bit is unsafe on MutableString (non-atomic `_flags`) and absent on Hash, so each runtime keeps 65,536 bits (8 KB) @@ -2153,7 +2203,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **perf/kernelcall (/perf-step, 2026-11-28, on 744b83e) - an Array without instance data is answered its class without the instance data table (`RubyArray.MayHaveInstanceData`, - `IR_ARRAY_CLASS_FAST`)** - instructions and clock, not gated. The round's premise (a C# Kernel + `IR_ARRAY_CLASS_FAST`)** - instructions and clock, gated 2026-11-28 (round 9's gate entry). The round's premise (a C# Kernel call costs ~28 ns over CRuby whatever it does) did not hold when counted: over an empty method in the same harness, `Integer(5)` costs what `@i.gcd(4)` costs, implicit and explicit self alike, and the rows' gap to CRuby is the harness's Ruby call. The outlier the counts @@ -2169,7 +2219,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has once one of its instances has a singleton class (a String's, a Hash's) - the bit is RubyArray's alone; and the harness's own Ruby call (gap 13). -- **perf/loopivar2 (/perf-step, 2026-11-28, not gated) - outlined loops write self's instance +- **perf/loopivar2 (/perf-step, 2026-11-28, gated 2026-11-28 (round 9's gate entry)) - outlined loops write self's instance variables by default (`IR_LOOP_IVAR_WRITES=0` refuses them), block loops included: the 2x "slowdown" that kept perf/loopivar off was the GC, not the stores** (on fcbc67b). - **The cause.** In Util/bench/loopivar-shapes.rb, `times_count` timed after `while_count` in one @@ -2207,7 +2257,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has core/array/each as on the base; IronRuby.Tests (Debug) PASSED. - **perf/sharedargs (round forty-one, 2026-11-28) - a call of another shape gets a shared rule of its - own (gap 32)** - not gated. A shared rule is one per method, receiver type and delegate type; OpenStruct's + own (gap 32)** - gated 2026-11-28 (round 9's gate entry). A shared rule is one per method, receiver type and delegate type; OpenStruct's `define_singleton_method!(name, ...)` (a Symbol) and `("#{name}=", ...)` (a String) share the key, and the second shape's call, failing the first's argument test, got a rule of its own, which tests one class version: built and compiled again for each object's singleton class (~200 us), 207-209 times in @@ -2230,7 +2280,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has module/define_method one error each on both builds (the known `into`/`to` messages). - **perf/heldrfc e8a74f4 (round forty-three, 2026-11-28) - a method's scope holds its caller's literal - block until it is parked (gap 25)** - not gated. At fcbc67b (rounds seven and eight merged) Havlak + block until it is parked (gap 25)** - gated 2026-11-28 (round 9's gate entry). At fcbc67b (rounds seven and eight merged) Havlak allocated 1.79 GB an iteration again, method scopes 24% and Procs 13% as before perf/havlakalloc: round thirty-seven's perf/literalcode (`2eda4af`, "a body that evaluates a literal block on every call is not a light frame") made `Vector#each`, `has_some` and every method that calls them with a literal methods @@ -2267,7 +2317,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has Proc keeps until the park (its converter, the callee's scope) is dropped only by that scope's park. - **perf/namedblock 4e87b11 977e047 (round forty-two, 2026-11-28) - a named block that a method only - passes on stays reusable (gap 25)** - not gated. `def each(&b) = @items.each(&b)` (som.rb's `SomSet#each`, + passes on stays reusable (gap 25)** - gated 2026-11-28 (round 9's gate entry). `def each(&b) = @items.each(&b)` (som.rb's `SomSet#each`, `has_some`, `get_one`; 5 of AWFY's 6 methods with a named block, about 320 of the standard library's 800) converted its caller's literal for good (`EnterLightMethodNamingBlock`: ConvertAsMethodFrame), so no caller passing a literal to it could make its Proc again or park its scope: a caller of `SomSet#each` 374 B @@ -4324,7 +4374,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope From c4520cdf59580127176355446cb1adbd27b130e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 18:09:11 +0000 Subject: [PATCH 325/439] File#path and File#inspect under a US-ASCII path encoding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under LANG=C the path encoding is US-ASCII, and EncodePath gives a name that is not ASCII as its UTF-8 bytes in a BINARY string. File#path made its result from that string read back as characters, one for each byte, and encoded them again: File.open("d3é/fé.txt").path was "d3\xC3\x83\xC2\xA9/...", and with a BINARY path String#b on it raised EncoderFallbackException. File#inspect appended the .NET path to a US-ASCII string, which was then invalid. CRuby 4.0 keeps the string the file was opened with (fptr->pathv): #path and #inspect are that path in its own encoding, UTF-8 or BINARY. File#path now makes the result from the path's characters in the encoding it was opened with (the file system's UTF-8 bytes for a BINARY one), and File#inspect appends what #path gives to a description that starts BINARY, as the other descriptions do. Left: a path opened in an encoding that is not the file system's (ISO-8859-1 "\xE9") is found by its characters, where CRuby passes its bytes and gets ENOENT; the base build does the same. Checked with File_PathUnderAsciiLocale1 (output from CRuby 4.0; it sets Encoding.default_external in the process), probes of UTF-8, BINARY, transcoded and ASCII paths under LANG=C and C.UTF-8 (the same as CRuby; the base build differed under both), and the File#path/#to_path/new/ open/realpath, IO#inspect, Dir.children/entries specs under both locales (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IoTests.cs | 26 ++++++++++++++++++++++++++ Src/Libraries/Builtins/FileOps.cs | 22 +++++++++++++++------- 3 files changed, 42 insertions(+), 7 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f85bc826b..4d82b8ce2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -185,6 +185,7 @@ public Tests(Driver/*!*/ driver) { IO_PopenDuplexBytes1, IO_PipeWithoutPipe2, File_AppendBytes1, + File_PathUnderAsciiLocale1, File_WriteBytes1, File_ReadLine1, File_LoadBufferOffset1, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index fd5469fd0..4a7f18e00 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -128,6 +128,32 @@ private byte[] B(string str) { return BinaryEncoding.Instance.GetBytes(str); } + /// + /// Under a US-ASCII path encoding (LANG=C) File#path and File#inspect give a path that is not ASCII in + /// the encoding of the string the file was opened with, as MRI does: File#path came back with each of its + /// UTF-8 bytes made a character of its own, and File#inspect was an invalid US-ASCII string. + /// + public void File_PathUnderAsciiLocale1() { + TestOutput(@" +require 'ruby4' +require 'tmpdir' +Dir.mktmpdir do |dir| + path = File.join(dir, ""é.txt"") + File.write(path, """") + Encoding.default_external = Encoding::US_ASCII + File.open(path) do |f| + s = f.inspect + p s.encoding, s.valid_encoding?, s.end_with?(""é.txt>"") + end + Encoding.default_external = Encoding::UTF_8 +end +", @" +# +true +true +"); + } + [Options(NoRuntime = true)] public void File_AppendBytes1() { string s; diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 89703f9be..869fce599 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1977,12 +1977,16 @@ public static object FileSize(RubyIO/*!*/ self) { } private static MutableString/*!*/ Inspect(RubyFile/*!*/ self) { - var result = MutableString.CreateMutable(self.Context.GetPathEncoding()). + string className = self.Context.GetClassOf(self).GetName(self.Context); + var result = RubyUtils.CreateObjectDescription(self.Context, className). Append("#<"). - Append(self.Context.GetClassOf(self).GetName(self.Context)). + Append(className). Append(':'); if (self.Path != null) { - result.Append(self.Path).Append(self.Closed ? " (closed)" : ""); + // the path as File#path gives it, in the encoding of the string the file was opened with (MRI's + // fptr->pathv): under LANG=C a UTF-8 path is not made an invalid US-ASCII string + RubyUtils.AppendToObjectDescription(result, GetPath(self)); + result.Append(self.Closed ? " (closed)" : ""); } else if (self.Closed) { // a File made from a descriptor has no path to show, only the descriptor result.Append("(closed)"); @@ -2026,12 +2030,16 @@ private static MutableString GetPath(RubyFile/*!*/ self) { if (self.Path == null) { return null; } - // File#path hands back the path in the encoding it was opened with. - MutableString result = self.Context.EncodePath(self.Path); + // File#path hands back the path in the encoding it was opened with, made from its characters: not from + // EncodePath's text, which under LANG=C is the name's UTF-8 bytes in a BINARY string, and read back as + // characters gave one for each byte ("d3\u00C3\u00A9" for "d3\u00E9"). + if (self.PathEncoding == RubyEncoding.Binary) { + return MutableString.CreateBinary(Encoding.UTF8.GetBytes(self.Path), RubyEncoding.Binary); + } if (self.PathEncoding != null) { - result = MutableString.CreateMutable(result.ConvertToString(), self.PathEncoding); + return MutableString.CreateMutable(self.Path, self.PathEncoding); } - return result; + return self.Context.EncodePath(self.Path); } #endregion From e12d05ef8a164d5a815c848563557a451183989e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 18:09:11 +0000 Subject: [PATCH 326/439] Method#inspect writes its modules with #inspect and #to_s, escaped MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CRuby 4.0's method_inspect writes the module a method was looked up on with rb_inspect and the module that defines it, in parentheses, with PRIsVALUE (#to_s): a class whose singleton #inspect says "LOUD!" gives "#" for a subclass's instance, and one whose #to_s says "TOS" gives "T1s(TOS)". Both are escaped as rb_inspect's result is when the default external encoding cannot take a name that is not ASCII: under LANG=C, "#". IronRuby used the modules' names for both (only an anonymous module went through #inspect), so neither override showed and nothing was escaped. InspectModule now always goes through RubyContext.Inspect, and the module in parentheses through the new RubyContext.ToSForDescription: #to_s by the to_s conversion site, then the same escaping. Checked with MethodInspect_Modules1 (output from CRuby 4.0; it sets Encoding.default_external in the process), probes of singleton, class-method-on-subclass, module, alias, anonymous and core method shapes and of #inspect/#to_s/#name overrides under LANG=C and C.UTF-8 (the same as CRuby), and the method/unboundmethod specs under both locales (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 27 +++++++++++++++++++++++ Src/Libraries/Builtins/UnboundMethod.cs | 13 +++++------ Src/Ruby/Runtime/RubyContext.cs | 9 ++++++++ 4 files changed, 43 insertions(+), 7 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 4d82b8ce2..1f1fb5eff 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1284,6 +1284,7 @@ public Tests(Driver/*!*/ driver) { MethodDef1, MethodInspect_LibraryParameters1, MethodInspect_Encoding1, + MethodInspect_Modules1, MethodArity_CoreMethods1, MethodArity_LibraryArguments1, MethodArity_PreludeMethods1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 31262546c..a57a4dc72 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1718,6 +1718,33 @@ p 1.method(:+).inspect.encoding, [].method(:each).unbind.inspect.encoding "); } + /// + /// Method#inspect writes the module it was looked up on with #inspect and the one that defines the + /// method, in parentheses, with #to_s (MRI's method_inspect: rb_inspect and PRIsVALUE); both come out + /// escaped where the default external encoding cannot take a name that is not ASCII. + /// + public void MethodInspect_Modules1() { + TestOutput(@" +class Café; def b; end; end +class Sub < Café; end +class Loud; def self.inspect = ""LOUD!""; def x; end; end +class LoudSub < Loud; end +class T1; def self.to_s = ""TOS""; def x; end; end +class T1s < T1; end +def s(m) = m.inspect.sub(/ \S+:\d+>\z/, "">"") +puts s(LoudSub.new.method(:x)), s(T1s.new.method(:x)), s(Sub.new.method(:b)) +Encoding.default_external = Encoding::US_ASCII +puts s(Sub.new.method(:b)), s(Café.new.method(:b)) +Encoding.default_external = Encoding::UTF_8 +", @" +# +# +# +# +# +"); + } + /// /// Method#inspect shows the parameter list for library methods and attribute accessors /// too, as MRI does ("_" for a required parameter with no name); a rule-generator method diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 62edaa88c..c54edd0fe 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -234,7 +234,8 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet if (attachedModule != null && targetAttached != null && !ReferenceEquals(targetAttached, attachedModule)) { result.Append(InspectModule(context, targetAttached)); result.Append('('); - result.Append(InspectModule(context, attachedModule)); + // the module in parentheses is written by its #to_s (PRIsVALUE), the one before them by #inspect + result.Append(context.ToSForDescription(attachedModule)); result.Append(')'); } else { result.Append(attachedModule != null @@ -252,7 +253,7 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet result.Append(InspectModule(context, origin)); if (!ReferenceEquals(origin, declaringModule)) { result.Append('('); - result.Append(InspectModule(context, declaringModule)); + result.Append(context.ToSForDescription(declaringModule)); result.Append(')'); } result.Append('#'); @@ -292,13 +293,11 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet } // method_inspect writes each module with rb_inspect, so an anonymous one that says what it is - // (EnvUtil.labeled_class) is shown by what it says rather than as #. + // (EnvUtil.labeled_class) is shown by what it says rather than as #, and a name that + // is not ASCII comes out escaped where the default external encoding cannot take it (LANG=C). private static MutableString/*!*/ InspectModule(RubyContext/*!*/ context, RubyModule/*!*/ module) { // and what its #inspect raises goes to the caller, as from rb_inspect - if (module.Name == null && !module.IsSingletonClass) { - return context.Inspect(module); - } - return module.GetDisplayName(context, false); + return context.Inspect(module); } [RubyMethod("of")] diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 84b4bb968..7749f0f72 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3333,6 +3333,15 @@ public object FreezeObjectBy(object obj, object source) { return EscapeInspectResult(toS.Target(toS, inspect.Target(inspect, obj))); } + /// + /// A value a description shows by its #to_s, as rb_sprintf's PRIsVALUE does (rb_obj_as_string): escaped as + /// rb_inspect's result is when the output's encoding cannot take it - "Sub(Caf\u00E9)" in Method#inspect under LANG=C. + /// + public MutableString/*!*/ ToSForDescription(object obj) { + var toS = GetClassOf(obj).InspectResultConversionSite; + return EscapeInspectResult(toS.Target(toS, obj)); + } + /// /// MRI's rb_inspect: a result with non-ASCII content in an encoding other than the one /// output is read in (default internal, else default external) comes back escaped by From 16891ecefbe806fe8f56572140d4c6b43a03a5f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 18:58:40 +0000 Subject: [PATCH 327/439] NameError and NoMethodError messages are US-ASCII when ASCII CRuby 4.0 builds the messages of the NameError family in US-ASCII (name_err_mesg_to_str): nil.foo's "undefined method 'foo' for nil", "uninitialized constant X", "undefined local variable or method...", Object#method's "undefined method 'nope' for class 'Object'". A name that is not ASCII makes the message UTF-8. IronRuby made every message of an exception the runtime raises UTF-8. RubyExceptionData.Message, which turns the CLR message of an exception the runtime raised into the Ruby one, makes a NameError's or NoMethodError's (MemberAccessException and its subclasses) US-ASCII when it is ASCII. A message given to raise or NameError.new keeps its own string, as before; NameError.new's default, the class name, is US-ASCII as rb_class_name's is. This is a slice of the BINARY/US-ASCII message encodings CRuby's C code gives: the rb_raise messages of other errors (IndexError, ArgumentError from Integer()...) are BINARY in CRuby and are left UTF-8. Checked with NameError_MessageEncoding1 (output from CRuby 4.0, the same under LANG=C and C.UTF-8), a probe of 25 NameError/NoMethodError shapes side by side with CRuby under both locales, IronRuby.Tests, and the exception, kernel, module and language specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 23 +++++++++++++++++++ Src/Ruby/Runtime/RubyExceptionData.cs | 4 ++++ 3 files changed, 28 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 1f1fb5eff..a7cd652ea 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1160,6 +1160,7 @@ public Tests(Driver/*!*/ driver) { DidYouMean_LazyThreads1, DidYouMean_LazyRequire1, NameError_LocalVariables1, + NameError_MessageEncoding1, ErrorHighlight_Spots1, ErrorHighlight_Report1, ErrorHighlight_Threads1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index 29528dae9..a220366c7 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -202,6 +202,29 @@ p bad.size } } + /// + /// NameError and NoMethodError messages the runtime makes are US-ASCII while they are ASCII, as MRI's + /// name_err_mesg_to_str makes them; one naming something that is not ASCII is UTF-8, and one given to + /// raise keeps its own encoding. + /// + public void NameError_MessageEncoding1() { + TestOutput(@" +def m = yield rescue $!.message.encoding +p m { nil.foo }, m { Object.new.foo }, m { undefined_local }, m { Undefined_Const }, m { Object.new.method(:nope) } +p m { raise NameError, ""x"" }, m { Object.new.é }, NameError.new.message.encoding, NoMethodError.new.message.encoding +", @" +# +# +# +# +# +# +# +# +# +"); + } + /// /// NameError#local_variables: those of the scope an undefined local variable or method was named /// in, or NameError.new was called in, which did_you_mean suggests. A struct's missing member diff --git a/Src/Ruby/Runtime/RubyExceptionData.cs b/Src/Ruby/Runtime/RubyExceptionData.cs index e5c295569..ecce0219e 100644 --- a/Src/Ruby/Runtime/RubyExceptionData.cs +++ b/Src/Ruby/Runtime/RubyExceptionData.cs @@ -783,6 +783,10 @@ public object Message { // MRI builds the transcoders' messages with rb_sprintf into binary strings // ("\"\xFF\" on UTF-8", "code converter not found (x to y)"). _message = MutableString.CreateBinary(System.Text.Encoding.UTF8.GetBytes(clrMessage)); + } else if (_exception is MemberAccessException && clrMessage.IsAscii()) { + // NameError and NoMethodError: MRI's name_err_mesg_to_str builds "undefined method 'foo' for + // nil", "uninitialized constant X"... in US-ASCII, and in UTF-8 only for a name that is not ASCII + _message = MutableString.Create(clrMessage, RubyEncoding.Ascii); } else { _message = MutableString.Create(clrMessage, RubyEncoding.UTF8); } From e5edc8af0243e82676ac38e11a7857aaf3ecee88 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 18:58:40 +0000 Subject: [PATCH 328/439] Exception#detailed_message is US-ASCII, #full_message BINARY, when ASCII CRuby 4.0's Exception#detailed_message is US-ASCII while it is ASCII, whatever the encoding of the message it is made from (a UTF-8 or a BINARY one), and #full_message is BINARY (rb_error_write into a binary buffer); a message that is not ASCII makes both UTF-8. The prelude's were interpolations and joins of UTF-8 literals, so UTF-8. detailed_message ends with __ir_us_ascii_if_ascii__, a private Kernel method like __ir_binary_if_ascii__ (a US-ASCII copy of an ASCII-only string, anything else as it is), and full_message with __ir_binary_if_ascii__. Checked with Exception_DetailedMessageEncoding1 (output from CRuby 4.0, the same under LANG=C and C.UTF-8), a probe of messages in each encoding, empty and on several lines, highlighted or not, side by side with CRuby under both locales, IronRuby.Tests, and the exception, kernel, module and language specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 22 +++++++++++++++++++ Src/Libraries/Builtins/KernelOps.cs | 14 ++++++++++++ Src/StdLib/ironruby/ruby4.rb | 8 ++++--- 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a7cd652ea..9abe92dfd 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1161,6 +1161,7 @@ public Tests(Driver/*!*/ driver) { DidYouMean_LazyRequire1, NameError_LocalVariables1, NameError_MessageEncoding1, + Exception_DetailedMessageEncoding1, ErrorHighlight_Spots1, ErrorHighlight_Report1, ErrorHighlight_Threads1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index a220366c7..e0645fbe3 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -225,6 +225,28 @@ public void NameError_MessageEncoding1() { "); } + /// + /// Exception#detailed_message is US-ASCII and #full_message BINARY while they are ASCII, whatever the + /// message's encoding, as MRI's; a message that is not ASCII makes them UTF-8. + /// + public void Exception_DetailedMessageEncoding1() { + TestOutput(@" +require 'ruby4' +e = (nil.foo rescue $!) +p e.detailed_message.encoding, e.full_message(highlight: false).encoding +p RuntimeError.new(""x"").detailed_message.encoding, RuntimeError.new(""é"").detailed_message.encoding, RuntimeError.new("""").detailed_message.encoding +p RuntimeError.new(""x"".b).full_message(highlight: false).encoding, RuntimeError.new(""é"").full_message(highlight: false).encoding +", @" +# +# +# +# +# +# +# +"); + } + /// /// NameError#local_variables: those of the scope an undefined local variable or method was named /// in, or NameError.new was called in, which did_you_mean suggests. A struct's missing member diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index 9493e7ac7..96e6de9b4 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1663,6 +1663,20 @@ public static bool IsSameObject(object self, object other) { return copy; } + /// + /// As , for a text MRI makes US-ASCII while it is ASCII (Exception#detailed_message, a copy + /// of the message with the class's name appended). + /// + [RubyMethod("__ir_us_ascii_if_ascii__", RubyMethodAttributes.PrivateInstance)] + public static MutableString/*!*/ UsAsciiIfAscii(object self, [NotNull]MutableString/*!*/ text) { + if (text.Encoding == RubyEncoding.Ascii || !text.IsAscii()) { + return text; + } + var copy = text.Clone(); + copy.ForceEncoding(RubyEncoding.Ascii); + return copy; + } + /// /// MRI's rb_inspect for the prelude: #inspect, escaped when its result is in an /// encoding the output cannot take (see RubyContext.Inspect). diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 542fc8604..dfdbd7ed7 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -12670,7 +12670,7 @@ def detailed_message(highlight: false, **) # MRI singles out RuntimeError: it is what a bare `raise "..."` produces, # so an empty one means nobody ever gave a reason. plain = self.class.equal?(::RuntimeError) ? "unhandled exception" : (name || self.class.to_s) - return highlight ? "\e[1;4m#{plain}\e[m" : plain + return __ir_us_ascii_if_ascii__(highlight ? "\e[1;4m#{plain}\e[m" : plain) end # a multi-line message carries the class on its first line only; a message @@ -12684,7 +12684,8 @@ def detailed_message(highlight: false, **) elsif name first = "#{first} (#{name})" end - lines.unshift(first).join("\n") + # US-ASCII while it is ASCII, whatever the message's encoding, as MRI's (exc_detailed_message) + __ir_us_ascii_if_ascii__(lines.unshift(first).join("\n")) end def full_message(highlight: Exception.to_tty?, order: :top, **options) @@ -12705,7 +12706,8 @@ def full_message(highlight: Exception.to_tty?, order: :top, **options) here = caller(1, 1)[0] fallback = here ? [here.sub(/:in .*\z/, ":in 'full_message'")] : nil Exception.send(:__append_full_message__, result, self, highlight, order, options, fallback, []) - result + # BINARY while it is ASCII, as MRI's (rb_error_write into a binary buffer) + __ir_binary_if_ascii__(result) end def self.__check_highlight__(highlight) From 8bcf9528dc3e37296d4ec2811dd2b14959a7e547 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 19:07:35 +0000 Subject: [PATCH 329/439] IO, File, File::Stat and TracePoint#to_s are Kernel's description Their #to_s is Kernel#to_s in CRuby 4.0 too, rb_any_to_s's BINARY "#". IronRuby's instances of these classes are CLR objects, not Ruby objects, and Kernel#to_s gave a CLR object's ToString as UTF-8: the right text for IO and File (RubyIO.ToString describes itself), but UTF-8, and for File::Stat and TracePoint the wrong text altogether - File.stat(".").to_s was "." and TracePoint#to_s "IronRuby.Builtins.TracePoint". Kernel#to_s has overloads for RubyIO, StatInfo (File::Stat's type exactly, so a System::IO::FileInfo of CLR interop keeps its CLR #to_s) and TracePoint that give RubyUtils.ObjectToMutableString's description, which is BINARY since 9aff9a7. #to_s stays Kernel's (IO.instance_method(:to_s) .owner is Kernel, as in CRuby). Checked with Scenario_DescriptionEncoding4 (output from CRuby 4.0, the same under LANG=C and C.UTF-8), a probe of 34 core #to_s encodings (all as CRuby's but Thread::Backtrace::Location#to_s under LANG=C, which follows the path's encoding in CRuby and is left), and the io, file, tracepoint and Kernel#to_s/#inspect specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 20 ++++++++++++++++++++ Src/Libraries/Builtins/KernelOps.cs | 17 +++++++++++++++++ 3 files changed, 38 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9abe92dfd..e8db7bc72 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -152,6 +152,7 @@ public Tests(Driver/*!*/ driver) { Scenario_DescriptionEncoding1, Scenario_DescriptionEncoding2, Scenario_DescriptionEncoding3, + Scenario_DescriptionEncoding4, Scenario_RubyMethodMissing1, Scenario_RubyMethodMissing2, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 90bf2aacd..2ba9e6c9c 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -136,6 +136,26 @@ p Data.define(:a).new(a: 1).inspect.encoding, Set[1].inspect.encoding, Fiber.new "); } + /// + /// IO, File, File::Stat and TracePoint#to_s are Kernel's, rb_any_to_s's BINARY #<Class:0x...>, as in MRI: + /// not the CLR's ToString ("." for a File::Stat), nor a UTF-8 string. + /// + public void Scenario_DescriptionEncoding4() { + TestOutput(@" +p File.open(IO::NULL).to_s.encoding, File::Stat.new(""."").to_s.encoding, TracePoint.new(:line) { }.to_s.encoding +p File::Stat.new(""."").to_s.match?(/\A#\z/), TracePoint.new(:line) { }.to_s.match?(/\A#\z/) +p File.instance_method(:to_s).owner, File::Stat.instance_method(:to_s).owner +", @" +# +# +# +true +true +Kernel +Kernel +"); + } + /// /// Kernel#inspect of an object met again inside its own inspect: MRI's "#<Foo:0x... ...>". /// diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index 96e6de9b4..ab148ad2b 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1547,6 +1547,23 @@ public static int Hash(object self) { return self == null ? MutableString.CreateEmpty() : MutableString.Create(self.ToString(), RubyEncoding.UTF8); } + // The core classes whose instances are not Ruby objects, and whose #to_s is Kernel's in MRI too: rb_any_to_s's + // "#" (BINARY), not the CLR's ToString - "." for File.stat("."), "IronRuby.Builtins.TracePoint". + [RubyMethod("to_s")] + public static MutableString/*!*/ ToS(RubyContext/*!*/ context, [NotNull]RubyIO/*!*/ self) { + return RubyUtils.ObjectToMutableString(context, self); + } + + [RubyMethod("to_s")] + public static MutableString/*!*/ ToS(RubyContext/*!*/ context, [NotNull]RubyFileOps.StatInfo/*!*/ self) { + return RubyUtils.ObjectToMutableString(context, self); + } + + [RubyMethod("to_s")] + public static MutableString/*!*/ ToS(RubyContext/*!*/ context, [NotNull]TracePoint/*!*/ self) { + return RubyUtils.ObjectToMutableString(context, self); + } + /// /// Returns a string containing a human-readable representation of obj. /// If not overridden, uses the to_s method to generate the string. From cf10c2fc858325423b24a2ae77605bc67494a8a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 19:53:05 +0000 Subject: [PATCH 330/439] Thread::Backtrace::Location's strings in CRuby's encodings CRuby 4.0's Location#label is BINARY when it is made of parts - "Object#m", "K.c", "block in
", "" (rb_sprintf) - and US-ASCII when it is a name as it stands: "
", "", "singleton class", a singleton method's "s". #base_label is US-ASCII (the method's name), but for a class or module body's, BINARY. #to_s is in the path's encoding: US-ASCII under LANG=C, UTF-8 under C.UTF-8. A part that is not ASCII makes any of them UTF-8. The prelude's Location gave the label as Kernel#caller's text had it and built #to_s by interpolation, so all of them were UTF-8 (US-ASCII under LANG=C). #label and #base_label pick the encoding by that rule through __ir_binary_if_ascii__ and __ir_us_ascii_if_ascii__; #to_s takes the path's encoding when it is ASCII. Checked with Backtrace_LocationEncoding1 (output from CRuby 4.0, the same under LANG=C and C.UTF-8), probes of method, class method, block, class and module body, singleton class, rescue, ensure, BEGIN, thread, eval, require, proc, lambda and define_method frames under both locales (the same as CRuby), IronRuby.Tests, and the Thread#backtrace(_locations), Kernel#caller(_locations), exception and language specs under both locales (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 26 +++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 23 +++++++++++++--- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e8db7bc72..fd4b7c4a2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1072,6 +1072,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_CallLine1, Backtrace_InterpolatedLocalLine1, Backtrace_CompiledModuleBody1, + Backtrace_LocationEncoding1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index e0645fbe3..c407c9229 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -580,6 +580,32 @@ show e.backtrace "); } + /// + /// Thread::Backtrace::Location's strings are in MRI's encodings: #label BINARY when it is made of parts + /// ("Object#m", "block in <main>") and US-ASCII when it is a name ("<main>"), #base_label US-ASCII, #to_s in the + /// path's encoding. + /// + public void Backtrace_LocationEncoding1() { + TestOutput(@" +require 'ruby4' +def m = caller_locations(0) +class K; def self.c = caller_locations(0)[0]; end +l = m +b = [1].map { caller_locations(0)[0] }.first +p l[0].label.encoding, l[1].label.encoding, l[0].base_label.encoding, K.c.label.encoding, b.label.encoding, b.base_label.encoding +p l[0].to_s.encoding == l[0].path.encoding, l[1].to_s.encoding == l[1].path.encoding +", @" +# +# +# +# +# +# +true +true +"); + } + /// /// The conversion of an interpolated local variable on a later line of a string (a heredoc's) reports that line, as /// MRI's does: the variable's node carries its declaration's span, so the part's line comes from StringConstructor.PartLines. diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index dfdbd7ed7..83aa2aca9 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -12112,7 +12112,20 @@ def self.limit end unless respond_to?(:limit) class Location - attr_reader :path, :lineno, :label + attr_reader :path, :lineno + + # MRI's label is BINARY when it is made of parts - "Object#m", "block in
", + # "" (rb_sprintf) - and US-ASCII when it is a name as it stands: "
", + # "", a singleton method's "s". One that is not ASCII is UTF-8. + def label + l = @label + return l if l.nil? || !l.ascii_only? + if l.start_with?("block ", " a Location. Both Kernel#caller_locations and @@ -12151,8 +12166,10 @@ def self.__parse__(entry) end end + # in the path's encoding, as MRI's location_to_str makes it, unless the label is not ASCII def to_s - @label ? "#{@path}:#{@lineno}:in '#{@label}'" : "#{@path}:#{@lineno}" + s = @label ? "#{@path}:#{@lineno}:in '#{@label}'" : "#{@path}:#{@lineno}" + s.ascii_only? && @path.is_a?(::String) ? s.force_encoding(@path.encoding) : s end def inspect; to_s.inspect; end From 836135e563017d05ca6e3747c93c9bc4780ac416 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 19:53:06 +0000 Subject: [PATCH 331/439] A backtrace frame with a UTF-8 label is UTF-8 under LANG=C Under LANG=C the path encoding is US-ASCII, and the stack trace builder made each frame with the path's rules: a frame that is not ASCII became the bytes of the whole of it in a BINARY string. A method named in UTF-8 gave "x.rb:1:in 'Object#\xC3\xA9'" as BINARY, where CRuby 4.0 joins the US-ASCII path and the UTF-8 label into a UTF-8 frame. caller_locations then made BINARY Location parts out of it. RubyStackTraceBuilder.CreateFrame(file, line, label) makes a frame whose path is ASCII and whose label is not a UTF-8 string, and makes any other frame as before. Location.__parse__ gives the path of such a frame, ASCII, the path encoding, as CRuby keeps it. Checked with Backtrace_NonAsciiLabelFrame1 (output from CRuby 4.0; it sets Encoding.default_external in the process), probes under LANG=C and C.UTF-8 (the same as CRuby), IronRuby.Tests, and the same specs as the previous commit. Left: under LANG=C __FILE__ is UTF-8 where CRuby's is US-ASCII, and an eval's "(eval at f:1)" file name is UTF-8 or US-ASCII where CRuby's is BINARY, while an eval file name given in UTF-8 comes back BINARY under LANG=C where CRuby keeps its UTF-8. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 18 +++++++++++++++ Src/Ruby/Runtime/RubyStackTraceBuilder.cs | 22 ++++++++++++++----- Src/StdLib/ironruby/ruby4.rb | 5 ++++- 4 files changed, 39 insertions(+), 7 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fd4b7c4a2..b776819dd 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1073,6 +1073,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_InterpolatedLocalLine1, Backtrace_CompiledModuleBody1, Backtrace_LocationEncoding1, + Backtrace_NonAsciiLabelFrame1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index c407c9229..3fde1624f 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -606,6 +606,24 @@ class K; def self.c = caller_locations(0)[0]; end "); } + /// + /// A frame of a method named in UTF-8 is a UTF-8 string under a US-ASCII path encoding (LANG=C), as MRI + /// joins its path and label: not the bytes of the whole frame in a BINARY string. + /// + public void Backtrace_NonAsciiLabelFrame1() { + TestOutput(@" +def é = caller(0)[0] +Encoding.default_external = Encoding::US_ASCII +f = é +Encoding.default_external = Encoding::UTF_8 +p f.encoding, f.valid_encoding?, f.end_with?(""'Object#é'"") +", @" +# +true +true +"); + } + /// /// The conversion of an interpolated local variable on a later line of a string (a heredoc's) reports that line, as /// MRI's does: the variable's node carries its declaration's span, so the part's line comes from StringConstructor.PartLines. diff --git a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs index 7f9e798bf..f3899c7b0 100644 --- a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs +++ b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs @@ -164,7 +164,7 @@ private void AddInterpretedBacktrace(IList frames, int ski } foreach (var deferred in _deferredMethodNames) { if (skipFrames == 0) { - _trace.Add(CreateFrame(FormatFrame(file, line, deferred))); + _trace.Add(CreateFrame(file, line, deferred)); } else { skipFrames--; skippedAny = true; @@ -172,7 +172,7 @@ private void AddInterpretedBacktrace(IList frames, int ski } _deferredMethodNames.Clear(); if (skipFrames == 0) { - _trace.Add(CreateFrame(FormatFrame(file, line, methodName))); + _trace.Add(CreateFrame(file, line, methodName)); } else { skipFrames--; skippedAny = true; @@ -471,11 +471,11 @@ internal RubyStackTraceBuilder(RubyContext/*!*/ context, InterpretedFrame frame, } foreach (var deferred in _deferredMethodNames) { - _trace.Add(CreateFrame(FormatFrame(file, line, deferred))); + _trace.Add(CreateFrame(file, line, deferred)); } _deferredMethodNames.Clear(); - _trace.Add(CreateFrame(FormatFrame(file, line, methodName))); + _trace.Add(CreateFrame(file, line, methodName)); } } @@ -498,6 +498,16 @@ private static int GetLine(DebugInfo/*!*/ debugInfo, Precompiled.PrecompiledFram return RubyContext.TryEncodeRawAsciiPath(frame, _encoding) ?? MutableString.Create(frame, _encoding); } + // The path in the path encoding and a label that is not ASCII in UTF-8, as MRI joins them: a method named in UTF-8 + // gives a UTF-8 frame under LANG=C, where the path encoding is US-ASCII and the frame was the bytes of it all, BINARY. + private MutableString/*!*/ CreateFrame(string file, int line, string label) { + string frame = FormatFrame(file, line, label); + if (label != null && !label.IsAscii() && (file == null || file.IsAscii())) { + return MutableString.Create(frame, RubyEncoding.UTF8); + } + return CreateFrame(frame); + } + private void SetCompiledFrames(Precompiled.PrecompiledFrames.Frame[] frames) { _compiledFrames = frames; _compiledFrameIndex = (frames != null) ? frames.Length - 1 : -1; @@ -798,7 +808,7 @@ private bool AddFrame(string file, int line, string methodName, bool isClrFrame, foreach (var deferred in _deferredMethodNames) { if (skipFrames == 0) { - _trace.Add(CreateFrame(FormatFrame(file, line, deferred))); + _trace.Add(CreateFrame(file, line, deferred)); } else { skipFrames--; skippedAny = true; @@ -810,7 +820,7 @@ private bool AddFrame(string file, int line, string methodName, bool isClrFrame, _libraryRun = 0; if (skipFrames == 0) { - _trace.Add(CreateFrame(FormatFrame(file, line, methodName))); + _trace.Add(CreateFrame(file, line, methodName)); } else { skipFrames--; skippedAny = true; diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 83aa2aca9..a0ad4164e 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -12160,7 +12160,10 @@ def base_label # Thread#backtrace_locations have only the string form to work from. def self.__parse__(entry) if (m = /\A(.*):(\d+)(?::in [`'](.*)')?\z/.match(entry)) - new(m[1], m[2].to_i, m[3]) + path = m[1] + # a frame whose label is not ASCII is UTF-8; its path, ASCII, is in the path encoding, as MRI keeps it + path = path.force_encoding(::Encoding.find("filesystem")) if path.ascii_only? && !entry.ascii_only? + new(path, m[2].to_i, m[3]) else new(entry, 0, nil) end From ce7bfe05f8bd65de15d98d1cacdb22ee7fe53f28 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 19:56:32 +0000 Subject: [PATCH 332/439] Make only a method with a regex literal a match sink (AWFY Towers 4.6% slower than master since round 7) Bisected by Towers' instructions per benchmark (callgrind): round 6's gate 54.21 M, round 7 56.50 M; within round 7 the merge 6251293 (lightmatch, sinkcarrier) is the step, and IR_LIGHT_MATCH_SINK=0 on it gives the instructions back. IsMatchSink made every method that reads no $~ a match sink. In one, each light call by a name of MatchSinkMethods - `[]', `[]=', `===', `index', which Arrays, Hashes and Ranges answer as much as Strings - took the frame's sink (a thread static, a pool slot) and the frame gave it back on return, and the site lost the precompiled light call. Towers' push_disk and pop_disk_from index an Array on every move. The sink is there so that a method with a regex literal given to a $~ method can be a light frame at all; a method without one was light before it. Now a sink needs a regex literal too, and the finder walks a parallel assignment's right side, which the base Walker leaves out (otherwise `a, b = s.match(/x/).captures' lost the sink, and a $~ read there would go unseen). Towers 56.37 -> 53.97 M instructions, Json 131.20 -> 129.11 M, regex-shapes within 0.4% but split +0.8%; by clock Towers went from 1.046 of master to 0.964 (8 rotated rounds). The census shows no light-frame verdict changed. Gate matrices around light frames and regexes PASS in every mode and with the sink off; IronRuby.Tests PASSED. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf3ugNj2V7fGRBP5ScY --- .../Ast/Definitions/MethodDefinition.cs | 20 ++++++++++- Util/perf/LEDGER.md | 35 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index d42df741e..42a98ab35 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -703,6 +703,11 @@ internal static bool IsNeverParkedIterator(string/*!*/ name) { /// where the frame would otherwise make its scope for them on every call and call them again (gap 16 of /// Util/perf/LEDGER.md). A scope the frame makes later gets that $~, for a TracePoint's binding; $~ after the method /// returns is its caller's, as in CRuby. + /// Only a method with a regex literal: the sink is what lets one be a light frame at all (without it a regex literal given to + /// a $~ method keeps the method out), while every method without one was a light frame before it. Made a sink too, every + /// light call it made by one of MatchSinkMethods' names - an Array's `[]' and `[]=', a Range's `===' as much as a String's - + /// took the sink and gave it back on return (a thread static, a pool slot stored and cleared) and lost the precompiled light + /// call (RubyCallAction): AWFY Towers 4.4% more instructions, Json 1.6% (Util/perf/LEDGER.md, perf/towersink). /// private bool IsMatchSink() { if (!LightMatchSinkEnabled || !LightRegexEnabled) { @@ -713,11 +718,24 @@ private bool IsMatchSink() { optional.Walk(finder); } Body.Walk(finder); - return !finder.Found; + return !finder.Found && finder.HasRegex; } private sealed class MatchObserverFinder : Walker { internal bool Found; + // A regex literal in the body: only such a method is made a sink (IsMatchSink) + internal bool HasRegex; + + public override bool Enter(RegularExpression/*!*/ node) { HasRegex = true; return true; } + // the right side too, which Walker.Walk(ParallelAssignmentExpression) leaves out: `a, b = s.match(/x/)...' has a regex + // literal there, and a read of $~ may be there as well + public override bool Enter(ParallelAssignmentExpression/*!*/ node) { + foreach (var value in node.Right) { + if (Found) { break; } + value.Walk(this); + } + return !Found; + } public override bool Enter(RegexMatchReference/*!*/ node) { Found = true; return false; } public override bool Enter(GlobalVariable/*!*/ node) { Found |= !MatchSinkGlobals.Contains(node.Name); return !Found; } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1b9a3ddbe..956981ee6 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,41 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/towersink (bisect, 2026-11-28, not gated) - only a method with a regex literal is a match sink: AWFY + Towers' 2-7% against master since round 7 was perf/lightmatch + perf/sinkcarrier making every light method one** + (on 597b8dc9). + - **The bisect.** Instructions per Towers#benchmark (Util/perf/callgrind/count.sh, AWFY's towers.rb run in place + after 300 warm-up runs; steady to the instruction): master c4719ea 64.40 M, round 6's gate 348fde1 54.21 M, round 7 + 33818f7 56.50 M, round 8 fcbc67b 56.52 M, round 9 597b8dc9 56.37 M. Round 7 moves; within it the step is the merge + 6251293 (claude/perf-dmethjit: lightmatch, sinkcarrier), 54.13 -> 56.50 M, and `IR_LIGHT_MATCH_SINK=0` on it gives + 54.18 M back. (Master counts more instructions than every round, yet ran faster by clock before this fix: + instruction counts are taken with tiered compilation off, and say which round moved, not how far master is.) + - **Why it cost.** MethodDefinition.IsMatchSink made every method whose body reads no $~ a match sink, regex or not. + In one, every light call by a name of MatchSinkMethods - `[]', `[]=', `===', `index', `slice' are an Array's, a + Hash's and a Range's as much as a String's - took the frame's sink as its scope (RubyOps.TakeMatchSink: a + thread-static read, a pool slot taken) and the frame gave it back on return (ReturnMatchSink: `$~' cleared, the + slot stored), and the site lost the precompiled light call (RubyCallAction returns null for a HasMatchSink site). + Towers' push_disk and pop_disk_from do `@piles[pile]' and `@piles[pile] = ...' on every move: TakeMatchSink 9.6 M, + ReturnMatchSink 10.8 M, write barriers 35 M, __tls_get_addr 5.9 M more per section of 30 runs. The sink exists to + let a method with a regex literal given to a $~ method be a light frame at all; a method without one was a light + frame before it. + - **The fix.** IsMatchSink also asks for a regex literal in the body (MatchObserverFinder.HasRegex). The finder now + walks the right side of a parallel assignment, which Walker.Walk(ParallelAssignmentExpression) leaves out: without + that, `a, b = s.match(/x/).captures' and `x, y = s.scan(/re/).last' lost the sink (four stdlib methods went from + light to scope in the census), and a $~ read there would go unseen. Tried first and dropped: choosing the sink by + the receiver at run time (String, Symbol or Regexp by exact class, else the plain light site), 57.3 M - the second + site costs more than the sink. + - **Numbers.** Towers 56.37 -> 53.97 M (the same as IR_LIGHT_MATCH_SINK=0, 0.957); Json 131.20 -> 129.11 M (0.984, + the same as the sink off). regex-shapes (count.sh, N=20000), sink-for-all -> regex-literal methods: every shape + within 0.4% (space 0.988, uri 0.994, kase 0.994) but split 1.008; the sink's gains over the switch off stay + (gsub 0.984, eqt 0.962 of off). Clock, AWFY Towers, 8 rounds pinned to two CPUs, order rotated, medians: master + 84,416 us, fcbc67b 88,292 (1.046 of master), this 81,341 (0.964); minimums 82,335 / 86,429 / 80,054. Census (AWFY, + Src/StdLib, app-shapes, against fcbc67b): 8 methods changed, all round 9's keyword-parameter JIT verdicts; none + from this (0 up, 0 down) once the parallel assignment's right side is walked. + - **Checks**: gate-matrices light-match-sink, regex-light, global-light, light-entry, shared-rule-light, super-light, + literal-block-light, hot-shapes, jit in every mode and with `IR_LIGHT_MATCH_SINK=0`: PASS (base fcbc67b); + IronRuby.Tests (Debug) PASSED. + - **perf/yieldloop (2026-11-28) - a `while` loop with a yield in its body runs in its compiled copy (gap 18, stage 3a of `Docs/jit-resume-deopt.md`)** - not gated. The OSR copy gave up at the YieldCall (`[osr] emitter: node: YieldCall`), so `def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; end` ran its loop generic: about 22 ns From 3d1332fb5aa10ea753f56ba104f195e12e86c18d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 20:42:51 +0000 Subject: [PATCH 333/439] __FILE__ and frame paths in the encoding their source was named in CRuby 4.0 keeps the string a source was named with, and its __FILE__, Kernel#caller's frames and Location#path are in that string's encoding: - an eval told a file name: the name's encoding (BINARY, US-ASCII, or UTF-8 under LANG=C too); - an eval not told one: BINARY, "(eval at file:line)" (rb_sprintf); - the main program: the path encoding (US-ASCII under LANG=C); - `ruby -e`: "-e" is BINARY. IronRuby made __FILE__ UTF-8 always and the frames in the path encoding, so an eval's were UTF-8 (US-ASCII under LANG=C) whatever it was told, and a UTF-8 eval name that is not ASCII gave BINARY frames under LANG=C. RubyContext.GetSourcePathEncoding gives a source's encoding: - one recorded by SetSourcePathEncoding, which Evaluate calls with the file name string, and which records only a name whose encoding is not the default, so a run under C.UTF-8 records nothing for UTF-8 names; - else BINARY for an "(eval at ...)" name; - else the path encoding. __FILE__ of an eval, of the main program and of -e takes it, and so do the frames RubyStackTraceBuilder makes of an eval's code. Required and loaded files are left as they were: CRuby's rules for them under LANG=C depend on whether the path came from $LOAD_PATH (UTF-8) or was given (the path encoding), and IronRuby is CRuby's under C.UTF-8 already. A backtrace of 30,000 raises 11 frames deep takes the same time as before (1.75-1.87 s against 1.81-1.90 s). Checked with Eval_FileNameEncoding1 (output from CRuby 4.0, the same under LANG=C and C.UTF-8), probes of the main program, -e, require, load, and evals with default, UTF-8, non-ASCII, BINARY and US-ASCII names and instance_eval under both locales (the same as CRuby, but for required files' frames under LANG=C), IronRuby.Tests, and the eval/binding/module_eval/instance_eval/__FILE__/caller/exception/ERB/ require/load and language specs under both locales (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/ErrorReportingTests.cs | 21 +++++++++++ Src/Prism/PrismAstBridge.cs | 20 ++++++++++- Src/Ruby/Runtime/RubyContext.cs | 35 +++++++++++++++++++ Src/Ruby/Runtime/RubyStackTraceBuilder.cs | 10 ++++++ Src/Ruby/Runtime/RubyUtils.cs | 4 +++ 6 files changed, 90 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index b776819dd..cce43a1f6 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1074,6 +1074,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_CompiledModuleBody1, Backtrace_LocationEncoding1, Backtrace_NonAsciiLabelFrame1, + Eval_FileNameEncoding1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, diff --git a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index 3fde1624f..28c2c4979 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -624,6 +624,27 @@ public void Backtrace_NonAsciiLabelFrame1() { "); } + /// + /// An eval's __FILE__ and the paths of its frames are in the encoding of the string its file name was + /// given in, as MRI keeps that string, and BINARY for the (eval at file:line) of an eval not told one. + /// + public void Eval_FileNameEncoding1() { + TestOutput(@" +require 'ruby4' +p eval(""__FILE__"").encoding, eval(""caller(0)[0]"").encoding, eval(""caller_locations(0)[0].path"").encoding +p eval(""__FILE__"", nil, ""x.rb"".b).encoding, eval(""caller(0)[0]"", nil, ""y.rb"".b).encoding +p eval(""__FILE__"", nil, ""z.rb"").encoding, eval(""caller(0)[0]"", nil, ""w.rb"".encode(""US-ASCII"")).encoding +", @" +# +# +# +# +# +# +# +"); + } + /// /// The conversion of an interpolated local variable on a later line of a string (a heredoc's) reports that line, as /// MRI's does: the variable's node carries its declaration's span, so the part's line comes from StringConstructor.PartLines. diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 8a33b6741..d29377494 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -34,6 +34,9 @@ public sealed class PrismAstBridge { // and backtraces inside the eval line up with the code it came from. private int _startLine = 1; private readonly RubyEncoding/*!*/ _encoding; + + // __FILE__'s encoding when the path is ASCII (see Parse) + private RubyEncoding/*!*/ _fileEncoding; private readonly Stack/*!*/ _scopes = new Stack(); private int _tempCounter; private SourceUnit _sourceUnit; @@ -249,6 +252,20 @@ private static SourceUnitTree ParseText(string/*!*/ code, string path, List/*!*/ _sourcePathEncodings = + new ConcurrentDictionary(StringComparer.Ordinal); + + /// + /// The encoding of the string a source was named with, which MRI keeps for its __FILE__ and the paths of its frames: + /// an eval's file name keeps the given string's, and the "(eval at file:line)" of an eval not told one is BINARY + /// (rb_sprintf); any other path is in the path encoding (US-ASCII under LANG=C). + /// + public RubyEncoding/*!*/ GetSourcePathEncoding(string path) { + RubyEncoding encoding; + if (path != null && _sourcePathEncodings.TryGetValue(path, out encoding)) { + return encoding; + } + return GetDefaultSourcePathEncoding(path); + } + + private RubyEncoding/*!*/ GetDefaultSourcePathEncoding(string path) { + if (path != null && (path.StartsWith("(eval at ", StringComparison.Ordinal) || path == "(eval)")) { + return RubyEncoding.Binary; + } + return GetPathEncoding(); + } + + /// Records the encoding of the string an eval was told its file name in (). + public void SetSourcePathEncoding(string/*!*/ path, RubyEncoding/*!*/ encoding) { + if (encoding == GetDefaultSourcePathEncoding(path)) { + RubyEncoding removed; + _sourcePathEncodings.TryRemove(path, out removed); + } else { + _sourcePathEncodings[path] = encoding; + } + } + public RubyEncoding/*!*/ GetPathEncoding() { // On everything but Windows the filesystem encoding follows the default external // encoding, so Encoding.default_external= moves it too. diff --git a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs index f3899c7b0..4a7e9b2fc 100644 --- a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs +++ b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs @@ -505,6 +505,16 @@ private static int GetLine(DebugInfo/*!*/ debugInfo, Precompiled.PrecompiledFram if (label != null && !label.IsAscii() && (file == null || file.IsAscii())) { return MutableString.Create(frame, RubyEncoding.UTF8); } + // a frame of an eval is in the encoding of its file name (RubyContext.GetSourcePathEncoding): BINARY for + // "(eval at file:line)", the given string's for a name eval was told + if (file != null) { + string path = file; + RubyUtils.DecodeEvalLineOffset(ref path); + RubyEncoding encoding = _context.GetSourcePathEncoding(path); + if (encoding != _encoding && (frame.IsAscii() || encoding == RubyEncoding.UTF8)) { + return MutableString.Create(frame, encoding); + } + } return CreateFrame(frame); } diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index a19672e07..1027150ef 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1634,6 +1634,10 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop // MRI's parser_prepare does (eval "\xEF\xBB\xBF..." from a binary or US-ASCII file). options.EvalSourceEncoding = StartsWithUtf8Bom(code) ? RubyEncoding.UTF8 : code.Encoding; string path = file != null ? file.ConvertToString() : DefaultEvalFileName(context); + if (file != null) { + // __FILE__ and the frames of the code are in the encoding the name was given in, as MRI keeps the string + context.SetSourcePathEncoding(path, file.Encoding); + } string sourcePath = (line <= 0) ? EncodeEvalLineOffset(path, line - 1) : path; byte[] bytes = code.ToByteArray(); From c1bc7503dc7b061a16e2df099f78163346633dbc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:31:45 +0000 Subject: [PATCH 334/439] Raise ThreadError, not NoMemoryError, when a thread cannot be created The CLR reports a thread the system refuses to create (pthread_create's EAGAIN, as under a low RLIMIT_NOFILE or RLIMIT_NPROC) as an OutOfMemoryException, which IronRuby maps to NoMemoryError. That gets past every rescue, and test-unit passes it through as fatal: CRuby's TestRequire#test_loading_fifo_fd_leak (setrlimit(RLIMIT_NOFILE, 50), then Thread.start in a loop) brought it back from its child and ended the whole test_require run without a summary, so none of its 52 tests were counted. MRI's thread_create_core raises ThreadError ("can't create Thread: ...") when the thread cannot be made. Thread.new/start/fork and a Ractor's main thread now do the same, and drop the half-made thread's registration. Checked: test_require runs to its summary again (52 tests, 33 passing). No IronRuby.Tests case: the condition needs a process-wide rlimit, which would take the test host down with it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/Libraries/Builtins/ThreadOps.cs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 2cc06088e..141096021 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -1454,7 +1454,7 @@ internal sealed class ThreadStarter { info.Group = starter.Group = new ThreadGroup(); ractor.MainThread = result; starter.Body = body; - result.Start(); + StartOrRaise(result); return result; } @@ -1469,7 +1469,22 @@ private static void Start(Thread/*!*/ thread, ThreadStarter/*!*/ starter, BlockP startRoutine.IsThreadRoot = true; starter.StartRoutine = startRoutine; starter.Args = args; - thread.Start(); + StartOrRaise(thread); + } + + /// + /// The CLR reports a thread the system would not create (pthread_create's EAGAIN under a + /// low RLIMIT_NOFILE or RLIMIT_NPROC, say) as an OutOfMemoryException, which is Ruby's + /// NoMemoryError and gets past every rescue. MRI's thread_create_core raises a ThreadError + /// ("can't create Thread: ...") instead. + /// + private static void StartOrRaise(Thread/*!*/ thread) { + try { + thread.Start(); + } catch (OutOfMemoryException) { + RubyThreadInfo.Unregister(RubyThreadInfo.FromThread(thread)); + throw new ThreadError("can't create Thread: Resource temporarily unavailable"); + } } // Keep ThreadStarter out of the context's lifetime-long termination callback closure. From 4d7eaaed39e9367f2a268c49e3c5b142221522f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:31:45 +0000 Subject: [PATCH 335/439] IO::Buffer: every value type, set_values, size_of, dup, copy and hexdump as in MRI The prelude's IO::Buffer knew only :U8 to :U64, :f32 and :f64, and read the floats and the lower-case names wrongly: MRI's lower-case types are little-endian and its upper-case ones big-endian (io_buffer.c's IO_BUFFER_DECLARE_TYPE), with :u128/:U128/:s128/:S128, :F32 and :F64 too. set_values and IO::Buffer.size_of did not exist, #each_byte yielded offsets, #dup shared the read-only memory of a buffer made by IO::Buffer.for, so dup.and!/copy raised AccessError, #copy and #clear took no offset/length the way MRI does, #hexdump took no arguments, and a buffer over a String frozen since was a FrozenError rather than AccessError. Rewritten after io_buffer.c: a table of the 22 types; the conversions of NUM2UINT/NUM2INT/NUM2ULL/NUM2LL/NUM2DBL and rb_numeric_to_(u)int128 with their RangeError and TypeError messages; the range checked, the value converted (which can run #to_int that frees the buffer) and the buffer checked again, under the buffer's lock; get_values/set_values/values/each/ each_byte with MRI's offset/count rules and messages; initialize_copy; copy/clear/hexdump(offset, length, width) with io_buffer_validate_range; the masks refusing an empty or overlapping mask (MaskError) and a freed one (InvalidatedError); io_buffer_validate_for_writing's order and messages; get_string's "Offset can't be negative!"; IO::Buffer.string checking the size before the block and IO::Buffer.map a non-IO. Checked against CRuby 4.0.10: CRuby's test_io_buffer goes from 22 failures and errors to none (86 of 87 passing, 1 skip); ruby/spec core/io/buffer and the io-buffer matrix unchanged in every mode. New IronRuby.Tests: IOBuffer_Values1, IOBuffer_CopyAndMasks1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 2 + Src/IronRuby.Tests/Runtime/IoTests.cs | 96 ++++++ Src/StdLib/ironruby/ruby4.rb | 478 +++++++++++++++++++++----- 3 files changed, 485 insertions(+), 91 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e8db7bc72..682b22b35 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1465,6 +1465,8 @@ public Tests(Driver/*!*/ driver) { Continuation_CrossThread1, RbConfig_ExecutableExts1, IOBuffer_ExperimentalWarning1, + IOBuffer_Values1, + IOBuffer_CopyAndMasks1, Array_Cycle1, Range_Recursive1, Array_JoinRecursive1, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index 4a7f18e00..c6eb5c91d 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -1133,6 +1133,102 @@ def t(label) utf-32le universal read: ""ab\ncd\n\n\xC3\xA9\nf\xE0\xA8\x80\xC4\x8A\n\n\ng"" utf-32le universal readlines: [""ab\n"", ""cd\n"", ""\n"", ""\xC3\xA9\n"", ""f\xE0\xA8\x80\xC4\x8A\n"", ""\n"", ""\n"", ""g""] utf-32le universal each_char: ""ab\ncd\n\n\xC3\xA9\nf\xE0\xA8\x80\xC4\x8A\n\n\ng"" +"); + } + + /// + /// MRI's IO::Buffer value types: lower case little-endian, upper case big-endian, the 128-bit ones, and + /// the conversions and errors of IO_BUFFER_DECLARE_TYPE (CRuby's TestIOBuffer#test_get_set_values, #test_128_bit_integers). + /// + public void IOBuffer_Values1() { + TestOutput(@" +require 'ruby4' +Warning[:experimental] = false +b = IO::Buffer.new(32) +p IO::Buffer.size_of(:u128), IO::Buffer.size_of([:U8, :f64]) +p b.set_value(:u16, 0, 0x1234), b.get_value(:U16, 0) +p b.set_values([:s32, :F32, :S8], 2, [-2, 1.5, -1]) +p b.get_values([:s32, :F32, :S8], 2) +b.set_value(:U128, 16, 2**127 + 5) +p b.get_value(:U128, 16), b.get_value(:S128, 16) +p b.values(:U8, 0, 4), b.each(:u16, 0, 2).to_a, b.each_byte(0, 3).to_a +[[:U8, 2**40], [:u128, -1], [:s64, 2**63], [:X8, 0], [""U8"", 0]].each do |t, v| + begin + b.set_value(t, 0, v) + rescue => e + puts ""#{e.class}: #{e.message}"" + end +end +begin + b.get_value(:u32, 30) +rescue => e + puts ""#{e.class}: #{e.message}"" +end +", @" +16 +9 +2 +13330 +11 +[-2, 1.5, -1] +170141183460469231731687303715884105733 +-170141183460469231731687303715884105723 +[52, 18, 254, 255] +[[0, 4660], [2, 65534]] +[52, 18, 254] +RangeError: integer 1099511627776 too big to convert to 'unsigned int' +RangeError: negative integer cannot be converted to unsigned 128-bit integer +RangeError: bignum too big to convert into 'long long' +ArgumentError: Invalid type name! +TypeError: wrong argument type String (expected Symbol) +ArgumentError: Type extends beyond end of buffer! (offset=30 > size=32) +"); + } + + /// + /// IO::Buffer#dup makes a writable internal copy, #copy moves bytes as memmove does, #clear and #hexdump take an + /// offset and length, and the in-place masks refuse an empty or overlapping mask (CRuby's TestIOBuffer). + /// + public void IOBuffer_CopyAndMasks1() { + TestOutput(@" +require 'ruby4' +Warning[:experimental] = false +buf = IO::Buffer.for('0123456789').dup +p buf.readonly?, buf.copy(buf, 3, 7), buf.get_string +p buf.copy(buf, 0, 7, 3), buf.get_string +buf.clear(0x141, 1, 2) +p buf.get_string +puts buf.hexdump(0, 10, 4) +[-> { buf.hexdump(0, 1, 0) }, -> { buf.get_string(-1) }, -> { buf.clear(0, 11) }, + -> { buf.and!(IO::Buffer.new(0)) }, -> { buf.xor!(buf.slice(2, 2)) }].each do |f| + f.call +rescue => e + puts ""#{e.class}: #{e.message}"" +end +s = +'Hello' +t = IO::Buffer.for(s, &:transfer) +s.freeze +begin + t.set_string('J') +rescue => e + puts ""#{e.class}: #{e.message}"" +end +", @" +false +7 +""0120123456"" +7 +""0123456456"" +""0AA3456456"" +0x00000000 30 41 41 33 0AA3 +0x00000004 34 35 36 34 4564 +0x00000008 35 36 56 +ArgumentError: Width must be at least 1! +ArgumentError: Offset can't be negative! +ArgumentError: The given offset is bigger than the buffer size! +IO::Buffer::MaskError: Zero-length mask given! +IO::Buffer::MaskError: Mask overlaps source buffer! +IO::Buffer::AccessError: Buffer is not writable! "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index dfdbd7ed7..b5f8b0f24 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -10493,7 +10493,6 @@ def self.for(string) # Yields a buffer of the given size and answers what was written into it. def self.string(length) - ::Kernel.raise(::LocalJumpError, "no block given") unless block_given? # The size goes to rb_str_new, whose parameter is a long rather than the # size_t the rest of the buffer API takes. unless length.is_a?(::Integer) @@ -10506,6 +10505,8 @@ def self.string(length) ::Kernel.raise(::ArgumentError, "negative string size (or size too big)") end string = "\0".b * length + # The string is made before the block is yielded to, so a bad size is reported first. + ::Kernel.raise(::LocalJumpError, "no block given") unless block_given? buffer = allocate buffer.__take_over__(string, 0, length, EXTERNAL, string) begin @@ -10541,6 +10542,10 @@ def self.map(file, size = nil, offset = 0, flags = 0) # A shared mapping asks mmap for PROT_WRITE, which the kernel refuses on a # descriptor that was not opened for writing; MAP_PRIVATE and a read-only # mapping do not need it. + # The descriptor is asked for only once the sizes are settled (rb_io_descriptor). + unless file.is_a?(::IO) + ::Kernel.raise(::TypeError, "expected IO or #fileno, #{__class_name__(file)} given") + end if (flags & (PRIVATE | READONLY)) == 0 && !file.__writable__? ::Kernel.raise(::Errno::EACCES, "io_buffer_map_file:mmap") end @@ -10583,6 +10588,27 @@ def initialize(size = DEFAULT_SIZE, *flags) end end + # dup and clone make an internal copy of the bytes (rb_io_buffer_initialize_copy): the copy + # is writable, owns its memory and is sized like a new buffer of its size. + def initialize_copy(source) + super + data = source.get_string + @offset = 0 + @source = nil + @locked_source = false + @address = nil + if data.empty? + @data = nil + @size = 0 + @flags = 0 + else + @data = data + @size = data.bytesize + @flags = self.class.__flags_for_size__(@size) + end + self + end + # The "address" a buffer shows in #to_s. There is no real one here, so the object # identity stands in for it - until #transfer hands the memory to another buffer. def __address__ @@ -10721,10 +10747,13 @@ def locked? end # A lock stops the buffer itself from moving; reads and writes through it - # carry on. + # carry on. io_buffer_validate_for_writing: a buffer over a String that has been frozen since + # is no more writable than a read-only one, and that is checked before the validity. def __check_writable__ - __check__ - ::Kernel.raise(AccessError, "Buffer is not writable!") if readonly? + if readonly? || (!@source.nil? && @source.frozen?) + ::Kernel.raise(AccessError, "Buffer is not writable!") + end + ::Kernel.raise(InvalidatedError, "Buffer is invalid!") unless valid? end private :__check_writable__ @@ -10833,22 +10862,14 @@ def slice(offset = 0, length = nil) other end - def get_string(offset = 0, length = nil, encoding = ::Encoding::BINARY) - __check__ - offset = self.class.__offset_arg__(offset) - length = @size - offset if length.nil? - length = self.class.__offset_arg__(length) - if offset < 0 || length < 0 || offset + length > @size - ::Kernel.raise(::ArgumentError, "Specified offset+length is bigger than the buffer size!") - end - if @data.nil? - result = "".dup - else - result = @data.byteslice(@offset + offset, length).to_s - result = result.dup if result.frozen? - end - result.force_encoding(encoding) if result.respond_to?(:force_encoding) - result + # io_buffer_get_string: the encoding is looked up (which can run #to_str) before the buffer + # is checked. + def get_string(offset = nil, length = nil, encoding = ::Encoding::BINARY) + offset, length = __offset_length__(offset, length) + encoding = ::Encoding.find(encoding) unless encoding.is_a?(::Encoding) + __validate_range__(offset, length) + result = @data.nil? ? "".b : @data.byteslice(@offset + offset, length) + result.force_encoding(encoding) end alias :to_str :get_string @@ -10870,90 +10891,332 @@ def set_string(string, offset = 0, length = nil, source_offset = 0) source.bytesize end - def clear(value = 0, offset = 0, length = nil) + # clear(value = 0, [offset, [length]]): the byte goes through NUM2UINT, so it can be any + # Integer an unsigned int holds, and only its low byte is written. + def clear(value = 0, offset = nil, length = nil) + value = __convert_value__(:U8, value) & 0xff + offset, length = __offset_length__(offset, length) __check_writable__ - length = @size - offset if length.nil? - set_string([value & 0xff].pack("C") * length, offset) + __validate_range__(offset, length) + __unlocked__ { @data.bytesplice(@offset + offset, length, [value].pack("C") * length) } if length > 0 self end - def __value_size__(type) - case type - when :U8, :S8 then 1 - when :U16, :S16 then 2 - when :U32, :S32, :f32 then 4 - when :U64, :S64, :f64 then 8 - else ::Kernel.raise(::ArgumentError, "Invalid type name!") + # MRI's data types (io_buffer.c): lower case is little-endian, upper case big-endian (network + # order), and the 8-bit ones are both. Each is [size, pack directive]; the 128-bit ones have + # no directive and are put together from their two 64-bit halves. + TYPES__ = { + U8: [1, "C"], S8: [1, "c"], + u16: [2, "S<"], U16: [2, "S>"], s16: [2, "s<"], S16: [2, "s>"], + u32: [4, "L<"], U32: [4, "L>"], s32: [4, "l<"], S32: [4, "l>"], + u64: [8, "Q<"], U64: [8, "Q>"], s64: [8, "q<"], S64: [8, "q>"], + u128: [16, nil], U128: [16, nil], s128: [16, nil], S128: [16, nil], + f32: [4, "e"], F32: [4, "g"], f64: [8, "E"], F64: [8, "G"], + }.freeze + __hide_constant__ :TYPES__ + + # RB_SYM2ID, then io_buffer_buffer_type_size. + def self.__type__(type) + unless type.is_a?(::Symbol) + ::Kernel.raise(::TypeError, "wrong argument type #{__class_name__(type)} (expected Symbol)") + end + TYPES__[type] || ::Kernel.raise(::ArgumentError, "Invalid type name!") + end + + def self.size_of(type) + if type.is_a?(::Array) + type.sum { |t| __type__(t)[0] } + else + __type__(type)[0] end end - private :__value_size__ - def __directive__(type) + # io_buffer_extract_offset, io_buffer_extract_length and io_buffer_extract_count: a negative + # one is refused by name before it is converted. + def __extract__(value, what) + value = self.class.__offset_arg__(value) + ::Kernel.raise(::ArgumentError, "#{what} can't be negative!") if value < 0 + value + end + private :__extract__ + + # io_buffer_extract_offset_length: a missing length runs to the end of the buffer, which an + # offset past the end leaves nothing of. + def __offset_length__(offset, length) + offset = offset.nil? ? 0 : __extract__(offset, "Offset") + if length.nil? + if offset > @size + ::Kernel.raise(::ArgumentError, "The given offset is bigger than the buffer size!") + end + length = @size - offset + else + length = __extract__(length, "Length") + end + [offset, length] + end + private :__offset_length__ + + def __validate_range__(offset, length) + __check__ + if offset + length > @size + ::Kernel.raise(::ArgumentError, "Specified offset+length is bigger than the buffer size!") + end + end + private :__validate_range__ + + def __validate_type__(offset, size) + if offset + size > @size + ::Kernel.raise(::ArgumentError, "Type extends beyond end of buffer! (offset=#{offset} > size=#{@size})") + end + end + private :__validate_type__ + + # The value conversions of IO_BUFFER_DECLARE_TYPE: NUM2UINT and NUM2INT for the types up to + # 32 bits (whatever an int holds is accepted and cut down to the type's width), NUM2ULL and + # NUM2LL for the 64-bit ones, rb_numeric_to_(u)int128 - an Integer and nothing else - for the + # 128-bit ones and NUM2DBL for the floats. + def __convert_value__(type, value) case type - when :U8 then "C" - when :S8 then "c" - when :U16 then "S>" - when :S16 then "s>" - when :U32 then "L>" - when :S32 then "l>" - when :U64 then "Q>" - when :S64 then "q>" - when :f32 then "g" - when :f64 then "G" - else ::Kernel.raise(::ArgumentError, "Invalid type name!") + when :f32, :F32, :f64, :F64 + case value + when ::Float then value + when ::Integer, ::Rational then value.to_f + when ::String then ::Kernel.raise(::TypeError, "no implicit conversion to float from string") + when nil, true, false + ::Kernel.raise(::TypeError, "no implicit conversion to float from #{::IO::Buffer.__class_name__(value)}") + else + unless value.respond_to?(:to_f) + ::Kernel.raise(::TypeError, "can't convert #{value.class} into Float") + end + value.to_f + end + when :u128, :U128, :s128, :S128 + ::Kernel.raise(::TypeError, "not an integer") unless value.is_a?(::Integer) + if type == :u128 || type == :U128 + if value < 0 + ::Kernel.raise(::RangeError, "negative integer cannot be converted to unsigned 128-bit integer") + end + if value >= 0x1_0000_0000_0000_0000_0000_0000_0000_0000 + ::Kernel.raise(::RangeError, "bignum too big to convert into 'unsigned 128-bit integer'") + end + elsif value >= 0x8000_0000_0000_0000_0000_0000_0000_0000 || value < -0x8000_0000_0000_0000_0000_0000_0000_0000 + ::Kernel.raise(::RangeError, "bignum too big to convert into 'signed 128-bit integer'") + end + value + else + wide = type == :u64 || type == :U64 || type == :s64 || type == :S64 + unsigned = type == :U8 || type == :u16 || type == :U16 || type == :u32 || type == :U32 || + type == :u64 || type == :U64 + if value.is_a?(::Float) + low, high = wide && unsigned ? [-0x8000_0000_0000_0000, 0x1_0000_0000_0000_0000] : + [-0x8000_0000_0000_0000, 0x8000_0000_0000_0000] + unless value >= low && value < high + range = !wide ? "integer" : unsigned ? "unsigned long long" : "long long" + ::Kernel.raise(::RangeError, "float #{format("%-.10g", value)} out of range of #{range}") + end + value = value.to_i + elsif !value.is_a?(::Integer) + unless value.respond_to?(:to_int) + ::Kernel.raise(::TypeError, "no implicit conversion of #{::IO::Buffer.__class_name__(value)} into Integer") + end + value = value.to_int + end + if wide + if unsigned ? (value >= 0x1_0000_0000_0000_0000 || value <= -0x1_0000_0000_0000_0000) : + (value >= 0x8000_0000_0000_0000 || value < -0x8000_0000_0000_0000) + ::Kernel.raise(::RangeError, "bignum too big to convert into '#{unsigned ? "unsigned " : ""}long long'") + end + else + if unsigned ? (value >= 0x1_0000_0000_0000_0000 || value <= -0x1_0000_0000_0000_0000) : + (value >= 0x8000_0000_0000_0000 || value < -0x8000_0000_0000_0000) + ::Kernel.raise(::RangeError, "bignum too big to convert into '#{unsigned ? "unsigned " : ""}long'") + end + c_type = unsigned ? "unsigned int" : "int" + if value > (unsigned ? 0xffff_ffff : 0x7fff_ffff) + ::Kernel.raise(::RangeError, "integer #{value} too big to convert to '#{c_type}'") + end + if value < -0x8000_0000 + ::Kernel.raise(::RangeError, "integer #{value} too small to convert to '#{c_type}'") + end + end + value + end + end + private :__convert_value__ + + # io_buffer_read_: offset is already known not to be negative. + def __get_value__(type, offset) + size, directive = self.class.__type__(type) + __validate_type__(offset, size) + bytes = @data.byteslice(@offset + offset, size) + return bytes.unpack1(directive) if directive + if type == :u128 || type == :s128 + low, high = bytes.unpack("QQ>") + end + value = (high << 64) | low + value -= 0x1_0000_0000_0000_0000_0000_0000_0000_0000 if (type == :s128 || type == :S128) && high >= 0x8000_0000_0000_0000 + value + end + private :__get_value__ + + # io_buffer_write_: the range is checked, the value converted - which runs Ruby code + # that can free or shrink the buffer - and then the buffer is checked again. Answers the + # offset after the value. + def __set_value__(type, offset, value) + size, directive = self.class.__type__(type) + __check_writable__ + __validate_type__(offset, size) + value = __convert_value__(type, value) + __check_writable__ + __validate_type__(offset, size) + if directive + bytes = [value].pack(directive) + else + value &= 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff + low = value & 0xffff_ffff_ffff_ffff + high = value >> 64 + bytes = (type == :u128 || type == :s128) ? [low, high].pack("QQ>") + end + at = @offset + offset + __unlocked__ { @data.bytesplice(at, size, bytes) } + offset + size + end + private :__set_value__ + + # MRI locks the buffer while it writes (io_buffer_try_lock), so a conversion that tries to + # free, resize or transfer it is refused. + def __while_locked__ + return yield if locked? + @flags |= LOCKED + begin + yield + ensure + @flags &= ~LOCKED end end - private :__directive__ + private :__while_locked__ def get_value(type, offset) - get_string(offset, __value_size__(type)).unpack(__directive__(type))[0] + offset = __extract__(offset, "Offset") + __check__ + __get_value__(type, offset) end def set_value(type, offset, value) - set_string([value].pack(__directive__(type)), offset) + __check_writable__ + offset = __extract__(offset, "Offset") + __while_locked__ { __set_value__(type, offset, value) } end - def get_values(types, offset = 0) - at = offset + def get_values(types, offset) + offset = __extract__(offset, "Offset") + __check__ + ::Kernel.raise(::ArgumentError, "Argument buffer_types should be an array!") unless types.is_a?(::Array) types.map do |type| - v = get_value(type, at) - at += __value_size__(type) - v + value = __get_value__(type, offset) + offset += self.class.__type__(type)[0] + value end end - def each(type = :U8, offset = 0, count = nil) - return ::Enumerator.new { |y| each(type, offset, count) { |i, v| y << [i, v] } } unless block_given? - step = __value_size__(type) - at = offset - n = count || ((@size - offset) / step) - n.times do - yield at, get_value(type, at) - at += step + def set_values(types, offset, values) + __check_writable__ + ::Kernel.raise(::ArgumentError, "Argument buffer_types should be an array!") unless types.is_a?(::Array) + offset = __extract__(offset, "Offset") + ::Kernel.raise(::ArgumentError, "Argument values should be an array!") unless values.is_a?(::Array) + if types.size != values.size + ::Kernel.raise(::ArgumentError, "Argument buffer_types and values should have the same length!") end - self + __while_locked__ do + types.each_with_index { |type, i| offset = __set_value__(type, offset, values[i]) } + end + offset + end + + # io_buffer_extract_offset_count: without a count, as many values as fit after the offset. + def __offset_count__(type, offset, count) + offset = offset.nil? ? 0 : __extract__(offset, "Offset") + if count.nil? + if offset > @size + ::Kernel.raise(::ArgumentError, "The given offset is bigger than the buffer size!") + end + count = (@size - offset) / self.class.__type__(type)[0] + else + count = __extract__(count, "Count") + end + [offset, count] end + private :__offset_count__ - def each_byte(offset = 0, count = nil) - return ::Enumerator.new { |y| each_byte(offset, count) { |i, v| y << [i, v] } } unless block_given? - each(:U8, offset, count) { |i, v| yield i, v } + def each(type = :U8, offset = nil, count = nil) + # MRI's RETURN_ENUMERATOR gives these no size function, so their #size is nil. + return to_enum(:each, type, offset, count) { nil } unless block_given? + __check__ + offset, count = __offset_count__(type, offset, count) + count.times do + at = offset + value = __get_value__(type, offset) + offset += self.class.__type__(type)[0] + yield at, value + end self end - def values(type = :U8, offset = 0, count = nil) - result = [] - each(type, offset, count) { |_, v| result << v } - result + def values(type = :U8, offset = nil, count = nil) + __check__ + offset, count = __offset_count__(type, offset, count) + ::Array.new(count) do + value = __get_value__(type, offset) + offset += self.class.__type__(type)[0] + value + end end - # Offset, sixteen bytes in hex padded out to a fixed width, then the same - # bytes as text with anything unprintable shown as a dot - MRI's layout. - def hexdump - get_string.bytes.each_slice(16).each_with_index.map { |row, i| - hex = row.map { |b| format("%02x", b) }.join(" ") + # Each byte on its own, without its offset. + def each_byte(offset = nil, count = nil) + return to_enum(:each_byte, offset, count) { nil } unless block_given? + __check__ + offset, count = __offset_count__(:U8, offset, count) + if offset + count > @size + ::Kernel.raise(::ArgumentError, "Specified offset+count is bigger than the buffer size!") + end + count.times { |i| yield @data.getbyte(@offset + offset + i) } + self + end + + # hexdump([offset, [length, [width]]]): offset, sixteen bytes (or width) in hex padded out to + # a fixed width, then the same bytes as text with anything unprintable shown as a dot - + # io_buffer_hexdump's layout. A null buffer has nothing to dump. + HEXDUMP_MAXIMUM_WIDTH__ = 1024 + __hide_constant__ :HEXDUMP_MAXIMUM_WIDTH__ + + def hexdump(offset = nil, length = nil, width = nil) + offset, length = __offset_length__(offset, length) + if width.nil? + width = 16 + else + width = self.class.__integer_arg__(width) if !width.is_a?(::Integer) + ::Kernel.raise(::ArgumentError, "Width can't be negative!") if width < 0 + ::Kernel.raise(::ArgumentError, "Width must be at least 1!") if width < 1 + if width > HEXDUMP_MAXIMUM_WIDTH__ + ::Kernel.raise(::ArgumentError, "Width must be at most #{HEXDUMP_MAXIMUM_WIDTH__}!") + end + end + __validate_range__(offset, length) + return nil if @data.nil? + bytes = @data.byteslice(@offset + offset, length).bytes + lines = [] + at = offset + bytes.each_slice(width) do |row| + hex = row.map { |b| format(" %02x", b) }.join + hex << " " * (width - row.size) text = row.map { |b| (b >= 0x20 && b < 0x7f) ? b.chr : "." }.join - format("0x%08x %-47s %s", i * 16, hex, text) - }.join("\n") + lines << format("0x%08x %s %s", at, hex, text) + at += width + end + lines.join("\n") end def to_s @@ -10989,16 +11252,16 @@ def ==(other) other.is_a?(::IO::Buffer) && get_string == other.get_string end - # The copying operators also want a Buffer. The result is the size of the - # receiver: a shorter mask repeats over it, and a longer one is cut off. + # The copying operators (io_buffer_and and the rest): the result is the size of the + # receiver, and the mask repeats over it. def __binary_op__(other, op) __require_buffer__(other) - a = get_string - b = other.get_string - bytes = a.bytes - unless b.empty? - bytes.each_index { |i| bytes[i] = bytes[i].__send__(op, b.getbyte(i % b.bytesize)) & 0xff } - end + __check__ + other.__send__(:__check__) + mask = other.get_string + ::Kernel.raise(MaskError, "Zero-length mask given!") if mask.empty? + bytes = get_string.bytes + bytes.each_index { |i| bytes[i] = bytes[i].__send__(op, mask.getbyte(i % mask.bytesize)) & 0xff } result = ::IO::Buffer.new(bytes.size) result.set_string(bytes.pack("C*")) result @@ -11018,15 +11281,25 @@ def __require_buffer__(other) end private :__require_buffer__ + # io_buffer_overlaps: two windows onto the same memory, one starting inside the other. + def __overlaps__(other) + data = other.__data__ + return false if @data.nil? || !@data.equal?(data) + a, b = @offset, other.__offset__ + a, b, size = a > b ? [b, a, other.__size__] : [a, b, @size] + b < a + size + end + private :__overlaps__ + def __in_place_op__(other, op) - __check_writable__ __require_buffer__(other) - a = get_string - b = other.get_string - bytes = a.bytes - unless b.empty? - bytes.each_index { |i| bytes[i] = bytes[i].__send__(op, b.getbyte(i % b.bytesize)) & 0xff } - end + ::Kernel.raise(MaskError, "Zero-length mask given!") if other.size == 0 + ::Kernel.raise(MaskError, "Mask overlaps source buffer!") if __overlaps__(other) + __check_writable__ + other.__send__(:__check__) + mask = other.get_string + bytes = get_string.bytes + bytes.each_index { |i| bytes[i] = bytes[i].__send__(op, mask.getbyte(i % mask.bytesize)) & 0xff } set_string(bytes.pack("C*")) self end @@ -11076,9 +11349,32 @@ def pwrite(io, from, length = nil, offset = 0) io.pwrite(get_string(offset, size - offset), from) end - def copy(source, offset = 0, length = nil, source_offset = 0) + # io_buffer_copy_from: the source's bytes are taken first, so a copy within one buffer + # behaves like memmove whichever way the two ranges overlap. + def copy(source, offset = nil, length = nil, source_offset = nil) __require_buffer__(source) - set_string(source.get_string, offset, length, source_offset) + bytes = source.get_string + offset = offset.nil? ? 0 : __extract__(offset, "Offset") + if source_offset.nil? + source_offset = 0 + else + source_offset = __extract__(source_offset, "Offset") + if source_offset > bytes.bytesize + ::Kernel.raise(::ArgumentError, "The given source offset is bigger than the source itself!") + end + end + length = length.nil? ? bytes.bytesize - source_offset : __extract__(length, "Length") + __check_writable__ + __validate_range__(offset, length) + if source_offset + length > bytes.bytesize + ::Kernel.raise(::ArgumentError, "The computed source range exceeds the size of the source buffer!") + end + if length > 0 + piece = bytes.byteslice(source_offset, length) + at = @offset + offset + __unlocked__ { @data.bytesplice(at, length, piece) } + end + length end def &(other) From 62f2cf69ebbd0f27a3c0a183ad665fcb774b8709 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:31:55 +0000 Subject: [PATCH 336/439] String#[]= with a Regexp raises "string modified" when the conversion shortened the string str[/re/] = obj converts obj with #to_str after the match, and that can change the string the match was made in. IronRuby spliced the old match range into the shortened string and let .NET's ArgumentOutOfRangeException out as a RangeError ("length ('-3') must be a non-negative value"). MRI's rb_str_subpat_set checks the range against the string's length once the value is converted and raises RuntimeError "string modified"; both the numbered and the named-group forms now do. Checked against CRuby 4.0.10: TestString and TestString2 #test_ASET_string_modified_during_conversion pass; ruby/spec core/string/element_set_spec unchanged. New IronRuby.Tests: MutableString_RegexpSetModified1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/MutableStringTests.cs | 40 +++++++++++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 15 ++++++- 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 682b22b35..d8ca4381a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -63,6 +63,7 @@ public Tests(Driver/*!*/ driver) { MutableString_SliceAppend1, MutableString_SipHash1, MutableString_WideBrokenLength1, + MutableString_RegexpSetModified1, RubyArray_Ctors, RubyArray_Basic, RubyArray_Add, diff --git a/Src/IronRuby.Tests/Runtime/MutableStringTests.cs b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs index 5ec040eeb..41567210d 100644 --- a/Src/IronRuby.Tests/Runtime/MutableStringTests.cs +++ b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs @@ -2113,6 +2113,46 @@ public void MutableString_WideBrokenLength1() { [""\n\x00"", ""x""] ""a\x00"" ""a\x00\n\x00\n\x00\r\x00"" +"); + } + + /// + /// str[/re/] = obj: when obj#to_str shortens the string the match was made in, MRI's rb_str_subpat_set raises + /// "string modified" instead of splicing past its end (CRuby's TestString#test_ASET_string_modified_during_conversion). + /// + public void MutableString_RegexpSetModified1() { + TestOutput(@" +str = ""hello"" * 3 +obj = Object.new +obj.define_singleton_method(:to_str) do + str.replace("""") + ""x"" +end +begin + str[/l+/] = obj +rescue => e + p e +end +named = +""hello"" +cut = Object.new +cut.define_singleton_method(:to_str) do + named.replace(""he"") + ""x"" +end +begin + named[/(?l+)/, ""v""] = cut +rescue => e + p e +end +s = +""hello"" +plain = Object.new +def plain.to_str = ""L"" +s[/l+/] = plain +p s +", @" +# +# +""heLo"" "); } } diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 52e85170b..439ceed4b 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1562,6 +1562,17 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index } /// Replaces the CLR range [start, start + count) with value. + // str[/re/] = obj: obj#to_str runs after the match, and can shorten the string the match + // was made in. MRI's rb_str_subpat_set checks the matched range against the string's + // length once the conversion is done and raises "string modified" rather than splice + // past the end. + private static MutableString/*!*/ ReplaceMatchedRange(MutableString/*!*/ self, int start, int count, MutableString/*!*/ value) { + if (start + count > self.Length) { + throw RubyExceptions.CreateRuntimeError("string modified"); + } + return ReplaceClrRange(self, start, count, value); + } + private static MutableString/*!*/ ReplaceClrRange(MutableString/*!*/ self, int start, int count, MutableString/*!*/ value) { self.Replace(start, count, value); return value; @@ -1660,7 +1671,7 @@ private static MutableString ReplaceSubstring(ConversionStorage/* } var replacement = value as MutableString ?? Protocols.CastToString(stringCast, value); - return ReplaceClrRange(self, match.GetNamedGroupStart(groupName), match.GetNamedGroupLength(groupName), replacement); + return ReplaceMatchedRange(self, match.GetNamedGroupStart(groupName), match.GetNamedGroupLength(groupName), replacement); } // The match of str[/re/] = s is a match like any other: it sets $~ (and its failure too). @@ -1695,7 +1706,7 @@ public static MutableString ReplaceSubstring(ConversionStorage/*! var replacement = value as MutableString ?? Protocols.CastToString(stringCast, value); - return ReplaceClrRange(self, match.GetGroupStart(groupIndex), match.GetGroupLength(groupIndex), replacement); + return ReplaceMatchedRange(self, match.GetGroupStart(groupIndex), match.GetGroupLength(groupIndex), replacement); } #endregion From e8ab6e7f3953fd384e7745d52c7f03262ecbf224 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:31:56 +0000 Subject: [PATCH 337/439] String#each_line raises "string modified" when the block changes the separator MRI's rb_str_enumerate_lines yields each line as it finds it and, after a line that ended at the separator, checks with str_mod_check that the block left the separator alone (pointer and length), raising RuntimeError "string modified" otherwise. The prelude's each_line splits the lines up front, so a block that cleared the separator went on unnoticed. The lines are still split first; after each one but a trailing line with no separator after it, the separator's length is compared with what it was. Paragraph mode and the default separator, which no block can change, are not checked, as in MRI. Checked against CRuby 4.0.10: TestString and TestString2 #test_each_line_modified_separator pass; ruby/spec core/string/each_line and lines unchanged, the string-methods and wide-lines matrices the same in every mode. New IronRuby.Tests: MutableString_EachLineModifiedSeparator1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/MutableStringTests.cs | 29 +++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 21 +++++++++++--- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index d8ca4381a..5a9be272d 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -64,6 +64,7 @@ public Tests(Driver/*!*/ driver) { MutableString_SipHash1, MutableString_WideBrokenLength1, MutableString_RegexpSetModified1, + MutableString_EachLineModifiedSeparator1, RubyArray_Ctors, RubyArray_Basic, RubyArray_Add, diff --git a/Src/IronRuby.Tests/Runtime/MutableStringTests.cs b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs index 41567210d..bd99f5d17 100644 --- a/Src/IronRuby.Tests/Runtime/MutableStringTests.cs +++ b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs @@ -2153,6 +2153,35 @@ p s # # ""heLo"" +"); + } + + /// + /// String#each_line checks after each line that ended at the separator that the block left the separator's length + /// alone (str_mod_check in rb_str_enumerate_lines; CRuby's TestString#test_each_line_modified_separator). + /// + public void MutableString_EachLineModifiedSeparator1() { + TestOutput(@" +require 'ruby4' +sep = +""--"" +begin + ""a--b--c"".each_line(sep) { |l| p l; sep.clear } +rescue => e + p e +end +sep = +""--"" +""a--b"".each_line(sep) { |l| p l; sep << ""x"" if l == ""b"" } +sep = +""--"" +""a--b"".each_line(sep, chomp: true) { |l| p l; sep.replace(""++"") if l == ""b"" } +p ""a--b--"".each_line(""--"").to_a +", @" +""a--"" +# +""a--"" +""b"" +""a"" +""b"" +[""a--"", ""b--""] "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index b5f8b0f24..d6d99ac51 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -6976,11 +6976,24 @@ def each_line(*args, chomp: (no_chomp = true; false), &block) # of the cost of a short string's each_line (URI.decode_www_form splits on "&"). if no_chomp && args.size == 1 && (sep = args[0]).is_a?(::String) && !sep.empty? && encoding.ascii_compatible? && (empty? || ::Encoding.compatible?(self, sep)) - __ir_lines__(sep).each(&block) - return self + lines = __ir_lines__(sep) + else + lines = __ir_split_lines__(args, chomp) + sep = args.size == 1 && args[0].is_a?(::String) && !args[0].empty? ? args[0] : nil + end + return lines.each(&block) && self if sep.nil? || lines.empty? + # MRI yields each line as it finds it, and after a line that ended at the separator checks + # that the block left the separator alone (str_mod_check in rb_str_enumerate_lines). The + # lines are split up front here, so the check is made against the separator's length; a + # last line with no separator after it is not checked. + checked = ::Encoding.compatible?(self, sep) && end_with?(sep) ? lines.size : lines.size - 1 + length = sep.bytesize + i = 0 + while i < lines.size + block.call(lines[i]) + ::Kernel.raise(::RuntimeError, "string modified") if i < checked && sep.bytesize != length + i += 1 end - lines = __ir_split_lines__(args, chomp) - lines.each(&block) self end From f545bc810158d95f9617b78107e39cd0151e982c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:32:11 +0000 Subject: [PATCH 338/439] defined? answers "expression" for parentheses that held more than one statement defined? (;x) and defined? (x;) are "expression" in CRuby: prism flags the parentheses MULTIPLE_STATEMENTS even when all but one statement is empty, and prism_compile's defined_expr0 answers DEFINED_EXPR for such parentheses before it would unwrap a lone statement. The bridge unwrapped them and asked about x, giving nil. Unparen now stops at flagged parentheses and Defined answers "expression" for them without running the body (its locals are still mapped); empty parentheses, defined?((;)), stay "nil". Checked against CRuby 4.0.10: TestDefined#test_defined_paren_void_stmts passes; ruby/spec language/defined_spec and the eval-defined matrix unchanged. New IronRuby.Tests: DefinedOperator_Parens1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/DefinedTests.cs | 24 ++++++++++++++++++++++ Src/Prism/PrismAstBridge.cs | 12 +++++++++++ 3 files changed, 37 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 5a9be272d..9e6c7af91 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -993,6 +993,7 @@ public Tests(Driver/*!*/ driver) { DefinedOperator_Yield1, DefinedOperator_Locals1, DefinedOperator_Super1, + DefinedOperator_Parens1, Scenario_ModuleOps_Methods, InstanceMethods_NotInherited1, diff --git a/Src/IronRuby.Tests/Runtime/DefinedTests.cs b/Src/IronRuby.Tests/Runtime/DefinedTests.cs index bb40f9118..4a1eb04bd 100644 --- a/Src/IronRuby.Tests/Runtime/DefinedTests.cs +++ b/Src/IronRuby.Tests/Runtime/DefinedTests.cs @@ -342,6 +342,30 @@ puts D.new.bar super +"); + } + + /// + /// Parentheses that held more than one statement, all but one of them empty included, are an "expression" to + /// defined?; empty ones are "nil" (CRuby's TestDefined#test_defined_paren_void_stmts). + /// + public void DefinedOperator_Parens1() { + TestOutput(@" +p defined? (;x) +p defined? (x;) +p defined?((;)) +p defined?((x)) +p defined?((;;String)) +p defined?((a = 1; a)) +p a +", @" +""expression"" +""expression"" +""nil"" +nil +""expression"" +""expression"" +nil "); } } diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 8a33b6741..adbc83cfb 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -1472,6 +1472,9 @@ private RubyRegexOptions RegexOptions(Pm.PmNode/*!*/ node) { while (true) { Pm.PmNode body; if (node is Pm.ParenthesesNode parens) { + // Parentheses that held more than one statement stay, even when all but one of + // them were empty, as in (;x): see Defined. + if ((parens.Flags & Pm.ParenthesesNodeFlags.MultipleStatements) != 0) return node; body = parens.Body; } else if (node is Pm.StatementsNode) { body = node; @@ -1565,6 +1568,15 @@ private static StringLiteralMutability StringMutability(Pm.PmNode/*!*/ node) { var node = Unparen(value); switch (node) { + // Parentheses that held more than one statement are an "expression" without a look + // inside, even when all but one were empty: defined?((;x)) (prism_compile's + // defined_expr0 tests PM_PARENTHESES_NODE_FLAGS_MULTIPLE_STATEMENTS before it + // unwraps a lone statement; empty ones, (;), are "nil" before that). The body is not run, but + // its locals are still mapped. + case Pm.ParenthesesNode parens when parens.Body != null && (parens.Flags & Pm.ParenthesesNodeFlags.MultipleStatements) != 0: + Expr(parens); + return FrozenString("expression", span); + // Since 3.4 every op-assignment answers "assignment" no matter what the target is. // `x ||= v` lowers to a SimpleAssignmentExpression whose "||" operation makes the // 1.9 AST report "expression" instead. From 20bdf7a7c8704effa3bb903bc59558d74aa37c58 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:32:11 +0000 Subject: [PATCH 339/439] __method__ and __callee__ are nil in a class body inside a method RubyScope.GetCurrentMethodName walked out of a class or module body to the method around it, so eval("class C; __method__; end") in a method, or a class << self in a method body, answered that method's name. A class body is a frame of its own in CRuby, with no method: nil. A block still answers the method it was written in, module_eval blocks included. Checked against CRuby 4.0.10: TestMethod#test_callee passes; ruby/spec core/kernel/__method__ unchanged. New IronRuby.Tests: CurrentMethod_ClassBody1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 27 +++++++++++++++++++++++ Src/Ruby/Runtime/RubyScope.cs | 3 +++ 3 files changed, 31 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9e6c7af91..ffbf01573 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1296,6 +1296,7 @@ public Tests(Driver/*!*/ driver) { MethodArity_PreludeMethods1, MethodDef_SymbolInBody1, KeywordsOmitted1, + CurrentMethod_ClassBody1, ToIntegerConversion1, Kernel_IntegerFloat1, Kernel_FloatOptions1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index a57a4dc72..3f51a460b 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1987,6 +1987,33 @@ alias am2 dm :am [:dm2, :am3] [:am, [:dm2, :am3]] +"); + } + + /// + /// __method__ in a class body is nil, even in a class opened by an eval in a method or a class << self in a method + /// body; a block keeps its method (CRuby's TestMethod#test_callee). + /// + public void CurrentMethod_ClassBody1() { + TestOutput(@" +def m1 + eval(""class TestCallee; __method__; end"") +end +def m2 + class << self; __method__; end +end +def m3 + eval(""class TestCallee; [1].map { __method__ }; end"") +end +def m4 + String.class_eval { __method__ } +end +p m1, m2, m3, m4 +", @" +nil +nil +[nil] +:m4 "); } } diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 788a7d4eb..938b3a1af 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1044,6 +1044,9 @@ public string GetCurrentMethodName(bool callee) { var proc = ((RubyBlockScope)scope).BlockFlowControl.Proc; return (callee ? proc.CalleeName : null) ?? proc.Method.DefinitionName; + // A class or module body is outside any method, even one opened in a method's + // eval or a `class << self` in a method body: CRuby's frame there has no method. + case ScopeKind.Module: case ScopeKind.TopLevel: return null; } From 3ae981ace766b05be4e5850eb5195f77c5ecf151 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:32:11 +0000 Subject: [PATCH 340/439] MatchData#initialize_copy raises FrozenError on a frozen receiver MRI's match_init_copy starts with rb_check_frozen; IronRuby overwrote a frozen MatchData. It now raises FrozenError ("can't modify frozen MatchData: ...") first. Checked against CRuby 4.0.10: TestObject#test_bad_initialize_copy passes; ruby/spec core/matchdata unchanged. New IronRuby.Tests: MatchDataInitializeCopyFrozen1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/CloningTests.cs | 21 +++++++++++++++++++++ Src/Libraries/Builtins/MatchDataOps.cs | 6 +++++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ffbf01573..e9f39b60f 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1334,6 +1334,7 @@ public Tests(Driver/*!*/ driver) { Dup1, CloneConstantLookup1, ModuleCopyBeforeInitializeCopy1, + MatchDataInitializeCopyFrozen1, Structs1, MetaModules1, MetaModulesDuplication1, diff --git a/Src/IronRuby.Tests/Runtime/CloningTests.cs b/Src/IronRuby.Tests/Runtime/CloningTests.cs index 837f7b10d..af5011fa5 100644 --- a/Src/IronRuby.Tests/Runtime/CloningTests.cs +++ b/Src/IronRuby.Tests/Runtime/CloningTests.cs @@ -227,6 +227,27 @@ p c.send(:initialize_copy, e).equal?(c), c.instance_methods(false), (Module.new. true [] # +"); + } + + /// + /// MatchData#initialize_copy refuses a frozen receiver (match_init_copy's rb_check_frozen; CRuby's + /// TestObject#test_bad_initialize_copy). + /// + public void MatchDataInitializeCopyFrozen1() { + TestOutput(@" +m = /.*/.match(""foo"") +c = m.dup.freeze +begin + c.instance_eval { initialize_copy(m) } +rescue => e + p e.class +end +d = m.dup +p d.instance_eval { initialize_copy(/o+/.match(""xoo"")) }[0] +", @" +FrozenError +""oo"" "); } } diff --git a/Src/Libraries/Builtins/MatchDataOps.cs b/Src/Libraries/Builtins/MatchDataOps.cs index 95a7252fd..ca8484d0e 100644 --- a/Src/Libraries/Builtins/MatchDataOps.cs +++ b/Src/Libraries/Builtins/MatchDataOps.cs @@ -27,7 +27,11 @@ public static class MatchDataOps { #region Private Instance Methods [RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)] - public static MatchData/*!*/ InitializeCopy(MatchData/*!*/ self, [NotNull]MatchData/*!*/ other) { + public static MatchData/*!*/ InitializeCopy(RubyContext/*!*/ context, MatchData/*!*/ self, [NotNull]MatchData/*!*/ other) { + // match_init_copy starts with rb_check_frozen: a frozen MatchData is not overwritten. + if (context.IsObjectFrozen(self)) { + throw RubyExceptions.CreateObjectFrozenError(context, self); + } self.InitializeFrom(other); return self; } From 032c90a0fc3ea34397b01fd958e04d3ea4700bc6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:32:11 +0000 Subject: [PATCH 341/439] eval refuses code in an ASCII-incompatible encoding eval, instance_eval, module_eval and Binding#eval of a UTF-16 or UTF-32 string parsed its bytes as if they were ASCII and ran whatever came of it (eval("__ENCODING__".encode("utf-16be")) answered nil). MRI's parser reads only an ASCII-compatible source (must_be_ascii_compatible) and raises ArgumentError "invalid source encoding"; RubyUtils.Evaluate now does the same before compiling. Checked against CRuby 4.0.10: TestEval#test_eval_ascii_incompatible passes; ruby/spec core/kernel/eval, basicobject/instance_eval, module/class_eval and binding/eval unchanged; the eval, eval-locals and eval-defined matrices the same or better in every mode. New IronRuby.Tests: EvalSourceEncoding1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/EvalTests.cs | 28 +++++++++++++++++++++++++ Src/Ruby/Runtime/RubyUtils.cs | 6 ++++++ 3 files changed, 35 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e9f39b60f..0c85e6e23 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1380,6 +1380,7 @@ public Tests(Driver/*!*/ driver) { ModuleEvalString2, InstanceEvalString2, ModuleInstanceEvalString3, + EvalSourceEncoding1, AliasInModuleEval1, MethodAliasInModuleEval1, SuperInModuleEval1, diff --git a/Src/IronRuby.Tests/Runtime/EvalTests.cs b/Src/IronRuby.Tests/Runtime/EvalTests.cs index 80084a811..b3bda24b2 100644 --- a/Src/IronRuby.Tests/Runtime/EvalTests.cs +++ b/Src/IronRuby.Tests/Runtime/EvalTests.cs @@ -673,5 +673,33 @@ def foo 1 1"); } + + /// + /// eval of code in an ASCII-incompatible encoding is an ArgumentError, as MRI's parser has it + /// (must_be_ascii_compatible; CRuby's TestEval#test_eval_ascii_incompatible). + /// + public void EvalSourceEncoding1() { + TestOutput(@" +[""UTF-16BE"", ""UTF-16LE"", ""UTF-32BE"", ""UTF-32LE""].each do |enc| + eval(""__ENCODING__"".encode(enc)) +rescue ArgumentError => e + p e +end +begin + Object.new.instance_eval(""1"".encode(""UTF-16LE"")) +rescue ArgumentError => e + p e +end +p eval(""__ENCODING__"".encode(""Shift_JIS"")), eval(""1 + 1"".b) +", @" +# +# +# +# +# +# +2 +"); + } } } diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index a19672e07..abf81b27a 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1618,6 +1618,12 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop RubyModule lexicalConstantModule, MutableString file, int line) { Assert.NotNull(code, targetScope); + // MRI's parser reads only an ASCII-compatible source (must_be_ascii_compatible): code in + // UTF-16 or UTF-32 is refused rather than parsed as the bytes it happens to be. + if (!code.Encoding.IsAsciiIdentity) { + throw RubyExceptions.CreateArgumentError("invalid source encoding"); + } + // the code can make a Proc, Binding or method over the scope (a block scope is then not reused) targetScope.MarkCaptured(); From d99c099f1959d17a974de2654f59dd14a3ac4149 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:36:47 +0000 Subject: [PATCH 342/439] A module's singleton class describes itself by the module's #inspect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CRuby 4.0's rb_mod_to_s writes the singleton class of a module as "#". A module whose #inspect is its own shows it: `class Foo; def self.inspect = "I"; end` gives Foo.singleton_class.to_s "#" (ActiveRecord models define self.inspect). A name the default external encoding cannot take comes out escaped, "#" under LANG=C, US-ASCII. IronRuby wrote the module's name as it is, so neither showed. Module#to_s/#inspect of the singleton class of a module now appends RubyContext.Inspect of the module, and is US-ASCII while it is ASCII as before. The singleton class of an object that is not a module, and everything else that uses RubyModule.GetDisplayName - NoMethodError's "for class #" among it, which CRuby also writes with #inspect - are left as they were: GetDisplayName runs where Ruby code must not. Checked with SingletonClass_ToS1 (output from CRuby 4.0; it sets Encoding.default_external in the process), a probe of named, anonymous, nested, core, non-ASCII and overridden (#to_s, #inspect giving a String, an Integer, raising) modules under LANG=C and C.UTF-8 (the same as CRuby), IronRuby.Tests, and the module, class, singleton_class, method, unboundmethod and Kernel#inspect/#to_s specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/SingletonTests.cs | 26 ++++++++++++++++++++ Src/Libraries/Builtins/ModuleOps.cs | 13 ++++++++++ 3 files changed, 40 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index cce43a1f6..71fcbc4e5 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -912,6 +912,7 @@ public Tests(Driver/*!*/ driver) { MethodDefinitionInModuleEval1A, MainSingleton1, + SingletonClass_ToS1, MainSingleton2, Singletons1A, Singletons1B, diff --git a/Src/IronRuby.Tests/Runtime/SingletonTests.cs b/Src/IronRuby.Tests/Runtime/SingletonTests.cs index f99b347d7..a4c4325e5 100644 --- a/Src/IronRuby.Tests/Runtime/SingletonTests.cs +++ b/Src/IronRuby.Tests/Runtime/SingletonTests.cs @@ -16,6 +16,32 @@ using System; namespace IronRuby.Tests { public partial class Tests { + /// + /// A module's singleton class describes itself as "#<Class:" + the module's #inspect + ">", as MRI's rb_mod_to_s + /// does: an #inspect override shows, and a name the default external encoding cannot take is escaped. + /// + public void SingletonClass_ToS1() { + TestOutput(@" +class Foo; def self.to_s = ""X""; def self.inspect = ""I""; end +class Café; end +p Foo.singleton_class.to_s, Foo.singleton_class.singleton_class.inspect, String.singleton_class.to_s, String.singleton_class.to_s.encoding +p Café.singleton_class.to_s, Café.singleton_class.to_s.encoding +Encoding.default_external = Encoding::US_ASCII +s = Café.singleton_class.to_s +Encoding.default_external = Encoding::UTF_8 +p s, s.encoding +", @" +""#"" +""#>"" +""#"" +# +""#"" +# +""#"" +# +"); + } + public void MainSingleton1() { AssertOutput(delegate() { CompilerTest(@" diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index ec15946b2..22cc0ee4d 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -1984,6 +1984,19 @@ public static bool PublicMethodDefined(ConversionStorage/*!*/ stringCast [RubyMethod("to_s")] [RubyMethod("inspect")] public static MutableString/*!*/ ToS(RubyContext/*!*/ context, RubyModule/*!*/ self) { + // MRI's rb_mod_to_s writes the singleton class of a module as "#": the module's own + // #inspect shows (an ActiveRecord model's, "#" for `def self.inspect = "I"'), and a name the default external + // encoding cannot take comes out escaped ("#" under LANG=C), US-ASCII + var singleton = self as RubyClass; + if (singleton != null && singleton.IsSingletonClass && singleton.SingletonClassOf is RubyModule attached) { + var result = MutableString.CreateMutable(RubyEncoding.Ascii).Append("#'); + if (result.IsAscii() && result.Encoding != RubyEncoding.Ascii) { + result.ForceEncoding(RubyEncoding.Ascii); + } + return result; + } return self.GetDisplayName(context, false); } From 5c1568e9e6c4d20599a041f0820954da41762ee1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:58:37 +0000 Subject: [PATCH 343/439] cruby-test: baseline after the third round of test/ruby fixes A full sweep of CRuby v4.0.10's test/ruby on net10.0 Release: 6,657 tests passing (6,614 before this round, on the same machine), and one file without a summary (test_iseq, a non-goal) instead of two: test_require runs to its end again. About fourteen assert_no_memory_leak(rss: true) tests in test_hash, test_string, test_regexp and test_settracefunc now fail where they passed: IronRuby's RSS ratio in them is about 2.0 against a limit of 2.0, and a longer prelude (the IO::Buffer rewrite; 500 lines of unused methods do the same) moves a startup GC so that the starting RSS is lower and noisier. Their behaviour did not change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 4 +- Util/cruby-test/baseline.txt | 126 +++++++++++++++++------------------ 2 files changed, 65 insertions(+), 65 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index 722e4cb01..a4c016942 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby -Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 53 clean, 86 with -failures, 3 without a summary; 10,325 tests counted, 6,342 passing. (The first sweep, of v4.0.9: +Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 66 clean, 75 with +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,657 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 506d31e8e..957126992 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -1,21 +1,21 @@ -test_alias 18 tests 1 failures 2 errors 0 skips +test_alias 18 tests 1 failures 0 errors 0 skips test_allocation 76 tests 0 failures 76 errors 0 skips -test_argf 73 tests 19 failures 1 errors 0 skips +test_argf 73 tests 18 failures 1 errors 1 skips test_arithmetic_sequence 37 tests 0 failures 0 errors 0 skips test_arity 3 tests 0 failures 0 errors 0 skips test_array 493 tests 0 failures 16 errors 2 skips test_assignment 29 tests 0 failures 0 errors 0 skips -test_ast 2666 tests 10 failures 2656 errors 0 skips -test_autoload 27 tests 1 failures 3 errors 0 skips +test_ast 2666 tests 11 failures 2654 errors 0 skips +test_autoload 27 tests 1 failures 1 errors 0 skips test_backtrace 31 tests 4 failures 0 errors 0 skips test_basicinstructions 26 tests 0 failures 0 errors 0 skips test_beginendblock 16 tests 4 failures 1 errors 0 skips test_bignum 73 tests 1 failures 2 errors 0 skips -test_box 65 tests 4 failures 25 errors 31 skips +test_box 65 tests 5 failures 22 errors 31 skips test_call 65 tests 2 failures 0 errors 0 skips test_case 6 tests 0 failures 0 errors 0 skips -test_class 62 tests 2 failures 3 errors 0 skips -test_clone 7 tests 0 failures 1 errors 0 skips +test_class 62 tests 2 failures 1 errors 0 skips +test_clone 7 tests 0 failures 0 errors 0 skips test_comparable 11 tests 0 failures 0 errors 0 skips test_compile_prism 182 tests 1 failures 179 errors 0 skips test_complex 57 tests 0 failures 0 errors 0 skips @@ -23,123 +23,123 @@ test_complex2 2 tests 0 failures 0 errors 0 sk test_complexrational 2 tests 0 failures 0 errors 0 skips test_condition 1 tests 0 failures 0 errors 0 skips test_const 5 tests 0 failures 0 errors 0 skips -test_continuation 7 tests 0 failures 5 errors 0 skips +test_continuation 7 tests 0 failures 3 errors 0 skips test_data 16 tests 0 failures 0 errors 0 skips test_default_gems 1 tests 0 failures 0 errors 0 skips -test_defined 39 tests 4 failures 1 errors 0 skips -test_dir 39 tests 1 failures 1 errors 0 skips -test_dir_m17n 22 tests 7 failures 5 errors 0 skips +test_defined 39 tests 3 failures 1 errors 0 skips +test_dir 38 tests 0 failures 2 errors 0 skips +test_dir_m17n 22 tests 7 failures 0 errors 0 skips test_dup 6 tests 0 failures 0 errors 0 skips -test_econv 85 tests 4 failures 2 errors 0 skips -test_encoding 15 tests 0 failures 4 errors 0 skips -test_enum 90 tests 2 failures 3 errors 0 skips -test_enumerator 70 tests 0 failures 1 errors 0 skips -test_env 94 tests 0 failures 11 errors 0 skips -test_eval 40 tests 3 failures 2 errors 0 skips -test_exception 101 tests 13 failures 7 errors 0 skips -test_fiber 35 tests 3 failures 1 errors 2 skips +test_econv 85 tests 4 failures 1 errors 0 skips +test_encoding 15 tests 1 failures 0 errors 0 skips +test_enum 90 tests 2 failures 0 errors 0 skips +test_enumerator 70 tests 0 failures 0 errors 0 skips +test_env 94 tests 9 failures 0 errors 1 skips +test_eval 40 tests 3 failures 0 errors 0 skips +test_exception 101 tests 14 failures 1 errors 0 skips +test_fiber 35 tests 2 failures 0 errors 2 skips test_file 80 tests 0 failures 23 errors 1 skips -test_file_exhaustive 125 tests 0 failures 2 errors 0 skips +test_file_exhaustive 125 tests 0 failures 0 errors 1 skips test_fixnum 39 tests 0 failures 0 errors 0 skips test_flip 5 tests 1 failures 0 errors 0 skips -test_float 63 tests 0 failures 1 errors 0 skips +test_float 63 tests 0 failures 0 errors 0 skips test_fnmatch 15 tests 3 failures 0 errors 0 skips test_frozen 6 tests 0 failures 0 errors 0 skips test_frozen_error 5 tests 1 failures 0 errors 0 skips -test_gc 53 tests 12 failures 11 errors 2 skips -test_gc_compact 28 tests 7 failures 7 errors 7 skips -test_hash 298 tests 3 failures 14 errors 0 skips +test_gc 53 tests 13 failures 7 errors 2 skips +test_gc_compact 28 tests 9 failures 4 errors 7 skips +test_hash 298 tests 8 failures 0 errors 0 skips test_ifunless 1 tests 0 failures 0 errors 0 skips test_inlinecache 3 tests 0 failures 0 errors 0 skips test_insns_leaf 2 tests 0 failures 0 errors 0 skips -test_integer 38 tests 0 failures 2 errors 0 skips +test_integer 38 tests 0 failures 0 errors 0 skips test_integer_comb 41 tests 0 failures 0 errors 0 skips -test_io 252 tests 11 failures 12 errors 4 skips -test_io_buffer 87 tests 9 failures 13 errors 1 skips -test_io_m17n 160 tests 14 failures 3 errors 0 skips +test_io 252 tests 11 failures 7 errors 5 skips +test_io_buffer 87 tests 0 failures 0 errors 1 skips +test_io_m17n 160 tests 13 failures 2 errors 0 skips test_io_timeout 4 tests 0 failures 0 errors 4 skips test_iseq NO SUMMARY (exit 1) test_iterator 32 tests 0 failures 0 errors 0 skips test_key_error 6 tests 0 failures 0 errors 0 skips -test_keyword 115 tests 4 failures 5 errors 0 skips +test_keyword 115 tests 4 failures 2 errors 0 skips test_lambda 27 tests 1 failures 0 errors 0 skips -test_lazy_enumerator 64 tests 0 failures 1 errors 0 skips +test_lazy_enumerator 64 tests 0 failures 0 errors 0 skips test_literal 29 tests 1 failures 1 errors 0 skips -test_m17n 127 tests 4 failures 0 errors 1 skips -test_m17n_comb 82 tests 1 failures 0 errors 0 skips +test_m17n 127 tests 2 failures 0 errors 1 skips +test_m17n_comb 82 tests 0 failures 0 errors 0 skips test_marshal 234 tests 8 failures 3 errors 0 skips test_math 34 tests 0 failures 0 errors 0 skips test_memory_view 0 tests 0 failures 0 errors 0 skips test_metaclass 1 tests 0 failures 0 errors 0 skips -test_method 99 tests 4 failures 5 errors 0 skips +test_method 99 tests 5 failures 0 errors 0 skips test_method_cache 4 tests 0 failures 0 errors 0 skips test_mixed_unicode_escapes 1 tests 1 failures 0 errors 0 skips -test_module 195 tests 6 failures 14 errors 0 skips -test_name_error 11 tests 0 failures 1 errors 0 skips +test_module 195 tests 6 failures 8 errors 0 skips +test_name_error 11 tests 0 failures 0 errors 0 skips test_nomethod_error 10 tests 0 failures 0 errors 0 skips test_not 2 tests 0 failures 0 errors 0 skips test_numeric 27 tests 1 failures 0 errors 0 skips -test_object 67 tests 5 failures 1 errors 0 skips -test_object_id 132 tests 0 failures 2 errors 0 skips -test_objectspace 37 tests 10 failures 9 errors 0 skips +test_object 67 tests 4 failures 0 errors 0 skips +test_object_id 132 tests 0 failures 0 errors 0 skips +test_objectspace 37 tests 10 failures 8 errors 0 skips test_optimization 90 tests 47 failures 23 errors 0 skips test_pack 56 tests 2 failures 0 errors 0 skips -test_parse 107 tests 17 failures 1 errors 0 skips +test_parse 107 tests 16 failures 1 errors 0 skips test_path 6 tests 0 failures 0 errors 0 skips test_pattern_matching 30 tests 0 failures 0 errors 0 skips test_pipe 12 tests 0 failures 2 errors 0 skips test_primitive 25 tests 0 failures 0 errors 0 skips -test_proc 120 tests 3 failures 6 errors 0 skips -test_process 142 tests 28 failures 19 errors 1 skips -test_ractor 19 tests 3 failures 8 errors 0 skips -test_rand 41 tests 0 failures 1 errors 0 skips +test_proc 120 tests 3 failures 1 errors 0 skips +test_process 141 tests 25 failures 18 errors 1 skips +test_ractor 19 tests 10 failures 0 errors 0 skips +test_rand 41 tests 0 failures 0 errors 0 skips test_random_formatter 26 tests 0 failures 0 errors 0 skips test_range 67 tests 0 failures 0 errors 0 skips test_rational 52 tests 0 failures 0 errors 0 skips test_rational2 1 tests 0 failures 0 errors 0 skips test_readpartial 4 tests 1 failures 0 errors 0 skips -test_refinement 122 tests 6 failures 8 errors 0 skips -test_regexp 167 tests 32 failures 12 errors 0 skips -test_require 52 tests 9 failures 14 errors 0 skips +test_refinement 122 tests 6 failures 2 errors 0 skips +test_regexp 167 tests 32 failures 8 errors 0 skips +test_require 52 tests 9 failures 10 errors 0 skips test_require_lib 39 tests 0 failures 2 errors 0 skips -test_rubyoptions 68 tests 50 failures 1 errors 0 skips +test_rubyoptions 68 tests 51 failures 1 errors 0 skips test_rubyvm 3 tests 1 failures 2 errors 0 skips -test_set 63 tests 0 failures 2 errors 2 skips -test_settracefunc 102 tests 38 failures 16 errors 0 skips +test_set 63 tests 0 failures 0 errors 2 skips +test_settracefunc 102 tests 43 failures 6 errors 0 skips test_shapes 0 tests 0 failures 0 errors 0 skips -test_signal 21 tests 2 failures 4 errors 1 skips +test_signal 21 tests 2 failures 2 errors 1 skips test_sleep 2 tests 0 failures 0 errors 0 skips test_sprintf 35 tests 3 failures 0 errors 0 skips test_sprintf_comb 95 tests 0 failures 0 errors 0 skips test_stack 3 tests 2 failures 1 errors 0 skips -test_string 475 tests 14 failures 17 errors 0 skips +test_string 475 tests 18 failures 4 errors 0 skips test_string_memory 3 tests 0 failures 3 errors 0 skips test_stringchar 4 tests 0 failures 0 errors 0 skips -test_struct 102 tests 0 failures 2 errors 0 skips -test_super 50 tests 2 failures 5 errors 0 skips -test_symbol 59 tests 0 failures 7 errors 0 skips -test_syntax 171 tests 8 failures 3 errors 0 skips +test_struct 102 tests 0 failures 0 errors 0 skips +test_super 50 tests 2 failures 1 errors 0 skips +test_symbol 59 tests 0 failures 0 errors 0 skips +test_syntax 171 tests 7 failures 2 errors 0 skips test_system 8 tests 2 failures 1 errors 0 skips -test_thread 98 tests 5 failures 6 errors 4 skips +test_thread 98 tests 5 failures 5 errors 4 skips test_thread_cv 13 tests 0 failures 1 errors 0 skips test_thread_queue 40 tests 2 failures 1 errors 0 skips test_threadgroup 3 tests 0 failures 0 errors 0 skips test_time 89 tests 2 failures 8 errors 0 skips -test_time_tz 166 tests 12 failures 1 errors 0 skips +test_time_tz 155 tests 1 failures 1 errors 0 skips test_trace 4 tests 0 failures 0 errors 0 skips -test_transcode 101 tests 14 failures 5 errors 0 skips +test_transcode 101 tests 15 failures 4 errors 0 skips test_undef 3 tests 0 failures 0 errors 0 skips test_unicode_escape 8 tests 0 failures 0 errors 0 skips -test_variable 32 tests 1 failures 1 errors 0 skips +test_variable 32 tests 1 failures 0 errors 0 skips test_vm_dump 0 tests 0 failures 0 errors 0 skips test_warning 1 tests 0 failures 0 errors 0 skips -test_weakkeymap 13 tests 0 failures 1 errors 0 skips -test_weakmap 19 tests 0 failures 1 errors 3 skips +test_weakkeymap 13 tests 0 failures 0 errors 0 skips +test_weakmap 19 tests 1 failures 0 errors 3 skips test_whileuntil 3 tests 0 failures 0 errors 0 skips test_yield 13 tests 0 failures 0 errors 0 skips test_yjit 0 tests 0 failures 0 errors 0 skips test_yjit_exit_locations 0 tests 0 failures 0 errors 0 skips test_zjit 0 tests 0 failures 0 errors 0 skips -142 files: 51 clean, 90 with failures, 1 without a summary -10382 tests, 2531843 assertions, 499 failures, 3323 errors, 66 skips; 6494 passing +142 files: 66 clean, 75 with failures, 1 without a summary +10369 tests, 2600466 assertions, 506 failures, 3136 errors, 70 skips; 6657 passing From 42647e0160a3635f2bf835ddde1e77ac8be9749e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:59:52 +0000 Subject: [PATCH 344/439] Register DefineMethodCallee1, which was written but never run 550159b added the test for __callee__ through an alias of a define_method body but not its entry in RubyTests.cs, so the driver never ran it. It passes, and its output is still CRuby 4.0.10's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0c85e6e23..318e73f30 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1296,6 +1296,7 @@ public Tests(Driver/*!*/ driver) { MethodArity_PreludeMethods1, MethodDef_SymbolInBody1, KeywordsOmitted1, + DefineMethodCallee1, CurrentMethod_ClassBody1, ToIntegerConversion1, Kernel_IntegerFloat1, From e18c87097e4e87be98aea5857ced2b600a85ee5b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:59:58 +0000 Subject: [PATCH 345/439] cruby-test: note that the RSS-ratio memory-leak tests flip with the prelude's size So that a sweep in which only they change is not taken for a regression. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index a4c016942..8b841ec06 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -34,6 +34,17 @@ test files one person (or agent) takes, in a build tree of their own. 7. **Report** per file: failures+errors before and after, what was fixed, what was excluded and why, and what remains with its cause in a line each, so the next round can be cut. +## RSS-ratio tests are not regressions + +The `assert_no_memory_leak(..., rss: true)` tests (test_hash's `*_memory_leak`, test_string's +`test_encode_fallback_*_memory_leak` and `test_initialize_nofree_memory_leak`, test_regexp's +`test_regsub_no_memory_leak`, test_settracefunc's `test_tracepoint_memory_leak` and others) pass +while the RSS at the end of the child is under twice the RSS at its start. On IronRuby the ratio +is about 2.0, and the starting RSS depends on where a startup GC falls, which moves with the size +of the prelude: 500 lines of unused methods added to `ruby4.rb` tip about fourteen of them over. +A sweep in which these flip, and nothing else, has not regressed; do not chase them, and do not +trim the prelude to make them pass. + ## Packages | # | Area | Files (baseline: tests / failures+errors) | From 41e326c86ce8dee1ea5ccb7288fa941077655364 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:14:09 +0000 Subject: [PATCH 346/439] Thread::SizedQueue defines pop, clear, close and num_waiting itself CRuby 4.0 defines #pop (#shift, #deq), #clear, #close and #num_waiting on Thread::SizedQueue as well as on Thread::Queue (they also wake the threads waiting to push): Thread::SizedQueue.instance_method(:pop).owner is Thread::SizedQueue, and a subclass's super finds them there. IronRuby inherited Queue's, so #owner said Thread::Queue. SizedQueue has the same overloads, forwarding to Queue's, which already wake every thread waiting on the queue: #arity, #parameters and what they do are as before. Checked with SizedQueue_OwnMethods1 (output from CRuby 4.0: owners, pop(true) on an empty queue, pop(timeout: 0), the argument errors, clear, close), the owner, arity and parameters of each Queue/SizedQueue method side by side with CRuby, IronRuby.Tests, and the sizedqueue, queue, conditionvariable, library/thread and thread specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/FiberTests.cs | 31 +++++++++++++++ Src/Libraries/Thread/SizedQueue.cs | 48 ++++++++++++++++++++++++ 3 files changed, 80 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 71fcbc4e5..3040704e5 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1269,6 +1269,7 @@ public Tests(Driver/*!*/ driver) { Fiber_ThreadRaiseReachesRunningFiber1, Thread_HandleInterruptOtherRuntime1, Thread_BlockedMethodFrame1, + SizedQueue_OwnMethods1, Thread_HandleInterruptInherited1, Thread_HandleInterruptIoWrite1, Thread_RaiseBetweenBlockCallsMeetsRescue1, diff --git a/Src/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index 7186197ca..8d825ae7b 100644 --- a/Src/IronRuby.Tests/Runtime/FiberTests.cs +++ b/Src/IronRuby.Tests/Runtime/FiberTests.cs @@ -168,6 +168,37 @@ sleep 0.01 ", "[0, 0, 0, 2]"); } + /// + /// Thread::SizedQueue defines #pop (#shift, #deq), #clear, #close and #num_waiting itself, as MRI does, rather + /// than inheriting Queue's: #owner says so, and a subclass's super reaches them there. + /// + public void SizedQueue_OwnMethods1() { + TestOutput(@" +require 'ruby4' +p Thread::SizedQueue.instance_method(:pop).owner, Thread::SizedQueue.instance_method(:close).owner, Thread::SizedQueue.instance_method(:clear).owner, Thread::SizedQueue.instance_method(:num_waiting).owner +q = Thread::SizedQueue.new(1) +a = (q.pop(true) rescue $!.class) +b = (q.pop(true, timeout: 1) rescue $!.message) +c = (q.pop(1, 2) rescue $!.message) +p a, q.pop(timeout: 0), q.num_waiting, b, c +q << 5 +p q.clear.size, q.close.closed?, q.pop +", @" +Thread::SizedQueue +Thread::SizedQueue +Thread::SizedQueue +Thread::SizedQueue +ThreadError +nil +0 +""can't set a timeout if non_block is enabled"" +""wrong number of arguments (given 2, expected 0..1)"" +0 +true +nil +"); + } + /// /// Thread#backtrace of a thread blocked in a core method shows that method on top, as MRI's does: /// Mutex#lock, Queue#pop, SizedQueue#push, Thread#join and #value, ConditionVariable#wait, diff --git a/Src/Libraries/Thread/SizedQueue.cs b/Src/Libraries/Thread/SizedQueue.cs index d5de6a68f..7f4912bd0 100644 --- a/Src/Libraries/Thread/SizedQueue.cs +++ b/Src/Libraries/Thread/SizedQueue.cs @@ -145,5 +145,53 @@ public static object Enqueue(RubyContext/*!*/ context, SizedQueue/*!*/ self, obj } return Enqueue(context, self, value, options); } + + // MRI defines these on SizedQueue itself, which #owner and `super' from a subclass see: the same as Queue's but for + // waking the threads that wait to push (here every waiter on the queue is woken, so they are Queue's). + + [RubyMethod("deq")] + [RubyMethod("pop")] + [RubyMethod("shift")] + public static object Dequeue(SizedQueue/*!*/ self, [Optional]bool nonBlocking) { + return RubyQueue.Dequeue(self, nonBlocking); + } + + [RubyMethod("deq")] + [RubyMethod("pop")] + [RubyMethod("shift")] + public static object Dequeue(RubyContext/*!*/ context, SizedQueue/*!*/ self, [Keywords, NotNull]Hash/*!*/ options) { + return RubyQueue.Dequeue(context, self, options); + } + + [RubyMethod("deq")] + [RubyMethod("pop")] + [RubyMethod("shift")] + public static object Dequeue(RubyContext/*!*/ context, SizedQueue/*!*/ self, bool nonBlocking, [Keywords, NotNull]Hash/*!*/ options) { + return RubyQueue.Dequeue(context, self, nonBlocking, options); + } + + [RubyMethod("deq")] + [RubyMethod("pop")] + [RubyMethod("shift")] + public static object Dequeue(SizedQueue/*!*/ self, object nonBlocking, object other) { + return RubyQueue.Dequeue(self, nonBlocking, other); + } + + [RubyMethod("clear")] + public static SizedQueue/*!*/ Clear(SizedQueue/*!*/ self) { + RubyQueue.Clear(self); + return self; + } + + [RubyMethod("num_waiting")] + public static int GetNumberOfWaitingThreads(SizedQueue/*!*/ self) { + return RubyQueue.GetNumberOfWaitingThreads(self); + } + + [RubyMethod("close")] + public static SizedQueue/*!*/ Close(SizedQueue/*!*/ self) { + RubyQueue.Close(self); + return self; + } } } From 80ef07c9e891ae153c6731e837b3185128eb5ea2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:14:09 +0000 Subject: [PATCH 347/439] A Ruby subclass of Thread::SizedQueue can be instantiated `class Q < Thread::SizedQueue; end; Q.new(2)` raised "can't allocate class 'Q' that derives from type 'Thread::SizedQueue' with no default constructor". SizedQueue's only constructor took the limit, and the class a Ruby subclass is compiled to mirrors the base's constructors, so there was none to allocate it with before #initialize ran. CRuby allocates it and #initialize sets the limit. SizedQueue has a protected constructor that takes no limit: the subclass is allocated with it and its #initialize (or SizedQueue's, through super) sets the limit. It is not public, so Thread::SizedQueue.new still raises "wrong number of arguments (given 0, expected 1)". Left: a subclass whose #initialize does not call super has, in CRuby, a queue that is not initialized - #size, #push, #pop raise "not initialized" and #max is 0 - for Queue as for SizedQueue; IronRuby's works as an empty queue (the base build's Queue subclasses too). Checked with SizedQueue_Subclass1 (output from CRuby 4.0: new without an argument, a subclass with and without its own #initialize calling super, super from its #pop), IronRuby.Tests, and the same specs as the previous commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/FiberTests.cs | 25 ++++++++++++++++++++++++ Src/Libraries/Thread/SizedQueue.cs | 6 ++++++ 3 files changed, 32 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 3040704e5..cda79a9ff 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1270,6 +1270,7 @@ public Tests(Driver/*!*/ driver) { Thread_HandleInterruptOtherRuntime1, Thread_BlockedMethodFrame1, SizedQueue_OwnMethods1, + SizedQueue_Subclass1, Thread_HandleInterruptInherited1, Thread_HandleInterruptIoWrite1, Thread_RaiseBetweenBlockCallsMeetsRescue1, diff --git a/Src/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index 8d825ae7b..37540a40c 100644 --- a/Src/IronRuby.Tests/Runtime/FiberTests.cs +++ b/Src/IronRuby.Tests/Runtime/FiberTests.cs @@ -199,6 +199,31 @@ public void SizedQueue_OwnMethods1() { "); } + /// + /// A Ruby subclass of Thread::SizedQueue can be made: it is allocated with a constructor that takes no limit, + /// which #initialize then sets; Thread::SizedQueue.new still wants its argument. + /// + public void SizedQueue_Subclass1() { + TestOutput(@" +require 'ruby4' +a = (Thread::SizedQueue.new rescue $!.message) +class Q < Thread::SizedQueue; def pop(*a, **k) = [:mine, super]; end +b = (Q.new rescue $!.message) +q = Q.new(2) +q << 1 +p a, b, q.max, q.pop +class Q3 < Thread::SizedQueue; def initialize; super(4); end; end +p Q3.new.max, Q3.new.push(1).size +", @" +""wrong number of arguments (given 0, expected 1)"" +""wrong number of arguments (given 0, expected 1)"" +2 +[:mine, 1] +4 +1 +"); + } + /// /// Thread#backtrace of a thread blocked in a core method shows that method on top, as MRI's does: /// Mutex#lock, Queue#pop, SizedQueue#push, Thread#join and #value, ConditionVariable#wait, diff --git a/Src/Libraries/Thread/SizedQueue.cs b/Src/Libraries/Thread/SizedQueue.cs index 7f4912bd0..82146e027 100644 --- a/Src/Libraries/Thread/SizedQueue.cs +++ b/Src/Libraries/Thread/SizedQueue.cs @@ -39,6 +39,12 @@ public SizedQueue([DefaultProtocol]int limit) { SetLimitChecked(limit); } + // What a Ruby subclass is allocated with (the class it is compiled to mirrors it), #initialize then setting the + // limit: without it `class Q < Thread::SizedQueue; end; Q.new(2)' could not allocate a Q. Not public, so that + // Thread::SizedQueue.new still wants its argument. + protected SizedQueue() { + } + private void SetLimitChecked(int limit) { if (limit <= 0) { throw RubyExceptions.CreateArgumentError("queue size must be positive"); From 50b2427a0469f32e8503c251f61c7d7841ec3130 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:25:14 +0000 Subject: [PATCH 348/439] Ledger: round 10's gate, PASS; Towers closed Round 10 of round thirty-seven (perf/crubydiff's rounds 11-15 and perf/towersink, at 3781af6a against master c4719ea) passed the gate: IronRuby.Tests 1,441 run, none failed; the matrices in seven modes with only the two known DIFFs and eleven fewer baseline rows; a probe file for the round as CRuby under C.UTF-8 and LANG=C; ruby/spec's five suites with no unlisted failure; the census unchanged. Towers, open at round 9, now runs at 0.969 and 0.964 of master's time (pinned, ten rounds in each order): perf/towersink made only methods with a regex literal match sinks. AWFY 12 is at a geomean of 0.915 and 0.900, and start-up at 0.86-0.97 of master's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e1f0994ac..1cf66b2d3 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,35 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-28 for round 10 of round thirty-seven** (perf/crubydiff's eleventh to fifteenth rounds, and + perf/towersink, the fix for the Towers lean round 9 left open): the branch `claude/happy-gauss-95wm2j` at + 3781af6a against master c4719ea, Release net10.0, the composite R2R host on both, four cores: **PASS**, Towers + closed. + The merge itself: both branches merged without a code conflict; the ledger kept both sides. No switch is new + but perf/towersink's change to `IR_LIGHT_MATCH_SINK`'s reach. ReflectionCache.Generated.cs is what + ClassInitGenerator writes. No new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,441 tests, every one executed, none failed. + `gate-matrices.rb --all` in 7 modes (the six default ones and IR_LIGHT_MATCH_SINK=0): 1,341 same, 108 baseline + (119 at round 9: eleven rows fewer differ from CRuby as master does), 14 DIFF, the two known ones: + regexp-binary-ctype as at round 8 in every mode; string-race-matrix compared over five runs of each tree (rows + not always ok 109 -> 87, lost writes 106 -> 0, no row failing only on the new build). thread-backtrace is the + same in every mode now (perf/crubydiff's 419f23e). + A probe file for the round - an alias made private keeping its original_name, the redefinition warning as one + message and an alias's warning naming its own line, ostruct quiet under `-w`, caller(0) and a raise inside a + compiled class or module body, the encodings of 17 core #inspect and #to_s, Rational and Complex strings, an + empty message's Exception#inspect, a non-ASCII class name and a module's #inspect/#to_s overrides in + Method#inspect, File#path and #inspect of a non-ASCII path - prints CRuby's output under C.UTF-8 and LANG=C, + with the JIT on and off. Master differs in 12 and 16 lines. + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against round 9: no method changed. + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.915 and 0.900; Towers + 0.967 and 0.950. Towers pinned to two CPUs, ten rounds in each order: 0.969 (base first) and 0.964 (new first) + - the lean is gone (perf/towersink: 56.37 -> 53.97M instructions per benchmark, the switch-off count). Alone, + five rounds in each order, medians new/base: Havlak 0.884 / 0.892, Json 0.941 / 0.909. micro-table in both + orders: no line more than 5% slower in both (getter 0.95 then 1.11). + Start-up on the composite R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 364 -> 336 and + 350 -> 331, `gem --version` 433 -> 406 and 410 -> 396, `gem list` 791 -> 681 and 758 -> 663, `require "irb"` + 796 -> 710 and 798 -> 699, irb 1+1 885 -> 769 and 868 -> 754: 0.86-0.97. - **Gate of 2026-11-28 for round 9 of round thirty-seven** (master c4719ea with #301 and #302, perf/crubydiff's eighth to tenth rounds, perf/ownerpark (rejected), perf/yieldloop, perf/kwjit with perf/kwcall's fix, perf/kernelcall, perf/datafilter, perf/namedblock, perf/heldrfc, perf/loopivar2, perf/sharedargs): the branch @@ -2093,7 +2122,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 385 -> 343, `gem --version` 431 -> 437 and 440 -> 448, `gem list` 827 -> 702 and 829 -> 711, `require "irb"` 812 -> 734 and 863 -> 765, irb 1+1 915 -> 784 and 926 -> 796: 0.85-0.96, `gem --version` level (1.015 and 1.019). -- **perf/towersink (bisect, 2026-11-28, not gated) - only a method with a regex literal is a match sink: AWFY +- **perf/towersink (bisect, 2026-11-28, gated 2026-11-28 (round 10's gate entry)) - only a method with a regex literal is a match sink: AWFY Towers' 2-7% against master since round 7 was perf/lightmatch + perf/sinkcarrier making every light method one** (on 597b8dc9). - **The bisect.** Instructions per Towers#benchmark (Util/perf/callgrind/count.sh, AWFY's towers.rb run in place @@ -4409,7 +4438,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's), its eleventh to fifteenth 2026-11-28 (round 10's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope From e7ef742ff5ed185f41204ff443d5dd96022fc9df Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:57:47 +0000 Subject: [PATCH 349/439] Array, Hash and String define the methods CRuby defines on them CRuby 4.0 defines Array#drop, #one? and #freeze, Hash#freeze, and String#freeze and #hash on the class itself; IronRuby had them only on Enumerable or Kernel, so #owner, instance_methods(false) and a subclass's super saw Enumerable or Kernel. Array#drop and #one? are Enumerable's bodies defined on Array in the prelude (define_method with the UnboundMethod), so their arity, parameters, errors and speed are as before. Array, Hash and String#freeze and String#hash are C# methods on the classes doing what Kernel's do: a copy of Kernel's made the same way bound more slowly (String#hash 25%, Array#freeze 8%); these time the same as Kernel's or a little faster (CPU time, best of five, 3,000,000 calls: s.hash 0.237 s against 0.238, a.freeze 0.163 against 0.169, h.freeze 0.153 against 0.177, s.dup.freeze 0.318 against 0.375). Hash tables hash String keys without calling #hash, as before. Left: Integer#hash, #step and #to_c, Float#to_c, Array#sort_by and #each_with_object, Hash#sort, Range#sum, Symbol#eql? and #clone, which IronRuby defines on the class where CRuby inherits them; they are C# fast paths. Checked with Methods_OwnedByClass1 (output from CRuby 4.0), a listing of the instance methods each core class defines itself against CRuby's, IronRuby.Tests, and the string, array, hash, Kernel#freeze/#frozen?, Enumerable#drop/#one? and language specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 27 ++++++++++++++++++++++ Src/Libraries/Builtins/ArrayOps.cs | 8 +++++++ Src/Libraries/Builtins/HashOps.cs | 8 +++++++ Src/Libraries/Builtins/MutableStringOps.cs | 13 +++++++++++ Src/StdLib/ironruby/ruby4.rb | 12 ++++++++++ 6 files changed, 69 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index cda79a9ff..a9f9dce5e 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1294,6 +1294,7 @@ public Tests(Driver/*!*/ driver) { MethodInspect_LibraryParameters1, MethodInspect_Encoding1, MethodInspect_Modules1, + Methods_OwnedByClass1, MethodArity_CoreMethods1, MethodArity_LibraryArguments1, MethodArity_PreludeMethods1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index a57a4dc72..8602dc2db 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1745,6 +1745,33 @@ puts s(Sub.new.method(:b)), s(Café.new.method(:b)) "); } + /// + /// Array#drop, #one? and #freeze, Hash#freeze and String#freeze and #hash are defined on the class, as in MRI, + /// rather than inherited from Enumerable or Kernel: #owner says so; they behave as before. + /// + public void Methods_OwnedByClass1() { + TestOutput(@" +require 'ruby4' +p [[Array, :drop], [Array, :one?], [Array, :freeze], [Hash, :freeze], [String, :freeze], [String, :hash]].map { |c, m| c.instance_method(m).owner } +p [1, 2, 3].drop(1), [1].one?, [1, 2].one?(Integer), ([1].drop(-1) rescue $!.message) +class S < String; end +s = ""ab"" +p s.hash == ""ab"".hash, S.new(""ab"").hash == ""ab"".hash, s.freeze.frozen?, [1].freeze.frozen?, {}.freeze.frozen?, S.new(""x"").freeze.frozen? +", @" +[Array, Array, Array, Hash, String, String] +[2, 3] +true +false +""attempt to drop negative size"" +true +true +true +true +true +true +"); + } + /// /// Method#inspect shows the parameter list for library methods and attribute accessors /// too, as MRI does ("_" for a required parameter with no name); a rule-generator method diff --git a/Src/Libraries/Builtins/ArrayOps.cs b/Src/Libraries/Builtins/ArrayOps.cs index b3b80165c..2c9159755 100644 --- a/Src/Libraries/Builtins/ArrayOps.cs +++ b/Src/Libraries/Builtins/ArrayOps.cs @@ -35,6 +35,14 @@ namespace IronRuby.Builtins { [RubyClass("Array", Extends = typeof(RubyArray), Inherits = typeof(object)), Includes(typeof(IList), Copy = true)] public static class ArrayOps { + // MRI defines #freeze on Array itself (#owner, instance_methods(false), super), with Kernel's behaviour; a C# + // method rather than a copy of Kernel's, which a call cannot bind as quickly. + [RubyMethod("freeze")] + public static RubyArray/*!*/ Freeze(RubyContext/*!*/ context, RubyArray/*!*/ self) { + KernelOps.Freeze(context, self); + return self; + } + #region Constructors // MRI defines new on the class itself (String.singleton_methods(false) includes it); it diff --git a/Src/Libraries/Builtins/HashOps.cs b/Src/Libraries/Builtins/HashOps.cs index 7ab405540..23e8c43bd 100644 --- a/Src/Libraries/Builtins/HashOps.cs +++ b/Src/Libraries/Builtins/HashOps.cs @@ -35,6 +35,14 @@ namespace IronRuby.Builtins { [RubyClass("Hash", Extends = typeof(Hash), Inherits = typeof(object)), Includes(typeof(IDictionary), Copy = true)] public static class HashOps { + // MRI defines #freeze on Hash itself (#owner, instance_methods(false), super), with Kernel's behaviour; a C# + // method rather than a copy of Kernel's, which a call cannot bind as quickly. + [RubyMethod("freeze")] + public static Hash/*!*/ Freeze(RubyContext/*!*/ context, Hash/*!*/ self) { + KernelOps.Freeze(context, self); + return self; + } + #region Construction [RubyConstructor] diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 52e85170b..068c07ef2 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -78,6 +78,19 @@ public class MutableStringOps { return MutableString.CreateBinary(value); } + // MRI defines #freeze and #hash on String itself (#owner, instance_methods(false), super), with Kernel's behaviour; a C# + // method rather than a copy of Kernel's, which a call cannot bind as quickly. + [RubyMethod("freeze")] + public static MutableString/*!*/ Freeze(RubyContext/*!*/ context, MutableString/*!*/ self) { + KernelOps.Freeze(context, self); + return self; + } + + [RubyMethod("hash")] + public static int GetHashCode(MutableString/*!*/ self) { + return self.GetHashCode(); + } + #region Helpers // Ruby indexes a String by character, the CLR by UTF-16 code unit, and the two differ for diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index a0ad4164e..81770e83f 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -13924,5 +13924,17 @@ def box end end +# Methods MRI defines on the class itself that IronRuby has only on a module above it: #owner, +# instance_methods(false) and a subclass's super see them on the class, as in MRI. The same +# bodies, so the same arity, parameters and behaviour. (Array, Hash and String#freeze and +# String#hash are C# methods of their own: a copy of Kernel's binds more slowly.) +{ + ::Array => [[::Enumerable, :drop], [::Enumerable, :one?]], +}.each do |klass, methods| + methods.each do |mod, name| + klass.send(:define_method, name, mod.instance_method(name)) unless klass.instance_methods(false).include?(name) + end +end + # Gem compatibility patches (see the file for the policy on adding one). require "ironruby/gem_compat" From 41d9e6aa6c8834340cbc81a1390bc653004d7c98 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:59:27 +0000 Subject: [PATCH 350/439] A singleton method of an Enumerator with instance variables no longer hangs An Enumerator keeps its instance variables itself (IRubyInstanceDataOwner). The compiled @ivar store (RubyOps.TrySetOwnedInstanceVariable) made that data through the owner alone, so the object was never marked in the context's instance-data filter (MayHaveTableInstanceData), and GetImmediateClassOf, which skips the lookup for an unmarked object, went on answering Enumerator after the object had been given a singleton class. Calling the singleton method then spun in the call site for good, holding the class hierarchy lock: Object.new.to_enum { 1 } followed by def e.each hung, as did ruby/spec's Enumerator::Lazy#uniq with a singleton #each once Kernel#to_enum recorded a size for every enumerator. The first data is now made through RubyContext.GetInstanceData, which marks the object; later stores still go straight to the owner's data. Checked: the hang is gone on Release net10.0, the ivar, loop-ivar and enum matrices are the same in every mode, IronRuby.Tests passes. New IronRuby.Tests: Enumerator_SingletonAfterInstanceVariable1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/EnumeratorTests.cs | 24 +++++++++++++++++++ Src/Ruby/Runtime/RubyOps.cs | 9 ++++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 318e73f30..58a475f88 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1084,6 +1084,7 @@ public Tests(Driver/*!*/ driver) { Enumerator_LazyEachResult1, Enumerator_LazyAncestors1, Enumerator_ChainNoNext1, + Enumerator_SingletonAfterInstanceVariable1, Io_Messages1, Encoding_Misc1, Encoding_List1, diff --git a/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs b/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs index de084ffe5..5fe11aa3a 100644 --- a/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs +++ b/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs @@ -240,6 +240,30 @@ p Enumerator.product([1], [2]).to_a false false [[1, 2]] +"); + } + + /// + /// An Enumerator keeps its instance variables itself (IRubyInstanceDataOwner). Its first one, written by a + /// compiled @ivar store, made the data without marking the object in the context's instance-data filter, so a + /// singleton class it was given later was never found and calling a singleton method spun for good. + /// + public void Enumerator_SingletonAfterInstanceVariable1() { + TestOutput(@" +class Enumerator + def mark_(v) + @mark_ = v + self + end +end +e = [1, 2].each.mark_(3) +def e.foo = :singleton +p e.foo, e.singleton_methods, e.to_a, e.instance_variable_get(:@mark_) +", @" +:singleton +[:foo] +[1, 2] +3 "); } } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index fde736fa7..500c72e13 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -6257,7 +6257,14 @@ private static bool TrySetOwnedInstanceVariable(RubyContext/*!*/ context, object if (owner == null) { return false; } - var data = owner.GetInstanceData(context); + // The object's first instance data is made through the context, which marks it in the + // filter that GetImmediateClassOf reads (MayHaveTableInstanceData): data made by the + // owner alone went unseen there, so a singleton class the object was given later was + // never found, and a call of its singleton method spun in the call site for good. + RubyInstanceData data; + if (!owner.TryGetInstanceData(context, out data) || data == null) { + data = context.GetInstanceData(self); + } return data != null && !data._frozen && data.TrySetCached(site.Cache, value, data.ImmediateClass); } From d2e820193b4d276444ca48dd952a3fdc197de68e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:59:27 +0000 Subject: [PATCH 351/439] Kernel#to_enum without a block gives an enumerator of unknown size IronRuby worked out the size of every enumerator from its receiver and method (Enumerator#__size_from_target__): o.to_enum.size answered o.size, and [1, 2].to_enum(:map).size 2. In MRI an enumerator from Kernel#to_enum has a size function only when a block gives one, so both are nil; only the core methods' own enumerators (RETURN_SIZED_ENUMERATOR) know their size. Kernel#to_enum and #enum_for now give the enumerator a size function that answers nil unless a block is passed. The prelude's core methods that made their enumerators with to_enum and relied on the worked-out size (each_entry, group_by, each_with_object, Struct#each, ENV#keep_if and the rest) call the private __ir_enum__ instead, which keeps it; like MRI's rb_enumeratorize it does not dispatch to #to_enum, except that a Lazy receiver still answers a Lazy (lazy_to_enum_i). Checked against CRuby 4.0.10: ruby/spec core/enumerator, enumerable, array, hash, struct, env, kernel, string, integer, range and set as on the base build; the enum, enum-next and enumerable2 matrices the same in every mode; test_enumerator, test_lazy_enumerator, test_enum, test_array and the rest unchanged. New IronRuby.Tests: Enumerator_ToEnumSize1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/EnumeratorTests.cs | 41 ++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 54 +++++++++++++------ 3 files changed, 79 insertions(+), 17 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 58a475f88..94ee5e5bf 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1085,6 +1085,7 @@ public Tests(Driver/*!*/ driver) { Enumerator_LazyAncestors1, Enumerator_ChainNoNext1, Enumerator_SingletonAfterInstanceVariable1, + Enumerator_ToEnumSize1, Io_Messages1, Encoding_Misc1, Encoding_List1, diff --git a/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs b/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs index 5fe11aa3a..2dd366c1e 100644 --- a/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs +++ b/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs @@ -264,6 +264,47 @@ def mark_(v) [:foo] [1, 2] 3 +"); + } + + /// + /// Kernel#to_enum without a block makes an enumerator with no size function: #size is nil whatever the + /// receiver and method, as in MRI. The core methods' own enumerators keep theirs. + /// + public void Enumerator_ToEnumSize1() { + TestOutput(@" +require 'ruby4' +o = Object.new +def o.each + yield 1 + yield 2 +end +def o.size = 5 +p o.to_enum.size, o.enum_for(:each).size, o.to_enum { 7 }.size +p [1, 2].to_enum.size, [1, 2].to_enum(:map).size, 3.to_enum(:times).size +p [1, 2].each.size, [1, 2].map.size, {a: 1}.each_pair.size, 3.times.size +p o.to_enum.to_a, o.to_enum.with_index.size, o.to_enum.lazy.size +e = Object.new.to_enum +def e.each + yield 0, ""a"" +end +p e.first, e.lazy.map { |a, b| b }.force +", @" +nil +nil +7 +nil +nil +nil +2 +2 +1 +3 +[1, 2] +nil +nil +[0, ""a""] +[""a""] "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index d6d99ac51..aa2a8d54d 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -359,7 +359,7 @@ def __enum_item__(values) # Extra arguments are passed straight through to #each, which is how a # receiver whose #each takes parameters gets to see them. def each_entry(*args, &block) - return to_enum(:each_entry, *args) unless block + return __ir_enum__(:each_entry, *args) unless block each(*args) do |*values| values.size == 1 ? block.call(values[0]) : __enum_yield__(values, &block) end @@ -473,7 +473,7 @@ def max(*args, &block) end def group_by(&block) - return to_enum(:group_by) unless block + return __ir_enum__(:group_by) unless block # an Array is grouped in C#, see Enumerable.ListGroupBy return __list_group_by__(&block) if __plain_list__? result = {} @@ -492,7 +492,7 @@ def group_by(&block) end unless method_defined?(:group_by) def each_with_object(memo) - return to_enum(:each_with_object, memo) unless block_given? + return __ir_enum__(:each_with_object, memo) unless block_given? # see group_by: a Hash's built-in #each yields one value per entry (an Array has its own, in C#) if __plain_each__? each { |item| yield(item, memo) } @@ -1707,7 +1707,7 @@ def sort_by!(&block) # Two modes, as in MRI: find-minimum when the block answers true/false/nil, # find-any when it answers a number (negative = look left, 0 = found). def bsearch_index(&block) - return to_enum(:bsearch_index) unless block + return __ir_enum__(:bsearch_index) unless block low = 0 high = size satisfied = nil @@ -1735,7 +1735,7 @@ def bsearch_index(&block) end unless method_defined?(:bsearch_index) def bsearch(&block) - return to_enum(:bsearch) unless block + return __ir_enum__(:bsearch) unless block index = bsearch_index(&block) index && self[index] end unless method_defined?(:bsearch) @@ -1747,7 +1747,7 @@ def rfind(*args, &block) if args.size > 1 ::Kernel.raise(::ArgumentError, "wrong number of arguments (given #{args.size}, expected 0..1)") end - return to_enum(:rfind, *args) unless block + return __ir_enum__(:rfind, *args) unless block ifnone = args[0] index = size - 1 while index >= 0 @@ -5554,7 +5554,7 @@ def __ir_each_impl__(*args, &block) if target receiver, method, initial = target arguments = initial + args - return receiver.to_enum(method, *arguments) unless block + return receiver.__send__(:__ir_enum__, method, *arguments) unless block return receiver.__send__(method, *arguments, &block) end end @@ -5653,7 +5653,6 @@ def __set_size__(value) @__size__ = value self end - def size n = @__size__ return n.call if !n.is_a?(::Numeric) && n.respond_to?(:call) @@ -6932,7 +6931,28 @@ module Kernel # enumerator's #size. # The arguments are kept and handed to the method when the enumerator runs, keywords # included - `enum_for(:find, *paths, ignore_error: true)' has to reach #find as keywords. + # + # Without a block the enumerator has no size function, so its #size is nil whatever the + # method (`[1, 2].to_enum(:map).size` is nil in MRI): only the core methods' own enumerators + # know their size, and the prelude makes those with __ir_enum__ below. + # The size function of an enumerator that has none. + NO_ENUM_SIZE__ = proc { nil } + __hide_constant__ :NO_ENUM_SIZE__ + ruby2_keywords def to_enum(method = :each, *args, &size_block) + enum = __ir_enum__(method, *args, &size_block) + enum.__set_size__(NO_ENUM_SIZE__) unless size_block + enum + end + alias :enum_for :to_enum + + # rb_enumeratorize for a core method written in Ruby: an enumerator whose #size, when no + # block gives it, is worked out from the receiver and the method, as the size functions of + # MRI's RETURN_SIZED_ENUMERATOR would (Enumerator#__size_from_target__). MRI's core methods + # do not dispatch to #to_enum, and neither does this. + ruby2_keywords def __ir_enum__(method = :each, *args, &size_block) + # rb_enumeratorize_with_size hands a Lazy receiver to lazy_to_enum_i: what it answers stays lazy. + return to_enum(method, *args, &size_block) if ::Enumerator::Lazy === self # Not Enumerator.new: Ruby 3.0 removed its (obj, meth, *args) form, and the # class-level initializer is what to_enum used to reach through. enum = ::Enumerator.allocate @@ -6941,7 +6961,7 @@ module Kernel enum.__set_size__(args.empty? ? size_block : lambda { size_block.call(*args) }) if size_block enum end - alias :enum_for :to_enum + private :__ir_enum__ # The C# Kernel#loop does not know about StopIteration, which is what makes # `loop { e.next }` terminate instead of blowing up. @@ -6970,7 +6990,7 @@ class String def each_line(*args, chomp: (no_chomp = true; false), &block) # the enumerator shows the chomp: given, false and nil too, as MRI's does - return to_enum(:each_line, *args, **(no_chomp ? {} : { chomp: chomp })) unless block + return __ir_enum__(:each_line, *args, **(no_chomp ? {} : { chomp: chomp })) unless block # The common case - one String separator, no chomp:, an ASCII-compatible receiver - is # where __ir_split_lines__ ends up after its checks; going there directly is a good part # of the cost of a short string's each_line (URI.decode_www_form splits on "&"). @@ -7417,7 +7437,7 @@ def upto(stop, exclusive = (no_exclusive = true; false), &block) end # the Enumerator names the arguments as given, as MRI's RETURN_ENUMERATOR does - return (no_exclusive ? to_enum(:upto, given) : to_enum(:upto, given, exclusive)) unless block + return (no_exclusive ? __ir_enum__(:upto, given) : __ir_enum__(:upto, given, exclusive)) unless block # A pair of decimal strings counts like Integer#upto, with the receiver's # width kept: "08".upto("11") answers "08", "09", "10", "11". @@ -8301,13 +8321,13 @@ def invert end def keep_if - return to_enum(:keep_if) unless block_given? + return __ir_enum__(:keep_if) unless block_given? to_hash.each { |k, v| self[k] = nil unless yield(k, v) } self end unless respond_to?(:keep_if) def select! - return to_enum(__callee__) unless block_given? + return __ir_enum__(__callee__) unless block_given? changed = false to_hash.each do |k, v| unless yield(k, v) @@ -11812,7 +11832,7 @@ def readlines(*args, **opts) alias :__ir_each_line__ :each_line def __io_each_line__(name, args, opts, block) - return to_enum(name, *args, **opts) unless block + return __ir_enum__(name, *args, **opts) unless block args, chomp = __take_chomp__(args, opts) chomp ? __each_line_chomp__(*args, &block) : __ir_each_line__(*args, &block) end @@ -12783,7 +12803,7 @@ def values_at(*args) # #each / #each_pair / #select return an Enumerator when no block is given. alias :__struct_each__ :each def each(&block) - return to_enum(:each) unless block + return __ir_enum__(:each) unless block __struct_each__(&block) end # Enumerator#next walks a struct with a cursor while this is the method. @@ -12792,7 +12812,7 @@ def each(&block) # each_pair yields one [name, value] array, so that a single-parameter block # receives the pair rather than just the name def each_pair(&block) - return to_enum(:each_pair) unless block + return __ir_enum__(:each_pair) unless block names = self.class.members names.each_with_index { |name, i| block.call([name, self[i]]) } self @@ -13226,7 +13246,7 @@ def bsearch(&block) # can be searched (a Rational one cannot). ::Kernel.raise(::TypeError, "can't do binary search for #{(b || e).class}") end - return to_enum(:bsearch) unless block + return __ir_enum__(:bsearch) unless block if integral # the built-in searches between two Fixnums only if respond_to?(:__ir_bsearch__, true) && __int32__(b) && __int32__(e) From 56ca135918e99844b7ccd1399df7998ce398ca5d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:59:41 +0000 Subject: [PATCH 352/439] cruby-test: baseline after round four The round-three full sweep with the files this round touched swept again (test_enumerator, test_lazy_enumerator, test_enum, test_array, test_hash, test_struct, test_env, test_set, test_range, test_iterator, test_object, test_io, test_string, test_integer, test_dir, test_argf): 6,660 passing. The three test_io tests that moved fail the same way on the base build when run alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index 8b841ec06..98cc657e0 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 66 clean, 75 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,657 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,660 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 957126992..80fa7a084 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -34,7 +34,7 @@ test_econv 85 tests 4 failures 1 errors 0 sk test_encoding 15 tests 1 failures 0 errors 0 skips test_enum 90 tests 2 failures 0 errors 0 skips test_enumerator 70 tests 0 failures 0 errors 0 skips -test_env 94 tests 9 failures 0 errors 1 skips +test_env 94 tests 7 failures 0 errors 1 skips test_eval 40 tests 3 failures 0 errors 0 skips test_exception 101 tests 14 failures 1 errors 0 skips test_fiber 35 tests 2 failures 0 errors 2 skips @@ -48,13 +48,13 @@ test_frozen 6 tests 0 failures 0 errors 0 sk test_frozen_error 5 tests 1 failures 0 errors 0 skips test_gc 53 tests 13 failures 7 errors 2 skips test_gc_compact 28 tests 9 failures 4 errors 7 skips -test_hash 298 tests 8 failures 0 errors 0 skips +test_hash 298 tests 6 failures 0 errors 0 skips test_ifunless 1 tests 0 failures 0 errors 0 skips test_inlinecache 3 tests 0 failures 0 errors 0 skips test_insns_leaf 2 tests 0 failures 0 errors 0 skips test_integer 38 tests 0 failures 0 errors 0 skips test_integer_comb 41 tests 0 failures 0 errors 0 skips -test_io 252 tests 11 failures 7 errors 5 skips +test_io 252 tests 12 failures 9 errors 4 skips test_io_buffer 87 tests 0 failures 0 errors 1 skips test_io_m17n 160 tests 13 failures 2 errors 0 skips test_io_timeout 4 tests 0 failures 0 errors 4 skips @@ -112,7 +112,7 @@ test_sleep 2 tests 0 failures 0 errors 0 sk test_sprintf 35 tests 3 failures 0 errors 0 skips test_sprintf_comb 95 tests 0 failures 0 errors 0 skips test_stack 3 tests 2 failures 1 errors 0 skips -test_string 475 tests 18 failures 4 errors 0 skips +test_string 475 tests 17 failures 4 errors 0 skips test_string_memory 3 tests 0 failures 3 errors 0 skips test_stringchar 4 tests 0 failures 0 errors 0 skips test_struct 102 tests 0 failures 0 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 66 clean, 75 with failures, 1 without a summary -10369 tests, 2600466 assertions, 506 failures, 3136 errors, 70 skips; 6657 passing +10369 tests, 2555808 assertions, 502 failures, 3138 errors, 69 skips; 6660 passing From affbb5b9abdf9f8121c2f638c907c304088eb7ca Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:38:31 +0000 Subject: [PATCH 353/439] Regexp timeouts are kept as MRI keeps them, a count of nanoseconds Regexp.timeout = Float::INFINITY answered Infinity and 1e300 answered 1e300. MRI stores a timeout as nanoseconds in a uint64 (double2hrtime) and reads it back as seconds (hrtime2double): from 2**63 seconds up it is the largest count, 18446744073.709553 s; below that the product with 10**9 goes into the uint64 as x86-64 converts it, so one too big for it (1e11 s) is 0; and 0 - anything under a nanosecond - is no timeout, nil. Other values come back rounded down to the nanosecond (1.23456789012 -> 1.23456789). Regexp.timeout= and Regexp.new(timeout:) now do the same. Checked against CRuby 4.0.10: TestRegexp#test_s_timeout_corner_cases and #test_timeout_corner_cases pass; ruby/spec core/regexp and the regex matrices unchanged. New IronRuby.Tests: Regex_TimeoutNanoseconds1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 31 ++++++++++++++++++++++++ Src/Libraries/Builtins/RubyRegexOps.cs | 15 +++++++++++- 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 94ee5e5bf..9504f74f1 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -220,6 +220,7 @@ public Tests(Driver/*!*/ driver) { Regex_LiteralEncodings1, Regex_PropertyEncoding1, Regex_BinaryCtype1, + Regex_TimeoutNanoseconds1, Regex_Latin1Ctype1, StringScanner_InsideCharacter1, StringScanner_ShorterSubject1, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 7eb6f5d51..5d9ea8664 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -1161,6 +1161,37 @@ def t(l) iso-8859-1: [0, 0] utf-8: [0, 0] absent /i: [""\xE9"", ""a"", ""\xC9a"", ""\xE9a""] +"); + } + + /// + /// MRI keeps a regexp timeout as nanoseconds in a uint64 (double2hrtime) and answers it back in seconds: from + /// 2**63 s up it is the largest count, a product of 10**9 too big for a uint64 is 0, and under a nanosecond is no + /// timeout (CRuby's TestRegexp#test_s_timeout_corner_cases, #test_timeout_corner_cases). + /// + public void Regex_TimeoutNanoseconds1() { + TestOutput(@" +require 'ruby4' +Regexp.timeout = Float::INFINITY +p Regexp.timeout +Regexp.timeout = 1e300 +p Regexp.timeout +Regexp.timeout = 1.23456789012 +p Regexp.timeout +Regexp.timeout = 1e-10 +p Regexp.timeout +Regexp.timeout = 1e11 +p Regexp.timeout +Regexp.timeout = nil +p Regexp.new(""a"", timeout: Float::INFINITY).timeout, Regexp.new(""a"", timeout: 2.5).timeout +", @" +18446744073.709553 +18446744073.709553 +1.23456789 +nil +nil +18446744073.709553 +2.5 "); } } diff --git a/Src/Libraries/Builtins/RubyRegexOps.cs b/Src/Libraries/Builtins/RubyRegexOps.cs index cf5fa6185..0c71d4c58 100644 --- a/Src/Libraries/Builtins/RubyRegexOps.cs +++ b/Src/Libraries/Builtins/RubyRegexOps.cs @@ -172,7 +172,20 @@ public static object SetGlobalTimeout(RubyClass/*!*/ self, object value) { if (Double.IsNaN(seconds) || seconds <= 0) { throw RubyExceptions.CreateArgumentError("invalid timeout: {0}", context.Inspect(value).ToString()); } - return seconds; + + // MRI keeps a timeout as a number of nanoseconds (double2hrtime) and reads it back as + // seconds (hrtime2double), so that is what Regexp.timeout and #timeout answer. From + // 2**63 seconds (TIMESPEC_SEC_MAX + 1) up it is the largest count there is; below that + // the seconds times 10**9 go into a uint64 as x86-64 converts them, a product too big + // for it giving 0. Fewer than one nanosecond, 0, is no timeout at all. + ulong nanoseconds; + if (seconds >= 9223372036854775808.0) { + nanoseconds = UInt64.MaxValue; + } else { + double product = seconds * 1e9; + nanoseconds = product >= 18446744073709551616.0 ? 0 : (ulong)product; + } + return nanoseconds == 0 ? (double?)null : nanoseconds / 1e9; } /// From 4f504a7557c6687af022f6c1d5b21e224fb5bdbf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:38:39 +0000 Subject: [PATCH 354/439] Module#const_set refuses a name in an ASCII-incompatible encoding const_set("X\u3042".encode("utf-16be"), v) defined X\u3042: the binder decoded the name to a CLR string before it was checked. MRI finds no constant ID for a name in UTF-16 or UTF-32 and raises NameError ("wrong constant name ..."). A String name now goes through an overload that refuses such an encoding first; an ASCII-compatible one is converted as before. Checked against CRuby 4.0.10: TestModule#test_const_set_invalid_name passes; ruby/spec core/module/const_set unchanged. New IronRuby.Tests: ConstSet_AsciiIncompatibleName1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ModuleTests.cs | 30 +++++++++++++++++++++++ Src/Libraries/Builtins/ModuleOps.cs | 11 +++++++++ 3 files changed, 42 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9504f74f1..50a0e8d2c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1003,6 +1003,7 @@ public Tests(Driver/*!*/ driver) { HiddenConstants1, PreludeHiddenState1, ExtendMany1, + ConstSet_AsciiIncompatibleName1, Scenario_MainSingleton, Time_LoadZone1, Time_DumpLoadedZone1, diff --git a/Src/IronRuby.Tests/Runtime/ModuleTests.cs b/Src/IronRuby.Tests/Runtime/ModuleTests.cs index e5a203775..c3182659f 100644 --- a/Src/IronRuby.Tests/Runtime/ModuleTests.cs +++ b/Src/IronRuby.Tests/Runtime/ModuleTests.cs @@ -1020,6 +1020,36 @@ p m.instance_method(:foo).bind_call(Object.new), keep[2].clone.foo, (keep[2].dup 2 2 NoMethodError +"); + } + + /// + /// Module#const_set refuses a name in an ASCII-incompatible encoding, whatever its characters decode to + /// (CRuby's TestModule#test_const_set_invalid_name). + /// + public void ConstSet_AsciiIncompatibleName1() { + TestOutput(@" +require 'ruby4' +c = Class.new +[""utf-16be"", ""utf-16le"", ""utf-32be"", ""utf-32le""].each do |enc| + c.const_set(""X\u{3042}"".encode(enc), 1) +rescue NameError => e + p e.class +end +p c.const_set(""X\u{3042}"", 2), c.constants == [:""X\u{3042}""] +begin + c.const_set(""foo"", 1) +rescue NameError => e + p e.message +end +", @" +NameError +NameError +NameError +NameError +2 +true +""wrong constant name foo"" "); } } diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index ec15946b2..369e2fa1a 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -1403,6 +1403,17 @@ public static object GetConstantValue(ConversionStorage/*!*/ stri return value; } + // A name in an encoding that is not ASCII-compatible (UTF-16, UTF-32) is no constant name in MRI + // (rb_is_const_name finds no ID for it), though its characters, decoded, would make one. + // thread-safe: + [RubyMethod("const_set")] + public static object SetConstantValue(RubyScope/*!*/ scope, RubyModule/*!*/ self, [NotNull]MutableString/*!*/ constantName, object value) { + if (!constantName.Encoding.IsAsciiIdentity) { + throw RubyExceptions.CreateNameError(String.Format("wrong constant name {0}", constantName.ToString())); + } + return SetConstantValue(scope, self, constantName.ConvertToString(), value); + } + // thread-safe: [RubyMethod("const_set")] public static object SetConstantValue(RubyScope/*!*/ scope, RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ constantName, object value) { From c132180c37f169062fdff02261d9f28f661276b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:38:57 +0000 Subject: [PATCH 355/439] attr_reader, attr_writer and attr_accessor methods have a source_location Their Method#source_location was nil. MRI records where the attr_* was called and reports that, for each method it made and for an alias of one. RubyAttributeAccessorInfo now carries a source path and line, taken at attr_* from the caller's location as Module#const_set takes it, kept by a copy (alias), and reported by UnboundMethod.GetSourceLocation unless the caller was the prelude, which stands in for C (Thread::Backtrace::Location #path stays nil, as in MRI). Checked against CRuby 4.0.10: TestProc#test_attr_source_location passes; ruby/spec core/module/attr*, method/source_location and unboundmethod/source_location unchanged; startup of -e 'require "json"' unchanged. New IronRuby.Tests: AttrAccessor_SourceLocation1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 29 ++++++++++++++++++++++ Src/Libraries/Builtins/ModuleOps.cs | 16 ++++++++++-- Src/Libraries/Builtins/UnboundMethod.cs | 10 ++++++++ Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs | 17 +++++++++++-- 5 files changed, 69 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 50a0e8d2c..7dc7dab1b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1302,6 +1302,7 @@ public Tests(Driver/*!*/ driver) { KeywordsOmitted1, DefineMethodCallee1, CurrentMethod_ClassBody1, + AttrAccessor_SourceLocation1, ToIntegerConversion1, Kernel_IntegerFloat1, Kernel_FloatOptions1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 3f51a460b..4102c3729 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -2014,6 +2014,35 @@ def m4 nil [nil] :m4 +"); + } + + /// + /// The methods attr_reader, attr_writer and attr_accessor make are located where that was called, an alias + /// of one too (CRuby's TestProc#test_attr_source_location). + /// + public void AttrAccessor_SourceLocation1() { + TestOutput(@" +base = __LINE__ +class Foo + attr_reader :r + attr_writer :w + attr_accessor :a +end +p Foo.instance_method(:r).source_location[1] - base, Foo.instance_method(:w=).source_location[1] - base +p Foo.instance_method(:a).source_location[1] - base, Foo.instance_method(:a=).source_location[1] - base +p Foo.new.method(:r).source_location[0] == __FILE__ +class Foo + alias rr r +end +p Foo.instance_method(:rr).source_location[1] - base +", @" +2 +3 +4 +4 +true +2 "); } } diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 369e2fa1a..4217cc361 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -751,15 +751,27 @@ private static void DefineAccessor(RubyScope/*!*/ scope, RubyModule/*!*/ self, s } } + // the methods' source_location is where attr_* was called + string sourcePath; + int sourceLine; + if (scope.IsEmpty || !RubyUtils.TryGetCallerSourceLocation(scope, out sourcePath, out sourceLine)) { + sourcePath = null; + sourceLine = 0; + } + if (readable) { var flags = (RubyMemberFlags)RubyUtils.GetSpecialMethodVisibility(visibility, name); self.WarnMethodRedefinition(name); - self.AddMethod(scope.RubyContext, name, new RubyAttributeReaderInfo(flags, self, varName)); + self.AddMethod(scope.RubyContext, name, new RubyAttributeReaderInfo(flags, self, varName) { + SourcePath = sourcePath, SourceLine = sourceLine + }); } if (writable) { self.WarnMethodRedefinition(name + "="); - self.AddMethod(scope.RubyContext, name + "=", new RubyAttributeWriterInfo((RubyMemberFlags)visibility, self, varName)); + self.AddMethod(scope.RubyContext, name + "=", new RubyAttributeWriterInfo((RubyMemberFlags)visibility, self, varName) { + SourcePath = sourcePath, SourceLine = sourceLine + }); } } diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index c54edd0fe..98652e6a1 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -360,6 +360,16 @@ internal static RubyArray GetSourceLocation(RubyMemberInfo/*!*/ info, string/*!* }; } + // an attr_reader's, attr_writer's or attr_accessor's method is located where that was called, + // unless that was the prelude, which stands in for C + var accessorInfo = info as RubyAttributeAccessorInfo; + if (accessorInfo != null && accessorInfo.SourcePath != null && !RubyStackTraceBuilder.IsInternalFile(accessorInfo.SourcePath)) { + return new RubyArray(2) { + accessorInfo.DeclaringModule.Context.EncodePath(accessorInfo.SourcePath), + accessorInfo.SourceLine + }; + } + // a method define_method made out of a block is located where the block was written // (unless that is the prelude, which stands in for C) var lambdaInfo = info as RubyLambdaMethodInfo; diff --git a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs index d1830281f..dc185862b 100644 --- a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs @@ -29,6 +29,19 @@ public abstract class RubyAttributeAccessorInfo : RubyMemberInfo { protected internal string/*!*/ InstanceVariableName { get { return _instanceVariableName; } } + /// + /// Where the attr_reader, attr_writer or attr_accessor that made the method was called (MRI + /// reports that as the method's source_location), or null where that was not known cheaply. + /// + public string SourcePath { get; set; } + public int SourceLine { get; set; } + + protected T/*!*/ CopyLocationTo(T/*!*/ copy) where T : RubyAttributeAccessorInfo { + copy.SourcePath = SourcePath; + copy.SourceLine = SourceLine; + return copy; + } + protected RubyAttributeAccessorInfo(RubyMemberFlags flags, RubyModule/*!*/ declaringModule, string/*!*/ variableName) : base(flags, declaringModule) { Assert.NotEmpty(variableName); @@ -114,7 +127,7 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA } protected internal override RubyMemberInfo/*!*/ Copy(RubyMemberFlags flags, RubyModule/*!*/ module) { - return new RubyAttributeReaderInfo(flags, module, InstanceVariableName); + return CopyLocationTo(new RubyAttributeReaderInfo(flags, module, InstanceVariableName)); } public override RubyMemberInfo TrySelectOverload(Type/*!*/[]/*!*/ parameterTypes) { @@ -158,7 +171,7 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA } protected internal override RubyMemberInfo/*!*/ Copy(RubyMemberFlags flags, RubyModule/*!*/ module) { - return new RubyAttributeWriterInfo(flags, module, InstanceVariableName); + return CopyLocationTo(new RubyAttributeWriterInfo(flags, module, InstanceVariableName)); } // the value to assign: Method#arity 1, #parameters [[:req]] From 964f587b60268bfdf9712385fded56762946d609 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:38:57 +0000 Subject: [PATCH 356/439] Array#pack notices a format resized while whitespace or a comment follows the last directive pack_pack checks on every byte of the format it steps over that the format was not resized under it (a #to_str or #to_int that changed it), raising RuntimeError "format string modified". IronRuby checked only before each directive, so [o].pack("a" + " " * n) with an o#to_str that cleared the format went on. The check is now also made at the end when the format has whitespace or a comment after its last directive; a format that ends with a directive is, as in MRI, not checked again. Checked against CRuby 4.0.10: TestPack#test_format_string_modified_by_to_str passes; ruby/spec core/array/pack and string/unpack and the pack and unpack matrices unchanged. New IronRuby.Tests: Pack_FormatModifiedTrailing1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ArrayTests.cs | 32 ++++++++++++++++++++++++ Src/Libraries/Builtins/RubyEncoder.cs | 19 ++++++++++++-- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 7dc7dab1b..25d925dce 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1483,6 +1483,7 @@ public Tests(Driver/*!*/ driver) { Range_Recursive1, Array_JoinRecursive1, Array_JoinNested1, + Pack_FormatModifiedTrailing1, Array_RangeLongEnd1, Array_DuckRangeIndex1, Array_HashRecursiveElement1, diff --git a/Src/IronRuby.Tests/Runtime/ArrayTests.cs b/Src/IronRuby.Tests/Runtime/ArrayTests.cs index a6d5097f4..14a6d28a7 100644 --- a/Src/IronRuby.Tests/Runtime/ArrayTests.cs +++ b/Src/IronRuby.Tests/Runtime/ArrayTests.cs @@ -678,6 +678,38 @@ public void Array_JoinNested1() { # # # +"); + } + + /// + /// Array#pack checks on every byte of the format it steps over that a conversion did not resize the format, + /// so whitespace or a comment after the last directive notices too (CRuby's TestPack#test_format_string_modified_by_to_str). + /// + public void Pack_FormatModifiedTrailing1() { + TestOutput(@" +fmt = +""a "" +o = Object.new +o.define_singleton_method(:to_str) do + fmt.clear + ""A"" +end +begin + [o].pack(fmt) +rescue => e + p e +end +fmt = +""a# comment"" +begin + [o].pack(fmt) +rescue => e + p e +end +fmt = +""a"" +p [o].pack(fmt) +", @" +# +# +""A"" "); } } diff --git a/Src/Libraries/Builtins/RubyEncoder.cs b/Src/Libraries/Builtins/RubyEncoder.cs index cb5c138ab..7fa381db7 100644 --- a/Src/Libraries/Builtins/RubyEncoder.cs +++ b/Src/Libraries/Builtins/RubyEncoder.cs @@ -1252,6 +1252,19 @@ private static bool IsKnownDirective(char c) { /// comes before it has been done, as it was when the format was read as the work went along (MRI /// reads it so too: ["x"].pack("Cy") is a TypeError for the "x", not the unknown 'y'). /// + // Whether the format goes on past its last directive with whitespace or a comment, which + // no directive contains. + private static bool EndsOutsideDirective(string/*!*/ format) { + if (format.Length == 0) { + return false; + } + if (Char.IsWhiteSpace(format[format.Length - 1])) { + return true; + } + int comment = format.LastIndexOf('#'); + return comment >= 0 && format.IndexOf('\n', comment) < 0; + } + private sealed class ParsedFormat { internal readonly FormatDirective[]/*!*/ Directives; private readonly bool _invalid; @@ -1548,8 +1561,10 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { i += count; } // The directive MRI cannot read is reached through the same check as the others, - // so a format a conversion has resized fails on that first. - if (parsed.IsInvalid && format.GetByteCount() != formatLength) { + // so a format a conversion has resized fails on that first. So does whitespace or a + // comment after the last directive: pack_pack checks on every byte of the format + // it steps over, not only before a directive. + if ((parsed.IsInvalid || EndsOutsideDirective(formatString)) && format.GetByteCount() != formatLength) { throw RubyExceptions.CreateRuntimeError("format string modified"); } parsed.ThrowIfInvalid(formatString, true); From 170fc4fe3ad1ae7ff25d8b09cc816553b3401f74 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:39:06 +0000 Subject: [PATCH 357/439] cruby-test: baseline after round five test_pack, test_module, test_proc, test_regexp, test_method and test_class swept again on top of round four's baseline: 6,665 passing. test_class's one new failure is test_safe_multi_ractor_subclasses_list_mutation, which flips from run to run on the base build too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index 98cc657e0..5af9e934c 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 66 clean, 75 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,660 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,665 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 80fa7a084..fba8e3e89 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -14,7 +14,7 @@ test_bignum 73 tests 1 failures 2 errors 0 sk test_box 65 tests 5 failures 22 errors 31 skips test_call 65 tests 2 failures 0 errors 0 skips test_case 6 tests 0 failures 0 errors 0 skips -test_class 62 tests 2 failures 1 errors 0 skips +test_class 62 tests 3 failures 1 errors 0 skips test_clone 7 tests 0 failures 0 errors 0 skips test_comparable 11 tests 0 failures 0 errors 0 skips test_compile_prism 182 tests 1 failures 179 errors 0 skips @@ -74,7 +74,7 @@ test_metaclass 1 tests 0 failures 0 errors 0 sk test_method 99 tests 5 failures 0 errors 0 skips test_method_cache 4 tests 0 failures 0 errors 0 skips test_mixed_unicode_escapes 1 tests 1 failures 0 errors 0 skips -test_module 195 tests 6 failures 8 errors 0 skips +test_module 195 tests 5 failures 8 errors 0 skips test_name_error 11 tests 0 failures 0 errors 0 skips test_nomethod_error 10 tests 0 failures 0 errors 0 skips test_not 2 tests 0 failures 0 errors 0 skips @@ -83,13 +83,13 @@ test_object 67 tests 4 failures 0 errors 0 sk test_object_id 132 tests 0 failures 0 errors 0 skips test_objectspace 37 tests 10 failures 8 errors 0 skips test_optimization 90 tests 47 failures 23 errors 0 skips -test_pack 56 tests 2 failures 0 errors 0 skips +test_pack 56 tests 1 failures 0 errors 0 skips test_parse 107 tests 16 failures 1 errors 0 skips test_path 6 tests 0 failures 0 errors 0 skips test_pattern_matching 30 tests 0 failures 0 errors 0 skips test_pipe 12 tests 0 failures 2 errors 0 skips test_primitive 25 tests 0 failures 0 errors 0 skips -test_proc 120 tests 3 failures 1 errors 0 skips +test_proc 120 tests 2 failures 1 errors 0 skips test_process 141 tests 25 failures 18 errors 1 skips test_ractor 19 tests 10 failures 0 errors 0 skips test_rand 41 tests 0 failures 0 errors 0 skips @@ -99,7 +99,7 @@ test_rational 52 tests 0 failures 0 errors 0 sk test_rational2 1 tests 0 failures 0 errors 0 skips test_readpartial 4 tests 1 failures 0 errors 0 skips test_refinement 122 tests 6 failures 2 errors 0 skips -test_regexp 167 tests 32 failures 8 errors 0 skips +test_regexp 167 tests 29 failures 8 errors 0 skips test_require 52 tests 9 failures 10 errors 0 skips test_require_lib 39 tests 0 failures 2 errors 0 skips test_rubyoptions 68 tests 51 failures 1 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 66 clean, 75 with failures, 1 without a summary -10369 tests, 2555808 assertions, 502 failures, 3138 errors, 69 skips; 6660 passing +10369 tests, 2552101 assertions, 497 failures, 3138 errors, 69 skips; 6665 passing From dd0dee1bac3d595d7f1b05b242f4e941a6c6fe46 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:50:51 +0000 Subject: [PATCH 358/439] Census: name the refusal of a body that evaluates a literal on every call perf/literalcode keeps a body that evaluates a literal block on every call out of light frames before the light rewrite runs, so the census and IR_LIGHT_FRAMES=why reported it as "body needs its scope after the rewrite", the reason for a body the rewrite gave up on. It is now "literal evaluated on every call": 4,183 of the 4,234 methods of Src/StdLib and Util/bench under that reason; 51 remain the rewrite's. The census counts are unchanged (light frames 24,020, 82.4%; JIT the same; no method's verdict changed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs index 42a98ab35..5e21d60e8 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/MethodDefinition.cs @@ -317,7 +317,9 @@ public MethodDefinition(LexicalScope/*!*/ definedScope, Expression target, strin string why = !(allowLightFrame && LightFramesEnabled) ? "not allowed" : definitionRefinements != null ? "refinements" : gen.Profiler != null ? "profiler" : gen.TraceEnabled ? "trace" : gen.CompilerOptions.IsEval ? "eval" : scope.HasClosures ? "defines a closure (block literal)" : - WhyNotLightFrameCandidate() ?? "body needs its scope after the rewrite"; + WhyNotLightFrameCandidate() ?? + (LightStraightLiteralEnabled && EvaluatesLiteralOnEveryCall() ? "literal evaluated on every call" : + "body needs its scope after the rewrite"); if (LightFramesWhy) { Console.Error.WriteLine("[light] why not: {0} ({1}:{2}): {3}", _name, gen.SourcePath, Location.Start.Line, why); } From b04c5a0aa9b82cef43a791b7e6532f977383ba81 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:59:58 +0000 Subject: [PATCH 359/439] /i takes the characters Onigmo's case folding takes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under /i Onigmo matches a character with every character its case folding takes for it. .NET's IgnoreCase leaves some of them out: - the special foldings: U+017F LONG S to s, U+00B5 MICRO SIGN to mu, U+0345 to iota, final sigma, the Greek symbol forms, U+1E9B, the Cyrillic variants U+1C80-U+1C88; - the characters newer than its Unicode tables; - every character above U+FFFF, which it sees as two surrogates. So "ſ" =~ /s/i, "µ" =~ /[[:upper:]]/i and "\u{10428}" =~ /\u{10400}/i matched in CRuby 4.0 and not in IronRuby. It also takes some Onigmo does not: U+212A KELVIN SIGN into /\w/i, where Onigmo's ASCII \w folds nothing. The groups of characters Onigmo's /i takes for one another are generated from CRuby (Util/gen-case-fold-groups.rb, Src/Ruby/Builtins/CaseFoldGroups.Generated.cs): each character's String#downcase(:fold), checked against CRuby's own /\A[x]\z/i. RegexpTransformer tracks /i and (?i) / (?-i) as it parses (_ignoreCase, as _extended), and for a Unicode subject (not the ASCII-8BIT or ISO-8859-1 ctype translations): - a literal character, or a \u escape, in a group .NET does not fold by itself becomes the class of its group, matched with IgnoreCase as before; - a class takes, member by member, everything its members fold to: a character, a range, a property, a POSIX class but in (?a), and not \w \d \s \h (Onigmo folds nothing into them) nor a nested class, which folded its own. It is emitted case-sensitively, (?-i:[...]), so that .NET adds nothing: [s\w]/i takes U+017F and not U+212A, and [a-z&&\w]/i neither, as in CRuby; - \w \d \s \h outside a class are emitted case-sensitively, and a property escape with what it folds to. Patterns with no /i are as before, and a literal in a group .NET folds (a, A) is emitted as before. A folded property (\p{L}, [[:upper:]]) is cached per table, so compiling 2,000 /i patterns with such classes takes 1.1-1.2 s, against 1.8 s before; matching takes the same time (scan of /[a-z_][\w-]*/i, /hello\s+world/i, /\w+/i, /[aeiou]{2}/i and /foo/i over 96 KB, CPU time best of five: within 3% each way). Left: U+023A/U+2C65 and U+023E/U+2C66, which Onigmo does not take for one another, still match as literals under /i, as .NET folds them (as before); the "character class has duplicated range" warning CRuby gives under -w is not given. Checked with Regex_CaseFoldGroups1 (output from CRuby 4.0), every pair of characters in every group of CRuby's (2,984 characters, as a literal and as a class), probes of inline (?i)/(?-i), negated classes, intersections, POSIX and property classes, ASCII ctypes in and out of classes, astral characters with quantifiers, scan and gsub (the same as CRuby), IronRuby.Tests, the regexp, matchdata, String#scan/gsub/sub/match/index/ split/casecmp, Symbol#casecmp, StringScanner and language/regexp specs (no change from the base build), and the differential matrices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- CLAUDE.md | 1 + Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 30 + Src/Ruby/Builtins/CaseFoldGroups.Generated.cs | 1485 +++++++++++++++++ Src/Ruby/Builtins/CaseFoldGroups.cs | 118 ++ Src/Ruby/Builtins/RegexpTransformer.cs | 112 ++ Util/gen-case-fold-groups.rb | 58 + 7 files changed, 1805 insertions(+) create mode 100644 Src/Ruby/Builtins/CaseFoldGroups.Generated.cs create mode 100644 Src/Ruby/Builtins/CaseFoldGroups.cs create mode 100644 Util/gen-case-fold-groups.rb diff --git a/CLAUDE.md b/CLAUDE.md index 9bb4a27f9..7f3b466e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -169,6 +169,7 @@ invalid definition is a build error (`IRGEN001`). To read what was generated, bu | `Src/Ruby/Builtins/UnicodeProperties.Generated.cs` | `Util/gen-unicode-properties.rb` | | | `Src/Ruby/Runtime/Utf8MacTables.Generated.cs` | `Util/gen-utf8-mac.rb` (with CRuby) | the oracle CRuby's UTF8-MAC converters change | | `Src/Ruby/Builtins/InspectPrintable.Generated.cs` | `Util/gen-inspect-printable.rb` (with CRuby) | the oracle CRuby's Onigmo ctype tables change | +| `Src/Ruby/Builtins/CaseFoldGroups.Generated.cs` | `Util/gen-case-fold-groups.rb` (with CRuby) | the oracle CRuby's case folding (its Unicode version) changes | | `*/AotSubclasses.Generated.cs` | `Util/aot/gen-subclasses.rb` | a library class is added | | `Src/Libraries/Rbs/RbsNodes.Generated.cs` | `Src/Libraries/Rbs/generate.rb` | | diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a9f9dce5e..ec07b67f9 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -218,6 +218,7 @@ public Tests(Driver/*!*/ driver) { Regex_LiteralEncodings1, Regex_PropertyEncoding1, Regex_BinaryCtype1, + Regex_CaseFoldGroups1, Regex_Latin1Ctype1, StringScanner_InsideCharacter1, StringScanner_ShorterSubject1, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 7eb6f5d51..27b395602 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -1114,6 +1114,36 @@ p l(""abc"").scan(/\w/).size "); } + /// + /// Under /i a character or class takes the characters Onigmo's case folding takes for it, which .NET's IgnoreCase + /// leaves out in part: U+017F folds to s, U+00B5 to mu, U+212A to k, astral letters to their pairs. The ASCII + /// ctypes (\w) fold nothing, and a class takes nothing .NET would add (U+212A into \w). + /// + public void Regex_CaseFoldGroups1() { + TestOutput(@" +c = [""µ"", ""ſ"", ""K"", ""ͅ"", ""ς"", ""ı"", ""s"", ""k""] +[/[[:upper:]]/i, /[a-z]/i, /[^[:upper:]]/i, /\w/i, /[s\w]/i, /[a-z&&\w]/i, /s/i, /Μ/i, /\p{Lu}/i, /(?i:s)/, /(?i)(?-i:s)/].each_with_index do |r, i| + puts ""#{i}: #{c.map { |x| (x =~ r) ? 1 : 0 }.join}"" +end +p ""\u{10428}"" =~ /\u{10400}/i, ""\u{10428}"" =~ /[\u{10400}]/i, ""a\u{10428}\u{10400}b"".gsub(/\u{10400}/i, ""-"") +", @" +0: 11111011 +1: 01100011 +2: 00000100 +3: 00000011 +4: 01000011 +5: 00000011 +6: 01000010 +7: 10000000 +8: 11111011 +9: 01000010 +10: 00000010 +0 +0 +""a--b"" +"); + } + public void Regex_BinaryCtype1() { TestOutput(@" require 'ruby4' diff --git a/Src/Ruby/Builtins/CaseFoldGroups.Generated.cs b/Src/Ruby/Builtins/CaseFoldGroups.Generated.cs new file mode 100644 index 000000000..a89eda65a --- /dev/null +++ b/Src/Ruby/Builtins/CaseFoldGroups.Generated.cs @@ -0,0 +1,1485 @@ +// generated by Util/gen-case-fold-groups.rb from CRuby 4.0.10 - do not edit +namespace IronRuby.Builtins { + internal static partial class CaseFoldGroups { + // The characters Onigmo's /i takes for one another, a group each, by its first member. + private static readonly int[][] _groups = new int[][] { + new[] { 0x41, 0x61 }, + new[] { 0x42, 0x62 }, + new[] { 0x43, 0x63 }, + new[] { 0x44, 0x64 }, + new[] { 0x45, 0x65 }, + new[] { 0x46, 0x66 }, + new[] { 0x47, 0x67 }, + new[] { 0x48, 0x68 }, + new[] { 0x49, 0x69 }, + new[] { 0x4A, 0x6A }, + new[] { 0x4B, 0x6B, 0x212A }, + new[] { 0x4C, 0x6C }, + new[] { 0x4D, 0x6D }, + new[] { 0x4E, 0x6E }, + new[] { 0x4F, 0x6F }, + new[] { 0x50, 0x70 }, + new[] { 0x51, 0x71 }, + new[] { 0x52, 0x72 }, + new[] { 0x53, 0x73, 0x17F }, + new[] { 0x54, 0x74 }, + new[] { 0x55, 0x75 }, + new[] { 0x56, 0x76 }, + new[] { 0x57, 0x77 }, + new[] { 0x58, 0x78 }, + new[] { 0x59, 0x79 }, + new[] { 0x5A, 0x7A }, + new[] { 0xB5, 0x39C, 0x3BC }, + new[] { 0xC0, 0xE0 }, + new[] { 0xC1, 0xE1 }, + new[] { 0xC2, 0xE2 }, + new[] { 0xC3, 0xE3 }, + new[] { 0xC4, 0xE4 }, + new[] { 0xC5, 0xE5, 0x212B }, + new[] { 0xC6, 0xE6 }, + new[] { 0xC7, 0xE7 }, + new[] { 0xC8, 0xE8 }, + new[] { 0xC9, 0xE9 }, + new[] { 0xCA, 0xEA }, + new[] { 0xCB, 0xEB }, + new[] { 0xCC, 0xEC }, + new[] { 0xCD, 0xED }, + new[] { 0xCE, 0xEE }, + new[] { 0xCF, 0xEF }, + new[] { 0xD0, 0xF0 }, + new[] { 0xD1, 0xF1 }, + new[] { 0xD2, 0xF2 }, + new[] { 0xD3, 0xF3 }, + new[] { 0xD4, 0xF4 }, + new[] { 0xD5, 0xF5 }, + new[] { 0xD6, 0xF6 }, + new[] { 0xD8, 0xF8 }, + new[] { 0xD9, 0xF9 }, + new[] { 0xDA, 0xFA }, + new[] { 0xDB, 0xFB }, + new[] { 0xDC, 0xFC }, + new[] { 0xDD, 0xFD }, + new[] { 0xDE, 0xFE }, + new[] { 0xDF, 0x1E9E }, + new[] { 0xFF, 0x178 }, + new[] { 0x100, 0x101 }, + new[] { 0x102, 0x103 }, + new[] { 0x104, 0x105 }, + new[] { 0x106, 0x107 }, + new[] { 0x108, 0x109 }, + new[] { 0x10A, 0x10B }, + new[] { 0x10C, 0x10D }, + new[] { 0x10E, 0x10F }, + new[] { 0x110, 0x111 }, + new[] { 0x112, 0x113 }, + new[] { 0x114, 0x115 }, + new[] { 0x116, 0x117 }, + new[] { 0x118, 0x119 }, + new[] { 0x11A, 0x11B }, + new[] { 0x11C, 0x11D }, + new[] { 0x11E, 0x11F }, + new[] { 0x120, 0x121 }, + new[] { 0x122, 0x123 }, + new[] { 0x124, 0x125 }, + new[] { 0x126, 0x127 }, + new[] { 0x128, 0x129 }, + new[] { 0x12A, 0x12B }, + new[] { 0x12C, 0x12D }, + new[] { 0x12E, 0x12F }, + new[] { 0x132, 0x133 }, + new[] { 0x134, 0x135 }, + new[] { 0x136, 0x137 }, + new[] { 0x139, 0x13A }, + new[] { 0x13B, 0x13C }, + new[] { 0x13D, 0x13E }, + new[] { 0x13F, 0x140 }, + new[] { 0x141, 0x142 }, + new[] { 0x143, 0x144 }, + new[] { 0x145, 0x146 }, + new[] { 0x147, 0x148 }, + new[] { 0x14A, 0x14B }, + new[] { 0x14C, 0x14D }, + new[] { 0x14E, 0x14F }, + new[] { 0x150, 0x151 }, + new[] { 0x152, 0x153 }, + new[] { 0x154, 0x155 }, + new[] { 0x156, 0x157 }, + new[] { 0x158, 0x159 }, + new[] { 0x15A, 0x15B }, + new[] { 0x15C, 0x15D }, + new[] { 0x15E, 0x15F }, + new[] { 0x160, 0x161 }, + new[] { 0x162, 0x163 }, + new[] { 0x164, 0x165 }, + new[] { 0x166, 0x167 }, + new[] { 0x168, 0x169 }, + new[] { 0x16A, 0x16B }, + new[] { 0x16C, 0x16D }, + new[] { 0x16E, 0x16F }, + new[] { 0x170, 0x171 }, + new[] { 0x172, 0x173 }, + new[] { 0x174, 0x175 }, + new[] { 0x176, 0x177 }, + new[] { 0x179, 0x17A }, + new[] { 0x17B, 0x17C }, + new[] { 0x17D, 0x17E }, + new[] { 0x180, 0x243 }, + new[] { 0x181, 0x253 }, + new[] { 0x182, 0x183 }, + new[] { 0x184, 0x185 }, + new[] { 0x186, 0x254 }, + new[] { 0x187, 0x188 }, + new[] { 0x189, 0x256 }, + new[] { 0x18A, 0x257 }, + new[] { 0x18B, 0x18C }, + new[] { 0x18E, 0x1DD }, + new[] { 0x18F, 0x259 }, + new[] { 0x190, 0x25B }, + new[] { 0x191, 0x192 }, + new[] { 0x193, 0x260 }, + new[] { 0x194, 0x263 }, + new[] { 0x195, 0x1F6 }, + new[] { 0x196, 0x269 }, + new[] { 0x197, 0x268 }, + new[] { 0x198, 0x199 }, + new[] { 0x19A, 0x23D }, + new[] { 0x19B, 0xA7DC }, + new[] { 0x19C, 0x26F }, + new[] { 0x19D, 0x272 }, + new[] { 0x19E, 0x220 }, + new[] { 0x19F, 0x275 }, + new[] { 0x1A0, 0x1A1 }, + new[] { 0x1A2, 0x1A3 }, + new[] { 0x1A4, 0x1A5 }, + new[] { 0x1A6, 0x280 }, + new[] { 0x1A7, 0x1A8 }, + new[] { 0x1A9, 0x283 }, + new[] { 0x1AC, 0x1AD }, + new[] { 0x1AE, 0x288 }, + new[] { 0x1AF, 0x1B0 }, + new[] { 0x1B1, 0x28A }, + new[] { 0x1B2, 0x28B }, + new[] { 0x1B3, 0x1B4 }, + new[] { 0x1B5, 0x1B6 }, + new[] { 0x1B7, 0x292 }, + new[] { 0x1B8, 0x1B9 }, + new[] { 0x1BC, 0x1BD }, + new[] { 0x1BF, 0x1F7 }, + new[] { 0x1C4, 0x1C5, 0x1C6 }, + new[] { 0x1C7, 0x1C8, 0x1C9 }, + new[] { 0x1CA, 0x1CB, 0x1CC }, + new[] { 0x1CD, 0x1CE }, + new[] { 0x1CF, 0x1D0 }, + new[] { 0x1D1, 0x1D2 }, + new[] { 0x1D3, 0x1D4 }, + new[] { 0x1D5, 0x1D6 }, + new[] { 0x1D7, 0x1D8 }, + new[] { 0x1D9, 0x1DA }, + new[] { 0x1DB, 0x1DC }, + new[] { 0x1DE, 0x1DF }, + new[] { 0x1E0, 0x1E1 }, + new[] { 0x1E2, 0x1E3 }, + new[] { 0x1E4, 0x1E5 }, + new[] { 0x1E6, 0x1E7 }, + new[] { 0x1E8, 0x1E9 }, + new[] { 0x1EA, 0x1EB }, + new[] { 0x1EC, 0x1ED }, + new[] { 0x1EE, 0x1EF }, + new[] { 0x1F1, 0x1F2, 0x1F3 }, + new[] { 0x1F4, 0x1F5 }, + new[] { 0x1F8, 0x1F9 }, + new[] { 0x1FA, 0x1FB }, + new[] { 0x1FC, 0x1FD }, + new[] { 0x1FE, 0x1FF }, + new[] { 0x200, 0x201 }, + new[] { 0x202, 0x203 }, + new[] { 0x204, 0x205 }, + new[] { 0x206, 0x207 }, + new[] { 0x208, 0x209 }, + new[] { 0x20A, 0x20B }, + new[] { 0x20C, 0x20D }, + new[] { 0x20E, 0x20F }, + new[] { 0x210, 0x211 }, + new[] { 0x212, 0x213 }, + new[] { 0x214, 0x215 }, + new[] { 0x216, 0x217 }, + new[] { 0x218, 0x219 }, + new[] { 0x21A, 0x21B }, + new[] { 0x21C, 0x21D }, + new[] { 0x21E, 0x21F }, + new[] { 0x222, 0x223 }, + new[] { 0x224, 0x225 }, + new[] { 0x226, 0x227 }, + new[] { 0x228, 0x229 }, + new[] { 0x22A, 0x22B }, + new[] { 0x22C, 0x22D }, + new[] { 0x22E, 0x22F }, + new[] { 0x230, 0x231 }, + new[] { 0x232, 0x233 }, + new[] { 0x23B, 0x23C }, + new[] { 0x23F, 0x2C7E }, + new[] { 0x240, 0x2C7F }, + new[] { 0x241, 0x242 }, + new[] { 0x244, 0x289 }, + new[] { 0x245, 0x28C }, + new[] { 0x246, 0x247 }, + new[] { 0x248, 0x249 }, + new[] { 0x24A, 0x24B }, + new[] { 0x24C, 0x24D }, + new[] { 0x24E, 0x24F }, + new[] { 0x250, 0x2C6F }, + new[] { 0x251, 0x2C6D }, + new[] { 0x252, 0x2C70 }, + new[] { 0x25C, 0xA7AB }, + new[] { 0x261, 0xA7AC }, + new[] { 0x264, 0xA7CB }, + new[] { 0x265, 0xA78D }, + new[] { 0x266, 0xA7AA }, + new[] { 0x26A, 0xA7AE }, + new[] { 0x26B, 0x2C62 }, + new[] { 0x26C, 0xA7AD }, + new[] { 0x271, 0x2C6E }, + new[] { 0x27D, 0x2C64 }, + new[] { 0x282, 0xA7C5 }, + new[] { 0x287, 0xA7B1 }, + new[] { 0x29D, 0xA7B2 }, + new[] { 0x29E, 0xA7B0 }, + new[] { 0x345, 0x399, 0x3B9, 0x1FBE }, + new[] { 0x370, 0x371 }, + new[] { 0x372, 0x373 }, + new[] { 0x376, 0x377 }, + new[] { 0x37B, 0x3FD }, + new[] { 0x37C, 0x3FE }, + new[] { 0x37D, 0x3FF }, + new[] { 0x37F, 0x3F3 }, + new[] { 0x386, 0x3AC }, + new[] { 0x388, 0x3AD }, + new[] { 0x389, 0x3AE }, + new[] { 0x38A, 0x3AF }, + new[] { 0x38C, 0x3CC }, + new[] { 0x38E, 0x3CD }, + new[] { 0x38F, 0x3CE }, + new[] { 0x391, 0x3B1 }, + new[] { 0x392, 0x3B2, 0x3D0 }, + new[] { 0x393, 0x3B3 }, + new[] { 0x394, 0x3B4 }, + new[] { 0x395, 0x3B5, 0x3F5 }, + new[] { 0x396, 0x3B6 }, + new[] { 0x397, 0x3B7 }, + new[] { 0x398, 0x3B8, 0x3D1, 0x3F4 }, + new[] { 0x39A, 0x3BA, 0x3F0 }, + new[] { 0x39B, 0x3BB }, + new[] { 0x39D, 0x3BD }, + new[] { 0x39E, 0x3BE }, + new[] { 0x39F, 0x3BF }, + new[] { 0x3A0, 0x3C0, 0x3D6 }, + new[] { 0x3A1, 0x3C1, 0x3F1 }, + new[] { 0x3A3, 0x3C2, 0x3C3 }, + new[] { 0x3A4, 0x3C4 }, + new[] { 0x3A5, 0x3C5 }, + new[] { 0x3A6, 0x3C6, 0x3D5 }, + new[] { 0x3A7, 0x3C7 }, + new[] { 0x3A8, 0x3C8 }, + new[] { 0x3A9, 0x3C9, 0x2126 }, + new[] { 0x3AA, 0x3CA }, + new[] { 0x3AB, 0x3CB }, + new[] { 0x3CF, 0x3D7 }, + new[] { 0x3D8, 0x3D9 }, + new[] { 0x3DA, 0x3DB }, + new[] { 0x3DC, 0x3DD }, + new[] { 0x3DE, 0x3DF }, + new[] { 0x3E0, 0x3E1 }, + new[] { 0x3E2, 0x3E3 }, + new[] { 0x3E4, 0x3E5 }, + new[] { 0x3E6, 0x3E7 }, + new[] { 0x3E8, 0x3E9 }, + new[] { 0x3EA, 0x3EB }, + new[] { 0x3EC, 0x3ED }, + new[] { 0x3EE, 0x3EF }, + new[] { 0x3F2, 0x3F9 }, + new[] { 0x3F7, 0x3F8 }, + new[] { 0x3FA, 0x3FB }, + new[] { 0x400, 0x450 }, + new[] { 0x401, 0x451 }, + new[] { 0x402, 0x452 }, + new[] { 0x403, 0x453 }, + new[] { 0x404, 0x454 }, + new[] { 0x405, 0x455 }, + new[] { 0x406, 0x456 }, + new[] { 0x407, 0x457 }, + new[] { 0x408, 0x458 }, + new[] { 0x409, 0x459 }, + new[] { 0x40A, 0x45A }, + new[] { 0x40B, 0x45B }, + new[] { 0x40C, 0x45C }, + new[] { 0x40D, 0x45D }, + new[] { 0x40E, 0x45E }, + new[] { 0x40F, 0x45F }, + new[] { 0x410, 0x430 }, + new[] { 0x411, 0x431 }, + new[] { 0x412, 0x432, 0x1C80 }, + new[] { 0x413, 0x433 }, + new[] { 0x414, 0x434, 0x1C81 }, + new[] { 0x415, 0x435 }, + new[] { 0x416, 0x436 }, + new[] { 0x417, 0x437 }, + new[] { 0x418, 0x438 }, + new[] { 0x419, 0x439 }, + new[] { 0x41A, 0x43A }, + new[] { 0x41B, 0x43B }, + new[] { 0x41C, 0x43C }, + new[] { 0x41D, 0x43D }, + new[] { 0x41E, 0x43E, 0x1C82 }, + new[] { 0x41F, 0x43F }, + new[] { 0x420, 0x440 }, + new[] { 0x421, 0x441, 0x1C83 }, + new[] { 0x422, 0x442, 0x1C84, 0x1C85 }, + new[] { 0x423, 0x443 }, + new[] { 0x424, 0x444 }, + new[] { 0x425, 0x445 }, + new[] { 0x426, 0x446 }, + new[] { 0x427, 0x447 }, + new[] { 0x428, 0x448 }, + new[] { 0x429, 0x449 }, + new[] { 0x42A, 0x44A, 0x1C86 }, + new[] { 0x42B, 0x44B }, + new[] { 0x42C, 0x44C }, + new[] { 0x42D, 0x44D }, + new[] { 0x42E, 0x44E }, + new[] { 0x42F, 0x44F }, + new[] { 0x460, 0x461 }, + new[] { 0x462, 0x463, 0x1C87 }, + new[] { 0x464, 0x465 }, + new[] { 0x466, 0x467 }, + new[] { 0x468, 0x469 }, + new[] { 0x46A, 0x46B }, + new[] { 0x46C, 0x46D }, + new[] { 0x46E, 0x46F }, + new[] { 0x470, 0x471 }, + new[] { 0x472, 0x473 }, + new[] { 0x474, 0x475 }, + new[] { 0x476, 0x477 }, + new[] { 0x478, 0x479 }, + new[] { 0x47A, 0x47B }, + new[] { 0x47C, 0x47D }, + new[] { 0x47E, 0x47F }, + new[] { 0x480, 0x481 }, + new[] { 0x48A, 0x48B }, + new[] { 0x48C, 0x48D }, + new[] { 0x48E, 0x48F }, + new[] { 0x490, 0x491 }, + new[] { 0x492, 0x493 }, + new[] { 0x494, 0x495 }, + new[] { 0x496, 0x497 }, + new[] { 0x498, 0x499 }, + new[] { 0x49A, 0x49B }, + new[] { 0x49C, 0x49D }, + new[] { 0x49E, 0x49F }, + new[] { 0x4A0, 0x4A1 }, + new[] { 0x4A2, 0x4A3 }, + new[] { 0x4A4, 0x4A5 }, + new[] { 0x4A6, 0x4A7 }, + new[] { 0x4A8, 0x4A9 }, + new[] { 0x4AA, 0x4AB }, + new[] { 0x4AC, 0x4AD }, + new[] { 0x4AE, 0x4AF }, + new[] { 0x4B0, 0x4B1 }, + new[] { 0x4B2, 0x4B3 }, + new[] { 0x4B4, 0x4B5 }, + new[] { 0x4B6, 0x4B7 }, + new[] { 0x4B8, 0x4B9 }, + new[] { 0x4BA, 0x4BB }, + new[] { 0x4BC, 0x4BD }, + new[] { 0x4BE, 0x4BF }, + new[] { 0x4C0, 0x4CF }, + new[] { 0x4C1, 0x4C2 }, + new[] { 0x4C3, 0x4C4 }, + new[] { 0x4C5, 0x4C6 }, + new[] { 0x4C7, 0x4C8 }, + new[] { 0x4C9, 0x4CA }, + new[] { 0x4CB, 0x4CC }, + new[] { 0x4CD, 0x4CE }, + new[] { 0x4D0, 0x4D1 }, + new[] { 0x4D2, 0x4D3 }, + new[] { 0x4D4, 0x4D5 }, + new[] { 0x4D6, 0x4D7 }, + new[] { 0x4D8, 0x4D9 }, + new[] { 0x4DA, 0x4DB }, + new[] { 0x4DC, 0x4DD }, + new[] { 0x4DE, 0x4DF }, + new[] { 0x4E0, 0x4E1 }, + new[] { 0x4E2, 0x4E3 }, + new[] { 0x4E4, 0x4E5 }, + new[] { 0x4E6, 0x4E7 }, + new[] { 0x4E8, 0x4E9 }, + new[] { 0x4EA, 0x4EB }, + new[] { 0x4EC, 0x4ED }, + new[] { 0x4EE, 0x4EF }, + new[] { 0x4F0, 0x4F1 }, + new[] { 0x4F2, 0x4F3 }, + new[] { 0x4F4, 0x4F5 }, + new[] { 0x4F6, 0x4F7 }, + new[] { 0x4F8, 0x4F9 }, + new[] { 0x4FA, 0x4FB }, + new[] { 0x4FC, 0x4FD }, + new[] { 0x4FE, 0x4FF }, + new[] { 0x500, 0x501 }, + new[] { 0x502, 0x503 }, + new[] { 0x504, 0x505 }, + new[] { 0x506, 0x507 }, + new[] { 0x508, 0x509 }, + new[] { 0x50A, 0x50B }, + new[] { 0x50C, 0x50D }, + new[] { 0x50E, 0x50F }, + new[] { 0x510, 0x511 }, + new[] { 0x512, 0x513 }, + new[] { 0x514, 0x515 }, + new[] { 0x516, 0x517 }, + new[] { 0x518, 0x519 }, + new[] { 0x51A, 0x51B }, + new[] { 0x51C, 0x51D }, + new[] { 0x51E, 0x51F }, + new[] { 0x520, 0x521 }, + new[] { 0x522, 0x523 }, + new[] { 0x524, 0x525 }, + new[] { 0x526, 0x527 }, + new[] { 0x528, 0x529 }, + new[] { 0x52A, 0x52B }, + new[] { 0x52C, 0x52D }, + new[] { 0x52E, 0x52F }, + new[] { 0x531, 0x561 }, + new[] { 0x532, 0x562 }, + new[] { 0x533, 0x563 }, + new[] { 0x534, 0x564 }, + new[] { 0x535, 0x565 }, + new[] { 0x536, 0x566 }, + new[] { 0x537, 0x567 }, + new[] { 0x538, 0x568 }, + new[] { 0x539, 0x569 }, + new[] { 0x53A, 0x56A }, + new[] { 0x53B, 0x56B }, + new[] { 0x53C, 0x56C }, + new[] { 0x53D, 0x56D }, + new[] { 0x53E, 0x56E }, + new[] { 0x53F, 0x56F }, + new[] { 0x540, 0x570 }, + new[] { 0x541, 0x571 }, + new[] { 0x542, 0x572 }, + new[] { 0x543, 0x573 }, + new[] { 0x544, 0x574 }, + new[] { 0x545, 0x575 }, + new[] { 0x546, 0x576 }, + new[] { 0x547, 0x577 }, + new[] { 0x548, 0x578 }, + new[] { 0x549, 0x579 }, + new[] { 0x54A, 0x57A }, + new[] { 0x54B, 0x57B }, + new[] { 0x54C, 0x57C }, + new[] { 0x54D, 0x57D }, + new[] { 0x54E, 0x57E }, + new[] { 0x54F, 0x57F }, + new[] { 0x550, 0x580 }, + new[] { 0x551, 0x581 }, + new[] { 0x552, 0x582 }, + new[] { 0x553, 0x583 }, + new[] { 0x554, 0x584 }, + new[] { 0x555, 0x585 }, + new[] { 0x556, 0x586 }, + new[] { 0x10A0, 0x2D00 }, + new[] { 0x10A1, 0x2D01 }, + new[] { 0x10A2, 0x2D02 }, + new[] { 0x10A3, 0x2D03 }, + new[] { 0x10A4, 0x2D04 }, + new[] { 0x10A5, 0x2D05 }, + new[] { 0x10A6, 0x2D06 }, + new[] { 0x10A7, 0x2D07 }, + new[] { 0x10A8, 0x2D08 }, + new[] { 0x10A9, 0x2D09 }, + new[] { 0x10AA, 0x2D0A }, + new[] { 0x10AB, 0x2D0B }, + new[] { 0x10AC, 0x2D0C }, + new[] { 0x10AD, 0x2D0D }, + new[] { 0x10AE, 0x2D0E }, + new[] { 0x10AF, 0x2D0F }, + new[] { 0x10B0, 0x2D10 }, + new[] { 0x10B1, 0x2D11 }, + new[] { 0x10B2, 0x2D12 }, + new[] { 0x10B3, 0x2D13 }, + new[] { 0x10B4, 0x2D14 }, + new[] { 0x10B5, 0x2D15 }, + new[] { 0x10B6, 0x2D16 }, + new[] { 0x10B7, 0x2D17 }, + new[] { 0x10B8, 0x2D18 }, + new[] { 0x10B9, 0x2D19 }, + new[] { 0x10BA, 0x2D1A }, + new[] { 0x10BB, 0x2D1B }, + new[] { 0x10BC, 0x2D1C }, + new[] { 0x10BD, 0x2D1D }, + new[] { 0x10BE, 0x2D1E }, + new[] { 0x10BF, 0x2D1F }, + new[] { 0x10C0, 0x2D20 }, + new[] { 0x10C1, 0x2D21 }, + new[] { 0x10C2, 0x2D22 }, + new[] { 0x10C3, 0x2D23 }, + new[] { 0x10C4, 0x2D24 }, + new[] { 0x10C5, 0x2D25 }, + new[] { 0x10C7, 0x2D27 }, + new[] { 0x10CD, 0x2D2D }, + new[] { 0x10D0, 0x1C90 }, + new[] { 0x10D1, 0x1C91 }, + new[] { 0x10D2, 0x1C92 }, + new[] { 0x10D3, 0x1C93 }, + new[] { 0x10D4, 0x1C94 }, + new[] { 0x10D5, 0x1C95 }, + new[] { 0x10D6, 0x1C96 }, + new[] { 0x10D7, 0x1C97 }, + new[] { 0x10D8, 0x1C98 }, + new[] { 0x10D9, 0x1C99 }, + new[] { 0x10DA, 0x1C9A }, + new[] { 0x10DB, 0x1C9B }, + new[] { 0x10DC, 0x1C9C }, + new[] { 0x10DD, 0x1C9D }, + new[] { 0x10DE, 0x1C9E }, + new[] { 0x10DF, 0x1C9F }, + new[] { 0x10E0, 0x1CA0 }, + new[] { 0x10E1, 0x1CA1 }, + new[] { 0x10E2, 0x1CA2 }, + new[] { 0x10E3, 0x1CA3 }, + new[] { 0x10E4, 0x1CA4 }, + new[] { 0x10E5, 0x1CA5 }, + new[] { 0x10E6, 0x1CA6 }, + new[] { 0x10E7, 0x1CA7 }, + new[] { 0x10E8, 0x1CA8 }, + new[] { 0x10E9, 0x1CA9 }, + new[] { 0x10EA, 0x1CAA }, + new[] { 0x10EB, 0x1CAB }, + new[] { 0x10EC, 0x1CAC }, + new[] { 0x10ED, 0x1CAD }, + new[] { 0x10EE, 0x1CAE }, + new[] { 0x10EF, 0x1CAF }, + new[] { 0x10F0, 0x1CB0 }, + new[] { 0x10F1, 0x1CB1 }, + new[] { 0x10F2, 0x1CB2 }, + new[] { 0x10F3, 0x1CB3 }, + new[] { 0x10F4, 0x1CB4 }, + new[] { 0x10F5, 0x1CB5 }, + new[] { 0x10F6, 0x1CB6 }, + new[] { 0x10F7, 0x1CB7 }, + new[] { 0x10F8, 0x1CB8 }, + new[] { 0x10F9, 0x1CB9 }, + new[] { 0x10FA, 0x1CBA }, + new[] { 0x10FD, 0x1CBD }, + new[] { 0x10FE, 0x1CBE }, + new[] { 0x10FF, 0x1CBF }, + new[] { 0x13A0, 0xAB70 }, + new[] { 0x13A1, 0xAB71 }, + new[] { 0x13A2, 0xAB72 }, + new[] { 0x13A3, 0xAB73 }, + new[] { 0x13A4, 0xAB74 }, + new[] { 0x13A5, 0xAB75 }, + new[] { 0x13A6, 0xAB76 }, + new[] { 0x13A7, 0xAB77 }, + new[] { 0x13A8, 0xAB78 }, + new[] { 0x13A9, 0xAB79 }, + new[] { 0x13AA, 0xAB7A }, + new[] { 0x13AB, 0xAB7B }, + new[] { 0x13AC, 0xAB7C }, + new[] { 0x13AD, 0xAB7D }, + new[] { 0x13AE, 0xAB7E }, + new[] { 0x13AF, 0xAB7F }, + new[] { 0x13B0, 0xAB80 }, + new[] { 0x13B1, 0xAB81 }, + new[] { 0x13B2, 0xAB82 }, + new[] { 0x13B3, 0xAB83 }, + new[] { 0x13B4, 0xAB84 }, + new[] { 0x13B5, 0xAB85 }, + new[] { 0x13B6, 0xAB86 }, + new[] { 0x13B7, 0xAB87 }, + new[] { 0x13B8, 0xAB88 }, + new[] { 0x13B9, 0xAB89 }, + new[] { 0x13BA, 0xAB8A }, + new[] { 0x13BB, 0xAB8B }, + new[] { 0x13BC, 0xAB8C }, + new[] { 0x13BD, 0xAB8D }, + new[] { 0x13BE, 0xAB8E }, + new[] { 0x13BF, 0xAB8F }, + new[] { 0x13C0, 0xAB90 }, + new[] { 0x13C1, 0xAB91 }, + new[] { 0x13C2, 0xAB92 }, + new[] { 0x13C3, 0xAB93 }, + new[] { 0x13C4, 0xAB94 }, + new[] { 0x13C5, 0xAB95 }, + new[] { 0x13C6, 0xAB96 }, + new[] { 0x13C7, 0xAB97 }, + new[] { 0x13C8, 0xAB98 }, + new[] { 0x13C9, 0xAB99 }, + new[] { 0x13CA, 0xAB9A }, + new[] { 0x13CB, 0xAB9B }, + new[] { 0x13CC, 0xAB9C }, + new[] { 0x13CD, 0xAB9D }, + new[] { 0x13CE, 0xAB9E }, + new[] { 0x13CF, 0xAB9F }, + new[] { 0x13D0, 0xABA0 }, + new[] { 0x13D1, 0xABA1 }, + new[] { 0x13D2, 0xABA2 }, + new[] { 0x13D3, 0xABA3 }, + new[] { 0x13D4, 0xABA4 }, + new[] { 0x13D5, 0xABA5 }, + new[] { 0x13D6, 0xABA6 }, + new[] { 0x13D7, 0xABA7 }, + new[] { 0x13D8, 0xABA8 }, + new[] { 0x13D9, 0xABA9 }, + new[] { 0x13DA, 0xABAA }, + new[] { 0x13DB, 0xABAB }, + new[] { 0x13DC, 0xABAC }, + new[] { 0x13DD, 0xABAD }, + new[] { 0x13DE, 0xABAE }, + new[] { 0x13DF, 0xABAF }, + new[] { 0x13E0, 0xABB0 }, + new[] { 0x13E1, 0xABB1 }, + new[] { 0x13E2, 0xABB2 }, + new[] { 0x13E3, 0xABB3 }, + new[] { 0x13E4, 0xABB4 }, + new[] { 0x13E5, 0xABB5 }, + new[] { 0x13E6, 0xABB6 }, + new[] { 0x13E7, 0xABB7 }, + new[] { 0x13E8, 0xABB8 }, + new[] { 0x13E9, 0xABB9 }, + new[] { 0x13EA, 0xABBA }, + new[] { 0x13EB, 0xABBB }, + new[] { 0x13EC, 0xABBC }, + new[] { 0x13ED, 0xABBD }, + new[] { 0x13EE, 0xABBE }, + new[] { 0x13EF, 0xABBF }, + new[] { 0x13F0, 0x13F8 }, + new[] { 0x13F1, 0x13F9 }, + new[] { 0x13F2, 0x13FA }, + new[] { 0x13F3, 0x13FB }, + new[] { 0x13F4, 0x13FC }, + new[] { 0x13F5, 0x13FD }, + new[] { 0x1C88, 0xA64A, 0xA64B }, + new[] { 0x1C89, 0x1C8A }, + new[] { 0x1D79, 0xA77D }, + new[] { 0x1D7D, 0x2C63 }, + new[] { 0x1D8E, 0xA7C6 }, + new[] { 0x1E00, 0x1E01 }, + new[] { 0x1E02, 0x1E03 }, + new[] { 0x1E04, 0x1E05 }, + new[] { 0x1E06, 0x1E07 }, + new[] { 0x1E08, 0x1E09 }, + new[] { 0x1E0A, 0x1E0B }, + new[] { 0x1E0C, 0x1E0D }, + new[] { 0x1E0E, 0x1E0F }, + new[] { 0x1E10, 0x1E11 }, + new[] { 0x1E12, 0x1E13 }, + new[] { 0x1E14, 0x1E15 }, + new[] { 0x1E16, 0x1E17 }, + new[] { 0x1E18, 0x1E19 }, + new[] { 0x1E1A, 0x1E1B }, + new[] { 0x1E1C, 0x1E1D }, + new[] { 0x1E1E, 0x1E1F }, + new[] { 0x1E20, 0x1E21 }, + new[] { 0x1E22, 0x1E23 }, + new[] { 0x1E24, 0x1E25 }, + new[] { 0x1E26, 0x1E27 }, + new[] { 0x1E28, 0x1E29 }, + new[] { 0x1E2A, 0x1E2B }, + new[] { 0x1E2C, 0x1E2D }, + new[] { 0x1E2E, 0x1E2F }, + new[] { 0x1E30, 0x1E31 }, + new[] { 0x1E32, 0x1E33 }, + new[] { 0x1E34, 0x1E35 }, + new[] { 0x1E36, 0x1E37 }, + new[] { 0x1E38, 0x1E39 }, + new[] { 0x1E3A, 0x1E3B }, + new[] { 0x1E3C, 0x1E3D }, + new[] { 0x1E3E, 0x1E3F }, + new[] { 0x1E40, 0x1E41 }, + new[] { 0x1E42, 0x1E43 }, + new[] { 0x1E44, 0x1E45 }, + new[] { 0x1E46, 0x1E47 }, + new[] { 0x1E48, 0x1E49 }, + new[] { 0x1E4A, 0x1E4B }, + new[] { 0x1E4C, 0x1E4D }, + new[] { 0x1E4E, 0x1E4F }, + new[] { 0x1E50, 0x1E51 }, + new[] { 0x1E52, 0x1E53 }, + new[] { 0x1E54, 0x1E55 }, + new[] { 0x1E56, 0x1E57 }, + new[] { 0x1E58, 0x1E59 }, + new[] { 0x1E5A, 0x1E5B }, + new[] { 0x1E5C, 0x1E5D }, + new[] { 0x1E5E, 0x1E5F }, + new[] { 0x1E60, 0x1E61, 0x1E9B }, + new[] { 0x1E62, 0x1E63 }, + new[] { 0x1E64, 0x1E65 }, + new[] { 0x1E66, 0x1E67 }, + new[] { 0x1E68, 0x1E69 }, + new[] { 0x1E6A, 0x1E6B }, + new[] { 0x1E6C, 0x1E6D }, + new[] { 0x1E6E, 0x1E6F }, + new[] { 0x1E70, 0x1E71 }, + new[] { 0x1E72, 0x1E73 }, + new[] { 0x1E74, 0x1E75 }, + new[] { 0x1E76, 0x1E77 }, + new[] { 0x1E78, 0x1E79 }, + new[] { 0x1E7A, 0x1E7B }, + new[] { 0x1E7C, 0x1E7D }, + new[] { 0x1E7E, 0x1E7F }, + new[] { 0x1E80, 0x1E81 }, + new[] { 0x1E82, 0x1E83 }, + new[] { 0x1E84, 0x1E85 }, + new[] { 0x1E86, 0x1E87 }, + new[] { 0x1E88, 0x1E89 }, + new[] { 0x1E8A, 0x1E8B }, + new[] { 0x1E8C, 0x1E8D }, + new[] { 0x1E8E, 0x1E8F }, + new[] { 0x1E90, 0x1E91 }, + new[] { 0x1E92, 0x1E93 }, + new[] { 0x1E94, 0x1E95 }, + new[] { 0x1EA0, 0x1EA1 }, + new[] { 0x1EA2, 0x1EA3 }, + new[] { 0x1EA4, 0x1EA5 }, + new[] { 0x1EA6, 0x1EA7 }, + new[] { 0x1EA8, 0x1EA9 }, + new[] { 0x1EAA, 0x1EAB }, + new[] { 0x1EAC, 0x1EAD }, + new[] { 0x1EAE, 0x1EAF }, + new[] { 0x1EB0, 0x1EB1 }, + new[] { 0x1EB2, 0x1EB3 }, + new[] { 0x1EB4, 0x1EB5 }, + new[] { 0x1EB6, 0x1EB7 }, + new[] { 0x1EB8, 0x1EB9 }, + new[] { 0x1EBA, 0x1EBB }, + new[] { 0x1EBC, 0x1EBD }, + new[] { 0x1EBE, 0x1EBF }, + new[] { 0x1EC0, 0x1EC1 }, + new[] { 0x1EC2, 0x1EC3 }, + new[] { 0x1EC4, 0x1EC5 }, + new[] { 0x1EC6, 0x1EC7 }, + new[] { 0x1EC8, 0x1EC9 }, + new[] { 0x1ECA, 0x1ECB }, + new[] { 0x1ECC, 0x1ECD }, + new[] { 0x1ECE, 0x1ECF }, + new[] { 0x1ED0, 0x1ED1 }, + new[] { 0x1ED2, 0x1ED3 }, + new[] { 0x1ED4, 0x1ED5 }, + new[] { 0x1ED6, 0x1ED7 }, + new[] { 0x1ED8, 0x1ED9 }, + new[] { 0x1EDA, 0x1EDB }, + new[] { 0x1EDC, 0x1EDD }, + new[] { 0x1EDE, 0x1EDF }, + new[] { 0x1EE0, 0x1EE1 }, + new[] { 0x1EE2, 0x1EE3 }, + new[] { 0x1EE4, 0x1EE5 }, + new[] { 0x1EE6, 0x1EE7 }, + new[] { 0x1EE8, 0x1EE9 }, + new[] { 0x1EEA, 0x1EEB }, + new[] { 0x1EEC, 0x1EED }, + new[] { 0x1EEE, 0x1EEF }, + new[] { 0x1EF0, 0x1EF1 }, + new[] { 0x1EF2, 0x1EF3 }, + new[] { 0x1EF4, 0x1EF5 }, + new[] { 0x1EF6, 0x1EF7 }, + new[] { 0x1EF8, 0x1EF9 }, + new[] { 0x1EFA, 0x1EFB }, + new[] { 0x1EFC, 0x1EFD }, + new[] { 0x1EFE, 0x1EFF }, + new[] { 0x1F00, 0x1F08 }, + new[] { 0x1F01, 0x1F09 }, + new[] { 0x1F02, 0x1F0A }, + new[] { 0x1F03, 0x1F0B }, + new[] { 0x1F04, 0x1F0C }, + new[] { 0x1F05, 0x1F0D }, + new[] { 0x1F06, 0x1F0E }, + new[] { 0x1F07, 0x1F0F }, + new[] { 0x1F10, 0x1F18 }, + new[] { 0x1F11, 0x1F19 }, + new[] { 0x1F12, 0x1F1A }, + new[] { 0x1F13, 0x1F1B }, + new[] { 0x1F14, 0x1F1C }, + new[] { 0x1F15, 0x1F1D }, + new[] { 0x1F20, 0x1F28 }, + new[] { 0x1F21, 0x1F29 }, + new[] { 0x1F22, 0x1F2A }, + new[] { 0x1F23, 0x1F2B }, + new[] { 0x1F24, 0x1F2C }, + new[] { 0x1F25, 0x1F2D }, + new[] { 0x1F26, 0x1F2E }, + new[] { 0x1F27, 0x1F2F }, + new[] { 0x1F30, 0x1F38 }, + new[] { 0x1F31, 0x1F39 }, + new[] { 0x1F32, 0x1F3A }, + new[] { 0x1F33, 0x1F3B }, + new[] { 0x1F34, 0x1F3C }, + new[] { 0x1F35, 0x1F3D }, + new[] { 0x1F36, 0x1F3E }, + new[] { 0x1F37, 0x1F3F }, + new[] { 0x1F40, 0x1F48 }, + new[] { 0x1F41, 0x1F49 }, + new[] { 0x1F42, 0x1F4A }, + new[] { 0x1F43, 0x1F4B }, + new[] { 0x1F44, 0x1F4C }, + new[] { 0x1F45, 0x1F4D }, + new[] { 0x1F51, 0x1F59 }, + new[] { 0x1F53, 0x1F5B }, + new[] { 0x1F55, 0x1F5D }, + new[] { 0x1F57, 0x1F5F }, + new[] { 0x1F60, 0x1F68 }, + new[] { 0x1F61, 0x1F69 }, + new[] { 0x1F62, 0x1F6A }, + new[] { 0x1F63, 0x1F6B }, + new[] { 0x1F64, 0x1F6C }, + new[] { 0x1F65, 0x1F6D }, + new[] { 0x1F66, 0x1F6E }, + new[] { 0x1F67, 0x1F6F }, + new[] { 0x1F70, 0x1FBA }, + new[] { 0x1F71, 0x1FBB }, + new[] { 0x1F72, 0x1FC8 }, + new[] { 0x1F73, 0x1FC9 }, + new[] { 0x1F74, 0x1FCA }, + new[] { 0x1F75, 0x1FCB }, + new[] { 0x1F76, 0x1FDA }, + new[] { 0x1F77, 0x1FDB }, + new[] { 0x1F78, 0x1FF8 }, + new[] { 0x1F79, 0x1FF9 }, + new[] { 0x1F7A, 0x1FEA }, + new[] { 0x1F7B, 0x1FEB }, + new[] { 0x1F7C, 0x1FFA }, + new[] { 0x1F7D, 0x1FFB }, + new[] { 0x1F80, 0x1F88 }, + new[] { 0x1F81, 0x1F89 }, + new[] { 0x1F82, 0x1F8A }, + new[] { 0x1F83, 0x1F8B }, + new[] { 0x1F84, 0x1F8C }, + new[] { 0x1F85, 0x1F8D }, + new[] { 0x1F86, 0x1F8E }, + new[] { 0x1F87, 0x1F8F }, + new[] { 0x1F90, 0x1F98 }, + new[] { 0x1F91, 0x1F99 }, + new[] { 0x1F92, 0x1F9A }, + new[] { 0x1F93, 0x1F9B }, + new[] { 0x1F94, 0x1F9C }, + new[] { 0x1F95, 0x1F9D }, + new[] { 0x1F96, 0x1F9E }, + new[] { 0x1F97, 0x1F9F }, + new[] { 0x1FA0, 0x1FA8 }, + new[] { 0x1FA1, 0x1FA9 }, + new[] { 0x1FA2, 0x1FAA }, + new[] { 0x1FA3, 0x1FAB }, + new[] { 0x1FA4, 0x1FAC }, + new[] { 0x1FA5, 0x1FAD }, + new[] { 0x1FA6, 0x1FAE }, + new[] { 0x1FA7, 0x1FAF }, + new[] { 0x1FB0, 0x1FB8 }, + new[] { 0x1FB1, 0x1FB9 }, + new[] { 0x1FB3, 0x1FBC }, + new[] { 0x1FC3, 0x1FCC }, + new[] { 0x1FD0, 0x1FD8 }, + new[] { 0x1FD1, 0x1FD9 }, + new[] { 0x1FE0, 0x1FE8 }, + new[] { 0x1FE1, 0x1FE9 }, + new[] { 0x1FE5, 0x1FEC }, + new[] { 0x1FF3, 0x1FFC }, + new[] { 0x2132, 0x214E }, + new[] { 0x2160, 0x2170 }, + new[] { 0x2161, 0x2171 }, + new[] { 0x2162, 0x2172 }, + new[] { 0x2163, 0x2173 }, + new[] { 0x2164, 0x2174 }, + new[] { 0x2165, 0x2175 }, + new[] { 0x2166, 0x2176 }, + new[] { 0x2167, 0x2177 }, + new[] { 0x2168, 0x2178 }, + new[] { 0x2169, 0x2179 }, + new[] { 0x216A, 0x217A }, + new[] { 0x216B, 0x217B }, + new[] { 0x216C, 0x217C }, + new[] { 0x216D, 0x217D }, + new[] { 0x216E, 0x217E }, + new[] { 0x216F, 0x217F }, + new[] { 0x2183, 0x2184 }, + new[] { 0x24B6, 0x24D0 }, + new[] { 0x24B7, 0x24D1 }, + new[] { 0x24B8, 0x24D2 }, + new[] { 0x24B9, 0x24D3 }, + new[] { 0x24BA, 0x24D4 }, + new[] { 0x24BB, 0x24D5 }, + new[] { 0x24BC, 0x24D6 }, + new[] { 0x24BD, 0x24D7 }, + new[] { 0x24BE, 0x24D8 }, + new[] { 0x24BF, 0x24D9 }, + new[] { 0x24C0, 0x24DA }, + new[] { 0x24C1, 0x24DB }, + new[] { 0x24C2, 0x24DC }, + new[] { 0x24C3, 0x24DD }, + new[] { 0x24C4, 0x24DE }, + new[] { 0x24C5, 0x24DF }, + new[] { 0x24C6, 0x24E0 }, + new[] { 0x24C7, 0x24E1 }, + new[] { 0x24C8, 0x24E2 }, + new[] { 0x24C9, 0x24E3 }, + new[] { 0x24CA, 0x24E4 }, + new[] { 0x24CB, 0x24E5 }, + new[] { 0x24CC, 0x24E6 }, + new[] { 0x24CD, 0x24E7 }, + new[] { 0x24CE, 0x24E8 }, + new[] { 0x24CF, 0x24E9 }, + new[] { 0x2C00, 0x2C30 }, + new[] { 0x2C01, 0x2C31 }, + new[] { 0x2C02, 0x2C32 }, + new[] { 0x2C03, 0x2C33 }, + new[] { 0x2C04, 0x2C34 }, + new[] { 0x2C05, 0x2C35 }, + new[] { 0x2C06, 0x2C36 }, + new[] { 0x2C07, 0x2C37 }, + new[] { 0x2C08, 0x2C38 }, + new[] { 0x2C09, 0x2C39 }, + new[] { 0x2C0A, 0x2C3A }, + new[] { 0x2C0B, 0x2C3B }, + new[] { 0x2C0C, 0x2C3C }, + new[] { 0x2C0D, 0x2C3D }, + new[] { 0x2C0E, 0x2C3E }, + new[] { 0x2C0F, 0x2C3F }, + new[] { 0x2C10, 0x2C40 }, + new[] { 0x2C11, 0x2C41 }, + new[] { 0x2C12, 0x2C42 }, + new[] { 0x2C13, 0x2C43 }, + new[] { 0x2C14, 0x2C44 }, + new[] { 0x2C15, 0x2C45 }, + new[] { 0x2C16, 0x2C46 }, + new[] { 0x2C17, 0x2C47 }, + new[] { 0x2C18, 0x2C48 }, + new[] { 0x2C19, 0x2C49 }, + new[] { 0x2C1A, 0x2C4A }, + new[] { 0x2C1B, 0x2C4B }, + new[] { 0x2C1C, 0x2C4C }, + new[] { 0x2C1D, 0x2C4D }, + new[] { 0x2C1E, 0x2C4E }, + new[] { 0x2C1F, 0x2C4F }, + new[] { 0x2C20, 0x2C50 }, + new[] { 0x2C21, 0x2C51 }, + new[] { 0x2C22, 0x2C52 }, + new[] { 0x2C23, 0x2C53 }, + new[] { 0x2C24, 0x2C54 }, + new[] { 0x2C25, 0x2C55 }, + new[] { 0x2C26, 0x2C56 }, + new[] { 0x2C27, 0x2C57 }, + new[] { 0x2C28, 0x2C58 }, + new[] { 0x2C29, 0x2C59 }, + new[] { 0x2C2A, 0x2C5A }, + new[] { 0x2C2B, 0x2C5B }, + new[] { 0x2C2C, 0x2C5C }, + new[] { 0x2C2D, 0x2C5D }, + new[] { 0x2C2E, 0x2C5E }, + new[] { 0x2C2F, 0x2C5F }, + new[] { 0x2C60, 0x2C61 }, + new[] { 0x2C67, 0x2C68 }, + new[] { 0x2C69, 0x2C6A }, + new[] { 0x2C6B, 0x2C6C }, + new[] { 0x2C72, 0x2C73 }, + new[] { 0x2C75, 0x2C76 }, + new[] { 0x2C80, 0x2C81 }, + new[] { 0x2C82, 0x2C83 }, + new[] { 0x2C84, 0x2C85 }, + new[] { 0x2C86, 0x2C87 }, + new[] { 0x2C88, 0x2C89 }, + new[] { 0x2C8A, 0x2C8B }, + new[] { 0x2C8C, 0x2C8D }, + new[] { 0x2C8E, 0x2C8F }, + new[] { 0x2C90, 0x2C91 }, + new[] { 0x2C92, 0x2C93 }, + new[] { 0x2C94, 0x2C95 }, + new[] { 0x2C96, 0x2C97 }, + new[] { 0x2C98, 0x2C99 }, + new[] { 0x2C9A, 0x2C9B }, + new[] { 0x2C9C, 0x2C9D }, + new[] { 0x2C9E, 0x2C9F }, + new[] { 0x2CA0, 0x2CA1 }, + new[] { 0x2CA2, 0x2CA3 }, + new[] { 0x2CA4, 0x2CA5 }, + new[] { 0x2CA6, 0x2CA7 }, + new[] { 0x2CA8, 0x2CA9 }, + new[] { 0x2CAA, 0x2CAB }, + new[] { 0x2CAC, 0x2CAD }, + new[] { 0x2CAE, 0x2CAF }, + new[] { 0x2CB0, 0x2CB1 }, + new[] { 0x2CB2, 0x2CB3 }, + new[] { 0x2CB4, 0x2CB5 }, + new[] { 0x2CB6, 0x2CB7 }, + new[] { 0x2CB8, 0x2CB9 }, + new[] { 0x2CBA, 0x2CBB }, + new[] { 0x2CBC, 0x2CBD }, + new[] { 0x2CBE, 0x2CBF }, + new[] { 0x2CC0, 0x2CC1 }, + new[] { 0x2CC2, 0x2CC3 }, + new[] { 0x2CC4, 0x2CC5 }, + new[] { 0x2CC6, 0x2CC7 }, + new[] { 0x2CC8, 0x2CC9 }, + new[] { 0x2CCA, 0x2CCB }, + new[] { 0x2CCC, 0x2CCD }, + new[] { 0x2CCE, 0x2CCF }, + new[] { 0x2CD0, 0x2CD1 }, + new[] { 0x2CD2, 0x2CD3 }, + new[] { 0x2CD4, 0x2CD5 }, + new[] { 0x2CD6, 0x2CD7 }, + new[] { 0x2CD8, 0x2CD9 }, + new[] { 0x2CDA, 0x2CDB }, + new[] { 0x2CDC, 0x2CDD }, + new[] { 0x2CDE, 0x2CDF }, + new[] { 0x2CE0, 0x2CE1 }, + new[] { 0x2CE2, 0x2CE3 }, + new[] { 0x2CEB, 0x2CEC }, + new[] { 0x2CED, 0x2CEE }, + new[] { 0x2CF2, 0x2CF3 }, + new[] { 0xA640, 0xA641 }, + new[] { 0xA642, 0xA643 }, + new[] { 0xA644, 0xA645 }, + new[] { 0xA646, 0xA647 }, + new[] { 0xA648, 0xA649 }, + new[] { 0xA64C, 0xA64D }, + new[] { 0xA64E, 0xA64F }, + new[] { 0xA650, 0xA651 }, + new[] { 0xA652, 0xA653 }, + new[] { 0xA654, 0xA655 }, + new[] { 0xA656, 0xA657 }, + new[] { 0xA658, 0xA659 }, + new[] { 0xA65A, 0xA65B }, + new[] { 0xA65C, 0xA65D }, + new[] { 0xA65E, 0xA65F }, + new[] { 0xA660, 0xA661 }, + new[] { 0xA662, 0xA663 }, + new[] { 0xA664, 0xA665 }, + new[] { 0xA666, 0xA667 }, + new[] { 0xA668, 0xA669 }, + new[] { 0xA66A, 0xA66B }, + new[] { 0xA66C, 0xA66D }, + new[] { 0xA680, 0xA681 }, + new[] { 0xA682, 0xA683 }, + new[] { 0xA684, 0xA685 }, + new[] { 0xA686, 0xA687 }, + new[] { 0xA688, 0xA689 }, + new[] { 0xA68A, 0xA68B }, + new[] { 0xA68C, 0xA68D }, + new[] { 0xA68E, 0xA68F }, + new[] { 0xA690, 0xA691 }, + new[] { 0xA692, 0xA693 }, + new[] { 0xA694, 0xA695 }, + new[] { 0xA696, 0xA697 }, + new[] { 0xA698, 0xA699 }, + new[] { 0xA69A, 0xA69B }, + new[] { 0xA722, 0xA723 }, + new[] { 0xA724, 0xA725 }, + new[] { 0xA726, 0xA727 }, + new[] { 0xA728, 0xA729 }, + new[] { 0xA72A, 0xA72B }, + new[] { 0xA72C, 0xA72D }, + new[] { 0xA72E, 0xA72F }, + new[] { 0xA732, 0xA733 }, + new[] { 0xA734, 0xA735 }, + new[] { 0xA736, 0xA737 }, + new[] { 0xA738, 0xA739 }, + new[] { 0xA73A, 0xA73B }, + new[] { 0xA73C, 0xA73D }, + new[] { 0xA73E, 0xA73F }, + new[] { 0xA740, 0xA741 }, + new[] { 0xA742, 0xA743 }, + new[] { 0xA744, 0xA745 }, + new[] { 0xA746, 0xA747 }, + new[] { 0xA748, 0xA749 }, + new[] { 0xA74A, 0xA74B }, + new[] { 0xA74C, 0xA74D }, + new[] { 0xA74E, 0xA74F }, + new[] { 0xA750, 0xA751 }, + new[] { 0xA752, 0xA753 }, + new[] { 0xA754, 0xA755 }, + new[] { 0xA756, 0xA757 }, + new[] { 0xA758, 0xA759 }, + new[] { 0xA75A, 0xA75B }, + new[] { 0xA75C, 0xA75D }, + new[] { 0xA75E, 0xA75F }, + new[] { 0xA760, 0xA761 }, + new[] { 0xA762, 0xA763 }, + new[] { 0xA764, 0xA765 }, + new[] { 0xA766, 0xA767 }, + new[] { 0xA768, 0xA769 }, + new[] { 0xA76A, 0xA76B }, + new[] { 0xA76C, 0xA76D }, + new[] { 0xA76E, 0xA76F }, + new[] { 0xA779, 0xA77A }, + new[] { 0xA77B, 0xA77C }, + new[] { 0xA77E, 0xA77F }, + new[] { 0xA780, 0xA781 }, + new[] { 0xA782, 0xA783 }, + new[] { 0xA784, 0xA785 }, + new[] { 0xA786, 0xA787 }, + new[] { 0xA78B, 0xA78C }, + new[] { 0xA790, 0xA791 }, + new[] { 0xA792, 0xA793 }, + new[] { 0xA794, 0xA7C4 }, + new[] { 0xA796, 0xA797 }, + new[] { 0xA798, 0xA799 }, + new[] { 0xA79A, 0xA79B }, + new[] { 0xA79C, 0xA79D }, + new[] { 0xA79E, 0xA79F }, + new[] { 0xA7A0, 0xA7A1 }, + new[] { 0xA7A2, 0xA7A3 }, + new[] { 0xA7A4, 0xA7A5 }, + new[] { 0xA7A6, 0xA7A7 }, + new[] { 0xA7A8, 0xA7A9 }, + new[] { 0xA7B3, 0xAB53 }, + new[] { 0xA7B4, 0xA7B5 }, + new[] { 0xA7B6, 0xA7B7 }, + new[] { 0xA7B8, 0xA7B9 }, + new[] { 0xA7BA, 0xA7BB }, + new[] { 0xA7BC, 0xA7BD }, + new[] { 0xA7BE, 0xA7BF }, + new[] { 0xA7C0, 0xA7C1 }, + new[] { 0xA7C2, 0xA7C3 }, + new[] { 0xA7C7, 0xA7C8 }, + new[] { 0xA7C9, 0xA7CA }, + new[] { 0xA7CC, 0xA7CD }, + new[] { 0xA7CE, 0xA7CF }, + new[] { 0xA7D0, 0xA7D1 }, + new[] { 0xA7D2, 0xA7D3 }, + new[] { 0xA7D4, 0xA7D5 }, + new[] { 0xA7D6, 0xA7D7 }, + new[] { 0xA7D8, 0xA7D9 }, + new[] { 0xA7DA, 0xA7DB }, + new[] { 0xA7F5, 0xA7F6 }, + new[] { 0xFF21, 0xFF41 }, + new[] { 0xFF22, 0xFF42 }, + new[] { 0xFF23, 0xFF43 }, + new[] { 0xFF24, 0xFF44 }, + new[] { 0xFF25, 0xFF45 }, + new[] { 0xFF26, 0xFF46 }, + new[] { 0xFF27, 0xFF47 }, + new[] { 0xFF28, 0xFF48 }, + new[] { 0xFF29, 0xFF49 }, + new[] { 0xFF2A, 0xFF4A }, + new[] { 0xFF2B, 0xFF4B }, + new[] { 0xFF2C, 0xFF4C }, + new[] { 0xFF2D, 0xFF4D }, + new[] { 0xFF2E, 0xFF4E }, + new[] { 0xFF2F, 0xFF4F }, + new[] { 0xFF30, 0xFF50 }, + new[] { 0xFF31, 0xFF51 }, + new[] { 0xFF32, 0xFF52 }, + new[] { 0xFF33, 0xFF53 }, + new[] { 0xFF34, 0xFF54 }, + new[] { 0xFF35, 0xFF55 }, + new[] { 0xFF36, 0xFF56 }, + new[] { 0xFF37, 0xFF57 }, + new[] { 0xFF38, 0xFF58 }, + new[] { 0xFF39, 0xFF59 }, + new[] { 0xFF3A, 0xFF5A }, + new[] { 0x10400, 0x10428 }, + new[] { 0x10401, 0x10429 }, + new[] { 0x10402, 0x1042A }, + new[] { 0x10403, 0x1042B }, + new[] { 0x10404, 0x1042C }, + new[] { 0x10405, 0x1042D }, + new[] { 0x10406, 0x1042E }, + new[] { 0x10407, 0x1042F }, + new[] { 0x10408, 0x10430 }, + new[] { 0x10409, 0x10431 }, + new[] { 0x1040A, 0x10432 }, + new[] { 0x1040B, 0x10433 }, + new[] { 0x1040C, 0x10434 }, + new[] { 0x1040D, 0x10435 }, + new[] { 0x1040E, 0x10436 }, + new[] { 0x1040F, 0x10437 }, + new[] { 0x10410, 0x10438 }, + new[] { 0x10411, 0x10439 }, + new[] { 0x10412, 0x1043A }, + new[] { 0x10413, 0x1043B }, + new[] { 0x10414, 0x1043C }, + new[] { 0x10415, 0x1043D }, + new[] { 0x10416, 0x1043E }, + new[] { 0x10417, 0x1043F }, + new[] { 0x10418, 0x10440 }, + new[] { 0x10419, 0x10441 }, + new[] { 0x1041A, 0x10442 }, + new[] { 0x1041B, 0x10443 }, + new[] { 0x1041C, 0x10444 }, + new[] { 0x1041D, 0x10445 }, + new[] { 0x1041E, 0x10446 }, + new[] { 0x1041F, 0x10447 }, + new[] { 0x10420, 0x10448 }, + new[] { 0x10421, 0x10449 }, + new[] { 0x10422, 0x1044A }, + new[] { 0x10423, 0x1044B }, + new[] { 0x10424, 0x1044C }, + new[] { 0x10425, 0x1044D }, + new[] { 0x10426, 0x1044E }, + new[] { 0x10427, 0x1044F }, + new[] { 0x104B0, 0x104D8 }, + new[] { 0x104B1, 0x104D9 }, + new[] { 0x104B2, 0x104DA }, + new[] { 0x104B3, 0x104DB }, + new[] { 0x104B4, 0x104DC }, + new[] { 0x104B5, 0x104DD }, + new[] { 0x104B6, 0x104DE }, + new[] { 0x104B7, 0x104DF }, + new[] { 0x104B8, 0x104E0 }, + new[] { 0x104B9, 0x104E1 }, + new[] { 0x104BA, 0x104E2 }, + new[] { 0x104BB, 0x104E3 }, + new[] { 0x104BC, 0x104E4 }, + new[] { 0x104BD, 0x104E5 }, + new[] { 0x104BE, 0x104E6 }, + new[] { 0x104BF, 0x104E7 }, + new[] { 0x104C0, 0x104E8 }, + new[] { 0x104C1, 0x104E9 }, + new[] { 0x104C2, 0x104EA }, + new[] { 0x104C3, 0x104EB }, + new[] { 0x104C4, 0x104EC }, + new[] { 0x104C5, 0x104ED }, + new[] { 0x104C6, 0x104EE }, + new[] { 0x104C7, 0x104EF }, + new[] { 0x104C8, 0x104F0 }, + new[] { 0x104C9, 0x104F1 }, + new[] { 0x104CA, 0x104F2 }, + new[] { 0x104CB, 0x104F3 }, + new[] { 0x104CC, 0x104F4 }, + new[] { 0x104CD, 0x104F5 }, + new[] { 0x104CE, 0x104F6 }, + new[] { 0x104CF, 0x104F7 }, + new[] { 0x104D0, 0x104F8 }, + new[] { 0x104D1, 0x104F9 }, + new[] { 0x104D2, 0x104FA }, + new[] { 0x104D3, 0x104FB }, + new[] { 0x10570, 0x10597 }, + new[] { 0x10571, 0x10598 }, + new[] { 0x10572, 0x10599 }, + new[] { 0x10573, 0x1059A }, + new[] { 0x10574, 0x1059B }, + new[] { 0x10575, 0x1059C }, + new[] { 0x10576, 0x1059D }, + new[] { 0x10577, 0x1059E }, + new[] { 0x10578, 0x1059F }, + new[] { 0x10579, 0x105A0 }, + new[] { 0x1057A, 0x105A1 }, + new[] { 0x1057C, 0x105A3 }, + new[] { 0x1057D, 0x105A4 }, + new[] { 0x1057E, 0x105A5 }, + new[] { 0x1057F, 0x105A6 }, + new[] { 0x10580, 0x105A7 }, + new[] { 0x10581, 0x105A8 }, + new[] { 0x10582, 0x105A9 }, + new[] { 0x10583, 0x105AA }, + new[] { 0x10584, 0x105AB }, + new[] { 0x10585, 0x105AC }, + new[] { 0x10586, 0x105AD }, + new[] { 0x10587, 0x105AE }, + new[] { 0x10588, 0x105AF }, + new[] { 0x10589, 0x105B0 }, + new[] { 0x1058A, 0x105B1 }, + new[] { 0x1058C, 0x105B3 }, + new[] { 0x1058D, 0x105B4 }, + new[] { 0x1058E, 0x105B5 }, + new[] { 0x1058F, 0x105B6 }, + new[] { 0x10590, 0x105B7 }, + new[] { 0x10591, 0x105B8 }, + new[] { 0x10592, 0x105B9 }, + new[] { 0x10594, 0x105BB }, + new[] { 0x10595, 0x105BC }, + new[] { 0x10C80, 0x10CC0 }, + new[] { 0x10C81, 0x10CC1 }, + new[] { 0x10C82, 0x10CC2 }, + new[] { 0x10C83, 0x10CC3 }, + new[] { 0x10C84, 0x10CC4 }, + new[] { 0x10C85, 0x10CC5 }, + new[] { 0x10C86, 0x10CC6 }, + new[] { 0x10C87, 0x10CC7 }, + new[] { 0x10C88, 0x10CC8 }, + new[] { 0x10C89, 0x10CC9 }, + new[] { 0x10C8A, 0x10CCA }, + new[] { 0x10C8B, 0x10CCB }, + new[] { 0x10C8C, 0x10CCC }, + new[] { 0x10C8D, 0x10CCD }, + new[] { 0x10C8E, 0x10CCE }, + new[] { 0x10C8F, 0x10CCF }, + new[] { 0x10C90, 0x10CD0 }, + new[] { 0x10C91, 0x10CD1 }, + new[] { 0x10C92, 0x10CD2 }, + new[] { 0x10C93, 0x10CD3 }, + new[] { 0x10C94, 0x10CD4 }, + new[] { 0x10C95, 0x10CD5 }, + new[] { 0x10C96, 0x10CD6 }, + new[] { 0x10C97, 0x10CD7 }, + new[] { 0x10C98, 0x10CD8 }, + new[] { 0x10C99, 0x10CD9 }, + new[] { 0x10C9A, 0x10CDA }, + new[] { 0x10C9B, 0x10CDB }, + new[] { 0x10C9C, 0x10CDC }, + new[] { 0x10C9D, 0x10CDD }, + new[] { 0x10C9E, 0x10CDE }, + new[] { 0x10C9F, 0x10CDF }, + new[] { 0x10CA0, 0x10CE0 }, + new[] { 0x10CA1, 0x10CE1 }, + new[] { 0x10CA2, 0x10CE2 }, + new[] { 0x10CA3, 0x10CE3 }, + new[] { 0x10CA4, 0x10CE4 }, + new[] { 0x10CA5, 0x10CE5 }, + new[] { 0x10CA6, 0x10CE6 }, + new[] { 0x10CA7, 0x10CE7 }, + new[] { 0x10CA8, 0x10CE8 }, + new[] { 0x10CA9, 0x10CE9 }, + new[] { 0x10CAA, 0x10CEA }, + new[] { 0x10CAB, 0x10CEB }, + new[] { 0x10CAC, 0x10CEC }, + new[] { 0x10CAD, 0x10CED }, + new[] { 0x10CAE, 0x10CEE }, + new[] { 0x10CAF, 0x10CEF }, + new[] { 0x10CB0, 0x10CF0 }, + new[] { 0x10CB1, 0x10CF1 }, + new[] { 0x10CB2, 0x10CF2 }, + new[] { 0x10D50, 0x10D70 }, + new[] { 0x10D51, 0x10D71 }, + new[] { 0x10D52, 0x10D72 }, + new[] { 0x10D53, 0x10D73 }, + new[] { 0x10D54, 0x10D74 }, + new[] { 0x10D55, 0x10D75 }, + new[] { 0x10D56, 0x10D76 }, + new[] { 0x10D57, 0x10D77 }, + new[] { 0x10D58, 0x10D78 }, + new[] { 0x10D59, 0x10D79 }, + new[] { 0x10D5A, 0x10D7A }, + new[] { 0x10D5B, 0x10D7B }, + new[] { 0x10D5C, 0x10D7C }, + new[] { 0x10D5D, 0x10D7D }, + new[] { 0x10D5E, 0x10D7E }, + new[] { 0x10D5F, 0x10D7F }, + new[] { 0x10D60, 0x10D80 }, + new[] { 0x10D61, 0x10D81 }, + new[] { 0x10D62, 0x10D82 }, + new[] { 0x10D63, 0x10D83 }, + new[] { 0x10D64, 0x10D84 }, + new[] { 0x10D65, 0x10D85 }, + new[] { 0x118A0, 0x118C0 }, + new[] { 0x118A1, 0x118C1 }, + new[] { 0x118A2, 0x118C2 }, + new[] { 0x118A3, 0x118C3 }, + new[] { 0x118A4, 0x118C4 }, + new[] { 0x118A5, 0x118C5 }, + new[] { 0x118A6, 0x118C6 }, + new[] { 0x118A7, 0x118C7 }, + new[] { 0x118A8, 0x118C8 }, + new[] { 0x118A9, 0x118C9 }, + new[] { 0x118AA, 0x118CA }, + new[] { 0x118AB, 0x118CB }, + new[] { 0x118AC, 0x118CC }, + new[] { 0x118AD, 0x118CD }, + new[] { 0x118AE, 0x118CE }, + new[] { 0x118AF, 0x118CF }, + new[] { 0x118B0, 0x118D0 }, + new[] { 0x118B1, 0x118D1 }, + new[] { 0x118B2, 0x118D2 }, + new[] { 0x118B3, 0x118D3 }, + new[] { 0x118B4, 0x118D4 }, + new[] { 0x118B5, 0x118D5 }, + new[] { 0x118B6, 0x118D6 }, + new[] { 0x118B7, 0x118D7 }, + new[] { 0x118B8, 0x118D8 }, + new[] { 0x118B9, 0x118D9 }, + new[] { 0x118BA, 0x118DA }, + new[] { 0x118BB, 0x118DB }, + new[] { 0x118BC, 0x118DC }, + new[] { 0x118BD, 0x118DD }, + new[] { 0x118BE, 0x118DE }, + new[] { 0x118BF, 0x118DF }, + new[] { 0x16E40, 0x16E60 }, + new[] { 0x16E41, 0x16E61 }, + new[] { 0x16E42, 0x16E62 }, + new[] { 0x16E43, 0x16E63 }, + new[] { 0x16E44, 0x16E64 }, + new[] { 0x16E45, 0x16E65 }, + new[] { 0x16E46, 0x16E66 }, + new[] { 0x16E47, 0x16E67 }, + new[] { 0x16E48, 0x16E68 }, + new[] { 0x16E49, 0x16E69 }, + new[] { 0x16E4A, 0x16E6A }, + new[] { 0x16E4B, 0x16E6B }, + new[] { 0x16E4C, 0x16E6C }, + new[] { 0x16E4D, 0x16E6D }, + new[] { 0x16E4E, 0x16E6E }, + new[] { 0x16E4F, 0x16E6F }, + new[] { 0x16E50, 0x16E70 }, + new[] { 0x16E51, 0x16E71 }, + new[] { 0x16E52, 0x16E72 }, + new[] { 0x16E53, 0x16E73 }, + new[] { 0x16E54, 0x16E74 }, + new[] { 0x16E55, 0x16E75 }, + new[] { 0x16E56, 0x16E76 }, + new[] { 0x16E57, 0x16E77 }, + new[] { 0x16E58, 0x16E78 }, + new[] { 0x16E59, 0x16E79 }, + new[] { 0x16E5A, 0x16E7A }, + new[] { 0x16E5B, 0x16E7B }, + new[] { 0x16E5C, 0x16E7C }, + new[] { 0x16E5D, 0x16E7D }, + new[] { 0x16E5E, 0x16E7E }, + new[] { 0x16E5F, 0x16E7F }, + new[] { 0x16EA0, 0x16EBB }, + new[] { 0x16EA1, 0x16EBC }, + new[] { 0x16EA2, 0x16EBD }, + new[] { 0x16EA3, 0x16EBE }, + new[] { 0x16EA4, 0x16EBF }, + new[] { 0x16EA5, 0x16EC0 }, + new[] { 0x16EA6, 0x16EC1 }, + new[] { 0x16EA7, 0x16EC2 }, + new[] { 0x16EA8, 0x16EC3 }, + new[] { 0x16EA9, 0x16EC4 }, + new[] { 0x16EAA, 0x16EC5 }, + new[] { 0x16EAB, 0x16EC6 }, + new[] { 0x16EAC, 0x16EC7 }, + new[] { 0x16EAD, 0x16EC8 }, + new[] { 0x16EAE, 0x16EC9 }, + new[] { 0x16EAF, 0x16ECA }, + new[] { 0x16EB0, 0x16ECB }, + new[] { 0x16EB1, 0x16ECC }, + new[] { 0x16EB2, 0x16ECD }, + new[] { 0x16EB3, 0x16ECE }, + new[] { 0x16EB4, 0x16ECF }, + new[] { 0x16EB5, 0x16ED0 }, + new[] { 0x16EB6, 0x16ED1 }, + new[] { 0x16EB7, 0x16ED2 }, + new[] { 0x16EB8, 0x16ED3 }, + new[] { 0x1E900, 0x1E922 }, + new[] { 0x1E901, 0x1E923 }, + new[] { 0x1E902, 0x1E924 }, + new[] { 0x1E903, 0x1E925 }, + new[] { 0x1E904, 0x1E926 }, + new[] { 0x1E905, 0x1E927 }, + new[] { 0x1E906, 0x1E928 }, + new[] { 0x1E907, 0x1E929 }, + new[] { 0x1E908, 0x1E92A }, + new[] { 0x1E909, 0x1E92B }, + new[] { 0x1E90A, 0x1E92C }, + new[] { 0x1E90B, 0x1E92D }, + new[] { 0x1E90C, 0x1E92E }, + new[] { 0x1E90D, 0x1E92F }, + new[] { 0x1E90E, 0x1E930 }, + new[] { 0x1E90F, 0x1E931 }, + new[] { 0x1E910, 0x1E932 }, + new[] { 0x1E911, 0x1E933 }, + new[] { 0x1E912, 0x1E934 }, + new[] { 0x1E913, 0x1E935 }, + new[] { 0x1E914, 0x1E936 }, + new[] { 0x1E915, 0x1E937 }, + new[] { 0x1E916, 0x1E938 }, + new[] { 0x1E917, 0x1E939 }, + new[] { 0x1E918, 0x1E93A }, + new[] { 0x1E919, 0x1E93B }, + new[] { 0x1E91A, 0x1E93C }, + new[] { 0x1E91B, 0x1E93D }, + new[] { 0x1E91C, 0x1E93E }, + new[] { 0x1E91D, 0x1E93F }, + new[] { 0x1E91E, 0x1E940 }, + new[] { 0x1E91F, 0x1E941 }, + new[] { 0x1E920, 0x1E942 }, + new[] { 0x1E921, 0x1E943 }, + }; + } +} diff --git a/Src/Ruby/Builtins/CaseFoldGroups.cs b/Src/Ruby/Builtins/CaseFoldGroups.cs new file mode 100644 index 000000000..4577bfa5e --- /dev/null +++ b/Src/Ruby/Builtins/CaseFoldGroups.cs @@ -0,0 +1,118 @@ +/* **************************************************************************** + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. + * + * ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace IronRuby.Builtins { + /// + /// The characters Onigmo's /i takes for one another (CaseFoldGroups.Generated.cs, from CRuby), for the ones .NET's + /// IgnoreCase does not: RegexpTransformer adds a group's other members to a character or a class under /i. + /// + internal static partial class CaseFoldGroups { + // The members of the groups .NET does not fold by itself, sorted, and each one's group. Built at the first use. + private sealed class Index { + internal readonly int[] Members; + internal readonly int[][] GroupOf; + + internal Index(int[] members, int[][] groupOf) { + Members = members; + GroupOf = groupOf; + } + } + + private static Index _index, _fullIndex; + + // full: every group, for a class emitted case-sensitively; else only those .NET's IgnoreCase does not fold by itself + private static Index/*!*/ GetIndex(bool full) { + var index = Volatile.Read(ref full ? ref _fullIndex : ref _index); + if (index != null) { + return index; + } + var members = new List>(); + foreach (int[] group in _groups) { + if (full || !IsFoldedByClr(group)) { + foreach (int cp in group) { + members.Add(new KeyValuePair(cp, group)); + } + } + } + members.Sort((a, b) => a.Key.CompareTo(b.Key)); + var keys = new int[members.Count]; + var groups = new int[members.Count][]; + for (int i = 0; i < keys.Length; i++) { + keys[i] = members[i].Key; + groups[i] = members[i].Value; + } + index = new Index(keys, groups); + if (full) { + Interlocked.CompareExchange(ref _fullIndex, index, null); + return Volatile.Read(ref _fullIndex); + } + Interlocked.CompareExchange(ref _index, index, null); + return Volatile.Read(ref _index); + } + + // A pair of BMP characters that are each other's upper and lower case, which .NET's IgnoreCase takes for one another + // (A and a). Anything else - a third member (s, S and U+017F LONG S), a character above U+FFFF - is left to the table. + private static bool IsFoldedByClr(int[]/*!*/ group) { + if (group.Length != 2 || group[0] > 0xffff || group[1] > 0xffff) { + return false; + } + char a = (char)group[0], b = (char)group[1]; + return Char.ToLowerInvariant(a) == Char.ToLowerInvariant(b) && Char.ToUpperInvariant(a) == Char.ToUpperInvariant(b); + } + + /// Whether is in a group .NET does not fold by itself. + internal static bool IsSpecial(int codepoint) { + return Array.BinarySearch(GetIndex(false).Members, codepoint) >= 0; + } + + /// + /// (see CodePointRanges) with the other members of each group one of its code points is in - + /// of every group if , else of those .NET does not fold by itself; the array itself if that adds + /// nothing. + /// + internal static int[]/*!*/ Close(int[]/*!*/ ranges, bool full) { + var index = GetIndex(full); + int[] members = index.Members; + List added = null; + for (int r = 0; r < ranges.Length; r += 2) { + int i = Array.BinarySearch(members, ranges[r]); + if (i < 0) { + i = ~i; + } + for (; i < members.Length && members[i] <= ranges[r + 1]; i++) { + foreach (int cp in index.GroupOf[i]) { + if (!CodePointRanges.Contains(ranges, cp, cp)) { + (added ??= new List()).Add(cp); + } + } + } + } + if (added == null) { + return ranges; + } + // the added code points as one range list, and one union: a union each was quadratic for a property (\p{L}) + added.Sort(); + var list = new List(added.Count * 2); + foreach (int cp in added) { + int n = list.Count; + if (n > 0 && list[n - 1] >= cp - 1) { + if (list[n - 1] < cp) { + list[n - 1] = cp; + } + } else { + list.Add(cp); + list.Add(cp); + } + } + return CodePointRanges.Union(ranges, list.ToArray()); + } + } +} diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index 57f5b9089..f81cc3a31 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -72,6 +72,10 @@ private enum CharacterClassMode { // called the wrong group. private bool _extended; + // /i or (?i) is in effect at the point being parsed: a character or class then takes the characters Onigmo's case + // folding takes for it that .NET's IgnoreCase does not (see FoldsCase). + private bool _ignoreCase; + /// /// A capturing group as a subexpression call or a loop copy needs it: its Ruby body and /// the parser state at the start of that body, so that the body can be transformed again @@ -323,6 +327,7 @@ private RegexpTransformer(RegexpTransformer/*!*/ parent, string/*!*/ source, int _characterClassMode = mode; _callDepth = callDepth; _extended = parent._extended; + _ignoreCase = parent._ignoreCase; // a copy is never the top level of the pattern (\K) _groupDepth = 1; } @@ -744,6 +749,7 @@ private static bool HasInlineIgnoreCase(string/*!*/ pattern) { var collector = new RegexpTransformer(_rubyPattern); collector._state = _state; collector._extended = (_clrOptions & RegexOptions.IgnorePatternWhitespace) != 0; + collector._ignoreCase = (_clrOptions & RegexOptions.IgnoreCase) != 0; _state.Collecting = true; collector.TransformBody(); _state.Collecting = false; @@ -760,6 +766,7 @@ private static bool HasInlineIgnoreCase(string/*!*/ pattern) { _characterClassMode = CharacterClassMode.Default; _dotAll = (_clrOptions & RegexOptions.Singleline) != 0; _extended = (_clrOptions & RegexOptions.IgnorePatternWhitespace) != 0; + _ignoreCase = (_clrOptions & RegexOptions.IgnoreCase) != 0; _groupNameOccurrences.Clear(); try { string result = TransformBody(); @@ -939,6 +946,14 @@ private void Parse(bool isSubexpression) { bool topLevelPosixClass; // Onigmo takes an undecodable byte for a character a class negated at its top ([^l]) matches bool negatedGroup = Peek() == '^'; + if (FoldsCase) { + // the class holds what /i folds into its members (ParseCharacterGroupUnion), and nothing else may: + // .NET's IgnoreCase would take U+212A KELVIN SIGN into [\w], which Onigmo does not + _sb.Append("(?-i:"); + AppendCharacterSet(ParseCharacterGroup(false, out topLevelPosixClass), true, negatedGroup); + _sb.Append(')'); + break; + } AppendCharacterSet(ParseCharacterGroup(false, out topLevelPosixClass), true, negatedGroup); break; @@ -975,6 +990,11 @@ private void Parse(bool isSubexpression) { // A literal character above U+FFFF is a surrogate pair, and a quantifier // after it applies to the whole of it, not to its trailing half. int low = Read(); + int astral = Char.ConvertToUtf32((char)c, (char)low); + if (FoldsCase && CaseFoldGroups.IsSpecial(astral)) { + AppendCharacterSet(CharacterSet.MakeCharacter(astral, null).WithCaseFolds(), true, false); + break; + } bool group = IsQuantifierNext(); if (group) { _sb.Append("(?:"); @@ -990,12 +1010,41 @@ private void Parse(bool isSubexpression) { AppendUnfoldedLatin1Letter(c); break; } + if (FoldsCase && CaseFoldGroups.IsSpecial(c)) { + AppendCharacterSet(CharacterSet.MakeCharacter(c, Escape(c)).WithCaseFolds(), true, false); + break; + } Append((char)c); break; } } } + /// + /// Whether a character or class takes, besides itself, the characters Onigmo's case folding takes for it that .NET's + /// IgnoreCase does not (CaseFoldGroups): /s/i matches U+017F LONG S, /[[:upper:]]/i U+00B5 MICRO SIGN, /\u{10400}/i + /// U+10428. Unicode subjects only: ASCII-8BIT and ISO-8859-1 fold their own way. + /// + private bool FoldsCase { + get { return _ignoreCase && !_state.AsciiCtype && !_state.Latin1Ctype; } + } + + /// + /// \w \d \s \h and their negations: Onigmo does not fold them under /i, a set of ASCII characters that it is in the + /// default mode - /\w/i does not match U+017F LONG S, nor [s\w]/i U+212A KELVIN SIGN, where /[a-z]/i matches both. + /// + private static bool IsCtypeEscape(int escape) { + switch (escape) { + case 'w': case 'W': case 'd': case 'D': case 's': case 'S': case 'h': case 'H': + return true; + default: + return false; + } + } + + // Whether the member ParseCharacter has just read folds under /i (see ParseCharacterGroupUnion). + private bool _memberFolds; + private bool IsQuantifierNext() { int next = Peek(); return next == '*' || next == '+' || next == '?' || next == '{'; @@ -1417,6 +1466,7 @@ private void ParseGroup() { var savedMode = _characterClassMode; var savedDotAll = _dotAll; var savedExtended = _extended; + var savedIgnoreCase = _ignoreCase; int bodyStart = _index; GroupDefinition definition = null; bool hasLevelGroup = false; @@ -1446,6 +1496,7 @@ private void ParseGroup() { _characterClassMode = savedMode; _dotAll = savedDotAll; _extended = savedExtended; + _ignoreCase = savedIgnoreCase; if (groupNumber >= 0) { CloseGroup("#" + groupNumber); if (groupName != null) { @@ -1483,6 +1534,7 @@ private void ParseGroupOptions(int c) { var mode = _characterClassMode; var dotAll = _dotAll; var extended = _extended; + var ignoreCase = _ignoreCase; bool isScoped = false; bool negative = false; @@ -1498,6 +1550,8 @@ private void ParseGroupOptions(int c) { flags.Append((char)c); if (c == 'x') { extended = !negative; + } else if (c == 'i') { + ignoreCase = !negative; } } else if (c == 'a') { mode = CharacterClassMode.Ascii; @@ -1528,6 +1582,7 @@ private void ParseGroupOptions(int c) { _characterClassMode = mode; _dotAll = dotAll; _extended = extended; + _ignoreCase = ignoreCase; if (options.Length != 0) { _sb.Append("(?").Append(options).Append(')'); } @@ -1538,15 +1593,18 @@ private void ParseGroupOptions(int c) { var savedMode = _characterClassMode; var savedDotAll = _dotAll; var savedExtended = _extended; + var savedIgnoreCase = _ignoreCase; _characterClassMode = mode; _dotAll = dotAll; _extended = extended; + _ignoreCase = ignoreCase; _groupDepth++; Parse(true); _groupDepth--; _characterClassMode = savedMode; _dotAll = savedDotAll; _extended = savedExtended; + _ignoreCase = savedIgnoreCase; _sb.Append(')'); } @@ -1779,6 +1837,17 @@ private void ParseEscape(int escape) { var latin1Word = CharacterSet.MakeSet(_latin1WordQuirk, null); set = (escape == 'w') ? set.Union(latin1Word) : set.Subtract(latin1Word); } + if (FoldsCase) { + // what /i folds into a character (\x41) or a property (\p{Lu}), and nothing into a ctype (\w, see + // IsCtypeEscape), matched case-sensitively, as a class is + if (!IsCtypeEscape(escape)) { + set = set.WithCaseFolds(true); + } + _sb.Append("(?-i:"); + AppendCharacterSet(set, false, escape == 'S' || escape == 'D' || escape == 'W' || escape == 'H'); + _sb.Append(')'); + break; + } // \S \D \W \H match an undecodable byte in Onigmo, as a negated class does AppendCharacterSet(set, false, escape == 'S' || escape == 'D' || escape == 'W' || escape == 'H'); break; @@ -2506,6 +2575,9 @@ private int ParseUnicodeCodePoint() { private void AppendUnicodeCodePoint(StringBuilder/*!*/ builder, int codepoint) { if (codepoint >= 0xd800 && codepoint <= 0xdfff || codepoint > 0x10ffff) { throw MakeError("invalid Unicode range"); + } else if (ReferenceEquals(builder, _sb) && FoldsCase && CaseFoldGroups.IsSpecial(codepoint)) { + // /\u039C/i matches U+00B5 too, as the character itself would (see FoldsCase) + AppendCharacterSet(MakeCodePointSet(codepoint).WithCaseFolds(), true, false); } else if (codepoint < 0x10000) { AppendEscaped(builder, codepoint); } else { @@ -2591,6 +2663,36 @@ private CharacterSet(int[]/*!*/ ranges, bool negated) return new CharacterSet(UnicodeProperties.GetRanges(table), !positive, null, -1, table); } + /// + /// The set with the characters Onigmo's /i takes for its members: all of them if , for a set + /// emitted case-sensitively, else those .NET's IgnoreCase does not (see FoldsCase). + /// + internal CharacterSet/*!*/ WithCaseFolds(bool full = false) { + if (_table >= 0) { + // a property (\p{L}, [[:upper:]]): large, so folded and rendered once per table + int key = (_table * 2 + (_negated ? 1 : 0)) * 2 + (full ? 1 : 0); + lock (_foldedProperties) { + CharacterSet cached; + if (_foldedProperties.TryGetValue(key, out cached)) { + return cached; + } + } + var folded = Fold(full); + lock (_foldedProperties) { + _foldedProperties[key] = folded; + } + return folded; + } + return Fold(full); + } + + private static readonly Dictionary _foldedProperties = new Dictionary(); + + private CharacterSet/*!*/ Fold(bool full) { + int[] closed = CaseFoldGroups.Close(_ranges, full); + return ReferenceEquals(closed, _ranges) ? this : new CharacterSet(closed, _negated); + } + /// The members in U+0000-U+00FF, the characters a BINARY subject is made of. internal int[]/*!*/ GetLatin1Members() { int[] members = CodePointRanges.Intersect(_ranges, Latin1Range); @@ -3002,6 +3104,9 @@ private static void AppendSurrogatePairs(StringBuilder/*!*/ sb, int[]/*!*/ range // private CharacterSet ParseCharacterGroupUnion() { CharacterSet result = CharacterSet.Empty; + // Under /i each member takes the characters Onigmo folds into it, as it is added (FoldsCase): an intersection + // then works on the folded operands, and a member that does not fold - \w, a nested class, which folded its own + // members, a POSIX class of (?a) - takes nothing ([s\w]/i matches U+017F, which folds to s, but not U+212A). // \u{1 2 3} produces multiple characters, the first and the last might be range bounds: IEnumerator codepoints = null; @@ -3061,12 +3166,16 @@ private CharacterSet ParseCharacterGroupUnion() { set.Text + "-" + rangeEnd.Text); } + if (_memberFolds && FoldsCase) { + set = set.WithCaseFolds(true); + } result = result.Union(set); } return result; } private CharacterSet ParseCharacter(ref IEnumerator codepoints, out bool mayStartRange) { + _memberFolds = true; if (codepoints != null) { mayStartRange = true; int current = codepoints.Current; @@ -3118,6 +3227,7 @@ private CharacterSet ParseCharacter(ref IEnumerator codepoints, out bool ma return MakeCodePointSet(codepoint); } else { mayStartRange = true; + _memberFolds = !IsCtypeEscape(escape); return ParseCharacterEscape(escape); } @@ -3129,6 +3239,8 @@ private CharacterSet ParseCharacter(ref IEnumerator codepoints, out bool ma bool posixClass; var group = ParseCharacterGroup(true, out posixClass); mayStartRange = posixClass; + // a POSIX class folds as a property does, but in (?a), where it is ASCII; a nested class folded its own + _memberFolds = posixClass && _characterClassMode != CharacterClassMode.Ascii; return group; } diff --git a/Util/gen-case-fold-groups.rb b/Util/gen-case-fold-groups.rb new file mode 100644 index 000000000..c39dcad7b --- /dev/null +++ b/Util/gen-case-fold-groups.rb @@ -0,0 +1,58 @@ +#!/usr/bin/env ruby +# Generates Src/Ruby/Builtins/CaseFoldGroups.Generated.cs: the groups of characters Onigmo's /i +# takes for one another (its simple case folding), asked of CRuby. RegexpTransformer adds a +# group's other members to a character or a class under /i, because .NET's IgnoreCase leaves +# out some of them - the special foldings (U+00B5 MICRO SIGN to mu, U+017F LONG S to s, the +# Greek symbol forms), characters newer than its Unicode tables, and every character above +# U+FFFF, which it sees as two surrogates. +# +# A character's group is the one its case folding (String#downcase(:fold)) names when that is a +# single character, and otherwise the one of the single character it matches under /i, if any; +# a member CRuby's own /\A[x]\z/i does not take for the group's first one, or the other way +# round, is left out (U+023A folds to U+2C65, which Onigmo does not match with it). +# +# ruby Util/gen-case-fold-groups.rb [output.cs] + +abort "run this with CRuby (it asks CRuby's own case folding and Onigmo)" if RUBY_ENGINE != "ruby" + +out = ARGV[0] || File.expand_path("../Src/Ruby/Builtins/CaseFoldGroups.Generated.cs", __dir__) + +def chr(cp) = cp.chr(Encoding::UTF_8) +def same?(a, b) = chr(a).match?(Regexp.new("\\A[#{Regexp.escape(chr(b))}]\\z", Regexp::IGNORECASE)) + +groups = Hash.new { |h, k| h[k] = [] } +(0..0x10ffff).each do |cp| + next if (0xd800..0xdfff).cover?(cp) + c = chr(cp) + f = c.downcase(:fold) + key = if f.length == 1 + f.ord + else + simple = [c.downcase, c.upcase, c.swapcase].find { |x| x.length == 1 && x != c && same?(cp, x.ord) } + simple ? simple.ord : cp + end + groups[key] << cp +end + +result = [] +groups.each do |key, members| + members = ([key] | members).sort + first = members[0] + members = members.select { |m| m == first || (same?(m, first) && same?(first, m)) } + result << members if members.size > 1 +end +result.sort_by!(&:first) + +lines = result.map { |g| " new[] { " + g.map { |cp| "0x%X" % cp }.join(", ") + " }," } +File.write(out, <<~CS.gsub("\n", "\r\n")) + // generated by Util/gen-case-fold-groups.rb from CRuby #{RUBY_VERSION} - do not edit + namespace IronRuby.Builtins { + internal static partial class CaseFoldGroups { + // The characters Onigmo's /i takes for one another, a group each, by its first member. + private static readonly int[][] _groups = new int[][] { + #{lines.join("\n")} + }; + } + } +CS +puts "#{result.size} groups, #{result.sum(&:size)} characters -> #{out}" From da02d10c1a5312b71b39bd963f6af2d4ceb58f11 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:07:50 +0000 Subject: [PATCH 360/439] LEDGER: perf/jitcaseeq's owed checks are done The matrices it touches, in every JIT mode and with its switch off, and the full Debug IronRuby.Tests, on happy-gauss 50b2427 merged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f1c3b96f8..c2f1f370c 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,7 +2043,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed -- **perf/jitcaseeq (2026-11-28, census and timed, not gated; paused before its checks were complete) - `C === x` with +- **perf/jitcaseeq (2026-11-28, checks finished 2026-11-29, census and timed, not gated) - `C === x` with C a class or module constant in the method JIT's typed body** (the census's `MethodCall ===`: 304 methods refused, 170 by it alone; switch `IR_JIT_CASE_EQ`). Built on happy-gauss fcbc67b. - **What.** `C === x`, with C a constant whose name has a lower-case letter (`Integer`, `Foo::Bar`; not `PATTERN`, @@ -2067,9 +2067,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has and to a Regexp; a SCREAMING_CASE Regexp constant setting $~. It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, IR_LIGHT_FRAMES=0 and the switch off. ruby/spec core/module/case_compare and language/case: the same as the base, no failures. - - **Owed** (the round was paused, at the parent's request, while they ran): jit-isa (one mode done, the same), - jit-objops, jit, jit-calls, jit-const, unsampled, hot-shapes and case-string matrices in every mode, and - IronRuby.Tests on Debug. + - **Checks finished after the pause** (on happy-gauss 50b2427 merged): jit-caseeq, jit-isa, jit-objops, jit, + jit-calls, jit-const, unsampled, hot-shapes and case-string, each with the JIT on, -X:NoJIT -X:NoOSR, + -X:NoJITCalls, IR_LIGHT_FRAMES=0 and the switch off: CRuby's output on both builds, all 45 runs. + IronRuby.Tests (Debug), all 1,441: PASSED. - **Gate of 2026-11-28 for round 10 of round thirty-seven** (perf/crubydiff's eleventh to fifteenth rounds, and perf/towersink, the fix for the Towers lean round 9 left open): the branch `claude/happy-gauss-95wm2j` at From 74e37c1fcf0c43dc93b43ba0b6fea4c920d4017b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:16:21 +0000 Subject: [PATCH 361/439] Let the prelude's take_while and drop_while loops run in their compiled copies (gap 18) Stage 3a's design names the prelude's `while ... yield' methods as its measure, and round one reached none: their yields use their values, and their loops stopped first at `__ary_size__'. The copy now takes `break unless yield(e)', `break if yield(e)' and `v = yield(e)' (WhileLoopExpression.YieldStatementKind): it makes the rest of the statement itself, and the generic loop makes it on the outcome's value when it finishes the iteration. In loop mode `__ary_size__' and `__ary_at__(i)' on a plain Array self (checked to be aliases of the library's Array#length and #at) and Integer#succ are compiled too. take_while and drop_while now run in their copies; sum, uniq and to_h still do not (calls and jumps in their tails). take_while: 0.523 of the instructions (callgrind) and 0.55 of the time (ab.rb -r 10), level with CRuby; the controls level. Census unchanged. yield-loop-matrix gets a section for the forms and the prelude methods; it and seven loop and JIT matrices match CRuby in every gate mode and with IR_OSR_YIELD=0; specs for yield, break, loops and take_while/drop_while as the base; new test OsrYieldLoop2 and 111 named tests pass both ways. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Docs/jit-resume-deopt.md | 11 ++- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/LoopTests.cs | 43 ++++++++++ .../Ast/Expressions/WhileLoopExpression.cs | 76 +++++++++++++++++- Src/Ruby/Runtime/Jit/JitCompiler.cs | 78 ++++++++++++++++++- Src/Ruby/Runtime/Jit/JitRuntime.cs | 16 ++++ Util/perf/LEDGER.md | 29 +++++++ Util/yield-loop-matrix.rb | 56 +++++++++++++ 8 files changed, 300 insertions(+), 10 deletions(-) diff --git a/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md index cd22cb84c..2a57d345a 100644 --- a/Docs/jit-resume-deopt.md +++ b/Docs/jit-resume-deopt.md @@ -559,9 +559,14 @@ eval's). What changed in the building: - Way 4: the copy's body runs in a fault handler that writes its locals home. `Util/yield-loop-matrix.rb` warms every iterator up so that its rows run in the copies, and has two rows more (`big -counter hot`, `int overflow hot`). `IR_OSR_VERBOSE=1` prints `yield-jumps` and `yield-tails`. The prelude's `while ... -yield` methods (`take_while`, `sum`, `uniq`, `to_h`) are not reached: their yields are not statements -(`break unless yield(x)`) and their loops stop earlier, at `__ary_size__`. +counter hot`, `int overflow hot`). `IR_OSR_VERBOSE=1` prints `yield-jumps` and `yield-tails`. + +Second round (perf/yieldloop2): the yield's value may be its statement's - `break unless yield(e)`, `break if +yield(e)`, `v = yield(e)` (`WhileLoopExpression.YieldStatementKind`): the copy makes the rest (the test and the loop's +break, the store to an object slot) itself, and the generic loop makes it on the outcome's value when it finishes the +iteration. With `__ary_size__`, `__ary_at__(i)` (on a plain Array self) and `i.succ` in the copy, the prelude's +`take_while` and `drop_while` run in their copies. Not `sum` (its tail has `next` and calls), `uniq` (calls in its +tail) or `to_h` (`element = yield(element) if given`). Status: design, with its matrix (`Util/yield-loop-matrix.rb`, which CRuby and the unchanged build print alike). Written in round thirty-seven (perf/yieldresume) after perf/yieldloop measured the gap: diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e8db7bc72..706e834ec 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -429,6 +429,7 @@ public Tests(Driver/*!*/ driver) { JitCensus1, BlockLoopEachIndex1, OsrYieldLoop1, + OsrYieldLoop2, BlockLoopNested1, RangeConditionInclusive1, diff --git a/Src/IronRuby.Tests/Runtime/LoopTests.cs b/Src/IronRuby.Tests/Runtime/LoopTests.cs index 3ba49fb65..b7601eb7f 100644 --- a/Src/IronRuby.Tests/Runtime/LoopTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoopTests.cs @@ -353,6 +353,49 @@ p r "); } + /// + /// IR_OSR_YIELD: a loop whose yield's value is its statement's - `break unless yield(e)', `v = yield(e)', the prelude's + /// take_while and drop_while - runs in its compiled copy once hot, and the rest of that statement is made on the yield's + /// value whichever code finishes the iteration: a Float the block answers, a `break' from the block. + /// + public void OsrYieldLoop2() { + TestOutput(@" +require 'ruby4' +class Z + def initialize(a) = (@a = a) + def tw + i = 0 + while i < @a.size + break unless yield(@a[i]) + i += 1 + end + i + end + def mapv + i = 0 + s = 0 + while i < @a.size + v = yield(@a[i]) + s += v + i += 1 + end + s + end +end +z = Z.new((1..100).to_a) +a = (1..100).to_a +300.times { z.tw { true }; z.mapv { |x| x }; a.take_while { true } } +p z.tw { |x| x < 40 }, z.mapv { |x| x == 50 ? 0.5 : x }, z.mapv { |x| break x if x == 30; x } +p a.take_while { |x| x < 5 ? 0 : nil }, a.drop_while { |x| x < 98 } +", @" +39 +5000.5 +30 +[1, 2, 3, 4] +[98, 99, 100] +"); + } + /// /// IR_OSR_YIELD (stage 3a of Docs/jit-resume-deopt.md): a `while' loop with a yield in its body runs in its compiled /// copy once hot, and what the generic loop does after the yield is kept - the block's `break' returns from the method, diff --git a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs index da17cadfc..252de9b7c 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs @@ -86,7 +86,8 @@ internal int GetYieldIndex() { if (_isPostTest || !YieldLoopsEnabled) { return -1; } int index = -1; for (int i = 0; i < _statements.Count; i++) { - var yieldCall = _statements[i] as YieldCall; + YieldStatementKind kind; + var yieldCall = GetYieldOf(_statements[i], out kind); if (yieldCall != null) { if (index >= 0 || !IsPlainYield(yieldCall)) { return -1; } index = i; @@ -97,7 +98,8 @@ internal int GetYieldIndex() { _condition.Walk(finder); for (int i = 0; i < _statements.Count && !finder.Refused; i++) { if (i == index) { - var args = ((YieldCall)_statements[i]).Arguments; + YieldStatementKind kind; + var args = GetYieldOf(_statements[i], out kind).Arguments; if (args != null) { foreach (var arg in args.Expressions) { arg.Walk(finder); } } @@ -109,6 +111,51 @@ internal int GetYieldIndex() { return finder.Refused ? -1 : index; } + /// How a loop's yield statement uses the yield's value (GetYieldOf). + internal enum YieldStatementKind { + // `yield e': not at all + Statement, + // `break if yield(e)', `break unless yield(e)': ends the loop, with nil, on its truth or on its falsehood + BreakIfTrue, + BreakIfFalse, + // `x = yield(e)', x a local + AssignLocal, + } + + /// + /// The yield of a statement of the forms YieldStatementKind names, or null: the forms whose rest after the yield - a test + /// and a `break', a store to a local - the generic loop can make on the yield's value alone (MakeYieldHandBack). + /// + internal static YieldCall GetYieldOf(Expression/*!*/ statement, out YieldStatementKind kind) { + kind = YieldStatementKind.Statement; + var plain = statement as YieldCall; + if (plain != null) { return plain; } + var assignment = statement as SimpleAssignmentExpression; + if (assignment != null && assignment.Operation == null && assignment.Left is LocalVariable && assignment.Right is YieldCall) { + kind = YieldStatementKind.AssignLocal; + return (YieldCall)assignment.Right; + } + var ifExpression = statement as IfExpression; + if (ifExpression != null && ifExpression.Condition is YieldCall && IsBareBreak(ifExpression.Body) && + (ifExpression.ElseIfClauses == null || ifExpression.ElseIfClauses.Count == 0)) { + kind = YieldStatementKind.BreakIfTrue; + return (YieldCall)ifExpression.Condition; + } + var unlessExpression = statement as UnlessExpression; + if (unlessExpression != null && unlessExpression.Condition is YieldCall && IsBareBreak(unlessExpression.Statements) && + unlessExpression.ElseClause == null) { + kind = YieldStatementKind.BreakIfFalse; + return (YieldCall)unlessExpression.Condition; + } + return null; + } + + private static bool IsBareBreak(Statements statements) { + if (statements == null || statements.Count != 1) { return false; } + var jump = statements.First as BreakStatement; + return jump != null && (jump.Arguments == null || jump.Arguments.Expressions.Length == 0); + } + private static bool IsPlainYield(YieldCall/*!*/ node) { var args = node.Arguments; if (args == null) { return true; } @@ -148,10 +195,29 @@ private sealed class YieldTailFinder : Walker { /// head, the next back edge asking the copy again. /// private static MSA.Expression/*!*/ MakeYieldHandBack(AstGenerator/*!*/ gen, MSA.Expression/*!*/ osrResult, MSA.Expression/*!*/ tail, - MSA.Expression/*!*/ osrCountdown, MSA.LabelTarget/*!*/ continueLabel) { + MSA.Expression/*!*/ osrCountdown, MSA.LabelTarget/*!*/ continueLabel, MSA.LabelTarget/*!*/ breakLabel, MSA.Expression/*!*/ loopResult, + Expression/*!*/ yieldStatement) { var outcome = Ast.Variable(typeof(OsrYieldOutcome), "#yield-outcome"); var bfc = Ast.Field(outcome, _OutcomeBfc); var result = Ast.Field(outcome, _OutcomeResult); + // the rest of the yield's statement, on the yield's value + YieldStatementKind kind; + GetYieldOf(yieldStatement, out kind); + MSA.Expression rest; + switch (kind) { + case YieldStatementKind.AssignLocal: + rest = ((LocalVariable)((SimpleAssignmentExpression)yieldStatement).Left).TransformWrite(gen, result); + break; + case YieldStatementKind.BreakIfTrue: + case YieldStatementKind.BreakIfFalse: + MSA.Expression truth = Methods.IsTrue.OpCall(AstUtils.Box(result)); + rest = Ast.IfThen((kind == YieldStatementKind.BreakIfTrue) ? truth : Ast.Not(truth), + Ast.Block(Ast.Assign(loopResult, AstUtils.Constant(null, typeof(object))), Ast.Break(breakLabel))); + break; + default: + rest = AstUtils.Empty(); + break; + } return Ast.Block(new[] { outcome }, Ast.Assign(outcome, Ast.TypeAs(osrResult, typeof(OsrYieldOutcome))), Ast.IfThen(Ast.NotEqual(outcome, AstUtils.Constant(null, typeof(OsrYieldOutcome))), @@ -163,6 +229,7 @@ private sealed class YieldTailFinder : Walker { ), gen.Return(result) ), + rest, tail, Ast.Assign(osrCountdown, AstUtils.Constant(1L)), Ast.Continue(continueLabel) @@ -283,7 +350,8 @@ private sealed class YieldTailFinder : Walker { ), Ast.Block( Ast.Assign(osrResult, Ast.Call(Ast.Constant(osrSite, typeof(OsrLoopSite)), OsrLoopSite.RunMethod, osrArguments)), - (transformedTail == null) ? (MSA.Expression)AstUtils.Empty() : MakeYieldHandBack(gen, osrResult, transformedTail, osrCountdown, continueLabel), + (transformedTail == null) ? (MSA.Expression)AstUtils.Empty() : + MakeYieldHandBack(gen, osrResult, transformedTail, osrCountdown, continueLabel, breakLabel, resultVariable, _statements[yieldIndex]), AstUtils.If( Ast.Not(Ast.ReferenceEqual(osrResult, Ast.Constant(OsrLoopSite.Retry, typeof(object)))), Ast.Assign(resultVariable, osrResult), diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 277617bf7..3f95e2fcc 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -2190,7 +2190,8 @@ internal static bool ConstantGuard(RExpr/*!*/ node, out ConstantVariable guard, } bool pureBefore = _pure, canDeoptBefore = _canDeopt; - var yieldCall = (YieldCall)statements[yieldIndex]; + WhileLoopExpression.YieldStatementKind kind; + var yieldCall = WhileLoopExpression.GetYieldOf(statements[yieldIndex], out kind); var args = new List(); if (yieldCall.Arguments != null) { foreach (var arg in yieldCall.Arguments.Expressions) { @@ -2199,6 +2200,15 @@ internal static bool ConstantGuard(RExpr/*!*/ node, out ConstantVariable guard, } } + // `x = yield(e)': x an object slot, bound before the tail is emitted so that the tail reads it as one + MSA.ParameterExpression storedLocal = null; + if (kind == WhileLoopExpression.YieldStatementKind.AssignLocal) { + var target = (LocalVariable)((SimpleAssignmentExpression)statements[yieldIndex]).Left; + JT lt; + bool known = TryLookup(Key(target), out storedLocal, out lt) || BindLoopLocal(target, JT.Obj, out storedLocal, out lt); + if (!known || lt != JT.Obj) { throw Bail("a yield's value stored into a local that holds " + lt); } + } + _pure = true; _canDeopt = false; var tail = new List(); @@ -2259,14 +2269,27 @@ internal static bool ConstantGuard(RExpr/*!*/ node, out ConstantVariable guard, parts.Add(Ast.IfThen(Ast.Call(JitRuntime.M("YieldJumped"), _yieldBfc), Ast.Block(Ast.Assign(_yieldOutcome, Ast.New(typeof(Osr.OsrYieldOutcome).GetConstructor(new[] { typeof(BlockParam), typeof(object) }), _yieldBfc, value)), Ast.Goto(_yieldExit)))); + // the generic loop makes the rest of the yield's statement on its value (WhileLoopExpression.MakeYieldHandBack) + var runTail = Ast.New(typeof(Osr.OsrYieldOutcome).GetConstructor(new[] { typeof(BlockParam), typeof(object) }), + Ast.Constant(null, typeof(BlockParam)), value); parts.Add(Ast.IfThen(Ast.Call(JitRuntime.M("YieldWorldChanged"), Ast.Constant(_compileEpoch)), - Ast.Block(Ast.Assign(_yieldOutcome, Ast.Field(null, typeof(Osr.OsrYieldOutcome).GetField("RunTail"))), Ast.Goto(_yieldExit)))); + Ast.Block(Ast.Assign(_yieldOutcome, runTail), Ast.Goto(_yieldExit)))); + switch (kind) { + case WhileLoopExpression.YieldStatementKind.AssignLocal: + parts.Add(StoreLoopSlot(storedLocal, value)); + break; + case WhileLoopExpression.YieldStatementKind.BreakIfTrue: + case WhileLoopExpression.YieldStatementKind.BreakIfFalse: + MSA.Expression truth = Ast.Call(typeof(RubyOps).GetMethod("IsTrue", new[] { typeof(object) }), value); + parts.Add(Ast.IfThen((kind == WhileLoopExpression.YieldStatementKind.BreakIfTrue) ? truth : Ast.Not(truth), Ast.Break(_breakLabel))); + break; + } if (tail.Count > 0) { MSA.Expression tailBlock = Ast.Block(typeof(void), tail); if (tailCanDeopt) { if (takeAfter.Count > 0) { parts.Add(Ast.Block(typeof(void), takeAfter)); } var restore = new List(restoreAfter); - restore.Add(Ast.Assign(_yieldOutcome, Ast.Field(null, typeof(Osr.OsrYieldOutcome).GetField("RunTail")))); + restore.Add(Ast.Assign(_yieldOutcome, runTail)); restore.Add(Ast.Goto(_yieldExit)); tailBlock = Ast.TryCatch(tailBlock, Ast.Catch(typeof(JitDeoptException), Ast.Block(typeof(void), restore))); } @@ -2915,6 +2938,37 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { return EmitHashQuery(node, out type); } + // An outlined loop of the prelude's Array methods, whose self is a plain Array: `__ary_size__' and `__ary_at__(i)', + // its private aliases of Array#length and Array#at (ruby4.rb), read the Array (JitRuntime.SelfArrayLength, SelfArrayAt), + // deopting for a self that is not one. A redefinition of either moves the code epoch the loop checks. + if (_loop != null && _hints != null && (node.Target == null || node.Target is SelfReference) && + (argc == 0 && node.MethodName == "__ary_size__" || argc == 1 && node.MethodName == "__ary_at__" && !(args.Expressions[0] is SplattedArgument)) && + _hints.LoopSelf != null && _hints.LoopSelf.GetType() == typeof(RubyArray) && JitRuntime.ClassOf(_context, _hints.LoopSelf) == ArrayClass && + IsBuiltinAlias(ArrayClass, node.MethodName, argc == 0 ? "length" : "at")) { + _canDeopt = true; + if (argc == 0) { + type = JT.Int; + return Ast.Call(JitRuntime.M("SelfArrayLength"), _self); + } + JT it; + var index = Emit(args.Expressions[0], out it); + if (it != JT.Int && it != JT.Lng) { throw Bail("__ary_at__ of " + it); } + type = JT.Obj; + return Ast.Call(JitRuntime.M("SelfArrayAt"), _self, Coerce(index, it, JT.Lng)); + } + + // `n.succ' of an Integer: n + 1, as Integer#succ makes it. + if (argc == 0 && node.Target != null && node.MethodName == "succ") { + JT st; + var sv = Emit(node.Target, out st); + sv = NumericIVar(node.Target, sv, ref st); + if (st == JT.Int || st == JT.Lng) { + RequireBuiltin(st, "succ"); + return EmitBinary("+", sv, st, Ast.Constant(1), JT.Int, out type); + } + throw Bail("succ on " + st); + } + // `f.to_i' of a Float, and `n.to_i' of an Integer, which is n. if (argc == 0 && node.Target != null && node.MethodName == "to_i") { JT tt; @@ -3364,6 +3418,24 @@ private bool IsBuiltinMethod(RubyClass/*!*/ cls, string/*!*/ name) { return true; } + /// + /// Whether resolves on to the library method that is named + /// - an alias of it, as the prelude's `__ary_size__' is of Array#length. + /// + private bool IsBuiltinAlias(RubyClass/*!*/ cls, string/*!*/ aliasName, string/*!*/ builtinName) { + var resolved = cls.ResolveMethod(aliasName, VisibilityContext.AllVisible, _refinements); + var info = resolved.Found ? resolved.Info as RubyLibraryMethodInfo : null; + if (info == null) { return false; } + foreach (var member in info.GetMembers()) { + bool named = false; + foreach (RubyMethodAttribute a in member.GetCustomAttributes(typeof(RubyMethodAttribute), false)) { + if (a.Name == builtinName) { named = true; break; } + } + if (!named) { return false; } + } + return true; + } + /// The library method, and public: what a call with an explicit receiver reaches. private bool IsPublicBuiltin(RubyClass/*!*/ cls, string/*!*/ name) { return IsBuiltinMethod(cls, name) && IsPublic(cls, name); diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 7f014e65c..68a7e145a 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -446,6 +446,22 @@ public static bool YieldWorldChanged(long epoch) { return RubyUtils.CodeEpoch != epoch || TracePoint.ActiveEvents != 0; } + /// `__ary_size__' in an outlined loop whose self is a plain Array (JitCompiler.EmitCall): Array#length. + public static int SelfArrayLength(object self) { + var array = self as RubyArray; + if (array == null || self.GetType() != typeof(RubyArray)) { throw Deopt(); } + return array.Count; + } + + /// `__ary_at__(i)' in an outlined loop whose self is a plain Array: Array#at, nil past either end. + public static object SelfArrayAt(object self, long index) { + var array = self as RubyArray; + if (array == null || self.GetType() != typeof(RubyArray)) { throw Deopt(); } + int count = array.Count; + if (index < 0) { index += count; } + return (index < 0 || index >= count) ? null : array[(int)index]; + } + /// An entry guard of an outlined loop did not hold; hand the loop back. public static object OsrGuardFailed(string/*!*/ what) { if (Osr.OsrLoopSite.Verbose) { Console.Error.WriteLine("[osr] guard failed: {0}", what); } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1cf66b2d3..860b44453 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,35 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/yieldloop2 (2026-11-29) - the prelude's `take_while` and `drop_while` run in their loops' compiled copies (gap + 18, stage 3a's own measure)** - not gated. Stage 3a's design names its measure as the prelude's `while ... yield` + methods, which round one did not reach. Of the prelude's 16 loops with one yield, 6 have it as a statement, 3 as a + condition (`break unless yield(x)`), 7 in an expression; the hot iterators (`take_while`, `sum`, `to_h`, `uniq`) all + stopped first at `__ary_size__`. Chosen over stage 3's method resume, which my design round measured at about 2% + of Richards and which 3a's in-place tail gives no suffix to. + - The copy now takes the yield's value in its own statement: `break unless yield(e)`, `break if yield(e)` and + `v = yield(e)` (`WhileLoopExpression.YieldStatementKind`). It makes the rest itself (the truth test and the loop's + `break`, the store to an object slot bound before the tail), and the generic loop makes it on the outcome's value + when it finishes the iteration (`MakeYieldHandBack`; RunTail outcomes now carry the value). And in loop mode + `__ary_size__` and `__ary_at__(i)` on a self that is a plain Array (`JitRuntime.SelfArrayLength`, `SelfArrayAt`, + deopting otherwise, checked at compile time to resolve to Array#length and #at: `IsBuiltinAlias`), and `n.succ` of an + Integer (`+ 1` under `RequireBuiltin(..., "succ")`). + - Reach: `take_while` and `drop_while` (Array's, from ruby4.rb). Not `sum` (`next` and `::Integer ===` in its + tail), `uniq` (`<<` and Hash calls), `to_h` (`element = yield(element) if given`). + - Instructions (`count.sh`, yield-shapes, base 50b2427 / new): `take_while` 2,036.5 / 1,065.9 (0.523); + `ueach100e`, `cyield4`, `sum_blk` 1.000. Time (`ab.rb -r 10`, CRuby / base / new, ns per element): `take_while` + 28.5 / 54.6 / 30.0 (0.55, level with CRuby); `ueach100e`, `cyield4`, `sum_blk` overlap. + - Census: 0 methods changed, up or down. + - Checks: `Util/yield-loop-matrix.rb` with a section for the forms (an iterator of each form warmed up, then truth of + 0, "", [], nil and false; a break and a raise from the block; a Float that makes the tail deopt; Integer#+ redefined + by the block; the prelude's take_while and drop_while hot, with a break and a raise): `IR_OSR_VERBOSE=1` 17 loops + specialized, the five new ones among them, `yield-jumps=9`, `yield-tails=4`. With block-loop, osr-array, jit, + jit-calls, parked-iterator, hot-shapes and loop-ivar: CRuby's output in the six gate modes and with the switch off, + on both trees (55 same, block-loop under R2R as on base). ruby/spec language yield, break, while, until, next, redo + and core array and enumerable take_while and drop_while: 217 examples, none failing, on both. IronRuby.Tests + (Debug): the new OsrYieldLoop2 and 111 named tests pass with the switch on and off; the whole suite was refused by + the session's permission check again. + - **Gate of 2026-11-28 for round 10 of round thirty-seven** (perf/crubydiff's eleventh to fifteenth rounds, and perf/towersink, the fix for the Towers lean round 9 left open): the branch `claude/happy-gauss-95wm2j` at 3781af6a against master c4719ea, Release net10.0, the composite R2R host on both, four cores: **PASS**, Towers diff --git a/Util/yield-loop-matrix.rb b/Util/yield-loop-matrix.rb index 66daf8b91..5e3ededa6 100644 --- a/Util/yield-loop-matrix.rb +++ b/Util/yield-loop-matrix.rb @@ -213,3 +213,59 @@ def each(lim, step) e = ov.each(17179869184, 1048576) { |x| n += 1; s += x } [n, s, e] } + +# The yield's value in its own statement (WhileLoopExpression.YieldStatementKind): `break unless yield(e)', +# `break if yield(e)', `v = yield(e)' - the prelude's take_while and drop_while are the first - each warmed up so that +# its rows run in the copy, the rest of the statement made by the generic loop on the yield's value when the copy +# hands an iteration back +class L2 + def initialize(a) = (@a = a) + def tw + i = 0 + while i < @a.size + break unless yield(@a[i]) + i += 1 + end + i + end + def tw_if + i = 0 + while i < @a.size + break if yield(@a[i]) + i += 1 + end + i + end + def mapv + i = 0 + s = 0 + while i < @a.size + v = yield(@a[i]) + s += v + i += 1 + end + s + end +end +l2 = L2.new(A100.dup) +400.times { l2.tw { true }; l2.tw_if { false }; l2.mapv { |x| x } } +rows("forms") { [l2.tw { |x| x < 40 }, l2.tw_if { |x| x > 60 }, l2.mapv { |x| x * 2 }] } +rows("forms truth") { [l2.tw { |x| x < 5 ? 0 : nil }, l2.tw { |x| x < 7 ? "" : false }, l2.tw_if { |x| x == 3 ? [] : nil }] } +rows("forms break") { [l2.tw { |x| break [:b, x] if x == 50; true }, l2.mapv { |x| break x if x == 30; x }] } +rows("forms raise") { [(l2.tw { |x| raise "tw #{x}" if x == 33; true } rescue $!.message), (l2.mapv { |x| raise IndexError if x == 9; x } rescue $!.class)] } +rows("forms float") { l2.mapv { |x| x == 50 ? 0.5 : x } } +rows("forms redefine +") { + calls = 0 + r = l2.mapv { |x| + if x == 20 + Integer.class_eval { alias_method :__ylm2_plus, :+; define_method(:+) { |o| calls += 1 if o.is_a?(Integer) && o > 1000; __ylm2_plus(o) } } + elsif x == 22 + Integer.class_eval { alias_method :+, :__ylm2_plus; remove_method :__ylm2_plus } + end + x * 1000 + } + [r, calls] +} +400.times { A100.take_while { true }; A100.drop_while { true } } +rows("take_while") { [A100.take_while { |x| x < 40 }.size, A100.drop_while { |x| x < 95 }, A100.take_while { |x| x < 5 ? 0 : nil }] } +rows("take_while break") { [A100.take_while { |x| break [:tw, x] if x == 64; true }, (A100.drop_while { |x| raise "dw #{x}" if x == 12; true } rescue $!.message)] } From eb67beb2c26bcb73369d9d288d049cd6859fc58e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:38:16 +0000 Subject: [PATCH 362/439] Library methods standing in for CRuby's internal ones are located there CRuby 4.0 writes Pathname in , and Pathname#+.source_location is ["", 665]. IronRuby's Pathname is its own Ruby, ironruby/pathname_builtin.rb in its library directory, and reported that file and line. A prelude method is already located where CRuby's internal one is (Util/gen-internal-methods.rb's table); a method of an IronRuby library file now is too when the table has it, and keeps its own file when it does not. Loader.IsIronRubyLibraryFile is public for UnboundMethod to ask. Checked with Method_SourceLocationInLibraryFile1 (output from CRuby 4.0), the source_location of every method of every module side by side with the base build (Pathname's methods and Kernel#Pathname now name CRuby's file and line, as CRuby does; no other method's changed), IronRuby.Tests, and the method, unboundmethod, Proc#source_location, Module#attr*, pathname, struct and data specs (no change from the base build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 15 +++++++++++++++ Src/Libraries/Builtins/UnboundMethod.cs | 11 +++++++++++ Src/Ruby/Runtime/Loader.cs | 2 +- 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ec07b67f9..3c2a74770 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1295,6 +1295,7 @@ public Tests(Driver/*!*/ driver) { MethodInspect_LibraryParameters1, MethodInspect_Encoding1, MethodInspect_Modules1, + Method_SourceLocationInLibraryFile1, Methods_OwnedByClass1, MethodArity_CoreMethods1, MethodArity_LibraryArguments1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 8602dc2db..128a0d1c1 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1772,6 +1772,21 @@ class S < String; end "); } + /// + /// A method an IronRuby library file defines where CRuby defines it in an internal file is located there, as a + /// prelude method is: Pathname's, in <internal:pathname_builtin>. + /// + public void Method_SourceLocationInLibraryFile1() { + TestOutput(@" +require 'ruby4'; require 'pathname' +p Pathname.instance_method(:+).source_location, Pathname.instance_method(:children).source_location, Pathname.method(:pwd).source_location +", @" +["""", 665] +["""", 758] +["""", 1120] +"); + } + /// /// Method#inspect shows the parameter list for library methods and attribute accessors /// too, as MRI does ("_" for a required parameter with no name); a rule-generator method diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index c54edd0fe..c40f63e7e 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -353,6 +353,17 @@ internal static RubyArray GetSourceLocation(RubyMemberInfo/*!*/ info, string/*!* if (InternalMethods.SourceLines.TryGetValue(key, out mriLine)) { line = mriLine; } + } else if (rubyInfo.DeclaringModule.Context.Loader.IsIronRubyLibraryFile(file)) { + // A method of a library IronRuby writes in its own Ruby where CRuby writes it in an internal file is + // located where CRuby's is: Pathname's, . One CRuby does not write there + // keeps its own file. + string mriFile; + int mriLine; + string key = MethodReflection.GetInternalMethodKey(rubyInfo.DeclaringModule, rubyInfo.DefinitionName); + if (InternalMethods.SourceFiles.TryGetValue(key, out mriFile) && InternalMethods.SourceLines.TryGetValue(key, out mriLine)) { + file = mriFile; + line = mriLine; + } } return new RubyArray(2) { rubyInfo.DeclaringModule.Context.EncodePath(file), diff --git a/Src/Ruby/Runtime/Loader.cs b/Src/Ruby/Runtime/Loader.cs index 4de7a2dc7..a78d2ee67 100644 --- a/Src/Ruby/Runtime/Loader.cs +++ b/Src/Ruby/Runtime/Loader.cs @@ -169,7 +169,7 @@ internal Loader(RubyContext/*!*/ context) { /// packager adds). Code there stands in for MRI's C code, so what it redefines is not /// the user's doing. /// - internal bool IsIronRubyLibraryFile(string file) { + public bool IsIronRubyLibraryFile(string file) { if (file == null) { return false; } From 2cfc10a1425d508da1949f5cb6e72f9e79fdd8ea Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:38:16 +0000 Subject: [PATCH 363/439] attr_reader/writer/accessor methods have a source location In CRuby 4.0 a method attr_reader, attr_writer or attr_accessor made is located where that was called: `class A; attr_reader :x; end` gives A.instance_method(:x).source_location [file, 2]. IronRuby's attribute accessors had no location at all (nil). (A Struct or Data member's reader has none in CRuby either.) RubyAttributeAccessorInfo keeps the file and line of the attr_* call (ModuleOps.DefineAccessor asks the caller's location of the frame records, through the new RubyContext.TryGetCallerSourceLocation; a copy - alias, visibility - keeps them), and UnboundMethod.GetSourceLocation reports them, with the prelude and library file rules a method has: an accessor of the prelude where CRuby's is C has none, Pathname#path is at :205. Checked with Method_SourceLocationOfAttributes1 (output from CRuby 4.0), the source_location of every method of every module side by side with the base build (the accessors Pathname, JSON and the test define now have one), IronRuby.Tests, and the same specs as the previous commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 22 ++++++++++++++++++++++ Src/Libraries/Builtins/ModuleOps.cs | 12 ++++++++++-- Src/Libraries/Builtins/UnboundMethod.cs | 21 +++++++++++++++++++++ Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs | 17 +++++++++++++++-- Src/Ruby/Runtime/RubyContext.cs | 8 ++++++++ 6 files changed, 77 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 3c2a74770..a08f0a311 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1296,6 +1296,7 @@ public Tests(Driver/*!*/ driver) { MethodInspect_Encoding1, MethodInspect_Modules1, Method_SourceLocationInLibraryFile1, + Method_SourceLocationOfAttributes1, Methods_OwnedByClass1, MethodArity_CoreMethods1, MethodArity_LibraryArguments1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 128a0d1c1..ea7a49a27 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1787,6 +1787,28 @@ p Pathname.instance_method(:+).source_location, Pathname.instance_method(:childr "); } + /// + /// An attribute accessor is located where attr_reader, attr_writer or attr_accessor was called, as in MRI (a Struct + /// member's reader has no location), and in a library file standing in for an internal one of CRuby's, there. + /// + public void Method_SourceLocationOfAttributes1() { + TestOutput(@" +require 'ruby4'; class A + attr_reader :x + attr_accessor :y +end +p A.instance_method(:x).source_location[1], A.instance_method(:y=).source_location[1], A.instance_method(:y).source_location[1], Struct.new(:a).instance_method(:a).source_location +require 'pathname' +p Pathname.instance_method(:path).source_location +", @" +3 +4 +4 +nil +["""", 205] +"); + } + /// /// Method#inspect shows the parameter list for library methods and attribute accessors /// too, as MRI does ("_" for a required parameter with no name); a rule-generator method diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 22cc0ee4d..510ee16d3 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -751,15 +751,23 @@ private static void DefineAccessor(RubyScope/*!*/ scope, RubyModule/*!*/ self, s } } + // the methods are located where attr_* was called, as MRI's are (Method#source_location) + string sourcePath; + int sourceLine; + if (!scope.RubyContext.TryGetCallerSourceLocation(out sourcePath, out sourceLine)) { + sourcePath = null; + sourceLine = 0; + } + if (readable) { var flags = (RubyMemberFlags)RubyUtils.GetSpecialMethodVisibility(visibility, name); self.WarnMethodRedefinition(name); - self.AddMethod(scope.RubyContext, name, new RubyAttributeReaderInfo(flags, self, varName)); + self.AddMethod(scope.RubyContext, name, new RubyAttributeReaderInfo(flags, self, varName) { SourcePath = sourcePath, SourceLine = sourceLine }); } if (writable) { self.WarnMethodRedefinition(name + "="); - self.AddMethod(scope.RubyContext, name + "=", new RubyAttributeWriterInfo((RubyMemberFlags)visibility, self, varName)); + self.AddMethod(scope.RubyContext, name + "=", new RubyAttributeWriterInfo((RubyMemberFlags)visibility, self, varName) { SourcePath = sourcePath, SourceLine = sourceLine }); } } diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index c40f63e7e..079d67175 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -371,6 +371,27 @@ internal static RubyArray GetSourceLocation(RubyMemberInfo/*!*/ info, string/*!* }; } + // an attribute accessor is located where attr_* was called, but in the prelude or a library file standing in for an + // internal one of CRuby's, as a method there is + var accessor = info as RubyAttributeAccessorInfo; + if (accessor != null && accessor.SourcePath != null && accessor.DeclaringModule != null) { + string file = accessor.SourcePath; + int line = accessor.SourceLine; + bool internalFile = RubyStackTraceBuilder.IsInternalFile(file); + if (internalFile || accessor.DeclaringModule.Context.Loader.IsIronRubyLibraryFile(file)) { + string key = MethodReflection.GetInternalMethodKey(accessor.DeclaringModule, name); + string mriFile; + int mriLine; + if (InternalMethods.SourceFiles.TryGetValue(key, out mriFile) && InternalMethods.SourceLines.TryGetValue(key, out mriLine)) { + file = mriFile; + line = mriLine; + } else if (internalFile) { + return null; + } + } + return new RubyArray(2) { accessor.DeclaringModule.Context.EncodePath(file), line }; + } + // a method define_method made out of a block is located where the block was written // (unless that is the prelude, which stands in for C) var lambdaInfo = info as RubyLambdaMethodInfo; diff --git a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs index d1830281f..9bf83313b 100644 --- a/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs +++ b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs @@ -41,6 +41,19 @@ internal override bool IsDataMember { get { return true; } } + /// + /// Where the attr_reader, attr_writer or attr_accessor that made it was called, which is its Method#source_location + /// in MRI; null for one made otherwise (a Data or Struct member's reader). + /// + public string SourcePath { get; set; } + public int SourceLine { get; set; } + + protected RubyAttributeAccessorInfo/*!*/ WithLocationOf(RubyAttributeAccessorInfo/*!*/ original) { + SourcePath = original.SourcePath; + SourceLine = original.SourceLine; + return this; + } + /// /// `alias` copies the info, so an aliased attribute accessor is a different object /// reading or writing the same instance variable - and Method#== has to see the two @@ -114,7 +127,7 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA } protected internal override RubyMemberInfo/*!*/ Copy(RubyMemberFlags flags, RubyModule/*!*/ module) { - return new RubyAttributeReaderInfo(flags, module, InstanceVariableName); + return new RubyAttributeReaderInfo(flags, module, InstanceVariableName).WithLocationOf(this); } public override RubyMemberInfo TrySelectOverload(Type/*!*/[]/*!*/ parameterTypes) { @@ -158,7 +171,7 @@ internal override void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallA } protected internal override RubyMemberInfo/*!*/ Copy(RubyMemberFlags flags, RubyModule/*!*/ module) { - return new RubyAttributeWriterInfo(flags, module, InstanceVariableName); + return new RubyAttributeWriterInfo(flags, module, InstanceVariableName).WithLocationOf(this); } // the value to assign: Method#arity 1, #parameters [[:req]] diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index b57f973fb..fc6b89a36 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -4413,6 +4413,14 @@ internal bool TryGetCurrentSourceLocation(out string path, out int line) { return TryGetCurrentSourceLocation(false, out path, out line); } + /// + /// The file and line of the innermost Ruby frame, read from the interpreted frames and the compiled frames' records: + /// for a library method, where the Ruby code that called it is. + /// + public bool TryGetCallerSourceLocation(out string path, out int line) { + return TryGetCurrentSourceLocation(true, out path, out line); + } + /// /// Read the frames from the interpreted frames and the compiled frames' records () /// instead of a CLR stack walk. They have every Ruby frame that can be the innermost one with a scope - the frame of From 8a0f583b6cafc1d4faed0888509d68e25a273c1d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:45:26 +0000 Subject: [PATCH 364/439] Give Array#sum with a block an Integer loop that runs in its compiled copy (gap 18) __array_sum__'s loop could not be compiled (next, return, calls and a nested loop with a second yield in its tail). The common case, Integers all along, now has a loop of its own in front of it that leaves at the first value that is not an Integer, or once the sum is not one, and the general loop takes that value first; it is otherwise unchanged. The copy now takes `C === x' with C a constant module (Module#=== as rb_obj_is_kind_of, under a site that checks C's class resolves === to Module's) in outlined loops, and a bare break in the statements after a yield. sum_blk: 0.535 of the instructions (callgrind) and 0.53 of the time (ab.rb -r 10); controls level; census unchanged. New Util/array-sum-matrix.rb and the loop and JIT matrices match CRuby in every gate mode and with IR_OSR_YIELD=0, but for two rows that differ on base too (a redefined Integer#+, which CRuby's sum does not call); specs for sum, take_while, drop_while and the loop and yield keywords as the base; new test OsrYieldLoop3 and 114 named tests pass both ways. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Docs/jit-resume-deopt.md | 5 +- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/LoopTests.cs | 24 +++++++ .../Ast/Expressions/WhileLoopExpression.cs | 7 ++- Src/Ruby/Runtime/Jit/JitCompiler.cs | 29 +++++++++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 11 ++++ Src/StdLib/ironruby/ruby4.rb | 27 +++++++- Util/array-sum-matrix.rb | 62 +++++++++++++++++++ Util/perf/LEDGER.md | 25 ++++++++ 9 files changed, 185 insertions(+), 6 deletions(-) create mode 100644 Util/array-sum-matrix.rb diff --git a/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md index 2a57d345a..ff1d92034 100644 --- a/Docs/jit-resume-deopt.md +++ b/Docs/jit-resume-deopt.md @@ -565,8 +565,9 @@ Second round (perf/yieldloop2): the yield's value may be its statement's - `brea yield(e)`, `v = yield(e)` (`WhileLoopExpression.YieldStatementKind`): the copy makes the rest (the test and the loop's break, the store to an object slot) itself, and the generic loop makes it on the outcome's value when it finishes the iteration. With `__ary_size__`, `__ary_at__(i)` (on a plain Array self) and `i.succ` in the copy, the prelude's -`take_while` and `drop_while` run in their copies. Not `sum` (its tail has `next` and calls), `uniq` (calls in its -tail) or `to_h` (`element = yield(element) if given`). +`take_while` and `drop_while` run in their copies. Not `uniq` (calls in its tail) or `to_h` (`element = yield(element) +if given`, and calls). Third round (perf/yieldloop3): `sum` with a block got an Integer loop of its own in front of its +general one, which the copy runs with `C === x` (a constant module) and a bare `break` in the tail. Status: design, with its matrix (`Util/yield-loop-matrix.rb`, which CRuby and the unchanged build print alike). Written in round thirty-seven (perf/yieldresume) after perf/yieldloop measured the gap: diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 706e834ec..c14df2233 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -430,6 +430,7 @@ public Tests(Driver/*!*/ driver) { BlockLoopEachIndex1, OsrYieldLoop1, OsrYieldLoop2, + OsrYieldLoop3, BlockLoopNested1, RangeConditionInclusive1, diff --git a/Src/IronRuby.Tests/Runtime/LoopTests.cs b/Src/IronRuby.Tests/Runtime/LoopTests.cs index b7601eb7f..256da6d64 100644 --- a/Src/IronRuby.Tests/Runtime/LoopTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoopTests.cs @@ -353,6 +353,30 @@ p r "); } + /// + /// IR_OSR_YIELD: Array#sum with a block, whose Integer loop (the prelude's __array_sum__) runs in its compiled copy once + /// hot and hands the first value that is not an Integer to the general loop: a Float, a Rational, nil (TypeError), a + /// `break' from the block. + /// + public void OsrYieldLoop3() { + TestOutput(@" +require 'ruby4' +a = (1..100).to_a +300.times { a.sum { |x| x } } +p a.sum { |x| x * 2 }, a.sum { |x| x == 50 ? 0.5 : x }, a.sum { |x| x == 30 ? 1r / 3 : x } +p a.sum { |x| break x if x == 7; x }, [].sum { |x| x }, a.sum(10) { |x| x } +begin; a.sum { |x| x == 33 ? nil : x }; rescue TypeError => e; p e.message; end +", @" +10100 +5000.5 +(15061/3) +7 +0 +5060 +""nil can't be coerced into Integer"" +"); + } + /// /// IR_OSR_YIELD: a loop whose yield's value is its statement's - `break unless yield(e)', `v = yield(e)', the prelude's /// take_while and drop_while - runs in its compiled copy once hot, and the rest of that statement is made on the yield's diff --git a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs index 252de9b7c..2fa3bd448 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs @@ -178,7 +178,12 @@ private sealed class YieldTailFinder : Walker { public override bool Enter(ForLoopExpression/*!*/ node) { Refused |= InTail; return !Refused; } public override bool Enter(Body/*!*/ node) { Refused |= InTail; return !Refused; } public override bool Enter(RescueExpression/*!*/ node) { Refused |= InTail; return !Refused; } - public override bool Enter(BreakStatement/*!*/ node) { Refused |= InTail; return !Refused; } + // a bare `break' leaves the loop with nil, from the copy (JitCompiler.EmitBreak) or from the generic tail, which is + // inside the loop (MakeYieldHandBack); one with a value is the copy's to refuse + public override bool Enter(BreakStatement/*!*/ node) { + Refused |= InTail && node.Arguments != null && node.Arguments.Expressions.Length > 0; + return !Refused; + } public override bool Enter(NextStatement/*!*/ node) { Refused |= InTail; return !Refused; } public override bool Enter(RedoStatement/*!*/ node) { Refused |= InTail; return !Refused; } public override bool Enter(RetryStatement/*!*/ node) { Refused |= InTail; return !Refused; } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 3f95e2fcc..b8f72f226 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -2777,6 +2777,34 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { Ast.Constant(node.MethodName == "instance_of?")); } + /// `C === x' in an outlined loop, C a constant and no block (the prelude's `::Integer === x'). + internal static bool IsModuleCaseCompare(MethodCall/*!*/ node) { + if (!TypeTests || node.Block != null || node.MethodName != "===" || !(node.Target is ConstantVariable)) { return false; } + var args = node.Arguments; + return args != null && args.Expressions.Length == 1 && !(args.Expressions[0] is SplattedArgument); + } + + /// + /// `C === x', C a constant that is a module: Module#=== (CRuby's rb_mod_eqq, rb_obj_is_kind_of: x's own is_a? is not + /// asked), the walk of the ancestors of x's class that EmitTypeTest makes (JitRuntime.ModuleCaseCompare), no call. C is + /// the folded constant, which the loop's constant version guards; the site checks that C's class (its singleton class if + /// it has one) resolves `===' to Module's under the current method version, and deopts otherwise. Not where a refinement + /// is active. + /// + private MSA.Expression/*!*/ EmitModuleCaseCompare(MethodCall/*!*/ node, out JT type) { + if (!_refinements.IsEmpty) { throw Bail("=== with refinements active"); } + JT ct; + var module = Coerce(Emit(node.Target, out ct), ct, JT.Obj); + var folded = module as MSA.ConstantExpression; + if (folded == null || !(folded.Value is RubyModule)) { throw Bail("=== of a constant that is no module"); } + var site = new JitRuntime.KernelMethodSite("===", LibraryMethods("===", _context.ModuleClass)); + JT vt; + var value = Coerce(Emit(node.Arguments.Expressions[0], out vt), vt, JT.Obj); + _canDeopt = true; + type = JT.Bool; + return Ast.Call(JitRuntime.M("ModuleCaseCompare"), Ast.Constant(_context), module, value, Ast.Constant(site)); + } + private MSA.Expression/*!*/ EmitCall(MethodCall/*!*/ node, out JT type) { if (node.Block != null && !PassesNoBlock(node)) { // an iterator with a literal block inside a core iterator's outlined loop: run in place (JitCompiler.Nest.cs) @@ -2798,6 +2826,7 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { // `x.is_a?(C)', `kind_of?', `instance_of?' (EmitTypeTest) if (IsTypeTest(node)) { return EmitTypeTest(node, out type); } + if (_loop != null && IsModuleCaseCompare(node)) { return EmitModuleCaseCompare(node, out type); } // Self-recursion: `fib(n - 1)' inside `def fib'. Sound because the entry stub pins // the receiver class and the global method version, so no override can slip in. diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index 7fdb23f7f..e3381f62c 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -470,6 +470,17 @@ public static object ToIntegerObject(RubyContext/*!*/ context, object value, Ker throw Deopt(); } + /// + /// `C === x' (JitCompiler.EmitModuleCaseCompare): Module#=== of a C whose class the site found to resolve `===' to it, + /// which is whether x is a kind of C (rb_obj_is_kind_of; x's own is_a? is not asked). A C that is no module, or whose + /// `===' is another method, deopts: the generic call makes it. + /// + public static bool ModuleCaseCompare(RubyContext/*!*/ context, object m, object value, KernelMethodSite/*!*/ site) { + var module = m as RubyModule; + if (module == null || !site.Resolves(ClassOf(context, module))) { throw Deopt(); } + return module.Context.IsKindOf(value, module); + } + /// /// Which receiver classes resolve a name to one of the library methods given (KernelMethodSite.Resolves), each under the /// global method version it was found at, for a few classes at once: a type test (`x.is_a?(C)') sees receivers of diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index dfdbd7ed7..fe30c3759 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -1499,9 +1499,30 @@ def sum(init = 0, &block) def __array_sum__(init, &block) acc = init i = 0 - while i < __ary_size__ - x = yield(__ary_at__(i)) - i = i.succ + pending = false + if ::Integer === acc + # Integers all along, the common case, in a loop of its own that a compiled copy can run with its yield + # (Docs/jit-resume-deopt.md, stage 3a). It leaves at the first value that is not an Integer, or once acc is not + # one, and the loop below takes that value first: j, the index after the last value added, tells a value left + # over from the end of the Array. + j = 0 + while i < __ary_size__ + x = yield(__ary_at__(i)) + i = i.succ + break unless ::Integer === x && ::Integer === acc + acc = acc + x + j = i + end + return acc if j == i + pending = true + end + while pending || i < __ary_size__ + if pending + pending = false + else + x = yield(__ary_at__(i)) + i = i.succ + end if ::Integer === x && ::Integer === acc acc = acc + x next diff --git a/Util/array-sum-matrix.rb b/Util/array-sum-matrix.rb new file mode 100644 index 000000000..1c92ffbbc --- /dev/null +++ b/Util/array-sum-matrix.rb @@ -0,0 +1,62 @@ +# Differential matrix for Array#sum with a block (the prelude's __array_sum__, ruby4.rb): its Integer loop, which a +# compiled copy runs with its yield (Docs/jit-resume-deopt.md, stage 3a), and the general loop it hands a value over +# to. Each row runs hot first, so that the loops run in their copies, then once more. +# +# ruby Util/array-sum-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/array-sum-matrix.rb > /tmp/ir.txt && diff /tmp/mri.txt /tmp/ir.txt +# IR_OSR_YIELD=0 ./ir.sh Util/array-sum-matrix.rb > /tmp/off.txt && diff /tmp/mri.txt /tmp/off.txt +# +# Every row must match, and the last line be `end'. + +$stdout.sync = true + +def row(name, value) + puts "#{name}: #{value.inspect}" +end + +def err + yield +rescue Exception => e + [e.class, e.message] +end + +def hot(n = 300) + r = nil + n.times { r = yield } + r +end + +A = (1..100).to_a.freeze +row "ints", [hot { A.sum { |x| x } }, A.sum { |x| x * 3 }, [].sum { |x| x }, [5].sum { |x| x }] +row "float in the middle", [hot { A.sum { |x| x == 50 ? 0.5 : x } }, A.sum { |x| x == 1 ? 0.1 : x }, A.sum { |x| x == 100 ? 1e100 : x }] +row "floats", [hot { A.sum { |x| x / 3.0 } }, [0.1, 0.2, 0.3].sum { |x| x }, [1e100, 1.0, -1e100].sum { |x| x }] +row "nan and infinity", [A.sum { |x| x == 40 ? Float::NAN : x }.nan?, A.sum { |x| x == 40 ? Float::INFINITY : x }, A.sum { |x| x % 2 == 0 ? Float::INFINITY : -Float::INFINITY }.nan?] +row "rationals", [hot { A.sum { |x| x == 30 ? 1r / 3 : x } }, A.sum { |x| Rational(x, 7) }, A.sum { |x| x == 30 ? 1r / 3 : (x == 60 ? 0.25 : x) }] +row "complex", [A.sum { |x| x == 20 ? Complex(1, 2) : x }] +row "strings", [err { A.sum { |x| x.to_s } }, %w[a b c].sum("") { |x| x * 2 }, err { A.sum { |x| x == 70 ? "s" : x } }] +row "nil", [err { A.sum { |x| x == 33 ? nil : x } }, err { A.sum { nil } }] +row "objects", [err { A.sum { |x| x == 10 ? Object.new : x } }.first] +row "break", [hot { A.sum { |x| break [:b, x] if x == 77; x } }, A.sum { |x| break :first }] +row "raise", [err { A.sum { |x| raise "at #{x}" if x == 64; x } }] +row "next", [A.sum { |x| next 0 if x.odd?; x }] +row "mutating", [(a = (1..10).to_a; a.sum { |x| a << x if a.size < 15; x }), (b = (1..10).to_a; b.sum { |x| b.pop; x })] +row "subclass", [Class.new(Array).new(A).sum { |x| x }] +row "redefine Integer#+", begin + calls = [] + Integer.class_eval { alias_method :__sm_plus, :+; define_method(:+) { |o| calls << o if calls.size < 3 && o.is_a?(Integer); __sm_plus(o) } } + r = A.sum { |x| x } + Integer.class_eval { alias_method :+, :__sm_plus; remove_method :__sm_plus } + [r, calls.size > 0] +end +row "+ returning a Float", begin + Integer.class_eval { alias_method :__sm_plus2, :+; define_method(:+) { |o| o == 7 ? __sm_plus2(o).to_f : __sm_plus2(o) } } + r = A.sum { |x| x } + Integer.class_eval { alias_method :+, :__sm_plus2; remove_method :__sm_plus2 } + [r, r.class] +end +row "threads", 4.times.map { |t| Thread.new { s = 0; 200.times { s = A.sum { |x| x * t } }; s } }.map(&:value) +# last: a Bignum (an initial value or a sum) makes the copy of the Integer loop retire (its accumulator an object), and the rows after it would run +# only in the generic loop +row "init", [A.sum(10) { |x| x }, A.sum(2**70) { |x| x }, A.sum(0.5) { |x| x }, A.sum(1r / 3) { |x| x }, A.sum(1i) { |x| x }] +row "bignums", [hot { A.sum { |x| x * 2**60 } }, A.sum { |x| x == 50 ? 2**64 : x }, [2**62, 2**62, 2**62].sum { |x| x }] +puts "end" diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 860b44453..c663d79d4 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,31 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/yieldloop3 (2026-11-29) - Array#sum with a block: its Integer case in a loop of its own that the compiled copy + runs (gap 18)** - not gated. `__array_sum__`'s loop could not be compiled: its tail has `next`, `return`, calls and a + nested `while true` with a second yield. The common case, Integers all along, now has a loop of its own in front of it + (`x = yield(__ary_at__(i)); i = i.succ; break unless ::Integer === x && ::Integer === acc; acc = acc + x; j = i`): + it leaves at the first value that is not an Integer (or once acc is not one, as a redefined Integer#+ can make it), + and the general loop, unchanged otherwise, takes that value first (`pending`); `j == i` tells a run to the end. Two + things in the copy: `C === x` with C a constant module (`JitCompiler.EmitModuleCaseCompare`, `JitRuntime. + ModuleCaseCompare`: Module#=== as rb_obj_is_kind_of, under a KernelMethodSite on C's class resolving `===` to Module's; + outlined loops only - in typed method bodies it was measured to reach nothing hot, perf/jiteqq), and a bare `break` + in the statements after the yield (`YieldTailFinder`; the generic tail's break is inside the loop). + - Instructions (`count.sh`, base 50b2427 / new): `sum_blk` 3,191.9 / 1,709.0 (0.535); `take_while` 0.538 (round + two's), controls 1.000. Time (`ab.rb -r 10`, CRuby / base / new): `sum_blk` 19.6 / 89.1 / 47.6 (0.53). + - A Bignum (an initial value or a sum past Int64) makes the copy retire for the rest of the process (its accumulator + an object, which `acc + x` with both operands objects cannot take): those sums run in the generic loops, as before. + - Census: 0 methods changed, up or down. + - Checks: the new `Util/array-sum-matrix.rb` (Integers; Floats, Rationals, Complex, nil, Strings, objects arriving in + the middle; NaN and infinities; break, raise, next; an Array mutated by the block; a subclass; Integer#+ + redefined; threads; Bignums and initial values last, since they retire the copy) and yield-loop, block-loop, + osr-array, jit, jit-calls, parked-iterator, hot-shapes and loop-ivar: CRuby's output in the six gate modes and with + `IR_OSR_YIELD=0`, except two rows of the sum matrix that differ from CRuby on base too (CRuby's Array#sum does not + call a redefined Integer#+, the prelude's does: `acc = acc + x`, in both loops) - 55 same, 8 baseline. ruby/spec core + array and enumerable sum, take_while, drop_while and language yield, break, while, next: 179 examples, none + failing, on both. IronRuby.Tests (Debug): the new OsrYieldLoop3 and 114 named tests pass with the switch on and off; + the whole suite was not run (the session's permission check refuses it). + - **perf/yieldloop2 (2026-11-29) - the prelude's `take_while` and `drop_while` run in their loops' compiled copies (gap 18, stage 3a's own measure)** - not gated. Stage 3a's design names its measure as the prelude's `while ... yield` methods, which round one did not reach. Of the prelude's 16 loops with one yield, 6 have it as a statement, 3 as a From b4fc1b68cab7044e997004cf029f57a89ff3db85 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:53:46 +0000 Subject: [PATCH 365/439] Kernel#warn with Warning#warn undefined raises NoMethodError Kernel#warn asked ::Warning.method(:warn) for its arity before calling it, so with Warning.undef_method(:warn) the warning failed with NameError ("undefined method 'warn' for class 'Module'"). MRI just calls the method (rb_warning_warn) and fails with NoMethodError ("undefined method 'warn' for module Warning"). The arity is now only asked of a method that is there, and the call does the failing. Checked against CRuby 4.0.10: TestException#test_undef_Warning_warn passes; ruby/spec core/kernel/warn and core/warning unchanged. New IronRuby.Tests: Warning_UndefinedWarn1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 19 +++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 4 +++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 25d925dce..35094eae1 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1029,6 +1029,7 @@ public Tests(Driver/*!*/ driver) { Pack_FloatOfNonNumeric1, Unpack_AtEnd1, String_UndumpUnknownEscapes1, + Warning_UndefinedWarn1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 2ba9e6c9c..5d5640e7c 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10143,6 +10143,25 @@ public void String_UndumpUnknownEscapes1() { ""#"" ""\"""" true +"); + } + + /// + /// With Warning#warn undefined, Kernel#warn fails as MRI's call to it does, with NoMethodError, rather than a + /// NameError from asking for the method first (CRuby's TestException#test_undef_Warning_warn). + /// + public void Warning_UndefinedWarn1() { + TestOutput(@" +require 'ruby4' +Warning.undef_method(:warn) +begin + warn ""x"" +rescue NoMethodError => e + p e.class, e.message +end +", @" +NoMethodError +""undefined method 'warn' for module Warning"" "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index aa2a8d54d..7efd66659 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3620,7 +3620,9 @@ def warn(*messages, uplevel: nil, category: nil) end # rb_warning_warn_arity: an override that takes exactly one argument gets no keywords. - if ::Warning.method(:warn).arity == 1 + # With Warning#warn undefined MRI's call is what fails, with a NoMethodError, so the + # arity is only asked of a method that is there. + if ::Warning.respond_to?(:warn, true) && ::Warning.method(:warn).arity == 1 ::Warning.warn(text) else ::Warning.warn(text, category: category) From 017a8ee9d7aff0be353671ba908118c6d2e833b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:53:46 +0000 Subject: [PATCH 366/439] Warning[], Warning[]= and Warning.categories are singleton methods only They were registered as instance methods of Warning too, so Warning.instance_methods(false) listed them and an object extended with Warning answered them. MRI defines them with rb_define_singleton_method; only #warn is an instance method, for a module that extends Warning to override it. Checked against CRuby 4.0.10; ruby/spec core/warning unchanged. New IronRuby.Tests: Warning_InstanceMethods1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 22 ++++++++++++++++++++++ Src/Libraries/Builtins/WarningOps.cs | 5 ++--- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 35094eae1..bc746bbce 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1030,6 +1030,7 @@ public Tests(Driver/*!*/ driver) { Unpack_AtEnd1, String_UndumpUnknownEscapes1, Warning_UndefinedWarn1, + Warning_InstanceMethods1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 5d5640e7c..f5d4ec2fc 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10162,6 +10162,28 @@ public void Warning_UndefinedWarn1() { ", @" NoMethodError ""undefined method 'warn' for module Warning"" +"); + } + + /// + /// Warning[], Warning[]= and Warning.categories are singleton methods only: #warn is the one instance method, + /// for a module that extends Warning to override. + /// + public void Warning_InstanceMethods1() { + TestOutput(@" +require 'ruby4' +p Warning.instance_methods(false), Warning.singleton_methods.sort +o = Object.new.extend(Warning) +p o.respond_to?(:warn), o.respond_to?(:categories), o.respond_to?(:[]) +p [true, false].include?(Warning[:deprecated]), Warning.categories.include?(:experimental) +", @" +[:warn] +[:[], :[]=, :categories, :warn] +true +false +false +true +true "); } } diff --git a/Src/Libraries/Builtins/WarningOps.cs b/Src/Libraries/Builtins/WarningOps.cs index a27753407..02b7ff857 100644 --- a/Src/Libraries/Builtins/WarningOps.cs +++ b/Src/Libraries/Builtins/WarningOps.cs @@ -33,21 +33,20 @@ namespace IronRuby.Builtins { [RubyModule("Warning")] public static class WarningOps { + // Warning[], Warning[]= and Warning.categories are the module's own (rb_define_singleton_method): + // only #warn is an instance method, for a module that extends Warning to override. [RubyMethod("[]", RubyMethodAttributes.PublicSingleton)] - [RubyMethod("[]", RubyMethodAttributes.PublicInstance)] public static bool GetCategory(RubyContext/*!*/ context, object self, [NotNull]RubySymbol/*!*/ category) { return context.IsWarningEnabled(CheckCategory(category)); } [RubyMethod("[]=", RubyMethodAttributes.PublicSingleton)] - [RubyMethod("[]=", RubyMethodAttributes.PublicInstance)] public static object SetCategory(RubyContext/*!*/ context, object self, [NotNull]RubySymbol/*!*/ category, object flag) { context.SetWarningEnabled(CheckCategory(category), RubyOps.IsTrue(flag)); return flag; } [RubyMethod("categories", RubyMethodAttributes.PublicSingleton)] - [RubyMethod("categories", RubyMethodAttributes.PublicInstance)] public static RubyArray/*!*/ GetCategories(RubyContext/*!*/ context, object self) { var result = new RubyArray(RubyContext.WarningCategories.Length); foreach (string category in RubyContext.WarningCategories) { From 89562fc1c39431188dc07d9462e0e8a0ba416641 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:53:46 +0000 Subject: [PATCH 367/439] Add Encoding::UNICODE_VERSION The standard library's unicode_normalize/normalize and tables check their tables against Encoding::UNICODE_VERSION, which IronRuby did not define, so requiring them failed with NameError. It is now the version of the Unicode data IronRuby's own character tables come from (UnicodeProperties.UnicodeVersion, "17.0.0", as CRuby 4.0's), a frozen US-ASCII String as in MRI. Checked against CRuby 4.0.10: TestRequireLib's unicode_normalize/normalize and unicode_normalize/tables cases pass; ruby/spec core/encoding unchanged. New IronRuby.Tests: Encoding_UnicodeVersion1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 14 ++++++++++++++ Src/Libraries/Builtins/RubyEncodingOps.cs | 3 +++ Src/Ruby/Builtins/RubyEncoding.cs | 9 +++++++++ 4 files changed, 27 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index bc746bbce..ca3e10102 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1031,6 +1031,7 @@ public Tests(Driver/*!*/ driver) { String_UndumpUnknownEscapes1, Warning_UndefinedWarn1, Warning_InstanceMethods1, + Encoding_UnicodeVersion1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index f5d4ec2fc..fec374664 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10184,6 +10184,20 @@ p Warning.instance_methods(false), Warning.singleton_methods.sort false true true +"); + } + + /// + /// Encoding::UNICODE_VERSION, which the standard library's unicode_normalize checks its tables against + /// (CRuby's TestRequireLib for unicode_normalize/normalize and tables). + /// + public void Encoding_UnicodeVersion1() { + TestOutput(@" +p Encoding::UNICODE_VERSION, Encoding::UNICODE_VERSION.frozen?, Encoding::UNICODE_VERSION.encoding +", @" +""17.0.0"" +true +# "); } } diff --git a/Src/Libraries/Builtins/RubyEncodingOps.cs b/Src/Libraries/Builtins/RubyEncodingOps.cs index d911549e7..97dd48053 100644 --- a/Src/Libraries/Builtins/RubyEncodingOps.cs +++ b/Src/Libraries/Builtins/RubyEncodingOps.cs @@ -129,6 +129,9 @@ public static class ConverterNotFoundErrorOps { /// form); plus an all upper case form whenever the name has a lower case letter. A name that /// starts with a digit ("646") makes no constant. /// + [RubyConstant("UNICODE_VERSION")] + public static readonly MutableString/*!*/ UnicodeVersion = MutableString.CreateAscii(RubyEncoding.UnicodeVersion).Freeze(); + [RubyConstant("UTF_8")] public static RubyEncoding/*!*/ DefineConstants(RubyModule/*!*/ module) { foreach (var name in RubyEncoding.GetAllNames()) { diff --git a/Src/Ruby/Builtins/RubyEncoding.cs b/Src/Ruby/Builtins/RubyEncoding.cs index 7a0704012..aa71d658c 100644 --- a/Src/Ruby/Builtins/RubyEncoding.cs +++ b/Src/Ruby/Builtins/RubyEncoding.cs @@ -418,6 +418,15 @@ public static RubyEncoding FindByName(string/*!*/ name) { } /// Every name and alias, in MRI's order (Encoding.name_list). + /// + /// The version of Unicode the character tables (UnicodeProperties) come from: MRI's + /// Encoding::UNICODE_VERSION, which the standard library's unicode_normalize checks its + /// own tables against. + /// + public static string/*!*/ UnicodeVersion { + get { return UnicodeProperties.UnicodeVersion; } + } + public static IEnumerable/*!*/ GetAllNames() { foreach (var entry in _names) { yield return entry.Name; From cd1f471cba8c74e6c73ffc7800a6d07ee96c0171 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:53:46 +0000 Subject: [PATCH 368/439] Shims for MRI's transcoder libraries, enc/trans/* MRI builds its transcoders as loadable libraries (enc/trans/single_byte.so and twenty others), and code that wants one before its first use requires it by name: CRuby's TestRequire#prepare_require_path does require 'enc/trans/single_byte', so the non-ASCII path tests failed with LoadError before they started. IronRuby's transcoders are built in; each name now has a shim in Src/StdLib/ironruby/enc/trans that has nothing to do. Checked against CRuby 4.0.10: require 'enc/trans/single_byte' answers true and then false, as in MRI. New IronRuby.Tests: Require_EncTransShims1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/LoaderTests.cs | 16 ++++++++++++++++ Src/StdLib/ironruby/enc/trans/big5.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/cesu_8.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/chinese.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/ebcdic.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/emoji.rb | 5 +++++ .../ironruby/enc/trans/emoji_iso2022_kddi.rb | 5 +++++ .../ironruby/enc/trans/emoji_sjis_docomo.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/emoji_sjis_kddi.rb | 5 +++++ .../ironruby/enc/trans/emoji_sjis_softbank.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/escape.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/gb18030.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/gbk.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/iso2022.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/japanese.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/japanese_euc.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/japanese_sjis.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/korean.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/single_byte.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/transdb.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/utf8_mac.rb | 5 +++++ Src/StdLib/ironruby/enc/trans/utf_16_32.rb | 5 +++++ 23 files changed, 122 insertions(+) create mode 100644 Src/StdLib/ironruby/enc/trans/big5.rb create mode 100644 Src/StdLib/ironruby/enc/trans/cesu_8.rb create mode 100644 Src/StdLib/ironruby/enc/trans/chinese.rb create mode 100644 Src/StdLib/ironruby/enc/trans/ebcdic.rb create mode 100644 Src/StdLib/ironruby/enc/trans/emoji.rb create mode 100644 Src/StdLib/ironruby/enc/trans/emoji_iso2022_kddi.rb create mode 100644 Src/StdLib/ironruby/enc/trans/emoji_sjis_docomo.rb create mode 100644 Src/StdLib/ironruby/enc/trans/emoji_sjis_kddi.rb create mode 100644 Src/StdLib/ironruby/enc/trans/emoji_sjis_softbank.rb create mode 100644 Src/StdLib/ironruby/enc/trans/escape.rb create mode 100644 Src/StdLib/ironruby/enc/trans/gb18030.rb create mode 100644 Src/StdLib/ironruby/enc/trans/gbk.rb create mode 100644 Src/StdLib/ironruby/enc/trans/iso2022.rb create mode 100644 Src/StdLib/ironruby/enc/trans/japanese.rb create mode 100644 Src/StdLib/ironruby/enc/trans/japanese_euc.rb create mode 100644 Src/StdLib/ironruby/enc/trans/japanese_sjis.rb create mode 100644 Src/StdLib/ironruby/enc/trans/korean.rb create mode 100644 Src/StdLib/ironruby/enc/trans/single_byte.rb create mode 100644 Src/StdLib/ironruby/enc/trans/transdb.rb create mode 100644 Src/StdLib/ironruby/enc/trans/utf8_mac.rb create mode 100644 Src/StdLib/ironruby/enc/trans/utf_16_32.rb diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ca3e10102..6d7ec67dc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -566,6 +566,7 @@ public Tests(Driver/*!*/ driver) { Require_PathLoadedDependency6, Require_UnreadableExtensions1, Require_UnreadableExtensions2, + Require_EncTransShims1, CaseEquals1, CaseEquals2, CaseEquals3, diff --git a/Src/IronRuby.Tests/Runtime/LoaderTests.cs b/Src/IronRuby.Tests/Runtime/LoaderTests.cs index 79b7b4320..5dfa357ee 100644 --- a/Src/IronRuby.Tests/Runtime/LoaderTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoaderTests.cs @@ -519,5 +519,21 @@ private static void WriteFixtureAssembly(string/*!*/ dir, string/*!*/ name, stri } #endregion + + /// + /// MRI's transcoders are libraries that code may require by name (enc/trans/single_byte); IronRuby's are built + /// in, and requiring one loads a shim that has nothing to do (CRuby's TestRequire#prepare_require_path). + /// + public void Require_EncTransShims1() { + TestOutput(@" +p require(""enc/trans/single_byte""), require(""enc/trans/single_byte""), require(""enc/trans/japanese"") +p (+""\xA4\xA2"").force_encoding(""EUC-JP"").encode(""UTF-8"") == ""あ"" +", @" +true +false +true +true +"); + } } } diff --git a/Src/StdLib/ironruby/enc/trans/big5.rb b/Src/StdLib/ironruby/enc/trans/big5.rb new file mode 100644 index 000000000..431f55175 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/big5.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/big5.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/cesu_8.rb b/Src/StdLib/ironruby/enc/trans/cesu_8.rb new file mode 100644 index 000000000..e914870c9 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/cesu_8.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/cesu_8.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/chinese.rb b/Src/StdLib/ironruby/enc/trans/chinese.rb new file mode 100644 index 000000000..328f7ccc7 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/chinese.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/chinese.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/ebcdic.rb b/Src/StdLib/ironruby/enc/trans/ebcdic.rb new file mode 100644 index 000000000..d5116de79 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/ebcdic.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/ebcdic.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/emoji.rb b/Src/StdLib/ironruby/enc/trans/emoji.rb new file mode 100644 index 000000000..f1be81ed1 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/emoji.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/emoji.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/emoji_iso2022_kddi.rb b/Src/StdLib/ironruby/enc/trans/emoji_iso2022_kddi.rb new file mode 100644 index 000000000..abc9198a6 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/emoji_iso2022_kddi.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/emoji_iso2022_kddi.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/emoji_sjis_docomo.rb b/Src/StdLib/ironruby/enc/trans/emoji_sjis_docomo.rb new file mode 100644 index 000000000..456d4cc6f --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/emoji_sjis_docomo.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/emoji_sjis_docomo.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/emoji_sjis_kddi.rb b/Src/StdLib/ironruby/enc/trans/emoji_sjis_kddi.rb new file mode 100644 index 000000000..0c884feae --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/emoji_sjis_kddi.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/emoji_sjis_kddi.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/emoji_sjis_softbank.rb b/Src/StdLib/ironruby/enc/trans/emoji_sjis_softbank.rb new file mode 100644 index 000000000..17eb71019 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/emoji_sjis_softbank.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/emoji_sjis_softbank.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/escape.rb b/Src/StdLib/ironruby/enc/trans/escape.rb new file mode 100644 index 000000000..23a025070 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/escape.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/escape.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/gb18030.rb b/Src/StdLib/ironruby/enc/trans/gb18030.rb new file mode 100644 index 000000000..9f9a4e33b --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/gb18030.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/gb18030.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/gbk.rb b/Src/StdLib/ironruby/enc/trans/gbk.rb new file mode 100644 index 000000000..df04b3ffe --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/gbk.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/gbk.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/iso2022.rb b/Src/StdLib/ironruby/enc/trans/iso2022.rb new file mode 100644 index 000000000..ac056f575 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/iso2022.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/iso2022.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/japanese.rb b/Src/StdLib/ironruby/enc/trans/japanese.rb new file mode 100644 index 000000000..0c5911455 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/japanese.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/japanese.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/japanese_euc.rb b/Src/StdLib/ironruby/enc/trans/japanese_euc.rb new file mode 100644 index 000000000..81c90a395 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/japanese_euc.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/japanese_euc.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/japanese_sjis.rb b/Src/StdLib/ironruby/enc/trans/japanese_sjis.rb new file mode 100644 index 000000000..003d84971 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/japanese_sjis.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/japanese_sjis.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/korean.rb b/Src/StdLib/ironruby/enc/trans/korean.rb new file mode 100644 index 000000000..75964bd24 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/korean.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/korean.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/single_byte.rb b/Src/StdLib/ironruby/enc/trans/single_byte.rb new file mode 100644 index 000000000..7fc30a0c9 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/single_byte.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/single_byte.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/transdb.rb b/Src/StdLib/ironruby/enc/trans/transdb.rb new file mode 100644 index 000000000..23df4fc62 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/transdb.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/transdb.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/utf8_mac.rb b/Src/StdLib/ironruby/enc/trans/utf8_mac.rb new file mode 100644 index 000000000..d45dbd70d --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/utf8_mac.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/utf8_mac.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. diff --git a/Src/StdLib/ironruby/enc/trans/utf_16_32.rb b/Src/StdLib/ironruby/enc/trans/utf_16_32.rb new file mode 100644 index 000000000..f0e41bda7 --- /dev/null +++ b/Src/StdLib/ironruby/enc/trans/utf_16_32.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +# MRI builds its transcoders as loadable libraries, enc/trans/utf_16_32.so among them, and code +# that needs one before its first use requires it by name (CRuby's test_require does +# require 'enc/trans/single_byte'). IronRuby's transcoders are built in and always there, +# so loading this one has nothing left to do. From e0e94e7af950cc28eb330f679b8fd3431cea60cd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:53:46 +0000 Subject: [PATCH 369/439] A file required by a non-ASCII path is loaded once under a US-ASCII filesystem encoding Loader.AnyFileLoaded compared the entries of $" with the paths it tested as Strings. A non-ASCII path a program required by its UTF-8 name is in $" as UTF-8, while the tested path is encoded in the filesystem encoding, US-ASCII under LANG=C: the same bytes in encodings that do not compare equal, so every require of the file loaded it again. MRI's rb_feature_p compares the bytes; so does this now when the encodings differ. Checked against CRuby 4.0.10: TestRequire#test_require_nonascii_path_utf8 passes (test_require_nonascii_path_shift_jis now gets as far as __FILE__'s encoding, which follows the required path's in MRI and not here yet); ruby/spec core/kernel/require, load and require_relative unchanged. New IronRuby.Tests: Require_NonAsciiFeatureBytes1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/LoaderTests.cs | 25 +++++++++++++++++++++++ Src/Ruby/Runtime/Loader.cs | 16 ++++++++++++++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 6d7ec67dc..262b88730 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -567,6 +567,7 @@ public Tests(Driver/*!*/ driver) { Require_UnreadableExtensions1, Require_UnreadableExtensions2, Require_EncTransShims1, + Require_NonAsciiFeatureBytes1, CaseEquals1, CaseEquals2, CaseEquals3, diff --git a/Src/IronRuby.Tests/Runtime/LoaderTests.cs b/Src/IronRuby.Tests/Runtime/LoaderTests.cs index 5dfa357ee..290911e19 100644 --- a/Src/IronRuby.Tests/Runtime/LoaderTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoaderTests.cs @@ -533,6 +533,31 @@ p require(""enc/trans/single_byte""), require(""enc/trans/single_byte""), requir false true true +"); + } + + /// + /// A feature is loaded once, whatever the encoding of the path it was required by: MRI compares the bytes, and a + /// non-ASCII path in $" (UTF-8) and the one tested (the filesystem encoding, US-ASCII under LANG=C) did not compare + /// equal as Strings (CRuby's TestRequire#test_require_nonascii_path_utf8). + /// + public void Require_NonAsciiFeatureBytes1() { + TestOutput(@" +require 'ruby4' +require ""tmpdir"" +$feature_loads = 0 +Dir.mktmpdir do |tmp| + dir = File.join(tmp, ""あい"") + Dir.mkdir(dir) + path = File.join(dir, ""feature.rb"") + File.write(path, ""$feature_loads += 1\n"") + p require(path), require(path.encode(""UTF-8"").b.force_encoding(""US-ASCII"")), require(path), $feature_loads +end +", @" +true +false +false +1 "); } } diff --git a/Src/Ruby/Runtime/Loader.cs b/Src/Ruby/Runtime/Loader.cs index 4de7a2dc7..0dd70aab8 100644 --- a/Src/Ruby/Runtime/Loader.cs +++ b/Src/Ruby/Runtime/Loader.cs @@ -1544,6 +1544,20 @@ private bool AlreadyLoaded(string/*!*/ path, IEnumerable/*!*/ file ); } + /// + /// MRI's rb_feature_p compares the bytes of the paths. A non-ASCII path a program required + /// by its UTF-8 name is in $" as UTF-8, while the path tested here is in the filesystem + /// encoding, which is US-ASCII under LANG=C: the same bytes in two encodings that do not + /// compare equal as Strings, and the file was loaded again by every require of it. + /// + private static bool SameFeaturePath(MutableString/*!*/ loaded, MutableString/*!*/ path) { + if (loaded.Equals(path)) { + return true; + } + return loaded.Encoding != path.Encoding && loaded.GetByteCount() == path.GetByteCount() + && loaded.ToByteArray().AsSpan().SequenceEqual(path.ToByteArray()); + } + private bool AnyFileLoaded(IEnumerable/*!*/ paths) { var toPath = _toStrStorage.GetSite(CompositeConversionAction.Make(_context, CompositeConversion.ToPathToStr)); @@ -1554,7 +1568,7 @@ private bool AnyFileLoaded(IEnumerable/*!*/ paths) { // use case sensitive comparison MutableString loadedPath = Protocols.CastToPath(toPath, file); - if (paths.Any((path) => loadedPath.Equals(path))) { + if (paths.Any((path) => SameFeaturePath(loadedPath, path))) { return true; } } From 44e950e7ca44c9b0e726b97a897928bd05386d95 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:53:46 +0000 Subject: [PATCH 370/439] main.public and main.private in a wrapped load work on the wrapper module In load(file, true) the file's top-level defs go to the wrapper module, but main.public and main.private still looked the names up in Object, so 'def foo; end; private :foo' in such a file raised NameError. MRI's rb_top_main_class answers the wrapper module there (and warns under -w, "main.private in the wrapped load is effective only in wrapper module"); these now do the same. Checked against CRuby 4.0.10: TestRequire#test_private_in_wrapped_load and #test_public_in_wrapped_load pass; ruby/spec core/main and core/kernel/load unchanged. New IronRuby.Tests: Load_WrappedMainVisibility1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/LoaderTests.cs | 25 +++++++++++++++++++++++ Src/Libraries/Builtins/SingletonOps.cs | 16 ++++++++++++--- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 262b88730..42289274c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -568,6 +568,7 @@ public Tests(Driver/*!*/ driver) { Require_UnreadableExtensions2, Require_EncTransShims1, Require_NonAsciiFeatureBytes1, + Load_WrappedMainVisibility1, CaseEquals1, CaseEquals2, CaseEquals3, diff --git a/Src/IronRuby.Tests/Runtime/LoaderTests.cs b/Src/IronRuby.Tests/Runtime/LoaderTests.cs index 290911e19..03e22e2ff 100644 --- a/Src/IronRuby.Tests/Runtime/LoaderTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoaderTests.cs @@ -558,6 +558,31 @@ p require(path), require(path.encode(""UTF-8"").b.force_encoding(""US-ASCII"")), false false 1 +"); + } + + /// + /// main.public and main.private in a wrapped load work on the wrapper module, where the file's methods went, as + /// MRI's rb_top_main_class has it, rather than on Object (CRuby's TestRequire#test_private_in_wrapped_load). + /// + public void Load_WrappedMainVisibility1() { + TestOutput(@" +require 'ruby4' +require ""tempfile"" +Tempfile.create([""wrapped"", "".rb""]) do |t| + t.puts ""def foo_in_wrap; end"", ""private :foo_in_wrap"", ""public :foo_in_wrap"", ""$wrap_main = self"" + t.close + verbose, $VERBOSE = $VERBOSE, false + p load(t.path, true) + $VERBOSE = verbose + p Object.method_defined?(:foo_in_wrap), Object.private_method_defined?(:foo_in_wrap) + p $wrap_main.singleton_class.method_defined?(:foo_in_wrap) +end +", @" +true +false +false +true "); } } diff --git a/Src/Libraries/Builtins/SingletonOps.cs b/Src/Libraries/Builtins/SingletonOps.cs index 01d999508..a4c56cbf6 100644 --- a/Src/Libraries/Builtins/SingletonOps.cs +++ b/Src/Libraries/Builtins/SingletonOps.cs @@ -52,7 +52,7 @@ public static class MainSingletonOps { public static object SetPublicVisibility(ConversionStorage/*!*/ stringCast, RubyScope/*!*/ scope, object/*!*/ self, params object[]/*!*/ methodNames) { - SetVisibility(scope, self, ModuleOps.ToMethodNames(stringCast, methodNames), RubyMethodAttributes.PublicInstance); + SetVisibility(scope, self, ModuleOps.ToMethodNames(stringCast, methodNames), RubyMethodAttributes.PublicInstance, "public"); return ModuleOps.VisibilityResult(methodNames); } @@ -61,13 +61,23 @@ public static object SetPublicVisibility(ConversionStorage/*!*/ stringCa public static object SetPrivateVisibility(ConversionStorage/*!*/ stringCast, RubyScope/*!*/ scope, object/*!*/ self, params object[]/*!*/ methodNames) { - SetVisibility(scope, self, ModuleOps.ToMethodNames(stringCast, methodNames), RubyMethodAttributes.PrivateInstance); + SetVisibility(scope, self, ModuleOps.ToMethodNames(stringCast, methodNames), RubyMethodAttributes.PrivateInstance, "private"); return ModuleOps.VisibilityResult(methodNames); } - private static RubyModule/*!*/ SetVisibility(RubyScope/*!*/ scope, object/*!*/ self, string/*!*/[]/*!*/ methodNames, RubyMethodAttributes attributes) { + private static RubyModule/*!*/ SetVisibility(RubyScope/*!*/ scope, object/*!*/ self, string/*!*/[]/*!*/ methodNames, + RubyMethodAttributes attributes, string/*!*/ methodName) { Assert.NotNull(scope, self, methodNames); + // In a wrapped load (load(file, true)) MRI's rb_top_main_class answers the wrapper module, where + // the file's top-level `def's went, rather than Object, and says so under -w. + RubyModule wrapper = scope.Top.Module; + if (wrapper != null && scope.Top.Kind == ScopeKind.TopLevel) { + scope.RubyContext.ReportWarning("main." + methodName + " in the wrapped load is effective only in wrapper module", true); + ModuleOps.SetMethodAttributes(scope, wrapper, methodNames, attributes); + return wrapper; + } + // MRI: Method is searched in the class of self (Object), not in the main singleton class. // IronRuby specific: If we are in a top-level scope with redirected method lookup module we use that module (hosted scopes). RubyModule mirror; From d00ccaf5dcf4d37d9bde9e38a88c3a3c695b95ad Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:53:57 +0000 Subject: [PATCH 371/439] cruby-test: baseline after round six test_exception, test_require, test_require_lib, test_encoding, test_warning, test_m17n and test_io_m17n swept again on top of round five's baseline: 6,671 passing, 67 files clean. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 4 ++-- Util/cruby-test/baseline.txt | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index 5af9e934c..ae21e1ab5 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby -Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 66 clean, 75 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,665 passing. (The first sweep, of v4.0.9: +Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 67 clean, 74 with +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,671 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index fba8e3e89..4f5fb6209 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -36,7 +36,7 @@ test_enum 90 tests 2 failures 0 errors 0 sk test_enumerator 70 tests 0 failures 0 errors 0 skips test_env 94 tests 7 failures 0 errors 1 skips test_eval 40 tests 3 failures 0 errors 0 skips -test_exception 101 tests 14 failures 1 errors 0 skips +test_exception 101 tests 13 failures 1 errors 0 skips test_fiber 35 tests 2 failures 0 errors 2 skips test_file 80 tests 0 failures 23 errors 1 skips test_file_exhaustive 125 tests 0 failures 0 errors 1 skips @@ -100,8 +100,8 @@ test_rational2 1 tests 0 failures 0 errors 0 sk test_readpartial 4 tests 1 failures 0 errors 0 skips test_refinement 122 tests 6 failures 2 errors 0 skips test_regexp 167 tests 29 failures 8 errors 0 skips -test_require 52 tests 9 failures 10 errors 0 skips -test_require_lib 39 tests 0 failures 2 errors 0 skips +test_require 52 tests 10 failures 5 errors 1 skips +test_require_lib 39 tests 0 failures 0 errors 0 skips test_rubyoptions 68 tests 51 failures 1 errors 0 skips test_rubyvm 3 tests 1 failures 2 errors 0 skips test_set 63 tests 0 failures 0 errors 2 skips @@ -141,5 +141,5 @@ test_yjit 0 tests 0 failures 0 errors 0 sk test_yjit_exit_locations 0 tests 0 failures 0 errors 0 skips test_zjit 0 tests 0 failures 0 errors 0 skips -142 files: 66 clean, 75 with failures, 1 without a summary -10369 tests, 2552101 assertions, 497 failures, 3138 errors, 69 skips; 6665 passing +142 files: 67 clean, 74 with failures, 1 without a summary +10369 tests, 2552117 assertions, 497 failures, 3131 errors, 70 skips; 6671 passing From 5dea321fc5b0a095aa579a3e4238b377fb6e6063 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:58:19 +0000 Subject: [PATCH 372/439] A literal block a typed body ignored is left reusable The method JIT's typed body for a method that never uses its block ignores the block it is called with, where the generic body's light frame converts a literal one and leaves it reusable. The literal stayed a plain block nothing had converted, which StageParkedProc must treat as possibly kept (a define_method body taking &b gets one unconverted), so a caller like `nb { }` never parked: after 64 failures its slot gave up and every call made a scope and a Proc. The JIT stub's entry now marks such a literal after the typed body returns (JitRuntime.IgnoredBlock, Proc.MarkIgnored), as the light frame would have left it. IR_IGNORED_BLOCKS=0 restores the old code. nbl now parks: 12 GCs in 3,000,000 calls become 2. Time is level (ab.rb -r 6: 121.7 / 121.3 ns, parking off 119.6), and the census is unchanged. Checked: twelve block and JIT matrices in every mode and with the switch off (84 same); a probe of a literal to a method that ignores it, then keeps it, then deopts, against CRuby with the JIT on and off; ruby/spec language in full; IronRuby.Tests on Debug (passed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Ruby/Builtins/Proc.cs | 16 ++++++++++++++++ Src/Ruby/Runtime/Jit/JitRuntime.cs | 12 ++++++++++++ Src/Ruby/Runtime/Jit/JitStub.cs | 12 ++++++++++++ Util/perf/LEDGER.md | 18 ++++++++++++++++++ 4 files changed, 58 insertions(+) diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index 2b7b7b96c..bd09da7d6 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -154,6 +154,22 @@ internal void ConvertAsLightFrame() { _activeFlowControlScope = this; } + /// + /// A literal block given to a method whose typed body ignored it and has returned (JitRuntime.IgnoredBlock): what + /// ConvertAsLightFrame and the light frame's exit (LeaveMethodFrame) leave, without the frame - nothing ran it, so no scope + /// it ran in was captured, and nothing holds it but the frame that made it. + /// + internal void MarkIgnored() { + if (IgnoredBlocksEnabled) { + _kind = ((_dispatcher.ReusesProc && TracePoint.ActiveEvents == 0) + ? (int)ProcKind.Proc | SelfConverterFlag | ReusableFlag + : (int)ProcKind.Proc | SelfConverterFlag) | (_kind & HeldFlag); + } + } + + /// IR_IGNORED_BLOCKS=0: a literal block a typed body ignored stays unconverted, not reusable, as it was. + internal static readonly bool IgnoredBlocksEnabled = Environment.GetEnvironmentVariable("IR_IGNORED_BLOCKS") != "0"; + /// /// ConvertAsFrame of a literal block for a light-frame method that names it (`def m(&b)'): see MethodConverterFlag. /// diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 7f014e65c..5ebe03a4a 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1368,6 +1368,18 @@ public static object NewSymbolHash3(RubyContext/*!*/ context, object key1, objec return result; } + /// + /// The block of a call whose typed body returned, for a method that never uses its block (JitStub: the body ignored it): + /// a literal one is marked as the generic body's light frame would have left it (Proc.MarkIgnored), so that the caller + /// may make it again and park its scope with it (perf/ignoredblock). Without this the literal stayed a plain block nothing + /// had converted, which StageParkedProc cannot tell from one a callee kept: `nb { }' never parked. + /// + public static void IgnoredBlock(Proc block) { + if (block != null && block.Kind == ProcKind.Block) { + block.MarkIgnored(); + } + } + internal static MethodInfo/*!*/ M(string/*!*/ name) { return typeof(JitRuntime).GetMethod(name, BindingFlags.Public | BindingFlags.Static); } diff --git a/Src/Ruby/Runtime/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index a21cb7e20..012e8c3a3 100644 --- a/Src/Ruby/Runtime/Jit/JitStub.cs +++ b/Src/Ruby/Runtime/Jit/JitStub.cs @@ -1485,6 +1485,18 @@ private bool SelfCallResolvesHere(RubyClass/*!*/ cls, RefinementActivation/*!*/ ); } + // A method that never uses its block: the typed body ignores it, where the generic body's light frame converted a literal + // one and left it reusable. Marked so once the body has returned (JitRuntime.IgnoredBlock); a deopt that ran the generic + // body has converted it already, and one the stub declined (AssumesNoBlock) never gets here with a block. + if (!_ast.UsesBlock && _ast.Parameters.Block == null && !code.AssumesNoBlock) { + var value = Ast.Variable(typeof(object), "#value"); + fast = Ast.Block(typeof(object), new[] { value }, + Ast.Assign(value, fast), + Ast.Call(JitRuntime.M("IgnoredBlock"), blk), + value + ); + } + MSA.Expression body = (test != null) ? Ast.Condition(test, fast, GenericCall(self, blk, args), typeof(object)) : fast; if (keywordValues != null) { body = Ast.Block(typeof(object), keywordValues, body); diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1cf66b2d3..a237917c6 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,24 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/ignoredblock (round thirty-seven, 2026-11-29) - a literal block given to a method whose typed body ignored it is + left reusable (gap 13)** - allocation, not time; not gated. `nb { }` to `def nb; 1; end` never parked: the parked slot's + `StageParkedProc` found the literal a plain block nothing had converted (kind `Block`, no flags), since the method JIT's + typed body for a method that never uses its block ignores it, where the generic body's light frame converts it and leaves + it reusable (`ConvertAsLightFrame`, then the exit). After 64 such calls the slot gave up, and every call made a scope and a + Proc (parking on or off: 119-121 ns either way). An unconverted literal cannot simply count as unheld - a `define_method` + body taking `&b` gets one unconverted - so the JIT stub's entry marks it where it drops it: after the typed body returns, + `JitRuntime.IgnoredBlock` leaves a literal (kind `Block`) as the light frame would have (`Proc.MarkIgnored`: reusable if its + literal allows, inactive). A deopt that ran the generic body has converted it already; a body compiled for calls without a + block (`AssumesNoBlock`) is declined for calls with one. `IR_IGNORED_BLOCKS=0` is the old code. Measured: `nbl` now parks; + GCs in 3,000,000 calls 12 -> 2 (as parking off: 12); time level (`ab.rb -r 6`, off/on/parking off: 121.7/121.3/119.6; + `e1`, `nyl`, controls overlapping), so parking itself saves `nbl` no time - its 75 ns over `nb0` are elsewhere. Census + (Src/StdLib and Util/bench): no method changed. Checked: block-given, block-pass, block-scope-reuse and its race, + jit-blockparam, jit-calls, jit, light-entry, literal-block-light, parked-iterator, parked-scope and hot-shapes in the six + modes and with the switch off: PASS, 84 same; a probe of a literal to a method that ignores it 200,000 times, the method then + redefined to keep its block (each call's Proc its own), back, and a deopt: CRuby's output with the JIT on and off. ruby/spec + language in full: 2935 examples, the one known error (send_spec's `into`/`to`). IronRuby.Tests in full on Debug: PASSED. + - **Gate of 2026-11-28 for round 10 of round thirty-seven** (perf/crubydiff's eleventh to fifteenth rounds, and perf/towersink, the fix for the Towers lean round 9 left open): the branch `claude/happy-gauss-95wm2j` at 3781af6a against master c4719ea, Release net10.0, the composite R2R host on both, four cores: **PASS**, Towers From 3b7bd0cf75e54e81e3901fc2985a96996e5bb66a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:59:18 +0000 Subject: [PATCH 373/439] Ledger: round 11's gate, PASS; a hang in perf/datafilter fixed Round 11 of round thirty-seven (perf/crubydiff's rounds 16-20 and claude/cruby-test's first two rounds, at 892d1386 against master c4719ea) passed the gate: IronRuby.Tests 1,459 run, none failed; the matrices with only the two known DIFFs; a probe file for the round as CRuby under C.UTF-8 and LANG=C; ruby/spec's five suites with no unlisted failure; AWFY 12 at a geomean of 0.900 and 0.916; start-up at 0.83-0.98 of master's. claude/cruby-test found that a compiled ivar store on an Enumerator made its instance data without setting round 9's instance-data filter bit, so a later singleton method call spun under the class hierarchy lock. That is fixed in the round (41d9e6a). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1cf66b2d3..7da3b9dcc 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,37 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-29 for round 11 of round thirty-seven** (perf/crubydiff's sixteenth to twentieth rounds, and + claude/cruby-test's first two rounds - CRuby's own test/ruby, 6,614 -> 6,660 passing, with the fix for a hang in + perf/datafilter): the branch at 892d1386 against master c4719ea, Release net10.0, the composite R2R host on both, + four cores: **PASS**. Gated in a worktree of its own and pushed only after, so that the open PR's CI was not + restarted. + The finding: claude/cruby-test's 41d9e6a - a compiled `@ivar` store on an IRubyInstanceDataOwner (an Enumerator) + made its instance data without setting perf/datafilter's bit, so GetImmediateClassOf went on answering the CLR + class after a singleton class was attached and the call site spun under the class hierarchy lock (round 9's + perf/datafilter; `Object.new.to_enum { 1 }` with an ivar and then `def e.each` hung). The store sets the bit now; + Enumerator_SingletonAfterInstanceVariable1. + The merge itself: no conflict. ReflectionCache.Generated.cs is what ClassInitGenerator writes. No new switch, no + new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,459 tests, every one executed, none failed. + `gate-matrices.rb --all` in the six default modes: 1,149 same, 93 baseline, 12 DIFF, the two known ones + (regexp-binary-ctype as at round 8; string-race-matrix compared over five runs of each tree: rows not always ok + 108 -> 88, lost writes 103 -> 0; three rows failed only on the new build in these five runs, `index`, `rindex` + and `=~` against `slice!` of the front, which failed on master in each earlier round's five, 1 to 5 times). + A probe file for the round - Location's label, base_label and to_s encodings, __FILE__'s for the main program + and evals, a singleton class described by its module's #inspect, NoMethodError on one, SizedQueue's own methods + and a subclass, the owners of drop, one?, freeze and hash, IO::Buffer values, String#[]= after to_str shortened + the string, defined?((;x)), __method__ in a class body, eval of UTF-16 source, a frozen MatchData's copy - + prints CRuby's output under C.UTF-8 and LANG=C with the JIT on and off (master: 22 lines differ); and the hang's + reproducer returns. + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against round 10: 5 methods changed, none hot - IO::Buffer's rewrite moves three methods to a scope and + one to a light frame, and Location#to_s no longer compiles (its encodings take force_encoding). + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.900 and 0.916; none more + than 5% slower in both. micro-table in both orders: no line more than 5% slower in both. + Start-up on the composite R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 369 -> 363 and + 360 -> 347, `gem --version` 449 -> 443 and 454 -> 438, `gem list` 802 -> 695 and 819 -> 679, `require "irb"` + 856 -> 727 and 817 -> 726, irb 1+1 894 -> 807 and 954 -> 828: 0.83-0.98. - **Gate of 2026-11-28 for round 10 of round thirty-seven** (perf/crubydiff's eleventh to fifteenth rounds, and perf/towersink, the fix for the Towers lean round 9 left open): the branch `claude/happy-gauss-95wm2j` at 3781af6a against master c4719ea, Release net10.0, the composite R2R host on both, four cores: **PASS**, Towers @@ -4438,7 +4469,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's), its eleventh to fifteenth 2026-11-28 (round 10's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's), its eleventh to fifteenth 2026-11-28 (round 10's), its sixteenth to twentieth 2026-11-29 (round 11's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope From 67ac8ea28ccfdee27d4104cb974567c03ac3bc02 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:02:07 +0000 Subject: [PATCH 374/439] Method JIT: defined?(@x) in typed bodies `defined?(@x)` was refused by the method JIT's screen (118 methods, 36 by it alone, nearly all of them `defined?` of an instance variable). As a condition it is now JitRuntime.HasInstanceVariable, whether self has the variable, with no String made: what the generic body's boolean form does. As a value, which the prism bridge writes `defined?(@x).freeze`, it is the frozen String the generic body makes, or nil, while String#freeze and NilClass#freeze are the library's. The value is not read, so nothing deopts; a body that holds a write back is compiled storing it where it is. Not in an outlined loop. IR_JIT_DEFINED_IVAR=0 turns it off. A first version made the String in conditions too and was slower than the generic body with the variable set; the condition takes the test alone now. Util/bench/defined-shapes.rb: 64.4 -> 48.6 ns set, 65.1 -> 49.7 unset, the memo idiom 59.6 -> 54.2 (CRuby about 28). Census: 44 methods up (31 to compiles), none down. Util/jit-defined-matrix.rb (new) and the matrices it touches print CRuby's output in every JIT mode; language/defined and IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 62 ++++++++++++++++++ Src/Ruby/Runtime/Jit/JitRuntime.cs | 10 +++ Util/bench/defined-shapes.rb | 29 +++++++++ Util/jit-defined-matrix.rb | 98 +++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 35 +++++++++++ 5 files changed, 234 insertions(+) create mode 100644 Util/bench/defined-shapes.rb create mode 100644 Util/jit-defined-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 4dfbb3494..9ba853005 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1359,6 +1359,9 @@ protected override MSA.Expression VisitNew(MSA.NewExpression node) { var or = node as OrExpression; if (or != null) { return EmitAndOr(or.Left, or.Right, false, out type); } + var isDefined = node as IsDefinedExpression; + if (isDefined != null && IsDefinedInstanceVariable(isDefined)) { return EmitDefinedInstanceVariable(isDefined, out type); } + var ivar = node as InstanceVariable; if (ivar != null) { if (_loop != null && _ivarProfile == null) { throw Bail("instance variable in a loop entered without self"); } @@ -2526,6 +2529,13 @@ private static JT Unify(JT a, JT b) { } private MSA.Expression/*!*/ EmitCondition(RExpr/*!*/ node, out JT t) { + // `if defined?(@x)': the test alone, as the generic body's TransformReadBoolean makes it - no String + var isDefined = node as IsDefinedExpression; + if (isDefined != null && IsDefinedInstanceVariable(isDefined)) { + if (_loop != null) { throw Bail("defined?(@x) in an outlined loop"); } + t = JT.Bool; + return Ast.Call(JitRuntime.M("HasInstanceVariable"), Ast.Constant(_context), _self, Ast.Constant(((InstanceVariable)isDefined.Expression).Name)); + } // `a && b' / `a || b' tested for truth: only the truth of the operands matters var and = node as AndExpression; var or = node as OrExpression; @@ -2711,6 +2721,49 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { internal static readonly bool SinkBoxedBooleans = Environment.GetEnvironmentVariable("IR_JIT_SINK_BOXED") != "0"; internal static readonly bool ScreenRefusesCall = Environment.GetEnvironmentVariable("IR_JIT_SCREEN_CALL") != "0"; + // IR_JIT_DEFINED_IVAR=0 turns EmitDefinedInstanceVariable off + internal static readonly bool DefinedInstanceVariables = Environment.GetEnvironmentVariable("IR_JIT_DEFINED_IVAR") != "0"; + + /// `defined?(@x)'. + internal static bool IsDefinedInstanceVariable(IsDefinedExpression/*!*/ node) { + return DefinedInstanceVariables && node.Expression is InstanceVariable; + } + + /// `defined?(@x)' where its value is used: PrismAstBridge makes it `defined?(@x).freeze', CRuby's frozen String. + internal static bool IsFrozenDefinedInstanceVariable(MethodCall/*!*/ node) { + var isDefined = node.Target as IsDefinedExpression; + return isDefined != null && node.MethodName == "freeze" && node.Block == null && (node.Arguments == null || node.Arguments.IsEmpty) && + IsDefinedInstanceVariable(isDefined); + } + + /// + /// `defined?(@x)': whether self has the instance variable (JitRuntime.HasInstanceVariable, which reads what + /// RubyOps.IsDefinedInstanceVariable reads), and then the String the generic body makes for it, made as it makes it + /// (RubyOps.CreateMutableStringL of "instance-variable", binary), or nil. The variable's value is not read, so nothing + /// is converted or deopts. A body that holds a write of the variable back calls a helper the held writes do not + /// allow (JitCompiler.Sink.cs), and is compiled storing them where they are. Not in an outlined loop. + /// + private MSA.Expression/*!*/ EmitDefinedInstanceVariable(IsDefinedExpression/*!*/ node, out JT type) { + return EmitDefinedInstanceVariable(node, false, out type); + } + + // frozen: the `.freeze' the bridge adds (IsFrozenDefinedInstanceVariable), String#freeze and NilClass#freeze the library's + private MSA.Expression/*!*/ EmitDefinedInstanceVariable(IsDefinedExpression/*!*/ node, bool frozen, out JT type) { + if (_loop != null) { throw Bail("defined?(@x) in an outlined loop"); } + if (frozen && (!IsPlainLibraryMethod(KindClass(JitRuntime.KindString), "freeze") || !IsPublicBuiltin(_context.NilClass, "freeze"))) { + throw Bail("freeze is not the library's"); + } + var name = ((InstanceVariable)node.Expression).Name; + type = JT.Obj; + MSA.Expression str = Ast.Call(typeof(RubyOps).GetMethod("CreateMutableStringL"), Ast.Constant("instance-variable"), Ast.Constant(RubyEncoding.Binary)); + if (frozen) { str = Ast.Call(str, typeof(MutableString).GetMethod("Freeze", Type.EmptyTypes)); } + return Ast.Condition( + Ast.Call(JitRuntime.M("HasInstanceVariable"), Ast.Constant(_context), _self, Ast.Constant(name)), + Ast.Convert(str, typeof(object)), + Ast.Constant(null, typeof(object)), + typeof(object)); + } + // IR_JIT_CASE_EQ=0 turns EmitModuleCaseEquality off internal static readonly bool ModuleCaseEquality = Environment.GetEnvironmentVariable("IR_JIT_CASE_EQ") != "0"; @@ -2816,6 +2869,9 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { // `x.is_a?(C)', `kind_of?', `instance_of?' (EmitTypeTest) if (IsTypeTest(node)) { return EmitTypeTest(node, out type); } + // `defined?(@x)' as a value (EmitDefinedInstanceVariable) + if (IsFrozenDefinedInstanceVariable(node)) { return EmitDefinedInstanceVariable((IsDefinedExpression)node.Target, true, out type); } + // `C === x' (EmitModuleCaseEquality) if (IsModuleCaseEquality(node)) { return EmitModuleCaseEquality(node, out type); } @@ -4217,6 +4273,9 @@ private bool Walk(RExpr/*!*/ node) { return (v is int || v is long || v is double || v is bool || v == null) || No(node); } if (node is SymbolLiteral) { return true; } + // `defined?(@x)' (JitCompiler.EmitDefinedInstanceVariable) + var isDefined = node as IsDefinedExpression; + if (isDefined != null) { return JitCompiler.IsDefinedInstanceVariable(isDefined) || No(node); } // a String literal is any other object (JitCompiler.EmitStringLiteral), never an operand (WalkOperand) if (node is StringLiteral) { return _inOperand == 0 || No(node); } // and so is an interpolated String (JitCompiler.EmitInterpolation), whose parts are any values @@ -4555,6 +4614,9 @@ private bool WalkCall(MethodCall/*!*/ node) { return WalkCondition(node.Target); } + // `defined?(@x)' as a value: `defined?(@x).freeze' (JitCompiler.EmitDefinedInstanceVariable) + if (JitCompiler.IsFrozenDefinedInstanceVariable(node)) { return true; } + if (JitCompiler.IsModuleCaseEquality(node)) { // `C === x' (JitCompiler.EmitModuleCaseEquality): C a constant, x any object return (WalkConstant((ConstantVariable)node.Target) || No(node)) && Walk(args.Expressions[0]); diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 7f014e65c..5e3a7af68 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1251,6 +1251,16 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* // An instance variable used as a numeric operand of an outlined loop (JitCompiler.NumericIVar): // unboxed while it holds the type it held when the loop was compiled, a deopt once it does not. + /// + /// `defined?(@x)' (JitCompiler.EmitDefinedInstanceVariable): whether self has the variable, read as + /// RubyOps.IsDefinedInstanceVariable reads it. + /// + public static bool HasInstanceVariable(RubyContext/*!*/ context, object self, string/*!*/ name) { + RubyInstanceData data = context.TryGetInstanceData(self); + object value; + return data != null && data.TryGetInstanceVariable(name, out value); + } + /// `!x' of an x speculated to be true, false or nil (JitCompiler.EmitNot). public static bool NotBoolean(object value) { if (value == null) { return true; } diff --git a/Util/bench/defined-shapes.rb b/Util/bench/defined-shapes.rb new file mode 100644 index 000000000..219b22c2e --- /dev/null +++ b/Util/bench/defined-shapes.rb @@ -0,0 +1,29 @@ +# `defined?(@x)' in hot methods (JitCompiler.EmitDefinedInstanceVariable): as a condition, as the memo idiom's guard. +# Every line prints the sum of its results next to its time; it must be CRuby's. +# ruby Util/perf/ab.rb Util/bench/defined-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ../ironruby/ir.sh" "new=env IR_CONFIG=Release ./ir.sh" +$stdout.sync = true +class DS + def initialize; @a = 1; end + def cond = defined?(@a) ? 1 : 0 + def unset = defined?(@zz) ? 1 : 0 + def memo + return @m if defined?(@m) + @m = 7 + end +end +def cpu; Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID); end +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times do + t0 = cpu; sum = yield n; d = cpu - t0 + best = d if d < best + end + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +o = DS.new +N = (ENV["N"] || 1_000_000).to_i +t("cond", N) { |n| i = 0; r = 0; while i < n; r += o.cond; i += 1; end; r } +t("unset", N) { |n| i = 0; r = 0; while i < n; r += o.unset; i += 1; end; r } +t("memo", N) { |n| i = 0; r = 0; while i < n; r += o.memo; i += 1; end; r } diff --git a/Util/jit-defined-matrix.rb b/Util/jit-defined-matrix.rb new file mode 100644 index 000000000..498b9536b --- /dev/null +++ b/Util/jit-defined-matrix.rb @@ -0,0 +1,98 @@ +# Differential matrix for `defined?(@x)' in methods the method JIT compiles (JitCompiler.EmitDefinedInstanceVariable, +# JitRuntime.HasInstanceVariable). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-defined-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-defined-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-defined-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-defined-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep DF +# The traps: a variable that is nil or false is defined, instance_variable_set and remove_instance_variable after the +# body is hot, a write the body itself made just before (and may hold back to its end), a frozen self, a self that is +# no plain object, the memo idiom. (The String's encoding and identity differ from CRuby's on every build: not here.) + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class DF + def d_a = defined?(@a) + def has_a = defined?(@a) ? 1 : 0 + def not_a = !defined?(@a) + def a_and = defined?(@a) && @a + def memo(x) + return @memo if defined?(@memo) + @memo = x * 2 + end + def write_then(x) + @w = x + defined?(@w) ? @w : -1 + end + def write_other(x) + @w2 = x + defined?(@other) ? 1 : 0 + end + def setter(x) = @a = x + def loop_defined(n) + i = 0 + c = 0 + while i < n + c += 1 if defined?(@a) + i += 1 + end + c + end + define_method(:dm_defined) { defined?(@a) ? :yes : :no } +end + +o = DF.new +t("unset, hot") { warm { o.has_a } } +t("unset") { [o.d_a, o.not_a, o.a_and] } +t("set to nil") { o.setter(nil); [o.d_a, o.has_a, o.not_a, o.a_and] } +t("set to false") { o.setter(false); [o.d_a, o.has_a, o.a_and] } +t("set to 5") { o.setter(5); [o.d_a, o.has_a, o.a_and] } +t("the String") { s = o.d_a; [s, s.frozen?, s.class] } +t("removed after hot") { warm { o.has_a }; o.remove_instance_variable(:@a); [o.d_a, o.has_a] } +t("instance_variable_set after hot") { warm { o.has_a }; o.instance_variable_set(:@a, 1); [o.d_a, o.has_a] } +t("memo") { q = DF.new; [warm { |i| q.memo(i + 1) }, q.memo(100)] } +t("memo, a fresh object each time") { warm { |i| DF.new.memo(i) } } +t("a write, then defined? of it") { q = DF.new; [warm { |i| q.write_then(i) }, q.write_then(7)] } +t("a write, then defined? of another") { q = DF.new; r = warm { |i| q.write_other(i) }; q.instance_variable_set(:@other, 1); [r, q.write_other(1)] } +t("frozen self") { q = DF.new; q.setter(1); warm { q.has_a }; q.freeze; [q.has_a, (q.write_then(1) rescue $!.class)] } +t("a loop") { q = DF.new; [q.loop_defined(2000), (q.setter(1); q.loop_defined(2000))] } +t("define_method") { q = DF.new; [warm { q.dm_defined }, (q.setter(1); q.dm_defined)] } + +class Integer + def int_defined = defined?(@a) ? :yes : :no +end +class StrSub < String + def sub_defined = defined?(@a) ? :yes : :no + def sub_set = @a = 1 +end +t("self an Integer") { warm { |i| i.int_defined } } +t("self a String subclass") { s = StrSub.new("x"); r = warm { s.sub_defined }; s.sub_set; [r, s.sub_defined] } + +# the value form is `defined?(@a).freeze' (PrismAstBridge). (With String#freeze redefined IronRuby calls it and CRuby does +# not, on every build: a difference of the bridge's, not here.) +q = DF.new +q.setter(1) +t("the value form, hot") { [warm { q.d_a }, q.d_a.frozen?, DF.new.d_a] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index c2f1f370c..275c15d39 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,41 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitdefined (2026-11-29, census and timed, not gated) - `defined?(@x)` in the method JIT's typed body** (the + census's `IsDefinedExpression`: 118 methods refused, 36 by it alone, nearly all `defined?(@ivar)`; switch + `IR_JIT_DEFINED_IVAR`). Built on perf/jitcaseeq da02d10 (happy-gauss 50b2427 merged). + - **First, the screen refusals passed over.** `@x ||= v` (296 first refusals, 44 alone) is already compiled. The + screen refuses it only where v is a call, on purpose: the 44 are memos of real work (`compute_*`, `find_*`, + `new`), which would be wrapped to be declined. String-literal arguments and regexps (they set $~) are + deliberate refusals too. + - **What.** As a condition (`if defined?(@x)`, `return @m if defined?(@m)`, `!defined?(@x)`), it is + `JitRuntime.HasInstanceVariable`: whether self has the variable, read as `RubyOps.IsDefinedInstanceVariable` + reads it, with no String made (the generic body's TransformReadBoolean). As a value, which PrismAstBridge + writes `defined?(@x).freeze`, it is the String the generic body makes (`RubyOps.CreateMutableStringL` of + "instance-variable", binary, frozen) or nil, while String#freeze and NilClass#freeze are the library's. The + variable's value is not read, so nothing converts or deopts. A body holding a write back calls a helper the + held writes do not allow, and is compiled storing them where they are. Not in an outlined loop. + - **Caught by the clock.** The first version made the String in a condition too, then tested it. With the + variable set, that was slower than the generic body (cond 62.7 -> 75.7 ns, memo 60.1 -> 81.5). EmitCondition + now takes the test alone. + - **Census** (Src/StdLib, Util/bench, AWFY, against da02d10): 44 methods up (31 never -> compiles, 13 never -> + maybe), none down. `IsDefinedExpression` as the first refusal: 118 -> 43. + - **app-shapes, traced:** specialized 123 -> 124 (URI::Generic#parser), declined 29 -> 29. + - **Clock** (ab.rb -r 5, `Util/bench/defined-shapes.rb`, ns, off -> new, CRuby): a set variable as a condition + 64.4 -> 48.6 (28.9), an unset one 65.1 -> 49.7 (27.7), the memo idiom 59.6 -> 54.2 (28.9). + - **A difference found on the way (all builds, not this change's).** PrismAstBridge's `.freeze` dispatches, so + with String#freeze redefined `defined?(@x)` answers its value; CRuby's frozen String calls nothing. The String + is BINARY and a new one each time; CRuby's is US-ASCII and always the same object. Left as it is; the matrix + leaves those three out. + - **Checks.** `Util/jit-defined-matrix.rb` (new, 18 rows): unset, nil, false and set variables; + remove_instance_variable and instance_variable_set after hot; the memo idiom; a write and then defined? of it + or of another (held writes); a frozen self; an outlined loop; define_method; self an Integer and a String + subclass; the value form. It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, + IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, jit-const, jit-objops, jit-caseeq, hot-shapes, loop-ivar + and unsampled in the same five modes: CRuby's output on both builds. jit-defined, jit, loop-ivar and + jit-objops again after the condition fix. ruby/spec language/defined: 258 examples, no failures on either + build. IronRuby.Tests (Debug), all 1,441: PASSED, before and after the condition fix. + - **perf/jitcaseeq (2026-11-28, checks finished 2026-11-29, census and timed, not gated) - `C === x` with C a class or module constant in the method JIT's typed body** (the census's `MethodCall ===`: 304 methods refused, 170 by it alone; switch `IR_JIT_CASE_EQ`). Built on happy-gauss fcbc67b. From 1d1335838d2a1fc983a0bd97e5b99aeccd6cf733 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:11:24 +0000 Subject: [PATCH 375/439] Ledger: where nb { }'s cost goes, and a parked scope reinitialized with fewer stores nb { } costs 75 ns over a call without a block, against CRuby's 3: passing any block is 5-17 of that, and making the literal 50-56, the parked cycle, whether or not the block runs. Reinitializing a parked scope with each reference stored once and the null ones skipped measured nothing in the harness (the scope's reinitialization 22.6 / 22.7 ns). Not kept; the census is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Util/perf/LEDGER.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index a237917c6..f0fd56ac1 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -9104,6 +9104,20 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/nblcost (round thirty-seven, 2026-11-29) - where `nb { }`'s 75 ns over `nb0` go, and a parked scope reinitialized + with fewer stores: attributed, the experiment not kept** (gap 13). Shapes that differ in one thing (`ab.rb -r 6`, ns per call, + CRuby in brackets): `nb0` 47 (40), `nbp` (`nb(&P)`) 64 (48), `nbl` (`nb { }`) 120 (43); in a body that reads a global, `nbg` + 60 (99), `nbgp` 64 (115), `nbgl` 114 (104). So passing any block costs 5-17 ns, and the literal itself 50-56 whether the body + is light or not and whether the block ever runs (`nb` ignores it) - the same 45-50 as `e1`'s literal: the parked cycle (take, + reinitialize, the Proc made again, stage, park) on an ordinary frame since perf/literalcode, which perf/ignoredblock made + `nbl` take. CRuby's `nb { }` costs it 3 ns: its block is a pointer into the caller's frame. The experiment: a parked scope is + only ever reinitialized after `ClearCallState` nulled its call state, so `RubyMethodScope.Reinitialize` stored each reference + once and skipped the null ones (the flow-control frame was set twice, the interpreted frame, block and callee name stored + even when null) - three or four write barriers fewer (`IR_PARK_REINIT`). Harness, off/on: the scope reinitialized (P2) 22.6 / + 22.7 ns, the Proc made again on top (P3) 30.4 / 28.6, `e1`'s steps 45.1 / 47.8 - nothing. With perf/endpark, perf/ownerpark + and perf/stagea, every step of the cycle has now been cut or simulated, each at 3-8 ns, none visible end to end; what is left + of a literal's cost is the cycle as a whole. Census: no change (runtime only). + - **perf/ownerpark (round thirty-seven, 2026-11-28) - a parked scope the thread that parked first takes and parks with plain loads and stores: measured, not kept** (gap 13). The take of a parked scope is the cycle's one atomic left after perf/endpark. The prototype (`IR_PARK_OWNER`) gave `ParkedScopeSlot` an `Owner` (the first thread to park, set once by From 4443759be12e455ef5db8314c36c4948e103cbfc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:14:10 +0000 Subject: [PATCH 376/439] An escaped character in an fnmatch/glob bracket expression is taken literally Glob's CharClass kept the characters of a bracket expression without remembering which were escaped, so "[a\-c]" made the range a-c (matching 'b') and "[\!a]" negated. In MRI's fnmatch_helper an escaped character in a bracket is that character: '-' between two others is a range only when it was not escaped, and only an unescaped '!' or '^' negates. FNM_NOESCAPE leaves the backslash a character of the set, as before. Checked against CRuby 4.0.10: TestFnmatch#test_escape passes; ruby/spec core/file/fnmatch and core/dir/glob unchanged, the glob matrix the same in every mode. New IronRuby.Tests: File_FnmatchEscapedInBracket1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IoTests.cs | 23 +++++++++++++++++++++++ Src/Ruby/Builtins/Glob.cs | 13 ++++++++++--- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 42289274c..7a6b731bc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1485,6 +1485,7 @@ public Tests(Driver/*!*/ driver) { IOBuffer_ExperimentalWarning1, IOBuffer_Values1, IOBuffer_CopyAndMasks1, + File_FnmatchEscapedInBracket1, Array_Cycle1, Range_Recursive1, Array_JoinRecursive1, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index c6eb5c91d..3ac859b09 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -1229,6 +1229,29 @@ 0x00000008 35 36 56 IO::Buffer::MaskError: Zero-length mask given! IO::Buffer::MaskError: Mask overlaps source buffer! IO::Buffer::AccessError: Buffer is not writable! +"); + } + + /// + /// An escaped character in a bracket expression is that character: "[a\-c]" is 'a', '-' and 'c', not the range + /// a-c, and an escaped '!' does not negate (CRuby's TestFnmatch#test_escape). + /// + public void File_FnmatchEscapedInBracket1() { + TestOutput(@" +p File.fnmatch('[a\-c]', '-'), File.fnmatch('[a\-c]', 'a'), File.fnmatch('[a\-c]', 'c'), File.fnmatch('[a\-c]', 'b') +p File.fnmatch('[a-c]', 'b'), File.fnmatch('[\!a]', '!'), File.fnmatch('[\!a]', 'b'), File.fnmatch('[!a]', 'b') +p File.fnmatch('[a\-c]', '-', File::FNM_NOESCAPE), File.fnmatch('[a\-c]', 'b', File::FNM_NOESCAPE) +", @" +true +true +true +false +true +true +false +true +false +true "); } } diff --git a/Src/Ruby/Builtins/Glob.cs b/Src/Ruby/Builtins/Glob.cs index 94512c738..b09b7c84e 100644 --- a/Src/Ruby/Builtins/Glob.cs +++ b/Src/Ruby/Builtins/Glob.cs @@ -55,6 +55,8 @@ internal static class Constants { private class CharClass { private readonly StringBuilder/*!*/ _chars = new StringBuilder(); + // which of _chars were escaped with '\': "[a\-c]" is 'a', '-' and 'c', not a range + private readonly List/*!*/ _escaped = new List(); private bool _negated; private bool _empty = true; @@ -65,13 +67,18 @@ private class CharClass { /// excluding it. /// internal void Add(char c) { - if (_empty && (c == '!' || c == '^')) { + Add(c, false); + } + + internal void Add(char c, bool escaped) { + if (_empty && !escaped && (c == '!' || c == '^')) { _negated = true; _empty = false; return; } _empty = false; _chars.Append(c); + _escaped.Add(escaped); } private static void AppendLiteral(StringBuilder/*!*/ builder, char c) { @@ -91,7 +98,7 @@ internal string MakeString() { // "a-z" is a range; "z-a" is not - glob(7) leaves a reversed range // undefined and CRuby falls back to three literal characters, while // the CLR regex engine would throw. - if (i + 2 < _chars.Length && _chars[i + 1] == '-' && _chars[i] <= _chars[i + 2]) { + if (i + 2 < _chars.Length && _chars[i + 1] == '-' && !_escaped[i + 1] && _chars[i] <= _chars[i + 2]) { AppendLiteral(result, _chars[i]); result.Append('-'); AppendLiteral(result, _chars[i + 2]); @@ -145,7 +152,7 @@ private static void AppendExplicitRegexChar(StringBuilder/*!*/ builder, char c) if (inEscape) { if (charClass != null) { - charClass.Add(c); + charClass.Add(c, true); } else { AppendExplicitRegexChar(result, c); } From d405b4d859b884067068c70123346eeb5cf081cc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:14:10 +0000 Subject: [PATCH 377/439] File.fnmatch refuses a pattern with a NUL in it File.fnmatch("a\0z", "a") answered false. MRI reads the pattern with StringValueCStr, before the path, and raises ArgumentError "string contains null byte" (the path's own check says "path name contains null byte"). Checked against CRuby 4.0.10: TestFnmatch#test_nullchar passes; ruby/spec core/file/fnmatch unchanged. New IronRuby.Tests: File_FnmatchNullPattern1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IoTests.cs | 21 +++++++++++++++++++++ Src/Libraries/Builtins/FileOps.cs | 4 ++++ 3 files changed, 26 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 7a6b731bc..0dadfa506 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1486,6 +1486,7 @@ public Tests(Driver/*!*/ driver) { IOBuffer_Values1, IOBuffer_CopyAndMasks1, File_FnmatchEscapedInBracket1, + File_FnmatchNullPattern1, Array_Cycle1, Range_Recursive1, Array_JoinRecursive1, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index 3ac859b09..5241365dd 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -1252,6 +1252,27 @@ p File.fnmatch('[a\-c]', '-', File::FNM_NOESCAPE), File.fnmatch('[a\-c]', 'b', F true false true +"); + } + + /// + /// File.fnmatch reads its pattern as a C string: a NUL in it is an ArgumentError (CRuby's TestFnmatch#test_nullchar). + /// + public void File_FnmatchNullPattern1() { + TestOutput(@" +begin + File.fnmatch(""a\0z"", ""a"") +rescue ArgumentError => e + p e.message +end +begin + File.fnmatch(""a"", ""a\0z"") +rescue ArgumentError => e + p e.message +end +", @" +""string contains null byte"" +""path name contains null byte"" "); } } diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 869fce599..26b09e652 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1195,6 +1195,10 @@ public static bool IsAbsolutePath(ConversionStorage/*!*/ toPath, public static bool FnMatch(ConversionStorage/*!*/ toPath, object/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ pattern, object path, [DefaultProtocol, Optional]int flags) { + // MRI reads the pattern with StringValueCStr, before it looks at the path + if (pattern.IndexOf('\0') >= 0) { + throw RubyExceptions.CreateArgumentError("string contains null byte"); + } return Glob.FnMatch(pattern.ConvertToString(), Protocols.CastToPath(toPath, path).ConvertToString(), flags); } From f68873f0e6989b4e5b4355273ad7f6040677da15 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:14:10 +0000 Subject: [PATCH 378/439] Class variables of a class's singleton class come from the class, not from the modules it extends A class extended with a module that has @@rule answered c.singleton_class.class_variables => [:@@rule] and read @@rule through it, while it could not read the class's own @@foo that way. MRI looks a class variable up in the singleton class itself and then, for the singleton class of a class or module, in that class or module and its ancestors (cvar_front_klass, used by CVAR_LOOKUP and mod_cvar_of); the singleton class's own ancestors - the extended modules - only for an object's singleton class. TryResolveClassVariable, IsClassVariableDefined and the inherited ForEachClassVariable now walk that order. Checked against CRuby 4.0.10: TestVariable#test_singleton_class_included_class_variable passes; ruby/spec core/module/class_variable* and language/class_variable unchanged. New IronRuby.Tests: ClassVariable_SingletonOfClass1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ModuleTests.cs | 34 +++++++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 24 ++++++++++++++-- 3 files changed, 56 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0dadfa506..eb6aee458 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1007,6 +1007,7 @@ public Tests(Driver/*!*/ driver) { PreludeHiddenState1, ExtendMany1, ConstSet_AsciiIncompatibleName1, + ClassVariable_SingletonOfClass1, Scenario_MainSingleton, Time_LoadZone1, Time_DumpLoadedZone1, diff --git a/Src/IronRuby.Tests/Runtime/ModuleTests.cs b/Src/IronRuby.Tests/Runtime/ModuleTests.cs index c3182659f..42f7a6bd3 100644 --- a/Src/IronRuby.Tests/Runtime/ModuleTests.cs +++ b/Src/IronRuby.Tests/Runtime/ModuleTests.cs @@ -1050,6 +1050,40 @@ p e.message 2 true ""wrong constant name foo"" +"); + } + + /// + /// A class variable of a class's singleton class is looked for in the class and its ancestors, not in the modules + /// the class was extended with (MRI's cvar_front_klass); an object's singleton class goes up its own ancestors + /// (CRuby's TestVariable#test_singleton_class_included_class_variable). + /// + public void ClassVariable_SingletonOfClass1() { + TestOutput(@" +module Olympians; @@rule = ""Zeus""; end +c = Class.new +c.extend(Olympians) +sc = c.singleton_class +p sc.class_variables, (sc.class_variable_get(:@@rule) rescue $!.class), sc.class_variable_defined?(:@@rule) +c.class_variable_set(:@@foo, 1) +p sc.class_variables, sc.class_variable_get(:@@foo), sc.class_variable_defined?(:@@foo) +d = Class.new(c) +p d.singleton_class.class_variables, d.singleton_class.class_variable_get(:@@foo) +o = Object.new; o.extend(Olympians) +p o.singleton_class.class_variables, (o.singleton_class.class_variable_get(:@@rule) rescue $!.class) +class << c; p class_variable_defined?(:@@foo); end +", @" +[] +NameError +false +[:@@foo] +1 +true +[:@@foo] +1 +[:@@rule] +""Zeus"" +true "); } } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 90f27a14b..ec09da638 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -3824,10 +3824,28 @@ public void ForEachMember(bool inherited, RubyMethodAttributes attributes, Actio // The table lock is always the innermost one - nothing here takes the class-hierarchy lock // while holding it - so the order the two are acquired in is fixed and cannot deadlock. + /// + /// The modules a class variable of this one is looked for in, in MRI's order (CVAR_LOOKUP and + /// mod_cvar_of, through cvar_front_klass): a singleton class of a class or module has its own, + /// and then those of the class or module it belongs to and that one's ancestors - not of the + /// modules the class was extended with, which are the singleton class's ancestors. Any other + /// module, an object's singleton class included, goes up its own ancestors. + /// + private bool ForEachClassVariableOwner(Func/*!*/ action) { + Context.RequiresClassHierarchyLock(); + var singleton = this as RubyClass; + RubyModule attached; + if (singleton != null && singleton.IsSingletonClass && (attached = singleton.SingletonClassOf as RubyModule) != null) { + return action(this) || attached.ForEachAncestor(action); + } + return ForEachAncestor(action); + } + public void ForEachClassVariable(bool inherited, Func/*!*/ action) { Context.RequiresClassHierarchyLock(); - ForEachAncestor(inherited, delegate(RubyModule/*!*/ module) { + Func, bool> walk = inherited ? (Func, bool>)ForEachClassVariableOwner : ForEachDeclaredAncestor; + walk(delegate(RubyModule/*!*/ module) { // notification that we entered the module (it could have no class variable): if (action(module, null, Missing.Value)) return true; @@ -3875,7 +3893,7 @@ public RubyModule TryResolveClassVariable(string/*!*/ name, out object value) { // MRI's CVAR_LOOKUP: the variable is the one furthest up the ancestors; one defined // lower down as well is "overtaken" by it, which is an error. using (Context.ClassHierarchyLocker()) { - ForEachAncestor(delegate(RubyModule/*!*/ module) { + ForEachClassVariableOwner(delegate(RubyModule/*!*/ module) { object moduleValue; if (module.TryGetClassVariable(name, out moduleValue)) { if (front == null) { @@ -3906,7 +3924,7 @@ public bool IsClassVariableDefined(string/*!*/ name) { Assert.NotNull(name); bool found = false; using (Context.ClassHierarchyLocker()) { - ForEachAncestor(delegate(RubyModule/*!*/ module) { + ForEachClassVariableOwner(delegate(RubyModule/*!*/ module) { object value; return found = module.TryGetClassVariable(name, out value); }); From d894adaaa7302e9a9d9112746e744d86804c017d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:14:25 +0000 Subject: [PATCH 379/439] A constant set in a frozen object's singleton class is refused naming the singleton class obj.singleton_class.const_set(:A, 2) on a frozen obj raised FrozenError naming obj ("can't modify frozen Object: ...", receiver obj): constants went through RubyModule.Mutate, which names a singleton class's object, as MRI does for a method definition (rb_class_modify_check). MRI's rb_const_set checks the module itself (rb_check_frozen) and names it: "can't modify frozen Class: #>", receiver the singleton class. SetConstantNoLock now does that check first. Checked against CRuby 4.0.10: TestFrozenError#test_receiver passes; ruby/spec core/module/const_set, core/exception/frozen_error and core/kernel/freeze unchanged; the constant matrices the same in every mode. New IronRuby.Tests: ConstSet_FrozenSingletonReceiver1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ModuleTests.cs | 24 +++++++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 6 ++++++ 3 files changed, 31 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index eb6aee458..859154295 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1008,6 +1008,7 @@ public Tests(Driver/*!*/ driver) { ExtendMany1, ConstSet_AsciiIncompatibleName1, ClassVariable_SingletonOfClass1, + ConstSet_FrozenSingletonReceiver1, Scenario_MainSingleton, Time_LoadZone1, Time_DumpLoadedZone1, diff --git a/Src/IronRuby.Tests/Runtime/ModuleTests.cs b/Src/IronRuby.Tests/Runtime/ModuleTests.cs index 42f7a6bd3..fef04b3f1 100644 --- a/Src/IronRuby.Tests/Runtime/ModuleTests.cs +++ b/Src/IronRuby.Tests/Runtime/ModuleTests.cs @@ -1084,6 +1084,30 @@ class << c; p class_variable_defined?(:@@foo); end [:@@rule] ""Zeus"" true +"); + } + + /// + /// A constant set in a frozen object's singleton class is refused naming the singleton class (rb_const_set's + /// rb_check_frozen), where a method defined there names the object (CRuby's TestFrozenError#test_receiver). + /// + public void ConstSet_FrozenSingletonReceiver1() { + TestOutput(@" +o = Object.new.freeze +begin; o.singleton_class.const_set(:A, 2); rescue FrozenError => e; p e.message.sub(/0x\h+/, """"), e.receiver.equal?(o.singleton_class); end +begin; def o.foo; end; rescue FrozenError => e; p e.message.sub(/0x\h+/, """"), e.receiver.equal?(o); end +begin; class << o; B = 1; end; rescue FrozenError => e; p e.message.sub(/0x\h+/, """"), e.receiver.equal?(o.singleton_class); end +M = Module.new.freeze +begin; M.const_set(:C, 1); rescue FrozenError => e; p e.message.sub(/0x\h+/, """"), e.receiver.equal?(M); end +", @" +""can't modify frozen Class: #>"" +true +""can't modify frozen Object: #"" +true +""can't modify frozen Class: #>"" +true +""can't modify frozen Module: M"" +true "); } } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index ec09da638..1d49f8003 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -1844,6 +1844,12 @@ private bool BringsFoldedConstantNoLock(RubyModule/*!*/[]/*!*/ modules) { } private void SetConstantNoLock(string/*!*/ name, object value) { + // MRI's rb_const_set checks the module itself (rb_check_frozen) and names it, a frozen + // object's singleton class included - "can't modify frozen Class: #>" + // - where a method definition names the object (Mutate, rb_class_modify_check). + if (IsFrozen && !IsDummySingletonClass) { + throw RubyExceptions.CreateObjectFrozenError(_context, this); + } Mutate(); SetConstantNoMutateNoLock(name, value); } From b5d1a5b60709975059ce7fba08246722de9e8777 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:14:38 +0000 Subject: [PATCH 380/439] cruby-test: baseline after round seven test_fnmatch, test_dir, test_file, test_variable, test_frozen_error, test_module, test_class, test_object and test_const swept again on top of round six's baseline: 6,676 passing, 69 files clean (test_class's ractor test, which fails only under the sweep's load, passed this time). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 4 ++-- Util/cruby-test/baseline.txt | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index ae21e1ab5..b809bb71c 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby -Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 67 clean, 74 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,671 passing. (The first sweep, of v4.0.9: +Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,676 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 4f5fb6209..6a7aa0cb6 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -14,7 +14,7 @@ test_bignum 73 tests 1 failures 2 errors 0 sk test_box 65 tests 5 failures 22 errors 31 skips test_call 65 tests 2 failures 0 errors 0 skips test_case 6 tests 0 failures 0 errors 0 skips -test_class 62 tests 3 failures 1 errors 0 skips +test_class 62 tests 2 failures 1 errors 0 skips test_clone 7 tests 0 failures 0 errors 0 skips test_comparable 11 tests 0 failures 0 errors 0 skips test_compile_prism 182 tests 1 failures 179 errors 0 skips @@ -43,9 +43,9 @@ test_file_exhaustive 125 tests 0 failures 0 errors 1 sk test_fixnum 39 tests 0 failures 0 errors 0 skips test_flip 5 tests 1 failures 0 errors 0 skips test_float 63 tests 0 failures 0 errors 0 skips -test_fnmatch 15 tests 3 failures 0 errors 0 skips +test_fnmatch 15 tests 1 failures 0 errors 0 skips test_frozen 6 tests 0 failures 0 errors 0 skips -test_frozen_error 5 tests 1 failures 0 errors 0 skips +test_frozen_error 5 tests 0 failures 0 errors 0 skips test_gc 53 tests 13 failures 7 errors 2 skips test_gc_compact 28 tests 9 failures 4 errors 7 skips test_hash 298 tests 6 failures 0 errors 0 skips @@ -130,7 +130,7 @@ test_trace 4 tests 0 failures 0 errors 0 sk test_transcode 101 tests 15 failures 4 errors 0 skips test_undef 3 tests 0 failures 0 errors 0 skips test_unicode_escape 8 tests 0 failures 0 errors 0 skips -test_variable 32 tests 1 failures 0 errors 0 skips +test_variable 32 tests 0 failures 0 errors 0 skips test_vm_dump 0 tests 0 failures 0 errors 0 skips test_warning 1 tests 0 failures 0 errors 0 skips test_weakkeymap 13 tests 0 failures 0 errors 0 skips @@ -141,5 +141,5 @@ test_yjit 0 tests 0 failures 0 errors 0 sk test_yjit_exit_locations 0 tests 0 failures 0 errors 0 skips test_zjit 0 tests 0 failures 0 errors 0 skips -142 files: 67 clean, 74 with failures, 1 without a summary -10369 tests, 2552117 assertions, 497 failures, 3131 errors, 70 skips; 6671 passing +142 files: 69 clean, 72 with failures, 1 without a summary +10369 tests, 2552025 assertions, 492 failures, 3131 errors, 70 skips; 6676 passing From 530202d02258390d45a4e3a04b373bb87b0e004c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:40:05 +0000 Subject: [PATCH 381/439] Method JIT: a, b = v of an Array A parallel assignment of one value was refused by the method JIT: 367 methods' first refusal, 67 by it alone, nearly all of them destructuring an Array (`errno, cred = data`, `@x, @y = pair`). EmitDestructuringAssignment evaluates v and takes an Array of any class as it is, as CRuby does (rb_check_array_type calls no to_ary for a T_ARRAY); anything else, nil and objects with a to_ary of their own, deopts before any target is written. Each target is written as `target = value` writes it, nil past the end; the value is v. Same targets as the list form. IR_JIT_DESTRUCTURE=0 turns it off. Util/bench/jit-masgn-shapes.rb: destructure 76.0 -> 65.8 ns (CRuby 43.7). Census: 23 methods up, none down. Util/jit-masgn-matrix.rb's new section and the matrices it touches print CRuby's output in every JIT mode; language/variables and IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 2 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 57 +++++++++++++++++++--- Src/Ruby/Runtime/Jit/JitRuntime.cs | 25 ++++++++++ Util/bench/jit-masgn-shapes.rb | 14 +++++- Util/jit-masgn-matrix.rb | 62 ++++++++++++++++++++++++ Util/perf/LEDGER.md | 30 ++++++++++++ 6 files changed, 181 insertions(+), 9 deletions(-) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index bb4d22e41..a08bcd599 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -308,7 +308,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { // deopt), a type or identity test (a class that resolves the method to anything but the library's deopts) and // `x.to_i' of an Integer, nil or a plain decimal String: no Ruby code, no instance variable, nothing but a deopt "IndexInt", "IndexLong", "IndexObj", "IndexIntChecked", "IndexLongChecked", "IndexObjChecked", "HashKeyInt", - "IsKindOf", "ModuleCaseEquals", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", + "IsKindOf", "ModuleCaseEquals", "DestructuredArray", "ElementOrNil", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", }; // Integer#abs of an Int32 (widened, so it cannot overflow) and Float#abs (JitCompiler.EmitCall) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 9ba853005..e04f2af5a 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1591,10 +1591,10 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { /// EmittedValue, so a local keeps its type and an instance variable write its effect and its deopt on a frozen /// self, exactly as the same writes spelled as statements. Only locals of the method and instance variables as /// targets, no `*rest' and no nested target, and two or more values, none splatted (IsListAssignment): a single - /// value is destructured by to_ary, which would be Ruby code run from the typed body, or a deopt after the effect - /// that computed it. The value of the expression, an Array of the right-hand values, is made only where it is used. + /// value is destructured (EmitDestructuringAssignment). The value of the expression, an Array of the right-hand values, is made only where it is used. /// private MSA.Expression/*!*/ EmitParallelAssignment(ParallelAssignmentExpression/*!*/ node, out JT type) { + if (IsDestructuringAssignment(node, _scopeDepth)) { return EmitDestructuringAssignment(node, out type); } if (!IsListAssignment(node, _scopeDepth)) { throw Bail("parallel assignment"); } var lefts = node.Left.LeftValues; var rights = node.Right; @@ -1626,18 +1626,61 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return Ast.Block(typeof(object), temps, parts); } + // IR_JIT_DESTRUCTURE=0 turns EmitDestructuringAssignment off + internal static readonly bool Destructuring = Environment.GetEnvironmentVariable("IR_JIT_DESTRUCTURE") != "0"; + + /// `a, b = v': one value, not splatted, into the targets IsListAssignment takes. + internal static bool IsDestructuringAssignment(ParallelAssignmentExpression/*!*/ node, int scopeDepth) { + return Destructuring && node.Right.Length == 1 && !(node.Right[0] is SplattedArgument) && HasPlainTargets(node, scopeDepth); + } + + /// + /// `a, b = v', `errno, cred = data', `@x, @y = pair' (JitRuntime.DestructuredArray): an Array - of any class: CRuby + /// takes a T_ARRAY as it is, calling no to_ary (rb_check_array_type) - gives its elements to the targets left to + /// right, nil past its end, each written as `target = value' writes it (EmitAssignment). Any other value (nil, an + /// object with a to_ary, which is Ruby code) deopts, after v is evaluated and before any target is written; a deopt + /// there, like any, only before an effect. The value of the expression is v. + /// + private MSA.Expression/*!*/ EmitDestructuringAssignment(ParallelAssignmentExpression/*!*/ node, out JT type) { + var lefts = node.Left.LeftValues; + JT t; + var v = Emit(node.Right[0], out t); + if (t == JT.None || t == JT.Never) { throw Bail("parallel assignment of a value that jumps away"); } + var value = Ast.Variable(typeof(object), "#masgn"); + var list = Ast.Variable(typeof(RubyArray), "#masgnArray"); + var parts = new List { + Ast.Assign(value, Coerce(v, t, JT.Obj)), + Ast.Assign(list, Ast.Call(JitRuntime.M("DestructuredArray"), value)), + }; + _canDeopt = true; + for (int i = 0; i < lefts.Length; i++) { + var element = new EmittedValue(Ast.Call(JitRuntime.M("ElementOrNil"), list, Ast.Constant(i)), JT.Obj); + JT ignored; + parts.Add(Emit(new SimpleAssignmentExpression(lefts[i], element, null, node.Location), out ignored)); + } + parts.Add(value); + type = JT.Obj; + return Ast.Block(typeof(object), new[] { value, list }, parts); + } + /// The parallel assignments EmitParallelAssignment takes (JitScreen walks the same). internal static bool IsListAssignment(ParallelAssignmentExpression/*!*/ node, int scopeDepth) { + if (node.Right.Length < 2) { return false; } + foreach (var value in node.Right) { + if (value is SplattedArgument) { return false; } + } + return HasPlainTargets(node, scopeDepth); + } + + // locals of the method and instance variables, with no `*rest' and nothing nested + private static bool HasPlainTargets(ParallelAssignmentExpression/*!*/ node, int scopeDepth) { var left = node.Left; - if (left.HasUnsplattedValue || node.Right.Length < 2) { return false; } + if (left.HasUnsplattedValue) { return false; } foreach (var target in left.LeftValues) { if (target is InstanceVariable) { continue; } var local = target as LocalVariable; if (local == null || local.DefinitionLexicalDepth != scopeDepth) { return false; } } - foreach (var value in node.Right) { - if (value is SplattedArgument) { return false; } - } return true; } @@ -4413,7 +4456,7 @@ private bool Walk(RExpr/*!*/ node) { // `a, b = x, y' into locals and instance variables (JitCompiler.EmitParallelAssignment) var parallel = node as ParallelAssignmentExpression; if (parallel != null) { - if (!JitCompiler.IsListAssignment(parallel, _scopeDepth) || _inKeywordDefault) { return No(node); } + if (!(JitCompiler.IsListAssignment(parallel, _scopeDepth) || JitCompiler.IsDestructuringAssignment(parallel, _scopeDepth)) || _inKeywordDefault) { return No(node); } foreach (var value in parallel.Right) { if (!Walk(value)) { return false; } } diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 5e3a7af68..d4aed8889 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1251,6 +1251,31 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* // An instance variable used as a numeric operand of an outlined loop (JitCompiler.NumericIVar): // unboxed while it holds the type it held when the loop was compiled, a deopt once it does not. + /// + /// The value `a, b = v' destructures (JitCompiler.EmitDestructuringAssignment): an Array of any class as it is, which + /// CRuby takes without calling to_ary; anything else deopts, before any target is written. + /// + public static RubyArray/*!*/ DestructuredArray(object value) { + var array = value as RubyArray; + if (array == null) { throw Deopt(); } + return array; + } + + /// + /// The element a target of `a, b = array' gets: the one at its index, or nil past the end - also past an end another + /// thread has just moved (no GVL): nothing but a deopt may leave a typed body's helper. + /// + public static object ElementOrNil(RubyArray/*!*/ array, int index) { + if (index >= array.Count) { return null; } + try { + return array[index]; + } catch (ArgumentOutOfRangeException) { + return null; + } catch (IndexOutOfRangeException) { + return null; + } + } + /// /// `defined?(@x)' (JitCompiler.EmitDefinedInstanceVariable): whether self has the variable, read as /// RubyOps.IsDefinedInstanceVariable reads it. diff --git a/Util/bench/jit-masgn-shapes.rb b/Util/bench/jit-masgn-shapes.rb index 5cf4b0c4c..362f48d8e 100644 --- a/Util/bench/jit-masgn-shapes.rb +++ b/Util/bench/jit-masgn-shapes.rb @@ -1,6 +1,7 @@ # What a multiple assignment costs in a method the method JIT can take (JitCompiler.EmitParallelAssignment): ns per # call of the method, the caller a `while' loop. swap `x, y = y, x', three `a, b, c = x, x + 1, x * 2', ivars -# `@a, @b = x, y', value the expression's Array used; seq `a = x; b = x + 1' is the control (taken already). +# `@a, @b = x, y', value the expression's Array used; seq `a = x; b = x + 1' is the control (taken already); +# destructure `a, b = pair' of an Array (JitCompiler.EmitDestructuringAssignment), into locals and into ivars. # # ruby Util/perf/ab.rb -r 6 Util/bench/jit-masgn-shapes.rb "base=env IR_CONFIG=Release ../ironruby/ir.sh" \ # "new=env IR_CONFIG=Release ./ir.sh" @@ -30,6 +31,14 @@ def seq(x) b = x + 1 a + b end + def destructure(pair) + a, b = pair + b.nil? ? a : b + end + def destructure_ivars(pair) + @a, @b = pair + @b + end end def cpu; File.read("/proc/thread-self/schedstat").to_i / 1e9; end @@ -54,3 +63,6 @@ def t(name, n) t("ivars", N) { |n| i = 0; r = 0; while i < n; r += s.ivars(i, 2); i += 1; end; r } t("value", N) { |n| i = 0; r = 0; while i < n; r += s.value(i); i += 1; end; r } t("seq", N) { |n| i = 0; r = 0; while i < n; r += s.seq(i); i += 1; end; r } +PAIR = [1, 2] +t("destructure", N) { |n| i = 0; r = 0; while i < n; r += s.destructure(PAIR); i += 1; end; r } +t("destructure_ivars", N) { |n| i = 0; r = 0; while i < n; r += s.destructure_ivars(PAIR); i += 1; end; r } diff --git a/Util/jit-masgn-matrix.rb b/Util/jit-masgn-matrix.rb index 8a9637787..fe48029e1 100644 --- a/Util/jit-masgn-matrix.rb +++ b/Util/jit-masgn-matrix.rb @@ -13,6 +13,9 @@ # type (Int to Bignum after the swap, a Float, an object); an instance variable write deopts on # a frozen self, after which the generic body must not repeat what came before; the value of # the expression is an Array of the right-hand values where it is used. +# The destructuring section (`a, b = v', JitCompiler.EmitDestructuringAssignment): an Array of any class is taken as it +# is, its own to_ary (an Array subclass's, a singleton one) never called; anything else, nil included, is the generic +# body's, which calls to_ary; nil past the end; the value is v. def t(label) print label.ljust(52), ' => ' @@ -148,3 +151,62 @@ def ma_swap(x, y) end end t("redefined") { o.ma_swap(3, 4) } + +# destructuring: `a, b = v' +class MD + def initialize; @a = nil; @b = nil; @n = 0; end + attr_reader :a, :b, :n + def md_two(v) + x, y = v + [x, y] + end + def md_sum(v) + x, y = v + x + y + end + def md_ivars(v) + @a, @b = v + @a + end + def md_value(v) = (x, y = v) + def md_one(v) + x, = v + x + end + def md_swap(x, y) + x, y = [y, x] + x - y + end + def md_effect(v) + @n += 1 + x, y = v + x + end +end + +class ArySub < Array + def to_ary = [:sub_to_ary] +end +class Pairish + def to_ary = [:p1, :p2] +end + +md = MD.new +t("md two, hot") { warm { |i| md.md_two([i, i + 1]) } } +t("md lengths") { [[], [1], [1, 2], [1, 2, 3]].map { |v| md.md_two(v) } } +t("md nil") { md.md_two(nil) } +t("md a String") { md.md_two("s") } +t("md a Hash") { md.md_two({ a: 1 }) } +t("md to_ary") { md.md_two(Pairish.new) } +t("md Array subclass") { md.md_two(ArySub[1, 2]) } +t("md singleton to_ary") { a = [3, 4]; def a.to_ary = [:single]; md.md_two(a) } +t("md sum, hot") { warm { |i| md.md_sum([i, 2]) } } +t("md sum, Bignum") { md.md_sum([2**62, 2**62]) } +t("md sum, Floats") { md.md_sum([1.5, 2]) } +t("md ivars") { warm { |i| md.md_ivars([i, -i]) }; [md.a, md.b, md.md_ivars([1]), md.b] } +t("md ivars, frozen") { q = MD.new; warm { |i| q.md_ivars([i, i]) }; q.freeze; [(q.md_ivars([7, 8]) rescue $!.class), q.a] } +t("md value") { warm { |i| md.md_value([i]) }; v = [1, 2]; r = md.md_value(v); [r, r.equal?(v)] } +t("md trailing comma") { warm { |i| md.md_one([i, 0]) }; [md.md_one([9, 8]), md.md_one([])] } +t("md swap literal") { warm { |i| md.md_swap(i, 1) } } +t("md effect, then nil") { q = MD.new; warm { |i| q.md_effect([i]) }; [q.md_effect(nil), q.n] } +t("md effect, to_ary") { q = MD.new; warm { |i| q.md_effect([i]) }; [q.md_effect(Pairish.new), q.n] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 275c15d39..e0d5ce4d2 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,36 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitmasgn1 (2026-11-29, census and timed, not gated) - `a, b = v` of an Array in the method JIT's typed body** + (the census's ParallelAssignmentExpression: 367 first refusals, 67 alone; switch `IR_JIT_DESTRUCTURE`). Built on + perf/jitdefined 67ac8ea. + - **Choosing it.** Of the refusals that keep the most methods out on their own, StringLiteral (82) and + RegularExpression (71) are deliberate (a String literal argument; $~). Next comes parallel assignment (67), whose + two-value form `a, b = x, y` perf/jitmasgn took. The 67 are nearly all one value destructured: `errno, cred = + data`, `gem_name, gem_version = args`, `@byte_pointer, @line_index = @mark_pointer`, `x, y = some_call(...)`. + - **What.** `JitCompiler.EmitDestructuringAssignment`: v is evaluated, then `JitRuntime.DestructuredArray` takes an + Array of any class as it is. CRuby's rb_check_array_type takes a T_ARRAY without calling to_ary, so an Array + subclass's or a singleton to_ary is not called. Anything else deopts, before any target is written: nil, and an + object whose to_ary would be Ruby code, are the generic body's. Each target is then written as `target = value` + writes it, from `ElementOrNil` (nil past the end, also past an end another thread just moved). The value of the + expression is v. Same targets as the list form: locals of the method and instance variables, no `*rest`, + nothing nested. Both helpers are on the sinking allow-list. + - **Census** (Src/StdLib, Util/bench, AWFY, against 67ac8ea): 23 methods up (5 never -> compiles, 18 never -> + maybe, 16 of them behind a call), none down. + - **Left as declines.** A typed body still cannot write an element, an object, into a local the profile typed as + an Integer (`x, y = [y, x]` with Integer parameters), nor add two such objects (`x, y = pair; x + y`). Those + methods pass the screen and are declined, as `x = @h[k]; x + y` already is. + - **app-shapes, traced:** specialized 124 -> 124, declined 29 -> 29. + - **Clock** (ab.rb -r 5, `Util/bench/jit-masgn-shapes.rb`, ns, off -> new, CRuby): destructure into locals 76.0 -> + 65.8 (43.7), into instance variables 67.8 -> 64.0 (39.8, overlapping); seq, the control, overlaps. + - **Checks.** `Util/jit-masgn-matrix.rb`'s new destructuring section (18 rows): lengths 0 to 3; nil, a String, a + Hash; an object with to_ary; an Array subclass and an Array with a singleton to_ary (not called); typed sums + with a Bignum and Floats; instance variables and a frozen self; the value; a trailing comma; a swap through a + literal; an effect then nil or a to_ary object. It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, + -X:NoJITCalls, IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, jit-const, jit-objops, hot-shapes and + jit-defined in the same five modes: CRuby's output on both builds (35 runs with jit-masgn). ruby/spec + language/variables: 119 examples, no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. + - **perf/jitdefined (2026-11-29, census and timed, not gated) - `defined?(@x)` in the method JIT's typed body** (the census's `IsDefinedExpression`: 118 methods refused, 36 by it alone, nearly all `defined?(@ivar)`; switch `IR_JIT_DEFINED_IVAR`). Built on perf/jitcaseeq da02d10 (happy-gauss 50b2427 merged). From befd3a1b9ef4f0206d0c01f9b7a9f90286671896 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:41:51 +0000 Subject: [PATCH 382/439] defined? answers with the deduplicated frozen US-ASCII String, with no call of #freeze The prism bridge wrote `defined?(x)` as `defined?(x).freeze`: a dispatched call, so a redefined String#freeze ran (and could fail the expression), and the answer was a new BINARY String on every evaluation. CRuby answers with the frozen US-ASCII fstring of the category (rb_iseq_defined_string), the same object every time and from every site, and calls nothing. IsDefinedExpression now makes that String itself, as a frozen literal interned once (StringLiteral.TransformFrozen); the categories the bridge writes as literals ("expression", "assignment") are frozen US-ASCII literals. The bridge's #freeze wrapper and UnfrozenDefined, which stripped it again in conditions, are gone. A method returning defined?(@x) takes less than half the time it did (3M calls of defined?(@x) and defined?(o.m): 0.78 s to 0.34 s). Checked against CRuby 4.0: encoding, frozen?, identity across sites and evaluations, FrozenError message, and a redefined String#freeze, for the variable, constant, method, assignment, expression, yield and guarded-call forms. ruby/spec language defined, if, while and string match the base. New IronRuby.Tests: Defined_FrozenUsAsciiString1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 25 ++++++++++ Src/Prism/PrismAstBridge.cs | 49 +++---------------- .../Compiler/Ast/Expressions/Expression.cs | 4 +- 4 files changed, 36 insertions(+), 43 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ccd0a1903..645f466d2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1207,6 +1207,7 @@ public Tests(Driver/*!*/ driver) { Float_RoundDigitsRange1, Enumerable_SortByOwnPush1, Defined_ConditionNoFreeze1, + Defined_FrozenUsAsciiString1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, Review212_1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 2ba9e6c9c..541a839b5 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -8046,6 +8046,31 @@ public void Defined_ConditionNoFreeze1() { "); } + /// + /// `defined?' answers with the deduplicated frozen US-ASCII String, the same object every time, made without a call of + /// #freeze (rb_iseq_defined_string). Expected output is CRuby 4.0's. + /// + public void Defined_FrozenUsAsciiString1() { + TestOutput(@" +$c = 0 +module CountFreeze; def freeze; $c += 1; super; end; end +String.prepend(CountFreeze) +@a = 1 +x = 1 +r = [defined?(@a), defined?(x), defined?(String), defined?(x.succ), defined?(x ||= 2), defined?([x]), defined?(String.new(""""))] +p r +p r.map { |s| [s.encoding.to_s, s.frozen?] }.uniq +p defined?(@a).equal?(defined?(@a)), defined?(x.succ).equal?(defined?(x.pred)) +p $c +", @" +[""instance-variable"", ""local-variable"", ""constant"", ""method"", ""assignment"", ""expression"", ""method""] +[[""US-ASCII"", true]] +true +true +0 +"); + } + /// /// A method whose first statement is `return ... unless defined?(yield)' - Kernel#then, written as CRuby writes it - is /// still a light frame (MethodDefinition.IsBlockGuard): given a block it makes no scope, and without one the guard makes diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index acd569216..95fc72b2c 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -521,38 +521,7 @@ private static bool HasFlag(Pm.PmNode node, uint flag) { // regex literals become $_ matches, ranges become flip-flops, etc. private Expression/*!*/ Condition(Pm.PmNode/*!*/ predicate) { - return UnfrozenDefined(Expr(predicate)).ToCondition(CurrentScope); - } - - /// - /// `if defined?(x)', `while defined?(x) && ...': in a condition only whether the answer is nil counts, so the string - /// need not be frozen by a call to #freeze (see Freeze) - which CRuby's defined? does not make at all, and which, being a - /// call, made the method it is in need its scope (`return ... unless defined?(yield)', MethodDefinition.IsBlockGuard). - /// The operands of &&, || and ! in a condition are conditions too: what one of them gives back is only tested. - /// - private static Expression/*!*/ UnfrozenDefined(Expression/*!*/ condition) { - switch (condition) { - case MethodCall call when call.MethodName == "freeze" && call.Target is IsDefinedExpression && - call.Arguments == null && call.Block == null: - return call.Target; - - case AndExpression and: { - var left = UnfrozenDefined(and.Left); - var right = UnfrozenDefined(and.Right); - return (left == and.Left && right == and.Right) ? condition : new AndExpression(left, right, and.Location); - } - case OrExpression or: { - var left = UnfrozenDefined(or.Left); - var right = UnfrozenDefined(or.Right); - return (left == or.Left && right == or.Right) ? condition : new OrExpression(left, right, or.Location); - } - case NotExpression not: { - var operand = UnfrozenDefined(not.Expression); - return (operand == not.Expression) ? condition : new NotExpression(operand, not.Location); - } - default: - return condition; - } + return Expr(predicate).ToCondition(CurrentScope); } // ---- program / statements ---- @@ -1506,7 +1475,6 @@ private RubyRegexOptions RegexOptions(Pm.PmNode/*!*/ node) { } } - // defined? answers with a frozen String in CRuby; IsDefinedExpression builds a mutable one. /// /// prism flags a literal Frozen where frozen_string_literal is on and Mutable where it was /// explicitly turned off. Neither flag means the file said nothing, which since Ruby 3.4 @@ -1562,12 +1530,10 @@ private static StringLiteralMutability StringMutability(Pm.PmNode/*!*/ node) { ? StringLiteralMutability.Mutable : StringLiteralMutability.Chilled; } - private Expression/*!*/ Freeze(Expression/*!*/ value, SourceSpan span) { - return new MethodCall(value, "freeze", null, span); - } - + // defined? answers with the deduplicated frozen US-ASCII String, made without a call of #freeze (a redefined + // String#freeze is not called), as IsDefinedExpression makes it (Expression.TransformIsDefined). private Expression/*!*/ FrozenString(string/*!*/ text, SourceSpan span) { - return Freeze(new StringLiteral(text, RubyEncoding.Binary, span), span); + return new StringLiteral(text, RubyEncoding.Ascii, StringLiteralMutability.Frozen, span); } // ? "".freeze : nil -- used where IsDefinedExpression would report @@ -1640,7 +1606,7 @@ when argumentsCall.Arguments is Pm.ArgumentsNode callArguments && callArguments. && !HasFlag(argumentsCall, Pm.CallNodeFlags.AttributeWrite): var callDefined = argumentsCall.Receiver != null ? GuardedDefined(argumentsCall.Receiver, new IsDefinedExpression(Expr(node), span), span) - : Freeze(new IsDefinedExpression(Expr(node), span), span); + : new IsDefinedExpression(Expr(node), span); return new ConditionalExpression(ElementsDefined(((Pm.ArgumentsNode)argumentsCall.Arguments).Arguments, span), callDefined, Literal.Nil(span), span); @@ -1662,7 +1628,7 @@ when argumentsCall.Arguments is Pm.ArgumentsNode callArguments && callArguments. return GuardedDefined(path.Parent, new IsDefinedExpression(Expr(node), span), span); default: - return Freeze(new IsDefinedExpression(Expr(node), span), span); + return new IsDefinedExpression(Expr(node), span); } } @@ -1670,9 +1636,8 @@ when argumentsCall.Arguments is Pm.ArgumentsNode callArguments && callArguments. // defined before it evaluates it, so `!$never_assigned` is nil rather than "method". // MethodCall/ConstantVariable only guard against the receiver *raising*. private Expression/*!*/ GuardedDefined(Pm.PmNode/*!*/ receiver, Expression/*!*/ defined, SourceSpan span) { - var result = Freeze(defined, span); var guard = DefinednessGuard(receiver, span); - return guard == null ? result : new ConditionalExpression(guard, result, Literal.Nil(span), span); + return guard == null ? defined : new ConditionalExpression(guard, defined, Literal.Nil(span), span); } // A test for "reading this receiver is defined", or null when reading it either always diff --git a/Src/Ruby/Compiler/Ast/Expressions/Expression.cs b/Src/Ruby/Compiler/Ast/Expressions/Expression.cs index bb101aa7a..b547c6844 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/Expression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/Expression.cs @@ -147,7 +147,9 @@ internal virtual MSA.Expression TransformDefinedCondition(AstGenerator/*!*/ gen) internal virtual MSA.Expression/*!*/ TransformIsDefined(AstGenerator/*!*/ gen) { MSA.Expression condition = TransformDefinedCondition(gen); - MSA.Expression result = Methods.CreateMutableStringL.OpCall(AstUtils.Constant(GetNodeName(gen)), Ast.Constant(RubyEncoding.Binary)); + // CRuby answers with the deduplicated frozen US-ASCII String (rb_iseq_defined_string), the same object every time, + // and calls no #freeze to make it so. + MSA.Expression result = StringLiteral.TransformFrozen(GetNodeName(gen), RubyEncoding.Ascii, null); return (condition != null) ? Ast.Condition(condition, result, AstFactory.NullOfMutableString) : result; } From cb92550df86826dfba592e824bd0fa8b7ae8d2d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:58:31 +0000 Subject: [PATCH 383/439] defined?(super) outside any method is nil At the top level, in a class body, or in a block or eval there, defined?(super) raised NoMethodError ("super called outside of method"): the super site's rule for a scope with no method raised whether the site was a call or a defined? check. A defined? site (ResolveOnly) now answers false there, which defined? makes nil, as in MRI. Checked against CRuby 4.0.10: TestDefined#test_super_toplevel passes; ruby/spec language unchanged, the eval-defined and super-light matrices the same in every mode. New IronRuby.Tests: DefinedOperator_SuperOutsideMethod1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/DefinedTests.cs | 20 ++++++++++++++++++++ Src/Ruby/Runtime/Calls/SuperCallAction.cs | 7 ++++++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index de157672c..66a825dec 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -999,6 +999,7 @@ public Tests(Driver/*!*/ driver) { DefinedOperator_Locals1, DefinedOperator_Super1, DefinedOperator_Parens1, + DefinedOperator_SuperOutsideMethod1, Scenario_ModuleOps_Methods, InstanceMethods_NotInherited1, diff --git a/Src/IronRuby.Tests/Runtime/DefinedTests.cs b/Src/IronRuby.Tests/Runtime/DefinedTests.cs index 4a1eb04bd..d3bf64359 100644 --- a/Src/IronRuby.Tests/Runtime/DefinedTests.cs +++ b/Src/IronRuby.Tests/Runtime/DefinedTests.cs @@ -366,6 +366,26 @@ p a ""expression"" ""expression"" nil +"); + } + + /// + /// defined?(super) outside any method - at the top level, in a class body, in a block or eval there - is nil, not + /// the NoMethodError a super call raises there (CRuby's TestDefined#test_super_toplevel). + /// + public void DefinedOperator_SuperOutsideMethod1() { + TestOutput(@" +p defined?(super) +p eval(""defined?(super)"") +class Foo; p defined?(super); end +p [1].map { defined?(super) } +p Object.new.instance_eval { defined?(super) } +", @" +nil +nil +nil +[nil] +nil "); } } diff --git a/Src/Ruby/Runtime/Calls/SuperCallAction.cs b/Src/Ruby/Runtime/Calls/SuperCallAction.cs index 5e0054b6c..186f07da9 100644 --- a/Src/Ruby/Runtime/Calls/SuperCallAction.cs +++ b/Src/Ruby/Runtime/Calls/SuperCallAction.cs @@ -114,7 +114,12 @@ protected override bool Build(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/ if (scopeNesting == -1) { metaBuilder.AddCondition(Methods.IsSuperOutOfMethodScope.OpCall(scopeExpr)); - metaBuilder.SetError(Methods.MakeTopLevelSuperException.OpCall()); + if (_signature.ResolveOnly) { + // defined?(super) outside any method is nil, not the error a call raises + metaBuilder.Result = AstUtils.Constant(false); + } else { + metaBuilder.SetError(Methods.MakeTopLevelSuperException.OpCall()); + } return true; } From 2f0feeb0e1e3026c4efe5b16c5588f0cc1b7ee19 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:58:32 +0000 Subject: [PATCH 384/439] alias_method of a name a module only made private needs a method to lead to Module.new { private :class } stores a super forwarder for #class (its private found Kernel#class through Object), and alias_method :xyz, :class then aliased the forwarder. MRI's rb_alias follows a ZSUPER entry up from the module that holds it, without the fallback to Object, and raises NameError ("undefined method 'class' for module '...'") when nothing above it has the method. AddMethodAlias now checks that the forwarder resolves from its module before aliasing it; a class whose ancestors have the method aliases it as before. Checked against CRuby 4.0.10: TestAlias#test_undef_method_error_message_with_zsuper_method passes; ruby/spec core/module/alias_method unchanged. New IronRuby.Tests: Alias_SuperForwarderWithoutTarget1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/AliasTests.cs | 28 ++++++++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 11 +++++++++- 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 66a825dec..0b270b295 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1341,6 +1341,7 @@ public Tests(Driver/*!*/ driver) { ErrorMessages_Ruby40, MethodAliasExpression, AliasUndefWithQuotedSymbols, + Alias_SuperForwarderWithoutTarget1, BasicObject1, BasicObject2, ClassDuplication1, diff --git a/Src/IronRuby.Tests/Runtime/AliasTests.cs b/Src/IronRuby.Tests/Runtime/AliasTests.cs index e343437bd..677205e6b 100644 --- a/Src/IronRuby.Tests/Runtime/AliasTests.cs +++ b/Src/IronRuby.Tests/Runtime/AliasTests.cs @@ -349,6 +349,34 @@ p instance_methods(false).sort ", @" [:ab, :c, :d] [:d] +"); + } + + /// + /// alias_method of a name a module only made private (a super forwarder) needs a method above the module to lead + /// to: rb_alias follows the ZSUPER entry without falling back to Object, so Module.new { private :class } has no + /// #class to alias (CRuby's TestAlias#test_undef_method_error_message_with_zsuper_method). + /// + public void Alias_SuperForwarderWithoutTarget1() { + TestOutput(@" +class A; def x; :ax; end; end +class B < A; private :x; alias y x; public :y; end +p B.new.y, B.private_method_defined?(:x) +class Foo; private :inspect; alias_method :insp, :inspect; end +p Foo.private_method_defined?(:insp) +m = Module.new { private :class } +begin; m.alias_method :xyz, :class; rescue NameError => e; p e.class; end +m2 = Module.new { prepend Module.new { private :class } } +begin; m2.alias_method :xyz, :class; rescue NameError => e; p e.class; end +c = Class.new { private :class; alias_method :klass, :class } +p c.private_method_defined?(:klass) +", @" +:ax +true +true +NameError +NameError +true "); } } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 1d49f8003..5ff2c53a2 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -2365,7 +2365,16 @@ public void AddMethodAlias(string/*!*/ newName, string/*!*/ oldName, bool warn) RubyMemberInfo method; using (Context.ClassHierarchyLocker()) { // MRI: aliases a super-forwarder not the real method. - method = ResolveMethodNoLock(oldName, VisibilityContext.AllVisible, MethodLookup.FallbackToObject | MethodLookup.ReturnForwarder).Info; + var resolved = ResolveMethodNoLock(oldName, VisibilityContext.AllVisible, MethodLookup.FallbackToObject | MethodLookup.ReturnForwarder); + method = resolved.Info; + + // ... but only one that leads somewhere: rb_alias follows a ZSUPER entry up from the module + // that holds it, without the fallback to Object, so `Module.new { private :class }' (whose + // `private' found Kernel#class through Object) has no #class to alias. + if (method != null && method.IsSuperForwarder && + !resolved.Owner.ResolveSuperMethodNoLock(((SuperForwarderInfo)method).SuperName, resolved.Owner).Found) { + throw RubyExceptions.CreateUndefinedMethodError(this, oldName); + } // `alias b a' inside a refinement means "the a of the module being refined": the refinement // starts empty, so its own lookup would find nothing. From 98963fae84af38afb14add81cfea72e611165290 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:58:32 +0000 Subject: [PATCH 385/439] Module#autoload?(name, false) does not look in included modules GetAutoloadedConstantPath walked ForEachAncestor(false), which visits the module's prepended and included modules as well as the module, so a module that included one with an autoload answered its path for autoload?(:X, false). MRI's rb_autoload_at_p with inherit false reads the module's own constant table only; so does this now. Checked against CRuby 4.0.10: TestAutoload#test_autoload_p passes; ruby/spec core/module/autoload and core/kernel/autoload unchanged. New IronRuby.Tests: Autoload_QueryNotInherited1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/LoaderTests.cs | 19 +++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 7 ++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0b270b295..e48cafac2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -569,6 +569,7 @@ public Tests(Driver/*!*/ driver) { Require_EncTransShims1, Require_NonAsciiFeatureBytes1, Load_WrappedMainVisibility1, + Autoload_QueryNotInherited1, CaseEquals1, CaseEquals2, CaseEquals3, diff --git a/Src/IronRuby.Tests/Runtime/LoaderTests.cs b/Src/IronRuby.Tests/Runtime/LoaderTests.cs index 03e22e2ff..bb4ca5ede 100644 --- a/Src/IronRuby.Tests/Runtime/LoaderTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoaderTests.cs @@ -583,6 +583,25 @@ p load(t.path, true) false false true +"); + } + + /// + /// Module#autoload?(name, false) looks in the module's own constants only, not in the modules it includes (CRuby's + /// TestAutoload#test_autoload_p). + /// + public void Autoload_QueryNotInherited1() { + TestOutput(@" +a = Module.new { autoload :X, ""/nonexistent/foo.rb"" } +b = Module.new { include a } +p a.autoload?(:X), b.autoload?(:X), a.autoload?(:X, false), a.autoload?(:X, nil), b.autoload?(:X, false), b.autoload?(:X, nil) +", @" +""/nonexistent/foo.rb"" +""/nonexistent/foo.rb"" +""/nonexistent/foo.rb"" +""/nonexistent/foo.rb"" +nil +nil "); } } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 5ff2c53a2..b03397f92 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -1939,7 +1939,12 @@ public MutableString GetAutoloadedConstantPath(string/*!*/ name) { public MutableString GetAutoloadedConstantPath(string/*!*/ name, bool inherit) { using (Context.ClassHierarchyLocker()) { MutableString result = null; - ForEachConstantAncestor(inherit, (module) => { + // autoload?(name, false) is this module's own table and nothing else (rb_autoload_at_p + // with inherit false), not the modules it includes, which ForEachAncestor(false) visits. + Func, bool> walk = inherit + ? (Func, bool>)(action => ForEachConstantAncestor(true, action)) + : (action => action(this)); + walk((module) => { ConstantStorage storage; AutoloadedConstant autoloaded; if (module.TryGetConstantNoAutoloadCheck(name, out storage)) { From 6b691ba6f5b07f21ed5a5700fff1ed085e644c57 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:58:32 +0000 Subject: [PATCH 386/439] super(args, &blk) evaluates the arguments before the block argument A super call with a block argument computed the block - its #to_proc - before the arguments, because MakeCallWithBlockRetryable assigns the block first (for a literal block's retry) and the arguments were evaluated inside the call: super(**o, &o) called o.to_proc before o.to_hash, and super(*o, **o, &o) to_proc before to_a. MRI evaluates the arguments first, as IronRuby already did for a method call (MethodCall hoists them). SuperCall now does the same when the block is an argument: the positional arguments, a splat (expanded into a fresh array) and a ** (its hash) go into temporaries ahead of the block argument; a literal block, a bare super and a super without a block are compiled as before. Checked against CRuby 4.0.10: TestCall#test_kwsplat_block_order_super passes; ruby/spec language unchanged; the block-pass, anon-forward, callable-parameters and super-light matrices the same in every mode. New IronRuby.Tests: Super_ArgumentsBeforeBlockArgument1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/SuperTests.cs | 55 +++++++++++++ .../Compiler/Ast/Expressions/SuperCall.cs | 79 +++++++++++++++---- 3 files changed, 120 insertions(+), 15 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e48cafac2..7d78234a8 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -965,6 +965,7 @@ public Tests(Driver/*!*/ driver) { SuperParameterless3, SuperParameterlessKeywordRest1, SuperMethodForwarder1, + Super_ArgumentsBeforeBlockArgument1, SuperKeywordSplat1, SuperKeywordRestPassOn1, SuperParameterlessKeywordRest2, diff --git a/Src/IronRuby.Tests/Runtime/SuperTests.cs b/Src/IronRuby.Tests/Runtime/SuperTests.cs index 69284e139..695de125f 100644 --- a/Src/IronRuby.Tests/Runtime/SuperTests.cs +++ b/Src/IronRuby.Tests/Runtime/SuperTests.cs @@ -1072,6 +1072,61 @@ class L < K; public :foo; end L nil :k +"); + } + + /// + /// super(args, &blk) evaluates the arguments - #to_a of a splat, #to_hash of a ** - before the block argument's + /// #to_proc, as a method call does (CRuby's TestCall#test_kwsplat_block_order_super). + /// + public void Super_ArgumentsBeforeBlockArgument1() { + TestOutput(@" +class P; def t(...) end; def u(...) end; end +class C < P + def t(splat) + o = Object.new + ary = [] + o.define_singleton_method(:to_a) {ary << :to_a; []} + o.define_singleton_method(:to_hash) {ary << :to_hash; {}} + o.define_singleton_method(:to_proc) {ary << :to_proc; lambda{}} + if splat + super(*o, **o, &o) + else + super(**o, &o) + end + ary + end + def u(splat) + o = Object.new + ary = [] + o.define_singleton_method(:to_a) {ary << :to_a; []} + o.define_singleton_method(:to_hash) {ary << :to_hash; {}} + o.define_singleton_method(:to_proc) {ary << :to_proc; lambda{}} + splat ? P.new.u(*o, **o, &o) : P.new.u(**o, &o) + ary + end +end +p C.new.t(false), C.new.t(true), C.new.u(false), C.new.u(true) +class P2; def m(*a, **k, &b) = [a, k, b&.call]; end +class C2 < P2 + def m(x) + log = [] + o = Object.new + o.define_singleton_method(:to_proc) { log << :to_proc; -> { :blk } } + r = super(log << :arg1 && 1, *(log << :splat; [2]), &o) + r2 = super(x, k: (log << :kw; 3), &o) + r3 = super(&o) + r4 = super { :lit } + [r, r2, r3, r4, log] + end +end +p C2.new.m(9) +", @" +[:to_hash, :to_proc] +[:to_a, :to_hash, :to_proc] +[:to_hash, :to_proc] +[:to_a, :to_hash, :to_proc] +[[[1, 2], {}, :blk], [[9], {k: 3}, :blk], [[], {}, :blk], [[9], {}, :lit], [:arg1, :splat, :to_proc, :kw, :to_proc, :to_proc]] "); } } diff --git a/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs b/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs index 5631218d5..d0f2f6c9d 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs @@ -67,10 +67,16 @@ public SuperCall(Arguments args, Block block, SourceSpan location, bool argument MSA.Expression invoke; Arguments arguments = Arguments ?? EvalImplicitArguments(gen); KeywordArgumentSplat keywordSplat = TrailingKeywordSplat(arguments); + + // `super(args, &blk)': MRI evaluates the arguments - #to_a of a splat, #to_hash of a ** + // - before the block argument's #to_proc, which MakeCallWithBlockRetryable computes + // first (for a literal block's retry). So, as for a method call, they are evaluated into + // temporaries up front. + List hoisted = (Block != null && !Block.IsDefinition && Arguments != null) ? new List() : null; if (keywordSplat != null) { - invoke = TransformKeywordSplatCall(gen, blockArgVariable, arguments, keywordSplat); + invoke = TransformKeywordSplatCall(gen, blockArgVariable, arguments, keywordSplat, hoisted); } else { - invoke = TransformCall(gen, blockArgVariable, arguments); + invoke = TransformCall(gen, blockArgVariable, arguments, hoisted); } // block: @@ -86,13 +92,15 @@ public SuperCall(Arguments args, Block block, SourceSpan location, bool argument invoke, blockArgVariable, transformedBlock, - Block != null && Block.IsDefinition + Block != null && Block.IsDefinition, + (hoisted != null && hoisted.Count > 0) ? Ast.Block(typeof(void), hoisted) : null ), "#RB: super call ('" + gen.CurrentMethod.MethodName + "')" ); } - private MSA.Expression/*!*/ TransformCall(AstGenerator/*!*/ gen, MSA.Expression/*!*/ blockArgVariable, Arguments arguments) { + private MSA.Expression/*!*/ TransformCall(AstGenerator/*!*/ gen, MSA.Expression/*!*/ blockArgVariable, Arguments arguments, + List hoisted) { // invoke super member action: var siteBuilder = new CallSiteBuilder(gen, gen.CurrentSelfVariable, blockArgVariable); @@ -118,6 +126,32 @@ public SuperCall(Arguments args, Block block, SourceSpan location, bool argument } else { // this means we are not inside any method scope -> an exception will be thrown at the call site } + } else if (hoisted != null) { + // see TransformReadCore: each argument, and the splat expanded into a fresh array, goes + // into a temporary first (MethodCall does the same for `recv.m(args, &blk)') + var scratch = new CallSiteBuilder(gen, gen.CurrentSelfVariable, blockArgVariable); + arguments.TransformToCall(gen, scratch); + siteBuilder.HasExplicitKeywords = scratch.HasExplicitKeywords; + int index = 0; + foreach (var argument in scratch) { + // skip the scope, the instance and the block + if (index++ < 3) { + continue; + } + var temp = gen.CurrentScope.DefineHiddenVariable("#super-arg", argument.Type); + hoisted.Add(Ast.Assign(temp, argument)); + siteBuilder.Add(temp); + } + if (scratch.SplattedArgument != null) { + var temp = gen.CurrentScope.DefineHiddenVariable("#super-splat", typeof(RubyArray)); + var list = AstUtils.Convert(scratch.SplattedArgument, typeof(IList)); + hoisted.Add(Ast.Assign(temp, scratch.SplattedArgumentIsFresh ? + (MSA.Expression)Methods.TakeFreshSplat.OpCall(list) : + Ast.New(typeof(RubyArray).GetConstructor(new[] { typeof(IList) }), list) + )); + siteBuilder.SplattedArgument = temp; + siteBuilder.SplattedArgumentIsFresh = true; + } } else { arguments.TransformToCall(gen, siteBuilder); } @@ -151,7 +185,7 @@ private static KeywordArgumentSplat TrailingKeywordSplat(Arguments arguments) { /// those are read where they are passed. /// private MSA.Expression/*!*/ TransformKeywordSplatCall(AstGenerator/*!*/ gen, MSA.Expression/*!*/ blockArgVariable, - Arguments/*!*/ arguments, KeywordArgumentSplat/*!*/ keywordSplat) { + Arguments/*!*/ arguments, KeywordArgumentSplat/*!*/ keywordSplat, List hoisted) { var expressions = arguments.Expressions; int count = expressions.Length - 1; @@ -163,21 +197,31 @@ private static KeywordArgumentSplat TrailingKeywordSplat(Arguments arguments) { var expression = expressions[i]; splatted[i] = expression is SplattedArgument; if (splatted[i]) { - var temp = Ast.Variable(typeof(IList), "#super-splat" + i); - temps.Add(temp); + var temp = NewTemp(gen, temps, hoisted, typeof(IList), "#super-splat" + i); body.Add(Ast.Assign(temp, AstUtils.Convert(expression.TransformRead(gen), typeof(IList)))); values[i] = temp; } else if (_argumentsAreImplicit && expression is LocalVariable) { values[i] = AstUtils.Box(expression.TransformRead(gen)); } else { - var temp = Ast.Variable(typeof(object), "#super-arg" + i); - temps.Add(temp); + var temp = NewTemp(gen, temps, hoisted, typeof(object), "#super-arg" + i); body.Add(Ast.Assign(temp, AstUtils.Box(expression.TransformRead(gen)))); values[i] = temp; } } - return MakeKeywordsCall(gen, blockArgVariable, temps, body, values, splatted, keywordSplat.TransformToArgument(gen)); + return MakeKeywordsCall(gen, blockArgVariable, temps, body, values, splatted, keywordSplat.TransformToArgument(gen), hoisted); + } + + // A temporary of the keyword splat call: a local of its own block, or, when the arguments are hoisted + // ahead of the block argument (TransformReadCore), a hidden variable of the scope. + private static MSA.ParameterExpression/*!*/ NewTemp(AstGenerator/*!*/ gen, List/*!*/ temps, + List hoisted, System.Type/*!*/ type, string/*!*/ name) { + if (hoisted != null) { + return gen.CurrentScope.DefineHiddenVariable(name, type); + } + var temp = Ast.Variable(type, name); + temps.Add(temp); + return temp; } #region Parameterless super in eval @@ -301,10 +345,9 @@ private Arguments EvalImplicitArguments(AstGenerator/*!*/ gen) { /// private MSA.Expression/*!*/ MakeKeywordsCall(AstGenerator/*!*/ gen, MSA.Expression/*!*/ blockArgVariable, List/*!*/ temps, List/*!*/ body, MSA.Expression/*!*/[]/*!*/ values, - bool[]/*!*/ splatted, MSA.Expression/*!*/ keywordsValue) { + bool[]/*!*/ splatted, MSA.Expression/*!*/ keywordsValue, List hoisted) { - var keywords = Ast.Variable(typeof(Hash), "#super-keywords"); - temps.Add(keywords); + var keywords = NewTemp(gen, temps, hoisted, typeof(Hash), "#super-keywords"); body.Add(Ast.Assign(keywords, keywordsValue)); // both pass their keywords explicitly - a `**' that passes nothing, or the hash - so a ruby2_keywords hash ending @@ -314,12 +357,18 @@ private Arguments EvalImplicitArguments(AstGenerator/*!*/ gen) { var with = new CallSiteBuilder(gen, gen.CurrentSelfVariable, blockArgVariable) { HasExplicitKeywords = true }; AddArguments(with, values, splatted, keywords); - body.Add(Ast.Condition( + var call = Ast.Condition( Ast.ReferenceEqual(keywords, AstUtils.Constant(null)), AstUtils.Convert(without.MakeSuperCallAction(gen.CurrentFrame.UniqueId, _argumentsAreImplicit), typeof(object)), AstUtils.Convert(with.MakeSuperCallAction(gen.CurrentFrame.UniqueId, _argumentsAreImplicit), typeof(object)), typeof(object) - )); + ); + if (hoisted != null) { + // the arguments and the keywords are evaluated ahead of the block argument; the call is what is left + hoisted.AddRange(body); + return call; + } + body.Add(call); return Ast.Block(typeof(object), temps, body); } From 8b82ec85ff9d56caad36671bdd457641a7816596 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:58:42 +0000 Subject: [PATCH 387/439] cruby-test: baseline after round eight test_defined, test_alias, test_autoload, test_call, test_super, test_keyword, test_method, test_module, test_proc and test_syntax swept again on top of round seven's baseline: 6,678 passing. Four tests were fixed; test_alias's test_alias_memory_leak (an RSS-ratio test, see PACKAGES.md) and test_autoload's test_autoload_same_file (a timeout that also comes and goes on the base build) failed this time. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index b809bb71c..fb5eef9ac 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,676 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,678 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 6a7aa0cb6..c75fbff04 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -1,4 +1,4 @@ -test_alias 18 tests 1 failures 0 errors 0 skips +test_alias 18 tests 0 failures 1 errors 0 skips test_allocation 76 tests 0 failures 76 errors 0 skips test_argf 73 tests 18 failures 1 errors 1 skips test_arithmetic_sequence 37 tests 0 failures 0 errors 0 skips @@ -6,13 +6,13 @@ test_arity 3 tests 0 failures 0 errors 0 sk test_array 493 tests 0 failures 16 errors 2 skips test_assignment 29 tests 0 failures 0 errors 0 skips test_ast 2666 tests 11 failures 2654 errors 0 skips -test_autoload 27 tests 1 failures 1 errors 0 skips +test_autoload 27 tests 0 failures 2 errors 0 skips test_backtrace 31 tests 4 failures 0 errors 0 skips test_basicinstructions 26 tests 0 failures 0 errors 0 skips test_beginendblock 16 tests 4 failures 1 errors 0 skips test_bignum 73 tests 1 failures 2 errors 0 skips test_box 65 tests 5 failures 22 errors 31 skips -test_call 65 tests 2 failures 0 errors 0 skips +test_call 65 tests 1 failures 0 errors 0 skips test_case 6 tests 0 failures 0 errors 0 skips test_class 62 tests 2 failures 1 errors 0 skips test_clone 7 tests 0 failures 0 errors 0 skips @@ -26,7 +26,7 @@ test_const 5 tests 0 failures 0 errors 0 sk test_continuation 7 tests 0 failures 3 errors 0 skips test_data 16 tests 0 failures 0 errors 0 skips test_default_gems 1 tests 0 failures 0 errors 0 skips -test_defined 39 tests 3 failures 1 errors 0 skips +test_defined 39 tests 3 failures 0 errors 0 skips test_dir 38 tests 0 failures 2 errors 0 skips test_dir_m17n 22 tests 7 failures 0 errors 0 skips test_dup 6 tests 0 failures 0 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 69 clean, 72 with failures, 1 without a summary -10369 tests, 2552025 assertions, 492 failures, 3131 errors, 70 skips; 6676 passing +10369 tests, 2552019 assertions, 489 failures, 3132 errors, 70 skips; 6678 passing From 5dbf6260498a54a1388f45eb7756808573c0a9b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:02:24 +0000 Subject: [PATCH 388/439] Compile the startup library's defs with a loop from source where OSR is on (gap 18) The startup library (IronRuby.Startup.dll), which the R2R host and the release downloads run, is compiled with SavePath set, and that turns off OSR outlining (AstGenerator.CanReplaceLoops: an OsrLoopSite is a runtime object). Every while/until loop in the prelude, rubygems and the other startup files therefore ran in generic code for good, and the compiled copies of the prelude's loops (stage 3a's sum, take_while, drop_while) never ran on the host users get. With the library, against the same host with IR_STARTUP_DLL=none (ab.rb, core-small): sum with a block 1.37 times slower, take_while 1.16, drop_while 1.12, inject 1.11, each_slice 1.10. The AOT compiler now marks a def that has a loop in its body or in a block in it (WhileFinder, CreateMethodBody's hasLoops), and RubyMethodBody compiles such a def from its source at its first call where OSR is on, through the path that a mislabelled def already takes (PrecompiledCode.ParseDefinition, which checks the file's hash). The compiled body still serves -X:NoOSR and an edited file. R2R, base / new: sum_blk 804 -> 613 ns, take_while 376 -> 328, drop_while 406 -> 332, the rest within noise. `ir -e 1` compiles no def from source, and startup is the same within noise. Census unchanged. check-startup.sh: as on base, except that its thread-backtrace rows get Kernel#loop back. The yield-loop, array-sum, osr-array, block-loop, jit and parked-iterator matrices and ruby/spec core (9 suites, 11,733 examples) give the same results on the R2R host as base, and the whole IronRuby.Tests suite (Debug) passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6g69LY1MArBPyLTVu --- Src/Ruby/Runtime/Calls/RubyMethodBody.cs | 17 +++++++++--- Src/Ruby/Runtime/PrecompiledCode.cs | 17 +++++++++--- Util/aot/IronRuby.Aot/AotCompiler.cs | 33 ++++++++++++++++++++++-- Util/aot/README.md | 8 ++++++ Util/perf/LEDGER.md | 26 +++++++++++++++++++ 5 files changed, 93 insertions(+), 8 deletions(-) diff --git a/Src/Ruby/Runtime/Calls/RubyMethodBody.cs b/Src/Ruby/Runtime/Calls/RubyMethodBody.cs index 11a1ef4c5..7728910b3 100644 --- a/Src/Ruby/Runtime/Calls/RubyMethodBody.cs +++ b/Src/Ruby/Runtime/Calls/RubyMethodBody.cs @@ -59,12 +59,16 @@ internal RubyMethodBody(MethodDeclaration/*!*/ ast, MSA.SymbolDocumentInfo docum // The label the precompiled body's frames carry, which the compiler worked out from the lexical nesting (see Compile). private readonly string _precompiledLabel; + // The precompiled def has a `while' or `until' loop, which its compiled body runs without OSR (see Compile). + private readonly bool _precompiledLoops; + internal RubyMethodBody(MethodDeclaration/*!*/ header, MSA.SymbolDocumentInfo document, RubyEncoding/*!*/ encoding, - Func/*!*/ precompiled, string jitSource, string label) + Func/*!*/ precompiled, string jitSource, string label, bool hasLoops) : this(header, document, encoding, (LineCoverage)null) { _precompiled = precompiled; _jitSource = jitSource; _precompiledLabel = label; + _precompiledLoops = hasLoops; } /// @@ -483,9 +487,16 @@ private Delegate FromModuleFactory(RubyScope/*!*/ declaringScope, RubyModule/*!* // - the singleton copy module_function makes (or the instance one), a def in class_eval or in a block - is // compiled from its source, as it is without the library, so that its frames are labelled after the module // the runtime gives it ("FileUtils.mkdir_p" or "FileUtils#mkdir_p"). - if (_precompiledLabel != null && _precompiledLabel != MethodDeclaration.QualifyFrameLabel(_ast.Name, declaringModule)) { + // A def with a loop likewise where OSR is on: code saved to disk outlines no loop (an OsrLoopSite is a runtime + // object, AstGenerator.CanReplaceLoops), so the library's body would run its loops in generic code for good - + // the prelude's Array#sum with a block and take_while, their loops' compiled copies left out, were 1.37 and 1.16 + // times slower with the library than without it (four elements). + if ((_precompiledLoops && declaringScope.RubyContext.RubyOptions.Osr) || + (_precompiledLabel != null && _precompiledLabel != MethodDeclaration.QualifyFrameLabel(_ast.Name, declaringModule))) { var source = Precompiled.PrecompiledCode.ParseDefinition(declaringScope.RubyContext, _ast, _encoding, - _document != null ? _document.FileName : null); + _document != null ? _document.FileName : null, + _precompiledLoops && declaringScope.RubyContext.RubyOptions.Osr ? "it has a loop, and OSR is on" : + "it runs for another module than its compiled frame label says"); if (source != null) { return CompileFromSyntaxTree(source, declaringScope, declaringModule); } diff --git a/Src/Ruby/Runtime/PrecompiledCode.cs b/Src/Ruby/Runtime/PrecompiledCode.cs index 5a83451be..039bf3277 100644 --- a/Src/Ruby/Runtime/PrecompiledCode.cs +++ b/Src/Ruby/Runtime/PrecompiledCode.cs @@ -248,8 +248,19 @@ private static SourceSpan Span(int[]/*!*/ s) { /// public static RubyMethodBody/*!*/ CreateMethodBody(MethodDefinition/*!*/ header, string documentPath, RubyEncoding/*!*/ encoding, Func/*!*/ factory, string jitSource, string label) { + return CreateMethodBody(header, documentPath, encoding, factory, jitSource, label, false); + } + + /// + /// : the def has a `while' or `until' loop, which the library's code runs without OSR (the + /// compiler outlines no loop into code saved to disk: an OsrLoopSite is a runtime object). Where OSR is on, the def is + /// compiled from its source at its first call instead (RubyMethodBody.Compile), so that its loops get their compiled + /// copies as without the library. + /// + public static RubyMethodBody/*!*/ CreateMethodBody(MethodDefinition/*!*/ header, string documentPath, RubyEncoding/*!*/ encoding, + Func/*!*/ factory, string jitSource, string label, bool hasLoops) { var document = documentPath != null ? MSA.Expression.SymbolDocument(documentPath) : null; - return new RubyMethodBody(header, document, encoding, factory, jitSource, label); + return new RubyMethodBody(header, document, encoding, factory, jitSource, label, hasLoops); } /// @@ -343,7 +354,7 @@ internal static string MagicComments(byte[]/*!*/ code) { /// UTF-8 source, whose bytes the def's location indexes. Null if not. /// internal static MethodDefinition ParseDefinition(RubyContext/*!*/ context, MethodDefinition/*!*/ header, RubyEncoding/*!*/ encoding, - string path) { + string path, string why) { string hash; if (path == null || encoding != RubyEncoding.UTF8 || _fileHashes == null || !_fileHashes.TryGetValue(path, out hash)) { return null; @@ -379,7 +390,7 @@ internal static MethodDefinition ParseDefinition(RubyContext/*!*/ context, Metho } if (Trace) { Console.Error.WriteLine("IronRuby.Startup: compiles `def " + header.Name + "' (" + path + ":" + header.Location.Start.Line + - ") from source: it runs for another module than its compiled frame label says"); + ") from source: " + why); } return ParseMethod(context, magicComments, text, header, path); } diff --git a/Util/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index f331d3b61..153499221 100644 --- a/Util/aot/IronRuby.Aot/AotCompiler.cs +++ b/Util/aot/IronRuby.Aot/AotCompiler.cs @@ -1259,11 +1259,17 @@ private Expression SerializeMethodBody(RubyMethodBody body) { Expression.Constant(ps.Unsplat != null ? ((LocalVariable)ps.Unsplat).Name : null, typeof(string)), Expression.Constant(ps.Block?.Name, typeof(string)), SerializeSignature(ps.Signature)); + // A def with a loop is compiled from its source at run time where OSR is on (RubyMethodBody.Compile): this + // compilation has none of the loops' OSR sites, which hold runtime objects. Its compiled body still serves + // -X:NoOSR, and a file edited since this compilation, whose defs are not parsed from it. + bool hasLoops = WhileFinder.HasLoop(ast); + if (hasLoops) Count("method bodies with a loop, compiled from source where OSR is on"); return Expression.Call(typeof(PrecompiledCode).GetMethod("CreateMethodBody", - new[] { typeof(MethodDefinition), typeof(string), typeof(RubyEncoding), typeof(Func), typeof(string), typeof(string) }), + new[] { typeof(MethodDefinition), typeof(string), typeof(RubyEncoding), typeof(Func), typeof(string), typeof(string), typeof(bool) }), header, StringExpression(body.Document?.FileName), ConstantField(AotHost.GetEncoding(body), typeof(RubyEncoding)), factory, - Expression.Constant(JitSource(body, ast), typeof(string)), Expression.Constant(label, typeof(string))); + Expression.Constant(JitSource(body, ast), typeof(string)), Expression.Constant(label, typeof(string)), + Expression.Constant(hasLoops)); } /// @@ -1457,6 +1463,29 @@ public override bool Enter(MethodCall node) { } } + // a `while' or `until' loop in a def's body or in a block in it, not in a nested def (see SerializeMethodBody) + private sealed class WhileFinder : Walker { + public bool Found; + + public static bool HasLoop(MethodDefinition def) { + var finder = new WhileFinder(); + def.Body.Walk(finder); + return finder.Found; + } + + public override bool Enter(WhileLoopExpression node) { + Found = true; + return false; + } + + public override bool Enter(MethodDefinition node) => false; + + public override bool Enter(MethodCall node) { + if (node.Block is BlockDefinition block) block.Walk(this); + return !Found; + } + } + // the modules `extend M' names, by their last segment private sealed class ExtendWalker : Walker { private readonly HashSet _names; diff --git a/Util/aot/README.md b/Util/aot/README.md index d3808a52d..adecd0b8f 100644 --- a/Util/aot/README.md +++ b/Util/aot/README.md @@ -469,6 +469,14 @@ How it stays correct: and `FileUtils#mkdir_p` for the included copy). `IR_STARTUP_DLL_TRACE=1` says which defs are compiled from source; `ir -e 1`, `require "set"`/`"json"` and requiring optparse, time, tempfile, pp, fileutils, date, stringio, strscan, delegate, tmpdir and io/console compile none. +- Loops. The compiler outlines no loop into saved code (`SavePath` turns `AstGenerator.CanReplaceLoops` + off: an OSR site is a runtime object), so a compiled `while` or `until` ran in generic code for good, + and the prelude's loops that have compiled copies were slower with the library than without it + (`Array#sum` with a block 1.37 times, `take_while` 1.16, `drop_while` 1.12, four elements). A def + with such a loop (in its body or in a block in it) is marked, and where OSR is on `RubyMethodBody` + compiles it from its source at its first call, the same way as above; its compiled body serves + `-X:NoOSR` and a source that no longer matches. `ir -e 1` compiles none of them; requiring set and + json, three. `IR_STARTUP_DLL_TRACE=1` names them ("it has a loop, and OSR is on"). - Other threads' backtraces (`Thread#backtrace`, `#backtrace_locations`) are built from the interpreter's frame chain, because .NET cannot walk another thread's stack, and precompiled code is compiled code from its first call. Without help, `Kernel#loop`, `Set#each` and diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index c663d79d4..264e7e54a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,32 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/aotosr (2026-11-29) - the startup library's defs with a loop are compiled from source where OSR is on (gap 18 + on the shipped host)** - not gated. The R2R host (what `./ir.sh` picks when it is newest, and the release download) + runs the startup library, IronRuby.Startup.dll, which the compiler makes with `SavePath` set: `AstGenerator. + CanReplaceLoops` is false there (an OsrLoopSite is a runtime object), so every `while`/`until` in ruby4.rb, + rubygems and the rest ran in generic code for good, and stage 3a's copies (sum, take_while, drop_while) never ran on + the host users get. Measured first (`ab.rb -r 3`, core-small, four elements, the R2R host with the library / with + `IR_STARTUP_DLL=none`): `sum_blk` 1.37, `take_while` 1.16, `drop_while` 1.12, `inject` 1.11, `each_slice` 1.10, the + rest within noise. The AOT compiler now marks a def with a loop in its body or in a block in it (`WhileFinder`, + `CreateMethodBody(..., hasLoops)`), and `RubyMethodBody.Compile` compiles such a def from its source at its first + call where OSR is on, through the path that a mislabelled def already takes (`PrecompiledCode.ParseDefinition`, + which checks the file's hash); its compiled body still serves `-X:NoOSR` and an edited file. + - Time (`ab.rb -r 4`, R2R, base 8a0f583 / library off / new): `sum_blk` 803.9 / 621.5 / 613.0 (0.76 of base), + `take_while` 375.9 / 312.0 / 327.9 (0.87), `drop_while` 405.5 / 335.9 / 331.9 (0.82), `inject` 0.96, `each_slice` + 0.96 (still 1.09 over the library off); `each`, `times`, `upto`, `sort_by`, `uniq_blk`, `to_h_blk` and eight more + within noise. Startup: `ir -e 1` compiles no def from source (`IR_STARTUP_DLL_TRACE=1`), requiring set and json + three; `ir -e 1` and requiring set, json and optparse, ten runs alternating, the same within noise (454-526 ms + against 468-497). + - Census: 0 methods changed, up or down (it parses sources and never sees the library). + - Checks: `Util/aot/check-startup.sh` - the library matches its sources, the tree copy and the fixtures pass; + startup-checks.rb's thread-backtrace rows differ with the library on base too (base loses `Kernel#loop`, + `Set#each`, `mon_synchronize`, `then`; the change gets `Kernel#loop` back, now compiled from source). On the R2R + host against CRuby, new and base: yield-loop, array-sum, osr-array, block-loop, jit and parked-iterator matrices + identical between the two (array-sum's two Integer#+ rows and block-loop's two `Range#each` frame rows differ from + CRuby on base as well). ruby/spec core array, enumerable, hash, range, integer, string, kernel, struct and set on + the R2R host: 11,733 examples, the same counts on both. IronRuby.Tests (Debug, the whole suite): PASSED. + - **perf/yieldloop3 (2026-11-29) - Array#sum with a block: its Integer case in a loop of its own that the compiled copy runs (gap 18)** - not gated. `__array_sum__`'s loop could not be compiled: its tail has `next`, `return`, calls and a nested `while true` with a second yield. The common case, Integers all along, now has a loop of its own in front of it From 37a65b33a40d48ba95fda5b515fcb2ba8e07116e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:16:26 +0000 Subject: [PATCH 389/439] Errors that rules and a few library methods throw defer their backtrace walk A rescued [].fetch(1) cost 24-29 us against a rescued raise in Ruby's 5-6 (CRuby 1.0 and 0.8). The difference is the catch-site walk of the whole CLR stack, which RubyExceptionData defers until the exception is exposed only for an exception nothing can have kept (RaisedUnkept): Kernel#raise and method_missing mark theirs, no library throw site did, since C# code may keep an exception and hand it to Ruby later. Marked now (RubyExceptionData.Unkept; IR_UNKEPT_LIB=0 restores the old code): every error a call rule throws (MetaObjectBuilder's SetError and SetArityError, each a factory's new exception thrown at once), and the throw sites of Array#fetch's IndexError, String's index errors, MutableString's FrozenError and Protocols' coercion TypeError. Rescued: [].fetch(1) 28.8 -> 4.8 us, a wrong argument count 26.8 -> 4.8, 1 + nil 26.3 -> 4.9, a frozen String's << 27.6 -> 5.2, S[10, 1] = "x" 27.5 -> 5.5. 1 / 0 is the CLR's own DivideByZeroException and stays at 28 us. Util/unkept-matrix.rb (new) checks the backtraces of each marked kind rescued, kept, read through $!, re-raised and dropped against CRuby, with the switch on and off and the JIT on and off. Also checked: eight exception and backtrace matrices in every mode (49 same), ruby/spec exception, rescue and the methods involved (516 examples) and language in full, IronRuby.Tests on Debug (passed). The census is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Libraries/Builtins/MutableStringOps.cs | 10 +++--- Src/Libraries/Extensions/IListOps.cs | 4 +-- Src/Ruby/Builtins/MutableString.cs | 4 +-- Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs | 8 ++++- Src/Ruby/Runtime/Protocols.cs | 10 +++--- Src/Ruby/Runtime/RubyExceptionData.cs | 8 +++++ Util/perf/LEDGER.md | 30 ++++++++++++++++ Util/unkept-matrix.rb | 39 +++++++++++++++++++++ 8 files changed, 98 insertions(+), 15 deletions(-) create mode 100644 Util/unkept-matrix.rb diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 52e85170b..7bda8248a 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -163,7 +163,7 @@ internal static int NormalizeInsertIndex(int index, int length) { int result = index < 0 ? index + length + 1 : index; if (result > length || result < 0) { // MRI inserts before index + 1 for a negative index and reports that one - throw RubyExceptions.CreateIndexError("index {0} out of string", index < 0 ? index + 1 : index); + throw RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of string", index < 0 ? index + 1 : index)); } return result; } @@ -1453,7 +1453,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index int count = self.GetByteCount(); int at = index < 0 ? index + count : index; if (at < 0 || at >= count) { - throw RubyExceptions.CreateIndexError("index {0} out of string", index); + throw RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of string", index)); } self.SetByte(at, unchecked((byte)value)); // MRI answers the value that was written, not the receiver. @@ -1469,7 +1469,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); } self.RequireNotFrozen(); - throw RubyExceptions.CreateIndexError("index {0} out of string", index); + throw RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of string", index)); } // MRI's rb_str_setbyte takes the low byte of any Integer (rb_int_and(value, 0xff)). @@ -1522,7 +1522,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index // Appending at the very end is allowed, which is the only way "" can be assigned to. if (at < 0 || at > length) { // MRI quotes the index as it was given - throw RubyExceptions.CreateIndexError("index {0} out of string", index); + throw RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of string", index)); } if (at == length) { @@ -1552,7 +1552,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index int length = GetCharacterLength(self); if (System.Math.Abs((long)start) > length) { - throw RubyExceptions.CreateIndexError("index {0} out of string", start); + throw RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of string", start)); } start = start < 0 ? start + length : start; diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index 8416d7930..784c7645b 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -1516,8 +1516,8 @@ public static object Fetch( if (defaultValue == Missing.Value) { // MRI: [1].fetch(5) => "index 5 outside of array bounds: -1...1" - throw RubyExceptions.CreateIndexError("index {0} outside of array bounds: {1}...{2}", - originalIndex, -list.Count, list.Count); + throw RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} outside of array bounds: {1}...{2}", + originalIndex, -list.Count, list.Count)); } return defaultValue; } diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index 8905c3f5a..3ec3cb18f 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -600,7 +600,7 @@ public bool DetectSingleByteCharacters() { /// private uint FrozenOrCopyOnWrite(uint flags, int appendCount = 0) { if ((flags & IsFrozenFlag) != 0) { - throw RubyExceptions.CreateStringFrozenError(this); + throw RubyExceptionData.Unkept(RubyExceptions.CreateStringFrozenError(this)); } if ((flags & IsTemporarilyLockedFlag) != 0) { @@ -1265,7 +1265,7 @@ public bool IsInterned { public void RequireNotFrozen() { if (IsFrozen) { - throw RubyExceptions.CreateStringFrozenError(this); + throw RubyExceptionData.Unkept(RubyExceptions.CreateStringFrozenError(this)); } } diff --git a/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs b/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs index 68baaee54..d5bb53cf3 100644 --- a/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs +++ b/Src/Ruby/Runtime/Calls/MetaObjectBuilder.cs @@ -115,7 +115,13 @@ public bool TreatRestrictionsAsConditions { Debug.Assert(ControlFlowBuilder == null, "Control flow required but not built"); var restrictions = _restrictions; - var expr = _error ? Ast.Throw(_result, returnType) : AstUtils.Convert(_result, returnType); + // A rule's error is made by its factory and thrown at once, so nothing can have kept it: its catch-site walk may wait for it + // to be exposed (RubyExceptionData.MarkUnkept; perf/unkept: a rescued arity error was 26 us, a raise in Ruby 5) + var expr = _error + ? Ast.Throw(RubyExceptionData.UnkeptLibraryErrors + ? Ast.Call(typeof(RubyExceptionData).GetMethod("MarkUnkept"), AstUtils.Convert(_result, typeof(Exception))) + : _result, returnType) + : AstUtils.Convert(_result, returnType); if (_condition != null) { var deferral = binder.GetUpdateExpression(returnType); diff --git a/Src/Ruby/Runtime/Protocols.cs b/Src/Ruby/Runtime/Protocols.cs index b128a35d7..58fe6d3b7 100644 --- a/Src/Ruby/Runtime/Protocols.cs +++ b/Src/Ruby/Runtime/Protocols.cs @@ -541,7 +541,7 @@ public static object CoerceAndApply(BinaryOpStorage/*!*/ coercionStorage, Binary return result; } - throw RubyExceptions.MakeCoercionError(coercionStorage.Context, other, self); + throw RubyExceptionData.Unkept(RubyExceptions.MakeCoercionError(coercionStorage.Context, other, self)); } /// @@ -583,7 +583,7 @@ public static object CoerceAndApplyBitwise(BinaryOpStorage/*!*/ coercionStorage, IList pair; var context = coercionStorage.Context; if (!TryCoerce(coercionStorage, self, other, out pair)) { - throw RubyExceptions.MakeCoercionError(context, other, self); + throw RubyExceptionData.Unkept(RubyExceptions.MakeCoercionError(context, other, self)); } // rb_check_funcall: an operator the receiver does not define still goes to its method_missing, unless @@ -593,11 +593,11 @@ public static object CoerceAndApplyBitwise(BinaryOpStorage/*!*/ coercionStorage, if (!defined) { var missing = context.GetImmediateClassOf(pair[0]).ResolveMethod("method_missing", VisibilityContext.AllVisible); if (!missing.Found || (missing.Info.DeclaringModule == context.BasicObjectClass && missing.Info is RubyLibraryMethodInfo)) { - throw RubyExceptions.MakeCoercionError(context, other, self); + throw RubyExceptionData.Unkept(RubyExceptions.MakeCoercionError(context, other, self)); } // (the context's own respond_to? site: binaryOpStorage holds one site, which is the operator's) if (HasUserDefinedRespondTo(context, pair[0]) && !context.RespondTo(pair[0], binaryOp)) { - throw RubyExceptions.MakeCoercionError(context, other, self); + throw RubyExceptionData.Unkept(RubyExceptions.MakeCoercionError(context, other, self)); } } @@ -615,7 +615,7 @@ public static object CoerceAndApplyBitwise(BinaryOpStorage/*!*/ coercionStorage, try { return opSite.Target(opSite, pair[0], pair[1]); } catch (MissingMethodException e) when (!defined && IsUndefinedMethod(context, e, binaryOp, pair[0])) { - throw RubyExceptions.MakeCoercionError(context, other, self); + throw RubyExceptionData.Unkept(RubyExceptions.MakeCoercionError(context, other, self)); } } } diff --git a/Src/Ruby/Runtime/RubyExceptionData.cs b/Src/Ruby/Runtime/RubyExceptionData.cs index ecce0219e..ec831e863 100644 --- a/Src/Ruby/Runtime/RubyExceptionData.cs +++ b/Src/Ruby/Runtime/RubyExceptionData.cs @@ -80,6 +80,14 @@ private static bool IsBuiltinConstruction(RubyContext/*!*/ context, RubyClass/*! /// have kept (): its catch-site walk may then wait for it to be exposed, as that of an /// exception Kernel#raise made does. Only for a throw site that keeps no reference to the exception. /// + /// IR_UNKEPT_LIB=0: a rule's error and the throw sites marked in perf/unkept are walked for at once, as before. + public static readonly bool UnkeptLibraryErrors = Environment.GetEnvironmentVariable("IR_UNKEPT_LIB") != "0"; + + /// MarkUnkept for a throw site of a library method, under . + public static Exception/*!*/ Unkept(Exception/*!*/ exception) { + return UnkeptLibraryErrors ? MarkUnkept(exception) : exception; + } + public static Exception/*!*/ MarkUnkept(Exception/*!*/ exception) { GetInstance(exception).RaisedUnkept = true; return exception; diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index f0fd56ac1..661f4c10f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1364,6 +1364,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has methods, not the 461 the census used to say, all cold wrappers whose rescued part is a call; a handler as a deopt can take only a call-free protected part (1 method). Left: a handler emitted in the typed body, worth it only once a run shows hot methods needing it. + perf/unkept (2026-11-29, see Landed): an error a library method or a call rule throws was 26-29 us rescued against a + raise in Ruby's 5-6 (CRuby 0.9-1.8): only an exception Kernel#raise made could defer its catch-site walk. Rule errors + (arity, method missing...) and the throw sites of `Array#fetch`, `String#[]=`, a frozen String and a failed numeric + coercion are now 4.7-5.5 us. Left: `1 / 0` (the CLR's own DivideByZeroException, 28.7 us) and the other library throw + sites, each a `RubyExceptionData.Unkept(...)` at a site that throws what it has just made. 23. **A method made by `define_method` is called at 2.3 times CRuby's time** (64 against 28 ns; a `def` of the same body 31; YJIT 2-5 ns): the method JIT takes no block as a method body. Rails-style code defines most of its small methods this way. @@ -2043,6 +2048,31 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/unkept (round thirty-seven, 2026-11-29) - errors that rules and a few library methods throw defer their catch-site + walk, as Kernel#raise's do (gap 22)** - time, not gated. A rescued `[].fetch(1)` cost 23.8-28.8 us against a rescued + `raise` in Ruby's 5.4-6.0 (CRuby 1.0 and 0.8). dotnet-trace (sampled thread time): `StackTrace..ctor` and + `StackFrameHelper.InitializeSourceInfo` under `CanRescueDeferTrace` -> `CaptureExceptionTrace` -> `CaptureTrace`, the eager + catch-site walk of the whole CLR stack. Deferring that walk until the exception is exposed (`TryDeferCatchSite`) is only for an + exception nothing can have kept (`RaisedUnkept`), which Kernel#raise and method_missing mark and no library throw site did: + C# code may keep an exception and hand it to Ruby later (`Encoding::Converter#last_error`, MiniSsl, Yajl, MessagePack, Fiddle, + OpenSSL callbacks, the C API, a thread's pending exception), so the default stays as it is. Now marked + (`RubyExceptionData.Unkept`, `IR_UNKEPT_LIB=0` for the old code): every error a call rule throws (`MetaObjectBuilder`'s + `SetError`/`SetArityError`, all of them a factory's new exception thrown at once: arity, NoMethodError, private and protected + calls, conversions, allocators), and the throw sites of `Array#fetch`'s IndexError, `String`'s index errors (five), + `MutableString`'s FrozenError (two) and `Protocols`' coercion TypeError (five) - each throws what it has just made. Per + rescued raise (`craise.rb`, best of five of 50,000, us, off/on; CRuby): `[].fetch(1)` 28.8/4.8 (1.2), `S[10, 1] = "x"` + 27.5/5.5 (1.2), a wrong argument count 26.8/4.8 (7.4), `1 + nil` 26.3/4.9 (1.6), a frozen String's `<<` 27.6/5.2 (1.8); + unchanged: `{}.fetch` 5.3, `Integer("zz")` 4.8, `nil.foo` 4.6, `raise` 5.9, `1 / 0` 28.1/28.6 (the CLR's own + DivideByZeroException: no throw site to mark). Census: no method changed (runtime only). Checked: `Util/unkept-matrix.rb` + (new: each marked kind raised one and three frames deep and through a block, rescued and dropped, rescued with `=> e`, kept + and read after its frame returned, read through `$!` in an ensure, re-raised bare, two hundred dropped and then one read) + with CRuby's output, the switch on and off, with and without the JIT (CRuby 4.0 leaves `String#<<` out of a frozen error's + backtrace and IronRuby shows it, with or without this change: the matrix leaves that frame out); caller, errinfo, jit-raise, + jit-rescue, raise, rescue-light, set-backtrace and thread-backtrace in the six modes and with the switch off: PASS, 49 same; + ruby/spec core/exception, core/array/fetch, core/string/element_set and append, core/kernel/raise, core/integer/plus, + language/rescue and ensure: 516 examples, no failure on either build; ruby/spec language in full: 2935 examples, the one + known error. IronRuby.Tests in full on Debug: PASSED. + - **perf/ignoredblock (round thirty-seven, 2026-11-29) - a literal block given to a method whose typed body ignored it is left reusable (gap 13)** - allocation, not time; not gated. `nb { }` to `def nb; 1; end` never parked: the parked slot's `StageParkedProc` found the literal a plain block nothing had converted (kind `Block`, no flags), since the method JIT's diff --git a/Util/unkept-matrix.rb b/Util/unkept-matrix.rb new file mode 100644 index 000000000..48a744d67 --- /dev/null +++ b/Util/unkept-matrix.rb @@ -0,0 +1,39 @@ +# Backtraces of errors library methods and call rules throw, rescued in every way that reads them or not, against CRuby's +# (perf/unkept: such an error is marked as one nothing can have kept, so its catch-site walk waits until it is exposed). +# +# ruby Util/unkept-matrix.rb > cruby.txt; ./ir.sh Util/unkept-matrix.rb | diff cruby.txt - (also IR_UNKEPT_LIB=0, -X:NoJIT) +# +# The frozen String's backtrace leaves out 'String#<<', which IronRuby shows and CRuby 4.0 does not (a difference older than +# perf/unkept, with or without it). +A = []; S = "abc" +def bt(e) = e.backtrace.reject { |l| l.include?("in 'String#<<'") }.map { |l| l.sub(/^.*\//, '') }.first(6) +def k_fetch = A.fetch(1) +def k_arity = k_fetch(1) +def k_coerce = 1 + nil +def k_frozen = "x".freeze << "y" +def k_strset = (S[10, 1] = "z") +KINDS = %i[k_fetch k_arity k_coerce k_frozen k_strset] +def deep3(m) = deep2(m) +def deep2(m) = deep1(m) +def deep1(m) = send(m) +def drop(m); send(m); rescue StandardError; :dropped; end +def named(m); deep3(m); rescue StandardError => e; [e.class, e.message, bt(e)]; end +def keep(m); deep3(m); rescue StandardError => e; e; end +def via_gvar(m); begin; send(m); ensure; $seen = $! && bt($!); end; rescue StandardError; $seen; end +def reraise_inner(m); send(m); rescue StandardError; raise; end +def reraise(m); reraise_inner(m); rescue StandardError => e; bt(e); end +def in_block(m); [1].each { |_| deep2(m) }; rescue StandardError => e; bt(e); end +def caught_then_other(m); drop(m); raise "later"; rescue => e; bt(e); end +KINDS.each do |m| + p m + p drop(m) + p named(m) + e = keep(m); p bt(e) + p via_gvar(m) + p reraise(m) + p in_block(m) + p caught_then_other(m) + # many in a row, then one looked at + 200.times { drop(m) } + p named(m)[2] +end From 0d15f470f56c1e7ee5ac775b05321ad1a7cb6a25 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:20:59 +0000 Subject: [PATCH 390/439] Marshal.load's proc does not see a wrapped object before its instance variables are read An 'I' record's object was counted finished as soon as it was read, before the instance variables after it. A back-reference to it among them - a String subclass instance whose @v is itself - then ran the proc on it, and Marshal.load(dump, :freeze.to_proc) froze the string before @v was set: FrozenError. MRI keeps the object in partial_objects until r_leave, so the proc sees it only after its ivars. ReadInstanced now takes it out of the finished set while it reads the ivars. Checked against CRuby 4.0.10: TestMarshal::TestMarshalFreezeProc#test_string_subclass_cycle passes; ruby/spec core/marshal unchanged, the marshal matrix the same in every mode. New IronRuby.Tests: Marshal_ProcPartialObject1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 27 +++++++++++++++++++++++++ Src/Libraries/Builtins/Marshal.cs | 7 +++++++ 3 files changed, 35 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 7d78234a8..857e9f8fc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1041,6 +1041,7 @@ public Tests(Driver/*!*/ driver) { Warning_UndefinedWarn1, Warning_InstanceMethods1, Encoding_UnicodeVersion1, + Marshal_ProcPartialObject1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index fec374664..13b9642c2 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10198,6 +10198,33 @@ public void Encoding_UnicodeVersion1() { ""17.0.0"" true # +"); + } + + /// + /// Marshal.load's proc does not see an object an 'I' record wraps until its instance variables are read (MRI's + /// partial_objects): a string whose @v is itself is not frozen by :freeze.to_proc before @v is set + /// (CRuby's TestMarshal::TestMarshalFreezeProc#test_string_subclass_cycle). + /// + public void Marshal_ProcPartialObject1() { + TestOutput(@" +class MyString < String + def initialize(v, *args) + super(*args) + @v = v + end +end +str = MyString.new(10, ""b"") +str.instance_eval { @v = str } +o = Marshal.load(Marshal.dump(str), :freeze.to_proc) +p o.frozen?, o.instance_eval { @v }.equal?(o) +log = [] +Marshal.load(Marshal.dump(str), ->(x) { log << x.class; x }) +p log +", @" +true +true +[TrueClass, MyString] "); } } diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index e0dddf740..e6f295bea 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -2266,7 +2266,14 @@ private RubyArray GetDataMembers(RubyClass/*!*/ dataClass) { SetIVar(obj, ivar.Key, ivar.Value); } } else { + // MRI's partial_objects: what an 'I' record wraps is not finished until its instance + // variables are read, so a reference to it among them - a string whose @v is itself - + // is not handed to the proc, which would freeze it before they are set. + bool wasFinished = objectRef >= 0 && _finished.Remove(objectRef); ReadIVars(obj); + if (wasFinished) { + _finished.Add(objectRef); + } } return obj; } From eb8acc7ef135afafd1fd79e0ee96686157b19f08 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:21:00 +0000 Subject: [PATCH 391/439] Time#_dump and Time._load take any year, as MRI's time_mdump and time_mload do Time#_dump went through DateTime and refused anything outside 1900...2038 ("unable to marshal time"), so Marshal.dump(Time.utc(0)) or of any time before 1900 failed. MRI writes the year field as 1900...1900+0xffff and, for a year outside that, the nearer end there and the distance from it after the eight bytes: its length as a Marshal long, then its bytes little-endian. _dump now computes the UTC reading from the seconds (RubyTime.CivilFromDays) and writes that form; _load reads it back. Checked against CRuby 4.0.10: the dumps of Time.utc(0), 1850, -12345, 99999, 67435 and 67436 are CRuby's byte for byte and load back equal; ruby/spec core/time and core/marshal unchanged, the marshal and time-local matrices the same in every mode. New IronRuby.Tests: Marshal_TimeAnyYear1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 27 +++++++++++ Src/Libraries/Builtins/RubyTimeOps.cs | 62 ++++++++++++++++++++----- 3 files changed, 79 insertions(+), 11 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 857e9f8fc..836227aa4 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1042,6 +1042,7 @@ public Tests(Driver/*!*/ driver) { Warning_InstanceMethods1, Encoding_UnicodeVersion1, Marshal_ProcPartialObject1, + Marshal_TimeAnyYear1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 13b9642c2..5c4e9d416 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10225,6 +10225,33 @@ p log true true [TrueClass, MyString] +"); + } + + /// + /// Time#_dump writes any year, as MRI's time_mdump does: one outside 1900...1900+0xffff is the nearer end in the + /// sixteen bits and the distance from it after the eight bytes; Time._load reads it back. The dumps are CRuby's + /// byte for byte (CRuby's TestMarshal#test_recursive_userdef dumps Time.utc(0)). + /// + public void Marshal_TimeAnyYear1() { + TestOutput(@" +[Time.utc(0), Time.utc(1850, 3, 4, 5, 6, 7), Time.utc(-12345, 6), Time.utc(99999, 12, 31, 23, 59, 59), Time.utc(2000, 1, 2, 3, 4, 5.5), Time.at(-1e10).utc, Time.utc(1899, 12, 31), Time.utc(67435, 1, 1), Time.utc(67436, 1, 1)].each do |t| + d = Marshal.dump(t) + l = Marshal.load(d) + p [d.unpack1(""H*""), l, l == t] +end +p Marshal.load(Marshal.dump(Time.new(1800, 1, 1, 0, 0, 0, ""+05:00""))) +", @" +[""040849753a0954696d6510200000c000000000076c07063a097a6f6e65492208555443063a064546"", 0000-01-01 00:00:00 UTC, true] +[""040849753a0954696d650f850800c0000070180632063a097a6f6e65492208555443063a064546"", 1850-03-04 05:06:07 UTC, true] +[""040849753a0954696d6510201400c00000000007a537063a097a6f6e65492208555443063a064546"", -12345-06-01 00:00:00 UTC, true] +[""040849753a0954696d6510f7efffff0000b0ef07347f063a097a6f6e65492208555443063a064546"", 99999-12-31 23:59:59 UTC, true] +[""040849753a0954696d650d430019c020a15710063a097a6f6e65492208555443063a064546"", 2000-01-02 03:04:05.5 UTC, true] +[""040849753a0954696d650f460500c00000403506f7063a097a6f6e65492208555443063a064546"", 1653-02-10 06:13:20 UTC, true] +[""040849753a0954696d650fe02f00c0000000000601063a097a6f6e65492208555443063a064546"", 1899-12-31 00:00:00 UTC, true] +[""040849753a0954696d650d20c0ffff00000000063a097a6f6e65492208555443063a064546"", 67435-01-01 00:00:00 UTC, true] +[""040849753a0954696d650f20c0ffff000000000601063a097a6f6e65492208555443063a064546"", 67436-01-01 00:00:00 UTC, true] +1800-01-01 00:00:00 +0500 "); } } diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index f266190da..4018ce8b4 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -1098,28 +1098,52 @@ private static int GetYear(RubyContext/*!*/ context, object[]/*!*/ components, i [RubyMethod("_dump", RubyMethodAttributes.PrivateInstance)] public static MutableString/*!*/ Dump(RubyContext/*!*/ context, RubyTime/*!*/ self, [Optional]int depth) { - DateTime value = self.UtcDateTime; - if (value.Year < 1900 || value.Year > 2038) { - throw RubyExceptions.CreateTypeError("unable to marshal time"); + // The UTC reading, from the seconds themselves: DateTime knows neither year 0 nor a year + // past 9999, and MRI's time_mdump takes any year. + long seconds = self.Seconds; + long days = RubyTime.FloorDiv(seconds, 86400); + int secondOfDay = (int)(seconds - days * 86400); + long year; + int month, day; + RubyTime.CivilFromDays(days, out year, out month, out day); + + // The sixteen bits of the year hold 1900 to 1900+0xffff. A year outside them is written + // as the nearer end, and the distance from it follows the eight bytes: its length as a + // Marshal long, then its bytes, little-endian, as time_mdump appends them. + const long maxYear = 1900 + 0xffff; + long fieldYear = year; + long yearExtend = 0; + if (year > maxYear) { + yearExtend = year - maxYear; + fieldYear = maxYear; + } else if (year < 1900) { + yearExtend = 1900 - year; + fieldYear = 1900; } // Little Endian // 32 | 32 | // minute:6|second:6|usec:20|1|utc:1|year:16|month:4|day:5|hour:5| uint dword1 = self.IsUtc ? 0xC0000000 : 0x80000000; - dword1 |= (unchecked((uint)(value.Year - 1900)) << 14); - dword1 |= (unchecked((uint)(value.Month - 1)) << 10); - dword1 |= ((uint)value.Day << 5); - dword1 |= ((uint)value.Hour); + dword1 |= (unchecked((uint)(fieldYear - 1900)) << 14); + dword1 |= (unchecked((uint)(month - 1)) << 10); + dword1 |= ((uint)day << 5); + dword1 |= ((uint)(secondOfDay / 3600)); uint dword2 = 0; - dword2 |= ((uint)value.Minute << 26); - dword2 |= ((uint)value.Second << 20); + dword2 |= ((uint)((secondOfDay / 60) % 60) << 26); + dword2 |= ((uint)(secondOfDay % 60) << 20); dword2 |= ((uint)self.Microseconds); MemoryStream buf = new MemoryStream(8); RubyEncoder.Write(buf, dword1, !BitConverter.IsLittleEndian); RubyEncoder.Write(buf, dword2, !BitConverter.IsLittleEndian); + if (yearExtend != 0) { + byte[] extend = new BigInteger(yearExtend).ToByteArray(isUnsigned: true, isBigEndian: false); + // a length under 123 is one byte, the length plus 5 (ruby_marshal_write_long) + buf.WriteByte((byte)(extend.Length + 5)); + buf.Write(extend, 0, extend.Length); + } var result = MutableString.CreateBinary(buf.ToArray()); // The time's own instance variables travel on the string as well: Marshal writes the @@ -1284,7 +1308,7 @@ private static ExactNum ReadSubmicro(RubyContext/*!*/ context, MutableString/*!* [RubyMethod("_load", RubyMethodAttributes.PrivateSingleton)] public static RubyTime/*!*/ Load(RubyContext/*!*/ context, RubyClass/*!*/ self, [NotNull]MutableString/*!*/ time) { byte[] data = time.ConvertToBytes(); - if (data.Length != 8) { + if (data.Length < 8) { throw RubyExceptions.CreateTypeError("marshaled time format differ"); } @@ -1323,7 +1347,23 @@ private static ExactNum ReadSubmicro(RubyContext/*!*/ context, MutableString/*!* hasOffset, offsetSeconds, zoneName))); } else { bool isUtc = (data[3] & 0x40) != 0; - int year = 1900 + (int)((dword1 >> 14) & 0xffff); + long longYear = 1900 + (long)((dword1 >> 14) & 0xffff); + // past the eight bytes: the distance of a year outside 1900...1900+0xffff from the end + // the field names (time_mload), its length a Marshal long and then its bytes + if (data.Length > 8) { + int length = data[8]; + if (length < 6 || length - 5 > data.Length - 9) { + throw RubyExceptions.CreateTypeError("marshaled time format differ"); + } + length -= 5; + var extend = new BigInteger(new ReadOnlySpan(data, 9, length), isUnsigned: true, isBigEndian: false); + BigInteger extended = longYear == 1900 ? longYear - extend : longYear + extend; + if (extended < Int32.MinValue || extended > Int32.MaxValue) { + throw RubyExceptions.CreateTypeError("marshaled time format differ"); + } + longYear = (long)extended; + } + int year = (int)longYear; int month = 1 + (int)((dword1 >> 10) & 0x0f); // the four bits hold 0...15; MRI's time_mload carries a month past December into // the next year (and a dump of Time.utc(2022, 4, 1) by Ruby 3.1 has one) From af6b2f7c1739b730828381e4244bca7059fd8b0a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:21:00 +0000 Subject: [PATCH 392/439] Marshal.dump refuses an object met again among its own _dump string's ivars A Time whose @v is itself sent Marshal.dump into _dump again and again until the process died of a stack overflow: Time#_dump copies the time's instance variables onto its string, and writing those met the time. MRI keeps the objects whose _dump ivars are being written (arg->userdefs) and raises RuntimeError "can't dump recursive object using _dump()"; so does WriteUsingDump now. Checked against CRuby 4.0.10: TestMarshal#test_recursive_userdef passes; ruby/spec core/marshal unchanged. New IronRuby.Tests: Marshal_RecursiveUserDef1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 22 ++++++++++++++++++++++ Src/Libraries/Builtins/Marshal.cs | 18 +++++++++++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 836227aa4..c89ef10e2 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1043,6 +1043,7 @@ public Tests(Driver/*!*/ driver) { Encoding_UnicodeVersion1, Marshal_ProcPartialObject1, Marshal_TimeAnyYear1, + Marshal_RecursiveUserDef1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 5c4e9d416..10d4832a8 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10252,6 +10252,28 @@ p Marshal.load(Marshal.dump(Time.new(1800, 1, 1, 0, 0, 0, ""+05:00""))) [""040849753a0954696d650d20c0ffff00000000063a097a6f6e65492208555443063a064546"", 67435-01-01 00:00:00 UTC, true] [""040849753a0954696d650f20c0ffff000000000601063a097a6f6e65492208555443063a064546"", 67436-01-01 00:00:00 UTC, true] 1800-01-01 00:00:00 +0500 +"); + } + + /// + /// An object met again among the instance variables of its own _dump string is refused, as MRI's arg->userdefs + /// does, rather than dumped without end (CRuby's TestMarshal#test_recursive_userdef). + /// + public void Marshal_RecursiveUserDef1() { + TestOutput(@" +t = Time.utc(2000) +t.instance_eval { @v = t } +begin + Marshal.dump(t) +rescue RuntimeError => e + p e.message +end +u = Time.utc(2001) +u.instance_eval { @w = [1, 2] } +p Marshal.load(Marshal.dump([u, u])).map { |x| x.instance_variable_get(:@w) } +", @" +""can't dump recursive object using _dump()"" +[[1, 2], [1, 2]] "); } } diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index e6f295bea..6fa47799e 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -795,7 +795,15 @@ private void WriteException(Exception/*!*/ exception, string[]/*!*/ instanceName } } + // MRI's arg->userdefs: the objects whose _dump string's instance variables are being written. + // Meeting one of them again among those - a Time whose @v is itself - is a recursion + // MRI refuses, where it would otherwise call _dump without end. + private HashSet _userDefs; + private void WriteUsingDump(object/*!*/ obj) { + if (_userDefs != null && _userDefs.Contains(obj)) { + throw RubyExceptions.CreateRuntimeError("can't dump recursive object using _dump()"); + } MutableString dumpResult = _sites.Dump.Target(_sites.Dump, obj, _recursionLimit) as MutableString; if (dumpResult == null) { throw RubyExceptions.CreateTypeError("_dump() must return string"); @@ -818,7 +826,15 @@ private void WriteUsingDump(object/*!*/ obj) { WriteModuleName(theClass); WriteStringValue(dumpResult); if (hasIVars) { - WriteIVars(dumpResult, resultIVars, resultEncoding); + if (_userDefs == null) { + _userDefs = new HashSet(ReferenceEqualityComparer.Instance); + } + _userDefs.Add(obj); + try { + WriteIVars(dumpResult, resultIVars, resultEncoding); + } finally { + _userDefs.Remove(obj); + } } } From 11e82fe68c4e75e51d74347bdf874d46d618430d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:21:09 +0000 Subject: [PATCH 393/439] cruby-test: baseline after round nine test_marshal, test_time, test_time_tz and test_exception swept again on top of round eight's baseline: 6,680 passing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index fb5eef9ac..e7d592a99 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,678 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,680 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index c75fbff04..feef345d5 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -67,7 +67,7 @@ test_lazy_enumerator 64 tests 0 failures 0 errors 0 sk test_literal 29 tests 1 failures 1 errors 0 skips test_m17n 127 tests 2 failures 0 errors 1 skips test_m17n_comb 82 tests 0 failures 0 errors 0 skips -test_marshal 234 tests 8 failures 3 errors 0 skips +test_marshal 234 tests 7 failures 2 errors 0 skips test_math 34 tests 0 failures 0 errors 0 skips test_memory_view 0 tests 0 failures 0 errors 0 skips test_metaclass 1 tests 0 failures 0 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 69 clean, 72 with failures, 1 without a summary -10369 tests, 2552019 assertions, 489 failures, 3132 errors, 70 skips; 6678 passing +10369 tests, 2552029 assertions, 488 failures, 3131 errors, 70 skips; 6680 passing From baeecdd1c24f40a484ae452f7302d74f9c63da27 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:23:46 +0000 Subject: [PATCH 394/439] Method JIT: s[a..b] and ary[a...b] without a Range A range literal was refused by the method JIT: 47 methods' first refusal, 32 by it alone, nearly all slices (`ref[0..6]`, `@path[1..-1]`, `@buffer[@position...length]`). `x[a..b]` and `x[a...b]` with Integer ends now compile to JitRuntime.RangeSlice: a String of class String sliced by characters, an Array of class Array copied, while String#[] and Array#[] are the library methods, with start and length as CRuby's rb_range_component_beg_len computes them (a start outside the receiver is nil). Any other receiver, a broken String or an Array shrunk mid-copy deopts. An instance-variable end is typed by its profile. Not where a refinement is active. IR_JIT_RANGE_SLICE=0 turns it off. Util/bench/slice-shapes.rb: s[1..-1] 116.1 -> 92.0 ns, a[0...3] 108.6 -> 90.5, @buf[@pos...@lim] 128.3 -> 96.6 (CRuby 113.0, 92.6, 205.6). Census: 25 methods up, none down. Util/jit-slice-matrix.rb (new) and the matrices it touches print CRuby's output in every JIT mode; the String and Array element reference specs and IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 2 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 55 ++++++++++++ Src/Ruby/Runtime/Jit/JitIntrinsics.cs | 48 ++++++++++ Util/bench/slice-shapes.rb | 28 ++++++ Util/jit-slice-matrix.rb | 109 +++++++++++++++++++++++ Util/perf/LEDGER.md | 32 +++++++ 6 files changed, 273 insertions(+), 1 deletion(-) create mode 100644 Util/bench/slice-shapes.rb create mode 100644 Util/jit-slice-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index a08bcd599..d25f85684 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -308,7 +308,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { // deopt), a type or identity test (a class that resolves the method to anything but the library's deopts) and // `x.to_i' of an Integer, nil or a plain decimal String: no Ruby code, no instance variable, nothing but a deopt "IndexInt", "IndexLong", "IndexObj", "IndexIntChecked", "IndexLongChecked", "IndexObjChecked", "HashKeyInt", - "IsKindOf", "ModuleCaseEquals", "DestructuredArray", "ElementOrNil", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", + "IsKindOf", "ModuleCaseEquals", "RangeSlice", "DestructuredArray", "ElementOrNil", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", }; // Integer#abs of an Int32 (widened, so it cannot overflow) and Float#abs (JitCompiler.EmitCall) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index e04f2af5a..4047d3f29 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -2764,6 +2764,52 @@ private bool IsBlockGiven(MethodCall/*!*/ node) { internal static readonly bool SinkBoxedBooleans = Environment.GetEnvironmentVariable("IR_JIT_SINK_BOXED") != "0"; internal static readonly bool ScreenRefusesCall = Environment.GetEnvironmentVariable("IR_JIT_SCREEN_CALL") != "0"; + // IR_JIT_RANGE_SLICE=0 turns EmitRangeSlice off + internal static readonly bool RangeSlices = Environment.GetEnvironmentVariable("IR_JIT_RANGE_SLICE") != "0"; + + /// `x[a..b]', `x[a...b]': one argument, a range literal with both ends, no block. + internal static bool IsRangeSlice(MethodCall/*!*/ node) { + if (!RangeSlices || node.Target == null || node.MethodName != "[]" || node.Block != null) { return false; } + var args = node.Arguments; + if (args == null || args.Expressions.Length != 1) { return false; } + var range = args.Expressions[0] as RangeExpression; + return range != null && range.GetType() == typeof(RangeExpression) && range.Begin != null && range.End != null && + !IsNilLiteral(range.Begin) && !IsNilLiteral(range.End); + } + + private static bool IsNilLiteral(RExpr/*!*/ node) { + var literal = node as Literal; + return literal != null && literal.Value == null; + } + + /// + /// `s[a..b]', `ary[a...b]' with Integer ends (`ref[0..6]', `@path[1..-1]', `@buffer[@position...length]'): String#[] or + /// Array#[] of a Range, without the Range (JitRuntime.RangeSlice). The receiver must be a String or an Array whose + /// class is String or Array itself, under the library method, as StringIndex and IndexInt take theirs; the ends become + /// a start and a length as CRuby's rb_range_component_beg_len makes them, a start outside the receiver giving nil. + /// Any other receiver deopts. An instance variable end is typed by what it held when the body was compiled (NumericIVar, + /// a guarded read); ends the body does not hold as Integers are the generic call's. + /// + private MSA.Expression/*!*/ EmitRangeSlice(MethodCall/*!*/ node, out JT type) { + if (!_refinements.IsEmpty) { throw Bail("[] of a range with refinements active"); } + var range = (RangeExpression)node.Arguments.Expressions[0]; + JT rt; + var recv = Emit(node.Target, out rt); + if (rt != JT.Obj) { throw Bail("[] of a range on a " + rt); } + JT bt, et; + var begin = NumericIVar(range.Begin, Emit(range.Begin, out bt), ref bt); + var end = NumericIVar(range.End, Emit(range.End, out et), ref et); + if (!IsInteger(bt) || !IsInteger(et)) { throw Bail("[] of a range of " + bt + " and " + et); } + var stringClass = KindClass(JitRuntime.KindString); + bool strings = IsPlainLibraryMethod(stringClass, "[]") && IsPublic(stringClass, "[]"); + bool arrays = IsPlainLibraryMethod(ArrayClass, "[]") && IsPublic(ArrayClass, "[]"); + if (!strings && !arrays) { throw Bail("[] is neither String's nor Array's library method"); } + _canDeopt = true; + type = JT.Obj; + return Ast.Call(JitRuntime.M("RangeSlice"), recv, Ast.Convert(begin, typeof(long)), Ast.Convert(end, typeof(long)), + Ast.Constant(range.IsExclusive), Ast.Constant(strings), Ast.Constant(arrays)); + } + // IR_JIT_DEFINED_IVAR=0 turns EmitDefinedInstanceVariable off internal static readonly bool DefinedInstanceVariables = Environment.GetEnvironmentVariable("IR_JIT_DEFINED_IVAR") != "0"; @@ -2912,6 +2958,9 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { // `x.is_a?(C)', `kind_of?', `instance_of?' (EmitTypeTest) if (IsTypeTest(node)) { return EmitTypeTest(node, out type); } + // `s[a..b]', `ary[a...b]' (EmitRangeSlice) + if (IsRangeSlice(node)) { return EmitRangeSlice(node, out type); } + // `defined?(@x)' as a value (EmitDefinedInstanceVariable) if (IsFrozenDefinedInstanceVariable(node)) { return EmitDefinedInstanceVariable((IsDefinedExpression)node.Target, true, out type); } @@ -4631,6 +4680,12 @@ private bool WalkCall(MethodCall/*!*/ node) { var args = node.Arguments; int argc = (args == null) ? 0 : args.Expressions.Length; + if (JitCompiler.IsRangeSlice(node)) { + // `s[a..b]' (JitCompiler.EmitRangeSlice): the ends are Integers or the body bails + var sliceRange = (RangeExpression)args.Expressions[0]; + return Walk(node.Target) && WalkOperand(sliceRange.Begin) && WalkOperand(sliceRange.End); + } + if (node.Target != null && ((node.MethodName == "[]" && argc == 1) || JitCompiler.IsHashQuery(node.MethodName, argc))) { if (!Walk(node.Target)) { return false; } if (args != null) { diff --git a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs index 997fa1668..f7fac5bd3 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -808,6 +808,54 @@ public static int StringLength(object recv) { throw Deopt(); } + /// + /// `s[b..e]', `a[b...e]' (JitCompiler.EmitRangeSlice): String#[] and Array#[] of a Range of Integers, for a String or + /// an Array whose class is String or Array itself (, : the library + /// methods). A String is sliced by characters, as StringIndex reads one; an Array gives a new Array of the elements. + /// A start outside the receiver is nil. Anything else deopts - also a String whose bytes are no characters and an Array + /// another thread shrinks while it is copied: nothing but a deopt leaves this helper. + /// + public static object RangeSlice(object recv, long begin, long end, bool exclusive, bool strings, bool arrays) { + if (recv != null) { + Type t = recv.GetType(); + try { + if (t == typeof(MutableString) && strings) { + var self = ((MutableString)recv).PrepareForCharacterRead(); + int length = self.KnowsCharIndexIsClrIndex ? self.GetCharCount() : self.GetCharacterCount(); + int start, count; + if (!RangeStartLength(begin, end, exclusive, length, out start, out count)) { return null; } + self.ToClrRange(ref start, ref count); + return self.GetSlice(start, count); + } + if (t == typeof(RubyArray) && arrays) { + var array = (RubyArray)recv; + int start, count; + if (!RangeStartLength(begin, end, exclusive, array.Count, out start, out count)) { return null; } + return new RubyArray(array, start, count); + } + } catch (Exception e) when (!(e is JitDeoptException)) { + } + } + throw Deopt(); + } + + // rb_range_component_beg_len with err 0 (String#[], Array#[]): false for a start outside [0, length] + private static bool RangeStartLength(long begin, long end, bool exclusive, int length, out int start, out int count) { + start = count = 0; + if (begin < 0) { + begin += length; + if (begin < 0) { return false; } + } + if (begin > length) { return false; } + if (end < 0) { end += length; } + if (!exclusive && end < Int64.MaxValue) { end++; } + if (end > length) { end = length; } + long n = end - begin; + start = (int)begin; + count = (n < 0) ? 0 : (int)n; + return true; + } + /// Array#empty?, Hash#empty?, and String#empty? of a String whose class is String itself; anything else deopts. public static bool IsEmptyOrString(object recv, bool arrays, bool hashes) { if (recv != null && recv.GetType() == typeof(MutableString)) { return ((MutableString)recv).IsEmpty; } diff --git a/Util/bench/slice-shapes.rb b/Util/bench/slice-shapes.rb new file mode 100644 index 000000000..ddf85cf6b --- /dev/null +++ b/Util/bench/slice-shapes.rb @@ -0,0 +1,28 @@ +# `s[a..b]' and `ary[a...b]' in hot methods (JitCompiler.EmitRangeSlice): a String's tail, an Array's head, a window of +# a String between two instance variables. Every line prints the sum of its results next to its time; it must be CRuby's. +# ruby Util/perf/ab.rb Util/bench/slice-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ../ironruby/ir.sh" "new=env IR_CONFIG=Release ./ir.sh" +$stdout.sync = true +class SS + def initialize; @buf = "abcdefghijklmnop"; @pos = 3; @lim = 9; end + def tail(s) = s[1..-1] + def head(a) = a[0...3] + def window = @buf[@pos...@lim] +end +def cpu; Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID); end +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times do + t0 = cpu; sum = yield n; d = cpu - t0 + best = d if d < best + end + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +o = SS.new +STR = "hello world" +ARY = [1, 2, 3, 4, 5] +N = (ENV["N"] || 1_000_000).to_i +t("tail", N) { |n| i = 0; r = 0; while i < n; r += o.tail(STR).size; i += 1; end; r } +t("head", N) { |n| i = 0; r = 0; while i < n; r += o.head(ARY).size; i += 1; end; r } +t("window", N) { |n| i = 0; r = 0; while i < n; r += o.window.size; i += 1; end; r } diff --git a/Util/jit-slice-matrix.rb b/Util/jit-slice-matrix.rb new file mode 100644 index 000000000..f000552d9 --- /dev/null +++ b/Util/jit-slice-matrix.rb @@ -0,0 +1,109 @@ +# Differential matrix for `s[a..b]' and `ary[a...b]' in methods the method JIT compiles (JitCompiler.EmitRangeSlice, +# JitRuntime.RangeSlice). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-slice-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-slice-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-slice-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-slice-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep SL +# The traps: ends at, past and before either end of the receiver (nil or empty), exclusive ranges, huge, Bignum and +# Float ends, multi-byte, binary, broken and UTF-16 Strings, other receivers (nil, a Hash, subclasses, a singleton []), +# String#[] and Array#[] redefined or refined, the result a new unfrozen object of the receiver's encoding. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class SL + def initialize(buf = "abcdefghij") ; @buf = buf; @pos = 2; @lim = 7; end + def head(s) = s[0..6] + def tail(s) = s[1..-1] + def last3(s) = s[-3..-1] + def excl(s, a, b) = s[a...b] + def incl(s, a, b) = s[a..b] + def window = @buf[@pos...@lim] + def set_window(p, l) = (@pos = p; @lim = l) + def big(s) = s[0..(2**62)] + def bignum(s) = s[0..(2**70)] + def float_end(s) = s[0..2.5] +end + +o = SL.new +S = "abcdefghij" +A = (1..10).to_a +t("head, hot") { warm { |i| o.head("s#{i}abcdefg") } } +t("head of short and empty") { [o.head("abc"), o.head(""), o.head(S)] } +t("tail") { warm { o.tail(S) }; [o.tail(S), o.tail("a"), o.tail("")] } +t("last3") { warm { o.last3(S) }; [o.last3(S), o.last3("ab"), o.last3("")] } +t("incl ends") { warm { |i| o.incl(S, i % 3, 5) }; [[0, 0], [3, 2], [10, 12], [11, 12], [-10, -1], [-11, 3], [2, -20], [5, 5]].map { |a, b| o.incl(S, a, b) } } +t("excl ends") { warm { |i| o.excl(S, i % 3, 5) }; [[0, 0], [3, 2], [10, 12], [11, 12], [-10, -1], [-11, 3], [2, 2], [0, 10]].map { |a, b| o.excl(S, a, b) } } +t("arrays") { warm { o.head(A) }; [o.head(A), o.tail(A), o.last3(A), o.incl(A, 10, 12), o.incl(A, 11, 12), o.excl([], 0, 1), o.tail([])] } +t("array result is new") { a = [1, 2, 3]; r = o.tail(a); r << 9; [a, r, r.class] } +t("multi-byte") { s = "äöüßé€x"; warm { o.head(s) }; [o.head(s), o.last3(s), o.head(s).encoding, o.excl(s, 2, 4)] } +t("binary") { s = "\xff\xfe\x00abc".b; [o.head(s), o.last3(s).encoding] } +t("broken UTF-8") { s = "ab\xffcd"; [o.head(s), o.incl(s, 2, 3), o.head(s).valid_encoding?] } +t("UTF-16LE") { s = "abcdef".encode("UTF-16LE"); [o.head(s).encode("UTF-8"), o.head(s).encoding] } +t("frozen source, unfrozen result") { s = "abcdefghij".freeze; r = o.head(s); [r, r.frozen?, r.equal?(s)] } +t("result independent") { s = +"abcdefghij"; r = o.tail(s); r << "!"; s << "?"; [s, r] } +t("window, hot") { warm { o.window } } +t("window moved") { o.set_window(0, 3); a = o.window; o.set_window(8, 20); [a, o.window] } +t("window ends of other types") { w = SL.new; warm { w.window }; r = []; [[1.5, 4], [nil, 3], [2, 2**70], [-3, -1]].each { |p, l| w.set_window(p, l); r << (w.window rescue $!.class) }; r } +t("big end") { warm { o.big(S) }; o.big(S) } +t("Bignum end") { o.bignum(S) } +t("Float end") { o.float_end(S) } +t("nil receiver") { o.head(nil) } +t("a Hash receiver") { o.head({ 0..6 => :range, 0 => :zero }) } +t("an Integer receiver") { o.head(255) } +t("String subclass") { c = Class.new(String); r = o.head(c.new("abcdefghij")); [r, r.class] } +t("Array subclass") { c = Class.new(Array); r = o.head(c[1, 2, 3]); [r, r.class] } +t("String subclass with []") { c = Class.new(String) { def [](*) = :sub }; o.head(c.new("abc")) } +t("singleton []") { s = +"abcdefghij"; def s.[](*) = :single; [o.head(s), o.head("abcdefghij")] } + +class String + alias_method :__orig_aref, :[] + def [](*a) = :redefined +end +t("String#[] redefined") { [o.head(S), o.head(A)] } +class String + alias_method :[], :__orig_aref +end +class Array + alias_method :__orig_aref, :[] + def [](*a) = :aredefined +end +t("Array#[] redefined") { [o.head(S), o.head(A)] } +class Array + alias_method :[], :__orig_aref +end +t("restored") { [o.head(S), o.head(A)] } + +module SliceRefinement + refine String do + def [](*) = :refined + end +end +class SL + using SliceRefinement + def refined(s) = s[0..2] +end +t("refined") { warm { o.refined(S) } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index e0d5ce4d2..9df42d5e5 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,38 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitslice (2026-11-29, census and timed, not gated) - `s[a..b]` and `ary[a...b]` in the method JIT's typed body** + (the census's RangeExpression: 47 first refusals, 32 alone; switch `IR_JIT_RANGE_SLICE`). Built on perf/jitmasgn1 + 530202d. + - **Choosing it.** After parallel assignment, the refusals keeping the most methods out alone are interpolation + (45, nearly all a part that is a call: deliberate), splatted arguments (42), constants the census cannot + resolve (40) and ranges (32). The ranges are almost all slices: `ref[0..6]`, `@path[1..-1]`, + `@buffer[@position...length]`. + - **What.** `JitCompiler.EmitRangeSlice`: `x[a..b]` / `x[a...b]` with both ends present compiles without a Range to + `JitRuntime.RangeSlice`. A String of class String is sliced by characters, as StringIndex reads one (an + ASCII-incompatible encoding too); an Array of class Array gives a new Array. This holds while String#[] and + Array#[] are the library methods (IsPlainLibraryMethod, as for StringIndex and IndexInt). Start and length come + from the ends as CRuby's rb_range_component_beg_len makes them (err 0): a start outside [0, length] is nil, an + end past the length is clamped, a negative end counts from the end. Any other receiver (nil, a Hash, a + subclass, an Integer) deopts, as do a String whose bytes are no characters and an Array shrunk by another + thread mid-copy. The ends must be Integers in the body; an instance variable end is typed by its profile + (NumericIVar), and a Bignum or Float end is the generic call's. Not where a refinement is active. + - **Census** (Src/StdLib, Util/bench, AWFY, against 530202d): 25 methods up (9 never -> compiles, 16 never -> + maybe), none down. RangeExpression as the first refusal: 47 -> 10. + - **app-shapes, traced:** specialized 124 -> 124, declined 29 -> 29. + - **Clock** (ab.rb -r 5, `Util/bench/slice-shapes.rb`, ns, off -> new, CRuby): a String's tail `s[1..-1]` 116.1 -> + 92.0 (113.0), an Array's head `a[0...3]` 108.6 -> 90.5 (92.6), `@buf[@pos...@lim]` 128.3 -> 96.6 (205.6). + - **Checks.** `Util/jit-slice-matrix.rb` (new, 33 rows): heads, tails and windows; ends at, past and before both + ends of the receiver, inclusive and exclusive; Arrays and empty receivers; multi-byte, binary, broken UTF-8 + and UTF-16LE Strings; a frozen source; the result unfrozen and independent; instance-variable ends turning + Float, nil, Bignum and negative; huge, Bignum and Float ends; nil, a Hash and an Integer receiver; String and + Array subclasses, with and without their own []; a singleton []; String#[] and Array#[] redefined, then + restored; refined. It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, + IR_LIGHT_FRAMES=0 and the switch off. jit-aref, jit-strop, jit, jit-calls, jit-const, jit-objops and hot-shapes + in the same five modes: CRuby's output on both builds (40 runs with jit-slice). ruby/spec core/string + element_reference and slice, core/array element_reference and slice: no failures on either build. + IronRuby.Tests (Debug), all 1,441: PASSED. + - **perf/jitmasgn1 (2026-11-29, census and timed, not gated) - `a, b = v` of an Array in the method JIT's typed body** (the census's ParallelAssignmentExpression: 367 first refusals, 67 alone; switch `IR_JIT_DESTRUCTURE`). Built on perf/jitdefined 67ac8ea. From 7e258de84b82fed85f718bfa0f20d625370e6e98 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:23:54 +0000 Subject: [PATCH 395/439] LEDGER: perf/jitslice's matrix has 31 rows Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 9df42d5e5..aee98eba9 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2064,7 +2064,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has - **app-shapes, traced:** specialized 124 -> 124, declined 29 -> 29. - **Clock** (ab.rb -r 5, `Util/bench/slice-shapes.rb`, ns, off -> new, CRuby): a String's tail `s[1..-1]` 116.1 -> 92.0 (113.0), an Array's head `a[0...3]` 108.6 -> 90.5 (92.6), `@buf[@pos...@lim]` 128.3 -> 96.6 (205.6). - - **Checks.** `Util/jit-slice-matrix.rb` (new, 33 rows): heads, tails and windows; ends at, past and before both + - **Checks.** `Util/jit-slice-matrix.rb` (new, 31 rows): heads, tails and windows; ends at, past and before both ends of the receiver, inclusive and exclusive; Arrays and empty receivers; multi-byte, binary, broken UTF-8 and UTF-16LE Strings; a frozen source; the result unfrozen and independent; instance-variable ends turning Float, nil, Bignum and negative; huge, Bignum and Float ends; nil, a Hash and an Integer receiver; String and From 91b84a70901ee6cd489af10fe769128890d77855 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:44:04 +0000 Subject: [PATCH 396/439] Array#sum and Enumerable#sum add numbers without calling a redefined Integer#+ or Float#+ MRI's rb_ary_sum and enum_sum add Integers in C (rb_fix_plus, rb_big_plus), Rationals with rb_rational_plus and Floats in a C Kahan-Babuska loop: a program's own Integer#+, Float#+ or Rational#+ is never called, nor Float#nan?, #infinite?, #abs or #to_f. Only a value that is not a number is added with #+, and a Float initial value with the Float's #+ once the exact sum holds a Rational (finish_exact_sum). IronRuby's prelude folded with #+ and compensated with Float arithmetic in Ruby, so [1, 2, 3].sum called a redefined Integer#+ three times and [0.5, 1.5].sum called Float#+ seven times; ArrayOps.NumericSum stepped aside whenever Integer#+ or Float#+ was redefined. Now: - NumericSum no longer checks for a redefined +. - The prelude adds exactly with Enumerable#__exact_add__ (ArrayOps.ExactAdd, moved there), and compensates with a C# KahanBabuskaSum through __kahan_begin__, __kahan_add__, __kahan_sum__ and __kahan_result__. The NaN and infinity rules are ArrayOps.KahanBabuskaAdd's, as before. - Enumerable#sum still adds a value that is not a Float with #+ while Integer#+ and Rational#+ are the built-in ones (__builtin_exact_plus__?, asked once a call and cached on the runtime in RubyContext.BuiltinExactPlusVersion), so #each.sum of Integers stays as fast as it was. Timings (ab.rb, 4 rounds, against the branch's base): Array#sum 0.74, with a block 0.77, Float with a block 0.38, with an initial value 0.77, Hash#sum and Range#sum level; Enumerator#sum of Floats 0.50, of Integers and Struct#sum level with the old prelude on the same build (6 rounds). Checked against CRuby 4.0: which #+ is called, and what each sum answers, for Arrays, Enumerators, Hashes and Ranges, with and without a block, from 0, 0.0, -0.0, 1r, 10**20 and 0.5, over NaN, infinities, signed zeros, Bignums, Rationals, Strings, Arrays and an object with its own #+. perf/dmethjit's Util/array-sum-matrix.rb now matches CRuby on every row (two differed before, on the base too). ruby/spec array/sum, enumerable/sum, range, struct, hash and enumerator match the base. New IronRuby.Tests: Array_SumRedefinedPlus1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ArrayTests.cs | 48 ++++++++ Src/Libraries/Builtins/ArrayOps.cs | 19 ++- Src/Libraries/Builtins/Enumerable.cs | 96 +++++++++++++++ Src/Ruby/Runtime/RubyContext.cs | 7 ++ Src/StdLib/ironruby/ruby4.rb | 145 +++++++---------------- 6 files changed, 205 insertions(+), 111 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 645f466d2..06b779a1b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -469,6 +469,7 @@ public Tests(Driver/*!*/ driver) { Array_SplatBlockYield1, Array_NumericSumMinShift1, Array_SumFloatInit1, + Array_SumRedefinedPlus1, Enumerable_TallyGroupBy1, Enumerable_ZipEnumerated1, IListOps_EnumerateRecursively1, diff --git a/Src/IronRuby.Tests/Runtime/ArrayTests.cs b/Src/IronRuby.Tests/Runtime/ArrayTests.cs index 14a6d28a7..da19e9d41 100644 --- a/Src/IronRuby.Tests/Runtime/ArrayTests.cs +++ b/Src/IronRuby.Tests/Runtime/ArrayTests.cs @@ -359,6 +359,54 @@ alias __test_plus + "); } + /// + /// Array#sum and Enumerable#sum add Integers, Floats and Rationals with the built-in arithmetic, whatever Integer#+, + /// Float#+ and Rational#+ are now (MRI's rb_ary_sum and enum_sum); only a value that is not a number is added with #+, and + /// a Float initial value to an exact sum with a Rational in it with the Float's. Expected output is CRuby 4.0's. + /// + public void Array_SumRedefinedPlus1() { + TestOutput(@" +require 'ruby4' +$n = [] +[Integer, Float, Rational].each do |c| + c.class_eval do + alias_method :__old_plus, :+ + define_method(:+) { |o| $n << c; __old_plus(o) } + end +end +def counted + $n.clear + r = yield + [r, $n.dup] +end +p counted { [1, 2, 3].sum } +p counted { [1, 2, 3].sum { |x| x } } +p counted { [0.5, 1.5].sum } +p counted { [1, 0.5].sum { |x| x } } +p counted { [1r, 2].sum } +p counted { [1r, 2].sum(0.0) } +p counted { [1, 2].sum(0.0) } +p counted { [1, 2].each.sum } +p counted { [0.5, 1, 1r].each.sum } +p counted { {a: 1, b: 2}.sum { |k, v| v } } +p counted { (1..3).sum { |x| x } } +p counted { [1, ""a""].sum rescue $!.class } +", @" +[6, []] +[6, []] +[2.0, []] +[1.5, []] +[(3/1), []] +[3.0, [Float]] +[3.0, []] +[3, []] +[2.5, []] +[3, []] +[6, []] +[TypeError, [Integer]] +"); + } + /// /// Enumerable#tally and #group_by over an Array whose #each is the built-in one run in C# /// (Enumerable.ListTally, ListGroupBy); a subclass or singleton #each, or another Enumerable, diff --git a/Src/Libraries/Builtins/ArrayOps.cs b/Src/Libraries/Builtins/ArrayOps.cs index 2c9159755..d0c7b1bd9 100644 --- a/Src/Libraries/Builtins/ArrayOps.cs +++ b/Src/Libraries/Builtins/ArrayOps.cs @@ -709,9 +709,8 @@ private static int RotationStart(long count, int n) { /// sum if no Float follows, otherwise as the first addend of the compensated sum, which starts /// from the exact sum - so that [10**16, 1, -10**16].sum(0.0) is 1.0, not 0.0. /// Answers nil, having changed nothing, when an element or the initial value is anything else - /// (the prelude then does the whole sum), or when, from an Integer, Integer#+ or Float#+ is - /// not the built-in one: the prelude's Enumerable#sum calls a redefined one. From a Float, - /// MRI calls no #+ on a number at all, and neither does this. + /// (the prelude then does the whole sum). MRI calls no #+ on a number, whatever Integer#+ and + /// Float#+ are now, and neither does this. /// [RubyMethod("__numeric_sum__", RubyMethodAttributes.PrivateInstance)] public static object NumericSum(RubyContext/*!*/ context, IList/*!*/ self, object init) { @@ -719,9 +718,6 @@ public static object NumericSum(RubyContext/*!*/ context, IList/*!*/ self, objec return null; } bool floatInit = init is double; - if (!floatInit && (!IListOps.IsBuiltinMethod(context.IntegerClass, "+") || !IListOps.IsBuiltinMethod(context.GetClass(typeof(double)), "+"))) { - return null; - } int count = self.Count; if (count == 0) { @@ -789,7 +785,7 @@ public static object NumericSum(RubyContext/*!*/ context, IList/*!*/ self, objec /// the sum unless the sum is the other infinity, and a finite number adds nothing to an /// infinite sum. /// - private static void KahanBabuskaAdd(ref double sum, ref double compensation, double value) { + internal static void KahanBabuskaAdd(ref double sum, ref double compensation, double value) { if (Double.IsNaN(sum)) { return; } else if (Double.IsNaN(value)) { @@ -811,11 +807,10 @@ private static void KahanBabuskaAdd(ref double sum, ref double compensation, dou /// /// a + b for Integers and Rationals, with the built-in arithmetic whatever Integer#+ and - /// Rational#+ are now: the exact part of Array#sum from a Float initial value (the prelude's - /// __float_init_sum__), which MRI's rb_ary_sum adds with rb_big_plus and rb_rational_plus. + /// Rational#+ are now, as MRI's rb_ary_sum and enum_sum add them (rb_fix_plus, rb_big_plus, + /// rb_rational_plus): Enumerable#__exact_add__. /// - [RubyMethod("__exact_add__", RubyMethodAttributes.PrivateInstance)] - public static object ExactAdd(IList/*!*/ self, object a, object b) { + internal static object ExactAdd(object a, object b) { RubyRational ra = a as RubyRational, rb = b as RubyRational; if (ra != null) { return rb != null ? RubyRational.Add(ra, rb) : ra.AddInteger(b); @@ -842,7 +837,7 @@ private static bool IsNumericSummand(object x) { return x is int || x is double || x is BigInteger || x is long; } - private static double SummandToDouble(object x) { + internal static double SummandToDouble(object x) { if (x is int) { return (int)x; } else if (x is double) { diff --git a/Src/Libraries/Builtins/Enumerable.cs b/Src/Libraries/Builtins/Enumerable.cs index f27a8141a..815fb3d3b 100644 --- a/Src/Libraries/Builtins/Enumerable.cs +++ b/Src/Libraries/Builtins/Enumerable.cs @@ -1440,6 +1440,102 @@ public static object Cycle(CallSiteStorage/*!*/ each, [NotNull]BlockPa #endregion + #region sum + + // Enumerable#sum and Array#sum in the prelude add numbers with these and not with #+, as MRI's + // enum_sum and rb_ary_sum do: they call no Integer#+, Float#+ or Rational#+ a program has + // redefined (nor Float#nan?, #infinite?, #abs or #to_f), only the #+ of a value that is not a + // number, or of a sum that is not one. + + /// + /// a + b, both Integers or Rationals, exactly (rb_fix_plus, rb_big_plus, rb_rational_plus). + /// + [RubyMethod("__exact_add__", RubyMethodAttributes.PrivateInstance)] + public static object ExactAdd(object self, object a, object b) { + return ArrayOps.ExactAdd(a, b); + } + + /// + /// Whether Integer#+ and Rational#+ are the built-in ones, so that #+ adds Integers and Rationals + /// as __exact_add__ does. + /// + [RubyMethod("__builtin_exact_plus__?", RubyMethodAttributes.PrivateInstance)] + public static bool IsBuiltinExactPlus(RubyContext/*!*/ context, object self) { + int version = RubyModule.GlobalMethodVersion; + if (context.BuiltinExactPlusVersion == version) { + return true; + } + if (IListOps.IsBuiltinMethod(context.IntegerClass, "+") && IListOps.IsBuiltinMethod(context.GetClass(typeof(RubyRational)), "+")) { + context.BuiltinExactPlusVersion = version; + return true; + } + return false; + } + + /// + /// The state of a Kahan-Babuska compensated summation (MRI's enum_sum_memo f and c). + /// + public sealed class KahanBabuskaSum { + internal double Sum; + internal double Compensation; + } + + /// + /// A compensated summation from a sum so far, an Integer, a Float or a Rational, with no + /// compensation yet. + /// + [RubyMethod("__kahan_begin__", RubyMethodAttributes.PrivateInstance)] + public static KahanBabuskaSum/*!*/ KahanBegin(object self, object sum) { + return new KahanBabuskaSum { Sum = SumToDouble(sum) }; + } + + /// + /// Adds x if it is an Integer, a Float or a Rational (sum_iter_Kahan_Babuska) and answers true; + /// answers false, having added nothing, for anything else, which the caller then adds to the + /// plain sum (__kahan_sum__) with #+, leaving out the compensation, as MRI does. + /// + [RubyMethod("__kahan_add__", RubyMethodAttributes.PrivateInstance)] + public static bool KahanAdd(object self, [NotNull]KahanBabuskaSum/*!*/ state, object x) { + if (!(x is int || x is double || x is long || x is System.Numerics.BigInteger || x is RubyRational)) { + return false; + } + ArrayOps.KahanBabuskaAdd(ref state.Sum, ref state.Compensation, SumToDouble(x)); + return true; + } + + /// + /// The plain sum so far, without the compensation. + /// + [RubyMethod("__kahan_sum__", RubyMethodAttributes.PrivateInstance)] + public static double KahanSum(object self, [NotNull]KahanBabuskaSum/*!*/ state) { + return state.Sum; + } + + /// + /// The compensated sum: the answer. + /// + [RubyMethod("__kahan_result__", RubyMethodAttributes.PrivateInstance)] + public static double KahanResult(object self, [NotNull]KahanBabuskaSum/*!*/ state) { + return state.Sum + state.Compensation; + } + + /// + /// A Float initial value added to the exact sum of the Integers and Rationals that were all the + /// values (MRI's finish_exact_sum: rb_fix_plus, rb_big_plus or rb_rational_plus of the sum and + /// the Float), with no compensation. + /// + [RubyMethod("__float_init_add__", RubyMethodAttributes.PrivateInstance)] + public static double FloatInitAdd(object self, double init, object exact) { + return SumToDouble(exact) + init; + } + + private static double SumToDouble(object x) { + var rational = x as RubyRational; + return (rational != null) ? RubyRational.ToFloat(rational) : ArrayOps.SummandToDouble(x); + } + + #endregion + #region each_cons, each_slice [RubyMethod("each_cons")] diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 9e4707d42..fb2cb9ae6 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -281,6 +281,13 @@ public Random/*!*/ RandomNumberGenerator { [Emitted] public int ConstantAccessVersion = 1; + /// + /// The RubyModule.GlobalMethodVersion at which Integer#+ and Rational#+ were last found to be the built-in ones + /// (Enumerable#__builtin_exact_plus__?, which Enumerable#sum asks once a call), or -1: one comparison instead of + /// two method-table checks, which made #sum of a few values 5% slower. + /// + public int BuiltinExactPlusVersion = -1; + /// /// A constant was set, removed or may resolve differently: the constant caches, the typed bodies /// and the outlined loops that folded one find out by ConstantAccessVersion, on their next entry. diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index ab4533ad1..343d70f7b 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -287,52 +287,36 @@ def tally(counts = nil) # added as Floats too: [10**16, 1, -10**16].each.sum(0.0) is 1.0, not 0.0. def sum(init = 0) acc = init - compensation = 0.0 - compensating = ::Float === init + # The compensated sum (__kahan_begin__), once there is one. The numbers are added with the + # built-in arithmetic (Enumerable#__exact_add__, __kahan_add__): MRI's enum_sum calls no + # Integer#+ or Float#+ a program has redefined. + kb = (::Float === init) ? __kahan_begin__(init) : nil + # While Integer#+ and Rational#+ are the built-in ones, a value that is not a Float is added + # with #+, which is what __exact_add__ would do for an Integer or a Rational, the compiler + # adding two Integers in place: testing for both and calling __exact_add__ made #each.sum + # of Integers 10-15% slower. + plain = __builtin_exact_plus__? each do |*values| x = __enum_item__(values) x = yield(x) if block_given? - unless compensating - unless x.is_a?(Float) && (acc.is_a?(Integer) || acc.is_a?(Float) || acc.is_a?(Rational)) - acc = acc + x - next - end - compensating = true - acc = acc.to_f - end - unless x.is_a?(Integer) || x.is_a?(Float) || x.is_a?(Rational) + if kb + next if __kahan_add__(kb, x) # back out of float mode. The compensation is dropped, not added in: MRI's # sum_iter_Kahan_Babuska goes on from the Float sum alone (memo->f), and so does rb_ary_sum. - compensation = 0.0 - compensating = false + acc = __kahan_sum__(kb) + x + kb = nil + elsif plain && !(::Float === x) + acc = acc + x + elsif (::Integer === x || ::Rational === x) && (::Integer === acc || ::Rational === acc) + acc = __exact_add__(acc, x) + elsif ::Float === x && (::Integer === acc || ::Float === acc || ::Rational === acc) + kb = __kahan_begin__(acc) + __kahan_add__(kb, x) + else acc = acc + x - next - end - x = x.to_f - - # Nothing infinite can be compensated: (1.0 - Infinity) + Infinity is NaN, which is - # how a single Infinity in the list used to take the whole sum with it. A NaN stays, - # an infinity swallows the sum unless the sum is the other infinity, and a finite - # number adds nothing to an infinite sum. - if acc.nan? - next - elsif x.nan? - acc = x - compensation = 0.0 - next - elsif x.infinite? - acc = (acc.infinite? == -x.infinite?) ? (0.0 / 0.0) : x - compensation = 0.0 - next - elsif acc.infinite? - next end - - t = acc + x - compensation += acc.abs >= x.abs ? (acc - t) + x : (x - t) + acc - acc = t end - compensating ? acc + compensation : acc + kb ? __kahan_result__(kb) : acc end unless method_defined?(:sum) alias :filter :select unless method_defined?(:filter) @@ -1502,14 +1486,11 @@ def __array_sum__(init, &block) while i < __ary_size__ x = yield(__ary_at__(i)) i = i.succ - if ::Integer === x && ::Integer === acc - acc = acc + x - next - end - # an Integer and a Rational, or two Rationals, are added exactly, as MRI's rb_ary_sum does - # until its first Float (rb_rational_plus, whatever Rational#+ is now): a Rational must not - # take the plain fold of __sum_rest__, which leaves out the compensation at a later Float - if (::Rational === x || ::Integer === x) && (::Rational === acc || ::Integer === acc) + # Integers and Rationals are added exactly, as MRI's rb_ary_sum does until its first Float + # (rb_fix_plus, rb_big_plus, rb_rational_plus, whatever Integer#+ and Rational#+ are now): a + # Rational must not take the plain fold of __sum_rest__, which leaves out the compensation + # at a later Float + if (::Integer === x || ::Rational === x) && (::Integer === acc || ::Rational === acc) acc = __exact_add__(acc, x) next end @@ -1517,31 +1498,15 @@ def __array_sum__(init, &block) # (a Float initial value ends up here at the first value: see __sum_rest__) return __sum_rest__(acc, x, i, &block) end - acc = acc.to_f - compensation = 0.0 - while true - # x is an Integer, a Float or a Rational - x = x.to_f - if acc.nan? - # a NaN stays - elsif x.nan? - acc = x - compensation = 0.0 - elsif x.infinite? - acc = (acc.infinite? == -x.infinite?) ? (0.0 / 0.0) : x - compensation = 0.0 - elsif !acc.infinite? - t = acc + x - compensation += acc.abs >= x.abs ? (acc - t) + x : (x - t) + acc - acc = t - end - return acc + compensation unless i < __ary_size__ + # the compensated sum, with the built-in Float arithmetic (__kahan_add__) + kb = __kahan_begin__(acc) + __kahan_add__(kb, x) + while i < __ary_size__ x = yield(__ary_at__(i)) i = i.succ - unless ::Integer === x || ::Float === x || ::Rational === x - return __sum_rest__(acc, x, i, &block) - end + return __sum_rest__(__kahan_sum__(kb), x, i, &block) unless __kahan_add__(kb, x) end + return __kahan_result__(kb) end acc end @@ -1563,47 +1528,29 @@ def __float_init_sum__(init, x, i, &block) while true if ::Integer === x || ::Rational === x exact = __exact_add__(exact, x) - return init + exact.to_f unless i < __ary_size__ + # (MRI's finish_exact_sum adds a Rational sum with rb_rational_plus, which calls the + # Float's #+; an Integer one with rb_fix_plus or rb_big_plus, which call nothing) + return (::Rational === exact ? init + exact.to_f : __float_init_add__(init, exact)) unless i < __ary_size__ x = __ary_at__(i) x = yield(x) if block i = i.succ next end - acc = exact.to_f - compensation = 0.0 - y = init - pending = true + # the compensated sum (__kahan_add__), from the exact sum, the initial value and x + kb = __kahan_begin__(exact) + __kahan_add__(kb, init) + y = x while true - # y is an Integer, a Float or a Rational - y = y.to_f - if acc.nan? - # a NaN stays - elsif y.nan? - acc = y - compensation = 0.0 - elsif y.infinite? - acc = (acc.infinite? == -y.infinite?) ? (0.0 / 0.0) : y - compensation = 0.0 - elsif !acc.infinite? - t = acc + y - compensation += acc.abs >= y.abs ? (acc - t) + y : (y - t) + acc - acc = t - end - if pending - # the value that ended the exact part - y = x - pending = false - else - return acc + compensation unless i < __ary_size__ - y = __ary_at__(i) - y = yield(y) if block - i = i.succ - end - unless ::Integer === y || ::Float === y || ::Rational === y + unless __kahan_add__(kb, y) # without the compensation, as in MRI (see Enumerable#sum) + acc = __kahan_sum__(kb) return __sum_tail__(acc, y, i, &block) if block return __sum_tail__(acc, y, i) { |e| e } end + return __kahan_result__(kb) unless i < __ary_size__ + y = __ary_at__(i) + y = yield(y) if block + i = i.succ end end end From 29efb32b0c01ce6bb6ed298fb686ec32a4161e26 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:49:36 +0000 Subject: [PATCH 397/439] More library errors defer their backtrace walk: division by zero, EOFError, frozen objects perf/unkept's second round. Integer#/ and #% on two Fixnums let the CLR's own DivideByZeroException fault, which no throw site could mark; they now test the divisor and throw a marked ZeroDivisionError with the same message, as the Float overload already did. 61 more throw sites that throw what they have just made are marked (RubyExceptionData.Unkept, one line each): every throw new DivideByZeroException, every EOFError("end of file reached"), every CreateObjectFrozenError, and Integer#chr's RangeErrors. Rescued, us, before -> after (CRuby): 1 / 0 29.9 -> 5.5 (1.1), 1 % 0 29.4 -> 5.2 (1.1), StringIO#readline at the end 27.4 -> 7.0 (1.2), a frozen Array's << 29.3 -> 6.3 (1.7), a frozen Hash's []= 27.6 -> 5.1 (1.7), 300.chr 27.6 -> 5.7 (1.3). IR_UNKEPT_LIB=0 restores the old code. Util/unkept-matrix.rb covers the six new kinds against CRuby with the switch on and off and the JIT on and off; two older backtrace differences (a FrozenError's core-method frame, StringIO#readline's name) are left out of its comparison with a comment. Also checked: the exception and backtrace matrices in every mode (55 same), division and modulo of every kind against CRuby, ruby/spec integer, rational, exception, stringio and the frozen paths (1738 examples, the same two known into/to errors on both builds) and language in full, IronRuby.Tests on Debug (passed). The census is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Libraries/Builtins/Enumerator.cs | 4 +-- Src/Libraries/Builtins/FileOps.cs | 2 +- Src/Libraries/Builtins/Integer.cs | 14 +++++------ Src/Libraries/Builtins/IoOps.cs | 10 ++++---- Src/Libraries/Builtins/KernelOps.cs | 2 +- Src/Libraries/Builtins/Marshal.cs | 4 +-- Src/Libraries/Builtins/ModuleOps.cs | 4 +-- Src/Libraries/Builtins/MutableStringOps.cs | 8 +++--- Src/Libraries/Builtins/ObjectSpace.cs | 4 +-- Src/Libraries/Builtins/RubyComplex.cs | 2 +- Src/Libraries/Builtins/RubyRational.cs | 14 +++++------ Src/Libraries/Builtins/RubyRegexOps.cs | 2 +- Src/Libraries/Builtins/RubyTimeOps.cs | 4 +-- Src/Libraries/Builtins/RubyTimeSupport.cs | 2 +- Src/Libraries/Builtins/StructOps.cs | 6 ++--- Src/Libraries/Extensions/ClrBigInteger.cs | 4 +-- Src/Libraries/Extensions/ClrFloat.cs | 2 +- Src/Libraries/Extensions/ClrInteger.cs | 11 ++++++-- Src/Libraries/StringIO/StringIO.cs | 10 ++++---- Src/Ruby/Builtins/Hash.cs | 2 +- Src/Ruby/Builtins/Range.cs | 4 +-- Src/Ruby/Builtins/RubyArray.cs | 2 +- Src/Ruby/Builtins/RubyModule.cs | 6 ++--- Src/Ruby/Builtins/RubyStruct.cs | 4 +-- Src/Ruby/Runtime/RubyContext.cs | 2 +- Util/perf/LEDGER.md | 29 ++++++++++++++++++++-- Util/unkept-matrix.rb | 22 ++++++++++++---- 27 files changed, 112 insertions(+), 68 deletions(-) diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index ff106c100..015c1b538 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -1240,7 +1240,7 @@ private static bool IsBuiltinMethod(RubyContext/*!*/ context, object target, str private static ExternalCursor GetCursor(CallSiteStorage>/*!*/ slowStorage, Enumerator/*!*/ self) { RubyContext context = slowStorage.Context; if (context.IsObjectFrozen(self)) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } ExternalCursor cursor = self._cursor; @@ -1528,7 +1528,7 @@ public static object Peek(CallSiteStorage [RubyMethod("feed")] public static object Feed(RubyContext/*!*/ context, Enumerator/*!*/ self, object value) { if (context.IsObjectFrozen(self)) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } if (self._hasFeed) { throw RubyExceptions.CreateTypeError("feed value already set"); diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 869fce599..d1f235a99 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -2327,7 +2327,7 @@ private static FileSystemInfo L(FileSystemInfo self) { return self; } if (context.IsObjectFrozen(self)) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } var source = other as StatInfo; if (source == null || context.GetClassOf(other) != context.GetClassOf(self)) { diff --git a/Src/Libraries/Builtins/Integer.cs b/Src/Libraries/Builtins/Integer.cs index 033bf9900..7e066964b 100644 --- a/Src/Libraries/Builtins/Integer.cs +++ b/Src/Libraries/Builtins/Integer.cs @@ -225,9 +225,9 @@ private static BigInteger ToBigInteger(object/*!*/ self) { // "bignum" is what MRI calls a number that is no Fixnum there, one beyond 62 bits: // 2**32 is named. if (self.IsFixnum || value >= -(BigInteger.One << 62) && value < (BigInteger.One << 62)) { - throw RubyExceptions.CreateRangeError("{0} out of char range", value); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", value)); } - throw RubyExceptions.CreateRangeError("bignum out of char range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum out of char range")); } uint codepoint = (uint)value; @@ -240,7 +240,7 @@ private static BigInteger ToBigInteger(object/*!*/ self) { } var internalEncoding = toStr.Context.DefaultInternalEncoding; if (internalEncoding == null) { - throw RubyExceptions.CreateRangeError("{0} out of char range", codepoint); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", codepoint)); } return ToChr(internalEncoding, internalEncoding, codepoint); } @@ -251,7 +251,7 @@ private static BigInteger ToBigInteger(object/*!*/ self) { internal static MutableString/*!*/ ToChr(RubyEncoding/*!*/ encoding, RubyEncoding/*!*/ resultEncoding, int codepoint) { if (codepoint < 0) { - throw RubyExceptions.CreateRangeError("{0} out of char range", codepoint); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", codepoint)); } return ToChr(encoding, resultEncoding, (uint)codepoint); } @@ -565,7 +565,7 @@ internal static byte[] ToFormatBytes(RubyEncoding/*!*/ encoding, uint code, out if (codepoint <= 0xffff) { return MutableString.CreateBinary(new[] { (byte)(codepoint >> 8), (byte)(codepoint & 0xff) }, resultEncoding); } - throw RubyExceptions.CreateRangeError("{0} out of char range", codepoint); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", codepoint)); } // Everything else - single byte encodings (BINARY too), dummy encodings, and anything // whose structure we don't model - has no character this wide. CRuby 4.0's onigmo @@ -1502,7 +1502,7 @@ public static object Pow(int self, int exponent, int modulus) { } long m = Math.Abs((long)modulus); if (m == 0) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } if (m == 1) { return ClrInteger.Zero; @@ -1551,7 +1551,7 @@ public static object Pow(object/*!*/ self, object exponent, object modulus) { m = -m; } if (m.IsZero) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } if (m.IsOne) { return ClrInteger.Zero; diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 7c43aa370..76cf7f3e4 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -2193,7 +2193,7 @@ private static MutableString Read(RubyIO/*!*/ self, int bytes, MutableString buf var result = Read(self, bytes, buffer, false); if (result == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return result; } @@ -2229,7 +2229,7 @@ public static MutableString ReadNoBlock(RubyIO/*!*/ self, [DefaultProtocol]int b MutableString result = null; self.RunNonBlocking(() => result = ReadOnceWithoutWaiting(self, bytes, buffer), true); if (result == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return result; } @@ -2387,7 +2387,7 @@ private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, M public static object/*!*/ ReadChar(TranscodeStorage/*!*/ transcode, TranscodeStorage/*!*/ universal, RubyIO/*!*/ self) { object c = Getc(transcode, universal, self); if (c == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return c; } @@ -2397,7 +2397,7 @@ public static int ReadByte(RubyIO/*!*/ self) { self.RequireByteReadable(); int b = self.ReadByteNormalizeEoln(); if (b == -1) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return b; } @@ -2425,7 +2425,7 @@ public static int ReadByte(RubyIO/*!*/ self) { private static MutableString/*!*/ RequireLine(MutableString line) { if (line == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return line; } diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index ab148ad2b..b95485d15 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -47,7 +47,7 @@ public static object InitializeCopy(RubyContext/*!*/ context, object self, objec } if (context.IsObjectFrozen(self)) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } RubyClass selfClass = context.GetClassOf(self); diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index e0dddf740..f61fcf0d9 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -207,7 +207,7 @@ public override int ReadByte() { var site = _sites.Getbyte; object b = site.Target(site, _io); if (b == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } if (b is MutableString str) { // NUM2CHR takes a String's first byte @@ -2663,7 +2663,7 @@ internal object Load() { // A stream that ended before a single record began is at its end, which MRI // reports as such; a record that started and ran out is a short dump. if (FromStream && !_started) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } throw RubyExceptions.CreateArgumentError("marshal data too short", e); } catch (EOFError) { diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index ec15946b2..5e0ba7b59 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -886,9 +886,9 @@ private static void RequireMutable(RubyModule/*!*/ self) { } var cls = self as RubyClass; if (cls != null && cls.IsSingletonClass) { - throw RubyExceptions.CreateObjectFrozenError(self.Context, cls.SingletonClassOf); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(self.Context, cls.SingletonClassOf)); } - throw RubyExceptions.CreateObjectFrozenError(self.Context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(self.Context, self)); } // thread-safe: diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 7bda8248a..8c09c4098 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -817,7 +817,7 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { if (c < 0) { // MRI's rb_str_concat checks the receiver first: a frozen string raises FrozenError whatever it is given self.RequireNotFrozen(); - throw RubyExceptions.CreateRangeError("{0} out of char range", c); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", c)); } // #5855: appending a 0x80-0xff code point to a US-ASCII string widens the receiver @@ -846,7 +846,7 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { // range" there, where Integer#chr in those encodings says "invalid codepoint 0x100 in ASCII-8BIT". private static void RequireByteCode(MutableString/*!*/ self, uint c) { if (c > 0xff && (self.Encoding == RubyEncoding.Binary || self.Encoding == RubyEncoding.Ascii)) { - throw RubyExceptions.CreateRangeError("{0} out of char range", c); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", c)); } } @@ -863,9 +863,9 @@ private static void RequireByteCode(MutableString/*!*/ self, uint c) { return self.Append(Integer.ToChr(self.Encoding, self.Encoding, (uint)c)); } if (c >= -((BigInteger)1 << 62) && c < ((BigInteger)1 << 62)) { - throw RubyExceptions.CreateRangeError("{0} out of char range", c); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", c)); } - throw RubyExceptions.CreateRangeError("bignum out of char range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum out of char range")); } /// diff --git a/Src/Libraries/Builtins/ObjectSpace.cs b/Src/Libraries/Builtins/ObjectSpace.cs index 2aaad3f15..b8489b5ec 100644 --- a/Src/Libraries/Builtins/ObjectSpace.cs +++ b/Src/Libraries/Builtins/ObjectSpace.cs @@ -214,7 +214,7 @@ public static object DefineFinalizer(RespondToStorage/*!*/ respondTo, BinaryOpSt throw RubyExceptions.CreateArgumentError("cannot define finalizer for {0}", context.GetClassDisplayName(obj)); } if (context.IsObjectFrozen(obj)) { - throw RubyExceptions.CreateObjectFrozenError(context, obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, obj)); } // A finalizer that holds on to the object keeps it alive for good, so it only runs at exit. @@ -272,7 +272,7 @@ private static bool ReferencesObject(object finalizer, object obj) { [RubyMethod("undefine_finalizer", RubyMethodAttributes.PublicSingleton)] public static object UndefineFinalizer(RubyContext/*!*/ context, RubyModule/*!*/ self, object obj) { if (context.IsObjectFrozen(obj)) { - throw RubyExceptions.CreateObjectFrozenError(context, obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, obj)); } object invokerObj; diff --git a/Src/Libraries/Builtins/RubyComplex.cs b/Src/Libraries/Builtins/RubyComplex.cs index d13189699..94420c9e1 100644 --- a/Src/Libraries/Builtins/RubyComplex.cs +++ b/Src/Libraries/Builtins/RubyComplex.cs @@ -411,7 +411,7 @@ private static object AbsPart(object x) { [RubyMethod("__ir_set_parts__", RubyMethodAttributes.PrivateInstance)] public static RubyComplex/*!*/ SetParts(RubyContext/*!*/ context, RubyComplex/*!*/ self, object real, object imaginary) { if (self.IsFrozen) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } self._real = real; self._imaginary = imaginary; diff --git a/Src/Libraries/Builtins/RubyRational.cs b/Src/Libraries/Builtins/RubyRational.cs index c6ee34924..edcd50a90 100644 --- a/Src/Libraries/Builtins/RubyRational.cs +++ b/Src/Libraries/Builtins/RubyRational.cs @@ -70,7 +70,7 @@ public static object GetDenominator(RubyRational/*!*/ self) { [RubyMethod("__ir_set_parts__", RubyMethodAttributes.PrivateInstance)] public static RubyRational/*!*/ SetParts(RubyContext/*!*/ context, RubyRational/*!*/ self, object numerator, object denominator) { if (self.IsFrozen) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } self._numerator = numerator; self._denominator = denominator; @@ -127,7 +127,7 @@ private RubyClass/*!*/ RationalClass { num = -num; den = -den; } else if (den == 0) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } return new RubyRational(RationalClass, Protocols.Normalize(num), Protocols.Normalize(den)); } @@ -137,7 +137,7 @@ private RubyClass/*!*/ RationalClass { num = -num; den = -den; } else if (den.IsZero) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } return new RubyRational(RationalClass, Protocols.Normalize(num), Protocols.Normalize(den)); } @@ -266,7 +266,7 @@ public static object Multiply(CallSiteStorage>/*!*/ coerce, RubyRational/*!*/ self, object other) { if (IsIntegerValue(other)) { if (Big(other).IsZero) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } return self.MulDiv(self._numerator, self._denominator, other, 1, true); } @@ -276,7 +276,7 @@ public static object Divide(CallSiteStorage private static void RequireUninitialized(RubyContext/*!*/ context, RubyRegex/*!*/ self) { if (context.IsObjectFrozen(self)) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } if (self.IsInitialized) { diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index f266190da..e12b48f1f 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -1453,7 +1453,7 @@ public static int GetHash(RubyTime/*!*/ self) { public static RubyTime/*!*/ SwitchToUtc(RubyContext/*!*/ context, RubyTime/*!*/ self) { if (!self.IsUtc) { if (context.IsObjectFrozen(self)) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } } self.CopyFrom(self.WithZone(RubyTimeZoneKind.Utc, ExactNum.Zero, null)); @@ -1465,7 +1465,7 @@ public static int GetHash(RubyTime/*!*/ self) { RubyTime result = GetLocal(context, self, zone); if (result.ZoneKind != self.ZoneKind || result.UtcOffsetExact.CompareTo(self.UtcOffsetExact) != 0) { if (context.IsObjectFrozen(self)) { - throw RubyExceptions.CreateObjectFrozenError(context, self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } } self.CopyFrom(result); diff --git a/Src/Libraries/Builtins/RubyTimeSupport.cs b/Src/Libraries/Builtins/RubyTimeSupport.cs index 5599efd60..a4a24bab9 100644 --- a/Src/Libraries/Builtins/RubyTimeSupport.cs +++ b/Src/Libraries/Builtins/RubyTimeSupport.cs @@ -33,7 +33,7 @@ private ExactNum(BigInteger numerator, BigInteger denominator) { public static ExactNum Make(BigInteger numerator, BigInteger denominator) { if (denominator.IsZero) { - throw new DivideByZeroException(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException()); } if (denominator.Sign < 0) { numerator = -numerator; diff --git a/Src/Libraries/Builtins/StructOps.cs b/Src/Libraries/Builtins/StructOps.cs index 57a977fda..2c2d177f6 100644 --- a/Src/Libraries/Builtins/StructOps.cs +++ b/Src/Libraries/Builtins/StructOps.cs @@ -106,7 +106,7 @@ public static object Initialize(CallSiteStorage [RubyMethod("/"), RubyMethod("div")] public static object/*!*/ Divide(int self, int other) { + if (other == 0) { + // thrown here rather than by the CLR's division, as one nothing can have kept (perf/unkept) + throw RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); + } if (self == Int32.MinValue && other == -1) { return MinusMinValue(); } @@ -839,7 +843,7 @@ public static double FDiv([NotNull]BigInteger/*!*/ self, double other) { throw new FloatDomainError(other > 0 ? "Infinity" : "-Infinity"); } if (other == 0.0) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } // other = mantissa * 2**exponent, the mantissa an integer of at most 53 bits long bits = BitConverter.DoubleToInt64Bits(other); @@ -880,6 +884,9 @@ public static object FDiv(BinaryOpStorage/*!*/ coercionStorage, BinaryOpStorage/ /// [RubyMethod("%"), RubyMethod("modulo")] public static int Modulo(int self, int other) { + if (other == 0) { + throw RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); + } return MathUtils.FloorRemainder(self, other); } @@ -888,7 +895,7 @@ public static int Modulo(int self, int other) { [RubyMethod("%"), RubyMethod("modulo")] public static double Modulo(int self, double other) { if (other == 0.0) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } return ClrFloat.Modulo((double)self, other); } diff --git a/Src/Libraries/StringIO/StringIO.cs b/Src/Libraries/StringIO/StringIO.cs index e0f27767e..a605a9929 100644 --- a/Src/Libraries/StringIO/StringIO.cs +++ b/Src/Libraries/StringIO/StringIO.cs @@ -659,7 +659,7 @@ public static int Write(StringIO/*!*/ self) { self._position = length; buffer.Append(content, start, length - start); } else if (eofError) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } // Only a read of so many bytes answers bytes; the rest of the string keeps its encoding. @@ -754,7 +754,7 @@ public static MutableString Read(StringIO/*!*/ self, [DefaultProtocol]int count, self._position = offset; var result = Read(self, count, buffer); if (result == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return result; } finally { @@ -783,7 +783,7 @@ public static MutableString Read(StringIO/*!*/ self, [DefaultProtocol]int count, public static MutableString/*!*/ SystemRead(StringIO/*!*/ self, [DefaultProtocol]int bytes, [DefaultProtocol, Optional, NotNull]MutableString buffer) { var result = Read(self, bytes, buffer); if (result == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return result; } @@ -917,7 +917,7 @@ public static int ReadChar(StringIO/*!*/ self) { int length = content.GetByteCount(); if (self._position >= length) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return content.GetByte(self._position++); @@ -1091,7 +1091,7 @@ public static MutableString Gets(ConversionStorage>/ // no dynamic call, modifies $_ scope variable: MutableString result = Gets(toHash, toStr, toInt, scope, self, separatorOrLimit, limitOrOptions, options); if (result == null) { - throw new EOFError("end of file reached"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } return result; diff --git a/Src/Ruby/Builtins/Hash.cs b/Src/Ruby/Builtins/Hash.cs index cee75e746..8e33315a8 100644 --- a/Src/Ruby/Builtins/Hash.cs +++ b/Src/Ruby/Builtins/Hash.cs @@ -290,7 +290,7 @@ object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers public void RequireNotFrozen() { if ((_flags & IsFrozenFlag) != 0) { // MRI: "can't modify frozen Hash: {a: 1}", with the hash as FrozenError#receiver. - throw RubyExceptions.CreateObjectFrozenErrorFor(this, "Hash"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenErrorFor(this, "Hash")); } } diff --git a/Src/Ruby/Builtins/Range.cs b/Src/Ruby/Builtins/Range.cs index 66803c5af..1f989159c 100644 --- a/Src/Ruby/Builtins/Range.cs +++ b/Src/Ruby/Builtins/Range.cs @@ -58,7 +58,7 @@ protected Range(SerializationInfo info, StreamingContext context) { /// public void InitializeCopy(RubyContext/*!*/ context, Range/*!*/ other) { if (_initialized) { - throw RubyExceptions.CreateObjectFrozenError(context, this); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, this)); } _begin = other._begin; _end = other._end; @@ -140,7 +140,7 @@ public void Initialize(BinaryOpStorage/*!*/ comparisonStorage, // A range is frozen the moment it is initialized, so a second call is // a modification of a frozen object rather than a naming problem; so is // a call on Range.allocate.freeze (range_modify's rb_check_frozen). - throw RubyExceptions.CreateObjectFrozenError(context, this); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, this)); } // Range tests whether the items can be compared, and uses that to determine if the range is valid diff --git a/Src/Ruby/Builtins/RubyArray.cs b/Src/Ruby/Builtins/RubyArray.cs index 7a5788a56..602d3e576 100644 --- a/Src/Ruby/Builtins/RubyArray.cs +++ b/Src/Ruby/Builtins/RubyArray.cs @@ -158,7 +158,7 @@ private void ThrowObjectFrozenException() { // MRI names the receiver in the message ("can't modify frozen Array: [1, 2]") and // hangs it off FrozenError#receiver. An Array does not carry its context, but the // process has one by the time any of this can run. - throw RubyExceptions.CreateObjectFrozenErrorFor(this, "Array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenErrorFor(this, "Array")); } private void Mutate() { diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 90f27a14b..8c333faee 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -950,7 +950,7 @@ internal void InitializeMembersFrom(RubyModule/*!*/ module) { public void InitializeModuleCopy(RubyModule/*!*/ module) { if (_context.IsObjectFrozen(this)) { - throw RubyExceptions.CreateObjectFrozenError(_context, this); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(_context, this)); } using (Context.ClassHierarchyLocker()) { @@ -1010,9 +1010,9 @@ private void Mutate() { // `class FrozenC; end` => "can't modify frozen Class: FrozenC" var cls = this as RubyClass; if (cls != null && cls.IsSingletonClass) { - throw RubyExceptions.CreateObjectFrozenError(_context, cls.SingletonClassOf); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(_context, cls.SingletonClassOf)); } - throw RubyExceptions.CreateObjectFrozenError(_context, this); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(_context, this)); } } diff --git a/Src/Ruby/Builtins/RubyStruct.cs b/Src/Ruby/Builtins/RubyStruct.cs index 7eda9dcf9..681837efb 100644 --- a/Src/Ruby/Builtins/RubyStruct.cs +++ b/Src/Ruby/Builtins/RubyStruct.cs @@ -326,7 +326,7 @@ public static object GetValue(RubyStruct/*!*/ self, int index) { [Emitted] public static object SetValue(RubyStruct/*!*/ self, int index, object value) { if (self.IsFrozen) { - throw RubyExceptions.CreateObjectFrozenErrorFor(self, "Struct"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenErrorFor(self, "Struct")); } return self._data[index] = RubyOps.ClearKeywordArguments(value); } @@ -376,7 +376,7 @@ public object this[int index] { private void RequireNotFrozen() { if (IsFrozen) { - throw RubyExceptions.CreateObjectFrozenErrorFor(this, "Struct"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenErrorFor(this, "Struct")); } } diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 7749f0f72..cd1f9427e 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3191,7 +3191,7 @@ public bool TryGetInstanceVariable(object obj, string/*!*/ name, out object valu private RubyInstanceData MutateInstanceVariables(object obj) { RubyInstanceData data; if (IsObjectFrozen(obj, out data)) { - throw RubyExceptions.CreateObjectFrozenError(this, obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(this, obj)); } // Giving a chilled string literal an instance variable is a change a frozen string diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 661f4c10f..18f9c124e 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1367,8 +1367,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has perf/unkept (2026-11-29, see Landed): an error a library method or a call rule throws was 26-29 us rescued against a raise in Ruby's 5-6 (CRuby 0.9-1.8): only an exception Kernel#raise made could defer its catch-site walk. Rule errors (arity, method missing...) and the throw sites of `Array#fetch`, `String#[]=`, a frozen String and a failed numeric - coercion are now 4.7-5.5 us. Left: `1 / 0` (the CLR's own DivideByZeroException, 28.7 us) and the other library throw - sites, each a `RubyExceptionData.Unkept(...)` at a site that throws what it has just made. + coercion are now 4.7-5.5 us. perf/unkept2 (2026-11-29, see Landed) did `1 / 0` and `1 % 0`, `EOFError`, a frozen + Array or Hash and `Integer#chr`'s RangeError (5.0-7.0 us). Left: `read_nonblock` with nothing to read (45.6 us, CRuby 2.3), + `File.open` of a missing file (58.8, 3.4), both errno errors made by helpers, and the other library throw sites; marking + every `throw new`/`throw RubyExceptions.Create...` at once would need the places that keep an exception and hand it on + (a thread's, `Thread#join`/`value`, Ractor, Fiddle, MessagePack...) to clear the mark first. 23. **A method made by `define_method` is called at 2.3 times CRuby's time** (64 against 28 ns; a `def` of the same body 31; YJIT 2-5 ns): the method JIT takes no block as a method body. Rails-style code defines most of its small methods this way. @@ -2048,6 +2051,28 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/unkept2 (round thirty-seven, 2026-11-29) - more library errors defer their catch-site walk: division by zero, EOFError, + frozen objects, `chr`'s RangeError (gap 22)** - time, not gated. perf/unkept's second round. `1 / 0` and `1 % 0` were not + thrown by a site at all: `Integer#/` and `#%` on two Fixnums divided and let the CLR raise its DivideByZeroException. They + now test the divisor and throw a marked one with the CRuby message ("divided by 0", as the CLR's was mapped to), as the Float + overload already did. And 61 sites that throw what they have just made are marked (`RubyExceptionData.Unkept`, one line + each, `IR_UNKEPT_LIB=0` for the old code): every `throw new DivideByZeroException(...)` (Integer, Rational, Complex, Bignum, + Float, Time), every `throw new EOFError("end of file reached")` (StringIO, IO, Marshal), every throw of + `RubyExceptions.CreateObjectFrozenError` (Array, Hash, Struct, Range, Module, ObjectSpace...) and `chr`'s four RangeErrors. + Per rescued raise (`craise2.rb`, best of five of 30,000, us, off/on; CRuby): `1 / 0` 29.9/5.5 (1.1), `1 % 0` 29.4/5.2 (1.1), + `StringIO#readline` at the end 27.4/7.0 (1.2), a frozen Array's `<<` 29.3/6.3 (1.7), a frozen Hash's `[]=` 27.6/5.1 (1.7), + `300.chr` 27.6/5.7 (1.3). Not done: `read_nonblock` with nothing to read 45.6 (2.3) and `File.open` of a missing file 58.8 + (3.4), errno errors made by helpers, and the other library throw sites (see gap 22). Census: no method changed. Checked: + `Util/unkept-matrix.rb`, now with these six kinds, CRuby's output with the switch on and off and the JIT on and off (two + differences older than this, the same either way, left out of the comparison with a comment: CRuby 4.0 shows no frame for + the core method that raised a FrozenError, and names StringIO#readline's frame 'IO::generic_readable#readline'); errinfo, + jit-raise, jit-rescue, raise, rescue-light, set-backtrace, thread-backtrace and unkept in the six modes and with the switch + off: PASS, 55 same; Integer and Float division and modulo of every kind against CRuby (`1/0`, `5 % 0`, `(-2**31)/-1`, a + Bignum by 0, `1 % 0.0`, `divmod`, `div`, `modulo`); ruby/spec core/integer, core/rational, core/exception, library/stringio, + Array#push and `<<`, Hash#[]=, Float#/ and #%, Kernel#freeze: 1738 examples, the same two errors on both builds (the known + `into`/`to` wording in Integer.try_convert); ruby/spec language in full: 2935 examples, the one known error. IronRuby.Tests + in full on Debug: PASSED. + - **perf/unkept (round thirty-seven, 2026-11-29) - errors that rules and a few library methods throw defer their catch-site walk, as Kernel#raise's do (gap 22)** - time, not gated. A rescued `[].fetch(1)` cost 23.8-28.8 us against a rescued `raise` in Ruby's 5.4-6.0 (CRuby 1.0 and 0.8). dotnet-trace (sampled thread time): `StackTrace..ctor` and diff --git a/Util/unkept-matrix.rb b/Util/unkept-matrix.rb index 48a744d67..960c94499 100644 --- a/Util/unkept-matrix.rb +++ b/Util/unkept-matrix.rb @@ -3,16 +3,28 @@ # # ruby Util/unkept-matrix.rb > cruby.txt; ./ir.sh Util/unkept-matrix.rb | diff cruby.txt - (also IR_UNKEPT_LIB=0, -X:NoJIT) # -# The frozen String's backtrace leaves out 'String#<<', which IronRuby shows and CRuby 4.0 does not (a difference older than -# perf/unkept, with or without it). -A = []; S = "abc" -def bt(e) = e.backtrace.reject { |l| l.include?("in 'String#<<'") }.map { |l| l.sub(/^.*\//, '') }.first(6) +# A FrozenError's backtrace leaves out the frame of the core method that raised it ('String#<<', 'Array#<<', 'Hash#[]='), +# which IronRuby shows and CRuby 4.0 does not; and StringIO#readline's, which CRuby 4.0 names +# 'IO::generic_readable#readline' and IronRuby 'StringIO#readline'. Both differences are older than perf/unkept. +require "stringio" +A = []; S = "abc"; SIO = StringIO.new(""); FA = [].freeze; FH = {}.freeze +def bt(e) + lines = e.backtrace.reject { |l| l.include?("#readline'") } + lines = lines.drop(1) if e.is_a?(FrozenError) && lines.first =~ /in '(String|Array|Hash)#/ + lines.map { |l| l.sub(/^.*\//, '') }.first(6) +end def k_fetch = A.fetch(1) def k_arity = k_fetch(1) def k_coerce = 1 + nil def k_frozen = "x".freeze << "y" def k_strset = (S[10, 1] = "z") -KINDS = %i[k_fetch k_arity k_coerce k_frozen k_strset] +def k_zdiv = 1 / 0 +def k_zmod = 1 % 0 +def k_eof = SIO.readline +def k_farr = FA << 1 +def k_fhash = FH[1] = 2 +def k_range = 300.chr +KINDS = %i[k_fetch k_arity k_coerce k_frozen k_strset k_zdiv k_zmod k_eof k_farr k_fhash k_range] def deep3(m) = deep2(m) def deep2(m) = deep1(m) def deep1(m) = send(m) From 81955567fa655342eb158b3f007b21576028c2e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:58:31 +0000 Subject: [PATCH 398/439] Name an eval's file and line in a warning when it starts below line 1 A compile-time warning in code that eval was told to start at line 0 or below printed the internal file name, with the line offset encoded in it, and the parser's line: eval "def m\n END {}\nend", nil, "test.rb", 0 warned "test.rb\x01-1:2: warning: END in method; use at_exit" where CRuby says "test.rb:1: ...". The error sink now takes the offset back out of the path for warnings, as a backtrace does. A syntax error keeps the encoded path: RubyUtils.Evaluate, which catches it, puts its line back itself. CRuby's TestBeginEndBlock#test_endblockwarn_in_eval passes now; checked with ruby/spec's core/kernel/eval_spec and language/END_spec on the base build and this one (no difference). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 19 +++++++++++++++++++ Src/Ruby/Runtime/RuntimeErrorSink.cs | 4 ++++ 3 files changed, 24 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index c89ef10e2..be7b57a01 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1044,6 +1044,7 @@ public Tests(Driver/*!*/ driver) { Marshal_ProcPartialObject1, Marshal_TimeAnyYear1, Marshal_RecursiveUserDef1, + Eval_WarningLineBelowOne1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 10d4832a8..c9824775a 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10276,5 +10276,24 @@ p Marshal.load(Marshal.dump([u, u])).map { |x| x.instance_variable_get(:@w) } [[1, 2], [1, 2]] "); } + + /// + /// A compile warning in code an eval was told to start at a line below 1 names the eval's file and line, as a + /// backtrace does, not the file name with the line offset encoded in it (CRuby's TestBeginEndBlock#test_endblockwarn_in_eval). + /// + public void Eval_WarningLineBelowOne1() { + TestOutput(@" +err = Object.new +def err.write(*s) = (($w ||= +'') << s.join; s.join.bytesize) +$stderr = err +eval ""def end2\n END {}\nend\n"", nil, ""test.rb"", 0 +eval ""def end3\n END {}\nend\n"", nil, ""other.rb"", -3 +$stderr = STDERR +print $w +", @" +test.rb:1: warning: END in method; use at_exit +other.rb:-2: warning: END in method; use at_exit +", 0, 2); + } } } diff --git a/Src/Ruby/Runtime/RuntimeErrorSink.cs b/Src/Ruby/Runtime/RuntimeErrorSink.cs index ddb043e39..99ad69997 100644 --- a/Src/Ruby/Runtime/RuntimeErrorSink.cs +++ b/Src/Ruby/Runtime/RuntimeErrorSink.cs @@ -82,6 +82,10 @@ public override void Add(SourceUnit sourceUnit, string message, SourceSpan span, throw new SyntaxError(message, path, line); } else { if (sourceUnit != null) { + // an eval told to start at a line below 1 names its code with the offset encoded in the + // path (RubyUtils.EncodeEvalLineOffset), which a backtrace takes back out; so does a + // warning (a syntax error's line is put back by RubyUtils.Evaluate, which catches it) + line += RubyUtils.DecodeEvalLineOffset(ref path); using (SourceCodeReader reader = sourceUnit.GetReader()) { if (reader.Encoding != null) { encoding = RubyEncoding.GetRubyEncoding(reader.Encoding); From c687879950b7dfc0e87db7026c261692d8b88e57 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:58:56 +0000 Subject: [PATCH 399/439] Word system(exception: true)'s error as CRuby does Kernel#system with exception: true raised "Command failed with status (3): exit 3" and "Command failed with signal 9: ...", and named the first argument even when it was the environment hash or an argv pair. CRuby's rb_f_system says "Command failed with exit 3: exit 3", reads a signal the way pst_message_status does ("SIGKILL (signal 9)", "(core dumped)"), and names the program: the string of a shell form, the first element of an [program, argv0] pair. The prelude's system now does the same. CRuby's TestSystem#test_system_exception passes now; ruby/spec's core/kernel/system_spec is unchanged (all pass on both builds). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 26 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 13 ++++++++++--- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index be7b57a01..dfae64a11 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1045,6 +1045,7 @@ public Tests(Driver/*!*/ driver) { Marshal_TimeAnyYear1, Marshal_RecursiveUserDef1, Eval_WarningLineBelowOne1, + Kernel_SystemExceptionMessage1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index c9824775a..a70d6182e 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10295,5 +10295,31 @@ public void Eval_WarningLineBelowOne1() { other.rb:-2: warning: END in method; use at_exit ", 0, 2); } + + /// + /// system(..., exception: true) words a failure as MRI's rb_f_system does: "Command failed with", the status as + /// pst_message_status reads it, and the command as named - an argv form's program, a shell form's whole string + /// (CRuby's TestSystem#test_system_exception). + /// + public void Kernel_SystemExceptionMessage1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } + TestOutput(@" +require 'ruby4' +[[""exit 3""], [{""A"" => ""1""}, ""exit 5""], [[""sh"", ""x""], ""-c"", ""exit 4""], [""sh"", ""-c"", ""kill -9 $$""]].each do |args| + system(*args, exception: true) +rescue RuntimeError => e + p e.message +end +p system(""exit 1"", exception: false) +", @" +""Command failed with exit 3: exit 3"" +""Command failed with exit 5: exit 5"" +""Command failed with exit 4: sh"" +""Command failed with SIGKILL (signal 9): sh"" +false +"); + } } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 7d508a0e6..b18bd291a 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9740,11 +9740,18 @@ def system(*args) status = $? return true if status.success? if exception - if status.exitstatus - raise RuntimeError, "Command failed with status (#{status.exitstatus}): #{args.first}" + # rb_f_system: "Command failed with" and pst_message_status's reading of the status, then the + # command as it was named - the program of an argv form, the whole string of a shell one. + how = if status.exitstatus + "exit #{status.exitstatus}" else - raise RuntimeError, "Command failed with signal #{status.termsig}: #{args.first}" + name = Signal.signame(status.termsig) + (name ? "SIG#{name} (signal #{status.termsig})" : "signal #{status.termsig}") + + (status.coredump? ? " (core dumped)" : "") end + command = args.find { |arg| !arg.is_a?(::Hash) } + command = command.first if command.is_a?(::Array) + raise RuntimeError, "Command failed with #{how}: #{command}" end false end From 94e9ce5d7b38dc78ab46001b1d367806c93764e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:58:56 +0000 Subject: [PATCH 400/439] Take -s from a script's #! line A script whose first line is "#! /usr/local/bin/ruby -s" gets its -xyz arguments as globals in CRuby even when it is started as "ruby script": MRI's load_file reads the switches after "ruby" on the #! line as if they had been given on the command line (moreswitches). IronRuby ignored them, so $x stayed nil. The command line now reads the #! line it already looks at for the script check and, when the switches there include -s (alone or among single-letter flags, "-ws"), processes the script's switches as -s would. This runs in the console host before a runtime exists, so there is no IronRuby.Tests case; CRuby's TestSystem#test_system, which runs such a script, passes now, and ruby/spec's command_line suite is unchanged (all 175 examples pass on both builds). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/Ruby/Hosting/RubyCommandLine.cs | 47 +++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Hosting/RubyCommandLine.cs b/Src/Ruby/Hosting/RubyCommandLine.cs index 49589f736..df0f4b96d 100644 --- a/Src/Ruby/Hosting/RubyCommandLine.cs +++ b/Src/Ruby/Hosting/RubyCommandLine.cs @@ -153,11 +153,21 @@ protected override int RunFile(string fileName) { } var options = ((RubyContext)Language).RubyOptions; - if (!HasRubyScript(scriptPath, options.SkipToRubyShebang)) { + string shebang; + if (!HasRubyScript(scriptPath, options.SkipToRubyShebang, out shebang)) { Console.Write(String.Format("{0}: no Ruby script found in input (LoadError)\n", fileName), Style.Error); return 1; } + // The switches on the script's #!...ruby line count as if given on the command line (MRI's + // moreswitches); -s, which the script's own arguments depend on, is the one taken here. + if (!options.ScriptSwitches && ShebangHasScriptSwitches(shebang)) { + int? status = ProcessScriptSwitches((RubyContext)Language); + if (status.HasValue) { + return status.Value; + } + } + return RunFile(Engine.CreateScriptSourceFromFile(RubyUtils.CanonicalizePath(fileName), GetSourceCodeEncoding())); } @@ -166,7 +176,8 @@ protected override int RunFile(string fileName) { /// the first #!...ruby line (prism skips to it); a script without one is a LoadError that /// MRI reports without a backtrace. /// - private static bool HasRubyScript(string/*!*/ path, bool skipToRubyShebang) { + private static bool HasRubyScript(string/*!*/ path, bool skipToRubyShebang, out string shebang) { + shebang = null; try { using (var reader = new StreamReader(path, Encoding.Latin1)) { string line = reader.ReadLine(); @@ -175,10 +186,12 @@ private static bool HasRubyScript(string/*!*/ path, bool skipToRubyShebang) { return true; } } else if (line.IndexOf("ruby", StringComparison.Ordinal) >= 0 || RubyUtils.ShebangNamesIronRuby(line)) { + shebang = line; return true; } while ((line = reader.ReadLine()) != null) { if (line.StartsWith("#!", StringComparison.Ordinal) && line.IndexOf("ruby", StringComparison.Ordinal) >= 0) { + shebang = line; return true; } } @@ -191,6 +204,36 @@ private static bool HasRubyScript(string/*!*/ path, bool skipToRubyShebang) { } } + /// + /// Whether the switches after "ruby" on a #! line include -s, alone ("-s") or among other + /// single-letter flags ("-ws"). + /// + private static bool ShebangHasScriptSwitches(string shebang) { + if (shebang == null) { + return false; + } + int ruby = shebang.IndexOf("ruby", StringComparison.Ordinal); + if (ruby < 0) { + return false; + } + foreach (string word in shebang.Substring(ruby + 4).Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)) { + if (word.Length < 2 || word[0] != '-' || word[1] == '-') { + continue; + } + bool flags = true; + for (int i = 1; i < word.Length; i++) { + if ("acdlnpsvwy".IndexOf(word[i]) < 0) { + flags = false; + break; + } + } + if (flags && word.IndexOf('s') > 0) { + return true; + } + } + return false; + } + protected override ScriptCodeParseResult GetCommandProperties(string code) { return CreateCommandSource(code, SourceCodeKind.InteractiveCode, "(ir)").GetCodeProperties(Engine.GetCompilerOptions(ScriptScope)); } From c596f90f49d29a1868ec81a05a010c31e5dccabf Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:59:02 +0000 Subject: [PATCH 401/439] Leave an at_exit block's SystemExit in $! for the blocks after it When an at_exit block called exit, the blocks that ran after it saw $! as nil (or as whatever exception came before). MRI's rb_ec_exec_end_proc leaves the SystemExit in errinfo, so the next block's $! is that exit: at_exit { p $! }; at_exit { exit } prints #. The shutdown handlers now set the current exception to the SystemExit, as they already did for any other exception a block raised. CRuby's TestBeginEndBlock#test_errinfo_at_exit passes now; ruby/spec's core/kernel/at_exit_spec and language/END_spec are unchanged (all pass on both builds). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 22 ++++++++++++++++++++++ Src/Ruby/Runtime/RubyContext.cs | 4 ++++ 3 files changed, 27 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index dfae64a11..ee389e050 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1046,6 +1046,7 @@ public Tests(Driver/*!*/ driver) { Marshal_RecursiveUserDef1, Eval_WarningLineBelowOne1, Kernel_SystemExceptionMessage1, + AtExit_ErrinfoAfterExit1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index a70d6182e..50ac022b3 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10321,5 +10321,27 @@ p system(""exit 1"", exception: false) false "); } + + /// + /// An at_exit block that runs after another one called exit sees that SystemExit as $!, as MRI's + /// rb_ec_exec_end_proc leaves it in errinfo; a rescue in a block puts it back (CRuby's + /// TestBeginEndBlock#test_errinfo_at_exit). + /// + public void AtExit_ErrinfoAfterExit1() { + var engine = Ruby.CreateEngine(); + var log = (RubyArray)engine.Execute(@" +$log = [] +at_exit { $log << ""1:#{$!}"" } +at_exit { $log << ""2:#{$!}""; raise 'x' rescue nil } +at_exit { exit } +$log +"); + try { + engine.Runtime.Shutdown(); + } catch (SystemExit) { + // the exit the last block registered called + } + Assert(log.Count == 2 && log[0].ToString() == "2:exit" && log[1].ToString() == "1:exit"); + } } } diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index b57f973fb..1c51c0104 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -5169,6 +5169,7 @@ private void RunShutdownHandlers(ref SystemExit lastSystemExit, ref Exception la try { exitHandler(); } catch (SystemExit e) { + CurrentException = e; lastSystemExit = e; } catch (Exception e) { CurrentException = e; @@ -5195,6 +5196,9 @@ private void RunShutdownHandlers(ref SystemExit lastSystemExit, ref Exception la } catch (SystemExit e) { // Kernel#at_exit can call exit and set the exitcode. Furthermore, exit can be called // from multiple blocks registered with Kernel#at_exit. + // The handlers after it see the SystemExit as $!, as MRI's rb_ec_exec_end_proc leaves + // it in errinfo for them. + CurrentException = e; lastSystemExit = e; } catch (Exception e) { CurrentException = e; From e34abb35c96b2be6387e5e8901ddffc374b9e20e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:59:11 +0000 Subject: [PATCH 402/439] Method JIT: Array literals with a splat `[*a, x]` was refused by the method JIT: the splatted item kept 42 methods out on its own (`[*@fixed, VARARGS]`, `[:mlhs, *inner]`, prism's `[constant, *requireds, rest, *posts]`). EmitSplattingArrayLiteral builds the Array item by item, a splatted Array's elements appended where it stands. CRuby's splat takes a T_ARRAY as it is, with no to_a, so an Array of any class gives its elements; anything else (nil, a Hash, a Range, an object with to_a) deopts while the Array is still nobody's. IR_JIT_SPLAT_LITERAL=0 turns it off. Util/bench/splatlit-shapes.rb: [*a] 96.2 -> 83.8 ns, [*a, :x] 98.9 -> 88.6. Census: 40 methods up, none down. Util/jit-splatlit-matrix.rb (new) and the matrices it touches print CRuby's output in every JIT mode; language/array and IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 2 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 43 ++++++++++++ Src/Ruby/Runtime/Jit/JitRuntime.cs | 25 +++++++ Util/bench/splatlit-shapes.rb | 29 ++++++++ Util/jit-splatlit-matrix.rb | 87 ++++++++++++++++++++++++ Util/perf/LEDGER.md | 27 ++++++++ 6 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 Util/bench/splatlit-shapes.rb create mode 100644 Util/jit-splatlit-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index d25f85684..463f884c9 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -308,7 +308,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { // deopt), a type or identity test (a class that resolves the method to anything but the library's deopts) and // `x.to_i' of an Integer, nil or a plain decimal String: no Ruby code, no instance variable, nothing but a deopt "IndexInt", "IndexLong", "IndexObj", "IndexIntChecked", "IndexLongChecked", "IndexObjChecked", "HashKeyInt", - "IsKindOf", "ModuleCaseEquals", "RangeSlice", "DestructuredArray", "ElementOrNil", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", + "IsKindOf", "ModuleCaseEquals", "NewArrayOfCapacity", "ArrayAppend", "SplatAppend", "RangeSlice", "DestructuredArray", "ElementOrNil", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", }; // Integer#abs of an Int32 (widened, so it cannot overflow) and Float#abs (JitCompiler.EmitCall) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 4047d3f29..1d4575392 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1543,6 +1543,7 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { private MSA.Expression/*!*/ EmitArrayLiteral(ArrayConstructor/*!*/ node, out JT type) { var items = node.Arguments.Expressions; if (items.Length > MaxArrayLiteral) { throw Bail("array literal of " + items.Length); } + if (HasSplattedItem(node)) { return EmitSplattingArrayLiteral(node, out type); } var values = new List(items.Length); foreach (var item in items) { JT t; @@ -1553,6 +1554,42 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return IronRuby.Compiler.Methods.MakeArrayOpCall(values); } + // IR_JIT_SPLAT_LITERAL=0 turns EmitSplattingArrayLiteral off + internal static readonly bool SplatLiterals = Environment.GetEnvironmentVariable("IR_JIT_SPLAT_LITERAL") != "0"; + + /// An Array literal with a `*x' among its items, which EmitSplattingArrayLiteral takes. + internal static bool HasSplattedItem(ArrayConstructor/*!*/ node) { + foreach (var item in node.Arguments.Expressions) { + if (item is SplattedArgument) { return true; } + } + return false; + } + + /// + /// `[*a, x]', `[constant, *requireds, rest, *posts]' (prism's child_nodes), `[:mlhs, *inner]': the items left to right + /// into a new Array (JitRuntime.NewArrayOfCapacity, ArrayAppend), a splatted item's elements appended where it stands + /// (JitRuntime.SplatAppend). An Array of any class gives its elements as it is: CRuby's splat calls no to_a for a + /// T_ARRAY (rb_check_to_array). Anything else - nil, whose to_a may have been redefined, and any object, whose to_a is + /// Ruby code - deopts, while the new Array is still nobody's. Keyword splats (`**h') are not Array items here. + /// + private MSA.Expression/*!*/ EmitSplattingArrayLiteral(ArrayConstructor/*!*/ node, out JT type) { + if (!SplatLiterals) { throw Bail("array literal with a splat"); } + var items = node.Arguments.Expressions; + var list = Ast.Variable(typeof(RubyArray), "#list"); + var parts = new List { Ast.Assign(list, Ast.Call(JitRuntime.M("NewArrayOfCapacity"), Ast.Constant(items.Length))) }; + foreach (var item in items) { + var splat = item as SplattedArgument; + JT t; + var value = Emit((splat != null) ? splat.Argument : item, out t); + if (t == JT.None || t == JT.Never) { throw Bail("array literal item that jumps away"); } + parts.Add(Ast.Call(JitRuntime.M((splat != null) ? "SplatAppend" : "ArrayAppend"), list, Coerce(value, t, JT.Obj))); + } + _canDeopt = true; + parts.Add(list); + type = JT.Obj; + return Ast.Block(typeof(object), new[] { list }, parts); + } + /// /// `{}', `{a: x}', `{"k" => v, 1 => w}': the Hash the generic body makes (HashConstructor.TransformReadCore), keys and /// values evaluated in order, built by the same code (JitRuntime.NewHash, NewSymbolHash1..3). Only with keys the @@ -4532,6 +4569,12 @@ private bool Walk(RExpr/*!*/ node) { var items = arrayLiteral.Arguments.Expressions; if (items.Length > JitCompiler.MaxArrayLiteral) { return No(node); } foreach (var item in items) { + // `[*a, x]' (JitCompiler.EmitSplattingArrayLiteral): the splatted value is any object + var splat = item as SplattedArgument; + if (splat != null && JitCompiler.SplatLiterals) { + if (!Walk(splat.Argument)) { return false; } + continue; + } if (!Walk(item)) { return false; } } return true; diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index d4aed8889..4860571ea 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1251,6 +1251,31 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* // An instance variable used as a numeric operand of an outlined loop (JitCompiler.NumericIVar): // unboxed while it holds the type it held when the loop was compiled, a deopt once it does not. + /// The Array an Array literal with a splat is built in (JitCompiler.EmitSplattingArrayLiteral). + public static RubyArray/*!*/ NewArrayOfCapacity(int capacity) { + return new RubyArray(capacity); + } + + /// An item of an Array literal with a splat, appended to the Array being built. + public static void ArrayAppend(RubyArray/*!*/ list, object item) { + list.Add(item); + } + + /// + /// `*x' in an Array literal: the elements of an Array of any class, as CRuby's splat takes a T_ARRAY without to_a. + /// Anything else deopts (its to_a is the generic body's), and so does an Array another thread changes under the + /// copy: nothing but a deopt leaves this helper. + /// + public static void SplatAppend(RubyArray/*!*/ list, object value) { + var array = value as RubyArray; + if (array == null) { throw Deopt(); } + try { + list.AddRange(array, 0, array.Count); + } catch (Exception e) when (!(e is JitDeoptException)) { + throw Deopt(); + } + } + /// /// The value `a, b = v' destructures (JitCompiler.EmitDestructuringAssignment): an Array of any class as it is, which /// CRuby takes without calling to_ary; anything else deopts, before any target is written. diff --git a/Util/bench/splatlit-shapes.rb b/Util/bench/splatlit-shapes.rb new file mode 100644 index 000000000..3e8174510 --- /dev/null +++ b/Util/bench/splatlit-shapes.rb @@ -0,0 +1,29 @@ +# `[*a, x]' Array literals in hot methods (JitCompiler.EmitSplattingArrayLiteral): one splat, a splat and an item, +# prism's child_nodes shape `[c, *req, rest, *posts]'. Every line prints the sum of its results next to its time; it +# must be CRuby's. +# ruby Util/perf/ab.rb Util/bench/splatlit-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ../ironruby/ir.sh" "new=env IR_CONFIG=Release ./ir.sh" +$stdout.sync = true +class SPS + def only(a) = [*a] + def mixed(a) = [*a, :x] + def nodes(c, req, rest, posts) = [c, *req, rest, *posts] +end +def cpu; Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID); end +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times do + t0 = cpu; sum = yield n; d = cpu - t0 + best = d if d < best + end + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +o = SPS.new +A3 = [1, 2, 3] +REQ = [:a, :b] +POSTS = [:p] +N = (ENV["N"] || 1_000_000).to_i +t("only", N) { |n| i = 0; r = 0; while i < n; r += o.only(A3).size; i += 1; end; r } +t("mixed", N) { |n| i = 0; r = 0; while i < n; r += o.mixed(A3).size; i += 1; end; r } +t("nodes", N) { |n| i = 0; r = 0; while i < n; r += o.nodes(:c, REQ, nil, POSTS).size; i += 1; end; r } diff --git a/Util/jit-splatlit-matrix.rb b/Util/jit-splatlit-matrix.rb new file mode 100644 index 000000000..f326f6fd2 --- /dev/null +++ b/Util/jit-splatlit-matrix.rb @@ -0,0 +1,87 @@ +# Differential matrix for `[*a, x]' Array literals in methods the method JIT compiles (JitCompiler.EmitSplattingArrayLiteral, +# JitRuntime.SplatAppend). Run under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-splatlit-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-splatlit-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-splatlit-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-splatlit-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep SP +# The traps: an Array of any class is splatted as it is (an Array subclass's or a singleton to_a is not called); +# everything else goes through to_a (nil, a Hash, a Range, a Struct, an object with to_a, one with only to_ary, a +# String, which has none) and NilClass#to_a redefined; the result a new Array; the order of evaluation. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class SP + def initialize; @fixed = [1, 2]; @log = []; end + attr_reader :log + def only(a) = [*a] + def mixed(a, x) = [*a, x] + def nodes(c, req, rest, posts) = [c, *req, rest, *posts] + def ivar = [*@fixed, :varargs] + def order(a, b) = [note(:x), *note(a), note(:y), *note(b)] + def note(v) = (@log << v; v) +end + +class ArySub < Array + def to_a = [:sub_to_a] +end +class ToA + def to_a = [:to_a1, :to_a2] +end +class ToAry + def to_ary = [:to_ary] + def inspect = "#" +end + +o = SP.new +t("only, hot") { warm { |i| o.only([i, i]) } } +t("only, kinds") { [o.only([]), o.only([1, [2]]), o.only([nil])] } +t("result is new") { a = [1, 2]; r = o.only(a); r << 3; [a, r, r.equal?(a)] } +t("frozen source") { r = o.only([1, 2].freeze); [r, r.frozen?] } +t("mixed, hot") { warm { |i| o.mixed([i], :x) }; [o.mixed([], 1), o.mixed([1, 2], [3])] } +t("nodes, hot") { warm { |i| o.nodes(:c, [i], :r, [:p]) }; [o.nodes(1, [], 2, []), o.nodes(nil, [nil], nil, [nil, nil])] } +t("ivar") { warm { o.ivar }; o.ivar } +t("Array subclass") { o.only(ArySub[1, 2]) } +t("singleton to_a") { a = [3]; def a.to_a = [:single]; o.only(a) } +t("nil") { [o.only(nil), o.mixed(nil, 1)] } +t("a Hash") { o.only({ a: 1, b: 2 }) } +t("a Range") { o.only(1..4) } +t("a String") { o.only("str") } +t("a Struct") { o.only(Struct.new(:a, :b).new(1, 2)) } +t("an object with to_a") { o.only(ToA.new) } +t("an object with only to_ary") { o.only(ToAry.new) } +t("an Integer") { o.only(5) } +t("an Enumerator") { o.only([1, 2].each_slice(1)) } +t("order of evaluation") { q = SP.new; warm { |i| q.order([i], [i]) }; q.log.clear; r = q.order([1], nil); [r, q.log] } +class NilClass + alias_method :__orig_to_a, :to_a + def to_a = [:nil_to_a] +end +t("NilClass#to_a redefined") { [o.only(nil), o.mixed(nil, 1)] } +class NilClass + alias_method :to_a, :__orig_to_a +end +t("restored") { [o.only(nil), o.only([1])] } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index aee98eba9..829cab90e 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,33 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitsplatlit (2026-11-29, census and timed, not gated) - `[*a, x]` Array literals in the method JIT's typed + body** (the census's SplattedArgument: 42 methods refused by it alone; switch `IR_JIT_SPLAT_LITERAL`). Built on + perf/jitslice 7e258de. + - **Choosing it.** The splats left are nearly all in Array literals: `[*@fixed, Type::Builtin::VARARGS]`, + `[:mlhs, *inner]` and prism's node `child_nodes`, `[*arguments]` and `[constant, *requireds, rest, *posts]`. + Splats in call arguments are perf/lsite's area and stay out. + - **What.** `JitCompiler.EmitSplattingArrayLiteral`: the items left to right into a new Array + (`NewArrayOfCapacity`, `ArrayAppend`), a splatted item's elements appended where it stands (`SplatAppend`). + CRuby's splat takes a T_ARRAY as it is, calling no to_a (rb_check_to_array), so an Array of any class gives its + elements without calling a subclass's or a singleton to_a. Anything else deopts while the new Array is still + nobody's: nil, a Hash, a Range, a Struct, an object with to_a, a String, which has none. (CRuby does not call a + redefined NilClass#to_a for `[*nil]`; the generic body decides that, as before.) An Array changed by another + thread under the copy deopts too. The three helpers are on the sinking allow-list. + - **Census** (Src/StdLib, Util/bench, AWFY, against 7e258de): 40 methods up (2 never -> compiles, 38 never -> maybe, + 37 of them behind a call, mostly an attribute reader such as prism's `arguments`), none down. + - **app-shapes, traced:** specialized 124 -> 124, declined 29 -> 29 (prism_walk does not go through child_nodes). + - **Clock** (ab.rb -r 5, `Util/bench/splatlit-shapes.rb`, ns, off -> new, CRuby): `[*a]` 96.2 -> 83.8 (72.1), + `[*a, :x]` 98.9 -> 88.6 (151.4), `[c, *req, rest, *posts]` 150.8 -> 142.3 (217.9, overlapping). + - **Checks.** `Util/jit-splatlit-matrix.rb` (new, 21 rows): one splat, a splat and an item, the child_nodes shape, + an instance-variable splat; empty Arrays; the result new and unfrozen; an Array subclass with its own to_a; a + singleton to_a; nil, a Hash, a Range, a String, a Struct, an Integer, an Enumerator, an object with to_a and one + with only to_ary; the order of evaluation with a splat of nil; NilClass#to_a redefined, then restored. It prints + CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, IR_LIGHT_FRAMES=0 and the switch off. + splat-pass, jit-masgn, jit, jit-calls, jit-const, jit-objops and hot-shapes in the same five modes: CRuby's + output on both builds (40 runs with jit-splatlit). ruby/spec language/array and core/array/constructor: no + failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. + - **perf/jitslice (2026-11-29, census and timed, not gated) - `s[a..b]` and `ary[a...b]` in the method JIT's typed body** (the census's RangeExpression: 47 first refusals, 32 alone; switch `IR_JIT_RANGE_SLICE`). Built on perf/jitmasgn1 530202d. From 91c601199ff538570ec1cdbab9b85d714f449572 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:59:12 +0000 Subject: [PATCH 403/439] cruby-test: baseline after round ten test_system, test_beginendblock, test_eval and test_exception re-swept after the round's fixes: 6,684 tests passing (from 6,680), one file without a summary (test_iseq), as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index e7d592a99..a5de98b30 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,680 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,684 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index feef345d5..4b6088f01 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -9,7 +9,7 @@ test_ast 2666 tests 11 failures 2654 errors 0 sk test_autoload 27 tests 0 failures 2 errors 0 skips test_backtrace 31 tests 4 failures 0 errors 0 skips test_basicinstructions 26 tests 0 failures 0 errors 0 skips -test_beginendblock 16 tests 4 failures 1 errors 0 skips +test_beginendblock 16 tests 2 failures 1 errors 0 skips test_bignum 73 tests 1 failures 2 errors 0 skips test_box 65 tests 5 failures 22 errors 31 skips test_call 65 tests 1 failures 0 errors 0 skips @@ -35,7 +35,7 @@ test_encoding 15 tests 1 failures 0 errors 0 sk test_enum 90 tests 2 failures 0 errors 0 skips test_enumerator 70 tests 0 failures 0 errors 0 skips test_env 94 tests 7 failures 0 errors 1 skips -test_eval 40 tests 3 failures 0 errors 0 skips +test_eval 40 tests 2 failures 1 errors 0 skips test_exception 101 tests 13 failures 1 errors 0 skips test_fiber 35 tests 2 failures 0 errors 2 skips test_file 80 tests 0 failures 23 errors 1 skips @@ -119,7 +119,7 @@ test_struct 102 tests 0 failures 0 errors 0 sk test_super 50 tests 2 failures 1 errors 0 skips test_symbol 59 tests 0 failures 0 errors 0 skips test_syntax 171 tests 7 failures 2 errors 0 skips -test_system 8 tests 2 failures 1 errors 0 skips +test_system 8 tests 0 failures 1 errors 0 skips test_thread 98 tests 5 failures 5 errors 4 skips test_thread_cv 13 tests 0 failures 1 errors 0 skips test_thread_queue 40 tests 2 failures 1 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 69 clean, 72 with failures, 1 without a summary -10369 tests, 2552029 assertions, 488 failures, 3131 errors, 70 skips; 6680 passing +10369 tests, 2552035 assertions, 483 failures, 3132 errors, 70 skips; 6684 passing From 3656ba6273699d0191f964c7b9f2ace85fbcd6f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:10:55 +0000 Subject: [PATCH 404/439] Split UTF-16 and UTF-32 lines on a broken separator as CRuby does "AB".force_encoding("UTF-32LE").lines("B".force_encoding("UTF-32LE")) was ["\x41\x42"] where CRuby gives []. MRI's rb_str_enumerate_lines finds the separator with rb_memsearch, which for a 2- or 4-byte-minimum encoding compares a character's width at a time from the line's start but finds a one-byte separator at any byte; a hit that is not at a character's head then moves the line's start to the next head (rb_enc_right_char_head), dropping what came before, and in UTF-32 that head can lie past the end, which ends the split with nothing more. __ir_lines__ (behind #lines and #each_line with a separator) now splits UTF-16LE/BE and UTF-32LE/BE strings in bytes that way, with Onigmo's left_adjust_char_head and enclen for the two encodings. A separator that is a whole character finds the same lines as before. CRuby's TestString#test_lines and TestString2#test_lines pass now. ruby/spec's core/string lines, each_line and split specs pass on both the base build and this one; the wide-lines, astral-string, strcow and dup matrices are unchanged in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 28 ++++++ Src/Libraries/Builtins/MutableStringOps.cs | 108 +++++++++++++++++++++ 3 files changed, 137 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ee389e050..29cc93a7f 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1047,6 +1047,7 @@ public Tests(Driver/*!*/ driver) { Eval_WarningLineBelowOne1, Kernel_SystemExceptionMessage1, AtExit_ErrinfoAfterExit1, + String_LinesWideBrokenSeparator1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index 252eb3b34..910408b05 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -1444,6 +1444,34 @@ class ToHashOptions; def to_hash = {undef: :replace}; end # # # +"); + } + + /// + /// String#lines in UTF-16 and UTF-32 splits the way MRI's rb_str_enumerate_lines does: the separator is searched for a + /// character's width at a time (a one-byte one at any byte), and a hit that is not at a character's head moves the line's + /// start to the next head, past the end for a broken UTF-32 tail (CRuby's TestString#test_lines). + /// + public void String_LinesWideBrokenSeparator1() { + TestOutput(@" +require 'ruby4' +u32 = Encoding::UTF_32LE +p (+""AB"").force_encoding(u32).lines((+""B"").force_encoding(u32)) +p (+""ABCDE"").force_encoding(Encoding::UTF_32BE).lines((+""B"").force_encoding(Encoding::UTF_32BE)).map(&:bytes) +p (+""ABC"").force_encoding(Encoding::UTF_16BE).lines((+""B"").force_encoding(Encoding::UTF_16BE)).map(&:bytes) +s = ""䉁C"".encode(""UTF-16LE"") +p s.lines(""䍂"".encode(""UTF-16LE"")).map(&:bytes) +p ""a\u{1F600}b\u{1F600}"".encode(""UTF-16LE"").lines(""b"".encode(""UTF-16LE"")).map { |l| l.encode(""UTF-8"").codepoints } +p ""ab\ncd"".encode(""UTF-32BE"").lines(""\n"".encode(""UTF-32BE"")).map { |l| l.encode(""UTF-8"").codepoints } +p (+""ABCDE"").force_encoding(u32).each_line((+""B"").force_encoding(u32)).map(&:bytes) +", @" +[] +[[69]] +[[67]] +[[65, 66, 67, 0]] +[[97, 128512, 98], [128512]] +[[97, 98, 10], [99, 100]] +[[69]] "); } } diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 43b987bb5..82c90b437 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -2879,6 +2879,12 @@ public static object EachLine([NotNull]BlockParam/*!*/ block, MutableString/*!*/ /// [RubyMethod("__ir_lines__", RubyMethodAttributes.PrivateInstance)] public static RubyArray/*!*/ GetLines(MutableString/*!*/ self, [NotNull]MutableString/*!*/ separator, bool chompNewline) { + int codePage = self.Encoding.CodePage; + if (!separator.IsEmpty && (codePage == RubyEncoding.CodePageUTF16LE || codePage == RubyEncoding.CodePageUTF16BE || + codePage == RubyEncoding.CodePageUTF32LE || codePage == RubyEncoding.CodePageUTF32BE)) { + return GetWideLines(self, separator, codePage); + } + var result = new RubyArray(); int start = 0; // Length counts in the representation the receiver is held in, and the search switches a @@ -2901,6 +2907,108 @@ public static object EachLine([NotNull]BlockParam/*!*/ block, MutableString/*!*/ return result; } + /// + /// The lines of a UTF-16 or UTF-32 string, split the way MRI's rb_str_enumerate_lines splits them, in + /// bytes: rb_memsearch looks for the separator a character's width at a time from the start of the + /// line (a one-byte separator at any byte), and a hit that is not at a character's head moves the + /// start of the line to the next head (rb_enc_right_char_head) - past the end of the string for a + /// broken UTF-32 tail, which leaves nothing more. A separator that is itself a broken character + /// ("B" in UTF-32LE) finds such hits; any other one finds the same lines a character search does. + /// + private static RubyArray/*!*/ GetWideLines(MutableString/*!*/ self, MutableString/*!*/ separator, int codePage) { + byte[] bytes = self.ToByteArray(); + byte[] sep = separator.ToByteArray(); + int unit = (codePage == RubyEncoding.CodePageUTF32LE || codePage == RubyEncoding.CodePageUTF32BE) ? 4 : 2; + var result = new RubyArray(); + int start = 0; + while (start < bytes.Length) { + int hit = WideMemsearch(bytes, start, sep, unit); + if (hit < 0) { + break; + } + int adjusted = WideRightCharHead(bytes, start, hit, codePage); + if (adjusted != hit) { + start = adjusted; + continue; + } + int end = hit + sep.Length; + result.Add(self.CreateDerived(bytes.AsSpan(start, end - start).ToArray(), end - start)); + start = end; + } + if (start < bytes.Length) { + result.Add(self.CreateDerived(bytes.AsSpan(start).ToArray(), bytes.Length - start)); + } + return result; + } + + // rb_memsearch for an encoding whose characters are at least 2 or 4 bytes long + private static int WideMemsearch(byte[]/*!*/ y, int start, byte[]/*!*/ x, int unit) { + int n = y.Length - start, m = x.Length; + if (m > n) { + return -1; + } + if (m == n) { + return y.AsSpan(start).SequenceEqual(x) ? start : -1; + } + if (m == 1) { + return Array.IndexOf(y, x[0], start); + } + for (int p = start; p + m <= y.Length; p += unit) { + if (y.AsSpan(p, m).SequenceEqual(x)) { + return p; + } + } + return -1; + } + + // onigenc_get_right_adjust_char_head with UTF-16's and UTF-32's left_adjust_char_head and enclen + private static int WideRightCharHead(byte[]/*!*/ s, int start, int p, int codePage) { + if (p <= start) { + return p; + } + int end = s.Length; + int q = p; + if (codePage == RubyEncoding.CodePageUTF32LE || codePage == RubyEncoding.CodePageUTF32BE) { + q -= (q - start) % 4; + // a fixed-width encoding's enclen is the width, whatever is left + return (q < p) ? q + 4 : q; + } + bool le = codePage == RubyEncoding.CodePageUTF16LE; + if ((q - start) % 2 == 1) { + q--; + } + int low = le ? q + 1 : q; + if (low < end && (s[low] & 0xfc) == 0xdc && q > start + 1) { + q -= 2; + } + if (q < p) { + q += Utf16CharLength(s, q, end, le); + } + return q; + } + + // onigenc_mbclen for UTF-16: a character's length, what is left of a character cut short, or 1 + private static int Utf16CharLength(byte[]/*!*/ s, int p, int end, bool le) { + int len = end - p; + if (len < 2) { + return len; + } + int high = le ? s[p + 1] : s[p]; + if ((high & 0xf8) != 0xd8) { + return 2; + } + if ((high & 0xfc) == 0xd8) { + if (len < 4) { + // UTF-16BE looks at a third byte when it has one + return (le || len == 2 || (s[p + 2] & 0xfc) == 0xdc) ? len : 1; + } + if ((s[le ? p + 3 : p + 2] & 0xfc) == 0xdc) { + return 4; + } + } + return 1; + } + /// /// The byte or the character at , whichever the string is held as: /// GetChar would switch a string held as bytes to characters, and the indices GetLines works From 4b5e0c19ac9d91b586deeb5dcddc9f495f3e808e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:22:07 +0000 Subject: [PATCH 405/439] No backtrace frame for String#<<, Array#<<, Array#[], Array#[]=, Hash#[] and Hash#[]= called as operators MRI runs these inside the caller's frame when Ruby code calls them as operators (opt_ltlt, opt_aref, opt_aset), so `frozen << "x"`, `frozen_array[0] = 1`, `frozen_hash[k] = v` and a Hash's default proc show no frame for the method. Sent (send, __send__, public_send) they have one, and so do String#concat, Array#slice and Hash#store, under their own names. IronRuby showed the frame every time, and named concat's 'String#<<' and store's 'Hash#[]=', since one C# method served both names. - A new RubyStackTraceOperatorAttribute marks those methods' C# overloads: every String#<< and Array#<<, Array#[] of one argument, Array#[]= of an index and a value, Hash#[] and Hash#[]=. - RubyStackTraceBuilder drops such a frame when it was the last library frame deferred and the next frame is Ruby code's, with no Kernel#send between. Kernel#send's hidden frame and LibraryDispatcher's SendCall count as send. - DispatchIntrinsics.TryBuildSend no longer folds a send of <<, [] or []=: folded, nothing would be left in the stack to tell it from an operator. Such a send costs a dispatch more (about 20 ns). - String#concat, Array#slice and Hash#store have NoInlining wrappers of their own, so their frames carry their names. slice's and store's are [SameRubyMethod]: Method#== still says they are #[] and #[]=, as CRuby does. Not told apart: a receiver of a subclass, which MRI's opt_* instructions leave to a real call (S.new.freeze << "x" with S < String has a frame there), and a[:x] = 1, which opt_aset takes for Integer indexes only. Checked against CRuby 4.0: labels for the operators, send, __send__ and public_send, concat, slice, store, push, a default proc, three-argument []=, and a block, interpreted and after 200 calls. ruby/spec string append and concat, array element_set, element_reference, slice, push and append, hash element_set, store and element_reference, kernel send, public_send, caller and caller_locations, __send__, exception, method, unboundmethod and the language suite match the base. New IronRuby.Tests: Backtrace_OperatorFrames1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BacktraceTests.cs | 52 ++++++++++++++++++++ Src/Libraries/Builtins/HashOps.cs | 1 + Src/Libraries/Builtins/MutableStringOps.cs | 28 +++++++++-- Src/Libraries/Extensions/IDictionaryOps.cs | 22 ++++++++- Src/Libraries/Extensions/IListOps.cs | 37 ++++++++++++-- Src/Ruby/Runtime/Attributes.cs | 10 ++++ Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs | 11 ++++- Src/Ruby/Runtime/RubyStackTraceBuilder.cs | 31 ++++++++++++ 9 files changed, 184 insertions(+), 9 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 06b779a1b..94f793364 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1437,6 +1437,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_AsciiLocalePaths1, Backtrace_LibraryErrors1, Backtrace_PreludeCallerSkip1, + Backtrace_OperatorFrames1, Dlr_RubySnippet, Dlr_ClrSubtype, diff --git a/Src/IronRuby.Tests/Runtime/BacktraceTests.cs b/Src/IronRuby.Tests/Runtime/BacktraceTests.cs index 041aeaacc..88f640f1b 100644 --- a/Src/IronRuby.Tests/Runtime/BacktraceTests.cs +++ b/Src/IronRuby.Tests/Runtime/BacktraceTests.cs @@ -1061,6 +1061,58 @@ puts label(1) { r.each_line { raise 'x' } }, label(2) { r.each_line { raise 'x' "); } + /// + /// A backtrace has no frame for String#<<, Array#<<, Array#[], Array#[]=, Hash#[] and Hash#[]= called as operators, which + /// MRI runs inside the caller's frame (opt_ltlt, opt_aref, opt_aset), and has one for them sent, and for String#concat, Array#slice + /// and Hash#store, named so. Expected output is CRuby 4.0's. + /// + public void Backtrace_OperatorFrames1() { + TestOutput(@" +require 'ruby4' +def labels + yield +rescue => e + e.backtrace_locations.map(&:label).take_while { |l| l != ""Object#labels"" } +end +s = ""s"".freeze +a = [].freeze +h = {}.freeze +d = Hash.new { |_, k| raise ""no #{k}"" } +p labels { s << ""x"" } +p labels { s.<<(1) } +p labels { s.concat(""x"") } +p labels { s.send(:<<, ""x"") } +p labels { a << 1 } +p labels { a[0] = 1 } +p labels { a[0, 1] = [] } +p labels { h[1] = 2 } +p labels { h.store(1, 2) } +p labels { d[:k] } +p labels { [1][:a] } +p labels { [1].slice(:a) } +p labels { a.push(1) } +p labels { [s].each { |x| x << ""y"" } } +def m(s) = s.send(:<<, ""x"") +p labels { m(s) } +", @" +[""block in
""] +[""block in
""] +[""String#concat"", ""block in
""] +[""String#<<"", ""block in
""] +[""block in
""] +[""block in
""] +[""Array#[]="", ""block in
""] +[""block in
""] +[""Hash#store"", ""block in
""] +[""block in
"", ""block in
""] +[""block in
""] +[""Array#slice"", ""block in
""] +[""Array#push"", ""block in
""] +[""block (2 levels) in
"", ""Array#each"", ""block in
""] +[""String#<<"", ""Object#m"", ""block in
""] +"); + } + /// /// The backtrace of an exception raised in a compiled method's ensure clause: on .NET 9 and later the exception's own trace /// has the method twice (the clause runs as a funclet of it), and so did the backtrace. A method that calls itself from diff --git a/Src/Libraries/Builtins/HashOps.cs b/Src/Libraries/Builtins/HashOps.cs index 23e8c43bd..d6bf276c6 100644 --- a/Src/Libraries/Builtins/HashOps.cs +++ b/Src/Libraries/Builtins/HashOps.cs @@ -265,6 +265,7 @@ public static int GetHashCode(UnaryOpStorage/*!*/ hashStorage, ConversionStorage } [RubyMethod("[]")] + [RubyStackTraceOperator] public static object GetElement(BinaryOpStorage/*!*/ storage, IDictionary/*!*/ self, object key) { object result; if (!self.TryGetValue(CustomStringDictionary.NullToObj(key), out result)) { diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 43b987bb5..195f62eab 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -819,13 +819,34 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { // encoding aware [RubyMethod("<<")] - [RubyMethod("concat")] + [RubyStackTraceOperator] public static MutableString/*!*/ Append(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ other) { return self.Append(other); } - [RubyMethod("<<")] + // #concat of one value: #<<'s, in a frame of its own, as MRI's String#concat has one where String#<< has none + // (RubyStackTraceOperatorAttribute). Not inlined, which would leave the frame of #<< in its place. + + [RubyMethod("concat")] + [MethodImpl(MethodImplOptions.NoInlining)] + public static MutableString/*!*/ Concat(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ other) { + return Append(self, other); + } + + [RubyMethod("concat")] + [MethodImpl(MethodImplOptions.NoInlining)] + public static MutableString/*!*/ Concat(MutableString/*!*/ self, int c) { + return Append(self, c); + } + [RubyMethod("concat")] + [MethodImpl(MethodImplOptions.NoInlining)] + public static MutableString/*!*/ Concat(MutableString/*!*/ self, [NotNull]BigInteger/*!*/ c) { + return Append(self, c); + } + + [RubyMethod("<<")] + [RubyStackTraceOperator] public static MutableString/*!*/ Append(MutableString/*!*/ self, int c) { if (c < 0) { // MRI's rb_str_concat checks the receiver first: a frozen string raises FrozenError whatever it is given @@ -864,7 +885,7 @@ private static void RequireByteCode(MutableString/*!*/ self, uint c) { } [RubyMethod("<<")] - [RubyMethod("concat")] + [RubyStackTraceOperator] public static MutableString/*!*/ Append(MutableString/*!*/ self, [NotNull]BigInteger/*!*/ c) { self.RequireNotFrozen(); @@ -887,6 +908,7 @@ private static void RequireByteCode(MutableString/*!*/ self, uint c) { /// where the binder's conversion of a [DefaultProtocol] parameter would raise the TypeError first. /// [RubyMethod("<<")] + [RubyStackTraceOperator] public static MutableString/*!*/ Append(ConversionStorage/*!*/ stringCast, MutableString/*!*/ self, object other) { self.RequireNotFrozen(); return self.Append(Protocols.CastToString(stringCast, other)); diff --git a/Src/Libraries/Extensions/IDictionaryOps.cs b/Src/Libraries/Extensions/IDictionaryOps.cs index b91336897..235c3708d 100644 --- a/Src/Libraries/Extensions/IDictionaryOps.cs +++ b/Src/Libraries/Extensions/IDictionaryOps.cs @@ -127,6 +127,7 @@ public static bool Equals(BinaryOpStorage/*!*/ equals, IDictionary/*!*/ self, object key) { object result; if (!self.TryGetValue(CustomStringDictionary.NullToObj(key), out result)) { @@ -137,18 +138,35 @@ public static object GetElement(RubyContext/*!*/ context, IDictionary/*!*/ self, object key, object value) { return RubyUtils.SetHashElement(context, self, key, value); } + // #store: #[]='s, in a frame of its own, as MRI's Hash#store has one where Hash#[]= has none + // (RubyStackTraceOperatorAttribute). Not inlined, which would leave the frame of #[]= in its place. + + [RubyMethod("store")] + [MethodImpl(MethodImplOptions.NoInlining)] + [SameRubyMethod("SetElement")] + public static object Store(RubyContext/*!*/ context, Hash/*!*/ self, object key, object value) { + return SetElement(context, self, key, value); + } + + [RubyMethod("store")] + [MethodImpl(MethodImplOptions.NoInlining)] + [SameRubyMethod("SetElement")] + public static object Store(RubyContext/*!*/ context, IDictionary/*!*/ self, object key, object value) { + return SetElement(context, self, key, value); + } + // The Hash overload exists for the frozen check: Hash.Clear does not make it (see Hash). [RubyMethod("clear")] public static IDictionary/*!*/ Clear(Hash/*!*/ self) { diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index 8416d7930..a5aca0387 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -618,8 +618,11 @@ public static int GetHashCode(UnaryOpStorage/*!*/ hashStorage, ConversionStorage #region slice, [], at + // #slice of one value: #[]'s, in a frame of its own, as MRI's Array#slice has one where Array#[] with one argument has + // none (RubyStackTraceOperatorAttribute). Not inlined, which would leave the frame of #[] in its place. + [RubyMethod("[]")] - [RubyMethod("slice")] + [RubyStackTraceOperator] public static object GetElement(ConversionStorage/*!*/ integerConversion, RangeValuesStorage/*!*/ rangeValues, ConversionStorage/*!*/ fixnumCast, UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self, object index) { if (index is int) { @@ -646,6 +649,14 @@ public static object GetElement(ConversionStorage/*!*/ integerConv return GetElement(self, Protocols.CastToInteger(integerConversion, index)); } + [RubyMethod("slice")] + [MethodImpl(MethodImplOptions.NoInlining)] + [SameRubyMethod("GetElement")] + public static object Slice(ConversionStorage/*!*/ integerConversion, RangeValuesStorage/*!*/ rangeValues, + ConversionStorage/*!*/ fixnumCast, UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self, object index) { + return GetElement(integerConversion, rangeValues, fixnumCast, allocateStorage, self, index); + } + private static object GetElement(IList/*!*/ self, IntegerValue index) { if (!index.IsFixnum) { // MRI indexes with a long, so an index that fits one is merely past the end of any list. @@ -690,7 +701,7 @@ public static IList GetElements(UnaryOpStorage/*!*/ allocateStorage, /// thing it cannot do. ///
[RubyMethod("[]")] - [RubyMethod("slice")] + [RubyStackTraceOperator] public static object GetElements(CallSiteStorage>/*!*/ slice, IList/*!*/ self, [NotNull]Enumerator/*!*/ sequence) { @@ -698,8 +709,16 @@ public static object GetElements(CallSiteStorage>/*!*/ slice, + IList/*!*/ self, [NotNull]Enumerator/*!*/ sequence) { + return GetElements(slice, self, sequence); + } + + [RubyMethod("[]")] + [RubyStackTraceOperator] public static IList GetElements(ConversionStorage/*!*/ fixnumCast, UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self, [NotNull]Range/*!*/ range) { @@ -711,6 +730,14 @@ public static IList GetElements(ConversionStorage/*!*/ fixnumCast, UnaryOpS return count < 0 ? CreateResultArray(allocateStorage, self) : GetElements(allocateStorage, self, start, count); } + [RubyMethod("slice")] + [MethodImpl(MethodImplOptions.NoInlining)] + [SameRubyMethod("GetElements")] + public static IList Slice(ConversionStorage/*!*/ fixnumCast, UnaryOpStorage/*!*/ allocateStorage, + IList/*!*/ self, [NotNull]Range/*!*/ range) { + return GetElements(fixnumCast, allocateStorage, self, range); + } + [RubyMethod("at")] public static object At(ConversionStorage/*!*/ integerConversion, IList/*!*/ self, object index) { if (index is int) { @@ -764,7 +791,10 @@ private static int CastIndex(ConversionStorage/*!*/ fixnumCast, object inde return index is int ? (int)index : Protocols.CastToFixnum(fixnumCast, index); } + // (MRI's opt_aset takes an Integer index only: a[:x] = 1, which this overload converts, has a frame there and none here. + // a[1..2] = [] and a[0, 1] = [], the other overloads, have one in both.) [RubyMethod("[]=")] + [RubyStackTraceOperator] public static object SetElement(ConversionStorage/*!*/ arrayTryCast, ConversionStorage/*!*/ fixnumCast, RangeValuesStorage/*!*/ rangeValues, IList/*!*/ self, object index, object value) { RequireNotFrozen(self); @@ -2621,6 +2651,7 @@ public static object Shift(ConversionStorage/*!*/ fixnumCast, IList/*!*/ se } [RubyMethod("<<")] + [RubyStackTraceOperator] public static IList/*!*/ Append(IList/*!*/ self, object value) { self.Add(value); return self; diff --git a/Src/Ruby/Runtime/Attributes.cs b/Src/Ruby/Runtime/Attributes.cs index 4412799d1..a361acbd6 100644 --- a/Src/Ruby/Runtime/Attributes.cs +++ b/Src/Ruby/Runtime/Attributes.cs @@ -342,6 +342,16 @@ public AliasMethodAttribute(string/*!*/ newName, string/*!*/ oldName) { public sealed class RubyStackTraceHiddenAttribute : Attribute { } + /// + /// A library method that MRI runs inside its caller's frame when Ruby code calls it as an operator: opt_ltlt, opt_aref and + /// opt_aset do the work of String#<<, Array#<<, Array#[], Array#[]=, Hash#[] and Hash#[]= themselves, so an + /// exception raised there, or a backtrace taken in a Hash's default proc, has no frame for the method. Called any other + /// way - by send, or by another library method - it has one, as here (RubyStackTraceBuilder). + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public sealed class RubyStackTraceOperatorAttribute : Attribute { + } + /// /// Marks a library method that needs a Ruby caller's frame and that MRI refuses to run for a /// caller that is not Ruby code: Kernel#binding called through a Method object diff --git a/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs b/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs index 3410d1d81..9cffbfb84 100644 --- a/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs +++ b/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs @@ -170,7 +170,8 @@ internal static bool TryBuildSend(MetaObjectBuilder/*!*/ metaBuilder, CallArgume } var symbol = args.GetSimpleArgument(0) as RubySymbol; - if (symbol == null || Interlocked.Increment(ref _folds.GetOrCreateValue(args.TargetClass).Send) > MaxFoldsPerClass) { + if (symbol == null || IsOperatorFrameName(symbol) || + Interlocked.Increment(ref _folds.GetOrCreateValue(args.TargetClass).Send) > MaxFoldsPerClass) { return false; } @@ -180,6 +181,14 @@ internal static bool TryBuildSend(MetaObjectBuilder/*!*/ metaBuilder, CallArgume return true; } + // A method a backtrace has no frame for when Ruby code calls it as an operator, and has one for when it is sent + // (RubyStackTraceOperatorAttribute): folded, a send would leave nothing in the stack to tell the two apart. Unfolded, + // the hidden frame of Kernel#send does. + private static bool IsOperatorFrameName(RubySymbol/*!*/ symbol) { + string name = symbol.ToString(); + return name == "<<" || name == "[]" || name == "[]="; + } + // Whether every overload of a library method is one of the given CLR methods (an alias of another method, or the method // of a user's library, is not). private static bool IsLibraryMethod(RubyMemberInfo/*!*/ method, string/*!*/ declaringType, string/*!*/ clrName, string otherClrName = null) { diff --git a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs index 4a7e9b2fc..cd7e0ff5a 100644 --- a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs +++ b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs @@ -56,12 +56,18 @@ public sealed class RubyStackTraceBuilder { // Whether a call site has been seen since the library frame last deferred: it called the method that is still on top // as a Ruby method. private bool _callSiteSinceLastLibrary; + // The library frame last deferred is a method MRI runs inside its caller's frame when called as an operator + // (RubyStackTraceOperatorAttribute), and no hidden library method (Kernel#send) has been seen since: if the next + // frame is the caller's own, the call was Ruby code's, and the frame is dropped (DropOperatorFrame). + private bool _operatorFrameLast; private readonly RubyContext/*!*/ _context; // The number of frames of the trace up to and including the outermost one that is not a host's CLR frame, reported or // skipped (see RubyTrace); -1 while there is none. private int _rubyFrameEnd = -1; // The frame TryGetStackFrameInfo has just read is a CLR method of no Ruby library (a "visible CLR frame"). private bool _isClrFrame; + // ... is a library method marked RubyStackTraceOperator, or one marked RubyStackTraceHidden. + private bool _isOperatorFrame, _isHiddenFrame; // TracePoint's c_call location needs the frame that really made the call, which inside a // core method written in Ruby is that method's own, not its caller's. private bool _keepInternalFrames; @@ -763,12 +769,16 @@ private void AddBacktrace(IEnumerable stackTrace, int skipFrames, bo _libraryRun++; } _callSiteSinceLastLibrary = false; + _operatorFrameLast = _isOperatorFrame; continue; } } else { if (_libraryRun > 0 && IsCallSiteFrame(frame.GetMethod())) { _callSiteSinceLastLibrary = true; } + if (_isHiddenFrame) { + _operatorFrameLast = false; + } continue; } @@ -816,6 +826,7 @@ private bool AddFrame(string file, int line, string methodName, bool isClrFrame, return false; } + DropOperatorFrame(); foreach (var deferred in _deferredMethodNames) { if (skipFrames == 0) { _trace.Add(CreateFrame(file, line, deferred)); @@ -876,6 +887,7 @@ private int AddInternalFrame(string methodName) { return 0; } int deferred = _deferredMethodNames.Count; + DropOperatorFrame(); string owner, name; SplitLabel(methodName, out owner, out name); @@ -900,6 +912,18 @@ private int AddInternalFrame(string methodName) { return dropped; } + /// + /// The library frame last deferred is gone when Ruby code called it as an operator (see RubyStackTraceOperatorAttribute): + /// called by a frame of Ruby code, the next one being reported, with nothing but call sites in between. (A receiver of a + /// subclass, which MRI calls the method for, is not told apart: `class S < String; end' and S.new.freeze << "x".) + /// + private void DropOperatorFrame() { + if (_operatorFrameLast && _libraryRun > 0) { + _deferredMethodNames.RemoveAt(_deferredMethodNames.Count - 1); + } + _operatorFrameLast = false; + } + // "Enumerable#map" -> ("Enumerable", "map"); "Math.sqrt" -> ("Math", "sqrt"); "foo" -> (null, "foo") private static void SplitLabel(string/*!*/ label, out string owner, out string/*!*/ name) { int i = label.LastIndexOfAny(_LabelSeparators); @@ -987,6 +1011,9 @@ private static bool IsInternalFrameFile(string file) { private bool TryGetStackFrameInfo(StackFrame/*!*/ frame, out string/*!*/ methodName, out string/*!*/ fileName, out int line) { MethodBase method = frame.GetMethod(); _isClrFrame = false; + _isOperatorFrame = false; + // a send the library dispatcher makes itself (LibraryDispatcher's SendCall) is Kernel#send's hidden frame + _isHiddenFrame = method.DeclaringType == typeof(Calls.SendCall); methodName = method.Name; fileName = (_needsClrFileInfo) ? GetFileName(frame) : null; @@ -1014,8 +1041,10 @@ private bool TryGetStackFrameInfo(StackFrame/*!*/ frame, out string/*!*/ methodN } else { FrameAttributes frameAttributes = GetFrameAttributes(method); if (frameAttributes.Hidden) { + _isHiddenFrame = true; return false; } + _isOperatorFrame = frameAttributes.Operator; object[] attrs = frameAttributes.RubyMethods; if (attrs.Length > 0) { // Ruby library method: @@ -1047,10 +1076,12 @@ private bool TryGetStackFrameInfo(StackFrame/*!*/ frame, out string/*!*/ methodN /// The attributes of a CLR method that decide how its frame is reported. private sealed class FrameAttributes { internal readonly bool Hidden; + internal readonly bool Operator; internal readonly object[]/*!*/ RubyMethods; internal FrameAttributes(MethodBase/*!*/ method) { Hidden = method.IsDefined(typeof(RubyStackTraceHiddenAttribute), false); + Operator = method.IsDefined(typeof(RubyStackTraceOperatorAttribute), false); RubyMethods = Hidden ? new object[0] : method.GetCustomAttributes(typeof(RubyMethodAttribute), false); } } From 409e75f224af2f668acb47bc20fa92358e8c1f28 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:22:15 +0000 Subject: [PATCH 406/439] Report a chilled string's mutation before setbyte and << read it A Warning.warn override can change the string a chilled-string warning is about. setbyte read the length before the warning ran and wrote past the end of a string the override had shortened, raising System::IndexOutOfRangeException; << resolved the encodings before the warning and kept UTF-8 for a receiver the override had made BINARY. MRI makes the receiver modifiable first (str_make_independent in rb_str_setbyte, str_modifiable in rb_str_buf_append), so its checks see the string as the override left it: an IndexError, a BINARY result. MutableString.ReportChilledMutation does that step on its own, and the two methods call it before they read anything. CRuby's TestString#test_setbyte_chilled_string_warning and #test_concat_chilled_string_warning pass now. ruby/spec's core/string setbyte, concat, append and chilled_string specs pass on both builds; the jit-objops, jit-strlit, jit-strop, strcow and string-search matrices are unchanged in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 42 ++++++++++++++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 5 +++ Src/Ruby/Builtins/MutableString.cs | 14 ++++++++ 4 files changed, 62 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 29cc93a7f..a26967490 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1048,6 +1048,7 @@ public Tests(Driver/*!*/ driver) { Kernel_SystemExceptionMessage1, AtExit_ErrinfoAfterExit1, String_LinesWideBrokenSeparator1, + String_ChilledWarningChangesReceiver1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index 910408b05..81a548087 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -1472,6 +1472,48 @@ p s.lines(""䍂"".encode(""UTF-16LE"")).map(&:bytes) [[97, 128512, 98], [128512]] [[97, 98, 10], [99, 100]] [[69]] +"); + } + + /// + /// String#setbyte and #<< report a chilled receiver's first mutation before they read its length or encoding, as MRI's + /// rb_str_setbyte and rb_str_buf_append do: a Warning.warn that changes the string then changes what they see (CRuby's + /// TestString#test_setbyte_chilled_string_warning and #test_concat_chilled_string_warning). + /// + public void String_ChilledWarningChangesReceiver1() { + TestOutput(@" +Warning[:deprecated] = true +module ShrinkOnWarning + def warn(message, category: nil, **kwargs) + return super unless category == :deprecated + $target.replace($replacement) + nil + end +end +Warning.extend(ShrinkOnWarning) +[7, -7].each do |i| + $target = ""abcdefghij"" + $replacement = ""ab"" + begin + $target.setbyte(i, 0) + rescue IndexError => e + p e + end +end +$target = ""abcdefghij"" +$replacement = ""\xff\xfe"".b +$target << $target +p $target, $target.encoding +$target = ""abcdefghij"" +$replacement = ""abc"" +p $target.setbyte(1, 66), $target +", @" +# +# +""\xFF\xFE\xFF\xFE"" +# +66 +""aBc"" "); } } diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 82c90b437..7247cad6f 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -821,6 +821,9 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { [RubyMethod("<<")] [RubyMethod("concat")] public static MutableString/*!*/ Append(MutableString/*!*/ self, [DefaultProtocol, NotNull]MutableString/*!*/ other) { + // the encodings are resolved after the chilled warning, whose Warning.warn may change the + // receiver - and the argument, when it is the receiver (rb_str_buf_append) + self.ReportChilledMutation(); return self.Append(other); } @@ -1462,7 +1465,9 @@ private static object CodeToObject(long code) { [RubyMethod("setbyte")] public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index, [DefaultProtocol]int value) { + // the length is read after the chilled warning, whose Warning.warn may change it (rb_str_setbyte) self.RequireNotFrozen(); + self.ReportChilledMutation(); int count = self.GetByteCount(); int at = index < 0 ? index + count : index; if (at < 0 || at >= count) { diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index 8905c3f5a..a9d65bae9 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -1263,6 +1263,20 @@ public bool IsInterned { get { return (_flags & IsInternedFlag) != 0; } } + /// + /// Reports a chilled string's first mutation, as the mutation that follows would (with that + /// mutation's other checks: frozen, locked, shared), for a caller that reads the string's length + /// or encoding first. MRI makes the string modifiable before it reads them (str_make_independent + /// in rb_str_setbyte, str_modifiable in rb_str_buf_append), and a Warning.warn override that the + /// chilled warning calls can change both. + /// + public void ReportChilledMutation() { + uint flags = _flags; + if ((flags & IsChilledFlag) != 0) { + FrozenOrCopyOnWrite(flags); + } + } + public void RequireNotFrozen() { if (IsFrozen) { throw RubyExceptions.CreateStringFrozenError(this); From 4fce2e355c0b695bb76270a71109adabc6af9ae2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:31:43 +0000 Subject: [PATCH 407/439] Ledger: round 12's gate, PASS Round 12 of round thirty-seven (perf/crubydiff's rounds 21-22, claude/cruby-test's rounds 5-7, perf/yieldloop2-3, perf/ignoredblock, perf/jitcaseeq and perf/jitdefined, at cc6aada1 against master c4719ea) passed the gate: IronRuby.Tests 1,478 run, none failed; the matrices in seven modes with only the two known DIFFs, regexp-binary-ctype one line nearer CRuby; a probe file for the round as CRuby under C.UTF-8 and LANG=C; ruby/spec's five suites with no unlisted failure; the census with 70 method-JIT ups and nothing down; AWFY 12 at a geomean of 0.919 and 0.913; start-up at 0.83-0.96 of master's. The round's entries are marked gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 3f90d8954..369d1273d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,35 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-29 for round 12 of round thirty-seven** (perf/crubydiff's twenty-first and twenty-second rounds + with the attr_* source locations reconciled with claude/cruby-test's, claude/cruby-test's rounds 5-7 (test/ruby + 6,660 -> 6,676 passing), perf/yieldloop2 and perf/yieldloop3, perf/ignoredblock with literalcode's census reason and + perf/nblcost, perf/jitcaseeq and perf/jitdefined): the branch at cc6aada1 against master c4719ea, Release net10.0, + the composite R2R host on both, four cores: **PASS**. Gated in a worktree of its own and pushed after. + The merge itself: JitIntrinsics.cs, where perf/yieldloop3 and perf/jitcaseeq each added the same Module#=== + intrinsic (ModuleCaseCompare for outlined loops, ModuleCaseEquals for typed bodies; both kept, each for its own + callers - one to fold into the other later); the ledger kept both sides. ReflectionCache.Generated.cs is what + ClassInitGenerator writes. No new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,478 tests, every one executed, none failed. + `gate-matrices.rb --all` in 7 modes (the six default ones, and IR_IGNORED_BLOCKS, IR_JIT_CASE_EQ, + IR_JIT_DEFINED_IVAR and IR_OSR_YIELD off at once): 1,355 same, 115 baseline, 14 DIFF, the two known ones: + regexp-binary-ctype now 8 lines from CRuby (9 before; perf/crubydiff's /i folding made the `[[:upper:]]/i` row + CRuby's), string-race-matrix over five runs of each tree (rows not always ok 108 -> 86, lost writes 100 -> 0, no + row failing only on the new build). + A probe file for the round - /i folding (long s, micro, Kelvin, final sigma, an astral pair), Pathname's internal + location and an attr_accessor's, Regexp.timeout's rounding, pack's format-modified check, fnmatch escapes, a + class variable through a singleton class, const_set on a frozen object's singleton class, take_while, + drop_while and sum hot and with values that leave sum's fast loop, `C === x` hot and then `===` redefined, + defined?(@x) hot as condition and value, an ignored literal and then a callee that keeps it - prints CRuby's + output under C.UTF-8 and LANG=C with the JIT on and off and with the round's switches off (master: 14 lines + differ). + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against round 11: method JIT 70 up, nothing down; light frames unchanged. + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.919 and 0.913; none more + than 5% slower in both. micro-table in both orders: no line more than 5% slower in both. + Start-up on the composite R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 394 -> 377 and + 366 -> 349, `gem --version` 466 -> 437 and 441 -> 412, `gem list` 864 -> 725 and 811 -> 709, `require "irb"` + 888 -> 739 and 854 -> 774, irb 1+1 973 -> 869 and 966 -> 821: 0.83-0.96. - **Gate of 2026-11-29 for round 11 of round thirty-seven** (perf/crubydiff's sixteenth to twentieth rounds, and claude/cruby-test's first two rounds - CRuby's own test/ruby, 6,614 -> 6,660 passing, with the fix for a hang in perf/datafilter): the branch at 892d1386 against master c4719ea, Release net10.0, the composite R2R host on both, @@ -2076,7 +2105,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 856 -> 727 and 817 -> 726, irb 1+1 894 -> 807 and 954 -> 828: 0.83-0.98. - **perf/yieldloop3 (2026-11-29) - Array#sum with a block: its Integer case in a loop of its own that the compiled copy - runs (gap 18)** - not gated. `__array_sum__`'s loop could not be compiled: its tail has `next`, `return`, calls and a + runs (gap 18)** - gated 2026-11-29 (round 12's gate entry). `__array_sum__`'s loop could not be compiled: its tail has `next`, `return`, calls and a nested `while true` with a second yield. The common case, Integers all along, now has a loop of its own in front of it (`x = yield(__ary_at__(i)); i = i.succ; break unless ::Integer === x && ::Integer === acc; acc = acc + x; j = i`): it leaves at the first value that is not an Integer (or once acc is not one, as a redefined Integer#+ can make it), @@ -2101,7 +2130,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the whole suite was not run (the session's permission check refuses it). - **perf/yieldloop2 (2026-11-29) - the prelude's `take_while` and `drop_while` run in their loops' compiled copies (gap - 18, stage 3a's own measure)** - not gated. Stage 3a's design names its measure as the prelude's `while ... yield` + 18, stage 3a's own measure)** - gated 2026-11-29 (round 12's gate entry). Stage 3a's design names its measure as the prelude's `while ... yield` methods, which round one did not reach. Of the prelude's 16 loops with one yield, 6 have it as a statement, 3 as a condition (`break unless yield(x)`), 7 in an expression; the hot iterators (`take_while`, `sum`, `to_h`, `uniq`) all stopped first at `__ary_size__`. Chosen over stage 3's method resume, which my design round measured at about 2% @@ -2130,7 +2159,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the session's permission check again. - **perf/ignoredblock (round thirty-seven, 2026-11-29) - a literal block given to a method whose typed body ignored it is - left reusable (gap 13)** - allocation, not time; not gated. `nb { }` to `def nb; 1; end` never parked: the parked slot's + left reusable (gap 13)** - allocation, not time; gated 2026-11-29 (round 12's gate entry). `nb { }` to `def nb; 1; end` never parked: the parked slot's `StageParkedProc` found the literal a plain block nothing had converted (kind `Block`, no flags), since the method JIT's typed body for a method that never uses its block ignores it, where the generic body's light frame converts it and leaves it reusable (`ConvertAsLightFrame`, then the exit). After 64 such calls the slot gave up, and every call made a scope and a @@ -2147,7 +2176,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has redefined to keep its block (each call's Proc its own), back, and a deopt: CRuby's output with the JIT on and off. ruby/spec language in full: 2935 examples, the one known error (send_spec's `into`/`to`). IronRuby.Tests in full on Debug: PASSED. -- **perf/jitdefined (2026-11-29, census and timed, not gated) - `defined?(@x)` in the method JIT's typed body** (the +- **perf/jitdefined (2026-11-29, census and timed, gated 2026-11-29 (round 12's gate entry)) - `defined?(@x)` in the method JIT's typed body** (the census's `IsDefinedExpression`: 118 methods refused, 36 by it alone, nearly all `defined?(@ivar)`; switch `IR_JIT_DEFINED_IVAR`). Built on perf/jitcaseeq da02d10 (happy-gauss 50b2427 merged). - **First, the screen refusals passed over.** `@x ||= v` (296 first refusals, 44 alone) is already compiled. The @@ -2182,7 +2211,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has jit-objops again after the condition fix. ruby/spec language/defined: 258 examples, no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED, before and after the condition fix. -- **perf/jitcaseeq (2026-11-28, checks finished 2026-11-29, census and timed, not gated) - `C === x` with +- **perf/jitcaseeq (2026-11-28, checks finished 2026-11-29, census and timed, gated 2026-11-29 (round 12's gate entry)) - `C === x` with C a class or module constant in the method JIT's typed body** (the census's `MethodCall ===`: 304 methods refused, 170 by it alone; switch `IR_JIT_CASE_EQ`). Built on happy-gauss fcbc67b. - **What.** `C === x`, with C a constant whose name has a lower-case letter (`Integer`, `Foo::Bar`; not `PATTERN`, @@ -4607,7 +4636,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's), its eleventh to fifteenth 2026-11-28 (round 10's), its sixteenth to twentieth 2026-11-29 (round 11's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's), its eleventh to fifteenth 2026-11-28 (round 10's), its sixteenth to twentieth 2026-11-29 (round 11's), its twenty-first and twenty-second 2026-11-29 (round 12's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope From a0f3f00750963eca11c618f63da6a7601e878a20 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:32:13 +0000 Subject: [PATCH 408/439] Every library error made and thrown at once defers its backtrace walk; keepers clear the mark perf/unkept's third round. Places that keep an exception to hand it to Ruby again now call RubyExceptionData.MarkKept, which resolves a pending catch site and clears RaisedUnkept: a thread's at its exit (re-raised by every Thread#join and #value), Ractor's, Fiddle's callback error, MessagePack's, MiniSsl's, OpenSSL's verify callback's, the C API's pending one and StackGuard's. With that, every throw RubyExceptions.Create...(...) or Make...(...) in Src/Ruby (but the compiler) and Src/Libraries throws RubyExceptionData.Unkept(...) of it: 1,367 sites in 149 files, one line each, rewritten by a script. IO#read_nonblock in the prelude rescued what the primitive raised and raised it again even with exception: true; it now calls the primitive directly then, which already raises an IO::EAGAINWaitReadable (now marked) or an EOFError. A rescued read_nonblock with nothing to read: 43.6 -> 10.1 us (CRuby 2.3). File.open of a missing file is left: the CLR throws DirectoryNotFoundException twice before the ENOENT. Checked: Util/unkept-matrix.rb (now also read_nonblock, a thread's error joined twice and read through value, an error raised again) against CRuby with the switch on and off and the JIT on and off; the exception and backtrace matrices in every mode (55 same); read_nonblock's behaviour against CRuby; ruby/spec core exception, io, kernel, array, hash, string, integer, file, struct and thread on both builds (the same failing examples) and language in full; IronRuby.Tests on Debug (passed). The census is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Libraries.Yaml/PsychNative.cs | 10 +- Src/Libraries/BCrypt/BCrypt.cs | 16 +- Src/Libraries/BigDecimal/BigDecimalOps.cs | 30 ++-- Src/Libraries/Builtins/ArrayOps.cs | 22 +-- Src/Libraries/Builtins/BasicObjectOps.cs | 16 +- Src/Libraries/Builtins/BindingOps.cs | 16 +- Src/Libraries/Builtins/ClassOps.cs | 8 +- Src/Libraries/Builtins/Comparable.cs | 12 +- Src/Libraries/Builtins/Dir.cs | 24 +-- Src/Libraries/Builtins/EncodingConverter.cs | 40 ++--- Src/Libraries/Builtins/Enumerable.cs | 10 +- Src/Libraries/Builtins/Enumerator.cs | 2 +- Src/Libraries/Builtins/ExceptionOps.cs | 6 +- Src/Libraries/Builtins/Exceptions.cs | 20 +-- Src/Libraries/Builtins/FileOps.cs | 74 ++++----- Src/Libraries/Builtins/FileTest.cs | 4 +- Src/Libraries/Builtins/HashOps.cs | 30 ++-- Src/Libraries/Builtins/Integer.cs | 24 +-- Src/Libraries/Builtins/IoOps.cs | 89 ++++++----- Src/Libraries/Builtins/KernelOps.cs | 144 ++++++++--------- Src/Libraries/Builtins/Marshal.cs | 132 +++++++-------- Src/Libraries/Builtins/MatchDataOps.cs | 2 +- Src/Libraries/Builtins/MethodOps.cs | 4 +- Src/Libraries/Builtins/ModuleOps.cs | 118 +++++++------- Src/Libraries/Builtins/MutableStringOps.cs | 150 +++++++++--------- Src/Libraries/Builtins/ObjectSpace.cs | 14 +- Src/Libraries/Builtins/PosixProcess.cs | 6 +- Src/Libraries/Builtins/PosixSignals.cs | 20 +-- Src/Libraries/Builtins/PosixSpawn.cs | 8 +- Src/Libraries/Builtins/PrintOps.cs | 2 +- Src/Libraries/Builtins/ProcOps.cs | 16 +- Src/Libraries/Builtins/RactorOps.cs | 34 ++-- Src/Libraries/Builtins/RangeOps.cs | 34 ++-- Src/Libraries/Builtins/RefinementOps.cs | 12 +- Src/Libraries/Builtins/RubyEncoder.cs | 70 ++++---- Src/Libraries/Builtins/RubyEncodingOps.cs | 6 +- Src/Libraries/Builtins/RubyPipe.cs | 2 +- Src/Libraries/Builtins/RubyProcess.cs | 20 +-- Src/Libraries/Builtins/RubyRegexOps.cs | 32 ++-- Src/Libraries/Builtins/RubyTime.cs | 4 +- Src/Libraries/Builtins/RubyTimeOps.cs | 120 +++++++------- Src/Libraries/Builtins/Signal.cs | 2 +- Src/Libraries/Builtins/SingletonOps.cs | 4 +- Src/Libraries/Builtins/Strftime.cs | 6 +- Src/Libraries/Builtins/StringFormatter.cs | 82 +++++----- Src/Libraries/Builtins/StructOps.cs | 10 +- Src/Libraries/Builtins/SymbolOps.cs | 2 +- Src/Libraries/Builtins/ThreadOps.cs | 22 +-- Src/Libraries/Builtins/TracePointOps.cs | 36 ++--- Src/Libraries/Builtins/UnboundMethod.cs | 6 +- Src/Libraries/Builtins/WarningOps.cs | 10 +- Src/Libraries/Builtins/WeakMap.cs | 6 +- Src/Libraries/Builtins/WindowsSpawn.cs | 6 +- Src/Libraries/CoolIo/CoolIo.cs | 66 ++++---- Src/Libraries/Date/Date.cs | 18 +-- Src/Libraries/Date/DateFormatter.cs | 2 +- Src/Libraries/Date/DateTime.cs | 8 +- Src/Libraries/Digest/Digest.cs | 14 +- Src/Libraries/Erb/ErbEscape.cs | 6 +- Src/Libraries/Extensions/CharOps.cs | 2 +- Src/Libraries/Extensions/ClrBigInteger.cs | 6 +- Src/Libraries/Extensions/ClrInteger.cs | 6 +- Src/Libraries/Extensions/ClrNameOps.cs | 2 +- Src/Libraries/Extensions/ClrStringOps.cs | 12 +- Src/Libraries/Extensions/DecimalOps.cs | 2 +- .../Extensions/FlagEnumerationOps.cs | 6 +- Src/Libraries/Extensions/IDictionaryOps.cs | 4 +- Src/Libraries/Extensions/IListOps.cs | 76 ++++----- Src/Libraries/Extensions/IronRubyOps.cs | 6 +- Src/Libraries/Extensions/NumericRounding.cs | 16 +- Src/Libraries/Extensions/TaskOps.cs | 2 +- Src/Libraries/Extensions/TupleOps.cs | 4 +- Src/Libraries/Extensions/TypeGroupOps.cs | 8 +- Src/Libraries/Extensions/TypeOps.cs | 2 +- Src/Libraries/Extensions/TypeTrackerOps.cs | 2 +- Src/Libraries/Fiddle/Fiddle.cs | 4 +- Src/Libraries/Fiddle/FiddleCall.cs | 14 +- Src/Libraries/Fiddle/FiddleClosure.cs | 4 +- Src/Libraries/Fiddle/FiddleFunction.cs | 20 +-- Src/Libraries/Fiddle/FiddleHandle.cs | 2 +- Src/Libraries/Fiddle/FiddlePointer.cs | 10 +- Src/Libraries/Iconv/Iconv.cs | 2 +- Src/Libraries/Markly/Markly.cs | 30 ++-- Src/Libraries/MessagePack/MessagePack.cs | 62 ++++---- Src/Libraries/Nio4r/Nio4r.cs | 40 ++--- Src/Libraries/Oj/Oj.cs | 60 +++---- Src/Libraries/Oj/OjDump.cs | 6 +- Src/Libraries/Oj/OjOptions.cs | 58 +++---- Src/Libraries/Oj/OjParse.cs | 8 +- Src/Libraries/Oj/OjRails.cs | 4 +- Src/Libraries/OpenSSL/OpenSSL.cs | 18 +-- Src/Libraries/Puma/MiniSsl.cs | 2 +- Src/Libraries/Rbs/RbsParser.cs | 6 +- Src/Libraries/Socket/BasicSocket.cs | 14 +- Src/Libraries/Socket/Socket.cs | 4 +- Src/Libraries/Socket/UNIXSocket.cs | 4 +- Src/Libraries/Sqlite3/Sqlite3.cs | 12 +- Src/Libraries/StringIO/StringIO.cs | 34 ++-- Src/Libraries/StringScanner/StringScanner.cs | 10 +- Src/Libraries/Strptime/Strptime.cs | 32 ++-- Src/Libraries/Thread/RubyConditionVariable.cs | 2 +- Src/Libraries/Thread/RubyMutex.cs | 14 +- Src/Libraries/Thread/RubyQueue.cs | 14 +- Src/Libraries/Thread/SizedQueue.cs | 4 +- Src/Libraries/Yajl/Yajl.cs | 6 +- Src/Libraries/Zstd/Zstd.cs | 92 +++++------ Src/Ruby/Builtins/CharacterMap.cs | 4 +- Src/Ruby/Builtins/DescriptorStream.cs | 12 +- Src/Ruby/Builtins/Hash.Storage.cs | 4 +- Src/Ruby/Builtins/Hash.cs | 2 +- Src/Ruby/Builtins/IOMode.cs | 26 +-- Src/Ruby/Builtins/InputLoopOps.cs | 4 +- Src/Ruby/Builtins/MatchData.cs | 4 +- Src/Ruby/Builtins/MutableString.cs | 20 +-- Src/Ruby/Builtins/MutableStringStream.cs | 2 +- Src/Ruby/Builtins/Proc.cs | 2 +- Src/Ruby/Builtins/Range.cs | 2 +- Src/Ruby/Builtins/RubyBufferedStream.cs | 2 +- Src/Ruby/Builtins/RubyClass.cs | 20 +-- Src/Ruby/Builtins/RubyEncoding.cs | 2 +- Src/Ruby/Builtins/RubyFile.cs | 22 +-- Src/Ruby/Builtins/RubyIO.cs | 54 +++---- Src/Ruby/Builtins/RubyModule.cs | 18 +-- Src/Ruby/Builtins/RubyRegex.cs | 8 +- Src/Ruby/Builtins/RubyStruct.cs | 2 +- Src/Ruby/CApi/CApi.Calls.cs | 26 +-- Src/Ruby/CApi/CApi.Collections.cs | 6 +- Src/Ruby/CApi/CApi.Debug.cs | 4 +- Src/Ruby/CApi/CApi.Io.cs | 14 +- Src/Ruby/CApi/CApi.Library.cs | 38 ++--- Src/Ruby/CApi/CApi.Mirrors.cs | 4 +- Src/Ruby/CApi/CApi.Numbers.cs | 38 ++--- Src/Ruby/CApi/CApi.Objects.cs | 42 ++--- Src/Ruby/CApi/CApi.Strings.cs | 34 ++-- Src/Ruby/CApi/CApi.Values.cs | 8 +- Src/Ruby/CApi/CApi.Variables.cs | 18 +-- Src/Ruby/CApi/CApi.cs | 32 ++-- Src/Ruby/CApi/NativeDigest.cs | 6 +- Src/Ruby/Runtime/Conversions/Converter.cs | 18 +-- Src/Ruby/Runtime/Globals/GlobalVariable.cs | 2 +- .../Globals/SpecialGlobalVariableInfo.cs | 8 +- Src/Ruby/Runtime/IntegerValue.cs | 6 +- Src/Ruby/Runtime/Loader.cs | 32 ++-- Src/Ruby/Runtime/Protocols.cs | 14 +- Src/Ruby/Runtime/RubyContext.cs | 46 +++--- Src/Ruby/Runtime/RubyExceptionData.cs | 16 ++ Src/Ruby/Runtime/RubyOps.cs | 88 +++++----- Src/Ruby/Runtime/RubyUtils.cs | 34 ++-- Src/Ruby/Runtime/StackGuard.cs | 4 +- Src/StdLib/ironruby/ruby4.rb | 5 + Util/perf/LEDGER.md | 33 +++- Util/unkept-matrix.rb | 4 +- 152 files changed, 1648 insertions(+), 1599 deletions(-) diff --git a/Src/Libraries.Yaml/PsychNative.cs b/Src/Libraries.Yaml/PsychNative.cs index 53bf39d66..ddcacb0e1 100644 --- a/Src/Libraries.Yaml/PsychNative.cs +++ b/Src/Libraries.Yaml/PsychNative.cs @@ -123,7 +123,7 @@ public static object NativeParse(PsychHandlerSites/*!*/ sites, RespondToStorage/ engine = new LibyamlParser(MakeScanner(respondTo, yaml, ioEncoding)); } catch (InvalidCastException) { // An IO whose #read answers something other than a String. - throw RubyExceptions.CreateTypeError("wrong argument type (expected String)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type (expected String)")); } context.SetInstanceVariable(parser, "@__scanner", engine.Scanner); @@ -381,7 +381,7 @@ private static MutableString MakeString(string value, RubyEncoding internalEncod [RubyMethod("__emitter_emit", RubyMethodAttributes.PublicSingleton)] public static MutableString/*!*/ EmitEvent(RubyModule/*!*/ self, [NotNull]LibyamlEmitter/*!*/ emitter, [NotNull]IList/*!*/ ev) { if (ev.Count == 0) { - throw RubyExceptions.CreateArgumentError("malformed emitter event"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("malformed emitter event")); } return Emit(emitter, MakeEvent(ev)) ?? MutableString.CreateMutable(RubyEncoding.UTF8); } @@ -400,7 +400,7 @@ public static MutableString EmitScalar(ConversionStorage/*!*/ str MutableString str = value as MutableString; if (str == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected String)", self.Context.GetClassDisplayName(value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected String)", self.Context.GetClassDisplayName(value))); } var e = new LibyamlEvent(); e.Kind = EmitterEventKind.Scalar; @@ -476,7 +476,7 @@ private static int ToStyle(RubyContext/*!*/ context, object obj) { if (obj is double) { return (int)(double)obj; } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", context.GetClassDisplayName(obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", context.GetClassDisplayName(obj))); } private static LibyamlEvent/*!*/ MakeEvent(IList/*!*/ ev) { @@ -541,7 +541,7 @@ private static int ToStyle(RubyContext/*!*/ context, object obj) { break; default: - throw RubyExceptions.CreateArgumentError("unknown emitter event"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown emitter event")); } return e; } diff --git a/Src/Libraries/BCrypt/BCrypt.cs b/Src/Libraries/BCrypt/BCrypt.cs index c8f29f48d..5fa0a4116 100644 --- a/Src/Libraries/BCrypt/BCrypt.cs +++ b/Src/Libraries/BCrypt/BCrypt.cs @@ -627,12 +627,12 @@ public static class EngineOps { private static byte[]/*!*/ CString(RubyContext/*!*/ context, object value) { var str = value as MutableString; if (str == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected String)", - value == null ? "nil" : context.GetClassDisplayName(value))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected String)", + value == null ? "nil" : context.GetClassDisplayName(value)))); } byte[] bytes = str.ToByteArray(); if (Array.IndexOf(bytes, (byte)0) >= 0) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } return bytes; } @@ -662,21 +662,21 @@ public static object BcSalt(RubyContext/*!*/ context, RubyModule/*!*/ self, obje } else if (count is BigInteger) { var big = (BigInteger)count; if (big > ulong.MaxValue || big < long.MinValue) { - throw RubyExceptions.CreateRangeError("bignum out of range of unsigned long"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum out of range of unsigned long")); } n = big.Sign < 0 ? unchecked((ulong)(long)big) : (ulong)big; } else if (count is double) { n = unchecked((ulong)(long)(double)count); } else { - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", - context.GetClassDisplayName(count))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", + context.GetClassDisplayName(count)))); } byte[] i = null; if (input != null) { var str = input as MutableString; if (str == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected String)", - context.GetClassDisplayName(input))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected String)", + context.GetClassDisplayName(input)))); } i = str.ToByteArray(); } diff --git a/Src/Libraries/BigDecimal/BigDecimalOps.cs b/Src/Libraries/BigDecimal/BigDecimalOps.cs index 3e6582780..5fb565e3f 100644 --- a/Src/Libraries/BigDecimal/BigDecimalOps.cs +++ b/Src/Libraries/BigDecimal/BigDecimalOps.cs @@ -93,7 +93,7 @@ internal static BigDecimal.Config GetConfig(RubyContext/*!*/ context) { private static string/*!*/ ToCString(MutableString/*!*/ str) { string value = str.ConvertToString(); if (value.IndexOf('\0') >= 0) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } return value; } @@ -107,7 +107,7 @@ public static BigDecimal FromString(RubyContext/*!*/ context, RubyClass/*!*/ sel string str = ToCString(value); BigDecimal result = BigDecimal.Parse(GetConfig(context), str, true); if (result == null && exception) { - throw RubyExceptions.CreateArgumentError("invalid value for BigDecimal(): \"" + str + "\""); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid value for BigDecimal(): \"" + str + "\"")); } return result; } @@ -124,7 +124,7 @@ public static BigDecimal FromString(RubyContext/*!*/ context, RubyClass/*!*/ sel case long l: return BigDecimal.Create(config, l); case BigInteger b: return BigDecimal.Create(config, b); case double d: return BigDecimal.Create(config, d, digits); - default: throw RubyExceptions.CreateUnexpectedTypeError(context, value, "Integer"); + default: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(context, value, "Integer")); } } @@ -147,13 +147,13 @@ public static BigDecimal FromString(RubyContext/*!*/ context, RubyClass/*!*/ sel int colon = text.IndexOf(':'); for (int i = 0; i < (colon < 0 ? text.Length : colon); i++) { if (text[i] < '0' || text[i] > '9') { - throw RubyExceptions.CreateTypeError("load failed: invalid character in the marshaled string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("load failed: invalid character in the marshaled string")); } } string value = colon < 0 ? "" : text.Substring(colon + 1); BigDecimal result = BigDecimal.Parse(GetConfig(context), value, true); if (result == null) { - throw RubyExceptions.CreateArgumentError("invalid value for BigDecimal(): \"" + value + "\""); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid value for BigDecimal(): \"" + value + "\"")); } return result; } @@ -182,7 +182,7 @@ public static int Mode(ConversionStorage/*!*/ fixnumCast, RubyContext/*!*/ return (int)config.ExceptionMode; } if (!(value is bool)) { - throw RubyExceptions.CreateArgumentError("second argument must be true or false"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("second argument must be true or false")); } foreach (var flag in new[] { BigDecimal.ExceptionModes.Infinity, BigDecimal.ExceptionModes.NaN, BigDecimal.ExceptionModes.Underflow, BigDecimal.ExceptionModes.ZeroDivide }) { @@ -199,7 +199,7 @@ public static int Mode(ConversionStorage/*!*/ fixnumCast, RubyContext/*!*/ } return (int)config.RoundingMode; } - throw RubyExceptions.CreateTypeError("first argument for BigDecimal.mode invalid"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("first argument for BigDecimal.mode invalid")); } /// BigDecimal.limit([n]) answers the limit there was; nil leaves it as it is. @@ -210,7 +210,7 @@ public static int Limit(ConversionStorage/*!*/ fixnumCast, RubyContext/*!*/ if (!(n is Missing) && n != null) { int value = Protocols.CastToFixnum(fixnumCast, n); if (value < 0) { - throw RubyExceptions.CreateArgumentError("argument must be positive"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument must be positive")); } config.Limit = value; } @@ -287,7 +287,7 @@ public static int SignificantDigits(BigDecimal/*!*/ self) { [RubyMethod("to_s")] public static MutableString/*!*/ ToString(BigDecimal/*!*/ self, [DefaultProtocol]int group) { if (group <= 0) { - throw RubyExceptions.CreateArgumentError("argument must be positive"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument must be positive")); } return MutableString.CreateAscii(self.ToString(group, "", false)); } @@ -393,13 +393,13 @@ private static BigDecimal ToBigDecimal(BigDecimal.Config/*!*/ config, object oth string name = other == null || other is bool || other is RubySymbol ? context.Inspect(other).ToString() : context.GetClassOf(other).Name; - throw RubyExceptions.CreateTypeError(name + " can't be coerced into BigDecimal"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(name + " can't be coerced into BigDecimal")); } /// MRI's check_int_precision. private static int CheckPrecision(int n) { if (n < 0) { - throw RubyExceptions.CreateArgumentError("negative precision"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative precision")); } return n; } @@ -617,11 +617,11 @@ internal static BigDecimal.RoundingModes ToRoundingMode(ConversionStorage/* if (_roundingModeNames.TryGetValue(symbol.ToString(), out BigDecimal.RoundingModes result)) { return result; } - throw RubyExceptions.CreateArgumentError("invalid rounding mode (" + symbol.ToString() + ")"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid rounding mode (" + symbol.ToString() + ")")); } int value = Protocols.CastToFixnum(fixnumCast, mode); if (value < (int)BigDecimal.RoundingModes.Up || value > (int)BigDecimal.RoundingModes.HalfEven) { - throw RubyExceptions.CreateArgumentError("invalid rounding mode (" + value.ToString(CultureInfo.InvariantCulture) + ")"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid rounding mode (" + value.ToString(CultureInfo.InvariantCulture) + ")")); } return (BigDecimal.RoundingModes)value; } @@ -640,13 +640,13 @@ private static BigDecimal.RoundingModes ToHalfRoundingMode(RubyContext/*!*/ cont case "down": return BigDecimal.RoundingModes.HalfDown; case "even": return BigDecimal.RoundingModes.HalfEven; } - throw RubyExceptions.CreateArgumentError("invalid rounding mode (" + (name ?? context.Inspect(half).ToString()) + ")"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid rounding mode (" + (name ?? context.Inspect(half).ToString()) + ")")); } /// NUM2INT, which takes no nil. private static int ToDigits(ConversionStorage/*!*/ fixnumCast, object n) { if (n == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion from nil to integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion from nil to integer")); } return Protocols.CastToFixnum(fixnumCast, n); } diff --git a/Src/Libraries/Builtins/ArrayOps.cs b/Src/Libraries/Builtins/ArrayOps.cs index b3b80165c..5ec19f7c0 100644 --- a/Src/Libraries/Builtins/ArrayOps.cs +++ b/Src/Libraries/Builtins/ArrayOps.cs @@ -160,12 +160,12 @@ private static object Reinitialize(BlockParam/*!*/ block, RubyArray/*!*/ self, i // Array.new(nil) is a size that is not an Integer, not a missing array. [RubyConstructor] public static RubyArray/*!*/ CreateArray(RubyClass/*!*/ self, DynamicNull size) { - throw RubyExceptions.CreateImplicitConversionError("nil", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "Integer")); } [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static RubyArray/*!*/ Reinitialize(RubyArray/*!*/ self, DynamicNull size) { - throw RubyExceptions.CreateImplicitConversionError("nil", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "Integer")); } [RubyConstructor] @@ -191,11 +191,11 @@ private static BigInteger ToBigInteger(object/*!*/ size) { private static void CheckArraySize(int size) { if (size < 0) { - throw RubyExceptions.CreateArgumentError("negative array size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size")); } if (size > Int32.MaxValue / 8) { - throw RubyExceptions.CreateArgumentError("array size too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("array size too big")); } } @@ -206,10 +206,10 @@ private static void CheckArraySize(int size) { /// private static int CheckArraySize(BigInteger size) { if (size.Sign < 0) { - throw RubyExceptions.CreateArgumentError("negative array size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size")); } if (size > Int32.MaxValue / 8) { - throw RubyExceptions.CreateArgumentError("array size too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("array size too big")); } return (int)size; } @@ -283,7 +283,7 @@ public static IList TryConvert(ConversionStorage/*!*/ toAry, RubyClass/*! foreach (var option in options) { var key = option.Key as RubySymbol; if (key == null || key.ToString() != "buffer") { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(option.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(option.Key))); } // buffer: nil is no buffer if (option.Value == null) { @@ -291,8 +291,8 @@ public static IList TryConvert(ConversionStorage/*!*/ toAry, RubyClass/*! } buffer = option.Value as MutableString; if (buffer == null) { - throw RubyExceptions.CreateTypeError("buffer must be String, not {0}", - context.GetClassDisplayName(option.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("buffer must be String, not {0}", + context.GetClassDisplayName(option.Value))); } buffer.RequireNotFrozen(); } @@ -357,7 +357,7 @@ internal static RubyArray SortInPlace(ComparisonStorage/*!*/ comparisonStorage, } if (result == null) { - throw RubyExceptions.MakeComparisonError(context, x, y); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(context, x, y)); } return Protocols.ConvertCompareResult(comparisonStorage, result); @@ -668,7 +668,7 @@ private static long RotationCount(IntegerValue count) { } long value; if (!count.Bignum.AsInt64(out value)) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } return value; } diff --git a/Src/Libraries/Builtins/BasicObjectOps.cs b/Src/Libraries/Builtins/BasicObjectOps.cs index e6be0c334..164aa3494 100644 --- a/Src/Libraries/Builtins/BasicObjectOps.cs +++ b/Src/Libraries/Builtins/BasicObjectOps.cs @@ -85,14 +85,14 @@ public static object MethodMissing(RubyScope/*!*/ scope, object/*!*/ self, [NotN [RubyMethod("method_missing", RubyMethodAttributes.PrivateInstance)] public static object MethodMissing(object/*!*/ self) { - throw RubyExceptions.CreateArgumentError("no method name given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no method name given")); } // rb_method_missing checks the name before anything else [RubyMethod("method_missing", RubyMethodAttributes.PrivateInstance)] public static object MethodMissing(RubyContext/*!*/ context, object/*!*/ self, object name, params object[]/*!*/ args) { - throw RubyExceptions.CreateArgumentError("method name must be a Symbol but {0} is given", - context.GetClassOf(name).GetNonNullName(context)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("method name must be a Symbol but {0} is given", + context.GetClassOf(name).GetNonNullName(context))); } #endregion @@ -282,16 +282,16 @@ public static object Evaluate(ConversionStorage/*!*/ toStr, Conve if (block != null) { if (args.Length != 0) { - throw RubyExceptions.CreateArgumentError( - "wrong number of arguments (given {0}, expected 0)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + "wrong number of arguments (given {0}, expected 0)", args.Length)); } // The receiver is passed to the block: `obj.instance_eval { |o| o }` is obj. return RubyUtils.EvaluateInSingleton(self, block, new object[] { self }); } if (args.Length < 1 || args.Length > 3) { - throw RubyExceptions.CreateArgumentError( - "wrong number of arguments (given {0}, expected 1..3)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + "wrong number of arguments (given {0}, expected 1..3)", args.Length)); } MutableString code = Protocols.CastToString(toStr, args[0]); @@ -315,7 +315,7 @@ public static object Evaluate(ConversionStorage/*!*/ toStr, Conve public static object InstanceExec(BlockParam block, object self, params object[] args) { args = args ?? new object[] { null }; if (block == null) { - throw RubyExceptions.CreateLocalJumpError("no block given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLocalJumpError("no block given")); } return RubyUtils.EvaluateInSingleton(self, block, args); } diff --git a/Src/Libraries/Builtins/BindingOps.cs b/Src/Libraries/Builtins/BindingOps.cs index 7d7c0c306..3b1663029 100644 --- a/Src/Libraries/Builtins/BindingOps.cs +++ b/Src/Libraries/Builtins/BindingOps.cs @@ -58,9 +58,9 @@ public static object GetImplicitParameter(ConversionStorage/*!*/ var context = toStr.Context; string parameterName = CheckImplicitParameterName(toStr, name); if (!IsImplicitParameter(self, parameterName)) { - throw RubyExceptions.CreateNameError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError( String.Format("implicit parameter '{0}' is not defined for {1}", parameterName, context.Inspect(self)) - ); + )); } return self.FrameScope.GetImplicitParameterValue(ImplicitParameterSlot(parameterName)); } @@ -83,9 +83,9 @@ private static bool IsImplicitParameter(Binding/*!*/ self, string/*!*/ name) { private static string/*!*/ CheckImplicitParameterName(ConversionStorage/*!*/ toStr, object name) { string text = ToIdentifier(toStr, name); if (text != "it" && !(text.Length == 2 && text[0] == '_' && text[1] >= '1' && text[1] <= '9')) { - throw RubyExceptions.CreateNameError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError( String.Format("'{0}' is not an implicit parameter", text) - ); + )); } return text; } @@ -124,9 +124,9 @@ public static object GetLocal(ConversionStorage/*!*/ toStr, Bindi string identifier = ToIdentifier(toStr, name); object value; if (!self.LocalScope.TryResolveBindingLocal(identifier, out value)) { - throw RubyExceptions.CreateNameError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError( String.Format("local variable '{0}' is not defined for {1}", identifier, toStr.Context.Inspect(self)) - ); + )); } return value; } @@ -157,8 +157,8 @@ public static object SetLocal(ConversionStorage/*!*/ toStr, Bindi if (converted != null) { return converted.ToString(); } - throw RubyExceptions.CreateTypeError("{0} is not a symbol nor a string", - toStr.Context.Inspect(name).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0} is not a symbol nor a string", + toStr.Context.Inspect(name).ToString())); } [RubyMethod("to_s"), RubyMethod("inspect")] diff --git a/Src/Libraries/Builtins/ClassOps.cs b/Src/Libraries/Builtins/ClassOps.cs index 7aa0a0cab..b67796d89 100644 --- a/Src/Libraries/Builtins/ClassOps.cs +++ b/Src/Libraries/Builtins/ClassOps.cs @@ -35,7 +35,7 @@ public sealed class ClassOps { [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static void Reinitialize(BlockParam body, RubyClass/*!*/ self, [Optional]RubyClass superClass) { // Class cannot be subclassed, so this can only be called directly on an already initialized class: - throw RubyExceptions.CreateTypeError("already initialized class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("already initialized class")); } // No initialize_copy: #dup and #clone fill in a class's copy before they call it (RubyClass's IDuplicable.Duplicate), @@ -76,7 +76,7 @@ public static RubyClass GetSuperclass(RubyClass/*!*/ self) { // the singleton class of a plain object has the object's class. That is exactly what // the class hierarchy already records, so there is nothing special to do here. if (self.IsUninitializedAllocation) { - throw RubyExceptions.CreateTypeError("uninitialized class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized class")); } return self.SuperClass; } @@ -106,7 +106,7 @@ public static void Inherited(object/*!*/ self, object subclass) { [RubyMethod("attached_object")] public static object GetAttachedObject(RubyClass/*!*/ self) { if (!self.IsSingletonClass || self.IsDummySingletonClass) { - throw RubyExceptions.CreateTypeError("'{0}' is not a singleton class", self.GetNonNullName(self.Context)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("'{0}' is not a singleton class", self.GetNonNullName(self.Context))); } return self.SingletonClassOf; } @@ -126,7 +126,7 @@ public static object GetAttachedObject(RubyClass/*!*/ self) { RubyMemberInfo info; if (self.TypeTracker == null) { - throw RubyExceptions.CreateNotClrTypeError(self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNotClrTypeError(self)); } if (!self.TryGetClrConstructor(out info)) { diff --git a/Src/Libraries/Builtins/Comparable.cs b/Src/Libraries/Builtins/Comparable.cs index 431f0f491..e1fc678c2 100644 --- a/Src/Libraries/Builtins/Comparable.cs +++ b/Src/Libraries/Builtins/Comparable.cs @@ -55,7 +55,7 @@ public static bool Greater(ComparisonStorage/*!*/ comparisonStorage, object self return Protocols.ConvertCompareResult(comparisonStorage, compareResult); } - throw RubyExceptions.MakeComparisonError(comparisonStorage.Context, lhs, rhs); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(comparisonStorage.Context, lhs, rhs)); } #region clamp @@ -68,13 +68,13 @@ public static bool Greater(ComparisonStorage/*!*/ comparisonStorage, object self // others do not, and raises MRI's error for them. [RubyMethod("clamp")] public static object Clamp(object self, params object[]/*!*/ args) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..2)", args.Length)); } [RubyMethod("clamp")] public static object Clamp(ComparisonStorage/*!*/ comparisonStorage, object self, object min, object max) { if (min != null && max != null && CompareOrRaise(comparisonStorage, min, max) > 0) { - throw RubyExceptions.CreateArgumentError("min argument must be less than or equal to max argument"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("min argument must be less than or equal to max argument")); } if (min != null) { @@ -113,7 +113,7 @@ public static object Clamp(ComparisonStorage/*!*/ comparisonStorage, RespondToSt string name = range == null ? "nil" : range is bool ? ((bool)range ? "true" : "false") : comparisonStorage.Context.GetClassOf(range).GetNonNullName(comparisonStorage.Context); - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Range)", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Range)", name)); } var beginSite = beginStorage.GetCallSite("begin", 0); @@ -126,7 +126,7 @@ public static object Clamp(ComparisonStorage/*!*/ comparisonStorage, RespondToSt private static object ClampToRange(ComparisonStorage/*!*/ comparisonStorage, object self, object min, object max, bool excludeEnd) { if (excludeEnd && max != null) { - throw RubyExceptions.CreateArgumentError("cannot clamp with an exclusive range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cannot clamp with an exclusive range")); } return Clamp(comparisonStorage, self, min, max); } @@ -138,7 +138,7 @@ private static int CompareOrRaise(ComparisonStorage/*!*/ comparisonStorage, obje var compare = comparisonStorage.CompareSite; object compareResult = compare.Target(compare, lhs, rhs); if (compareResult == null) { - throw RubyExceptions.MakeComparisonError(comparisonStorage.Context, lhs, rhs); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(comparisonStorage.Context, lhs, rhs)); } return Protocols.ConvertCompareResult(comparisonStorage, compareResult); } diff --git a/Src/Libraries/Builtins/Dir.cs b/Src/Libraries/Builtins/Dir.cs index 4d29458a1..4f57ca78b 100644 --- a/Src/Libraries/Builtins/Dir.cs +++ b/Src/Libraries/Builtins/Dir.cs @@ -82,8 +82,8 @@ private static RubyEncoding GetEncodingOption(RubyContext/*!*/ context, IDiction } } if (unknown.Count > 0) { - throw RubyExceptions.CreateArgumentError( - (unknown.Count == 1 ? "unknown keyword: " : "unknown keywords: ") + String.Join(", ", unknown)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + (unknown.Count == 1 ? "unknown keyword: " : "unknown keywords: ") + String.Join(", ", unknown))); } return result; } @@ -151,7 +151,7 @@ public static object ChangeDirectory(BlockParam block, RubyClass/*!*/ self) { defaultDirectory = RubyUtils.GetHomeDirectory(pal); } if (defaultDirectory == null) { - throw RubyExceptions.CreateArgumentError("HOME/LOGDIR not set"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("HOME/LOGDIR not set")); } return ChangeDirectory(self.Context, defaultDirectory, self.Context.EncodePath(defaultDirectory), block); @@ -225,7 +225,7 @@ private static bool ChdirAloneBlock(RubyContext/*!*/ context, bool blockGiven) { chdirLock.Blocking = 1; chdirLock.Thread = System.Threading.Thread.CurrentThread; } else if (chdirLock.Thread != System.Threading.Thread.CurrentThread) { - throw RubyExceptions.CreateRuntimeError("conflicting chdir during another chdir block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("conflicting chdir during another chdir block")); } else if (blockGiven) { chdirLock.Blocking++; return true; @@ -460,8 +460,8 @@ private sealed class GlobOptions { if (entry.Value is bool) { options.Sort = (bool)entry.Value; } else { - throw RubyExceptions.CreateArgumentError("expected true or false as sort: {0}", - toPath.Context.Inspect(entry.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("expected true or false as sort: {0}", + toPath.Context.Inspect(entry.Value))); } break; @@ -474,7 +474,7 @@ private sealed class GlobOptions { break; default: - throw RubyExceptions.CreateArgumentError("unknown keyword: :{0}", key ?? toPath.Context.Inspect(entry.Key).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: :{0}", key ?? toPath.Context.Inspect(entry.Key).ToString())); } } @@ -502,7 +502,7 @@ private sealed class GlobOptions { } catch (ArgumentException e) when (single && e.Message == "path name contains null byte") { // A lone glob pattern reports an embedded NUL in its own words; one of several // patterns (an Array, or Dir.[] with more arguments) is an ordinary path name. - throw RubyExceptions.CreateArgumentError("nul-separated glob pattern is deprecated"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("nul-separated glob pattern is deprecated")); } } @@ -532,7 +532,7 @@ public static object Glob(ConversionStorage/*!*/ toPath, Conversi var options = ParseGlobOptions(toPath, toInt, ref args, true); if (args.Length < 1 || args.Length > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..2)", args.Length)); } if (args.Length == 2) { options.Flags = Protocols.CastToFixnum(toInt, args[1]); @@ -583,7 +583,7 @@ public static int MakeDirectory(ConversionStorage/*!*/ toPath, Co string strDir = self.Context.DecodePath(Protocols.CastToPath(toPath, dirname)); if (platform.FileExists(strDir) || platform.DirectoryExists(strDir)) { - throw RubyExceptions.CreateEEXIST(strDir); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEEXIST(strDir)); } string containingDir = platform.GetDirectoryName(strDir); @@ -593,7 +593,7 @@ public static int MakeDirectory(ConversionStorage/*!*/ toPath, Co } if (!String.IsNullOrEmpty(containingDir) && !platform.DirectoryExists(containingDir)) { // mkdir(2) reports the path it was given, not the missing parent - throw RubyExceptions.CreateENOENT("No such file or directory - {0}", strDir); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("No such file or directory - {0}", strDir)); } // The permission argument is not decoration: Dir.mkdir(path, 01755) has to @@ -843,7 +843,7 @@ private static void SyncCurrentDirectory(PlatformAdaptationLayer/*!*/ pal) { private void ThrowIfClosed() { if (Closed) { - throw RubyExceptions.CreateIOError("closed directory"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed directory")); } } diff --git a/Src/Libraries/Builtins/EncodingConverter.cs b/Src/Libraries/Builtins/EncodingConverter.cs index 0b9a70e2c..37b02756e 100644 --- a/Src/Libraries/Builtins/EncodingConverter.cs +++ b/Src/Libraries/Builtins/EncodingConverter.cs @@ -346,7 +346,7 @@ private static void RequireOneNewlineDecorator(ConversionStorage/ return encoding.Name; } if (obj == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into String")); } return Protocols.CastToString(toStr, obj).ToString(); } @@ -606,15 +606,15 @@ internal bool IsFinished { byte[] existing = destination.ToByteArray(); int offset = byteOffset ?? existing.Length; if (offset > existing.Length) { - throw RubyExceptions.CreateArgumentError("output_byteoffset too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("output_byteoffset too big")); } if (offset < 0) { - throw RubyExceptions.CreateArgumentError("negative output_byteoffset"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative output_byteoffset")); } // MRI's econv_primitive_convert checks its arguments before it converts anything, // so a finished converter still refuses a negative size if (byteLimit.HasValue && byteLimit.Value < 0) { - throw RubyExceptions.CreateArgumentError("negative output_bytesize"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative output_bytesize")); } if (_finished) { return "finished"; @@ -1418,7 +1418,7 @@ private string XmlEscape(int codepoint) { internal MutableString/*!*/ Convert(MutableString/*!*/ str) { if (_finished) { - throw RubyExceptions.CreateArgumentError("converter already finished"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("converter already finished")); } var source = MutableString.CreateBinary(str.ToByteArray()); @@ -1461,9 +1461,9 @@ private string XmlEscape(int codepoint) { return str; } if (obj == null || obj is bool || obj is int) { - throw RubyExceptions.CreateTypeError(String.Format(CultureInfo.InvariantCulture, + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format(CultureInfo.InvariantCulture, "no implicit conversion of {0} into String", - obj == null ? "nil" : toStr.Context.GetClassDisplayName(obj))); + obj == null ? "nil" : toStr.Context.GetClassDisplayName(obj)))); } return Protocols.CastToString(toStr, obj); } @@ -1509,7 +1509,7 @@ private static int ParseOptions(ConversionStorage>/* hash = site.Target(site, options); } if (hash == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion into Hash"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion into Hash")); } int flags = 0; @@ -1520,7 +1520,7 @@ private static int ParseOptions(ConversionStorage>/* if (SymbolName(entry.Value) == "replace") { flags |= InvalidReplaceFlag; } else if (entry.Value != null) { - throw RubyExceptions.CreateArgumentError("unknown value for invalid character option"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown value for invalid character option")); } break; @@ -1528,7 +1528,7 @@ private static int ParseOptions(ConversionStorage>/* if (SymbolName(entry.Value) == "replace") { flags |= UndefReplaceFlag; } else if (entry.Value != null) { - throw RubyExceptions.CreateArgumentError("unknown value for undefined character option"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown value for undefined character option")); } break; @@ -1545,8 +1545,8 @@ private static int ParseOptions(ConversionStorage>/* } else if (SymbolName(entry.Value) == "attr") { flags |= XmlAttrContentFlag | XmlAttrQuoteFlag | UndefHexCharRefFlag; } else { - throw RubyExceptions.CreateArgumentError("unexpected value for xml option: {0}", - (object)SymbolName(entry.Value) ?? toHash.Context.Inspect(entry.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected value for xml option: {0}", + (object)SymbolName(entry.Value) ?? toHash.Context.Inspect(entry.Value))); } break; @@ -1581,8 +1581,8 @@ private static int ParseOptions(ConversionStorage>/* case "cr": newlineOption = CrNewlineFlag; break; case "lf": newlineOption = LfNewlineFlag; break; default: - throw RubyExceptions.CreateArgumentError("unexpected value for newline option: {0}", - (object)SymbolName(entry.Value) ?? toHash.Context.Inspect(entry.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected value for newline option: {0}", + (object)SymbolName(entry.Value) ?? toHash.Context.Inspect(entry.Value))); } break; @@ -1633,7 +1633,7 @@ private static int ParseOptions(ConversionStorage>/* if (destination == Missing.Value) { var convpath = source as IList; if (convpath == null) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 1, expected 2..3)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 1, expected 2..3)")); } return CreateFromConvPath(toStr, convpath); } @@ -1694,18 +1694,18 @@ private static bool TryGetDecoratorFlag(string/*!*/ name, out int flag) { var pair = item as IList; if (pair != null) { if (pair.Count != 2) { - throw RubyExceptions.CreateArgumentError("not a 2-element array in convpath"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("not a 2-element array in convpath")); } string sourceName = EncodingName(toStr, pair[0]); string destinationName = EncodingName(toStr, pair[1]); RubyEncoding from = FindEncoding(toStr.Context, pair[0], sourceName); RubyEncoding to = FindEncoding(toStr.Context, pair[1], destinationName); if (from == null || to == null || from == to || from.HasNoTranscoder || to.HasNoTranscoder) { - throw RubyExceptions.CreateArgumentError("adding conversion failed: {0} to {1}", sourceName, destinationName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("adding conversion failed: {0} to {1}", sourceName, destinationName)); } RubyEncoding[] leg = RubyExceptions.ConversionPath(from, to); if (path.Count != 0 && path[path.Count - 1] != leg[0]) { - throw RubyExceptions.CreateArgumentError("adding conversion failed: {0} to {1}", sourceName, destinationName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("adding conversion failed: {0} to {1}", sourceName, destinationName)); } for (int i = (path.Count == 0) ? 0 : 1; i < leg.Length; i++) { path.Add(leg[i]); @@ -1719,7 +1719,7 @@ private static bool TryGetDecoratorFlag(string/*!*/ name, out int flag) { string name = Protocols.CastToString(toStr, item).ToString(); int decorator; if (!TryGetDecoratorFlag(name, out decorator)) { - throw RubyExceptions.CreateArgumentError("decoration failed: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("decoration failed: {0}", name)); } flags |= decorator; reported.Add(MutableString.CreateBinary(Encoding.ASCII.GetBytes(name)).Freeze()); @@ -1839,7 +1839,7 @@ public static object PrimitiveConvert( // MRI's econv_primitive_convert reads the source and writes the destination in // place, so the two cannot be one string if (ReferenceEquals(source, destination)) { - throw RubyExceptions.CreateArgumentError("cannot convert into the source string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cannot convert into the source string")); } int? offset = ToOptionalInt(toInt, byteOffset); diff --git a/Src/Libraries/Builtins/Enumerable.cs b/Src/Libraries/Builtins/Enumerable.cs index f27a8141a..4334c6907 100644 --- a/Src/Libraries/Builtins/Enumerable.cs +++ b/Src/Libraries/Builtins/Enumerable.cs @@ -975,7 +975,7 @@ public static object GetExtremes(CallSiteStorage/*!*/ each, Comparison } if (blockResult == null) { - throw RubyExceptions.MakeComparisonError(comparisonStorage.Context, left, right); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(comparisonStorage.Context, left, right)); } return Protocols.ConvertCompareResult(comparisonStorage, blockResult); @@ -1265,13 +1265,13 @@ public static object First(CallSiteStorage/*!*/ each, object self) { [RubyMethod("take")] public static RubyArray/*!*/ Take(CallSiteStorage/*!*/ each, object self, [DefaultProtocol]int count) { if (count < 0) { - throw RubyExceptions.CreateArgumentError("attempt to take negative size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("attempt to take negative size")); } // MRI allocates the result up front (rb_ary_new_capa) and so refuses a count no array // can hold (here, past the CLR's longest array); a large count that can be held is not worth reserving before #each says // how many elements there are. if (count > Array.MaxLength) { - throw RubyExceptions.CreateArgumentError("array size too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("array size too big")); } var result = new RubyArray(Math.Min(count, 1024)); @@ -1322,7 +1322,7 @@ public static object TakeWhile(CallSiteStorage/*!*/ each, [NotNull]Blo [RubyMethod("drop")] public static RubyArray/*!*/ Drop(CallSiteStorage/*!*/ each, object self, [DefaultProtocol]int count) { if (count < 0) { - throw RubyExceptions.CreateArgumentError("attempt to drop negative size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("attempt to drop negative size")); } var result = new RubyArray(); @@ -1472,7 +1472,7 @@ private static object EachSlice(CallSiteStorage/*!*/ each, BlockParam/ bool includeIncomplete, Func/*!*/ newSliceFactory) { if (sliceSize <= 0) { - throw RubyExceptions.CreateArgumentError("invalid slice size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid slice size")); } RubyArray slice = null; diff --git a/Src/Libraries/Builtins/Enumerator.cs b/Src/Libraries/Builtins/Enumerator.cs index 015c1b538..e8cbc5e00 100644 --- a/Src/Libraries/Builtins/Enumerator.cs +++ b/Src/Libraries/Builtins/Enumerator.cs @@ -1531,7 +1531,7 @@ public static object Feed(RubyContext/*!*/ context, Enumerator/*!*/ self, object throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, self)); } if (self._hasFeed) { - throw RubyExceptions.CreateTypeError("feed value already set"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("feed value already set")); } self._feedValue = value; self._hasFeed = true; diff --git a/Src/Libraries/Builtins/ExceptionOps.cs b/Src/Libraries/Builtins/ExceptionOps.cs index 1ea818886..80fdc5b46 100644 --- a/Src/Libraries/Builtins/ExceptionOps.cs +++ b/Src/Libraries/Builtins/ExceptionOps.cs @@ -142,7 +142,7 @@ public static RubyArray GetRaiseBacktrace(Exception/*!*/ self) { [RubyMethod("set_backtrace", RubyMethodAttributes.PublicInstance)] public static RubyArray SetBacktrace(Exception/*!*/ self, RubyArray backtrace) { if (backtrace != null && !CollectionUtils.TrueForAll(backtrace, (item) => item is MutableString)) { - throw RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location")); } return RubyExceptionData.GetInstance(self).Backtrace = backtrace; @@ -151,7 +151,7 @@ public static RubyArray SetBacktrace(Exception/*!*/ self, RubyArray backtrace) { [RubyMethod("set_backtrace", RubyMethodAttributes.PublicInstance)] public static RubyArray SetBacktrace(Exception/*!*/ self, object backtrace) { // anything but nil, a String or an Array of Strings - throw RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location")); } /// @@ -172,7 +172,7 @@ public static object GetException(UnaryOpStorage/*!*/ cloneStorage, RubyContext/ var site = cloneStorage.GetCallSite("clone"); var copy = site.Target(site, self) as Exception; if (copy == null) { - throw RubyExceptions.CreateTypeError("exception object expected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("exception object expected")); } // unlike #initialize this leaves the backtrace alone, as MRI's clone does diff --git a/Src/Libraries/Builtins/Exceptions.cs b/Src/Libraries/Builtins/Exceptions.cs index 4a37d18ac..b3388aad7 100644 --- a/Src/Libraries/Builtins/Exceptions.cs +++ b/Src/Libraries/Builtins/Exceptions.cs @@ -117,7 +117,7 @@ private static bool TryGetStatus(object value, out int status) { if (!TryGetStatus(status, out value)) { // MRI only has room for a message after a status, so anything else in front of // one leaves it with an argument it cannot place. - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 0..1)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 0..1)")); } return Make(self, value, message); } @@ -138,8 +138,8 @@ private static bool TryGetStatus(object value, out int status) { } } else if (args.Length >= 2) { if (args.Length > 2 || !TryGetStatus(args[0], out status)) { - throw RubyExceptions.CreateArgumentError( - "wrong number of arguments (given {0}, expected 0..1)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + "wrong number of arguments (given {0}, expected 0..1)", args.Length)); } message = args[1]; } @@ -283,7 +283,7 @@ public static class NameErrorOps { object receiver; bool hasReceiver = TryTakeReceiverKeyword(ref args, out receiver); if (args.Length > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..2)", args.Length)); } object message = args.Length > 0 ? args[0] : null; @@ -308,7 +308,7 @@ public static object GetName(Exception/*!*/ self) { public static object GetReceiver(Exception/*!*/ self) { var data = RubyExceptionData.GetInstance(self); if (!data.HasReceiver) { - throw RubyExceptions.CreateArgumentError("no receiver is available"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no receiver is available")); } return data.Receiver; } @@ -365,7 +365,7 @@ public static class NoMethodErrorOps { object receiver; bool hasReceiver = NameErrorOps.TryTakeReceiverKeyword(ref allArgs, out receiver); if (allArgs.Length > 4) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..4)", allArgs.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..4)", allArgs.Length)); } object message = allArgs.Length > 0 ? allArgs[0] : null; @@ -436,11 +436,11 @@ public static class UncaughtThrowErrorOps { [RubyConstructor] public static UncaughtThrowError/*!*/ Create(RubyClass/*!*/ self, object tag, object value, params object[]/*!*/ rest) { if (rest.Length > 1) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..1)", rest.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..1)", rest.Length)); } object message = rest.Length == 1 ? rest[0] : null; if (message != null && !(message is MutableString)) { - throw RubyExceptions.CreateImplicitConversionError(self.Context.GetClassDisplayName(message), "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(self.Context.GetClassDisplayName(message), "String")); } var result = new UncaughtThrowError(message != null ? ((MutableString)message).ConvertToString() : null, tag, value); result.FormatsTag = true; @@ -481,7 +481,7 @@ public static class FrozenErrorOps { object receiver; bool hasReceiver = NameErrorOps.TryTakeReceiverKeyword(ref args, out receiver); if (args.Length > 1) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..1)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..1)", args.Length)); } object message = args.Length > 0 ? args[0] : null; @@ -496,7 +496,7 @@ public static class FrozenErrorOps { [RubyMethod("receiver")] public static object Receiver(FrozenError/*!*/ self) { if (!self.HasReceiver) { - throw RubyExceptions.CreateArgumentError("no receiver is available"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no receiver is available")); } return self.Receiver; } diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index d1f235a99..5885a1bfa 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -105,7 +105,7 @@ public static void RequireUninitialized(RubyIO/*!*/ self) { if (optionsOrPermissions != Missing.Value && optionsOrPermissions != null) { int? p = toIntSite.Target(toIntSite, optionsOrPermissions); if (!p.HasValue) { - throw RubyExceptions.CreateImplicitConversionError(context.GetClassName(optionsOrPermissions), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassName(optionsOrPermissions), "Integer")); } permissions = p.Value; } @@ -117,11 +117,11 @@ public static void RequireUninitialized(RubyIO/*!*/ self) { object permOption; if (options.TryGetValue(context.CreateAsciiSymbol("perm"), out permOption) && permOption != null) { if (optionsOrPermissions != Missing.Value && optionsOrPermissions != null) { - throw RubyExceptions.CreateArgumentError("perm specified twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("perm specified twice")); } int? p = toIntSite.Target(toIntSite, permOption); if (!p.HasValue) { - throw RubyExceptions.CreateImplicitConversionError(context.GetClassName(permOption), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassName(permOption), "Integer")); } permissions = p.Value; } @@ -390,7 +390,7 @@ private static int ToUidGid(RubyContext/*!*/ context, object value, bool owner) if (value is int) { return (int)value; } - throw RubyExceptions.CreateUnexpectedTypeError(context, value, "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(context, value, "Integer")); } [RubyMethod("chown")] @@ -441,7 +441,7 @@ private static int ChangeOwner(ConversionStorage/*!*/ toPath, Rub throw Posix.Error(errno, strPath, self.Context); } } else if (!Exists(context, Protocols.CastToPath(toPath, path))) { - throw RubyExceptions.CreateENOENT("No such file or directory - {0}", strPath); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("No such file or directory - {0}", strPath)); } } return paths.Length; @@ -502,7 +502,7 @@ public static int Delete(ConversionStorage/*!*/ toPath, RubyClass } if (!self.Context.Platform.FileExists(strPath)) { - throw RubyExceptions.CreateENOENT("{0}", strPath); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("{0}", strPath)); } Delete(self.Context, strPath); @@ -513,7 +513,7 @@ internal static void Delete(RubyContext/*!*/ context, string/*!*/ path) { try { context.Platform.DeleteFile(path, true); } catch (DirectoryNotFoundException) { - throw RubyExceptions.CreateENOENT("No such file or directory - {0}", path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("No such file or directory - {0}", path)); } catch (IOException e) { throw Errno.CreateEACCES(e.Message, e); } @@ -553,7 +553,7 @@ public static int Truncate(ConversionStorage/*!*/ toPath, Convers string strPath = self.Context.DecodePath(Protocols.CastToPath(toPath, path)); long size = Protocols.CastToInteger(integerConversion, length).ToInt64(); if (size < 0) { - throw RubyExceptions.CreateEINVAL("Invalid argument - {0}", strPath); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("Invalid argument - {0}", strPath)); } using (RubyFile f = new RubyFile(self.Context, strPath, IOMode.ReadWrite)) { f.Length = size; @@ -569,7 +569,7 @@ public static int Rename(ConversionStorage/*!*/ toPath, RubyClass string strNewPath = context.DecodePath(Protocols.CastToPath(toPath, newPath)); if (strOldPath.Length == 0 || strNewPath.Length == 0) { - throw RubyExceptions.CreateENOENT(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT()); } // MRI names both ends of a failed rename: "No such file or directory - (old, new)". @@ -581,13 +581,13 @@ public static int Rename(ConversionStorage/*!*/ toPath, RubyClass if (Posix.IsAvailable) { int errno; if (Posix.Rename(strOldPath, strNewPath, out errno) != 0) { - throw RubyExceptions.CreateErrno(context, errno, paths); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, errno, paths)); } return 0; } if (!context.Platform.FileExists(strOldPath) && !context.Platform.DirectoryExists(strOldPath)) { - throw RubyExceptions.CreateENOENT("No such file or directory - {0}", paths); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("No such file or directory - {0}", paths)); } if (RubyUtils.ExpandPath(context.Platform, strOldPath) == RubyUtils.ExpandPath(context.Platform, strNewPath)) { @@ -597,10 +597,10 @@ public static int Rename(ConversionStorage/*!*/ toPath, RubyClass // win32.c's rename: a directory cannot replace a file, nor a file a directory. bool oldIsDirectory = context.Platform.DirectoryExists(strOldPath); if (oldIsDirectory && context.Platform.FileExists(strNewPath)) { - throw RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ENOTDIR"), paths); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ENOTDIR"), paths)); } if (!oldIsDirectory && context.Platform.DirectoryExists(strNewPath)) { - throw RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("EISDIR"), paths); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("EISDIR"), paths)); } if (context.Platform.FileExists(strNewPath)) { @@ -610,9 +610,9 @@ public static int Rename(ConversionStorage/*!*/ toPath, RubyClass try { context.Platform.MoveFileSystemEntry(strOldPath, strNewPath); } catch (DirectoryNotFoundException e) { - throw RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", paths); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", paths)); } catch (FileNotFoundException e) { - throw RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", paths); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", paths)); } catch (IOException e) { throw Errno.CreateEACCES(e.Message, e); } @@ -718,7 +718,7 @@ public static int Rename(ConversionStorage/*!*/ toPath, RubyClass [DefaultProtocol]int level) { if (level < 0) { - throw RubyExceptions.CreateArgumentError("negative level: {0}", level); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative level: {0}", level)); } MutableString result = Protocols.CastToPath(toPath, path); @@ -1039,15 +1039,15 @@ private static string StripPathCharacters(string path) { } if (home == null) { // MRI's rb_default_home_dir names the real uid, whatever it looked up - throw RubyExceptions.CreateArgumentError("couldn't find home for uid '{0}'", Posix.GetUid()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("couldn't find home for uid '{0}'", Posix.GetUid())); } if (home.Length == 0 || home[0] != DirectorySeparatorChar) { - throw RubyExceptions.CreateArgumentError("non-absolute home"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("non-absolute home")); } } else { home = Posix.GetHomeDirectory(userName); if (home == null) { - throw RubyExceptions.CreateArgumentError("user {0} doesn't exist", userName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("user {0} doesn't exist", userName)); } } @@ -1067,7 +1067,7 @@ private static string StripPathCharacters(string path) { string rest = (slash < 0) ? null : path.Substring(slash + 1); if (userName.Length != 0) { - throw RubyExceptions.CreateArgumentError("can't find user {0}", userName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't find user {0}", userName)); } string home = RubyEnvironment.GetVariable(context.Platform, "HOME"); @@ -1082,7 +1082,7 @@ private static string StripPathCharacters(string path) { } } if (home == null) { - throw RubyExceptions.CreateArgumentError("couldn't find HOME environment -- expanding '~'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("couldn't find HOME environment -- expanding '~'")); } home = home.Replace(AltDirectorySeparatorChar, DirectorySeparatorChar); @@ -1098,7 +1098,7 @@ private static string StripPathCharacters(string path) { private static void RequireUsablePathEncoding(RubyContext/*!*/ context, MutableString/*!*/ path) { var external = context.DefaultExternalEncoding; if (external != null && !external.IsAsciiIdentity) { - throw RubyExceptions.CreateEncodingCompatibilityError(path.Encoding, external); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEncodingCompatibilityError(path.Encoding, external)); } } @@ -1235,7 +1235,7 @@ private static void JoinList(ConversionStorage/*!*/ toPath, IList Protocols.CheckPath(s); } catch (ArgumentException e) when (e.Message == "path name contains null byte") { // rb_file_join reports a NUL as a plain string problem (StringValueCStr). - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } } } @@ -1248,7 +1248,7 @@ private static void JoinList(ConversionStorage/*!*/ toPath, IList if (nested.Count == 0) { str = MutableString.FrozenEmpty; } else if (ReferenceEquals(nested, list) || (visitedLists != null && visitedLists.ContainsKey(nested))) { - throw RubyExceptions.CreateArgumentError("recursive array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("recursive array")); } else { if (visitedLists == null) { visitedLists = new Dictionary(ReferenceEqualityComparer.Instance); @@ -1263,13 +1263,13 @@ private static void JoinList(ConversionStorage/*!*/ toPath, IList str = nestedResult ?? MutableString.FrozenEmpty; } } else if (part == null) { - throw RubyExceptions.CreateImplicitConversionError("NilClass", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("NilClass", "String")); } else { try { str = Protocols.CastToPath(toPath, part); } catch (ArgumentException e) when (e.Message == "path name contains null byte") { // rb_file_join reports a NUL as a plain string problem. - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } } @@ -1354,7 +1354,7 @@ public static object FileLock(RubyIO/*!*/ self, [DefaultProtocol]int operation) int fd = GetNativeFileDescriptor(self); if (fd < 0) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } int errno; @@ -1509,7 +1509,7 @@ private static void WindowsSymLink(string/*!*/ strOld, string/*!*/ strNew) { private static object WindowsFileLock(RubyIO/*!*/ self, int operation) { var fs = self.GetStream().BaseStream as FileStream; if (fs == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } // Windows locks are mandatory: what is buffered has to reach the file first. fs.Flush(); @@ -1520,7 +1520,7 @@ private static object WindowsFileLock(RubyIO/*!*/ self, int operation) { int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); // Unlocking a file that is not locked is not an error for flock(2). if (error != ERROR_NOT_LOCKED) { - throw RubyExceptions.CreateEINVAL("{0}", FilePathOf(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("{0}", FilePathOf(self))); } } return 0; @@ -1530,7 +1530,7 @@ private static object WindowsFileLock(RubyIO/*!*/ self, int operation) { if ((operation & Posix.LOCK_EX) != 0) { flags |= LOCKFILE_EXCLUSIVE_LOCK; } else if ((operation & Posix.LOCK_SH) == 0) { - throw RubyExceptions.CreateEINVAL("{0}", FilePathOf(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("{0}", FilePathOf(self))); } while (true) { @@ -1540,7 +1540,7 @@ private static object WindowsFileLock(RubyIO/*!*/ self, int operation) { } int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (error != ERROR_LOCK_VIOLATION && error != ERROR_IO_PENDING) { - throw RubyExceptions.CreateEINVAL("{0}", FilePathOf(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("{0}", FilePathOf(self))); } if ((operation & Posix.LOCK_NB) != 0) { return false; @@ -1744,7 +1744,7 @@ public static int MakeFifo(ConversionStorage/*!*/ toPath, RubyCla string full = self.Context.DecodePath(expanded).TrimEnd('/', '\\'); string mustExist = strict ? full : System.IO.Path.GetDirectoryName(full); if (!String.IsNullOrEmpty(mustExist) && !System.IO.File.Exists(mustExist) && !System.IO.Directory.Exists(mustExist)) { - throw RubyExceptions.CreateENOENT("{0}", strPath); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("{0}", strPath)); } return expanded; } @@ -1870,7 +1870,7 @@ private static int UpdateTimes(ConversionStorage/*!*/ toPath, Rub FileInfo info = new FileInfo(strPath); if (!info.Exists) { - throw RubyExceptions.CreateENOENT("No such file or directory - {0}", strPath); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("No such file or directory - {0}", strPath)); } info.LastAccessTimeUtc = atime.ToUniversalTime(); info.LastWriteTimeUtc = mtime.ToUniversalTime(); @@ -1896,7 +1896,7 @@ private static RubyTime MakeTime(RubyContext/*!*/ context, object obj) { return new RubyTime(RubyTime.ToLocalTime(RubyTime.Epoch.AddSeconds((double)obj))); } else { string name = context.GetClassOf(obj).Name; - throw RubyExceptions.CreateTypeConversionError(name, "time"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(name, "time")); } } @@ -2152,7 +2152,7 @@ public class RubyStatOps { case Microsoft.Scripting.Utils.ConsoleStreamType.Input: fd = 0; break; case Microsoft.Scripting.Utils.ConsoleStreamType.Output: fd = 1; break; case Microsoft.Scripting.Utils.ConsoleStreamType.ErrorOutput: fd = 2; break; - default: throw RubyExceptions.CreateEBADF(); + default: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -2299,7 +2299,7 @@ private static FileSystemInfo L(FileSystemInfo self) { // MRI's get_stat: a File::Stat that File::Stat.allocate made and nothing filled in. private static StatInfo/*!*/ Initialized(StatInfo/*!*/ self) { if (!self.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized File::Stat"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized File::Stat")); } return self; } @@ -2331,7 +2331,7 @@ private static FileSystemInfo L(FileSystemInfo self) { } var source = other as StatInfo; if (source == null || context.GetClassOf(other) != context.GetClassOf(self)) { - throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("initialize_copy should take same class object")); } self.CopyFrom(source); return self; diff --git a/Src/Libraries/Builtins/FileTest.cs b/Src/Libraries/Builtins/FileTest.cs index 865e334cf..4f605e11c 100644 --- a/Src/Libraries/Builtins/FileTest.cs +++ b/Src/Libraries/Builtins/FileTest.cs @@ -136,8 +136,8 @@ internal static RubyIO ToIO(RespondToStorage/*!*/ respondToStorage, } io = converted as RubyIO; if (io == null) { - throw RubyExceptions.CreateTypeError("can't convert {0} to IO ({0}#to_io gives {1})", - context.GetClassDisplayName(obj), context.GetClassDisplayName(converted)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to IO ({0}#to_io gives {1})", + context.GetClassDisplayName(obj), context.GetClassDisplayName(converted))); } return io; } diff --git a/Src/Libraries/Builtins/HashOps.cs b/Src/Libraries/Builtins/HashOps.cs index 7ab405540..6bb7a6bcb 100644 --- a/Src/Libraries/Builtins/HashOps.cs +++ b/Src/Libraries/Builtins/HashOps.cs @@ -70,13 +70,13 @@ private static void CheckOptions(RubyContext/*!*/ context, Hash/*!*/ options) { unknown.Add(context.Inspect(entry.Key).ToString()); } else if (!(entry.Value is int || entry.Value is System.Numerics.BigInteger || entry.Value is double)) { // MRI converts the hint with to_int; the hint itself is not used here. - throw RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(entry.Value), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(entry.Value), "Integer")); } } if (unknown.Count > 0) { - throw RubyExceptions.CreateArgumentError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( (unknown.Count == 1 ? "unknown keyword: " : "unknown keywords: ") + String.Join(", ", unknown) - ); + )); } } @@ -88,7 +88,7 @@ private static Proc CheckDefaultProc(Proc proc) { if (proc != null && proc.Kind == ProcKind.Lambda) { int arity = proc.Dispatcher.Arity; if (arity != 2 && (arity >= 0 || arity < -3)) { - throw RubyExceptions.CreateTypeError("default_proc takes two arguments (2 for {0})", arity); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("default_proc takes two arguments (2 for {0})", arity)); } } return proc; @@ -120,7 +120,7 @@ private static Proc CheckDefaultProc(Proc proc) { return CreateSubclass(toAry, self, array); } - throw RubyExceptions.CreateArgumentError("odd number of arguments for Hash"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("odd number of arguments for Hash")); } [RubyMethod("[]", RubyMethodAttributes.PublicSingleton)] @@ -131,11 +131,11 @@ private static Proc CheckDefaultProc(Proc proc) { object item = list[i]; IList pair = toArySite.Target(toArySite, item); if (pair == null) { - throw RubyExceptions.CreateArgumentError("wrong element type {0} at {1} (expected array)", - item == null ? "nil" : self.Context.GetClassDisplayName(item), i); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong element type {0} at {1} (expected array)", + item == null ? "nil" : self.Context.GetClassDisplayName(item), i)); } if (pair.Count < 1 || pair.Count > 2) { - throw RubyExceptions.CreateArgumentError("invalid number of elements ({0} for 1..2)", pair.Count); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid number of elements ({0} for 1..2)", pair.Count)); } RubyUtils.SetHashElement(self.Context, result, pair[0], (pair.Count == 2) ? pair[1] : null); } @@ -152,7 +152,7 @@ private static Proc CheckDefaultProc(Proc proc) { public static Hash/*!*/ CreateSubclass(RubyClass/*!*/ self, params object[]/*!*/ items) { Debug.Assert(items.Length > 0); if (items.Length % 2 != 0) { - throw RubyExceptions.CreateArgumentError("odd number of arguments for Hash"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("odd number of arguments for Hash")); } return RubyUtils.SetHashElements(self.Context, Hash.CreateInstance(self), items); @@ -181,7 +181,7 @@ private static Proc CheckDefaultProc(Proc proc) { return self; } if (block != null) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 1, expected 0)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 1, expected 0)")); } self.DefaultProc = null; self.DefaultValue = defaultValue; @@ -192,7 +192,7 @@ private static Proc CheckDefaultProc(Proc proc) { public static Hash/*!*/ Initialize(RubyContext/*!*/ context, BlockParam block, Hash/*!*/ self, object defaultValue, [Keywords]object options) { // a second argument is only allowed as keywords if (!IsOptions(options)) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 0..1)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 0..1)")); } CheckOptions(context, (Hash)options); return Initialize(context, block, self, defaultValue); @@ -235,7 +235,7 @@ public static bool IsRuby2KeywordsHash(RubyClass/*!*/ self, [NotNull]Hash/*!*/ h [RubyMethod("ruby2_keywords_hash?", RubyMethodAttributes.PublicSingleton)] public static bool IsRuby2KeywordsHash(RubyContext/*!*/ context, RubyClass/*!*/ self, object hash) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Hash)", context.GetClassDisplayName(hash)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Hash)", context.GetClassDisplayName(hash))); } /// @@ -355,7 +355,7 @@ private static void RequireDig(RespondToStorage/*!*/ respondTo, object value) { // respond_to? may be overridden - a Hash or an Array included, when its class, a module in it or the // object itself redefines #dig: rb_obj_dig takes its short cut only while rb_method_basic_definition_p. if (!HasBuiltinDig(respondTo.Context, value) && !Protocols.RespondTo(respondTo, value, "dig")) { - throw RubyExceptions.CreateTypeError("{0} does not have #dig method", respondTo.Context.GetClassName(value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0} does not have #dig method", respondTo.Context.GetClassName(value))); } } @@ -427,7 +427,7 @@ public static bool ComparesByIdentity(Hash/*!*/ self) { if (hash == null) { // nil is the one argument the conversion site lets through; it would empty the // hash before failing - throw RubyExceptions.CreateImplicitConversionError("nil", "Hash"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "Hash")); } return Replace(toHash.Context, self, hash); } @@ -439,7 +439,7 @@ public static bool ComparesByIdentity(Hash/*!*/ self) { } self.RequireNotFrozen(); if (self.IsIterating) { - throw RubyExceptions.CreateRuntimeError("can't replace hash during iteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("can't replace hash during iteration")); } Hash otherHash = other as Hash; diff --git a/Src/Libraries/Builtins/Integer.cs b/Src/Libraries/Builtins/Integer.cs index 7e066964b..29463ee2c 100644 --- a/Src/Libraries/Builtins/Integer.cs +++ b/Src/Libraries/Builtins/Integer.cs @@ -175,7 +175,7 @@ private static BigInteger ToBigInteger(object/*!*/ self) { if (self is BigInteger) { return (BigInteger)self; } - throw RubyExceptions.CreateTypeError("can't convert {0} into Integer", self == null ? "nil" : self.GetType().Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into Integer", self == null ? "nil" : self.GetType().Name)); } #endregion @@ -1115,7 +1115,7 @@ private static object UpToImpl(BinaryOpStorage/*!*/ greaterThanStorage, BinaryOp // If the comparison failed (i.e. returned null) then we throw an error. if (compare == null) { - throw RubyExceptions.MakeComparisonError(greaterThanStorage.Context, i, other); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(greaterThanStorage.Context, i, other)); } // If the comparison worked but returned false then we carry on @@ -1208,7 +1208,7 @@ private static object DownToImpl(BinaryOpStorage/*!*/ lessThanStorage, BinaryOpS // If the comparison failed (i.e. returned null) then we throw an error. if (compare == null) { - throw RubyExceptions.MakeComparisonError(lessThanStorage.Context, i, other); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(lessThanStorage.Context, i, other)); } // If the comparison worked but returned false then we @@ -1274,7 +1274,7 @@ private static int SignedGcd(int a, int b) { [RubyMethod("gcd")] public static object/*!*/ Gcd(object/*!*/ self, object other) { - throw RubyExceptions.CreateTypeError("not an integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("not an integer")); } [RubyMethod("lcm")] @@ -1289,7 +1289,7 @@ private static int SignedGcd(int a, int b) { [RubyMethod("lcm")] public static object/*!*/ Lcm(object/*!*/ self, object other) { - throw RubyExceptions.CreateTypeError("not an integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("not an integer")); } [RubyMethod("gcdlcm")] @@ -1306,7 +1306,7 @@ private static int SignedGcd(int a, int b) { [RubyMethod("gcdlcm")] public static RubyArray/*!*/ GcdLcm(object/*!*/ self, object other) { - throw RubyExceptions.CreateTypeError("not an integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("not an integer")); } #endregion @@ -1494,7 +1494,7 @@ public static object Pow(BinaryOpStorage/*!*/ powStorage, object/*!*/ self, obje [RubyMethod("pow")] public static object Pow(int self, int exponent, int modulus) { if (exponent < 0) { - throw RubyExceptions.CreateRangeError("Integer#pow() 1st argument cannot be negative when 2nd argument specified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("Integer#pow() 1st argument cannot be negative when 2nd argument specified")); } // MRI's shortcut: 0 ** x is 0 for any modulus, 0 included, unless x is 0 if (self == 0 && exponent != 0) { @@ -1532,13 +1532,13 @@ public static object Pow(int self, int exponent, int modulus) { public static object Pow(object/*!*/ self, object exponent, object modulus) { BigInteger b, m; if (!TryGetInteger(exponent, out b)) { - throw RubyExceptions.CreateTypeError("Integer#pow() 2nd argument not allowed unless a 1st argument is integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Integer#pow() 2nd argument not allowed unless a 1st argument is integer")); } if (b.Sign < 0) { - throw RubyExceptions.CreateRangeError("Integer#pow() 1st argument cannot be negative when 2nd argument specified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("Integer#pow() 1st argument cannot be negative when 2nd argument specified")); } if (!TryGetInteger(modulus, out m)) { - throw RubyExceptions.CreateTypeError("Integer#pow() 2nd argument not allowed unless all arguments are integers"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Integer#pow() 2nd argument not allowed unless all arguments are integers")); } BigInteger a; TryGetInteger(self, out a); @@ -1584,10 +1584,10 @@ public static object Pow(object/*!*/ self, object exponent, object modulus) { BigInteger radixValue = (radix == Missing.Value) ? new BigInteger(10) : CastToBigInteger(integerCast, radix); if (radixValue.Sign < 0) { - throw RubyExceptions.CreateArgumentError("negative radix"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative radix")); } if (radixValue < 2) { - throw RubyExceptions.CreateArgumentError(String.Format("invalid radix {0}", radixValue)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("invalid radix {0}", radixValue))); } var result = new RubyArray(); diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 76cf7f3e4..ae3f4f3ca 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -56,7 +56,7 @@ public class RubyIOOps { } } if (stream == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } return stream; } @@ -96,7 +96,8 @@ public static class WaitWritable { io, isRead ? "EAGAINWaitReadable" : "EAGAINWaitWritable", operation ); if (error != null) { - return error; + // made by the classes' #new, IronRuby's own, and thrown by the caller at once (perf/unkept3) + return RubyExceptionData.Unkept(error); } } } @@ -107,7 +108,7 @@ public static class WaitWritable { if (context.TryGetModule(isRead ? typeof(WaitReadable) : typeof(WaitWritable), out waitModule)) { ModuleOps.ExtendObject(waitModule, fallback); } - return fallback; + return RubyExceptionData.Unkept(fallback); } #endregion @@ -147,7 +148,7 @@ public static class WaitWritable { var toHashSite = toHash.GetSite(TryConvertToHashAction.Make(context)); options = (optionsArgument != null) ? toHashSite.Target(toHashSite, optionsArgument) : null; if (options == null) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 3, expected 1..2)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 3, expected 1..2)")); } } @@ -169,7 +170,7 @@ public static class WaitWritable { int? desc = toIntSite.Target(toIntSite, descriptor); if (!desc.HasValue) { - throw RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(descriptor), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(descriptor), "Integer")); } info.RequireBinmodeForAsciiIncompatible(context); Reinitialize(self, desc.Value, info); @@ -221,7 +222,7 @@ public static class WaitWritable { // an adopted one has just told us its mode and cannot disagree with itself. if (info.HasMode && known) { if ((mode.CanRead() && !stream.CanRead) || (mode.CanWrite() && !stream.CanWrite)) { - throw RubyExceptions.CreateEINVAL(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL()); } } @@ -352,8 +353,8 @@ private static RubyIO TryToIO(RespondToStorage/*!*/ respondToStorage, object converted = site.Target(site, obj); io = converted as RubyIO; if (io == null && strict) { - throw RubyExceptions.CreateTypeError("can't convert {0} to IO ({0}#to_io gives {1})", - context.GetClassDisplayName(obj), context.GetClassDisplayName(converted)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to IO ({0}#to_io gives {1})", + context.GetClassDisplayName(obj), context.GetClassDisplayName(converted))); } return io; } @@ -362,7 +363,7 @@ private static RubyIO TryToIO(RespondToStorage/*!*/ respondToStorage, public static RubyIO/*!*/ Reopen(RubyIO/*!*/ self, [NotNull]RubyIO/*!*/ source) { // Neither end of a dup2 can be a stream that is already gone. if (self.Closed || source.Closed) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } // MRI's io_reopen gives the read-ahead back first, and what #ungetc left goes with it // when there is some; with nothing read the text stays, as it does when a path is @@ -608,7 +609,7 @@ public static int SysOpen(ConversionStorage/*!*/ toInt, ConversionStorage< if (perm != Missing.Value && perm != null) { int? p = toIntSite.Target(toIntSite, perm); if (!p.HasValue) { - throw RubyExceptions.CreateImplicitConversionError(context.GetClassName(perm), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassName(perm), "Integer")); } permissions = p.Value; } @@ -882,15 +883,15 @@ private static int ToTimeInterval(RubyContext/*!*/ context, object timeout) { } else if (timeout is BigInteger) { seconds = (double)(BigInteger)timeout; } else { - throw RubyExceptions.CreateTypeError("can't convert {0} into time interval", - context.GetClassDisplayName(timeout)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into time interval", + context.GetClassDisplayName(timeout))); } if (Double.IsNaN(seconds)) { - throw RubyExceptions.CreateRangeError("NaN out of Time range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("NaN out of Time range")); } if (seconds < 0) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } if (Double.IsPositiveInfinity(seconds)) { return Timeout.Infinite; @@ -919,8 +920,8 @@ private struct SelectEntry { var array = set as RubyArray; if (array == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Array)", - context.GetClassDisplayName(set)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Array)", + context.GetClassDisplayName(set))); } var result = new SelectEntry[array.Count]; @@ -939,7 +940,7 @@ private struct SelectEntry { CallSiteStorage>/*!*/ toIoStorage, RubyContext/*!*/ context, object obj) { return TryToIO(respondToStorage, toIoStorage, context, obj, true) ?? - throw RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(obj), "IO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(obj), "IO")); } private static RubyArray SelectInternal(RespondToStorage/*!*/ respondToStorage, @@ -1073,7 +1074,7 @@ private static bool IsReady(RubyIO/*!*/ io, Readiness kind) { /// private static bool IsReady(RubyIO/*!*/ io, Readiness kind, bool ignoreBuffer) { if (io.Closed) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } var stream = io.GetStream(); @@ -1223,7 +1224,7 @@ private static void ParseWaitArguments(ConversionStorage/*!*/ fixnumCast, R if (args.Length == 2 && !(args[0] is RubySymbol) && !(args[1] is RubySymbol)) { events = Protocols.CastToFixnum(fixnumCast, args[0]); if (events <= 0) { - throw RubyExceptions.CreateArgumentError("Events must be positive integer!"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Events must be positive integer!")); } timeout = args[1]; answerSelf = false; @@ -1243,7 +1244,7 @@ private static void ParseWaitArguments(ConversionStorage/*!*/ fixnumCast, R ToTimeInterval(context, arg); timeout = arg; } else { - throw RubyExceptions.CreateArgumentError("timeout given more than once"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("timeout given more than once")); } } @@ -1261,7 +1262,7 @@ private static int ToWaitEvents(RubySymbol/*!*/ mode) { case "rw": case "read_write": case "readable_writable": return Readable | Writable; default: - throw RubyExceptions.CreateArgumentError("unsupported mode: {0}", mode.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unsupported mode: {0}", mode.ToString())); } } @@ -1306,7 +1307,7 @@ private static int ReadyEvents(RubyIO/*!*/ io, int events, bool ignoreBuffer) { // Nothing asked of the IO leaves the closed check undone, and a closed IO has to be an // IOError however the events were spelled. if (events == 0 && io.Closed) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } return ready; } @@ -1494,7 +1495,7 @@ public static int IoControl(CallSiteStorage) goes down MRI's "the second argument names // the internal encoding of a pair" path and tries to coerce nil to a String. - throw RubyExceptions.CreateTypeConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError("nil", "String")); } internalEncoding = ToEncodingOrWarn(toStr, @internal); } @@ -1767,7 +1768,7 @@ private static RubyEncoding ToEncodingOrWarn(ConversionStorage/*! } string name = Protocols.CastToString(toStr, value).ToString(); if (name.IndexOf('\0') >= 0) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } return IOInfo.TryParseEncoding(toStr.Context, name); } @@ -1816,7 +1817,7 @@ public static object SysSeek(BinaryOpStorage/*!*/ writeStorage, ConversionStorag RubyIO/*!*/ self, [DefaultProtocol]IntegerValue pos, [DefaultProtocol, DefaultParameterValue(SEEK_SET)]int seekOrigin) { var stream = self.GetStream(); if (stream.DataBuffered || self.HasPendingChars) { - throw RubyExceptions.CreateIOError("sysseek for buffered IO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("sysseek for buffered IO")); } if (self.IsConsoleOutput ? self.HasBufferedOutput : stream.WritePending) { PrintOps.ReportWarning(writeStorage, tosConversion, MutableString.CreateAscii("sysseek for buffered IO")); @@ -2153,7 +2154,7 @@ public static MutableString Read(RubyIO/*!*/ self, [DefaultProtocol]int bytes, [ private static MutableString Read(RubyIO/*!*/ self, int bytes, MutableString buffer, bool fully) { self.RequireReadable(); if (bytes < 0) { - throw RubyExceptions.CreateArgumentError("negative length {0} given", bytes); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative length {0} given", bytes)); } self.RequireByteReadable(); @@ -2171,7 +2172,7 @@ private static MutableString Read(RubyIO/*!*/ self, int bytes, MutableString buf [RubyMethod("sysread")] public static MutableString/*!*/ SystemRead(RubyIO/*!*/ self, [DefaultProtocol]int bytes, [DefaultProtocol, Optional]MutableString buffer) { if (bytes < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } if (bytes == 0) { // MRI answers a zero-length read before it looks at the stream or the buffer. @@ -2181,7 +2182,7 @@ private static MutableString Read(RubyIO/*!*/ self, int bytes, MutableString buf self.RequireByteReadable(); var stream = self.GetReadableStream(); if (stream.DataBuffered) { - throw RubyExceptions.CreateIOError("sysread for buffered IO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("sysread for buffered IO")); } // We use Flush to simulate non-buffered IO. @@ -2207,7 +2208,7 @@ private static MutableString Read(RubyIO/*!*/ self, int bytes, MutableString buf public static MutableString ReadAvailable(RubyIO/*!*/ self, [DefaultProtocol]int bytes) { self.RequireReadable(); if (bytes < 0) { - throw RubyExceptions.CreateArgumentError("negative length " + bytes + " given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative length " + bytes + " given")); } self.RequireByteReadable(); var buffer = MutableString.CreateBinary(); @@ -2251,7 +2252,7 @@ public static bool IsDataBuffered(RubyIO/*!*/ self) { /// private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, MutableString buffer) { if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative length " + count + " given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative length " + count + " given")); } var stream = io.GetReadableStream(); @@ -2354,11 +2355,11 @@ private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, M int offset = (optionsOrOffset != Missing.Value && optionsOrOffset != null) ? site.Target(site, optionsOrOffset) : 0; if (offset < 0) { - throw RubyExceptions.CreateEINVAL(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL()); } if (length < 0) { - throw RubyExceptions.CreateArgumentError("negative length {0} given", length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative length {0} given", length)); } // TODO: options @@ -2493,7 +2494,7 @@ public static int ReadByte(RubyIO/*!*/ self) { /// private static void CheckLineLimit(int limit, string/*!*/ methodName) { if (limit == 0) { - throw RubyExceptions.CreateArgumentError("invalid limit: 0 for {0}", methodName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid limit: 0 for {0}", methodName)); } } @@ -2675,8 +2676,8 @@ private static MutableString SeparatorToRead(RubyIO/*!*/ self, MutableString sep bool ascii = separator.IsAscii(); if (separator.Encoding != readEncoding && (!ascii || !readEncoding.IsAsciiIdentity) && !ReferenceEquals(separator, self.Context.InputSeparator)) { - throw RubyExceptions.CreateArgumentError("encoding mismatch: {0} IO with {1} RS", - readEncoding.Name, separator.Encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("encoding mismatch: {0} IO with {1} RS", + readEncoding.Name, separator.Encoding.Name)); } if (ascii && self.Enc2 == null && !readEncoding.IsAsciiIdentity && !readEncoding.IsDummy && separator.Encoding != readEncoding) { // The default separator, in a wide encoding read as it is (prepare_getline_args @@ -2875,7 +2876,7 @@ private static void CheckSeparatorEncoding(RubyContext/*!*/ context, RubyIO/*!*/ && separator.GetByte(0) == (byte)'\n') { return; } - throw RubyExceptions.CreateArgumentError("encoding mismatch: {0} IO with {1} RS", io.Name, rs.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("encoding mismatch: {0} IO with {1} RS", io.Name, rs.Name)); } private static RubyEncoding/*!*/ ReadEncoding(RubyIO/*!*/ self) { @@ -3229,7 +3230,7 @@ private static void ParseLineArguments(ConversionStorage/*!*/ toS } if (count > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..2)", count); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..2)", count)); } separator = context.InputSeparator; @@ -3268,8 +3269,8 @@ private static void ParseLineArguments(ConversionStorage/*!*/ toS } } if (unknown != null) { - throw RubyExceptions.CreateArgumentError( - (unknown.Count == 1 ? "unknown keyword: " : "unknown keywords: ") + String.Join(", ", unknown)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + (unknown.Count == 1 ? "unknown keyword: " : "unknown keywords: ") + String.Join(", ", unknown))); } } } @@ -3449,7 +3450,7 @@ public static object ForEach(CallSiteStorage= -1"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("count should be >= -1")); } if (src_offset < -1) { - throw RubyExceptions.CreateArgumentError("src_offset should be >= -1"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("src_offset should be >= -1")); } var context = toPath.Context; @@ -3661,7 +3662,7 @@ public static object CopyStream( if (src_offset != -1) { if (srcStream == null) { - throw RubyExceptions.CreateArgumentError("cannot specify src_offset for non-IO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cannot specify src_offset for non-IO")); } if (!srcStream.CanSeek) { throw new Errno.InvalidSeekError("pread"); diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index b95485d15..a6f4cc4c3 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -53,7 +53,7 @@ public static object InitializeCopy(RubyContext/*!*/ context, object self, objec RubyClass selfClass = context.GetClassOf(self); RubyClass sourceClass = context.GetClassOf(source); if (sourceClass != selfClass) { - throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("initialize_copy should take same class object")); } return self; @@ -250,7 +250,7 @@ public static object ToInteger(ConversionStorage/*!*/ fixnumCast, UnaryOpSt bool raise = TakeExceptionOption(fixnumCast.Context, ref radixOrOptions, options, 2); if (radixOrOptions == null) { // a base given as nil is not a base left out (MRI's NUM2INT), whatever exception: says - throw RubyExceptions.CreateTypeError("no implicit conversion from nil to integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion from nil to integer")); } int radix = (radixOrOptions == Missing.Value) ? 0 : Protocols.CastToFixnum(fixnumCast, radixOrOptions); RubyContext context = fixnumCast.Context; @@ -261,7 +261,7 @@ public static object ToInteger(ConversionStorage/*!*/ fixnumCast, UnaryOpSt if (!raise) { return null; } - throw RubyExceptions.CreateArgumentError("base specified for non string value"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("base specified for non string value")); } value = str; } @@ -283,7 +283,7 @@ public static object ToInteger(ConversionStorage/*!*/ fixnumCast, UnaryOpSt if (!raise) { return null; } - throw RubyExceptions.CreateTypeConversionError("NilClass", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError("NilClass", "Integer")); } // rb_protect(rb_check_to_int) @@ -313,14 +313,14 @@ public static object ToInteger(ConversionStorage/*!*/ fixnumCast, UnaryOpSt string className = RubyExceptions.MessageTypeName(context.GetClassName(value)); if (!CanCall(context, value, "to_i")) { - throw RubyExceptions.CreateTypeConversionError(className, "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(className, "Integer")); } object result = Call(toI, value, "to_i"); if (AsInteger(result) != null) { return AsInteger(result); } - throw RubyExceptions.CreateTypeError("can't convert {0} to Integer ({0}#to_i gives {1})", - className, RubyExceptions.MessageTypeName(context.GetClassName(result))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to Integer ({0}#to_i gives {1})", + className, RubyExceptions.MessageTypeName(context.GetClassName(result)))); } /// @@ -452,7 +452,7 @@ public static object ToFloat(UnaryOpStorage/*!*/ toF, object self, object value, if (value is MutableString str) { RequireAsciiCompatible(str); if (str.IndexOf('\0') >= 0) { - return raise ? throw RubyExceptions.CreateArgumentError("string for Float contains null byte") : null; + return raise ? throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string for Float contains null byte")) : null; } if (!raise) { double parsed; @@ -464,14 +464,14 @@ public static object ToFloat(UnaryOpStorage/*!*/ toF, object self, object value, if (!raise) { return null; } - throw RubyExceptions.CreateTypeConversionError(context.GetClassName(value), "Float"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(context.GetClassName(value), "Float")); } if (!CanCall(context, value, "to_f")) { if (!raise) { return null; } - throw RubyExceptions.CreateTypeConversionError(context.GetClassName(value), "Float"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(context.GetClassName(value), "Float")); } object result; @@ -486,8 +486,8 @@ public static object ToFloat(UnaryOpStorage/*!*/ toF, object self, object value, if (!raise) { return null; } - throw RubyExceptions.CreateTypeError("can't convert {0} to Float ({0}#to_f gives {1})", - context.GetClassName(value), context.GetClassName(result)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to Float ({0}#to_f gives {1})", + context.GetClassName(value), context.GetClassName(result))); } /// @@ -500,12 +500,12 @@ private static bool TakeExceptionOption(RubyContext/*!*/ context, ref object arg if (options != Missing.Value) { keywords = options as Hash; if (keywords == null || !keywords.IsKeywordArguments) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..{1})", maxArgs + 1, maxArgs); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..{1})", maxArgs + 1, maxArgs)); } } else if ((keywords = arg as Hash) != null && keywords.IsKeywordArguments) { arg = Missing.Value; } else if (maxArgs == 1 && arg != Missing.Value) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 1)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 1)")); } else { return true; } @@ -514,10 +514,10 @@ private static bool TakeExceptionOption(RubyContext/*!*/ context, ref object arg foreach (var entry in keywords) { var key = entry.Key as RubySymbol; if (key == null || key.ToString() != "exception") { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key))); } if (!(entry.Value is bool flag)) { - throw RubyExceptions.CreateArgumentError("expected true or false as exception: {0}", context.Inspect(entry.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("expected true or false as exception: {0}", context.Inspect(entry.Value))); } raise = flag; } @@ -584,8 +584,8 @@ private static MutableString TryConvertToStr(UnaryOpStorage/*!*/ toStr, object v return (MutableString)result; } string className = RubyExceptions.MessageTypeName(context.GetClassName(value)); - throw RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_str gives {1})", - className, RubyExceptions.MessageTypeName(context.GetClassName(result))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_str gives {1})", + className, RubyExceptions.MessageTypeName(context.GetClassName(result)))); } private static bool IsStandardError(RubyContext/*!*/ context, Exception/*!*/ e) { @@ -618,7 +618,7 @@ public static object ParseInteger(MutableString/*!*/ value, int radix, bool rais // Only a positive radix is range-checked; a negative one is a hint, and an // unusable magnitude just falls back to 10. if (radix > 0 && (radix < 2 || radix > 36)) { - throw RubyExceptions.CreateArgumentError("invalid radix {0}", radix); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid radix {0}", radix)); } object result; @@ -978,7 +978,7 @@ public static RubyArray GetStackTrace(RubyContext/*!*/ context, object self, public static RubyArray GetStackTrace(RubyContext/*!*/ context, object self, [DefaultProtocol]int skipFrames, [DefaultProtocol]int length) { if (length < 0) { - throw RubyExceptions.CreateArgumentError("negative size ({0})", length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative size ({0})", length)); } return GetStackTrace(context, skipFrames, length); } @@ -1027,7 +1027,7 @@ public static RubyArray GetStackTrace(ConversionStorage/*!*/ fixnumCast, Ru /// private static RubyArray GetStackTrace(RubyContext/*!*/ context, int skipFrames, int length) { if (skipFrames < 0) { - throw RubyExceptions.CreateArgumentError("negative level ({0})", skipFrames); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative level ({0})", skipFrames)); } // caller(n, length) and caller_locations(n, length): the frames past the last one asked for are not made @@ -1153,7 +1153,7 @@ public static object Loop(BlockParam/*!*/ block, object self) { [RubyMethod("lambda", RubyMethodAttributes.PublicSingleton)] public static Proc/*!*/ CreateLambda(BlockParam/*!*/ block, object self) { if (block == null) { - throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to create Proc object without a block")); } // lambda(&a_lambda) is that lambda @@ -1163,7 +1163,7 @@ public static object Loop(BlockParam/*!*/ block, object self) { // Since 3.3 a Proc object is not turned into a lambda: lambda(&a_proc) is an error. if (!block.IsLiteralBlock) { - throw RubyExceptions.CreateArgumentError("the lambda method requires a literal block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("the lambda method requires a literal block")); } return block.Proc.ToLambda(null); @@ -1173,7 +1173,7 @@ public static object Loop(BlockParam/*!*/ block, object self) { [RubyMethod("proc", RubyMethodAttributes.PublicSingleton)] public static Proc/*!*/ CreateProc(BlockParam/*!*/ block, object self) { if (block == null) { - throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to create Proc object without a block")); } return block.Proc; @@ -1303,11 +1303,11 @@ public static MutableString GetSourceFileLocation(RubyContext/*!*/ context, obje bool hasCause = TryTakeCauseKeyword(ref args, out cause); if (args.Length > 3) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..3)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..3)", args.Length)); } if (args.Length == 0 && hasCause) { - throw RubyExceptions.CreateArgumentError("only cause is given with no arguments"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("only cause is given with no arguments")); } Exception exception; @@ -1326,7 +1326,7 @@ public static MutableString GetSourceFileLocation(RubyContext/*!*/ context, obje if (args.Length >= 3 && args[2] != null) { if (!(args[2] is MutableString || args[2] is RubyArray)) { - throw RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location")); } var site = setBackTraceStorage.GetCallSite("set_backtrace", 1); site.Target(site, exception, args[2]); @@ -1366,7 +1366,7 @@ public static MutableString GetSourceFileLocation(RubyContext/*!*/ context, obje // what this check cost var respondTo = respondToStorage.GetCallSite(); if (!RubyOps.IsTrue(respondTo.Target(respondTo, obj, respondToStorage.Context.StringifyIdentifier("exception")))) { - throw RubyExceptions.CreateTypeError("exception class/object expected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("exception class/object expected")); } object result; @@ -1382,7 +1382,7 @@ public static MutableString GetSourceFileLocation(RubyContext/*!*/ context, obje if (exception == null) { // MRI distinguishes "you passed something that isn't raisable at all" from // "#exception answered something that isn't an exception". - throw RubyExceptions.CreateTypeError("exception object expected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("exception object expected")); } return exception; } @@ -1451,7 +1451,7 @@ private static void SetCause(RubyContext/*!*/ context, Exception/*!*/ exception, } else { causeException = cause as Exception; if (causeException == null) { - throw RubyExceptions.CreateTypeError("exception object expected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("exception object expected")); } } } else { @@ -1471,7 +1471,7 @@ private static void SetCause(RubyContext/*!*/ context, Exception/*!*/ exception, if (causeException != exception) { for (Exception c = causeException; c != null; c = RubyExceptionData.GetInstance(c).Cause) { if (c == exception) { - throw RubyExceptions.CreateArgumentError("circular causes"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("circular causes")); } } } @@ -1628,7 +1628,7 @@ public static object GetObjectId(RubyContext/*!*/ context, object self) { if (options != Missing.Value) { var keywords = options as Hash; if (keywords == null || !keywords.IsKeywordArguments) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 1, expected 0)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 1, expected 0)")); } var context = allocateStorage.Context; object freeze = null; @@ -1642,12 +1642,12 @@ public static object GetObjectId(RubyContext/*!*/ context, object self) { } } if (unknown != null) { - throw RubyExceptions.CreateArgumentError("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", unknown)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", unknown))); } if (freeze != null) { if (!(freeze is bool)) { - throw RubyExceptions.CreateArgumentError("unexpected value for freeze: {0}", - RubyExceptions.MessageTypeName(context.GetClassMessageName(freeze))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected value for freeze: {0}", + RubyExceptions.MessageTypeName(context.GetClassMessageName(freeze)))); } return CloneWithFreeze(initializeCloneStorage, allocateStorage, self, (bool)freeze); } @@ -1832,8 +1832,8 @@ public static object PlainToS(UnaryOpStorage/*!*/ toSStorage, object self, objec } // MRI's conversion_mismatch names the class of what #to_s gave, nil's included ("gives NilClass") string className = context.GetClassMessageName(obj); - throw RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_s gives {1})", className, - context.GetClassMessageName(converted)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_s gives {1})", className, + context.GetClassMessageName(converted))); } private static bool IsPlainToSClass(RubyContext/*!*/ context, RubyClass/*!*/ cls) { @@ -1978,7 +1978,7 @@ public static bool IsOfClass(RubyContext/*!*/ context, object self, object other if (typeGroup != null) { return RubyOps.ConvertTypeGroupToModule(context, typeGroup); } - throw RubyExceptions.CreateTypeError("class or module required"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("class or module required")); } return module; } @@ -1994,10 +1994,10 @@ public static object Extend( // a class is a Module, but not one that can be mixed in foreach (var mixin in new[] { module }.Concat(modules)) { if (mixin is RubyClass) { - throw RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)")); } if (mixin.IsRefinement) { - throw RubyExceptions.CreateTypeError("Cannot extend object with refinement"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot extend object with refinement")); } } @@ -2081,7 +2081,7 @@ public static object Evaluate(RubyScope/*!*/ scope, object self, [DefaultProtoco public static object Evaluate(RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]MutableString/*!*/ code, [NotNull]Proc/*!*/ procBinding, [Optional, NotNull]MutableString file, [DefaultParameterValue(1)]int line) { - throw RubyExceptions.CreateTypeError("wrong argument type proc (expected binding)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type proc (expected binding)")); } #endregion @@ -2389,7 +2389,7 @@ public static object RemoveInstanceVariable(RubyContext/*!*/ context, object/*!* string key = name.StartsWith("$", StringComparison.Ordinal) ? name.Substring(1) : name; object value; if (mustExist && !context.TryGetGlobalVariable(null, key, out value)) { - throw RubyExceptions.CreateNameError(String.Format("undefined global variable ${0}", key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("undefined global variable ${0}", key))); } return key; } @@ -2418,7 +2418,7 @@ public static object TraceVariable(RubyScope/*!*/ scope, BlockParam block, objec } else if (block != null) { handler = block.Proc; } else { - throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to create Proc object without a block")); } scope.RubyContext.AddGlobalVariableTrace(GlobalVariableName(scope.RubyContext, name, false), handler); @@ -2589,7 +2589,7 @@ public static bool RespondToMissing(object self, object methodName, object inclu [RubyMethod("send")] [RubyStackTraceHidden] public static object SendMessage(RubyScope/*!*/ scope, object self) { - throw RubyExceptions.CreateArgumentError("no method name given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no method name given")); } // Its own method rather than a second name on the one above, so that the frame in the @@ -2597,7 +2597,7 @@ public static object SendMessage(RubyScope/*!*/ scope, object self) { // method carries, and ruby/spec looks for that name. [RubyMethod("public_send")] public static object PublicSendMessage(RubyScope/*!*/ scope, object self) { - throw RubyExceptions.CreateArgumentError("no method name given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no method name given")); } // public_send differs from send only in visibility: the site sees Ruby-public members @@ -2827,7 +2827,7 @@ internal static object SendMessageOpt(RubyScope/*!*/ scope, BlockParam block, ob RubyClass cls = context.GetClassOf(self); Type type = (asType != null) ? Protocols.ToType(context, asType) : null; if (!cls.TryGetClrMember(name, type, out info)) { - throw RubyExceptions.CreateNameError("undefined CLR method '{0}' for class '{1}'", name, cls.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("undefined CLR method '{0}' for class '{1}'", name, cls.Name)); } return new RubyMethod(self, info, name); @@ -2860,7 +2860,7 @@ internal static object SendMessageOpt(RubyScope/*!*/ scope, BlockParam block, ob } } - throw RubyExceptions.CreateUndefinedMethodError(context.GetClassOf(self), name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(context.GetClassOf(self), name)); } /// @@ -2881,9 +2881,9 @@ internal static object SendMessageOpt(RubyScope/*!*/ scope, BlockParam block, ob if (info.Visibility == RubyMethodVisibility.Public) { return new RubyMethod(self, info, name); } - throw RubyExceptions.CreateNameError("method '{0}' for class '{1}' is {2}", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("method '{0}' for class '{1}' is {2}", name, context.GetClassDisplayName(self), - info.Visibility == RubyMethodVisibility.Private ? "private" : "protected"); + info.Visibility == RubyMethodVisibility.Private ? "private" : "protected")); } // Nothing of that name is defined, so only a public #respond_to_missing? can still @@ -2898,7 +2898,7 @@ internal static object SendMessageOpt(RubyScope/*!*/ scope, BlockParam block, ob } } - throw RubyExceptions.CreateUndefinedMethodError(context.GetClassOf(self), name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(context.GetClassOf(self), name)); } /// @@ -3099,7 +3099,7 @@ internal static object SendMessageOpt(RubyScope/*!*/ scope, BlockParam block, ob [RubyMethod("fork", RubyMethodAttributes.PublicSingleton)] [RubyNotImplemented] public static object Fork(BlockParam block, object self) { - throw RubyExceptions.CreateNotImplementedError("fork() function is unimplemented on this machine"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNotImplementedError("fork() function is unimplemented on this machine")); } #endregion @@ -3125,7 +3125,7 @@ public static void Sleep(object self) { [RubyMethod("sleep", RubyMethodAttributes.PublicSingleton)] public static int Sleep(object self, int seconds) { if (seconds < 0) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } long ms = seconds * 1000L; @@ -3137,10 +3137,10 @@ public static int Sleep(object self, int seconds) { public static int Sleep(object self, double seconds) { // MRI's rb_time_interval if (Double.IsNaN(seconds)) { - throw RubyExceptions.CreateRangeError("NaN out of Time range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("NaN out of Time range")); } if (seconds < 0) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } double ms = seconds * 1000; @@ -3156,10 +3156,10 @@ public static int Sleep(RubyContext/*!*/ context, object self, object seconds) { ThreadOps.DoSleep(); return 0; case BigInteger: - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); default: // Numerics that answer #divmod (Rational) are split up by the prelude's Kernel#sleep. - throw RubyExceptions.CreateTypeError("can't convert {0} into time interval", context.GetClassDisplayName(seconds)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into time interval", context.GetClassDisplayName(seconds))); } } @@ -3170,7 +3170,7 @@ public static int Sleep(RubyContext/*!*/ context, object self, object seconds) { [RubyMethod("test", RubyMethodAttributes.PublicSingleton)] public static object Test(ConversionStorage/*!*/ toPath, object self, [NotNull]MutableString/*!*/ cmd, object path) { if (cmd.IsEmpty) { - throw RubyExceptions.CreateTypeConversionError("String", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError("String", "Integer")); } return Test(toPath, self, cmd.GetChar(0), path); } @@ -3219,7 +3219,7 @@ public static object Test(ConversionStorage/*!*/ toPath, object s case 'M': return RubyFileOps.RubyStatOps.ModifiedTime(RubyFileOps.RubyStatOps.Create(context, pathStr)); default: - throw RubyExceptions.CreateArgumentError("unknown command '{0}'", (char)cmd); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown command '{0}'", (char)cmd)); } } @@ -3229,7 +3229,7 @@ public static object Test(ConversionStorage/*!*/ toPath, object s object path1, object path2) { if (cmd.IsEmpty) { - throw RubyExceptions.CreateTypeConversionError("String", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError("String", "Integer")); } return Test(toPath, self, cmd.GetChar(0), path1, path2); } @@ -3242,7 +3242,7 @@ public static object Test(ConversionStorage/*!*/ toPath, object s RubyContext context = toPath.Context; cmd &= 0xFF; if (cmd != '-' && cmd != '=' && cmd != '<' && cmd != '>') { - throw RubyExceptions.CreateArgumentError("unknown command '{0}'", (char)cmd); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown command '{0}'", (char)cmd)); } FileSystemInfo first = TryStat(context, Protocols.CastToPath(toPath, path1), true); @@ -3281,7 +3281,7 @@ private static bool Stat(RubyContext/*!*/ context, MutableString/*!*/ path, bool [RubyMethod("syscall", RubyMethodAttributes.PrivateInstance)] [RubyMethod("syscall", RubyMethodAttributes.PublicSingleton)] public static object Syscall(object self, params object[]/*!*/ args) { - throw RubyExceptions.CreateNotImplementedError("syscall() function is unimplemented on this machine"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNotImplementedError("syscall() function is unimplemented on this machine")); } [RubyMethod("trap", RubyMethodAttributes.PrivateInstance)] @@ -3367,7 +3367,7 @@ public static void TerminateExecution(RubyContext/*!*/ context, object self, int [RubyMethod("at_exit", RubyMethodAttributes.PublicSingleton)] public static Proc/*!*/ AtExit(BlockParam/*!*/ block, object self) { if (block == null) { - throw RubyExceptions.CreateArgumentError("called without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("called without a block")); } block.RubyContext.RegisterShutdownHandler(block.Proc); @@ -3441,10 +3441,10 @@ public static void UsingClrExtensions(RubyContext/*!*/ context, object self, Rub if (namespaceModule == null) { ns = ""; } else if (namespaceModule.NamespaceTracker == null) { - throw RubyExceptions.CreateNotClrNamespaceError(namespaceModule); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNotClrNamespaceError(namespaceModule)); } else if (context != namespaceModule.Context) { - throw RubyExceptions.CreateTypeError("Cannot use namespace '{0}' defined in a foreign runtime #{1}", - namespaceModule.NamespaceTracker.Name, namespaceModule.Context.RuntimeId); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot use namespace '{0}' defined in a foreign runtime #{1}", + namespaceModule.NamespaceTracker.Name, namespaceModule.Context.RuntimeId)); } else { ns = namespaceModule.NamespaceTracker.Name; } @@ -3790,7 +3790,7 @@ public static object ReadInputLine(CallSiteStorage>::C") has no name to load by. if (theModule.Name == null || theModule.GetDisplayName(_context, false).ToString().StartsWith("#", StringComparison.Ordinal)) { - throw RubyExceptions.CreateTypeError("can't dump anonymous {0} {1}", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't dump anonymous {0} {1}", theModule.IsClass ? "class" : "module", theModule.GetDisplayName(_context, false) - ); + )); } } @@ -702,9 +702,9 @@ private void WriteObject(object/*!*/ obj) { private void RequireDumpableAsObject(RubyClass/*!*/ theClass) { if (!IsDumpableAsObject(theClass)) { - throw RubyExceptions.CreateTypeError("no _dump_data is defined for class {0}", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no _dump_data is defined for class {0}", theClass.Name ?? theClass.GetDisplayName(_context, false).ToString() - ); + )); } } @@ -798,7 +798,7 @@ private void WriteException(Exception/*!*/ exception, string[]/*!*/ instanceName private void WriteUsingDump(object/*!*/ obj) { MutableString dumpResult = _sites.Dump.Target(_sites.Dump, obj, _recursionLimit) as MutableString; if (dumpResult == null) { - throw RubyExceptions.CreateTypeError("_dump() must return string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("_dump() must return string")); } // What gets written are the instance variables of the string _dump returned, and @@ -832,15 +832,15 @@ private void WriteUsingMarshalDump(object/*!*/ obj) { // compares the immediate classes, so an object with a singleton class may answer // another instance of its own class as long as that one has no singleton of its own. if (data != null && ReferenceEquals(_context.GetImmediateClassOf(data), _context.GetImmediateClassOf(obj))) { - throw RubyExceptions.CreateRuntimeError("{0}#marshal_dump returned same class instance", - _context.GetImmediateClassOf(obj).GetDisplayName(_context, false)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("{0}#marshal_dump returned same class instance", + _context.GetImmediateClassOf(obj).GetDisplayName(_context, false))); } WriteAnObject(data); } private void WriteClass(RubyClass/*!*/ obj) { if (obj.IsSingletonClass) { - throw RubyExceptions.CreateTypeError("singleton class can't be dumped"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("singleton class can't be dumped")); } WriteModuleDefinition((byte)'c', obj); } @@ -1001,12 +1001,12 @@ obj is IronRuby.StandardLibrary.Threading.RubyMutex || obj is IronRuby.StandardLibrary.Monitors.RubyMonitor || obj is System.Threading.Thread || obj is Binding) { - throw RubyExceptions.CreateTypeError("no _dump_data is defined for class {0}", - _context.GetClassDisplayName(obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no _dump_data is defined for class {0}", + _context.GetClassDisplayName(obj))); } if (obj is RubyIO || obj is MatchData) { - throw RubyExceptions.CreateTypeError("can't dump {0}", _context.GetClassDisplayName(obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't dump {0}", _context.GetClassDisplayName(obj))); } } @@ -1020,7 +1020,7 @@ private void CheckSingleton(RubyClass/*!*/ immediate) { hasState = _context.GetInstanceVariableNames(immediate).Length > 0; } if (hasState) { - throw RubyExceptions.CreateTypeError("singleton can't be dumped"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("singleton can't be dumped")); } } } @@ -1034,9 +1034,9 @@ private void WriteExtendedModules(RubyClass/*!*/ theClass) { if (prepends.Length > 0) { foreach (var prepended in prepends) { if (prepended.Name == null) { - throw RubyExceptions.CreateTypeError("can't dump anonymous class {0}", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't dump anonymous class {0}", prepended.GetDisplayName(_context, false) - ); + )); } _writer.Write((byte)'e'); WriteModuleName(prepended); @@ -1049,9 +1049,9 @@ private void WriteExtendedModules(RubyClass/*!*/ theClass) { // MRI reaches an extended module through its iclass and reports an // anonymous one as a class, not as a module. if (mixin.Name == null) { - throw RubyExceptions.CreateTypeError("can't dump anonymous class {0}", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't dump anonymous class {0}", mixin.GetDisplayName(_context, false) - ); + )); } WriteModuleName(mixin); } @@ -1060,7 +1060,7 @@ private void WriteExtendedModules(RubyClass/*!*/ theClass) { private void WriteAnObject(object obj) { if (_recursionLimit == 0) { - throw RubyExceptions.CreateArgumentError("exceed depth limit"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("exceed depth limit")); } if (_recursionLimit > 0) { _recursionLimit--; @@ -1205,7 +1205,7 @@ obj is RubyArray || obj is Hash || obj is RubyRegex || obj is RubyModule || // (Queue's own says "can't dump"), such as a Queue.dup that removed it: a Ruby class // as far as the class chain says, backed by C data all the same ([Bug #9674]). if (obj is IronRuby.StandardLibrary.Threading.RubyQueue || obj is IronRuby.StandardLibrary.Threading.RubyConditionVariable) { - throw RubyExceptions.CreateTypeError("no _dump_data is defined for class {0}", _context.GetClassDisplayName(obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no _dump_data is defined for class {0}", _context.GetClassDisplayName(obj))); } RequireDumpableAsObject(theClass); WriteObject(obj); @@ -1417,10 +1417,10 @@ private void CheckPreamble() { int major = _reader.ReadByte(); int minor = _reader.ReadByte(); if (major != MAJOR_VERSION || minor > MINOR_VERSION) { - throw RubyExceptions.CreateTypeError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError( "incompatible marshal file format (can't be read)\n\tformat version {0}.{1} required; {2}.{3} given", MAJOR_VERSION, MINOR_VERSION, major, minor - ); + )); } if (minor < MINOR_VERSION) { @@ -1435,11 +1435,11 @@ private void CheckPreamble() { private byte[]/*!*/ ReadBytes(int count) { if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } byte[] data = _reader.ReadBytes(count); if (data.Length != count) { - throw RubyExceptions.CreateArgumentError("marshal data too short"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("marshal data too short")); } return data; } @@ -1456,7 +1456,7 @@ private void CheckPreamble() { } int words = ReadInt32(); if (words < 0) { - throw RubyExceptions.CreateArgumentError("negative length"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative length")); } // MRI reads up to four 16-bit words a byte at a time (r_byte, so an IO-like source // is asked for #getbyte) and a longer payload in one piece (r_bytes0). A length @@ -1468,7 +1468,7 @@ private void CheckPreamble() { data[i] = _reader.ReadByte(); } } else if (words > Int32.MaxValue / 2) { - throw RubyExceptions.CreateArgumentError("marshal data too short"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("marshal data too short")); } else { data = ReadBytes(words * 2); } @@ -1705,7 +1705,7 @@ private static bool IsAscii(byte[]/*!*/ data, string/*!*/ text) { private RubyArray/*!*/ ReadArray(RubyArray/*!*/ result) { int count = ReadInt32(); if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative array size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size (or size too big)")); } AddReadable(count - 1); for (int i = 0; i < count; i++) { @@ -1741,13 +1741,13 @@ private static bool IsAscii(byte[]/*!*/ data, string/*!*/ text) { if (typeFlag == ';') { int position = ReadInt32(); if (!_symbols.TryGetValue(position, out result) || result == null) { - throw RubyExceptions.CreateArgumentError("bad symbol"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("bad symbol")); } } else if (typeFlag == 'I') { // An encoded symbol: "I" ":" . int inner = _reader.ReadByte(); if (inner != ':') { - throw RubyExceptions.CreateArgumentError("dump format error for symbol"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("dump format error for symbol")); } result = ReadEncodedSymbol(symbol); } else { @@ -1835,7 +1835,7 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { // record, and the reading side refuses to take one out of it: an 'o' record is // instance variables and nothing else, so it cannot rebuild a File. if (!IsDumpableAsObject(theClass)) { - throw RubyExceptions.CreateArgumentError("dump format error"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("dump format error")); } int count = ReadInt32(); @@ -1916,7 +1916,7 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { private object/*!*/ ReadRange(RubyClass/*!*/ theClass, int count, int objectRef, bool asStruct) { if (asStruct && count != RangeMembers.Length) { - throw RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", theClass.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", theClass.Name)); } var range = (Range)RubyUtils.CreateObject(theClass); if (objectRef >= 0) { @@ -1927,7 +1927,7 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { for (int i = 0; i < count; i++) { string name = ReadIdentifier(); if (asStruct && name != RangeMembers[i]) { - throw RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", theClass.Name, name, RangeMembers[i]); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", theClass.Name, name, RangeMembers[i])); } object value = ReadAnObject(false); switch (name) { @@ -1943,7 +1943,7 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { if (rangeBegin != null && rangeEnd != null) { var compare = _sites.Compare; if (compare.Target(compare, rangeBegin, rangeEnd) == null) { - throw RubyExceptions.CreateArgumentError("bad value for range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("bad value for range")); } } range.InitializeLoaded(rangeBegin, rangeEnd, excludeEnd, theClass == Context.GetClass(typeof(Range))); @@ -2037,8 +2037,8 @@ private void CheckLoad(RubyClass/*!*/ theClass) { bool ranUserCode = false; if (!Context.ResolveMethod(theClass, "_load", VisibilityContext.AllVisible).Found && !ObjRespondTo(_sites, Context.GetImmediateClassOf(theClass), theClass, "_load", ref ranUserCode)) { - throw RubyExceptions.CreateTypeError("class {0} needs to have method '_load'", - theClass.GetDisplayName(Context, false).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("class {0} needs to have method '_load'", + theClass.GetDisplayName(Context, false).ToString())); } } @@ -2047,7 +2047,7 @@ private void CheckLoad(RubyClass/*!*/ theClass) { private object/*!*/ ReadData(int objectRef) { RubyClass theClass = ReadType(); if (IsDumpableAsObject(theClass)) { - throw RubyExceptions.CreateArgumentError("dump format error"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("dump format error")); } object obj = RubyUtils.CreateObject(theClass); @@ -2055,8 +2055,8 @@ private void CheckLoad(RubyClass/*!*/ theClass) { _objects[objectRef] = obj; } if (!Context.ResolveMethod(obj, "_load_data", true).Found) { - throw RubyExceptions.CreateTypeError("class {0} needs to have instance method '_load_data'", - theClass.GetDisplayName(Context, false).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("class {0} needs to have instance method '_load_data'", + theClass.GetDisplayName(Context, false).ToString())); } object data = ReadAnObject(false); _sites.LoadData.Target(_sites.LoadData, obj, data); @@ -2076,8 +2076,8 @@ private void CheckLoad(RubyClass/*!*/ theClass) { ModuleOps.ExtendObject(extension, obj); } if (!Context.ResolveMethod(obj, "marshal_load", VisibilityContext.AllVisible).Found) { - throw RubyExceptions.CreateTypeError("instance of {0} needs to have method 'marshal_load'", - Context.GetClassOf(obj).GetDisplayName(Context, false).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("instance of {0} needs to have method 'marshal_load'", + Context.GetClassOf(obj).GetDisplayName(Context, false).ToString())); } object data = ReadAnObject(false); _sites.MarshalLoad.Target(_sites.MarshalLoad, obj, data); @@ -2112,9 +2112,9 @@ private void CheckLoad(RubyClass/*!*/ theClass) { bool notModule; if (!Context.TryGetModule(_globalScope, name, out result, out notModule)) { if (notModule) { - throw RubyExceptions.CreateTypeError("{0} does not refer to class/module", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0} does not refer to class/module", name)); } - throw RubyExceptions.CreateArgumentError("undefined class/module {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("undefined class/module {0}", name)); } return result; } @@ -2124,10 +2124,10 @@ private void CheckLoad(RubyClass/*!*/ theClass) { bool isClass = result is RubyClass; if (isClass && typeFlag == 'm') { - throw RubyExceptions.CreateArgumentError("{0} does not refer to module", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("{0} does not refer to module", name)); } if (!isClass && typeFlag == 'c') { - throw RubyExceptions.CreateArgumentError("{0} does not refer to class", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("{0} does not refer to class", name)); } return result; } @@ -2143,7 +2143,7 @@ private void CheckLoad(RubyClass/*!*/ theClass) { // rb_struct_s_members says before the object is made ([ruby-dev:31709]). bool isStruct = theClass.IsSubclassOf(Context.GetClass(typeof(RubyStruct))); if (!isStruct && GetDataMembers(theClass) == null) { - throw RubyExceptions.CreateTypeError("class {0} not a struct", theClass.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("class {0} not a struct", theClass.Name)); } object instance = RubyUtils.CreateObject(theClass); @@ -2160,14 +2160,14 @@ private void CheckLoad(RubyClass/*!*/ theClass) { var names = obj.GetNames(); int count = ReadInt32(); if (count != names.Count) { - throw RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", Context.GetClassOf(obj).Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", Context.GetClassOf(obj).Name)); } AddReadable((count - 1) * 2L); for (int i = 0; i < count; i++) { string name = ReadIdentifier(); if (name != names[i]) { - throw RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", theClass.Name, name, names[i]); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", theClass.Name, name, names[i])); } obj[i] = ReadAnObject(false); AddReadable(-2); @@ -2186,13 +2186,13 @@ private void CheckLoad(RubyClass/*!*/ theClass) { RubyArray members = GetDataMembers(dataClass); int count = ReadInt32(); if (members != null && count != members.Count) { - throw RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", dataClass.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", dataClass.Name)); } AddReadable((count - 1) * 2L); for (int i = 0; i < count; i++) { string name = ReadIdentifier(); if (members != null && name != members[i].ToString()) { - throw RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", dataClass.Name, name, members[i]); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", dataClass.Name, name, members[i])); } Context.SetInstanceVariable(instance, RubyUtils.GetHiddenInstanceVariableName(name), ReadAnObject(false)); AddReadable(-2); @@ -2287,8 +2287,8 @@ private void ReadIVars(object obj) { } } if (count > 0) { - throw RubyExceptions.CreateTypeError("can't override instance variable of {0} '{1}'", - module.IsClass ? "class" : "module", module.GetDisplayName(Context, false).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't override instance variable of {0} '{1}'", + module.IsClass ? "class" : "module", module.GetDisplayName(Context, false).ToString())); } return; } @@ -2307,8 +2307,8 @@ private void SetIVar(object obj, string/*!*/ name, object value) { // MRI's r_ivar: the flag Hash.ruby2_keywords_hash leaves, whatever its value Hash hash = obj as Hash; if (hash == null) { - throw RubyExceptions.CreateArgumentError("ruby2_keywords flag is given but {0} is not a Hash", - ((obj as MutableString) ?? RubyUtils.ObjectToMutableString(Context, obj)).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("ruby2_keywords flag is given but {0} is not a Hash", + ((obj as MutableString) ?? RubyUtils.ObjectToMutableString(Context, obj)).ToString())); } hash.IsRuby2KeywordsHash = true; } else { @@ -2329,8 +2329,8 @@ private void SetIVar(object obj, string/*!*/ name, object value) { object instance = ReadAnObject(typeFlag, objectRef); RubyClass actual = Context.GetClassOf(instance); if (actual != originClass) { - throw RubyExceptions.CreateArgumentError("prepended class {0} differs from class {1}", - extensionName, actual.GetDisplayName(Context, false).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("prepended class {0} differs from class {1}", + extensionName, actual.GetDisplayName(Context, false).ToString())); } _prependedBelow = true; return instance; @@ -2431,7 +2431,7 @@ private void SetIVar(object obj, string/*!*/ name, object value) { break; } if (!loaded) { - throw RubyExceptions.CreateArgumentError("incompatible base type"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("incompatible base type")); } return obj; } @@ -2492,13 +2492,13 @@ private object ReadAnObject(int typeFlag, int reservedRef) { case '@': int link = ReadInt32(); if (!_objects.TryGetValue(link, out obj)) { - throw RubyExceptions.CreateArgumentError("dump format error (unlinked)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("dump format error (unlinked)")); } // A Regexp's instance variables are read before the Regexp exists (ReadRegex): one of them // that refers to it is MRI's "bad link" (r_object's link to an entry that is still Qundef). // Not any empty slot: a _load that answers nil fills its slot with nil. if (link == _regexBeingRead) { - throw RubyExceptions.CreateArgumentError("dump format error (bad link)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("dump format error (bad link)")); } // MRI runs the proc over a back-reference too - the proc sees each place // an object appears in the dump, not each object - but only once the @@ -2587,8 +2587,8 @@ private object ReadAnObject(int typeFlag, int reservedRef) { obj = ReadUserClass(objectRef); break; default: - throw RubyExceptions.CreateArgumentError("dump format error({0})", - "0x" + ((int)typeFlag).ToString("x", CultureInfo.InvariantCulture)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("dump format error({0})", + "0x" + ((int)typeFlag).ToString("x", CultureInfo.InvariantCulture))); } if (objectRef >= 0 && !_selfLinked) { _objects[objectRef] = obj; @@ -2665,12 +2665,12 @@ internal object Load() { if (FromStream && !_started) { throw IronRuby.Runtime.RubyExceptionData.Unkept(new EOFError("end of file reached")); } - throw RubyExceptions.CreateArgumentError("marshal data too short", e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("marshal data too short", e)); } catch (EOFError) { // an IO-like source's #getbyte answered nil (MRI's r_byte: rb_eof_error) throw; } catch (IOException e) { - throw RubyExceptions.CreateArgumentError("marshal data too short", e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("marshal data too short", e)); } } } @@ -2727,7 +2727,7 @@ public static object Dump(WriterSites/*!*/ sites, RespondToStorage/*!*/ respondT stream = RubyIOOps.CreateIOWrapper(respondToStorage, io, FileAccess.Write); } if (stream == null || !stream.CanWrite) { - throw RubyExceptions.CreateTypeError("instance of IO needed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("instance of IO needed")); } SetBinaryMode(sites.Binmode, respondToStorage, io); @@ -2758,7 +2758,7 @@ private static bool ParseLoadOptions(RubyContext/*!*/ context, object arg1, obje if (key != null && key.ToString() == "freeze") { freeze = RubyOps.IsTrue(pair.Value); } else { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(pair.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(pair.Key))); } } continue; @@ -2812,7 +2812,7 @@ public static object Load(ReaderSites/*!*/ sites, RespondToStorage/*!*/ respondT if (source == null || !Protocols.RespondTo(respondToStorage, source, "getbyte") || !Protocols.RespondTo(respondToStorage, source, "read")) { - throw RubyExceptions.CreateTypeError("instance of IO needed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("instance of IO needed")); } SetBinaryMode(sites.Binmode, respondToStorage, source); diff --git a/Src/Libraries/Builtins/MatchDataOps.cs b/Src/Libraries/Builtins/MatchDataOps.cs index 95a7252fd..fcb0b38ef 100644 --- a/Src/Libraries/Builtins/MatchDataOps.cs +++ b/Src/Libraries/Builtins/MatchDataOps.cs @@ -59,7 +59,7 @@ private static MutableString GetNamedGroup(MatchData/*!*/ self, string/*!*/ name // sliced by the CLR offsets, not through String#[], which counts characters MutableString value; if (!self.TryGetNamedGroupValue(name, out value)) { - throw RubyExceptions.CreateIndexError("undefined group name reference: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("undefined group name reference: {0}", name)); } return value; } diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 2c32e6132..4d87bf10f 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -159,7 +159,7 @@ public static RubyMethod GetSuperMethod(RubyContext/*!*/ context, RubyMethod/*!* internal static RubyMemberInfo/*!*/ SelectOverload(RubyContext/*!*/ context, RubyMemberInfo/*!*/ info, string/*!*/ name, object[]/*!*/ typeArgs) { RubyMemberInfo result = info.TrySelectOverload(Protocols.ToTypes(context, typeArgs)); if (result == null) { - throw RubyExceptions.CreateArgumentError("no overload of '{0}' matches given parameter types", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no overload of '{0}' matches given parameter types", name)); } return result; } @@ -171,7 +171,7 @@ public static RubyMethod GetSuperMethod(RubyContext/*!*/ context, RubyMethod/*!* [RubyMethod("overloads")] public static RubyMethod/*!*/ SelectOverload_old(RubyContext/*!*/ context, RubyMethod/*!*/ self, [NotNullItems]params object/*!*/[]/*!*/ parameterTypes) { - throw RubyExceptions.CreateNameError("Method#overloads is an obsolete name, use Method#overload."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("Method#overloads is an obsolete name, use Method#overload.")); } [RubyMethod("overload")] diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 5e0ba7b59..a49297ee9 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -36,7 +36,7 @@ public static class ModuleOps { public static object Reinitialize(BlockParam block, RubyModule/*!*/ self) { // no class can be reinitialized: if (self.IsClass) { - throw RubyExceptions.CreateTypeError("already initialized class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("already initialized class")); } return (block != null) ? RubyUtils.EvaluateInModule(self, block, new object[] { self }) : null; @@ -71,12 +71,12 @@ public static void ObjectExtended(RubyModule/*!*/ self, object extendedObject) { RubyModule/*!*/ self, [NotNullItems]params RubyModule/*!*/[]/*!*/ modules) { if (modules.Length == 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)")); } foreach (var module in modules) { if (module.IsRefinement) { - throw RubyExceptions.CreateTypeError("Cannot include refinement"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot include refinement")); } } @@ -118,7 +118,7 @@ public static void Included(RubyModule/*!*/ self, RubyModule/*!*/ owner) { RubyModule/*!*/ self, params object[]/*!*/ args) { if (args.Length == 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)")); } // reported by name rather than by the generic conversion failure, the way MRI does it: @@ -126,15 +126,15 @@ public static void Included(RubyModule/*!*/ self, RubyModule/*!*/ owner) { for (int i = 0; i < args.Length; i++) { modules[i] = args[i] as RubyModule; if (modules[i] == null && args[i] != null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Module)", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Module)", self.Context.GetClassDisplayName(args[i]) - ); + )); } } foreach (var module in modules) { if (module != null && module.IsRefinement) { - throw RubyExceptions.CreateTypeError("Cannot prepend refinement"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot prepend refinement")); } } @@ -173,15 +173,15 @@ public static void Prepended(RubyModule/*!*/ self, RubyModule/*!*/ owner) { public static RubyModule/*!*/ Refine(BlockParam block, RubyModule/*!*/ self, object target) { RubyModule refinedModule = target as RubyModule; if (refinedModule == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Class or Module)", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Class or Module)", self.Context.GetClassDisplayName(target) - ); + )); } if (block == null) { - throw RubyExceptions.CreateArgumentError("no block given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no block given")); } if (!block.IsLiteralBlock) { - throw RubyExceptions.CreateArgumentError("can't pass a Proc as a block to Module#refine"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't pass a Proc as a block to Module#refine")); } RubyModule refinement = self.GetOrCreateRefinement(refinedModule); @@ -205,7 +205,7 @@ public static void Prepended(RubyModule/*!*/ self, RubyModule/*!*/ owner) { // its own and may use it. A string module_eval is not: it runs in the frame that called it. for (RubyScope s = scope; s != null; s = s.Parent) { if (s.Kind == ScopeKind.Method || s.Kind == ScopeKind.BlockMethod) { - throw RubyExceptions.CreateRuntimeError("Module#using is not permitted in methods"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("Module#using is not permitted in methods")); } if ((s.Kind == ScopeKind.Module && !(s is RubyModuleEvalScope)) || s.Kind == ScopeKind.TopLevel) { break; @@ -213,7 +213,7 @@ public static void Prepended(RubyModule/*!*/ self, RubyModule/*!*/ owner) { } // and only on the module whose body (or module_eval block) is running if (!ReferenceEquals(scope.SelfObject, self)) { - throw RubyExceptions.CreateRuntimeError("Module#using is not called on self"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("Module#using is not called on self")); } ActivateRefinements(scope, module); return self; @@ -222,9 +222,9 @@ public static void Prepended(RubyModule/*!*/ self, RubyModule/*!*/ owner) { internal static void ActivateRefinements(RubyScope/*!*/ scope, object module) { RubyModule refiner = module as RubyModule; if (refiner == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Module)", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Module)", scope.RubyContext.GetClassDisplayName(module) - ); + )); } // A CLR namespace brings in its extension methods where it is used, as C#'s `using System.Linq;' @@ -233,7 +233,7 @@ internal static void ActivateRefinements(RubyScope/*!*/ scope, object module) { Type staticClass; if (RubyModule.IsClrExtensionSource(refiner, out ns, out staticClass)) { if (refiner.Context != scope.RubyContext) { - throw RubyExceptions.CreateTypeError("Cannot use '{0}' defined in a foreign runtime #{1}", refiner.Name, refiner.Context.RuntimeId); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot use '{0}' defined in a foreign runtime #{1}", refiner.Name, refiner.Context.RuntimeId)); } scope.RubyContext.ActivateScopedExtensions(ns ?? staticClass.Namespace ?? String.Empty); scope.ActivateRefinements(refiner, true); @@ -241,7 +241,7 @@ internal static void ActivateRefinements(RubyScope/*!*/ scope, object module) { } if (refiner.IsClass) { - throw RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)")); } // `using' is a no-op for a module that refines nothing, exactly as in CRuby. @@ -386,7 +386,7 @@ public static object CopyMethodsToModuleSingleton(ConversionStorage/*!*/ // This is an important restriction for correct super calls in module functions (see RubyOps.DefineMethod). // MRI has it wrong. It checks just here and not in method definition. if (self.IsClass) { - throw RubyExceptions.CreateTypeError("module_function must be called for modules"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("module_function must be called for modules")); } CheckScopeVisibility(scope, "module_function", methodNames); @@ -424,7 +424,7 @@ internal static void SetMethodAttributes(RubyModule/*!*/ module, string/*!*/[]/* var resolved = module.ResolveMethodNoLock(methodName, VisibilityContext.AllVisible, options); method = resolved.Info; if (method == null) { - throw RubyExceptions.CreateUndefinedMethodError(module, methodName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(module, methodName)); } // MRI only adds method to the target module if visibility differs: @@ -501,8 +501,8 @@ public static void MakeSameMethod(RubyModule/*!*/ self, [DefaultProtocol, NotNul [RubyMethod("define_method")] public static RubySymbol/*!*/ DefineMethod(RubyScope/*!*/ scope, RubyModule/*!*/ self, [DefaultProtocol, NotNull]string/*!*/ methodName, object method) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Proc/Method/UnboundMethod)", - scope.RubyContext.GetClassDisplayName(method)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Proc/Method/UnboundMethod)", + scope.RubyContext.GetClassDisplayName(method))); } // thread-safe: @@ -566,11 +566,11 @@ internal static void DefineMethod(RubyScope/*!*/ scope, RubyModule/*!*/ self, st } if (targetConstraint.IsClass && !self.HasAncestorNoLock(targetConstraint)) { if (targetConstraint.IsSingletonClass) { - throw RubyExceptions.CreateTypeError("can't bind singleton method to a different class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't bind singleton method to a different class")); } - throw RubyExceptions.CreateTypeError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError( "bind argument must be a subclass of {0}", targetConstraint.GetName(scope.RubyContext) - ); + )); } self.SetDefinedMethodNoEventNoLock(self.Context, methodName, info, visibility, sourceName); @@ -903,8 +903,8 @@ private static void RequireMutable(RubyModule/*!*/ self) { if (!self.RemoveMethod(methodName)) { // MRI's wording for remove_method differs from undef_method's: // "method 'x' not defined in C" - throw RubyExceptions.CreateNameError("method '{0}' not defined in {1}", - methodName, RubyExceptions.GetModuleErrorName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("method '{0}' not defined in {1}", + methodName, RubyExceptions.GetModuleErrorName(self))); } } return self; @@ -920,7 +920,7 @@ private static void RequireMutable(RubyModule/*!*/ self) { foreach (var methodName in methodNames) { self.WarnIfUndefiningCoreMethod(methodName); if (!self.ResolveMethod(methodName, VisibilityContext.AllVisible).Found) { - throw RubyExceptions.CreateUndefinedMethodError(self, methodName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(self, methodName)); } self.UndefineMethod(methodName); } @@ -1047,7 +1047,7 @@ public static object Comparison(RubyModule/*!*/ self, object module) { [RubyMethod("<=")] [RubyMethod(">=")] public static object InvalidComparison(RubyModule/*!*/ self, object module) { - throw RubyExceptions.CreateTypeError("compared with non class/module"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("compared with non class/module")); } // thread-safe: @@ -1090,7 +1090,7 @@ public static object InvalidComparison(RubyModule/*!*/ self, object module) { [RubyMethod("include?")] public static bool IncludesModule(RubyModule/*!*/ self, [NotNull]RubyModule/*!*/ other) { if (other.IsClass) { - throw RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)")); } return other != self && self.HasAncestor(other); @@ -1131,7 +1131,7 @@ private static object Evaluate(ConversionStorage/*!*/ toStr, Conv if (block != null) { if (args.Length != 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0)", args.Length)); } // The module is passed to the block as its single argument, so @@ -1141,7 +1141,7 @@ private static object Evaluate(ConversionStorage/*!*/ toStr, Conv } if (args.Length == 0 || args.Length > 3) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..3)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..3)", args.Length)); } var code = Protocols.CastToString(toStr, args[0]); @@ -1168,7 +1168,7 @@ public static object ClassExec(BlockParam block, RubyModule/*!*/ self, params ob private static object Execute(BlockParam block, RubyModule/*!*/ self, object[]/*!*/ args) { if (block == null) { - throw RubyExceptions.CreateLocalJumpError("no block given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLocalJumpError("no block given")); } return RubyUtils.EvaluateInModule(self, block, args); } @@ -1249,9 +1249,9 @@ public static object RemoveClassVariable(RubyModule/*!*/ self, [DefaultProtocol, if (!self.TryGetClassVariable(variableName, out value)) { // MRI words a bad name differently here than class_variable_get and friends do if (!Tokenizer.IsClassVariableName(variableName)) { - throw RubyExceptions.CreateNameError("wrong class variable name {0}", variableName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("wrong class variable name {0}", variableName)); } - throw RubyExceptions.CreateNameError("class variable {0} not defined for {1}", variableName, self.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("class variable {0} not defined for {1}", variableName, self.Name)); } self.RemoveClassVariable(variableName); return value; @@ -1422,9 +1422,9 @@ public static object RemoveConstant(RubyModule/*!*/ self, [DefaultProtocol, NotN object value; if (self.IsHiddenConstant(constantName) || !self.TryRemoveConstant(constantName, out value)) { if (!Tokenizer.IsConstantName(constantName)) { - throw RubyExceptions.CreateNameError("'{0}' is not allowed as a constant variable name", constantName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("'{0}' is not allowed as a constant variable name", constantName)); } - throw RubyExceptions.CreateNameError("constant {0}::{1} not defined", self.Name, constantName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("constant {0}::{1} not defined", self.Name, constantName)); } if (deprecated) { @@ -1508,8 +1508,8 @@ private static bool IsHiddenConstant(RubyModule/*!*/ owner, string/*!*/ name, bo names[i] = Protocols.CastToSymbol(stringCast, constantNames[i]); // a hidden constant is not there, except to __hide_constant__ itself (a prelude loaded again) if (methodName != "__hide_constant__" && self.IsHiddenConstant(names[i])) { - throw RubyExceptions.CreateNameError(String.Format("constant {0}::{1} not defined", - self.Name, names[i])); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("constant {0}::{1} not defined", + self.Name, names[i]))); } } return names; @@ -1593,16 +1593,16 @@ public ConstantPath(ConversionStorage/*!*/ stringCast, object nam /// public RubyModule/*!*/ Enter(int index, RubyModule/*!*/ owner, object previous) { if (index == _malformedAt) { - throw RubyExceptions.CreateNameError(String.Format("wrong constant name {0}", _name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("wrong constant name {0}", _name))); } if (index > 0) { owner = previous as RubyModule; if (owner == null) { - throw RubyExceptions.CreateTypeError("{0} does not refer to class/module", _name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0} does not refer to class/module", _name)); } } if (!Tokenizer.IsConstantName(this[index])) { - throw RubyExceptions.CreateNameError(String.Format("wrong constant name {0}", this[index])); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("wrong constant name {0}", this[index]))); } return owner; } @@ -1733,7 +1733,7 @@ public static void SetAutoloadedConstant(ConversionStorage/*!*/ t RubyUtils.CheckConstantName(constantName); MutableString path = Protocols.CastToPath(toPath, pathArg); if (path.IsEmpty) { - throw RubyExceptions.CreateArgumentError("empty file name"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("empty file name")); } self.SetAutoloadedConstant(constantName, path); @@ -1946,7 +1946,7 @@ public static bool PublicMethodDefined(ConversionStorage/*!*/ stringCast // refined method, whose #owner is the refinement. RubyMemberInfo method = self.ResolveMethodWithRefinements(methodName, VisibilityContext.AllVisible, scope).Info; if (method == null) { - throw RubyExceptions.CreateUndefinedMethodError(self, methodName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(self, methodName)); } RubyModule constraint = self; @@ -1965,13 +1965,13 @@ public static bool PublicMethodDefined(ConversionStorage/*!*/ stringCast RubyMemberInfo method = self.ResolveMethodWithRefinements(methodName, VisibilityContext.AllVisible, scope).Info; if (method == null) { - throw RubyExceptions.CreateUndefinedMethodError(self, methodName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(self, methodName)); } if (method.Visibility != RubyMethodVisibility.Public) { // the method is there, just not public - which is what MRI says - throw RubyExceptions.CreateNameError("method '{0}' for {1} '{2}' is {3}", methodName, + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("method '{0}' for {1} '{2}' is {3}", methodName, self.IsClass ? "class" : "module", self.GetDisplayName(scope.RubyContext, false), - method.Visibility == RubyMethodVisibility.Private ? "private" : "protected"); + method.Visibility == RubyMethodVisibility.Private ? "private" : "protected")); } return GetInstanceMethod(scope, self, methodName); @@ -2015,7 +2015,7 @@ private static bool IsConstantPath(string/*!*/ name) { [RubyMethod("set_temporary_name")] public static RubyModule/*!*/ SetTemporaryName(RubyContext/*!*/ context, RubyModule/*!*/ self, [DefaultProtocol]MutableString name) { if (self.HasPermanentName) { - throw RubyExceptions.CreateRuntimeError("can't change permanent name"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("can't change permanent name")); } if (name == null) { @@ -2025,10 +2025,10 @@ private static bool IsConstantPath(string/*!*/ name) { string str = name.ConvertToString(); if (str.Length == 0) { - throw RubyExceptions.CreateArgumentError("empty class/module name"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("empty class/module name")); } if (IsConstantPath(str)) { - throw RubyExceptions.CreateArgumentError("the temporary name must not be a constant path to avoid confusion"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("the temporary name must not be a constant path to avoid confusion")); } self.SetName(str, false); @@ -2049,9 +2049,9 @@ public static RubyModule ToClrRef(RubyModule/*!*/ self) { try { return self.TypeTracker != null ? self.Context.GetClass(self.TypeTracker.Type.MakeByRefType()) : null; } catch (Exception) { - throw RubyExceptions.CreateTypeError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError( "Cannot create by-ref type for '{0}'", self.Context.GetTypeName(self.TypeTracker.Type, true) - ); + )); } } @@ -2059,7 +2059,7 @@ public static RubyModule ToClrRef(RubyModule/*!*/ self) { [RubyMethod("[]")] public static RubyModule/*!*/ Of(RubyModule/*!*/ self, [NotNullItems]params object/*!*/[]/*!*/ typeArgs) { if (self.TypeTracker == null) { - throw RubyExceptions.CreateArgumentError("'{0}' is not a type", self.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("'{0}' is not a type", self.Name)); } Type type = self.TypeTracker.Type; @@ -2071,23 +2071,23 @@ public static RubyModule ToClrRef(RubyModule/*!*/ self) { try { arrayType = elementType.MakeArrayType(); } catch (Exception) { - throw RubyExceptions.CreateTypeError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError( "Cannot create array type for '{0}'", self.Context.GetTypeName(elementType, true) - ); + )); } return self.Context.GetModule(arrayType); } if (!type.IsGenericTypeDefinition) { if (provided > 0) { - throw RubyExceptions.CreateArgumentError("'{0}' is not a generic type definition", self.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("'{0}' is not a generic type definition", self.Name)); } return self; } int required = type.GetGenericArguments().Length; if (required != provided) { - throw RubyExceptions.CreateArgumentError("Type '{0}' requires {1} generic type arguments, {2} provided", self.Name, required, provided); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Type '{0}' requires {1} generic type arguments, {2} provided", self.Name, required, provided)); } Type concreteType = Protocols.MakeGenericType(self.Context, type, self.Name, typeArgs); @@ -2098,20 +2098,20 @@ public static RubyModule ToClrRef(RubyModule/*!*/ self) { [RubyMethod("[]")] public static RubyModule/*!*/ Of(RubyModule/*!*/ self, int genericArity) { if (self.TypeTracker == null) { - throw RubyExceptions.CreateArgumentError("'{0}' is not a type", self.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("'{0}' is not a type", self.Name)); } Type type = self.TypeTracker.Type; if (!type.IsGenericTypeDefinition) { if (genericArity > 0) { - throw RubyExceptions.CreateArgumentError("'{0}' is not a generic type definition", self.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("'{0}' is not a generic type definition", self.Name)); } return self; } if (type.GetGenericArguments().Length != genericArity) { - throw RubyExceptions.CreateArgumentError("'{0}' does not have generic arity {1}", self.Name, genericArity); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("'{0}' does not have generic arity {1}", self.Name, genericArity)); } return self; diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 8c09c4098..f5cb80c86 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -67,7 +67,7 @@ public class MutableStringOps { result.ForceEncoding(Protocols.ConvertToEncoding(toStr, entry.Value)); } } else if (name != "capacity") { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key).ToString())); } } return result; @@ -206,7 +206,7 @@ public int NextToken() { int digit2 = Tokenizer.ToDigit(GetChar()); if (digit1 >= 16) { - throw RubyExceptions.CreateArgumentError("Invalid escape character syntax"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Invalid escape character syntax")); } if (digit2 >= 16) { @@ -433,11 +433,11 @@ private static int CodepointAt(MutableString/*!*/ str, ref int position) { int last = CodepointAt(selector, ref position); if (first > last) { if (first < 0x80 && last < 0x80) { - throw RubyExceptions.CreateArgumentError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( String.Format("invalid range \"{0}-{1}\" in string transliteration", (char)first, (char)last) - ); + )); } - throw RubyExceptions.CreateArgumentError("invalid range in string transliteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid range in string transliteration")); } result._rangeBounds.Add(first); result._rangeBounds.Add(last); @@ -754,7 +754,7 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { [RubyMethod("*")] public static MutableString/*!*/ Repeat(MutableString/*!*/ self, [DefaultProtocol]int times) { if (times < 0) { - throw RubyExceptions.CreateArgumentError("negative argument"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative argument")); } // Ruby 3.0 dropped subclass preservation here: "MyString.new("x") * 2".class is String. @@ -764,7 +764,7 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { return result; } if ((long)self.GetByteCount() * times > Int32.MaxValue) { - throw RubyExceptions.CreateArgumentError("argument too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument too big")); } return result.AppendMultiple(self, times); } @@ -777,10 +777,10 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { [RubyMethod("*")] public static MutableString/*!*/ Repeat(MutableString/*!*/ self, [NotNull]BigInteger/*!*/ times) { if (times.Sign < 0) { - throw RubyExceptions.CreateArgumentError("negative argument"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative argument")); } if (times > Int64.MaxValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } // Ruby 3.0 dropped subclass preservation here: "MyString.new("x") * 2".class is String. @@ -788,7 +788,7 @@ private static bool IsBare(RubyContext/*!*/ context, MutableString/*!*/ self) { if (self.IsEmpty) { return result; } - throw RubyExceptions.CreateArgumentError("argument too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument too big")); } // encoding aware @@ -1251,7 +1251,7 @@ public static MutableString ByteSlice(ConversionStorage/*!*/ fixnumCast, Mu /// private static int NarrowIndex(BigInteger value) { if (value > Int64.MaxValue || value < Int64.MinValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } if (value > Int32.MaxValue) { return Int32.MaxValue; @@ -1348,7 +1348,7 @@ private static MutableString GetNamedGroupSubstring(RubyScope/*!*/ scope, Mutabl } if (!match.HasNamedGroup(groupName)) { - throw RubyExceptions.CreateIndexError("undefined group name reference: {0}", groupName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("undefined group name reference: {0}", groupName)); } return match.GetNamedGroupValue(groupName); @@ -1374,7 +1374,7 @@ private static bool IsEscapedByte(MutableString/*!*/ str, int index) { [RubyMethod("ord")] public static object Ord(MutableString/*!*/ str) { if (str.IsEmpty) { - throw RubyExceptions.CreateArgumentError("empty string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("empty string")); } // The first character, as the string's characters are walked: taking the first char @@ -1405,7 +1405,7 @@ public static object Ord(MutableString/*!*/ str) { return ScriptingRuntimeHelpers.Int32ToObject(first.Invalid[0]); } - throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", str.Encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", str.Encoding)); } // In an encoding that is not Unicode the ordinal is the character's own code, the bytes @@ -1466,7 +1466,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index public static MutableString/*!*/ ReplaceCharacter(MutableString/*!*/ self, [NotNull]BigInteger/*!*/ index, [DefaultProtocol, NotNull]MutableString/*!*/ value) { if (index < Int64.MinValue || index > Int64.MaxValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } self.RequireNotFrozen(); throw RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of string", index)); @@ -1498,7 +1498,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index if (range.Begin is int) { int begin = (int)range.Begin < 0 ? (int)range.Begin + length : (int)range.Begin; if (begin < 0 || begin > length) { - throw RubyExceptions.CreateRangeError("{0} out of range", (object)rangeValues.Context.Inspect(index).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of range", (object)rangeValues.Context.Inspect(index).ToString())); } } int start, count; @@ -1546,7 +1546,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index [DefaultProtocol]int start, [DefaultProtocol]int charsToOverwrite, [DefaultProtocol, NotNull]MutableString/*!*/ value) { if (charsToOverwrite < 0) { - throw RubyExceptions.CreateIndexError("negative length {0}", charsToOverwrite); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("negative length {0}", charsToOverwrite)); } self.RequireCompatibleEncoding(value); @@ -1590,8 +1590,8 @@ private static void NormalizeReplacedRange(ConversionStorage/*!*/ fixnumCas if (normalizedBegin < 0 || normalizedBegin > length) { // MRI quotes the range as it was written, not as it was normalized - and an // endless one without its missing end. - throw RubyExceptions.CreateRangeError("{0}{1}{2} out of range", begin, - range.ExcludeEnd ? "..." : "..", range.End ?? ""); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0}{1}{2} out of range", begin, + range.ExcludeEnd ? "..." : "..", range.End ?? "")); } end = end < 0 ? end + length : end; @@ -1614,7 +1614,7 @@ public static MutableString ReplaceSubstring(MutableString/*!*/ self, substring.PrepareForCharacterRead(); int index = IsBrokenNeedle(substring) ? -1 : self.IndexOf(substring); if (index == -1) { - throw RubyExceptions.CreateIndexError("string not matched"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("string not matched")); } return ReplaceClrRange(self, index, substring.Length, value); @@ -1653,10 +1653,10 @@ private static MutableString ReplaceSubstring(ConversionStorage/* MatchData match = MatchForReplacement(scope, regex, self); if (!match.HasNamedGroup(groupName)) { - throw RubyExceptions.CreateIndexError("undefined group name reference: {0}", groupName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("undefined group name reference: {0}", groupName)); } if (!match.NamedGroupSuccess(groupName)) { - throw RubyExceptions.CreateIndexError("regexp group {0} not matched", groupName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("regexp group {0} not matched", groupName)); } var replacement = value as MutableString ?? Protocols.CastToString(stringCast, value); @@ -1668,7 +1668,7 @@ private static MutableString ReplaceSubstring(ConversionStorage/* MatchData match = RegexpOps.Match(scope, regex, self); scope.GetInnerMostClosureScope().CurrentMatch = match; if (match == null) { - throw RubyExceptions.CreateIndexError("regexp not matched"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("regexp not matched")); } return match; } @@ -1682,7 +1682,7 @@ public static MutableString ReplaceSubstring(ConversionStorage/*! MatchData match = MatchForReplacement(scope, regex, self); if (groupIndex <= -match.GroupCount || groupIndex >= match.GroupCount) { - throw RubyExceptions.CreateIndexError("index {0} out of regexp", groupIndex); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of regexp", groupIndex)); } if (groupIndex < 0) { @@ -1690,7 +1690,7 @@ public static MutableString ReplaceSubstring(ConversionStorage/*! } if (!match.GroupSuccess(groupIndex)) { - throw RubyExceptions.CreateIndexError("regexp group {0} not matched", groupIndex); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("regexp group {0} not matched", groupIndex)); } var replacement = value as MutableString ?? Protocols.CastToString(stringCast, value); @@ -1717,7 +1717,7 @@ private static CaseMappingOptions ParseCaseOptions(object[]/*!*/ options, bool f return CaseMappingOptions.None; } if (options.Length > 2) { - throw RubyExceptions.CreateArgumentError("too many options"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("too many options")); } CaseMappingOptions first, partner; @@ -1727,23 +1727,23 @@ private static CaseMappingOptions ParseCaseOptions(object[]/*!*/ options, bool f case "lithuanian": first = CaseMappingOptions.Lithuanian; partner = CaseMappingOptions.Turkic; break; case "fold": if (!foldingAllowed) { - throw RubyExceptions.CreateArgumentError("option :fold only allowed for downcasing"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("option :fold only allowed for downcasing")); } first = CaseMappingOptions.Fold; partner = CaseMappingOptions.None; break; default: - throw RubyExceptions.CreateArgumentError("invalid option"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid option")); } if (options.Length == 1) { return first; } if (partner == CaseMappingOptions.None) { - throw RubyExceptions.CreateArgumentError("too many options"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("too many options")); } if (OptionName(options[1]) != (partner == CaseMappingOptions.Turkic ? "turkic" : "lithuanian")) { - throw RubyExceptions.CreateArgumentError("invalid second option"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid second option")); } return first | partner; } @@ -1804,7 +1804,7 @@ private static void RequireCaseMappable(MutableString/*!*/ self, CaseMappingOpti } if ((flags & CaseMappingOptions.Ascii) == 0 && !ReferenceEquals(self.Encoding, RubyEncoding.Binary) && self.ContainsInvalidCharacters()) { - throw RubyExceptions.CreateArgumentError("input string invalid"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("input string invalid")); } } @@ -2015,7 +2015,7 @@ public static object CasecmpQ(ConversionStorage/*!*/ stringTryCas } // MRI folds both with String#downcase(:fold), which refuses a broken string if (self.ContainsInvalidCharacters() || str.ContainsInvalidCharacters()) { - throw RubyExceptions.CreateArgumentError("input string invalid"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("input string invalid")); } return ScriptingRuntimeHelpers.BooleanToObject(FoldForComparison(self) == FoldForComparison(str)); } @@ -2104,7 +2104,7 @@ private static int JustifyCount(MutableString/*!*/ self, int width, MutableStrin if (padding != _DefaultPadding) { self.RequireCompatibleEncoding(padding); if (padding.IsEmpty) { - throw RubyExceptions.CreateArgumentError("zero width padding"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("zero width padding")); } } return width - GetCharacterLength(self); @@ -2777,7 +2777,7 @@ public static object EachChar([NotNull]BlockParam/*!*/ block, MutableString/*!*/ var enumerator = self.GetCharacters(); while (enumerator.MoveNext()) { if (!enumerator.Current.IsValid) { - throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", self.Encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", self.Encoding.Name)); } result.Add(CodeToObject(NativeCode(self.Encoding, enumerator.Current))); } @@ -2799,7 +2799,7 @@ public static object EachCodePoint([NotNull]BlockParam/*!*/ block, MutableString var enumerator = self.GetCharacters(); while (enumerator.MoveNext()) { if (!enumerator.Current.IsValid) { - throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", encoding.Name)); } object result; @@ -3236,8 +3236,8 @@ internal static TranscodeSettings Parse(RubyContext/*!*/ context, // MRI's rb_econv_prepare_options refuses a broken replacement up // front, whether or not anything will need replacing if (result.Replacement != null && result.Replacement.ContainsInvalidCharacters()) { - throw RubyExceptions.CreateArgumentError("replacement string is broken: {0} as {1}", - context.Inspect(result.Replacement).ToString(), result.Replacement.Encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("replacement string is broken: {0} as {1}", + context.Inspect(result.Replacement).ToString(), result.Replacement.Encoding.Name)); } break; @@ -3252,8 +3252,8 @@ internal static TranscodeSettings Parse(RubyContext/*!*/ context, } else if (xml != null && xml.ToString() == "attr") { result.XmlMode = 'a'; } else { - throw RubyExceptions.CreateArgumentError("unexpected value for xml option: {0}", - xml != null ? (object)xml.ToString() : context.Inspect(entry.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected value for xml option: {0}", + xml != null ? (object)xml.ToString() : context.Inspect(entry.Value))); } // :xml implies escaping anything the target cannot hold. result.ReplaceUndefined = true; @@ -3271,8 +3271,8 @@ internal static TranscodeSettings Parse(RubyContext/*!*/ context, } else if (nlName == "lf") { result.Newline = 'l'; } else { - throw RubyExceptions.CreateArgumentError("unexpected value for newline option: {0}", - (object)nlName ?? context.Inspect(entry.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected value for newline option: {0}", + (object)nlName ?? context.Inspect(entry.Value))); } break; @@ -3310,7 +3310,7 @@ private static bool CheckReplaceOption(object value, string/*!*/ name) { if (symbol != null && symbol.ToString() == "replace") { return true; } - throw RubyExceptions.CreateArgumentError("unknown value for {0} character option", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown value for {0} character option", name)); } } @@ -3431,7 +3431,7 @@ private static void TranscodeByCharacter( string replacementText = substitute.ConvertToString(); // The substitute has to fit in the target encoding too. if (!CanEncode(encoder, replacementText.ToCharArray(), replacementText.Length)) { - throw RubyExceptions.CreateArgumentError("too big fallback string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("too big fallback string")); } result.Append(replacementText); continue; @@ -3540,7 +3540,7 @@ private static void TranscodeByCharacter( byte[] errorBytes = (e.BytesUnknown != null && e.BytesUnknown.Length > 0) ? e.BytesUnknown : new byte[] { bytes[Math.Min(Math.Max(e.Index, 0), bytes.Length - 1)] }; - throw RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, null, false); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, null, false)); } } } @@ -3578,8 +3578,8 @@ private static void TranscodeByCharacter( pending = 0; decoder = strict.GetDecoder(); if (!settings.ReplaceUndefined) { - throw RubyExceptions.CreateUndefinedConversionError( - RubyExceptions.InspectTranscodingBytes(character), character, RubyExceptions.ConversionPath(from, to), 0); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedConversionError( + RubyExceptions.InspectTranscodingBytes(character), character, RubyExceptions.ConversionPath(from, to), 0)); } result.Append(settings.GetReplacement(from, to).ConvertToString()); continue; @@ -3602,7 +3602,7 @@ private static void TranscodeByCharacter( if (replacement == null) { - throw RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, readAgain, false); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, readAgain, false)); } result.Append(replacement); continue; @@ -3621,7 +3621,7 @@ private static void TranscodeByCharacter( var errorBytes = new byte[pending]; Array.Copy(bytes, bytes.Length - pending, errorBytes, 0, pending); if (replacement == null) { - throw RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, null, true); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, null, true)); } result.Append(replacement); } @@ -3698,7 +3698,7 @@ private static void TranscodeByCharacter( errorBytes = new byte[length]; Array.Copy(bytes, i, errorBytes, 0, length); if (replacement == null) { - throw RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, readAgain, incomplete); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, readAgain, incomplete)); } result.Append(replacement); i += length; @@ -4064,12 +4064,12 @@ private static bool TryAppendNamedGroup(MatchData/*!*/ match, MutableString/*!*/ // rb_reg_regsub: a "\k<" with no closing ">" is a malformed reference, and an empty // name is one the pattern does not have if (end >= replacement.Length) { - throw RubyExceptions.CreateRuntimeError("invalid group name reference format"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("invalid group name reference format")); } string name = replacement.GetSlice(start, end - start).ConvertToString(); if (!match.HasNamedGroup(name)) { - throw RubyExceptions.CreateIndexError("undefined group name reference: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("undefined group name reference: {0}", name)); } var value = match.GetNamedGroupValue(name); @@ -4399,7 +4399,7 @@ public static object ReplaceAllInPlace(ConversionStorage/*!*/ tos } MutableString str = Protocols.TryCastToString(stringTryCast, pattern); if (str == null) { - throw RubyExceptions.CreateUnexpectedTypeError(stringTryCast.Context, pattern, "Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(stringTryCast.Context, pattern, "Regexp")); } return RubyRegex.FromLiteralPattern(str); } @@ -4627,7 +4627,7 @@ private static bool TryByteSearch(MutableString/*!*/ self, object[]/*!*/ args, b } clrOffset = chars.Length; } else if (clrOffset < 0) { - throw RubyExceptions.CreateIndexError("offset {0} does not land on character boundary", offset); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("offset {0} does not land on character boundary", offset)); } } charOffset = self.ToCharacterIndex(clrOffset); @@ -4952,7 +4952,7 @@ private static MutableString InternalDelete(MutableString/*!*/ self, MutableStri /// private static void RequireValidEncoding(MutableString/*!*/ self) { if (self.ContainsInvalidCharacters()) { - throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", self.Encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", self.Encoding.Name)); } } @@ -4965,7 +4965,7 @@ private static void RequireValidEncoding(MutableString/*!*/ self) { return self.CreateDerived(); } if (strs.Length == 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)")); } return InternalDelete(self, strs, false) ?? self.CloneDerived(); } @@ -4977,7 +4977,7 @@ public static MutableString DeleteInPlace(MutableString/*!*/ self, return null; } if (strs.Length == 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)")); } MutableString result = InternalDelete(self, strs, true); if (result == null) { @@ -5022,7 +5022,7 @@ private static object InternalCount(MutableString/*!*/ self, MutableString[]/*!* public static object Count(RubyContext/*!*/ context, MutableString/*!*/ self, [DefaultProtocol, NotNullItems]params MutableString/*!*/[]/*!*/ strs) { if (strs.Length == 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 0, expected 1+)")); } return InternalCount(self, strs); } @@ -5092,8 +5092,8 @@ public static bool IsMatch(MutableString/*!*/ self, [NotNull]MutableString/*!*/ [RubyMethod("match?")] public static bool IsMatch(RubyContext/*!*/ context, MutableString/*!*/ self, object pattern, [DefaultProtocol, DefaultParameterValue(0)]int start) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Regexp)", - pattern == null ? "nil" : context.GetClassDisplayName(pattern)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Regexp)", + pattern == null ? "nil" : context.GetClassDisplayName(pattern))); } [RubyMethod("=~")] @@ -5103,7 +5103,7 @@ public static object Match(RubyScope/*!*/ scope, MutableString/*!*/ self, [NotNu [RubyMethod("=~")] public static object Match(MutableString/*!*/ self, [NotNull]MutableString/*!*/ str) { - throw RubyExceptions.CreateTypeError("type mismatch: String given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("type mismatch: String given")); } [RubyMethod("=~")] @@ -5158,7 +5158,7 @@ public static object Match(ConversionStorage/*!*/ stringTryCast, // a Regexp or a String. MutableString converted = (pattern is RubySymbol) ? null : Protocols.TryCastToString(stringTryCast, pattern); if (converted == null) { - throw RubyExceptions.CreateUnexpectedTypeError(scope.RubyContext, pattern, "Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(scope.RubyContext, pattern, "Regexp")); } return RegexpOps.Match(scope, block, new RubyRegex(converted, RubyRegexOptions.NONE), self, start); } @@ -5173,7 +5173,7 @@ public static object Match(CallSiteStorage/*!*/ stringCast, Con MutableString strSeparator = null; if (separator != null) { strSeparator = separator as MutableString ?? Protocols.TryCastToString(stringTryCast, separator) ?? - throw RubyExceptions.CreateUnexpectedTypeError(stringCast.Context, separator, "Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(stringCast.Context, separator, "Regexp")); } return YieldSplit(block, self, Split(stringCast, self, strSeparator, limit)); } @@ -6023,7 +6023,7 @@ private static object YieldSplit(BlockParam block, MutableString/*!*/ self, Ruby return blockResult; } if (self.GetByteCount() != length) { - throw RubyExceptions.CreateRuntimeError("string modified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("string modified")); } } @@ -6116,7 +6116,7 @@ private static void RequireStrippable(MutableString/*!*/ str, bool trimLeft, boo var characters = str.GetCharacters(); while (characters.MoveNext()) { if (!characters.Current.IsValid) { - throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", str.Encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", str.Encoding.Name)); } int c = characters.Current.Codepoint; if (c >= 0x80 || !IsStrippedCharacter((char)c)) { @@ -6654,7 +6654,7 @@ private static void AppendCodePoint(MutableString/*!*/ str, int c) { position++; int last = CodePointAt(spec, ref position); if (first > last) { - throw RubyExceptions.CreateArgumentError("invalid range in string transliteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid range in string transliteration")); } result.Add(first); result.Add(last); @@ -6899,10 +6899,10 @@ public static object Unpack(ConversionStorage/*!*/ fixnumCast, RubyContext/ return true; } if (self.GetByteCount() != length) { - throw RubyExceptions.CreateRuntimeError("string modified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("string modified")); } if (format.GetByteCount() != formatLength) { - throw RubyExceptions.CreateRuntimeError("format string modified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("format string modified")); } return false; }); @@ -6938,16 +6938,16 @@ private static int GetUnpackOffset(ConversionStorage/*!*/ fixnumCast, RubyC } else foreach (var entry in options) { var key = entry.Key as RubySymbol; if (key == null || key.ToString() != "offset") { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key))); } offset = Protocols.CastToFixnum(fixnumCast, entry.Value); } if (offset < 0) { - throw RubyExceptions.CreateArgumentError("offset can't be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("offset can't be negative")); } if (offset > self.GetByteCount()) { - throw RubyExceptions.CreateArgumentError("offset outside of string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("offset outside of string")); } return offset; } @@ -6969,7 +6969,7 @@ private static int GetUnpackOffset(ConversionStorage/*!*/ fixnumCast, RubyC byte[] key = self.ToByteArray(); if (Array.IndexOf(key, (byte)0) >= 0) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } byte[] saltBytes = salt.ToByteArray(); @@ -6978,7 +6978,7 @@ private static int GetUnpackOffset(ConversionStorage/*!*/ fixnumCast, RubyC saltLength = saltBytes.Length; } if (saltLength < 2) { - throw RubyExceptions.CreateArgumentError("salt too short (need >=2 bytes)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("salt too short (need >=2 bytes)")); } var keyArg = new byte[key.Length + 1]; @@ -6989,7 +6989,7 @@ private static int GetUnpackOffset(ConversionStorage/*!*/ fixnumCast, RubyC string hashed = Posix.Crypt(keyArg, saltArg); if (hashed == null) { - throw RubyExceptions.CreateEINVAL(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL()); } var result = MutableString.CreateAscii(hashed); result.ForceEncoding(RubyEncoding.Binary); @@ -7025,7 +7025,7 @@ public static object GetChecksum(MutableString/*!*/ self, [DefaultProtocol, Defa private static void RequireNoVersionChange(MutableString/*!*/ self, int changeCount) { if (self.ChangeCount != changeCount) { - throw RubyExceptions.CreateRuntimeError("string modified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("string modified")); } } } diff --git a/Src/Libraries/Builtins/ObjectSpace.cs b/Src/Libraries/Builtins/ObjectSpace.cs index b8489b5ec..0170863fd 100644 --- a/Src/Libraries/Builtins/ObjectSpace.cs +++ b/Src/Libraries/Builtins/ObjectSpace.cs @@ -207,11 +207,11 @@ public static object DefineFinalizer(RespondToStorage/*!*/ respondTo, BinaryOpSt var context = respondTo.Context; if (!Protocols.RespondTo(respondTo, finalizer, "call")) { - throw RubyExceptions.CreateArgumentError("finalizer should be callable (respond to :call)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("finalizer should be callable (respond to :call)")); } // an immediate - nil, true, a Symbol, a small Integer - is never collected if (obj == null || obj is bool || obj is RubySymbol || !RubyUtils.HasObjectState(obj)) { - throw RubyExceptions.CreateArgumentError("cannot define finalizer for {0}", context.GetClassDisplayName(obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cannot define finalizer for {0}", context.GetClassDisplayName(obj))); } if (context.IsObjectFrozen(obj)) { throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(context, obj)); @@ -303,14 +303,14 @@ public static object EachObject([NotNull]BlockParam/*!*/ block, RubyModule/*!*/ var objects = context.GetObjectSpaceObjects(); if (objects == null) { if (theModule == null || !OnlyModulesAreInstances(theModule)) { - throw RubyExceptions.CreateRuntimeError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError( "each_object only supported for modules and classes unless ObjectSpace is enabled (-X:ObjectSpace)" - ); + )); } } else if (theModule != null && !CanFindInstances(theModule)) { - throw RubyExceptions.CreateRuntimeError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError( "each_object only supported for modules, classes and objects of classes derived from Object or BasicObject" - ); + )); } int matches = 0; @@ -406,7 +406,7 @@ public static object IdToReference(RubyModule/*!*/ self, [DefaultProtocol]Intege } } - throw RubyExceptions.CreateRangeError(String.Format("\"{0}\" is not an id value", id.IsFixnum ? id.Fixnum.ToString() : id.Bignum.ToString())); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("\"{0}\" is not an id value", id.IsFixnum ? id.Fixnum.ToString() : id.Bignum.ToString()))); } // GC.start's keywords (full_mark:, immediate_sweep:) have no CLR counterpart and are ignored diff --git a/Src/Libraries/Builtins/PosixProcess.cs b/Src/Libraries/Builtins/PosixProcess.cs index 72c64573c..14b408d30 100644 --- a/Src/Libraries/Builtins/PosixProcess.cs +++ b/Src/Libraries/Builtins/PosixProcess.cs @@ -120,18 +120,18 @@ private static ulong ToRLimitValue(object value) { var big = (System.Numerics.BigInteger)value; if (big.Sign < 0) { if (big < Int64.MinValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long'")); } return unchecked((ulong)(long)big); } if (big > UInt64.MaxValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long'")); } return (ulong)big; } - throw RubyExceptions.CreateTypeError("no implicit conversion into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion into Integer")); } [RubyMethod("__getpgid__", RubyMethodAttributes.PublicSingleton)] diff --git a/Src/Libraries/Builtins/PosixSignals.cs b/Src/Libraries/Builtins/PosixSignals.cs index 3c4991a4e..148f697c6 100644 --- a/Src/Libraries/Builtins/PosixSignals.cs +++ b/Src/Libraries/Builtins/PosixSignals.cs @@ -82,9 +82,9 @@ internal static int ToNumber(RubyContext context, object signalId, bool forTrap) // Deliberately without #to_int: ruby/spec checks that an object which only // answers #to_int is rejected. The Ruby class name, not the CLR one - MRI says // "bad signal type Float", not "Double". - throw RubyExceptions.CreateArgumentError("bad signal type {0}", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("bad signal type {0}", context != null ? context.GetClassName(signalId) - : (signalId == null ? "NilClass" : signalId.GetType().Name)); + : (signalId == null ? "NilClass" : signalId.GetType().Name))); } // "-TERM" and "-SIGTERM" are the spelled-out forms of a negative signal number, @@ -92,7 +92,7 @@ internal static int ToNumber(RubyContext context, object signalId, bool forTrap) bool negated = name.StartsWith("-", StringComparison.Ordinal); if (negated) { if (forTrap) { - throw RubyExceptions.CreateArgumentError("negative signal name: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative signal name: {0}", name)); } name = name.Substring(1); } @@ -104,8 +104,8 @@ internal static int ToNumber(RubyContext context, object signalId, bool forTrap) int number; if (!_numbers.TryGetValue(bare, out number)) { - throw RubyExceptions.CreateArgumentError("unsupported signal '{0}'", - name.StartsWith("SIG", StringComparison.Ordinal) ? name : "SIG" + name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unsupported signal '{0}'", + name.StartsWith("SIG", StringComparison.Ordinal) ? name : "SIG" + name)); } return negated ? -number : number; } @@ -121,14 +121,14 @@ internal static int ToNumber(RubyContext context, object signalId, bool forTrap) private static void CheckTrapNumber(int number) { int maxSignal = RubyProcess.IsWindows ? 22 : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 31 : 64; if (number < 0 || number > maxSignal) { - throw RubyExceptions.CreateArgumentError("invalid signal number ({0})", number); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid signal number ({0})", number)); } if (ToName(number) != null) { return; } bool taken = RubyProcess.IsWindows ? (number == 6 || number == 21) : (number != 32 && number != 33); if (!taken) { - throw RubyExceptions.CreateEINVAL("SIG{0}", number); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("SIG{0}", number)); } } @@ -289,7 +289,7 @@ internal static int Kill(int pid, int signal) { int error = Marshal.GetLastWin32Error(); if (error == EINVAL) { - throw RubyExceptions.CreateArgumentError("invalid signal number ({0})", signal); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid signal number ({0})", signal)); } return -(error == 0 ? 1 : error); } @@ -352,11 +352,11 @@ internal static void CheckTrappable(int signal) { case 8: // FPE case 11: // SEGV case 26: // VTALRM - throw RubyExceptions.CreateArgumentError("can\'t trap reserved signal: SIG{0}", ToName(signal)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can\'t trap reserved signal: SIG{0}", ToName(signal))); case 9: // KILL case 19: // STOP - throw RubyExceptions.CreateEINVAL("SIG{0}", ToName(signal)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("SIG{0}", ToName(signal))); } } diff --git a/Src/Libraries/Builtins/PosixSpawn.cs b/Src/Libraries/Builtins/PosixSpawn.cs index a43580ce2..a840bfcce 100644 --- a/Src/Libraries/Builtins/PosixSpawn.cs +++ b/Src/Libraries/Builtins/PosixSpawn.cs @@ -287,7 +287,7 @@ private static RubyArray OrderActions(RubyContext context, RubyArray actions, bo spare = LowSpareDescriptor(source, used); } if (spare < 0) { - throw RubyExceptions.CreateErrno(context, LastErrno(), null); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, LastErrno(), null)); } } else { if (spare < 0) { @@ -801,7 +801,7 @@ public static int NativeDescriptor(RubyContext/*!*/ context, RubyModule/*!*/ sel int[] fds = new int[2]; int errno = CloseOnExecPipe(fds); if (errno != 0) { - throw RubyExceptions.CreateErrno(context, errno, null); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, errno, null)); } // Not a FileStream: a read that is already blocked has to be interruptible by a // close from another thread, which is what Ruby's IO#close promises. @@ -940,7 +940,7 @@ internal static int Adopt(RubyContext/*!*/ context, int descriptor, Stream/*!*/ int[] fds = new int[2]; int errno = CloseOnExecPipe(fds); if (errno != 0) { - throw RubyExceptions.CreateErrno(context, errno, null); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, errno, null)); } int pid; @@ -957,7 +957,7 @@ internal static int Adopt(RubyContext/*!*/ context, int descriptor, Stream/*!*/ pid = ToInt(SpawnPrimitive(context, null, file, argv, envp, redirected, null, false)); if (pid < 0) { - throw RubyExceptions.CreateENOENT(file.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(file.ToString())); } } catch { SysClose(fds[0]); diff --git a/Src/Libraries/Builtins/PrintOps.cs b/Src/Libraries/Builtins/PrintOps.cs index a092829a1..b718357c3 100644 --- a/Src/Libraries/Builtins/PrintOps.cs +++ b/Src/Libraries/Builtins/PrintOps.cs @@ -81,7 +81,7 @@ public static void Print(BinaryOpStorage/*!*/ writeStorage, object self, object [RubyMethod("putc")] public static object Putc(ConversionStorage/*!*/ fixnumCast, BinaryOpStorage/*!*/ writeStorage, object self, object c) { if (c == null) { - throw RubyExceptions.CreateImplicitConversionError("nil", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "Integer")); } int value = Protocols.CastToFixnum(fixnumCast, c); MutableString str = MutableString.CreateBinary(1).Append(unchecked((byte)value)); diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index 5505165d0..a3319117b 100644 --- a/Src/Libraries/Builtins/ProcOps.cs +++ b/Src/Libraries/Builtins/ProcOps.cs @@ -28,7 +28,7 @@ public static class ProcOps { [RubyConstructor] public static void Error(RubyClass/*!*/ self, params object[] args) { - throw RubyExceptions.CreateAllocatorUndefinedError(self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateAllocatorUndefinedError(self)); } #region ==, eql?, hash, dup, clone @@ -83,9 +83,9 @@ public static int GetArity(Proc/*!*/ self) { foreach (var entry in options) { var key = entry.Key as RubySymbol; if (key == null || key.ToString() != "lambda") { - throw RubyExceptions.CreateArgumentError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( String.Format(CultureInfo.InvariantCulture, "unknown keyword: {0}", - context.Inspect(entry.Key).ToString())); + context.Inspect(entry.Key).ToString()))); } // an explicit nil means "do not override", matching MRI if (entry.Value != null) { @@ -117,12 +117,12 @@ public static bool IsLambda(Proc/*!*/ self) { [RubyMethod("binding")] public static Binding/*!*/ GetLocalScope(Proc/*!*/ self) { if (self.IsIsolated) { - throw RubyExceptions.CreateArgumentError("Can't create Binding from isolated Proc"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Can't create Binding from isolated Proc")); } // a curried or composed proc has no Ruby scope of its own to hand out, nor does // Symbol#to_proc's, which MRI makes as a C level (ifunc) proc if (self.LocalScope.IsEmpty || self.SymbolName != null) { - throw RubyExceptions.CreateArgumentError("Can't create Binding from C level Proc"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Can't create Binding from C level Proc")); } // Method#to_proc makes a proc whose self is the method's receiver rather than the // scope's, and the binding reports that one @@ -399,7 +399,7 @@ private static void GetArgumentCountRange(Proc/*!*/ self, out int min, out int m private static void RequireCallable(RespondToStorage/*!*/ respondTo, object other) { if (!Protocols.RespondTo(respondTo, other, "call")) { - throw RubyExceptions.CreateTypeError("callable object is expected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("callable object is expected")); } } @@ -422,14 +422,14 @@ public static object CreateNew(CallSiteStorage 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0)", args.Length)); } return proc; } diff --git a/Src/Libraries/Builtins/RactorOps.cs b/Src/Libraries/Builtins/RactorOps.cs index 01e79998f..812f324f0 100644 --- a/Src/Libraries/Builtins/RactorOps.cs +++ b/Src/Libraries/Builtins/RactorOps.cs @@ -339,7 +339,7 @@ private void Terminate(object value, Exception exception) { } _terminated = true; _value = value; - _exception = exception; + _exception = RubyExceptionData.MarkKept(exception); foreach (var port in _openPorts) { port.Closed = true; } @@ -426,12 +426,12 @@ private void JoinFrom(RubyRactor/*!*/ current) { foreach (var entry in options) { var key = entry.Key as RubySymbol; if (key == null || key.ToString() != "name") { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key))); } if (entry.Value != null) { name = Protocols.CastToString(toStr, entry.Value); if (!name.Encoding.IsAsciiIdentity) { - throw RubyExceptions.CreateArgumentError("ASCII incompatible encoding ({0})", name.Encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("ASCII incompatible encoding ({0})", name.Encoding.Name)); } name = name.Clone(); name.Freeze(); @@ -441,7 +441,7 @@ private void JoinFrom(RubyRactor/*!*/ current) { } if (block == null) { - throw RubyExceptions.CreateArgumentError("must be called with a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("must be called with a block")); } var registry = GetRegistry(context); if (Volatile.Read(ref registry.Alive) == 1) { @@ -478,15 +478,15 @@ private void JoinFrom(RubyRactor/*!*/ current) { internal static void Isolate(Proc/*!*/ proc) { var names = proc.Dispatcher.OuterVariableNames; if (names != null && names.Length > 0) { - throw RubyExceptions.CreateArgumentError("{0}", - "can not isolate a Proc because it accesses outer variables (" + String.Join(", ", names) + ")."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("{0}", + "can not isolate a Proc because it accesses outer variables (" + String.Join(", ", names) + ").")); } proc.IsIsolated = true; } [RubyMethod("allocate", RubyMethodAttributes.PublicSingleton)] public static RubyRactor/*!*/ Allocate(RubyClass/*!*/ self) { - throw RubyExceptions.CreateTypeError("allocator undefined for Ractor"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("allocator undefined for Ractor")); } [RubyMethod("current", RubyMethodAttributes.PublicSingleton)] @@ -528,7 +528,7 @@ public static object Receive(RubyRactor/*!*/ self) { [RubyMethod("select", RubyMethodAttributes.PublicSingleton)] public static RubyArray/*!*/ Select(RubyClass/*!*/ self, params object[]/*!*/ sources) { if (sources.Length == 0) { - throw RubyExceptions.CreateArgumentError("specify at least one Ractor::Port or Ractor"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("specify at least one Ractor::Port or Ractor")); } var context = self.Context; @@ -545,7 +545,7 @@ public static object Receive(RubyRactor/*!*/ self) { ractor.AddMonitor(port); ports[i] = port; } else if ((ports[i] = sources[i] as RactorPort) == null) { - throw RubyExceptions.CreateArgumentError("should be Ractor::Port or Ractor"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("should be Ractor::Port or Ractor")); } ports[i].RequireReceiver(current); } @@ -653,7 +653,7 @@ public static MutableString GetName(RubyRactor/*!*/ self) { if (str != null) { return context.CreateSymbol(str); } - throw RubyExceptions.CreateTypeError("{0}", context.Inspect(key) + " is not a symbol nor a string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0}", context.Inspect(key) + " is not a symbol nor a string")); } private object GetLocal(RubySymbol/*!*/ key) { @@ -741,7 +741,7 @@ public static object MakeShareable(CloneStorage/*!*/ cloneStorage, AllocateStora foreach (var entry in options) { var key = entry.Key as RubySymbol; if (!options.IsKeywordArguments || key == null || key.ToString() != "copy") { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key))); } copy = RubyOps.IsTrue(entry.Value); } @@ -772,13 +772,13 @@ public static object MakeShareable(CloneStorage/*!*/ cloneStorage, AllocateStora foreach (var entry in options) { var key = entry.Key as RubySymbol; if (!options.IsKeywordArguments || key == null || key.ToString() != "self") { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", context.Inspect(entry.Key))); } procSelf = entry.Value; } } if (block == null) { - throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to create Proc object without a block")); } if (!Shareability.IsShareable(context, procSelf)) { // MRI formats it with #to_s @@ -921,7 +921,7 @@ internal void Send(CallSiteStorage 0) { - throw RubyExceptions.CreateArgumentError("{0}", - "can not " + operation + " because it accesses outer variables (" + String.Join(", ", assigned) + ")."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("{0}", + "can not " + operation + " because it accesses outer variables (" + String.Join(", ", assigned) + ").")); } var names = proc.Dispatcher.OuterVariableNames; if (names != null) { @@ -1302,7 +1302,7 @@ internal object Copy(object obj) { } // a copy is a clone, and MRI's rb_obj_clone has no allocator for these if (obj is Proc || obj is RubyMethod || obj is UnboundMethod || obj is Thread || obj is Binding) { - throw RubyExceptions.CreateTypeError("allocator undefined for {0}", _context.GetClassDisplayName(obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("allocator undefined for {0}", _context.GetClassDisplayName(obj))); } if (!structural && Shareability.IsNeverShareable(_context, obj)) { throw new RactorError(String.Format("can not copy {0} object.", _context.GetClassDisplayName(obj))); diff --git a/Src/Libraries/Builtins/RangeOps.cs b/Src/Libraries/Builtins/RangeOps.cs index 6777da4a9..2ac431817 100644 --- a/Src/Libraries/Builtins/RangeOps.cs +++ b/Src/Libraries/Builtins/RangeOps.cs @@ -86,7 +86,7 @@ public static object Reinitialize(BinaryOpStorage/*!*/ comparisonStorage, public static Range/*!*/ InitializeCopy(RubyContext/*!*/ context, Range/*!*/ self, object other) { var range = other as Range; if (range == null) { - throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("initialize_copy should take same class object")); } self.InitializeCopy(context, range); return self; @@ -111,7 +111,7 @@ public static object Begin([NotNull]Range/*!*/ self) { [RubyMethod("first")] public static object First([NotNull]Range/*!*/ self) { if (self.Begin == null) { - throw RubyExceptions.CreateRangeError("cannot get the first element of beginless range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("cannot get the first element of beginless range")); } return self.Begin; } @@ -137,7 +137,7 @@ public static object First(CallSiteStorage>/*!*/ s return (count.Sign <= 0) ? ScriptingRuntimeHelpers.Int32ToObject(0) : Protocols.Normalize(count); } } else if (begin == null) { - throw RubyExceptions.CreateTypeError("can't iterate from NilClass"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't iterate from NilClass")); } else if (begin is double) { - throw RubyExceptions.CreateTypeError("can't iterate from Float"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't iterate from Float")); } var site = slow.GetCallSite("__size__", 0); return site.Target(site, self); @@ -282,7 +282,7 @@ private static BigInteger ToBigInteger(object integer) { // MRI counts the arguments of #first, #last, #min and #max against a single count: "expected 1". [RubyMethod("first"), RubyMethod("last"), RubyMethod("min"), RubyMethod("max")] public static object CountArity([NotNull]Range/*!*/ self, object count, object extra, params object[]/*!*/ more) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1)", 2 + more.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1)", 2 + more.Length)); } /// @@ -598,8 +598,8 @@ public static bool Cover(ComparisonStorage/*!*/ comparisonStorage, UnaryOpStorag public static bool Overlap(ComparisonStorage/*!*/ comparisonStorage, [NotNull]Range/*!*/ self, object other) { var otherRange = other as Range; if (otherRange == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Range)", - comparisonStorage.Context.GetClassDisplayName(other)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Range)", + comparisonStorage.Context.GetClassDisplayName(other))); } return Overlap(comparisonStorage, self, otherRange); } @@ -735,8 +735,8 @@ private static MutableString TryCastToString(EachStorage/*!*/ storage, object va [RubyMethod("bsearch")] public static object BinarySearch(ConversionStorage/*!*/ fixnumCast, [NotNull]BlockParam/*!*/ block, Range/*!*/ self) { if (!(self.Begin is int || self.Begin == null) || !(self.End is int || self.End == null)) { - throw RubyExceptions.CreateTypeError("can't do binary search for {0}", - block.RubyContext.GetClassName(self.Begin ?? self.End)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't do binary search for {0}", + block.RubyContext.GetClassName(self.Begin ?? self.End))); } // long rather than int throughout: an endless range's upper bound starts at @@ -839,8 +839,8 @@ private static bool Probe(BlockParam/*!*/ block, long candidate, ref object sati } else if (result == null) { searchLower = false; } else { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (must be numeric, true, false or nil)", - block.RubyContext.GetClassName(result)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (must be numeric, true, false or nil)", + block.RubyContext.GetClassName(result))); } return true; } @@ -1217,10 +1217,10 @@ private static int RLess(ComparisonStorage/*!*/ storage, object a, object b) { /// private static void CheckStep(int step) { if (step == 0) { - throw RubyExceptions.CreateArgumentError("step can't be 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("step can't be 0")); } if (step < 0) { - throw RubyExceptions.CreateArgumentError("step can't be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("step can't be negative")); } } @@ -1230,12 +1230,12 @@ private static void CheckStep(int step) { private static void CheckStep(EachStorage/*!*/ storage, object step) { var equals = storage.EqualsSite; if (Protocols.IsTrue(equals.Target(equals, step, 0))) { - throw RubyExceptions.CreateArgumentError("step can't be 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("step can't be 0")); } var lessThan = storage.LessThanSite; if (RubyOps.IsTrue(lessThan.Target(lessThan, step, 0))) { - throw RubyExceptions.CreateArgumentError("step can't be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("step can't be negative")); } } @@ -1244,7 +1244,7 @@ private static void CheckStep(EachStorage/*!*/ storage, object step) { /// private static void CheckBegin(EachStorage/*!*/ storage, object begin) { if (!Protocols.RespondTo(storage.RespondToSite, storage.Context, begin, "succ")) { - throw RubyExceptions.CreateTypeError("can't iterate from {0}", storage.Context.GetClassDisplayName(begin)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't iterate from {0}", storage.Context.GetClassDisplayName(begin))); } } diff --git a/Src/Libraries/Builtins/RefinementOps.cs b/Src/Libraries/Builtins/RefinementOps.cs index 36c6587d8..10fce2446 100644 --- a/Src/Libraries/Builtins/RefinementOps.cs +++ b/Src/Libraries/Builtins/RefinementOps.cs @@ -64,12 +64,12 @@ public static RubyModule GetTarget(RubyModule/*!*/ self) { [RubyMethod("include")] public static RubyModule Include(RubyModule/*!*/ self, params object[]/*!*/ modules) { - throw RubyExceptions.CreateTypeError("Refinement#include has been removed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Refinement#include has been removed")); } [RubyMethod("prepend")] public static RubyModule Prepend(RubyModule/*!*/ self, params object[]/*!*/ modules) { - throw RubyExceptions.CreateTypeError("Refinement#prepend has been removed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Refinement#prepend has been removed")); } /// @@ -82,9 +82,9 @@ public static RubyModule Prepend(RubyModule/*!*/ self, params object[]/*!*/ modu foreach (object obj in modules) { RubyModule module = obj as RubyModule; if (module == null || module.IsClass) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Module)", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Module)", self.Context.GetClassDisplayName(obj) - ); + )); } } @@ -111,10 +111,10 @@ public static RubyModule Prepend(RubyModule/*!*/ self, params object[]/*!*/ modu // A refinement's methods have to be re-compiled against the refinement, so a method with // no Ruby body (a library or CLR member) cannot be imported at all. if (!(entry.Value is RubyMethodInfo)) { - throw RubyExceptions.CreateArgumentError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( "Can't import method which is not defined with Ruby code: {0}#{1}", module.GetDisplayName(self.Context, false).ToString(), entry.Key - ); + )); } } diff --git a/Src/Libraries/Builtins/RubyEncoder.cs b/Src/Libraries/Builtins/RubyEncoder.cs index cb5c138ab..2386a91c0 100644 --- a/Src/Libraries/Builtins/RubyEncoder.cs +++ b/Src/Libraries/Builtins/RubyEncoder.cs @@ -62,7 +62,7 @@ private static void WriteUtf8CodePoint(Stream/*!*/ stream, int codepoint) { // 200000 - 3FFFFFF 111110vv 10vvvvzz 10zzzzyy 10yyyyyy 10xxxxxx // 4000000 - 7FFFFFFF 1111110v 10vvvvuu 10uuuuzz 10zzzzyy 10yyyyxx 10xxxxxx if (codepoint < 0) { - throw RubyExceptions.CreateRangeError("pack(U): value out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("pack(U): value out of range")); } int count, mark; GetCodePointByteCount(codepoint, out count, out mark); @@ -103,19 +103,19 @@ private static int ReadUtf8CodePoint(MutableString/*!*/ data, ref int index) { count = 6; mask = 0x01; } else { - throw RubyExceptions.CreateArgumentError("malformed UTF-8 character"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("malformed UTF-8 character")); } int codepoint = b & mask; for (int i = 1; i < count; i++) { if (index >= length) { - throw RubyExceptions.CreateArgumentError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( "malformed UTF-8 character (expected {0} bytes, given {1} bytes)", count, i - ); + )); } b = data.GetByte(index++); if ((b & 0xc0) != 0x80) { - throw RubyExceptions.CreateArgumentError("malformed UTF-8 character"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("malformed UTF-8 character")); } codepoint = (codepoint << 6) | (b & 0x3f); @@ -125,7 +125,7 @@ private static int ReadUtf8CodePoint(MutableString/*!*/ data, ref int index) { int mark; GetCodePointByteCount(codepoint, out requiredCount, out mark); if (requiredCount != count) { - throw RubyExceptions.CreateArgumentError("redundant UTF-8 sequence"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("redundant UTF-8 sequence")); } return codepoint; } @@ -137,7 +137,7 @@ private static int ReadUtf8CodePoint(MutableString/*!*/ data, ref int index) { private static void WriteBer(Stream/*!*/ stream, IntegerValue value) { if (value.IsFixnum) { if (value.Fixnum < 0) { - throw RubyExceptions.CreateArgumentError("can't compress negative numbers"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't compress negative numbers")); } int f = value.Fixnum; bool write = false; @@ -152,7 +152,7 @@ private static void WriteBer(Stream/*!*/ stream, IntegerValue value) { } else { BigInteger bignum = value.Bignum; if (bignum.Sign < 0) { - throw RubyExceptions.CreateArgumentError("can't compress negative numbers"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't compress negative numbers")); } // not very efficient but good enough: @@ -369,7 +369,7 @@ public static void WriteBase64(Stream/*!*/ stream, MutableString/*!*/ str, int b int value = Base64Value(c); if (value < 0 || padding > 0) { - throw RubyExceptions.CreateArgumentError("invalid base64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid base64")); } buffer = (buffer << 6) | value; @@ -384,34 +384,34 @@ public static void WriteBase64(Stream/*!*/ stream, MutableString/*!*/ str, int b } if (consumed % 4 != 0) { - throw RubyExceptions.CreateArgumentError("invalid base64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid base64")); } switch (bits) { case 0: if (padding != 0) { - throw RubyExceptions.CreateArgumentError("invalid base64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid base64")); } break; case 12: // MRI's strict decoder also rejects a final character whose unused bits are set if (padding != 2 || (buffer & 0xf) != 0) { - throw RubyExceptions.CreateArgumentError("invalid base64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid base64")); } result.Append((byte)((buffer >> 4) & 0xff)); break; case 18: if (padding != 1 || (buffer & 0x3) != 0) { - throw RubyExceptions.CreateArgumentError("invalid base64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid base64")); } result.Append((byte)((buffer >> 10) & 0xff)); result.Append((byte)((buffer >> 2) & 0xff)); break; default: - throw RubyExceptions.CreateArgumentError("invalid base64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid base64")); } return result; @@ -902,7 +902,7 @@ private static void WriteSingle(ConversionStorage/*!*/ floatConversion, private static double ToPackFloat(ConversionStorage/*!*/ floatConversion, object value) { if (value is MutableString) { - throw RubyExceptions.CreateTypeError("can't convert String into Float"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert String into Float")); } // MRI's rb_to_float: only a Numeric is asked for to_f; anything else is "can't convert ToF into Float" (nil, true // and false by value) @@ -910,7 +910,7 @@ private static double ToPackFloat(ConversionStorage/*!*/ floatConversion var context = floatConversion.Context; if (!context.GetClassOf(value).IsSubclassOf(context.GetClass(typeof(Numeric)))) { string name = (value == null || value is bool) ? context.Inspect(value).ToString() : context.GetClassOf(value).GetNonSingletonClass().Name; - throw RubyExceptions.CreateTypeError("can't convert {0} into Float", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into Float", name)); } } double result = Protocols.CastToFloat(floatConversion, value); @@ -924,7 +924,7 @@ private static void WriteInteger(ConversionStorage/*!*/ integerCon for (int j = 0; j < count; j++) { object value = GetPackArg(self, i + j); if (value == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer")); } // a Fixnum, by far the most common, without the conversion site @@ -1040,7 +1040,7 @@ private static int NativeLongSize { private static void RequireModifiable(char directive, char modifier) { if (ModifiableTypes.IndexOf(directive) < 0) { - throw RubyExceptions.CreateArgumentError("'{0}' allowed only after types {1}", modifier, ModifiableTypes); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("'{0}' allowed only after types {1}", modifier, ModifiableTypes)); } } @@ -1156,7 +1156,7 @@ private static bool IsKnownDirective(char c) { for (int i = 0; i < format.Length; i++) { char c = format[i]; if (c == '%') { - throw RubyExceptions.CreateArgumentError("% is not supported"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("% is not supported")); } if (c == '#') { @@ -1187,7 +1187,7 @@ private static bool IsKnownDirective(char c) { if (modifier == '<' || modifier == '>') { RequireModifiable(c, modifier); if (order != Endianness.Native) { - throw RubyExceptions.CreateRangeError("Can't use both '<' and '>'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("Can't use both '<' and '>'")); } order = modifier == '<' ? Endianness.Little : Endianness.Big; } else if (modifier == '!' || modifier == '_') { @@ -1220,7 +1220,7 @@ private static bool IsKnownDirective(char c) { // an error, and one that fits a long but not an int cannot be satisfied anyway. long longCount; if (!Int64.TryParse(format.Substring(pos1, (i - pos1)), NumberStyles.None, CultureInfo.InvariantCulture, out longCount)) { - throw RubyExceptions.CreateRangeError("pack length too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("pack length too big")); } count = (int)Math.Min(longCount, Int32.MaxValue); i--; @@ -1302,7 +1302,7 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { // MRI's pack_pack checks, before each directive, that a conversion (#to_int, // #to_str) has not resized the format it is reading. if (format.GetByteCount() != formatLength) { - throw RubyExceptions.CreateRuntimeError("format string modified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("format string modified")); } int count = directive.Count ?? self.Count - i; @@ -1430,7 +1430,7 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { case 'm': // Base64 if (GetPackArg(self, i) == null) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } WriteBase64(stream, ToMutableString(stringCast, GetPackArg(self, i)), // count 0 means a single unbroken line; 1 and 2 fall back to the default 45 @@ -1452,7 +1452,7 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { case 'u': // UU-encoded if (GetPackArg(self, i) == null) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } RubyEncoder.EncodeUU(ToMutableString(stringCast, GetPackArg(self, i)).ToByteArray(), (directive.Count.HasValue && directive.Count.Value > 2) ? directive.Count.Value : 45, @@ -1478,10 +1478,10 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { } else { // MRI converts to long first, so a value that does not even fit // there is reported as a conversion failure, not a bad code point. - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } if (scalar < 0 || scalar > 0x7fffffff) { - throw RubyExceptions.CreateRangeError("pack(U): value out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("pack(U): value out of range")); } RubyEncoder.WriteUtf8CodePoint(stream, (int)scalar); } @@ -1491,7 +1491,7 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { count = 0; int len3 = directive.Count.HasValue ? directive.Count.Value : 0; if (len3 > stream.Position) { - throw RubyExceptions.CreateArgumentError("X outside of string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("X outside of string")); } stream.String.Write((int)stream.Position - len3, 0, len3); stream.Position -= len3; @@ -1517,8 +1517,8 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { if (target != null && directive.Directive == 'P') { int needed = directive.Count ?? 1; if (target.GetByteCount() < needed) { - throw RubyExceptions.CreateArgumentError( - "too short buffer for P({0} for {1})", target.GetByteCount(), needed); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + "too short buffer for P({0} for {1})", target.GetByteCount(), needed)); } } if (target != null) { @@ -1550,7 +1550,7 @@ internal void ThrowIfInvalid(string/*!*/ format, bool packing) { // The directive MRI cannot read is reached through the same check as the others, // so a format a conversion has resized fails on that first. if (parsed.IsInvalid && format.GetByteCount() != formatLength) { - throw RubyExceptions.CreateRuntimeError("format string modified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("format string modified")); } parsed.ThrowIfInvalid(formatString, true); stream.SetLength(stream.Position); @@ -1611,7 +1611,7 @@ private static object Dereference(RubyContext/*!*/ context, MutableString/*!*/ s } } if (target == null) { - throw RubyExceptions.CreateArgumentError("no associated pointer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no associated pointer")); } if (directive.Directive == 'p') { @@ -1631,7 +1631,7 @@ private static MutableString ToMutableString(ConversionStorage/*! private static object GetPackArg(RubyArray/*!*/ array, int index) { if (index >= array.Count) { - throw RubyExceptions.CreateArgumentError("too few arguments"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("too few arguments")); } return array[index]; } @@ -1731,7 +1731,7 @@ void Push(object value) { case '@': if (directive.Count.HasValue) { if (directive.Count.Value > length) { - throw RubyExceptions.CreateArgumentError("@ outside of string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("@ outside of string")); } position = directive.Count.Value > 0 ? directive.Count.Value : 0; } else { @@ -1943,7 +1943,7 @@ void Push(object value) { case 'X': int len3 = directive.Count.HasValue ? directive.Count.Value : (int)(length - position); if (len3 > position) { - throw RubyExceptions.CreateArgumentError("X outside of string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("X outside of string")); } position -= len3; break; @@ -1951,7 +1951,7 @@ void Push(object value) { case 'x': int newPos = directive.Count.HasValue ? (int)position + directive.Count.Value : (int)length; if (newPos > length) { - throw RubyExceptions.CreateArgumentError("x outside of string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("x outside of string")); } position = newPos; break; diff --git a/Src/Libraries/Builtins/RubyEncodingOps.cs b/Src/Libraries/Builtins/RubyEncodingOps.cs index d911549e7..d606e71e4 100644 --- a/Src/Libraries/Builtins/RubyEncodingOps.cs +++ b/Src/Libraries/Builtins/RubyEncodingOps.cs @@ -292,7 +292,7 @@ public static bool IsAsciiCompatible(RubyEncoding/*!*/ self) { [RubyMethod("find", RubyMethodAttributes.PublicSingleton)] public static RubyEncoding GetEncoding(RubyClass/*!*/ self, DynamicNull name) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } // An Encoding is a constant of the runtime: there is nothing in it to change. @@ -304,7 +304,7 @@ public static bool IsFrozen(RubyEncoding/*!*/ self) { // A Symbol is not a name here: MRI takes only a String or something with #to_str. [RubyMethod("find", RubyMethodAttributes.PublicSingleton)] public static RubyEncoding/*!*/ GetEncoding(RubyClass/*!*/ self, [NotNull]RubySymbol/*!*/ name) { - throw RubyExceptions.CreateTypeError("no implicit conversion of Symbol into String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of Symbol into String")); } [RubyMethod("find", RubyMethodAttributes.PublicSingleton)] @@ -424,7 +424,7 @@ public static RubyEncoding GetCompatible(RubyClass/*!*/ self, object obj1, objec [RubyMethod("default_external=", RubyMethodAttributes.PublicSingleton)] public static RubyEncoding/*!*/ SetDefaultExternalEncoding(RubyClass/*!*/ self, RubyEncoding encoding) { if (encoding == null) { - throw RubyExceptions.CreateArgumentError("default external can not be nil"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("default external can not be nil")); } var old = self.Context.DefaultExternalEncoding; self.Context.DefaultExternalEncoding = encoding; diff --git a/Src/Libraries/Builtins/RubyPipe.cs b/Src/Libraries/Builtins/RubyPipe.cs index 12a029faa..cba645832 100644 --- a/Src/Libraries/Builtins/RubyPipe.cs +++ b/Src/Libraries/Builtins/RubyPipe.cs @@ -274,7 +274,7 @@ public override int Read(byte[] buffer, int offset, int count) { throw new TimeoutException(); } if (signaled == ReaderClosedEventIndex) { - throw RubyExceptions.CreateIOError("stream closed in another thread"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("stream closed in another thread")); } } } diff --git a/Src/Libraries/Builtins/RubyProcess.cs b/Src/Libraries/Builtins/RubyProcess.cs index 4ea04b1f5..a9b914ad8 100644 --- a/Src/Libraries/Builtins/RubyProcess.cs +++ b/Src/Libraries/Builtins/RubyProcess.cs @@ -46,7 +46,7 @@ public static partial class RubyProcess { context.ChildProcessExitStatus = new RubyProcess.Status(p); return p; } catch (Exception e) { - throw RubyExceptions.CreateENOENT(psi.FileName, e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(psi.FileName, e)); } } @@ -85,7 +85,7 @@ private static bool IsUnixPlatform { try { p.Start(); } catch (Exception e) { - throw RubyExceptions.CreateENOENT(p.StartInfo.FileName, e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(p.StartInfo.FileName, e)); } context.ChildProcessExitStatus = new RubyProcess.Status(p); @@ -95,7 +95,7 @@ private static bool IsUnixPlatform { private static void GetExecutable(PlatformAdaptationLayer/*!*/ pal, string/*!*/ command, out string executable, out string arguments) { command = command.Trim(' '); if (command.Length == 0) { - throw RubyExceptions.CreateEINVAL(command); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL(command)); } // This seems to be quite complicated: @@ -160,12 +160,12 @@ private static void GetExecutable(PlatformAdaptationLayer/*!*/ pal, string/*!*/ } } catch (Exception e) { if (next < 0) { - throw RubyExceptions.CreateENOENT(command, e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(command, e)); } } if (next < 0) { - throw RubyExceptions.CreateENOENT(command); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(command)); } start = next + 1; @@ -705,11 +705,11 @@ public static object ClockGetTime(ConversionStorage/*!*/ fixnumCast, Conver var symbol = clockId as RubySymbol; if (symbol != null) { if (!_emulatedClocks.TryGetValue(symbol.ToString(), out kind)) { - throw RubyExceptions.CreateEINVAL("clock_gettime({0})", context.Inspect(clockId)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("clock_gettime({0})", context.Inspect(clockId))); } } else if (clockId == null) { // NUM2CLOCKID's wording, not to_int's - throw RubyExceptions.CreateTypeError("no implicit conversion from nil to integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion from nil to integer")); } else { switch (Protocols.CastToFixnum(fixnumCast, clockId)) { case CLOCK_REALTIME: case CLOCK_REALTIME_COARSE: case CLOCK_REALTIME_ALARM: case CLOCK_TAI: @@ -725,7 +725,7 @@ public static object ClockGetTime(ConversionStorage/*!*/ fixnumCast, Conver kind = ClockKind.ThreadTime; break; default: - throw RubyExceptions.CreateEINVAL("clock_gettime({0})", context.Inspect(clockId)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("clock_gettime({0})", context.Inspect(clockId))); } } @@ -759,7 +759,7 @@ public static object ClockGetTime(ConversionStorage/*!*/ fixnumCast, Conver case "microsecond": return ClrFloat.ToInt(seconds * 1000000); case "nanosecond": return ClrFloat.ToInt(seconds * 1000000000); default: - throw RubyExceptions.CreateArgumentError("unexpected unit: " + Protocols.ConvertToString(tosConversion, unit).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected unit: " + Protocols.ConvertToString(tosConversion, unit).ToString())); } } @@ -775,7 +775,7 @@ private static object ConvertClockTime(ConversionStorage/*!*/ tos case "microsecond": return Protocols.Normalize(nanoseconds / 1000); case "nanosecond": return Protocols.Normalize(nanoseconds); default: - throw RubyExceptions.CreateArgumentError("unexpected unit: " + Protocols.ConvertToString(tosConversion, unit).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected unit: " + Protocols.ConvertToString(tosConversion, unit).ToString())); } } diff --git a/Src/Libraries/Builtins/RubyRegexOps.cs b/Src/Libraries/Builtins/RubyRegexOps.cs index 01f3c4a7d..b0e4ad4b2 100644 --- a/Src/Libraries/Builtins/RubyRegexOps.cs +++ b/Src/Libraries/Builtins/RubyRegexOps.cs @@ -109,7 +109,7 @@ internal static bool NormalizeGroupIndex(ref int index, int groupCount) { [RubyConstructor] public static RubyRegex/*!*/ Create(RubyClass/*!*/ self, DynamicNull pattern, [Optional]object options, [Keywords, Optional]object keywords) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } [RubyMethod("compile", RubyMethodAttributes.PublicSingleton)] @@ -123,7 +123,7 @@ internal static bool NormalizeGroupIndex(ref int index, int groupCount) { /// private static void RequireInitialized(RubyRegex/*!*/ self) { if (!self.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Regexp")); } } @@ -165,12 +165,12 @@ public static object SetGlobalTimeout(RubyClass/*!*/ self, object value) { } else if (value is BigInteger) { seconds = Protocols.ConvertToDouble(context, (BigInteger)value); } else { - throw RubyExceptions.CreateTypeError("no implicit conversion to float from {0}", - context.GetClassDisplayName(value).ToLowerInvariant()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion to float from {0}", + context.GetClassDisplayName(value).ToLowerInvariant())); } if (Double.IsNaN(seconds) || seconds <= 0) { - throw RubyExceptions.CreateArgumentError("invalid timeout: {0}", context.Inspect(value).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid timeout: {0}", context.Inspect(value).ToString())); } return seconds; } @@ -202,7 +202,7 @@ public static object SetGlobalTimeout(RubyClass/*!*/ self, object value) { } } if (unknown.Count > 0) { - throw RubyExceptions.CreateArgumentError("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", unknown)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", unknown))); } return ToTimeout(context, timeout); @@ -218,7 +218,7 @@ private static void RequireUninitialized(RubyContext/*!*/ context, RubyRegex/*!* } if (self.IsInitialized) { - throw RubyExceptions.CreateTypeError("already initialized regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("already initialized regexp")); } } @@ -307,7 +307,7 @@ private static RubyRegexOptions ParseOptionString(MutableString/*!*/ flags) { case 'm': result |= RubyRegexOptions.Multiline; break; case 'x': result |= RubyRegexOptions.Extended; break; default: - throw RubyExceptions.CreateArgumentError("unknown regexp option: {0}", flags.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown regexp option: {0}", flags.ToString())); } } @@ -431,7 +431,7 @@ internal static RubyRegexOptions StringToRegexEncoding(MutableString encoding) { [RubyMethod("options")] public static int GetOptions(RubyRegex/*!*/ self) { if (!self.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Regexp")); } // FIXEDENCODING is set on any regexp whose encoding is pinned, by a modifier or by its // source: /\u3042/, /\xc2\xa1/n and /\p{L}/ have it as much as /x/u. @@ -507,7 +507,7 @@ public static object Match(RubyScope/*!*/ scope, [Optional]BlockParam block, Rub [DefaultProtocol]MutableString str, [DefaultProtocol, DefaultParameterValue(0)]int start) { if (!self.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Regexp")); } MatchData match; @@ -543,7 +543,7 @@ public static object Match(RubyScope/*!*/ scope, [Optional]BlockParam block, Rub [RubyMethod("match?")] public static bool IsMatch(RubyRegex/*!*/ self, [DefaultProtocol]MutableString str, [DefaultProtocol, DefaultParameterValue(0)]int start) { if (!self.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Regexp")); } if (str == null) { return false; @@ -674,9 +674,9 @@ public static RubyRegex TryConvert(RespondToStorage/*!*/ respondToStorage, Unary regex = result as RubyRegex; if (regex == null) { var context = respondToStorage.Context; - throw RubyExceptions.CreateTypeError("can't convert {0} to Regexp ({0}#to_regexp gives {1})", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to Regexp ({0}#to_regexp gives {1})", context.GetClassDisplayName(obj), context.GetClassDisplayName(result) - ); + )); } return regex; @@ -724,7 +724,7 @@ public static MutableString LastMatch(ConversionStorage/*!*/ fixnumCast, Ru string name = GroupName(groupIndex); if (name != null) { if (!match.HasNamedGroup(name)) { - throw RubyExceptions.CreateIndexError("undefined group name reference: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("undefined group name reference: {0}", name)); } return match.GetNamedGroupValue(name); } @@ -903,7 +903,7 @@ private static string GroupName(object groupIndex) { if (incompatible != null) { if (hasAsciiOnlyPart) { - throw RubyExceptions.CreateArgumentError("ASCII incompatible encoding: {0}", incompatible.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("ASCII incompatible encoding: {0}", incompatible.Name)); } if (compatibleFixed != null) { throw IncompatibleEncodings(incompatible, compatibleFixed); @@ -911,7 +911,7 @@ private static string GroupName(object groupIndex) { } if (sourceEncoding != null && sourceEncoding != textEncoding && !sourceIsAscii && !textIsAscii) { - throw RubyExceptions.CreateEncodingCompatibilityError(sourceEncoding, textEncoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEncodingCompatibilityError(sourceEncoding, textEncoding)); } if (sourceEncoding == null || sourceIsAscii && !textIsAscii) { sourceEncoding = textEncoding; diff --git a/Src/Libraries/Builtins/RubyTime.cs b/Src/Libraries/Builtins/RubyTime.cs index 082047383..3101235ad 100644 --- a/Src/Libraries/Builtins/RubyTime.cs +++ b/Src/Libraries/Builtins/RubyTime.cs @@ -248,8 +248,8 @@ private void ResolveLocalZone() { // the arithmetic on them. MRI keeps a bignum and has no such limit. private static long ClampSeconds(BigInteger value) { if (value > new BigInteger(Int64.MaxValue / 2) || value < new BigInteger(Int64.MinValue / 2)) { - throw RubyExceptions.CreateRangeError(String.Format(System.Globalization.CultureInfo.InvariantCulture, - "time {0} out of Time range", value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format(System.Globalization.CultureInfo.InvariantCulture, + "time {0} out of Time range", value))); } return (long)value; } diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index e12b48f1f..a13fd3adc 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -102,7 +102,7 @@ private static BigInteger ToBigInteger(object value) { if (value is double) { return new BigInteger((double)value); } - throw RubyExceptions.CreateTypeError("can't convert to an exact number"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert to an exact number")); } private static bool TryToExactSimple(object value, out ExactNum result) { @@ -214,11 +214,11 @@ private static int ToInt32(object value) { private static int ToInt32(BigInteger value) { // rb_num2int goes through rb_num2long, which has its own message for a Bignum if (value > Int64.MaxValue || value < Int64.MinValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } if (value > Int32.MaxValue || value < Int32.MinValue) { - throw RubyExceptions.CreateRangeError(String.Format(CultureInfo.InvariantCulture, - "integer {0} too {1} to convert to 'int'", value, value.Sign < 0 ? "small" : "big")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format(CultureInfo.InvariantCulture, + "integer {0} too {1} to convert to 'int'", value, value.Sign < 0 ? "small" : "big"))); } return (int)value; } @@ -252,14 +252,14 @@ private static bool TryParseOffsetString(RubyContext/*!*/ context, object value, } if (!str.IsAscii() && !str.Encoding.IsAsciiIdentity) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } string s; try { s = str.ConvertToString(); } catch (Exception) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } // MRI's utc_offset_arg compares "UTC" ignoring case (STRNCASECMP); "Z" has to be upper case. @@ -299,7 +299,7 @@ private static bool TryParseOffsetString(RubyContext/*!*/ context, object value, int sec = m.Groups["s"].Success ? Int32.Parse(m.Groups["s"].Value, CultureInfo.InvariantCulture) : 0; if (h > 23) { - throw RubyExceptions.CreateArgumentError("utc_offset out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("utc_offset out of range")); } if (min > 59 || sec > 59) { throw InvalidUtcOffset(s); @@ -324,7 +324,7 @@ private static Exception InvalidUtcOffset(string value) { private static void CheckOffsetRange(ExactNum offset) { if (offset.CompareTo(ExactNum.FromInteger(86400)) >= 0 || offset.CompareTo(ExactNum.FromInteger(-86400)) <= 0) { - throw RubyExceptions.CreateArgumentError("utc_offset out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("utc_offset out of range")); } } @@ -385,7 +385,7 @@ private static long ZoneResultToSeconds(RubyContext/*!*/ context, object value) if (value != null && RespondTo(context, value, "to_i")) { return (long)ToExact(context, Invoke(context, "to_i", value)).Floor(); } - throw RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(value))); } /// @@ -394,7 +394,7 @@ private static long ZoneResultToSeconds(RubyContext/*!*/ context, object value) /// private static RubyTime/*!*/ ApplyZoneObjectToInstant(RubyContext/*!*/ context, RubyTime/*!*/ instant, object/*!*/ zoneObject) { if (!RespondTo(context, zoneObject, "utc_to_local")) { - throw RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(zoneObject)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(zoneObject))); } var utcView = new RubyTime(instant.Seconds, ExactNum.Zero, RubyTimeZoneKind.Utc, ExactNum.Zero); @@ -407,7 +407,7 @@ private static long ZoneResultToSeconds(RubyContext/*!*/ context, object value) long offsetSeconds = localSeconds - instant.Seconds; if (offsetSeconds <= -86400 || offsetSeconds >= 86400) { - throw RubyExceptions.CreateArgumentError("utc_offset out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("utc_offset out of range")); } var result = instant.WithZone(RubyTimeZoneKind.FixedOffset, ExactNum.FromInteger(offsetSeconds), zoneObject); @@ -490,7 +490,7 @@ private static object GetInOption(IDictionary options, bool allo var symbol = key as RubySymbol; string name = symbol != null ? symbol.ToString() : null; if (name != "in" && !(allowPrecision && name == "precision")) { - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", symbol != null ? ":" + name : key.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", symbol != null ? ":" + name : key.ToString())); } } } @@ -560,7 +560,7 @@ private static object GetInOption(IDictionary options, bool allo private static void RequireUninitialized(RubyContext/*!*/ context, RubyTime/*!*/ self) { if (self.IsInitialized) { - throw RubyExceptions.CreateTypeError("already initialized {0}", context.GetClassOf(self).Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("already initialized {0}", context.GetClassOf(self).Name)); } } @@ -594,15 +594,15 @@ private static void RequireUninitialized(RubyContext/*!*/ context, RubyTime/*!*/ } if (args.Length > 7) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..7)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..7)", args.Length)); } if (args[0] == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer")); } if (args.Length == 7 && inZone != null) { - throw RubyExceptions.CreateArgumentError("timezone argument given as positional and keyword arguments"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("timezone argument given as positional and keyword arguments")); } object zone = (args.Length == 7) ? args[6] : inZone; @@ -638,7 +638,7 @@ private static void RequireUninitialized(RubyContext/*!*/ context, RubyTime/*!*/ object inZone, IDictionary options) { if (!str.Encoding.IsAsciiIdentity) { - throw RubyExceptions.CreateArgumentError("time string should have ASCII compatible encoding"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time string should have ASCII compatible encoding")); } // MRI's time_init_parse converts precision: before it reads the string, which the @@ -650,7 +650,7 @@ private static void RequireUninitialized(RubyContext/*!*/ context, RubyTime/*!*/ if (precisionValue == null) { precision = -1; } else if (precisionValue is MutableString) { - throw RubyExceptions.CreateTypeError("no implicit conversion of String into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of String into Integer")); } else { precision = ToIntComponent(context, precisionValue); } @@ -703,10 +703,10 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s digits++; } if (digits == 0) { - throw RubyExceptions.CreateArgumentError("can't parse: {0}", context.Inspect(str).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't parse: {0}", context.Inspect(str).ToString())); } if (digits < 4) { - throw RubyExceptions.CreateArgumentError("year must be 4 or more digits: {0}", text.Substring(pos, digits)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("year must be 4 or more digits: {0}", text.Substring(pos, digits))); } year = ToInt32(BigInteger.Parse(text.Substring(pos, digits), CultureInfo.InvariantCulture)); pos += digits; @@ -724,12 +724,12 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s int timePart = pos + 1; hour = TwoDigits(text, ref pos, "hour"); if (pos < end && text[pos] == '.') { - throw RubyExceptions.CreateArgumentError("fraction hour is not supported: {0}", text.Substring(timePart, pos + 1 - timePart)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("fraction hour is not supported: {0}", text.Substring(timePart, pos + 1 - timePart))); } if (pos < end && text[pos] == ':') { minute = TwoDigits(text, ref pos, "min"); if (pos < end && text[pos] == '.') { - throw RubyExceptions.CreateArgumentError("fraction min is not supported: {0}", text.Substring(timePart, pos + 1 - timePart)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("fraction min is not supported: {0}", text.Substring(timePart, pos + 1 - timePart))); } if (pos < end && text[pos] == ':') { second = ExactNum.FromInteger(TwoDigits(text, ref pos, "sec")); @@ -741,17 +741,17 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s } if (pos == start) { int shown = Math.Min(end, pos + 1); - throw RubyExceptions.CreateArgumentError("subsecond expected after dot: {0}", text.Substring(timePart, shown - timePart)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("subsecond expected after dot: {0}", text.Substring(timePart, shown - timePart))); } fraction = text.Substring(start, pos - start); } } else { // MRI shows the time part up to and including the character that was // not the expected ':' - throw RubyExceptions.CreateArgumentError("missing sec part: {0}", text.Substring(timePart, Math.Min(end, pos + 1) - timePart)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("missing sec part: {0}", text.Substring(timePart, Math.Min(end, pos + 1) - timePart))); } } else { - throw RubyExceptions.CreateArgumentError("missing min part: {0}", text.Substring(timePart, Math.Min(end, pos + 1) - timePart)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("missing min part: {0}", text.Substring(timePart, Math.Min(end, pos + 1) - timePart))); } } } else { @@ -765,7 +765,7 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s } // whitespace has to introduce a zone; trailing whitespace alone is a parse error if (pos == end) { - throw RubyExceptions.CreateArgumentError("can't parse: {0}", context.Inspect(str).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't parse: {0}", context.Inspect(str).ToString())); } } if (pos < end) { @@ -778,13 +778,13 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s pos++; } if (pos < end) { - throw RubyExceptions.CreateArgumentError("can't parse at: {0}", text.Substring(pos)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't parse at: {0}", text.Substring(pos))); } } // a date without a time of day or a zone is not a Time if (!hasTime && zoneText == null) { - throw RubyExceptions.CreateArgumentError("no time information"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no time information")); } } @@ -802,7 +802,7 @@ private static int TwoDigits(string/*!*/ text, ref int pos, string/*!*/ name) { message += " after '" + separator + "'"; } int shown = Math.Min(len > 10 ? 10 : len, len) + 1; - throw RubyExceptions.CreateArgumentError(message + ": {0}", text.Substring(pos, Math.Min(shown, text.Length - pos))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(message + ": {0}", text.Substring(pos, Math.Min(shown, text.Length - pos)))); } pos = start + 2; return (text[start] - '0') * 10 + (text[start + 1] - '0'); @@ -849,32 +849,32 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { // (obj2ubits lets 0..15 through for the month, 0..31 for the day and the hour, // and the range check that follows names the field.) if (month < 1 || month > 12) { - throw RubyExceptions.CreateArgumentError((month >= 0 && month <= 15) ? "mon out of range" : "argument out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError((month >= 0 && month <= 15) ? "mon out of range" : "argument out of range")); } if (hour < 0 || hour > 24) { - throw RubyExceptions.CreateArgumentError((hour >= 25 && hour <= 31) ? "hour out of range" : "argument out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError((hour >= 25 && hour <= 31) ? "hour out of range" : "argument out of range")); } if (minute < 0 || minute > 59) { - throw RubyExceptions.CreateArgumentError((minute >= 60 && minute <= 63) ? "min out of range" : "argument out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError((minute >= 60 && minute <= 63) ? "min out of range" : "argument out of range")); } if (second.Sign < 0) { - throw RubyExceptions.CreateArgumentError("argument out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument out of range")); } if (second.CompareTo(ExactNum.FromInteger(61)) >= 0) { - throw RubyExceptions.CreateArgumentError( - second.CompareTo(ExactNum.FromInteger(64)) < 0 ? "sec out of range" : "argument out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + second.CompareTo(ExactNum.FromInteger(64)) < 0 ? "sec out of range" : "argument out of range")); } // A day beyond the end of the month rolls into the next one (Feb 31 == Mar 3), // but a day outside 1..31 is an error. if (day < 1 || day > 31) { - throw RubyExceptions.CreateArgumentError(day == 0 ? "mday out of range" : "argument out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(day == 0 ? "mday out of range" : "argument out of range")); } // 24:00:00 is the end of the day; anything past it is not a time of that day. if (hour == 24 && minute != 0) { - throw RubyExceptions.CreateArgumentError("min out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("min out of range")); } if (hour == 24 && second.Sign != 0) { - throw RubyExceptions.CreateArgumentError("sec out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("sec out of range")); } long wallSeconds; @@ -882,7 +882,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { wallSeconds = checked(RubyTime.DaysFromCivil(year, month, 1) * 86400 + (long)(day - 1) * 86400 + (long)hour * 3600 + (long)minute * 60); } catch (OverflowException) { - throw RubyExceptions.CreateArgumentError("argument out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument out of range")); } BigInteger wholeSecond = second.Floor(); @@ -919,7 +919,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { private static RubyTime/*!*/ ApplyTimezoneObject(RubyContext/*!*/ context, long wallSeconds, ExactNum fraction, object/*!*/ zoneObject) { // Hand the zone object a UTC "Time-like" value and let it map it to a real instant. if (!RespondTo(context, zoneObject, "local_to_utc")) { - throw RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(zoneObject)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(zoneObject))); } var asUtc = new RubyTime(wallSeconds, ExactNum.Zero, RubyTimeZoneKind.Utc, ExactNum.Zero); @@ -927,7 +927,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { long offsetSeconds = wallSeconds - utcSeconds; if (offsetSeconds <= -86400 || offsetSeconds >= 86400) { - throw RubyExceptions.CreateArgumentError("utc_offset out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("utc_offset out of range")); } var result = new RubyTime(utcSeconds, fraction, RubyTimeZoneKind.FixedOffset, ExactNum.FromInteger(offsetSeconds)); @@ -945,7 +945,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { object inZone = GetInOption(options); if (args.Length < 1 || args.Length > 3) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..3)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..3)", args.Length)); } ExactNum offset; @@ -962,7 +962,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { RubyTime other = args[0] as RubyTime; if (other != null && args.Length > 1) { - throw RubyExceptions.CreateTypeError("can't convert Time into an exact number"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert Time into an exact number")); } ExactNum seconds = (other != null) ? other.ToExactSeconds() : ToExact(context, args[0]); @@ -974,7 +974,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { if (args.Length == 3) { var unit = args[2] as RubySymbol; if (unit == null) { - throw RubyExceptions.CreateArgumentError("unexpected unit: {0}", context.Inspect(args[2]).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected unit: {0}", context.Inspect(args[2]).ToString())); } switch (unit.ToString()) { case "millisecond": unitDivisor = new BigInteger(1000); break; @@ -983,7 +983,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { case "nsec": case "nanosecond": unitDivisor = RubyTime.NanosecondsPerSecond; break; default: - throw RubyExceptions.CreateArgumentError("unexpected unit: {0}", context.Inspect(args[2]).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unexpected unit: {0}", context.Inspect(args[2]).ToString())); } } @@ -1016,7 +1016,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { public static RubyTime/*!*/ Now(RubyContext/*!*/ context, RubyClass/*!*/ self, [NotNull]params object[]/*!*/ args) { var options = ExtractOptions(ref args); if (args.Length != 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0)", args.Length)); } return Subclass(context, self, NowInternal(context, self, GetInOption(options))); } @@ -1049,7 +1049,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { Array.Reverse(newComponents); components = newComponents; } else if (components.Length > 8 || components.Length == 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..8)", components.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..8)", components.Length)); } int year = GetYear(context, components, 0); @@ -1064,7 +1064,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { if (components.Length == 7 && components[6] != null) { ExactNum usec = ToExactComponent(context, components[6]); if (usec.Sign < 0 || usec.CompareTo(ExactNum.FromInteger(RubyTime.MicrosecondsPerSecond)) >= 0) { - throw RubyExceptions.CreateArgumentError("subsecx out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("subsecx out of range")); } // An explicit microsecond argument supersedes any fraction of the seconds argument. second = ExactNum.FromInteger(second.Floor()) + usec / ExactNum.FromInteger(RubyTime.MicrosecondsPerSecond); @@ -1085,7 +1085,7 @@ private static int GetComponent(RubyContext/*!*/ context, object[]/*!*/ componen private static int GetYear(RubyContext/*!*/ context, object[]/*!*/ components, int index) { if (index >= components.Length || components[index] == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer")); } return ToIntComponent(context, components[index]); } @@ -1100,7 +1100,7 @@ private static int GetYear(RubyContext/*!*/ context, object[]/*!*/ components, i public static MutableString/*!*/ Dump(RubyContext/*!*/ context, RubyTime/*!*/ self, [Optional]int depth) { DateTime value = self.UtcDateTime; if (value.Year < 1900 || value.Year > 2038) { - throw RubyExceptions.CreateTypeError("unable to marshal time"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("unable to marshal time")); } // Little Endian @@ -1285,7 +1285,7 @@ private static ExactNum ReadSubmicro(RubyContext/*!*/ context, MutableString/*!* public static RubyTime/*!*/ Load(RubyContext/*!*/ context, RubyClass/*!*/ self, [NotNull]MutableString/*!*/ time) { byte[] data = time.ConvertToBytes(); if (data.Length != 8) { - throw RubyExceptions.CreateTypeError("marshaled time format differ"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("marshaled time format differ")); } uint dword1 = GetUint(data, 0); @@ -1351,7 +1351,7 @@ private static ExactNum ReadSubmicro(RubyContext/*!*/ context, MutableString/*!* instant = AssembleTime(context, year, month, day, hour, minute, seconds, RubyTimeZoneKind.Utc, ExactNum.Zero, null, false); } catch (Exception) { - throw RubyExceptions.CreateTypeError("marshaled time format differ"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("marshaled time format differ")); } return CopyExtraIVars(context, time, Subclass(context, self, @@ -1372,13 +1372,13 @@ private static ExactNum ReadSubmicro(RubyContext/*!*/ context, MutableString/*!* [RubyMethod("+")] public static RubyTime/*!*/ AddSeconds(RubyContext/*!*/ context, RubyTime/*!*/ self, object seconds) { if (seconds is RubyTime) { - throw RubyExceptions.CreateTypeError("time + time?"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("time + time?")); } RubyTime result; try { result = Shift(self, ToExact(context, seconds)); } catch (OverflowException) { - throw RubyExceptions.CreateRangeError(String.Format("time + {0} out of Time range", context.Inspect(seconds).ToString())); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("time + {0} out of Time range", context.Inspect(seconds).ToString()))); } return RezoneShifted(context, self, result); } @@ -1396,7 +1396,7 @@ public static object Subtract(RubyContext/*!*/ context, RubyTime/*!*/ self, obje try { result = Shift(self, -ToExact(context, other)); } catch (OverflowException) { - throw RubyExceptions.CreateRangeError(String.Format("time - {0} out of Time range", context.Inspect(other).ToString())); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("time - {0} out of Time range", context.Inspect(other).ToString()))); } return RezoneShifted(context, self, result); } @@ -1665,12 +1665,12 @@ public static bool IsSaturday(RubyTime/*!*/ self) { digits = 0; } else if (ndigits is MutableString) { // NUM2INT: a String is not converted here - throw RubyExceptions.CreateImplicitConversionError("String", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("String", "Integer")); } else { digits = ToIntComponent(context, ndigits); } if (digits < 0) { - throw RubyExceptions.CreateArgumentError("negative ndigits given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative ndigits given")); } ExactNum scale = ExactNum.FromInteger(BigInteger.Pow(new BigInteger(10), digits)); @@ -1790,8 +1790,8 @@ public static object ToRational(CallSiteStorage/*!*/ stringC bool inModule = module.ResolveMethod(name, VisibilityContext.AllVisible).Found; bool inMirror = mirror.ResolveMethod(name, VisibilityContext.AllVisible).Found; if (!inModule && !inMirror) { - throw RubyExceptions.CreateUndefinedMethodError(mirror, name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(mirror, name)); } if (inMirror) { ModuleOps.SetMethodAttributes(mirror, names, attributes); @@ -201,7 +201,7 @@ public static object Using(RubyScope/*!*/ scope, object/*!*/ self, object module // m); end' activates for X's body, not for main's file, which is not what the // caller can have meant. if (s.Kind == ScopeKind.Method || s.Kind == ScopeKind.BlockMethod || s.Kind == ScopeKind.Module) { - throw RubyExceptions.CreateRuntimeError("main.using is permitted only at toplevel"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("main.using is permitted only at toplevel")); } if (s.Kind == ScopeKind.TopLevel) { break; diff --git a/Src/Libraries/Builtins/Strftime.cs b/Src/Libraries/Builtins/Strftime.cs index fa6aeb377..8986ca43f 100644 --- a/Src/Libraries/Builtins/Strftime.cs +++ b/Src/Libraries/Builtins/Strftime.cs @@ -73,7 +73,7 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, if (i >= format.Length) { // MRI: a lone % at the end, or one followed only by flags or a width, is an // error that names the whole format - throw RubyExceptions.CreateArgumentError("invalid format: " + format); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid format: " + format)); } Modifiers modifiers = new Modifiers(); @@ -108,7 +108,7 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, } if (i >= format.Length) { - throw RubyExceptions.CreateArgumentError("invalid format: " + format); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid format: " + format)); } if (format[i] == 'E' || format[i] == 'O') { @@ -160,7 +160,7 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, // ERANGE, naming the format, rather than going on: "%2147483647d" would // otherwise ask for a 4 GB string. A %Z with no zone name writes nothing, // so it asks for no room. - throw RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ERANGE"), format); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ERANGE"), format)); } string piece = FormatDirective(context, time, directive, modifiers, modifiers.Width, depth); diff --git a/Src/Libraries/Builtins/StringFormatter.cs b/Src/Libraries/Builtins/StringFormatter.cs index 621b16c57..62cb03b07 100644 --- a/Src/Libraries/Builtins/StringFormatter.cs +++ b/Src/Libraries/Builtins/StringFormatter.cs @@ -163,7 +163,7 @@ internal StringFormatter(RubyContext/*!*/ context, string/*!*/ format, RubyEncod // MRI's rb_str_format reads the format as ASCII directives, so it has to be ASCII // compatible itself, even an empty one if (!encoding.IsAsciiIdentity) { - throw RubyExceptions.CreateAsciiIncompatibleEncodingError(encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateAsciiIncompatibleEncodingError(encoding)); } _context = context; @@ -205,7 +205,7 @@ internal StringFormatter(StringFormatterSiteStorage/*!*/ siteStorage, string/*!* object debug; if (_context.TryGetGlobalVariable(null, "DEBUG", out debug) && RubyOps.IsTrue(debug)) { - throw RubyExceptions.CreateArgumentError("too many arguments for format string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("too many arguments for format string")); } if (RubyOps.IsTrue(_context.Verbose)) { _context.ReportWarning("too many arguments for format string"); @@ -246,7 +246,7 @@ private static bool IsAsciiOnly(string/*!*/ str) { private void DoFormatCode() { // we already pulled the first '%'; _index points just past it. if (_index == _format.Length) { - throw RubyExceptions.CreateArgumentError("incomplete format specifier; use %% (double %) instead"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("incomplete format specifier; use %% (double %) instead")); } _opts = new FormatSettings(); @@ -266,7 +266,7 @@ private void DoFormatCode() { // Ruby 3.3 and earlier were laxer here - "%1$" produced a literal '%' - but // 3.4 made every truncated specifier an error (spec/core/kernel/shared/sprintf.rb). if (numberSeen) { - throw RubyExceptions.CreateArgumentError("malformed format string - %*[0-9]"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("malformed format string - %*[0-9]")); } if (flagSeen || argumentSeen) { // MRI's sprintf has fetched the argument of a "%1$" or "%" already (GETPOSARG, GETNAMEARG), so @@ -274,9 +274,9 @@ private void DoFormatCode() { if (argumentSeen) { GetData(_opts.ArgIndex, _opts.Name); } - throw RubyExceptions.CreateArgumentError("malformed format string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("malformed format string")); } - throw RubyExceptions.CreateArgumentError("incomplete format specifier; use %% (double %) instead"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("incomplete format specifier; use %% (double %) instead")); } char c = _format[_index]; @@ -284,10 +284,10 @@ private void DoFormatCode() { if (c == '#' || c == '-' || c == '+' || c == ' ' || c == '0') { // MRI: flags belong before the width ("%5 d" is an error, "% 5d" is not) if (widthSeen) { - throw RubyExceptions.CreateArgumentError("flag after width"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("flag after width")); } if (precisionSeen) { - throw RubyExceptions.CreateArgumentError("flag after precision"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("flag after precision")); } _index++; flagSeen = true; @@ -307,20 +307,20 @@ private void DoFormatCode() { // The digits that may follow are checked before the argument is fetched, so // a bare trailing "%*" is malformed whether or not an argument was supplied. if (_index >= _format.Length) { - throw RubyExceptions.CreateArgumentError("malformed format string - %*[0-9]"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("malformed format string - %*[0-9]")); } if (widthSeen) { - throw RubyExceptions.CreateArgumentError("width given twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width given twice")); } if (precisionSeen) { - throw RubyExceptions.CreateArgumentError("width after precision"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width after precision")); } widthSeen = true; int w = _siteStorage.CastToFixnum(GetData(TryReadStarArgumentIndex("width"), null)); if (w < 0) { // MRI: -INT_MIN is still negative, and is "width too big" if (w == Int32.MinValue) { - throw RubyExceptions.CreateArgumentError("width too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width too big")); } _opts.LeftAdj = true; w = -w; @@ -333,7 +333,7 @@ private void DoFormatCode() { _index++; numberSeen = true; if (precisionSeen) { - throw RubyExceptions.CreateArgumentError("precision given twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("precision given twice")); } precisionSeen = true; if (_index < _format.Length && _format[_index] == '*') { @@ -346,7 +346,7 @@ private void DoFormatCode() { // A precision that does not fit in a Fixnum is an error, not a silent // wrap: "%.99999999999s" raises rather than truncating to garbage. if (p > (Int32.MaxValue - 9) / 10) { - throw RubyExceptions.CreateArgumentError("precision too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("precision too big")); } p = p * 10 + (_format[_index++] - '0'); } @@ -363,34 +363,34 @@ private void DoFormatCode() { if (end < _format.Length && _format[end] == '$') { string digits = _format.Substring(_index, end - _index); if (_opts.ArgIndex.HasValue) { - throw RubyExceptions.CreateArgumentError("value given twice - {0}$", digits); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("value given twice - {0}$", digits)); } if (_useNamed) { - throw RubyExceptions.CreateArgumentError("numbered({0}) after named", digits); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("numbered({0}) after named", digits)); } if (_useAbsolute.HasValue && !_useAbsolute.Value) { - throw RubyExceptions.CreateArgumentError("numbered({0}) after unnumbered({1})", digits, _relativeIndex.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("numbered({0}) after unnumbered({1})", digits, _relativeIndex.ToString())); } // numbered from here on: a "*" width in this directive may not be unnumbered _useAbsolute = true; int argIndex; if (!Int32.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out argIndex)) { - throw RubyExceptions.CreateArgumentError("width too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width too big")); } _opts.ArgIndex = argIndex; _index = end + 1; argumentSeen = true; } else { if (widthSeen) { - throw RubyExceptions.CreateArgumentError("width given twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width given twice")); } if (precisionSeen) { - throw RubyExceptions.CreateArgumentError("width after precision"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width after precision")); } widthSeen = true; int width; if (!Int32.TryParse(_format.Substring(_index, end - _index), NumberStyles.None, CultureInfo.InvariantCulture, out width)) { - throw RubyExceptions.CreateArgumentError("width too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width too big")); } _opts.FieldWidth = width; _index = end; @@ -403,7 +403,7 @@ private void DoFormatCode() { char close = (c == '<') ? '>' : '}'; int end = _format.IndexOf(close, _index + 1); if (end < 0) { - throw RubyExceptions.CreateArgumentError("malformed name - unmatched parenthesis"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("malformed name - unmatched parenthesis")); } string spelled = _format.Substring(_index, end - _index + 1); // with its brackets, as MRI quotes it if (_opts.Name != null) { @@ -437,7 +437,7 @@ private void DoFormatCode() { if (conversion == '%' && _opts.NameStyle != '{') { if (flagSeen || numberSeen || argumentSeen) { - throw RubyExceptions.CreateArgumentError("invalid format character - %"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid format character - %")); } _buf.Append('%'); return; @@ -462,7 +462,7 @@ private void DoFormatCode() { if (end < _format.Length && _format[end] == '$') { int result; if (!Int32.TryParse(_format.Substring(_index, end - _index), NumberStyles.None, CultureInfo.InvariantCulture, out result)) { - throw RubyExceptions.CreateArgumentError("{0} too big", what); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("{0} too big", what)); } _index = end + 1; return result; @@ -506,18 +506,18 @@ private object GetData(int? absoluteIndex, string name) { if (_useNamed) { if (absoluteIndex.HasValue) { - throw RubyExceptions.CreateArgumentError("numbered({0}) after named", absoluteIndex.Value.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("numbered({0}) after named", absoluteIndex.Value.ToString())); } - throw RubyExceptions.CreateArgumentError("unnumbered({0}) mixed with named", (_relativeIndex + 1).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unnumbered({0}) mixed with named", (_relativeIndex + 1).ToString())); } if (_useAbsolute.HasValue) { // All arguments must use absolute or relative index. They can't be mixed if (_useAbsolute.Value && !absoluteIndex.HasValue) { - throw RubyExceptions.CreateArgumentError("unnumbered({0}) mixed with numbered", (_relativeIndex + 1).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unnumbered({0}) mixed with numbered", (_relativeIndex + 1).ToString())); } else if (!_useAbsolute.Value && absoluteIndex.HasValue) { - throw RubyExceptions.CreateArgumentError("numbered({0}) after unnumbered({1})", - absoluteIndex.Value.ToString(), _relativeIndex.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("numbered({0}) after unnumbered({1})", + absoluteIndex.Value.ToString(), _relativeIndex.ToString())); } } else { // First time through, set _useAbsolute based on our current value @@ -529,7 +529,7 @@ private object GetData(int? absoluteIndex, string name) { return _data[index]; } - throw RubyExceptions.CreateArgumentError("too few arguments"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("too few arguments")); } // MRI raises the errors that quote a name from the format in the format's encoding. @@ -548,7 +548,7 @@ private object GetNamedData(string/*!*/ name) { _useNamed = true; if (_data.Count != 1 || !(_data[0] is IDictionary)) { - throw RubyExceptions.CreateArgumentError("one hash required"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("one hash required")); } object hash = _data[0]; @@ -640,7 +640,7 @@ private BigInteger ToIntegerArgument() { object value = _opts.Value; if (value == null) { - throw RubyExceptions.CreateTypeError("can't convert nil into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert nil into Integer")); } if (value is int) { @@ -664,7 +664,7 @@ private BigInteger ToIntegerArgument() { } if (str != null) { if (!str.Encoding.IsAsciiIdentity) { - throw RubyExceptions.CreateAsciiIncompatibleEncodingError(str.Encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateAsciiIncompatibleEncodingError(str.Encoding)); } object parsed = KernelOps.ParseInteger(str, 0); return (parsed is BigInteger) ? (BigInteger)parsed : (parsed is long ? (BigInteger)(long)parsed : (BigInteger)(int)parsed); @@ -1407,7 +1407,7 @@ private void AppendChar() { str = _siteStorage.TryConvertToStr(value); } catch (InvalidOperationException e) { // to_str exists but returned a non-String - throw RubyExceptions.CreateTypeError(e, "can't convert {0} into String", _context.GetClassDisplayName(value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(e, "can't convert {0} into String", _context.GetClassDisplayName(value))); } } @@ -1451,7 +1451,7 @@ private int CharArgumentToInt(object value) { // MRI 4.0 says "no implicit conversion from nil to integer" here; ruby/spec pins // this wording for every other engine (raise_consistent_error in // core/kernel/shared/sprintf.rb), as it does for the conversion errors. - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer")); } if (value is BigInteger) { throw IntegerOutOfIntRange((BigInteger)value); @@ -1466,7 +1466,7 @@ private int CharArgumentToInt(object value) { if (value is double) { double d = (double)value; if (Double.IsNaN(d) || d >= 9223372036854775808.0 || d < -9223372036854775808.0) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", FormatFloatG10(d))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", FormatFloatG10(d)))); } long truncated = (long)d; if (truncated < Int32.MinValue || truncated > Int32.MaxValue) { @@ -1517,7 +1517,7 @@ private int CharArgumentToInt(object value) { /// private string/*!*/ FormatCodepoint(int codepoint) { if (codepoint < 0) { - throw RubyExceptions.CreateArgumentError("invalid character"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid character")); } RubyEncoding encoding = _resultEncoding ?? _encoding; @@ -1526,7 +1526,7 @@ private int CharArgumentToInt(object value) { byte[] bytes = Integer.ToFormatBytes(encoding, (uint)codepoint, out known); if (known) { if (bytes == null) { - throw RubyExceptions.CreateArgumentError("invalid character"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid character")); } if (codepoint < 0x80 && bytes.Length == 1) { return ((char)codepoint).ToString(); @@ -1556,12 +1556,12 @@ private int CharArgumentToInt(object value) { // MRI: rb_enc_codelen fails for a code point the encoding has no character for if (codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) { - throw RubyExceptions.CreateArgumentError("invalid character"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid character")); } string text = Char.ConvertFromUtf32(codepoint); if (codepoint > 0x7F && !IsRepresentable(text)) { - throw RubyExceptions.CreateArgumentError("invalid character"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid character")); } return text; } @@ -1626,7 +1626,7 @@ private void TrackEncoding(MutableString/*!*/ str) { return; } - throw RubyExceptions.CreateEncodingCompatibilityError(_resultEncoding ?? _encoding, encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEncodingCompatibilityError(_resultEncoding ?? _encoding, encoding)); } private static int CountCharacters(string/*!*/ str) { diff --git a/Src/Libraries/Builtins/StructOps.cs b/Src/Libraries/Builtins/StructOps.cs index 2c2d177f6..1506dcfcf 100644 --- a/Src/Libraries/Builtins/StructOps.cs +++ b/Src/Libraries/Builtins/StructOps.cs @@ -31,7 +31,7 @@ namespace IronRuby.Builtins { public static partial class RubyStructOps { [RubyConstructor] public static void AllocatorUndefined(RubyClass/*!*/ self, params object[] args) { - throw RubyExceptions.CreateAllocatorUndefinedError(self); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateAllocatorUndefinedError(self)); } [RubyMethod("new", RubyMethodAttributes.PublicSingleton)] @@ -58,7 +58,7 @@ public static object NewStruct(BlockParam block, RubyClass/*!*/ self, [DefaultPr string strName = className.ConvertToString(); if (!IronRuby.Compiler.Tokenizer.IsConstantName(strName)) { - throw RubyExceptions.CreateNameError(String.Format("identifier {0} needs to be constant", strName)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("identifier {0} needs to be constant", strName))); } // new_struct: MRI warns (rb_warn, so even without -w) and replaces the constant. @@ -204,7 +204,7 @@ public static void Reinitialize(RubyStruct/*!*/ self, params object[]/*!*/ items // MRI: anything but an instance of this very struct class is rejected with this message var other = source as RubyStruct; if (other == null || self.ImmediateClass.GetNonSingletonClass() != other.ImmediateClass.GetNonSingletonClass()) { - throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("initialize_copy should take same class object")); } self.SetValues(other.Values); @@ -448,8 +448,8 @@ private static int NormalizeIndex(int itemCount, int index) { return normalized; } // MRI reports the index as given, and says which way it is out. - throw RubyExceptions.CreateIndexError( - index < 0 ? "offset {0} too small for struct(size:{1})" : "offset {0} too large for struct(size:{1})", index, itemCount); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError( + index < 0 ? "offset {0} too small for struct(size:{1})" : "offset {0} too large for struct(size:{1})", index, itemCount)); } } } diff --git a/Src/Libraries/Builtins/SymbolOps.cs b/Src/Libraries/Builtins/SymbolOps.cs index f50efd53e..c85e78a9a 100644 --- a/Src/Libraries/Builtins/SymbolOps.cs +++ b/Src/Libraries/Builtins/SymbolOps.cs @@ -246,7 +246,7 @@ public static object Match(RubyScope/*!*/ scope, RubySymbol/*!*/ self, [NotNull] [RubyMethod("=~")] public static object Match(ClrName/*!*/ self, [NotNull]RubySymbol/*!*/ str) { - throw RubyExceptions.CreateTypeError("type mismatch: Symbol given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("type mismatch: Symbol given")); } [RubyMethod("=~")] diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 2cc06088e..2f5f888d5 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -968,8 +968,8 @@ public static Thread Join(ConversionStorage/*!*/ floatConversion, RubyCo } else if (timeout is System.Numerics.BigInteger) { seconds = (double)(System.Numerics.BigInteger)timeout; } else if (timeout is MutableString || timeout is bool) { - throw RubyExceptions.CreateTypeError("no implicit conversion to float from {0}", - timeout is bool ? ((bool)timeout ? "true" : "false") : "string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion to float from {0}", + timeout is bool ? ((bool)timeout ? "true" : "false") : "string")); } else { seconds = Protocols.CastToFloat(floatConversion, timeout); } @@ -1424,7 +1424,7 @@ public static object GlobalAbortOnException(object self, bool value) { [ReceivesKeywords] public static Thread/*!*/ StartThread(RubyContext/*!*/ context, BlockParam startRoutine, object self, params object[]/*!*/ args) { if (startRoutine == null) { - throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to create Proc object without a block")); } RubyClass cls = self as RubyClass; return StartThread(context, (cls != null && cls.IsRubyClass) ? cls : null, startRoutine, args); @@ -1485,8 +1485,8 @@ private static Action CreateThreadTerminator(RubyContext context) { private static Thread/*!*/ AllocateThread(RubyContext/*!*/ context, RubyClass subclass, out ThreadStarter/*!*/ starter) { if (OperatingSystem.IsBrowser()) { // single-threaded WebAssembly: Thread.Start would throw PlatformNotSupportedException - throw RubyExceptions.CreateNotImplementedError( - "Thread.new is not available in the browser: .NET on WebAssembly runs on a single thread (so do Fiber and Enumerator#next, which are built on threads)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNotImplementedError( + "Thread.new is not available in the browser: .NET on WebAssembly runs on a single thread (so do Fiber and Enumerator#next, which are built on threads)")); } RubyThreadInfo creator = RubyThreadInfo.FromThread(Thread.CurrentThread); ThreadGroup group = creator.Group; @@ -1642,7 +1642,7 @@ private static void RubyThreadStart(RubyContext/*!*/ context, BlockParam startRo if (!RubyUtils.IsRubyThreadExit(e) && !(e is ThreadInterruptedException)) { Exception visible = RubyUtils.GetVisibleException(e); RubyExceptionData.GetInstance(visible).CaptureExceptionTrace(context); - info.Exception = visible; + info.Exception = RubyExceptionData.MarkKept(visible); // A thread killed while it was already unwinding a Thread#raise still dies // of that exception, and MRI reports it. @@ -1654,7 +1654,7 @@ private static void RubyThreadStart(RubyContext/*!*/ context, BlockParam startRo e = RubyUtils.GetVisibleException(e); // a start routine that is a method (Thread.new(&method(:m))) has no Ruby frame that captured the backtrace: RubyExceptionData.GetInstance(e).CaptureExceptionTrace(context); - info.Exception = e; + info.Exception = RubyExceptionData.MarkKept(e); StringBuilder trace = new StringBuilder(); trace.Append(e.Message); @@ -1825,7 +1825,7 @@ public static MutableString GetName(Thread/*!*/ self) { [RubyMethod("name=")] public static object SetName(Thread/*!*/ self, [DefaultProtocol]MutableString name) { if (name != null && name.IndexOf((byte)0) >= 0) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } RubyThreadInfo.FromThread(self).Name = name; if (name != null) { @@ -1880,7 +1880,7 @@ public static Proc SetTraceFunc(RubyContext/*!*/ context, Thread/*!*/ self, obje public static Proc AddTraceFunc(RubyContext/*!*/ context, Thread/*!*/ self, object traceFunc) { Proc proc = KernelOps.CastTraceFunc(traceFunc); if (proc == null) { - throw RubyExceptions.CreateTypeError("trace_func needs to be Proc"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("trace_func needs to be Proc")); } TracePoint.AddTraceFunc(context, proc, self); return proc; @@ -1969,7 +1969,7 @@ public static object GlobalReportOnException(object self, object value) { [RubyMethod("handle_interrupt", RubyMethodAttributes.PublicSingleton)] public static object HandleInterrupt(RubyContext/*!*/ context, BlockParam block, object self, [NotNull]Hash/*!*/ mask) { if (block == null) { - throw RubyExceptions.CreateArgumentError("block is needed."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("block is needed.")); } var classes = new RubyModule[mask.Count]; @@ -1983,7 +1983,7 @@ public static object HandleInterrupt(RubyContext/*!*/ context, BlockParam block, case "immediate": timings[i] = RubyUtils.InterruptImmediate; break; case "on_blocking": timings[i] = RubyUtils.InterruptOnBlocking; break; case "never": timings[i] = RubyUtils.InterruptNever; break; - default: throw RubyExceptions.CreateArgumentError("unknown mask signature"); + default: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown mask signature")); } i++; } diff --git a/Src/Libraries/Builtins/TracePointOps.cs b/Src/Libraries/Builtins/TracePointOps.cs index 0bc1681b8..07f6df642 100644 --- a/Src/Libraries/Builtins/TracePointOps.cs +++ b/Src/Libraries/Builtins/TracePointOps.cs @@ -45,7 +45,7 @@ public static class TracePointOps { TraceEvents mask = ParseEvents(respondTo, toSym, events); if (handler == null) { - throw RubyExceptions.CreateArgumentError("must be called with a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("must be called with a block")); } return new TracePoint(self.Context, mask, handler.Proc); } @@ -76,13 +76,13 @@ private static TraceEvents ParseEvent(RespondToStorage/*!*/ respondTo, UnaryOpSt object symbol = e; if (!(symbol is RubySymbol) && !(symbol is MutableString)) { if (!Protocols.RespondTo(respondTo, e, "to_sym")) { - throw RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(e), "Symbol"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(e), "Symbol")); } var site = toSym.GetCallSite("to_sym"); symbol = site.Target(site, e); if (!(symbol is RubySymbol)) { - throw RubyExceptions.CreateTypeError("can't convert {0} to Symbol ({0}#to_sym gives {1})", - context.GetClassDisplayName(e), context.GetClassDisplayName(symbol)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to Symbol ({0}#to_sym gives {1})", + context.GetClassDisplayName(e), context.GetClassDisplayName(symbol))); } } @@ -96,7 +96,7 @@ private static TraceEvents ParseEvent(RespondToStorage/*!*/ respondTo, UnaryOpSt case "a_call": return TraceEvents.Call | TraceEvents.BCall | TraceEvents.CCall; case "a_return": return TraceEvents.Return | TraceEvents.BReturn | TraceEvents.CReturn; } - throw RubyExceptions.CreateArgumentError("unknown event: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown event: {0}", name)); } #endregion @@ -113,7 +113,7 @@ private static TraceEvents ParseEvent(RespondToStorage/*!*/ respondTo, UnaryOpSt public static object AllowReentry([NotNull]BlockParam/*!*/ block, RubyClass/*!*/ self) { TraceEventInfo current = TracePoint.CurrentEvent; if (current == null) { - throw RubyExceptions.CreateRuntimeError("No need to allow reentrance."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("No need to allow reentrance.")); } TracePoint.CurrentEvent = null; @@ -144,7 +144,7 @@ public static object Enable(ConversionStorage/*!*/ fixnumCast, BlockParam b case "target_line": targetLine = entry.Value; break; case "target_thread": targetThread = entry.Value; defaultThread = false; break; default: - throw RubyExceptions.CreateArgumentError("unknown keyword: {0}", self.Context.Inspect(entry.Key)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword: {0}", self.Context.Inspect(entry.Key))); } } } @@ -159,19 +159,19 @@ public static object Enable(ConversionStorage/*!*/ fixnumCast, BlockParam b if (targetThread != null) { var thread = targetThread as Thread; if (thread == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected VM/thread)", self.Context.GetClassDisplayName(targetThread)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected VM/thread)", self.Context.GetClassDisplayName(targetThread))); } if (self.TargetThread != null && self.TargetThread != thread) { - throw RubyExceptions.CreateArgumentError("can not override target_thread filter"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can not override target_thread filter")); } } if (target == null) { if (targetLine != null) { - throw RubyExceptions.CreateArgumentError("only target_line is specified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("only target_line is specified")); } if (self.HasTarget) { - throw RubyExceptions.CreateArgumentError("can't nest-enable a targeting TracePoint"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't nest-enable a targeting TracePoint")); } self.TargetThread = (Thread)targetThread; self.Enable(); @@ -218,17 +218,17 @@ public static object Enable(ConversionStorage/*!*/ fixnumCast, BlockParam b var rubyMethod = method as RubyMethodInfo; if (rubyMethod == null && proc == null) { - throw RubyExceptions.CreateArgumentError("specified target is not supported"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("specified target is not supported")); } if (self.IsEnabled) { - throw RubyExceptions.CreateArgumentError("can't nest-enable a targeting TracePoint"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't nest-enable a targeting TracePoint")); } int line = 0; if (targetLine != null) { if ((self.Events & TraceEvents.Line) == 0) { - throw RubyExceptions.CreateArgumentError("target_line is specified, but line event is not specified"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("target_line is specified, but line event is not specified")); } line = Protocols.CastToFixnum(fixnumCast, targetLine); } @@ -250,7 +250,7 @@ public static object Enable(ConversionStorage/*!*/ fixnumCast, BlockParam b } if ((self.Events & possible) == 0 || targetLine != null && (line < firstLine || line > lastLine)) { - throw RubyExceptions.CreateArgumentError("can not enable any hooks"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can not enable any hooks")); } return (rubyMethod != null) @@ -267,7 +267,7 @@ public static object Disable(BlockParam block, TracePoint/*!*/ self) { } if (self.HasTarget) { - throw RubyExceptions.CreateArgumentError("can't disable a targeting TracePoint in a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't disable a targeting TracePoint in a block")); } Thread targetThread = self.TargetThread; @@ -296,7 +296,7 @@ public static bool IsEnabled(TracePoint/*!*/ self) { private static TraceEventInfo/*!*/ GetEvent(TracePoint/*!*/ self) { TraceEventInfo info = TracePoint.CurrentEvent; if (info == null) { - throw RubyExceptions.CreateRuntimeError("access from outside"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("access from outside")); } return info; } @@ -304,7 +304,7 @@ public static bool IsEnabled(TracePoint/*!*/ self) { private static TraceEventInfo/*!*/ GetEvent(TracePoint/*!*/ self, TraceEvents supported) { TraceEventInfo info = GetEvent(self); if ((info.Event & supported) == 0) { - throw RubyExceptions.CreateRuntimeError("not supported by this event"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not supported by this event")); } return info; } diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index c54edd0fe..3ae046376 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -112,9 +112,9 @@ public static int GetArity(UnboundMethod/*!*/ self) { } if (constraint.IsClass && !context.IsKindOf(target, constraint)) { - throw RubyExceptions.CreateTypeError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError( "bind argument must be an instance of {0}", context.GetModuleMessageName(constraint) - ); + )); } if (self._isMethodMissing) { @@ -307,7 +307,7 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet [RubyMethod("overloads")] public static RubyMethod/*!*/ SelectOverload_old(RubyContext/*!*/ context, RubyMethod/*!*/ self, [NotNullItems]params object/*!*/[]/*!*/ parameterTypes) { - throw RubyExceptions.CreateNameError("UnboundMethod#overloads is an obsolete name, use UnboundMethod#overload."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("UnboundMethod#overloads is an obsolete name, use UnboundMethod#overload.")); } [RubyMethod("overload")] diff --git a/Src/Libraries/Builtins/WarningOps.cs b/Src/Libraries/Builtins/WarningOps.cs index a27753407..5bf765f6f 100644 --- a/Src/Libraries/Builtins/WarningOps.cs +++ b/Src/Libraries/Builtins/WarningOps.cs @@ -67,19 +67,19 @@ public static object Warn(RubyContext/*!*/ context, object self, object message, MutableString str = message as MutableString; if (str == null) { - throw RubyExceptions.CreateUnexpectedTypeError(context, message, "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(context, message, "String")); } // rb_must_asciicompat if (!str.Encoding.IsAsciiIdentity) { - throw RubyExceptions.CreateAsciiIncompatibleEncodingError(str.Encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateAsciiIncompatibleEncodingError(str.Encoding)); } object category; if (options != null && options.TryGetValue(context.CreateAsciiSymbol("category"), out category) && category != null) { var symbol = category as RubySymbol; if (symbol == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Symbol)", - context.GetClassDisplayName(category)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Symbol)", + context.GetClassDisplayName(category))); } if (!context.IsWarningEnabled(CheckCategory(symbol))) { return null; @@ -95,7 +95,7 @@ public static object Warn(RubyContext/*!*/ context, object self, object message, private static string/*!*/ CheckCategory(RubySymbol/*!*/ category) { string name = category.ToString(); if (Array.IndexOf(RubyContext.WarningCategories, name) < 0) { - throw RubyExceptions.CreateArgumentError("unknown category: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown category: {0}", name)); } return name; } diff --git a/Src/Libraries/Builtins/WeakMap.cs b/Src/Libraries/Builtins/WeakMap.cs index cff5e9d4f..149f81cbe 100644 --- a/Src/Libraries/Builtins/WeakMap.cs +++ b/Src/Libraries/Builtins/WeakMap.cs @@ -262,7 +262,7 @@ public static object Each(BlockParam block, WeakMap/*!*/ self) { var entries = self.GetLiveEntries(); if (entries.Count > 0 && block == null) { // wmap_each and friends yield from C: MRI's message has no "(yield)" - throw RubyExceptions.CreateLocalJumpError("no block given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLocalJumpError("no block given")); } foreach (var entry in entries) { object result; @@ -277,7 +277,7 @@ public static object Each(BlockParam block, WeakMap/*!*/ self) { public static object EachKey(BlockParam block, WeakMap/*!*/ self) { var entries = self.GetLiveEntries(); if (entries.Count > 0 && block == null) { - throw RubyExceptions.CreateLocalJumpError("no block given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLocalJumpError("no block given")); } foreach (var entry in entries) { object result; @@ -292,7 +292,7 @@ public static object EachKey(BlockParam block, WeakMap/*!*/ self) { public static object EachValue(BlockParam block, WeakMap/*!*/ self) { var entries = self.GetLiveEntries(); if (entries.Count > 0 && block == null) { - throw RubyExceptions.CreateLocalJumpError("no block given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLocalJumpError("no block given")); } foreach (var entry in entries) { object result; diff --git a/Src/Libraries/Builtins/WindowsSpawn.cs b/Src/Libraries/Builtins/WindowsSpawn.cs index 3c807d0de..2cc1d70ca 100644 --- a/Src/Libraries/Builtins/WindowsSpawn.cs +++ b/Src/Libraries/Builtins/WindowsSpawn.cs @@ -790,7 +790,7 @@ private static object Reap(RubyContext/*!*/ context, int pid, IntPtr handle) { IntPtr read, write; if (!CreatePipe(out read, out write, ref attributes, 0)) { - throw RubyExceptions.CreateEINVAL("pipe"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("pipe")); } SetHandleInformation(read, HANDLE_FLAG_INHERIT, 0); SetHandleInformation(write, HANDLE_FLAG_INHERIT, 0); @@ -843,7 +843,7 @@ internal static object SetCloseOnExec(RubyContext/*!*/ context, int descriptor, IntPtr read, write; if (!CreatePipe(out read, out write, ref attributes, 0)) { - throw RubyExceptions.CreateEINVAL("pipe"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("pipe")); } int pid; @@ -851,7 +851,7 @@ internal static object SetCloseOnExec(RubyContext/*!*/ context, int descriptor, if (plan.Error != 0) { CloseHandle(read); CloseHandle(write); - throw RubyExceptions.CreateENOENT(file.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(file.ToString())); } IntPtr stdIn = Inheritable(plan.StdIn); diff --git a/Src/Libraries/CoolIo/CoolIo.cs b/Src/Libraries/CoolIo/CoolIo.cs index 113909b60..e8d45cb8d 100644 --- a/Src/Libraries/CoolIo/CoolIo.cs +++ b/Src/Libraries/CoolIo/CoolIo.cs @@ -104,9 +104,9 @@ internal static int GetIntIvar(RubyContext/*!*/ context, object obj, string/*!*/ return (int)value; } if (value == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion from nil to integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion from nil to integer")); } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", context.GetClassDisplayName(value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", context.GetClassDisplayName(value))); } #region Loop @@ -177,7 +177,7 @@ private static int SupportedBackends { [RubyMethod("ev_loop_new", RubyMethodAttributes.PrivateInstance)] public static object EvLoopNew(Loop/*!*/ self, [DefaultProtocol]int flags) { if (self._initialized) { - throw RubyExceptions.CreateRuntimeError("loop already initialized"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("loop already initialized")); } // ev_loop_new: LIBEV_FLAGS in the environment replaces the flags unless the loop // was told not to consult it, and a loop asked only for backends this platform @@ -191,7 +191,7 @@ public static object EvLoopNew(Loop/*!*/ self, [DefaultProtocol]int flags) { } int backends = flags & EVBACKEND_MASK; if (backends != 0 && (backends & SupportedBackends) == 0) { - throw RubyExceptions.CreateRuntimeError("unable to initialize the event loop (no usable backend)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("unable to initialize the event loop (no usable backend)")); } self._initialized = true; self._waiter = ReadinessWaiter.Create(); @@ -204,7 +204,7 @@ public static int RunOnce(ConversionStorage/*!*/ floatConversion, Loop/* if (timeout != null && !(timeout is Missing)) { double value = Protocols.CastToFloat(floatConversion, timeout); if (value < 0) { - throw RubyExceptions.CreateArgumentError("time interval must be positive"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must be positive")); } seconds = value; } @@ -218,11 +218,11 @@ public static int RunNonBlock(Loop/*!*/ self) { private int Run(bool nonblock, double? timeout) { if (!_initialized) { - throw RubyExceptions.CreateRuntimeError("loop not initialized"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("loop not initialized")); } if (_running) { // The extension asserts this away; its eventbuf cannot be shared. - throw RubyExceptions.CreateRuntimeError("loop is already running"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("loop is already running")); } _running = true; @@ -780,12 +780,12 @@ internal virtual void Dispatch(Loop/*!*/ loop, int revents) { [RubyConstructor] public static Watcher/*!*/ Create(RubyClass/*!*/ self, params object[]/*!*/ args) { - throw RubyExceptions.CreateRuntimeError("watcher base class should not be initialized directly"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("watcher base class should not be initialized directly")); } [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static object Initialize(Watcher/*!*/ self, params object[]/*!*/ args) { - throw RubyExceptions.CreateRuntimeError("watcher base class should not be initialized directly"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("watcher base class should not be initialized directly")); } // Coolio::Watcher#attach - the bookkeeping the subclasses' #attach finishes with @@ -812,7 +812,7 @@ internal void AttachBookkeeping(object loop) { internal void DetachBookkeeping() { var loop = _loop; if (loop == null) { - throw RubyExceptions.CreateRuntimeError("not attached to a loop"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not attached to a loop")); } var context = Context; @@ -836,7 +836,7 @@ internal void DetachBookkeeping() { internal void EnableBookkeeping() { if (_enabled) { - throw RubyExceptions.CreateRuntimeError("already enabled"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("already enabled")); } _enabled = true; var context = Context; @@ -845,7 +845,7 @@ internal void EnableBookkeeping() { internal void DisableBookkeeping() { if (!_enabled) { - throw RubyExceptions.CreateRuntimeError("already disabled"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("already disabled")); } _enabled = false; var context = Context; @@ -855,8 +855,8 @@ internal void DisableBookkeeping() { internal static Loop/*!*/ RequireLoop(RubyContext/*!*/ context, object loop) { var result = loop as Loop; if (result == null) { - throw RubyExceptions.CreateArgumentError("expected loop to be an instance of Coolio::Loop, not {0}", - context.Inspect(loop).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("expected loop to be an instance of Coolio::Loop, not {0}", + context.Inspect(loop).ToString())); } return result; } @@ -884,7 +884,7 @@ internal void AttachTo(Loop/*!*/ loop) { internal void DetachFromLoop() { var loop = _loop; if (loop == null) { - throw RubyExceptions.CreateRuntimeError("not attached to a loop"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not attached to a loop")); } if (_enabled) { loop.CallDisable(this); @@ -899,7 +899,7 @@ internal void DetachFromLoop() { internal void EnableOnLoop() { var loop = _loop; if (loop == null) { - throw RubyExceptions.CreateRuntimeError("not attached to a loop"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not attached to a loop")); } EnableBookkeeping(); lock (loop._lock) { @@ -910,7 +910,7 @@ internal void EnableOnLoop() { internal void DisableOnLoop() { var loop = _loop; if (loop == null) { - throw RubyExceptions.CreateRuntimeError("not attached to a loop"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not attached to a loop")); } if (_enabled) { lock (loop._lock) { @@ -935,7 +935,7 @@ internal void DisableOnLoop() { [RubyMethod("enable")] public static Watcher/*!*/ Enable(Watcher/*!*/ self) { if (self._loop == null) { - throw RubyExceptions.CreateRuntimeError("not attached to a loop"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not attached to a loop")); } self.EnableBookkeeping(); return self; @@ -944,7 +944,7 @@ internal void DisableOnLoop() { [RubyMethod("disable")] public static Watcher/*!*/ Disable(Watcher/*!*/ self) { if (self._loop == null) { - throw RubyExceptions.CreateRuntimeError("not attached to a loop"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not attached to a loop")); } self.DisableBookkeeping(); return self; @@ -1040,7 +1040,7 @@ public static object Initialize(RespondToStorage/*!*/ respondToStorage, case "w": events = EV_WRITE; break; case "rw": events = EV_READ | EV_WRITE; break; default: - throw RubyExceptions.CreateArgumentError("invalid event type: '{0}' (must be 'r', 'w', or 'rw')", what); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid event type: '{0}' (must be 'r', 'w', or 'rw')", what)); } var rubyIO = NioModule.ToIO(respondToStorage, toIoStorage, context, io); @@ -1080,7 +1080,7 @@ internal override void Dispatch(Loop/*!*/ loop, int revents) { } else if ((revents & EV_WRITE) != 0) { loop.CallOnWritable(this); } else { - throw RubyExceptions.CreateRuntimeError("unknown revents value for ev_io: {0}", revents); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("unknown revents value for ev_io: {0}", revents)); } } @@ -1260,7 +1260,7 @@ internal override void Dispatch(Loop/*!*/ loop, int revents) { public static TimerWatcher/*!*/ Reset(TimerWatcher/*!*/ self) { var loop = self._loop; if (loop == null) { - throw RubyExceptions.CreateRuntimeError("not attached to a loop"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not attached to a loop")); } lock (loop._lock) { if (self._active) { @@ -1301,15 +1301,15 @@ internal double Convert(object obj) { var context = Context; var respondTo = RubyUtils.GetCallSite(ref _respondTo, context, "respond_to?", RubyCallSignature.WithImplicitSelf(1)); if (!Protocols.RespondTo(respondTo, context, obj, "to_f")) { - throw RubyExceptions.CreateTypeError("can't convert {0} into Float", ConversionTarget(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into Float", ConversionTarget(context, obj))); } var toF = RubyUtils.GetCallSite(ref _toF, context, "to_f", RubyCallSignature.WithImplicitSelf(0)); object result = toF.Target(toF, obj); if (result is double) { return (double)result; } - throw RubyExceptions.CreateTypeError("can't convert {0} to Float ({0}#to_f gives {1})", - context.GetClassDisplayName(obj), context.GetClassDisplayName(result)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to Float ({0}#to_f gives {1})", + context.GetClassDisplayName(obj), context.GetClassDisplayName(result))); } private static string/*!*/ ConversionTarget(RubyContext/*!*/ context, object obj) { @@ -1375,7 +1375,7 @@ public static object Initialize(ToFloatStorage/*!*/ floatConversion, var str = path as MutableString ?? MutableString.Create(StringOf(stringCast, self.Context, path), RubyEncoding.UTF8); if (str.ToString().IndexOf('\0') >= 0) { // StringValueCStr - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } double seconds = (interval == null || interval is Missing) ? 0 : floatConversion.Convert(interval); self.Context.SetInstanceVariable(self, "@path", str); @@ -1506,7 +1506,7 @@ internal override void Dispatch(Loop/*!*/ loop, int revents) { statInfo = structClass as RubyClass; } if (statInfo == null) { - throw RubyExceptions.CreateNameError("uninitialized constant Struct::StatInfo"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("uninitialized constant Struct::StatInfo")); } object previous = BuildStatInfo(statInfo, ref _prev); object current = BuildStatInfo(statInfo, ref _attr); @@ -1820,7 +1820,7 @@ private static int ConvertNodeSize(NodeSizeStorage/*!*/ storage, ConversionStora var gt = storage.GreaterThan; if (Protocols.IsTrue(lt.Target(lt, size, ScriptingRuntimeHelpers.Int32ToObject(1))) || Protocols.IsTrue(gt.Target(gt, size, ScriptingRuntimeHelpers.Int32ToObject(MaxBufferSize)))) { - throw RubyExceptions.CreateArgumentError("invalid buffer size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid buffer size")); } return Protocols.CastToFixnum(fixnumCast, size); } @@ -1946,7 +1946,7 @@ public static bool IsEmpty(Buffer/*!*/ self) { if (!(length is Missing)) { var requested = Protocols.CastToInteger(integerConversion, length); if (requested.IsFixnum ? requested.Fixnum < 1 : requested.Bignum.Sign < 0) { - throw RubyExceptions.CreateArgumentError("length must be greater than zero"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("length must be greater than zero")); } count = (requested.IsFixnum && requested.Fixnum < self._count) ? requested.Fixnum : self._count; } else { @@ -2079,20 +2079,20 @@ public static int NCpus(RubyModule/*!*/ self) { } } } catch (Exception) { - throw RubyExceptions.CreateSystemCallError("fopen"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateSystemCallError("fopen")); } return count; } if (_isUnix) { return Environment.ProcessorCount; } - throw RubyExceptions.CreateRuntimeError("operation not supported"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("operation not supported")); } [RubyMethod("maxfds", RubyMethodAttributes.PublicSingleton)] public static object MaxFds(RubyModule/*!*/ self) { if (!_isUnix) { - throw RubyExceptions.CreateRuntimeError("operation not supported"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("operation not supported")); } var rlim = new ulong[2]; if (getrlimit(RlimitNoFile, rlim) < 0) { @@ -2105,7 +2105,7 @@ public static object MaxFds(RubyModule/*!*/ self) { [RubyMethod("maxfds=", RubyMethodAttributes.PublicSingleton)] public static object SetMaxFds(ConversionStorage/*!*/ fixnumCast, RubyModule/*!*/ self, object max) { if (!_isUnix) { - throw RubyExceptions.CreateRuntimeError("operation not supported"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("operation not supported")); } int value = Protocols.CastToFixnum(fixnumCast, max); var rlim = new ulong[2]; diff --git a/Src/Libraries/Date/Date.cs b/Src/Libraries/Date/Date.cs index c1f76ff80..613ef0463 100644 --- a/Src/Libraries/Date/Date.cs +++ b/Src/Libraries/Date/Date.cs @@ -133,7 +133,7 @@ internal static double ToStart(object sg) { if (sg is long) { return (long)sg; } - throw RubyExceptions.CreateTypeError("expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("expected numeric")); } internal static long ToLong(object value) { @@ -149,7 +149,7 @@ internal static long ToLong(object value) { if (value is double) { return (long)Math.Floor((double)value); } - throw RubyExceptions.CreateTypeError("expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("expected numeric")); } internal static DateError InvalidDate() { @@ -549,8 +549,8 @@ internal static bool TryToFrac(UnaryOpStorage/*!*/ toR, UnaryOpStorage/*!*/ num, if (!(r is int || r is long || r is BigInteger)) { RubyClass cls = context.GetClassOf(r); if (cls.Name != "Rational") { - throw RubyExceptions.CreateTypeError(String.Format( - "wrong argument type {0} (expected Rational)", context.GetClassDisplayName(r))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format( + "wrong argument type {0} (expected Rational)", context.GetClassDisplayName(r)))); } } @@ -602,7 +602,7 @@ public static object Add(UnaryOpStorage/*!*/ toR, UnaryOpStorage/*!*/ num, Unary RubyDate/*!*/ self, object other) { Frac f; if (!TryToFrac(toR, num, den, other, out f)) { - throw RubyExceptions.CreateTypeError("expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("expected numeric")); } return self.AddDays(f); } @@ -617,7 +617,7 @@ public static object Subtract(BinaryOpStorage/*!*/ quo, UnaryOpStorage/*!*/ toR, } Frac f; if (!TryToFrac(toR, num, den, other, out f)) { - throw RubyExceptions.CreateTypeError("expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("expected numeric")); } return self.AddDays(new Frac(-f.N, f.D)); } @@ -797,8 +797,8 @@ public static int GetHash(RubyDate/*!*/ self) { internal static IList CheckDeconstructKeys(RubyContext/*!*/ context, object keys) { if (keys != null && !(keys is IList)) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Array or nil)", - context.GetClassDisplayName(keys)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Array or nil)", + context.GetClassDisplayName(keys))); } return keys as IList; } @@ -839,7 +839,7 @@ internal static void AddKey(RubyContext/*!*/ context, Hash/*!*/ hash, IList want public static RubyDate/*!*/ MarshalLoad(UnaryOpStorage/*!*/ toR, UnaryOpStorage/*!*/ num, UnaryOpStorage/*!*/ den, RubyDate/*!*/ self, [NotNull]IList/*!*/ data) { if (data.Count < 6) { - throw RubyExceptions.CreateTypeError("invalid marshalled date"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("invalid marshalled date")); } Frac sf; if (!TryToFrac(toR, num, den, data[3], out sf)) { diff --git a/Src/Libraries/Date/DateFormatter.cs b/Src/Libraries/Date/DateFormatter.cs index b44340c9b..da76b6c3c 100644 --- a/Src/Libraries/Date/DateFormatter.cs +++ b/Src/Libraries/Date/DateFormatter.cs @@ -213,7 +213,7 @@ private static void Format(StringBuilder/*!*/ sb, RubyDate/*!*/ date, string/*!* if (hasWidth && width > MaxWidth) { // CRuby raises Errno::ERANGE here; the point is not to try to // allocate the string, which would take the process down. - throw RubyExceptions.CreateArgumentError("width too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("width too big")); } int colons = 0; diff --git a/Src/Libraries/Date/DateTime.cs b/Src/Libraries/Date/DateTime.cs index d30672dde..53dc7da61 100644 --- a/Src/Libraries/Date/DateTime.cs +++ b/Src/Libraries/Date/DateTime.cs @@ -167,7 +167,7 @@ private static long SplitField(UnaryOpStorage/*!*/ toR, UnaryOpStorage/*!*/ num, } Frac f; if (!TryToFrac(toR, num, den, value, out f)) { - throw RubyExceptions.CreateTypeError(String.Format("invalid {0} (not numeric)", field)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("invalid {0} (not numeric)", field))); } // MRI's *_trunc uses floor division, so the fraction is always in [0,1). BigInteger whole = f.Floor; @@ -275,7 +275,7 @@ private static long SplitField(UnaryOpStorage/*!*/ toR, UnaryOpStorage/*!*/ num, if (second == null) { sec = Frac.Zero; } else if (!TryToFrac(toR, num, den, second, out sec)) { - throw RubyExceptions.CreateTypeError("expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("expected numeric")); } long j = jd == null ? 0 : ToLong(jd); BigInteger sWhole = sec.Floor; @@ -305,7 +305,7 @@ private static long SplitField(UnaryOpStorage/*!*/ toR, UnaryOpStorage/*!*/ num, if (second == null) { sec = Frac.Zero; } else if (!TryToFrac(toR, num, den, second, out sec)) { - throw RubyExceptions.CreateTypeError("expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("expected numeric")); } BigInteger sWhole = sec.Floor; var result = Allocate(self); @@ -335,7 +335,7 @@ private static long SplitField(UnaryOpStorage/*!*/ toR, UnaryOpStorage/*!*/ num, if (second == null) { sec = Frac.Zero; } else if (!TryToFrac(toR, num, den, second, out sec)) { - throw RubyExceptions.CreateTypeError("expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("expected numeric")); } BigInteger sWhole = sec.Floor; var result = Allocate(self); diff --git a/Src/Libraries/Digest/Digest.cs b/Src/Libraries/Digest/Digest.cs index 3262d0206..65a0f7c2a 100644 --- a/Src/Libraries/Digest/Digest.cs +++ b/Src/Libraries/Digest/Digest.cs @@ -119,12 +119,12 @@ protected Base(RubyClass/*!*/ cls) { owner = owner.SuperClass; } if (owner == null) { - throw RubyExceptions.CreateRuntimeError("Digest::Base cannot be directly inherited in Ruby"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("Digest::Base cannot be directly inherited in Ruby")); } _native = NativeDigest.TryCreate(metadata); if (_native == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected digest/metadata)", - cls.Context.GetClassDisplayName(metadata))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected digest/metadata)", + cls.Context.GetClassDisplayName(metadata)))); } _digestLength = _native.DigestLength; _blockLength = _native.BlockLength; @@ -209,7 +209,7 @@ private void Append(byte[]/*!*/ data) { public static Base/*!*/ InitializeCopy(Base/*!*/ self, [NotNull]Base/*!*/ other) { if (self._native != null || other._native != null) { if (self._native == null || other._native == null) { - throw RubyExceptions.CreateTypeError("different algorithms"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("different algorithms")); } self._native.CopyFrom(other._native); return self; @@ -306,7 +306,7 @@ public static object Digest( [RubyMethod("digest", RubyMethodAttributes.PublicSingleton)] public static MutableString Digest(RubyClass/*!*/ self) { - throw RubyExceptions.CreateArgumentError("no data given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no data given")); } [RubyMethod("hexdigest", RubyMethodAttributes.PublicSingleton)] @@ -323,7 +323,7 @@ public static MutableString Digest(RubyClass/*!*/ self) { [RubyMethod("hexdigest", RubyMethodAttributes.PublicSingleton)] public static MutableString HexDigest(RubyClass/*!*/ self) { - throw RubyExceptions.CreateArgumentError("no data given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no data given")); } #region Helpers @@ -361,7 +361,7 @@ public static object Digest( object clone; if (!RubyUtils.TryDuplicateObject(initializeCopyStorage, allocateStorage, self, true, out clone)) { - throw RubyExceptions.CreateArgumentError("unable to copy object"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unable to copy object")); } var finish = finishStorage.GetCallSite("finish", 0); diff --git a/Src/Libraries/Erb/ErbEscape.cs b/Src/Libraries/Erb/ErbEscape.cs index ca5651772..a7d08069e 100644 --- a/Src/Libraries/Erb/ErbEscape.cs +++ b/Src/Libraries/Erb/ErbEscape.cs @@ -97,7 +97,7 @@ private static string EntityOf(byte b) { var context = storage.Context; object cgi; if (!context.ObjectClass.TryGetConstant(null, "CGI", out cgi)) { - throw RubyExceptions.CreateNameError("uninitialized constant CGI"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("uninitialized constant CGI")); } var site = storage.GetCallSite("escapeHTML", 1); return (MutableString)site.Target(site, cgi, str); @@ -174,8 +174,8 @@ private static object CallToS(UnaryOpStorage/*!*/ storage, object value) { return str; } string className = RubyExceptions.MessageTypeName(context.GetClassName(value)); - throw RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_s gives {1})", - className, RubyExceptions.MessageTypeName(context.GetClassName(result))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_s gives {1})", + className, RubyExceptions.MessageTypeName(context.GetClassName(result)))); } private static Exception/*!*/ CannotConvert(RubyContext/*!*/ context, object value) { diff --git a/Src/Libraries/Extensions/CharOps.cs b/Src/Libraries/Extensions/CharOps.cs index 9d52a6f34..755359ba6 100644 --- a/Src/Libraries/Extensions/CharOps.cs +++ b/Src/Libraries/Extensions/CharOps.cs @@ -31,7 +31,7 @@ public static char Create(RubyClass/*!*/ self, int utf16) { try { return checked((char)utf16); } catch (OverflowException) { - throw RubyExceptions.CreateRangeError("{0} is not a valid UTF-16 character code", utf16); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} is not a valid UTF-16 character code", utf16)); } } diff --git a/Src/Libraries/Extensions/ClrBigInteger.cs b/Src/Libraries/Extensions/ClrBigInteger.cs index 6ab78b9bd..97ba20f7a 100644 --- a/Src/Libraries/Extensions/ClrBigInteger.cs +++ b/Src/Libraries/Extensions/ClrBigInteger.cs @@ -422,7 +422,7 @@ public static object Power(CallSiteStorage= 2, so from here on the exponent is below 2**34 @@ -1177,7 +1177,7 @@ public static double ToFloat(RubyContext/*!*/ context, BigInteger/*!*/ self) { [RubyMethod("inspect")] public static MutableString/*!*/ ToString(int self, int radix) { if (radix < 2 || radix > 36) { - throw RubyExceptions.CreateArgumentError("invalid radix {0}", radix); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid radix {0}", radix)); } return MutableString.CreateAscii(radix == 10 ? self.ToString(CultureInfo.InvariantCulture) : ToRadixString((long)self, radix)); } @@ -1190,7 +1190,7 @@ public static double ToFloat(RubyContext/*!*/ context, BigInteger/*!*/ self) { [RubyMethod("inspect")] public static MutableString/*!*/ ToString(BigInteger/*!*/ self, int radix) { if (radix < 2 || radix > 36) { - throw RubyExceptions.CreateArgumentError("invalid radix {0}", radix); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid radix {0}", radix)); } return MutableString.CreateAscii(ToRadixString(self, radix)); diff --git a/Src/Libraries/Extensions/ClrInteger.cs b/Src/Libraries/Extensions/ClrInteger.cs index 844dbb738..43d4008a1 100644 --- a/Src/Libraries/Extensions/ClrInteger.cs +++ b/Src/Libraries/Extensions/ClrInteger.cs @@ -148,7 +148,7 @@ public static partial class ClrInteger { } if (leftShift >= MaxLeftShift) { - throw RubyExceptions.CreateRangeError("shift width too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("shift width too big")); } // At most two Int32.MaxValue steps below that bound. @@ -352,7 +352,7 @@ public static int Bit(int self, double index) { return ScriptingRuntimeHelpers.Int32ToObject(Bit(value, position)); } if (!slow.Context.GetClassOf(self).ResolveMethod("__ir_int_aref1__", VisibilityContext.AllVisible).Found) { - throw RubyExceptions.CreateTypeConversionError(slow.Context.GetClassName(index), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(slow.Context.GetClassName(index), "Integer")); } var site = slow.GetCallSite("__ir_int_aref1__", 1); return site.Target(site, self, index); @@ -365,7 +365,7 @@ public static int Bit(int self, double index) { private static object/*!*/ BitsSlow(CallSiteStorage>/*!*/ slow, object/*!*/ self, object offset, object size) { if (!slow.Context.GetClassOf(self).ResolveMethod("__ir_int_aref2__", VisibilityContext.AllVisible).Found) { - throw RubyExceptions.CreateTypeConversionError(slow.Context.GetClassName(offset is int ? size : offset), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(slow.Context.GetClassName(offset is int ? size : offset), "Integer")); } var site = slow.GetCallSite("__ir_int_aref2__", 2); return site.Target(site, self, offset, size); diff --git a/Src/Libraries/Extensions/ClrNameOps.cs b/Src/Libraries/Extensions/ClrNameOps.cs index b63149c8d..85a7a2f61 100644 --- a/Src/Libraries/Extensions/ClrNameOps.cs +++ b/Src/Libraries/Extensions/ClrNameOps.cs @@ -123,7 +123,7 @@ public static object Match(RubyScope/*!*/ scope, ClrName/*!*/ self, [NotNull]Rub [RubyMethod("=~")] public static object Match(ClrName/*!*/ self, [NotNull]ClrName/*!*/ str) { - throw RubyExceptions.CreateTypeError("type mismatch: ClrName given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("type mismatch: ClrName given")); } [RubyMethod("=~")] diff --git a/Src/Libraries/Extensions/ClrStringOps.cs b/Src/Libraries/Extensions/ClrStringOps.cs index c2bb7d1b1..4b4a1befc 100644 --- a/Src/Libraries/Extensions/ClrStringOps.cs +++ b/Src/Libraries/Extensions/ClrStringOps.cs @@ -77,7 +77,7 @@ public static class ClrString { [RubyMethod("*")] public static string/*!*/ Repeat(string/*!*/ self, [DefaultProtocol]int times) { if (times < 0) { - throw RubyExceptions.CreateArgumentError("negative argument"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative argument")); } var result = new StringBuilder(); @@ -303,7 +303,7 @@ public static object Match(RubyScope/*!*/ scope, string/*!*/ self, [NotNull]Ruby [RubyMethod("=~")] public static object Match(string/*!*/ self, [NotNull]string/*!*/ str) { - throw RubyExceptions.CreateTypeError("type mismatch: String given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("type mismatch: String given")); } [RubyMethod("=~")] @@ -345,7 +345,7 @@ public static object Match(CallSiteStorage 36) { - throw RubyExceptions.CreateArgumentError("invalid radix {0}", @base); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid radix {0}", @base)); } return Tokenizer.ParseInteger(self, @base).ToObject(); } @@ -501,7 +501,7 @@ private static int AppendDigits(string/*!*/ self, ref int i, StringBuilder/*!*/ public static RubySymbol/*!*/ ToSymbol(RubyContext/*!*/ context, string/*!*/ self) { // Cannot convert a string that contains \0 to a symbol if (self.IndexOf('\0') >= 0) { - throw RubyExceptions.CreateArgumentError("symbol string may not contain '\0'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("symbol string may not contain '\0'")); } return context.CreateSymbol(self, RubyEncoding.UTF8); @@ -538,9 +538,9 @@ public static object MethodMissing(RubyScope/*!*/ scope, BlockParam block, strin var context = scope.RubyContext; string methodName = name.ToString(); if (context.GetClass(typeof(MutableString)).ResolveMethod(methodName, VisibilityContext.AllVisible).Found) { - throw RubyExceptions.CreateTypeError("Mutating method '{0}' called for an immutable string (System::String)", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Mutating method '{0}' called for an immutable string (System::String)", name)); } - throw RubyExceptions.CreateMethodMissing(context, self, methodName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateMethodMissing(context, self, methodName)); } // TODO: forward to MutableString until we implement the methods here: diff --git a/Src/Libraries/Extensions/DecimalOps.cs b/Src/Libraries/Extensions/DecimalOps.cs index e6019ee67..adbe009cd 100644 --- a/Src/Libraries/Extensions/DecimalOps.cs +++ b/Src/Libraries/Extensions/DecimalOps.cs @@ -26,7 +26,7 @@ public static decimal Create(RubyModule/*!*/ self, double value) { try { return (decimal)value; } catch (OverflowException) { - throw RubyExceptions.CreateRangeError("number too big or to small to convert into System::Decimal"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big or to small to convert into System::Decimal")); } } diff --git a/Src/Libraries/Extensions/FlagEnumerationOps.cs b/Src/Libraries/Extensions/FlagEnumerationOps.cs index f8dfb9b81..f94db3bbe 100644 --- a/Src/Libraries/Extensions/FlagEnumerationOps.cs +++ b/Src/Libraries/Extensions/FlagEnumerationOps.cs @@ -34,7 +34,7 @@ public static class FlagEnumerationOps { return result; } - throw RubyExceptions.CreateUnexpectedTypeError(context, other, context.GetClassDisplayName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(context, other, context.GetClassDisplayName(self))); } [RubyMethod("&")] @@ -45,7 +45,7 @@ public static class FlagEnumerationOps { if (result != null) { return result; } - throw RubyExceptions.CreateUnexpectedTypeError(context, other, context.GetClassDisplayName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(context, other, context.GetClassDisplayName(self))); } [RubyMethod("^")] @@ -56,7 +56,7 @@ public static class FlagEnumerationOps { if (result != null) { return result; } - throw RubyExceptions.CreateUnexpectedTypeError(context, other, context.GetClassDisplayName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(context, other, context.GetClassDisplayName(self))); } [RubyMethod("~")] diff --git a/Src/Libraries/Extensions/IDictionaryOps.cs b/Src/Libraries/Extensions/IDictionaryOps.cs index b91336897..bb8f2aa8e 100644 --- a/Src/Libraries/Extensions/IDictionaryOps.cs +++ b/Src/Libraries/Extensions/IDictionaryOps.cs @@ -790,7 +790,7 @@ public static object Update(ConversionStorage>/*!*/ public static IDictionary Rehash(Hash/*!*/ self) { self.RequireNotFrozen(); if (self.IsIterating) { - throw RubyExceptions.CreateRuntimeError("rehash during iteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("rehash during iteration")); } // MRI builds the new table while the old one is still in place and swaps them (rb_hash_rehash): // a key that is the hash itself is hashed as the full hash, not as one emptied for the rebuild, @@ -824,7 +824,7 @@ public static object Reject(RubyContext/*!*/ context, BlockParam block, IDiction public static Hash/*!*/ Replace(RubyContext/*!*/ context, Hash/*!*/ self, [DefaultProtocol, NotNull]IDictionary/*!*/ other) { self.RequireNotFrozen(); if (self.IsIterating) { - throw RubyExceptions.CreateRuntimeError("can't replace hash during iteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("can't replace hash during iteration")); } return IDictionaryOps.ReplaceData(self, other); } diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index 784c7645b..c36c707ce 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -54,7 +54,7 @@ internal static int NormalizeIndexThrowIfNegative(IList/*!*/ list, int index) { index = NormalizeIndex(list.Count, index); if (index < 0) { // MRI: a[-5] = 1 on a 2-element array => "index -5 too small for array; minimum: -2" - throw RubyExceptions.CreateIndexError("index {0} too small for array; minimum: {1}", original, -list.Count); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} too small for array; minimum: {1}", original, -list.Count)); } return index; } @@ -104,7 +104,7 @@ private static long CastToLongRangeEndpoint(ConversionStorage/*!*/ fixnumCa if (value is System.Numerics.BigInteger) { var big = (System.Numerics.BigInteger)value; if (big > Int64.MaxValue || big < Int64.MinValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } return (long)big; } @@ -154,8 +154,8 @@ internal static void NormalizeRangeNoClamp(ConversionStorage/*!*/ fixnumCas if (longBegin < 0) { longBegin += listCount; if (longBegin < 0) { - throw RubyExceptions.CreateRangeError("{0}{1}{2} out of range", - originalBegin, excludeEnd ? "..." : "..", endless ? "" : end.ToString(CultureInfo.InvariantCulture)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0}{1}{2} out of range", + originalBegin, excludeEnd ? "..." : "..", endless ? "" : end.ToString(CultureInfo.InvariantCulture))); } } @@ -173,7 +173,7 @@ internal static void NormalizeRangeNoClamp(ConversionStorage/*!*/ fixnumCas // The answer is padded with nil to the range's full length; one longer than an array // may be is MRI's rb_ary_store error rather than an allocation that never ends. if (longCount >= MaxArraySize) { - throw RubyExceptions.CreateIndexError("index {0} too big", longCount - 1); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} too big", longCount - 1)); } // A beginning past the end only pads: it is kept as the list's length rather than cut @@ -281,7 +281,7 @@ internal static void AddRange(IList/*!*/ collection, IList/*!*/ items) { return result; } - throw RubyExceptions.CreateTypeError("{0}#allocate should return IList", cls.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0}#allocate should return IList", cls.Name)); } // The reverse walks below are MRI's (rb_ary_reverse_each, rb_ary_rindex): index Count - 1 @@ -301,7 +301,7 @@ internal static void AddRange(IList/*!*/ collection, IList/*!*/ items) { IList list = Protocols.CastToArray(arrayCast, other); if (list == null) { // nil is the one argument the cast lets through; it would empty the array first - throw RubyExceptions.CreateImplicitConversionError("nil", "Array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "Array")); } return Replace(self, list); } @@ -353,11 +353,11 @@ public static IList Clear(IList/*!*/ self) { [RubyMethod("*")] public static IList/*!*/ Repeat(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self, int repeat) { if (repeat < 0) { - throw RubyExceptions.CreateArgumentError("negative argument"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative argument")); } // rb_ary_times if (repeat > 0 && self.Count > MaxArraySize / repeat) { - throw RubyExceptions.CreateArgumentError("argument too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument too big")); } IList result = CreateResultArray(allocateStorage, self); @@ -411,7 +411,7 @@ public static object Repeat(UnaryOpStorage/*!*/ allocateStorage, JoinConversionS if (others[i] == null) { // nil converts to a null reference rather than failing, so it has to be // turned away here or it arrives as a null IList. - throw RubyExceptions.CreateImplicitConversionError("NilClass", "Array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("NilClass", "Array")); } IList other = Protocols.CastToArray(arrayCast, others[i]); // A snapshot, not the receiver itself: the first append would otherwise make @@ -487,12 +487,12 @@ public static object Product(BlockParam block, IList/*!*/ self, [DefaultProtocol for (int i = 0; i < arrays.Length; i++) { long count = arrays[i].Count; if (size > Int64.MaxValue / count) { - throw RubyExceptions.CreateRangeError("too big to product"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("too big to product")); } size *= count; } if (size > Int32.MaxValue) { - throw RubyExceptions.CreateRangeError("too big to product"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("too big to product")); } } @@ -651,7 +651,7 @@ private static object GetElement(IList/*!*/ self, IntegerValue index) { // MRI indexes with a long, so an index that fits one is merely past the end of any list. long _; if (!index.Bignum.AsInt64(out _)) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } return null; } @@ -664,7 +664,7 @@ public static object GetElement(IList/*!*/ self, int index) { private static object GetElement(IList/*!*/ self, double index) { if (Double.IsNaN(index) || index >= 9.2233720368547758E18 || index < -9.2233720368547758E18) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(index))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(index)))); } long truncated = (long)index; return (truncated > Int32.MaxValue || truncated < Int32.MinValue) ? null : GetElement(self, (int)truncated); @@ -776,7 +776,7 @@ public static object SetElement(ConversionStorage/*!*/ arrayTryCast, Conv Range range = rangeValues.TryConvert(index); if (range != null) { if (range.Begin is int && (int)range.Begin + length < 0) { - throw RubyExceptions.CreateRangeError("{0} out of range", (object)rangeValues.Context.Inspect(index).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of range", (object)rangeValues.Context.Inspect(index).ToString())); } int start, count; RangeToStartAndCount(fixnumCast, range, length, out start, out count); @@ -809,7 +809,7 @@ public static object SetElement(RubyArray/*!*/ self, int index, object value) { // MRI's rb_ary_store: an index the array cannot grow to is an IndexError, not an // arithmetic accident or an out-of-memory. if (index >= MaxArraySize) { - throw RubyExceptions.CreateIndexError("index {0} too big", index); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} too big", index)); } self.AddMultiple(index + 1 - self.Count, null); } @@ -832,7 +832,7 @@ public static object SetElement(IList/*!*/ self, int index, object value) { public static object SetElement(ConversionStorage/*!*/ arrayTryCast, IList/*!*/ self, int index, int length, object value) { if (length < 0) { - throw RubyExceptions.CreateIndexError("negative length ({0})", length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("negative length ({0})", length)); } index = NormalizeIndexThrowIfNegative(self, index); @@ -844,7 +844,7 @@ public static object SetElement(ConversionStorage/*!*/ arrayTryCast, ILis // rb_ary_splice: the array cannot be grown to put the values that far out if (index > self.Count && (long)index > MaxArraySize - (valueAsList != null ? valueAsList.Count : 1)) { - throw RubyExceptions.CreateIndexError("index {0} too big", index); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} too big", index)); } if (valueAsList != null && valueAsList.Count == 0) { @@ -901,7 +901,7 @@ private static void RangeToStartAndCount(ConversionStorage/*!*/ fixnumCast, if (start < 0) { // The range is reported as it was written, not as it was normalized: MRI says // "-9..0 out of range" for a[-9..0], not "-6..0". - throw RubyExceptions.CreateRangeError("{0}..{1} out of range", originalStart, endless ? "" : end.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0}..{1} out of range", originalStart, endless ? "" : end.ToString())); } if (endless) { @@ -1536,7 +1536,7 @@ public static object Fill(ConversionStorage/*!*/ fixnumCast, BlockParam blo int begin, length; if (block == null) { if (args.Length < 1 || args.Length > 3) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..3)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..3)", args.Length)); } object obj = args[0]; if (args.Length == 1) { @@ -1554,7 +1554,7 @@ public static object Fill(ConversionStorage/*!*/ fixnumCast, BlockParam blo } if (args.Length > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 0..2)", args.Length)); } if (args.Length == 0) { return Fill(block, self, 0); @@ -1600,7 +1600,7 @@ public static object Fill(ConversionStorage/*!*/ fixnumCast, BlockParam blo // loop below appended one element at a time until the process died. MRI reports // "argument too big" for a size it cannot represent; the CLR's is Int32.MaxValue. if (length >= 0 && (start >= MaxArraySize || length > MaxArraySize - start)) { - throw RubyExceptions.CreateArgumentError("argument too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument too big")); } ExpandList(self, Math.Min(start, start + length)); @@ -1638,7 +1638,7 @@ private static void FillRange(ConversionStorage/*!*/ fixnumCast, IList/*!*/ begin = NormalizeIndex(self, rawBegin); if (begin < 0) { - throw RubyExceptions.CreateRangeError("{0}..{1} out of range", rawBegin, endless ? "" : rawEnd.ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0}..{1} out of range", rawBegin, endless ? "" : rawEnd.ToString())); } int end = endless ? self.Count - 1 : NormalizeIndex(self, rawEnd); @@ -1675,7 +1675,7 @@ public static object Fill([NotNull]BlockParam/*!*/ block, IList/*!*/ self, int s // as for an object (above): MRI's rb_ary_fill refuses the size before the first yield if (length >= 0 && (start >= MaxArraySize || length > MaxArraySize - start)) { - throw RubyExceptions.CreateArgumentError("argument too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument too big")); } ExpandList(self, Math.Min(start, start + length)); @@ -1703,7 +1703,7 @@ public static object First(IList/*!*/ self) { [RubyMethod("first")] public static IList/*!*/ First(IList/*!*/ self, [DefaultProtocol]int count) { if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative array size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size")); } if (count > self.Count) { @@ -1718,7 +1718,7 @@ public static object First(IList/*!*/ self) { [RubyMethod("take")] public static RubyArray/*!*/ Take(IList/*!*/ self, [DefaultProtocol]int count) { if (count < 0) { - throw RubyExceptions.CreateArgumentError("attempt to take negative size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("attempt to take negative size")); } return new RubyArray(self, 0, Math.Min(count, self.Count)); } @@ -1728,10 +1728,10 @@ public static object First(IList/*!*/ self) { [RubyMethod("take")] public static RubyArray/*!*/ Take(IList/*!*/ self, [NotNull]System.Numerics.BigInteger count) { if (count < Int64.MinValue || count > Int64.MaxValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } if (count.Sign < 0) { - throw RubyExceptions.CreateArgumentError("attempt to take negative size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("attempt to take negative size")); } return new RubyArray(self, 0, self.Count); } @@ -1744,7 +1744,7 @@ public static object Last(IList/*!*/ self) { [RubyMethod("last")] public static IList/*!*/ Last(IList/*!*/ self, [DefaultProtocol]int count) { if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative array size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size")); } if (count > self.Count) { @@ -1870,7 +1870,7 @@ public static IEnumerable EnumerateRecursively(ConversionStorage/ internal static IList/*!*/ Flatten(ConversionStorage/*!*/ tryToAry, IList/*!*/ list, int maxDepth, IList/*!*/ result) { var recEnum = EnumerateRecursively(tryToAry, list, maxDepth, (_) => { - throw RubyExceptions.CreateArgumentError("tried to flatten recursive array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to flatten recursive array")); }); if (recEnum != null) { @@ -1963,7 +1963,7 @@ public static IList FlattenInPlace(ConversionStorage/*!*/ tryToAry, IList } if (isRecursive) { - throw RubyExceptions.CreateArgumentError("tried to flatten recursive array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to flatten recursive array")); } return self; } @@ -2282,7 +2282,7 @@ private static bool JoinItem(JoinConversionStorage/*!*/ conversions, IList/*!*/ // on what its to_ary returned): an object whose to_ary answers a new [self] each time recurs // through ever new arrays, which used to overflow the stack. if (ReferenceEquals(listItem, list) || seen != null && seen.ContainsKey(item)) { - throw RubyExceptions.CreateArgumentError("recursive array join"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("recursive array join")); } if (seen == null) { @@ -2520,7 +2520,7 @@ public static bool Empty(IList/*!*/ self) { index = index < 0 ? index + self.Count + 1 : index; if (index < 0) { // MRI: [1,2].insert(-5, 3) => "index -5 too small for array; minimum: -3" - throw RubyExceptions.CreateIndexError("index {0} too small for array; minimum: {1}", originalIndex, -self.Count - 1); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} too small for array; minimum: {1}", originalIndex, -self.Count - 1)); } if (index >= self.Count) { @@ -2558,7 +2558,7 @@ public static object Pop(RubyContext/*!*/ context, IList/*!*/ self, [DefaultProt RequireNotFrozen(self); if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative array size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size")); } if (count == 0 || self.Count == 0) { @@ -2593,7 +2593,7 @@ public static object Shift(ConversionStorage/*!*/ fixnumCast, IList/*!*/ se RequireNotFrozen(self); int n = Protocols.CastToFixnum(fixnumCast, count); if (n < 0) { - throw RubyExceptions.CreateArgumentError("negative array size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size")); } if (n > self.Count) { @@ -2827,7 +2827,7 @@ public static object SortInPlace(ComparisonStorage/*!*/ comparisonStorage, Block result.Add(new RubyArray()); } } else if (list.Count != result.Count) { - throw RubyExceptions.CreateIndexError("element size differs ({0} should be {1})", list.Count, result.Count); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("element size differs ({0} should be {1})", list.Count, result.Count)); } // add items @@ -3242,7 +3242,7 @@ private static object GetExtreme(ComparisonStorage/*!*/ comparisonStorage, Block return blockResult; } if (blockResult == null) { - throw RubyExceptions.MakeComparisonError(comparisonStorage.Context, item, result); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(comparisonStorage.Context, item, result)); } compareResult = Protocols.ConvertCompareResult(comparisonStorage, blockResult); } else { @@ -3268,7 +3268,7 @@ private static object GetExtremes(ConversionStorage/*!*/ fixnumCast, Compar int n = Protocols.CastToFixnum(fixnumCast, count); if (n < 0) { - throw RubyExceptions.CreateArgumentError("negative size ({0})", n); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative size ({0})", n)); } StrongBox breakResult; diff --git a/Src/Libraries/Extensions/IronRubyOps.cs b/Src/Libraries/Extensions/IronRubyOps.cs index 9da1905a3..eb75261b6 100644 --- a/Src/Libraries/Extensions/IronRubyOps.cs +++ b/Src/Libraries/Extensions/IronRubyOps.cs @@ -135,7 +135,7 @@ public static class IronRubyOps { foreach (object path in paths) { var str = path as MutableString; if (str == null) { - throw RubyExceptions.CreateTypeError("jit_census takes an Array of paths"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("jit_census takes an Array of paths")); } files.Add(str.ConvertToString()); } @@ -147,7 +147,7 @@ public static class Clr { [RubyMethod("profile", RubyMethodAttributes.PublicSingleton)] public static Hash/*!*/ GetProfile(RubyContext/*!*/ context, object self) { if (!context.RubyOptions.Profile) { - throw RubyExceptions.CreateSystemCallError("You must enable profiling to use Clr.profile"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateSystemCallError("You must enable profiling to use Clr.profile")); } Hash result = new Hash(context); @@ -160,7 +160,7 @@ public static class Clr { [RubyMethod("profile", RubyMethodAttributes.PublicSingleton)] public static object GetProfile(RubyContext/*!*/ context, BlockParam/*!*/ block, object self) { if (!context.RubyOptions.Profile) { - throw RubyExceptions.CreateSystemCallError("You must enable profiling to use Clr.profile"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateSystemCallError("You must enable profiling to use Clr.profile")); } var start = Profiler.Instance.GetProfile(); diff --git a/Src/Libraries/Extensions/NumericRounding.cs b/Src/Libraries/Extensions/NumericRounding.cs index 52ac76b20..fa57e1e73 100644 --- a/Src/Libraries/Extensions/NumericRounding.cs +++ b/Src/Libraries/Extensions/NumericRounding.cs @@ -65,7 +65,7 @@ internal static Half GetHalfOption(RubyContext/*!*/ context, IDictionary internal static int GetNDigits(ConversionStorage/*!*/ integerCast, object ndigits) { if (ndigits == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer")); } if (ndigits is double) { @@ -98,11 +98,11 @@ internal static int GetNDigits(ConversionStorage/*!*/ integerCast, // rb_num2int of a Float: to a long first ("float NaN out of range of integer"), then to an int // ("integer 3000000000 too big to convert to 'int'") if (Double.IsNaN(d) || d >= 9223372036854775808.0 || d < -9223372036854775808.0) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(d))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(d)))); } long whole = (long)d; if (whole > Int32.MaxValue || whole < Int32.MinValue) { - throw RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", whole, whole < 0 ? "small" : "big")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", whole, whole < 0 ? "small" : "big"))); } return (int)whole; } @@ -112,9 +112,9 @@ internal static int GetNDigits(ConversionStorage/*!*/ integerCast, // MRI's NUM2INT narrows to a C long first, and a value too large for one fails there. BigInteger big = value.Bignum; if (big > Int64.MaxValue || big < Int64.MinValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } - throw RubyExceptions.CreateRangeError("integer {0} too {1} to convert to 'int'", big, big.Sign < 0 ? "small" : "big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("integer {0} too {1} to convert to 'int'", big, big.Sign < 0 ? "small" : "big")); } return value.Fixnum; } diff --git a/Src/Libraries/Extensions/TaskOps.cs b/Src/Libraries/Extensions/TaskOps.cs index d15e672dd..562ad447a 100644 --- a/Src/Libraries/Extensions/TaskOps.cs +++ b/Src/Libraries/Extensions/TaskOps.cs @@ -145,7 +145,7 @@ public static object Each(RubyContext/*!*/ context, BlockParam block, object/*!* // the module can also be included into a Ruby class var each = _eachers.GetOrAdd(self.GetType(), MakeEacher); if (each == null) { - throw RubyExceptions.CreateTypeError("{0} is not an IAsyncEnumerable", context.GetClassDisplayName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0} is not an IAsyncEnumerable", context.GetClassDisplayName(self))); } return each(block, self); } diff --git a/Src/Libraries/Extensions/TupleOps.cs b/Src/Libraries/Extensions/TupleOps.cs index 906a0e286..0a7f81a5c 100644 --- a/Src/Libraries/Extensions/TupleOps.cs +++ b/Src/Libraries/Extensions/TupleOps.cs @@ -46,7 +46,7 @@ internal static IList GetRequestedKeys(RubyContext/*!*/ context, object keys) { } IList list = keys as IList; if (list == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Array or nil)", context.GetClassDisplayName(keys)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Array or nil)", context.GetClassDisplayName(keys))); } return list; } @@ -159,7 +159,7 @@ private static KeyValuePair GetPair(RubyContext/*!*/ context, ob Type type = self != null ? self.GetType() : null; // the module can also be included into a Ruby class if (type == null || !type.IsGenericType || type.GetGenericTypeDefinition() != typeof(KeyValuePair<,>)) { - throw RubyExceptions.CreateTypeError("{0} is not a KeyValuePair", context.GetClassDisplayName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0} is not a KeyValuePair", context.GetClassDisplayName(self))); } var unbox = _unboxers.GetOrAdd(type, t => diff --git a/Src/Libraries/Extensions/TypeGroupOps.cs b/Src/Libraries/Extensions/TypeGroupOps.cs index 789547faf..57791b52a 100644 --- a/Src/Libraries/Extensions/TypeGroupOps.cs +++ b/Src/Libraries/Extensions/TypeGroupOps.cs @@ -34,7 +34,7 @@ public static class TypeGroupOps { TypeTracker tracker = self.GetTypeForArity(typeArgs.Length); if (tracker == null) { - throw RubyExceptions.CreateArgumentError("Invalid number of type arguments for '{0}'", self.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Invalid number of type arguments for '{0}'", self.Name)); } Type concreteType; @@ -52,7 +52,7 @@ public static class TypeGroupOps { public static RubyModule/*!*/ Of(RubyContext/*!*/ context, TypeGroup/*!*/ self, int genericArity) { TypeTracker tracker = self.GetTypeForArity(genericArity); if (tracker == null) { - throw RubyExceptions.CreateArgumentError("Type group '{0}' does not contain a type of generic arity {1}", self.Name, genericArity); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Type group '{0}' does not contain a type of generic arity {1}", self.Name, genericArity)); } return context.GetModule(tracker.Type); @@ -106,7 +106,7 @@ public static object EachType(RubyContext/*!*/ context, BlockParam/*!*/ block, T private static Type/*!*/ GetNonGenericType(TypeGroup/*!*/ self) { TypeTracker type = self.GetTypeForArity(0); if (type == null) { - throw RubyExceptions.CreateTypeError("type group doesn't include non-generic type"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("type group doesn't include non-generic type")); } return type.Type; @@ -116,7 +116,7 @@ public static object EachType(RubyContext/*!*/ context, BlockParam/*!*/ block, T public static RubyClass/*!*/ GetNonGenericClass(RubyContext/*!*/ context, TypeGroup/*!*/ typeGroup) { Type type = GetNonGenericType(typeGroup); if (type.IsInterface) { - throw RubyExceptions.CreateTypeError("cannot instantiate an interface"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("cannot instantiate an interface")); } return context.GetClass(type); } diff --git a/Src/Libraries/Extensions/TypeOps.cs b/Src/Libraries/Extensions/TypeOps.cs index 6e59d19dd..dc8d0fb74 100644 --- a/Src/Libraries/Extensions/TypeOps.cs +++ b/Src/Libraries/Extensions/TypeOps.cs @@ -27,7 +27,7 @@ public static class TypeOps { [RubyMethod("to_class")] public static RubyClass/*!*/ ToClass(RubyContext/*!*/ context, Type/*!*/ self) { if (self.IsInterface) { - throw RubyExceptions.CreateTypeError("Cannot convert a CLR interface to a Ruby class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot convert a CLR interface to a Ruby class")); } return context.GetClrTypeModule(self) as RubyClass ?? context.GetClass(self); } diff --git a/Src/Libraries/Extensions/TypeTrackerOps.cs b/Src/Libraries/Extensions/TypeTrackerOps.cs index ca6e7ba8c..353700d4c 100644 --- a/Src/Libraries/Extensions/TypeTrackerOps.cs +++ b/Src/Libraries/Extensions/TypeTrackerOps.cs @@ -27,7 +27,7 @@ public static class TypeTrackerOps { [RubyMethod("to_class")] public static RubyClass/*!*/ ToClass(RubyContext/*!*/ context, TypeTracker/*!*/ self) { if (self.Type.IsInterface) { - throw RubyExceptions.CreateTypeError("Cannot convert a CLR interface to a Ruby class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot convert a CLR interface to a Ruby class")); } return context.GetClrTypeModule(self.Type) as RubyClass ?? context.GetClass(self.Type); } diff --git a/Src/Libraries/Fiddle/Fiddle.cs b/Src/Libraries/Fiddle/Fiddle.cs index 9a1c9dc10..992ef2eea 100644 --- a/Src/Libraries/Fiddle/Fiddle.cs +++ b/Src/Libraries/Fiddle/Fiddle.cs @@ -134,7 +134,7 @@ static FiddleOps() { internal static IntPtr Allocate(long size) { if (size < 0) { - throw RubyExceptions.CreateArgumentError("negative size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative size")); } IntPtr result = (_malloc != null) ? _malloc((IntPtr)size) : Marshal.AllocHGlobal((IntPtr)Math.Max(size, 1)); if (result == IntPtr.Zero) { @@ -493,7 +493,7 @@ internal static IntPtr ToAddress(object value) { if (closure != null) { return closure.Address; } - throw RubyExceptions.CreateTypeError("cannot convert to an address"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("cannot convert to an address")); } #endregion diff --git a/Src/Libraries/Fiddle/FiddleCall.cs b/Src/Libraries/Fiddle/FiddleCall.cs index ade7b0df1..d9a45f2b1 100644 --- a/Src/Libraries/Fiddle/FiddleCall.cs +++ b/Src/Libraries/Fiddle/FiddleCall.cs @@ -98,8 +98,8 @@ internal static class NativeCall { case FiddleType.Double: return typeof(double); case FiddleType.Bool: return typeof(byte); default: - throw RubyExceptions.CreateTypeError( - "unknown fiddle type " + type.ToString(System.Globalization.CultureInfo.InvariantCulture)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError( + "unknown fiddle type " + type.ToString(System.Globalization.CultureInfo.InvariantCulture))); } } @@ -145,7 +145,7 @@ internal static bool IsUnsigned(int type) { for (int i = 0; i < argTypes.Length; i++) { native[i] = ClrType(argTypes[i]); if (native[i] == typeof(void)) { - throw RubyExceptions.CreateTypeError("void is not a valid argument type"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("void is not a valid argument type")); } } Type nativeReturn = ClrType(returnType); @@ -214,7 +214,7 @@ private static void EmitArguments(ILGenerator/*!*/ il, int[]/*!*/ argTypes, Type for (int i = 0; i < argTypes.Length; i++) { native[i] = ClrType(argTypes[i]); if (native[i] == typeof(void)) { - throw RubyExceptions.CreateTypeError("void is not a valid argument type"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("void is not a valid argument type")); } } Type nativeReturn = ClrType(returnType); @@ -331,7 +331,7 @@ internal static long ToLong(object value) { if (ptr != null) { return (long)ptr.Address; } - throw RubyExceptions.CreateTypeError("no implicit conversion into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion into Integer")); } internal static double ToDouble(object value) { @@ -347,7 +347,7 @@ internal static double ToDouble(object value) { if (value == null) { return 0.0; } - throw RubyExceptions.CreateTypeError("no implicit conversion into Float"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion into Float")); } /// @@ -435,7 +435,7 @@ internal static long ToPointerArgument(RespondToStorage/*!*/ respondTo, UnaryOpS } } - throw RubyExceptions.CreateTypeError("no implicit conversion into Fiddle::Pointer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion into Fiddle::Pointer")); } /// diff --git a/Src/Libraries/Fiddle/FiddleClosure.cs b/Src/Libraries/Fiddle/FiddleClosure.cs index b3763521c..42e894b86 100644 --- a/Src/Libraries/Fiddle/FiddleClosure.cs +++ b/Src/Libraries/Fiddle/FiddleClosure.cs @@ -97,7 +97,7 @@ internal IntPtr Address { NativeCall.ClrType(returnCode); for (int i = 0; i < self._argTypes.Length; i++) { if (NativeCall.ClrType(self._argTypes[i]) == typeof(void)) { - throw RubyExceptions.CreateTypeError("void is not a valid argument type"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("void is not a valid argument type")); } } @@ -203,7 +203,7 @@ internal static object Dispatch(object closure, object[]/*!*/ args) { } catch (Exception e) { // thrown again from Fiddle::Function#call, which starts its CLR trace over: RubyExceptionData.GetInstance(e).CaptureExceptionTrace(self._context); - _pendingCallbackError = e; + _pendingCallbackError = RubyExceptionData.MarkKept(e); return NativeCall.IsFloating(self._returnType) ? (object)0.0 : (object)0L; } } diff --git a/Src/Libraries/Fiddle/FiddleFunction.cs b/Src/Libraries/Fiddle/FiddleFunction.cs index 7be93a6cc..443982f61 100644 --- a/Src/Libraries/Fiddle/FiddleFunction.cs +++ b/Src/Libraries/Fiddle/FiddleFunction.cs @@ -144,7 +144,7 @@ internal static int ToTypeCode(ConversionStorage/*!*/ fixnumCast, object va if (_typeNames.TryGetValue(name, out code)) { return code; } - throw RubyExceptions.CreateTypeError("unknown type: " + name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("unknown type: " + name)); } return Protocols.CastToFixnum(fixnumCast, value); @@ -153,13 +153,13 @@ internal static int ToTypeCode(ConversionStorage/*!*/ fixnumCast, object va internal static int[]/*!*/ ReadTypes(ConversionStorage/*!*/ fixnumCast, object types) { var list = types as IList; if (list == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion into Array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion into Array")); } var result = new int[list.Count]; for (int i = 0; i < list.Count; i++) { result[i] = ToTypeCode(fixnumCast, list[i]); if (result[i] == FiddleType.Variadic && i != list.Count - 1) { - throw RubyExceptions.CreateArgumentError("TYPE_VARIADIC must be the last argument type"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("TYPE_VARIADIC must be the last argument type")); } } // [TYPE_VOID] is C's f(void): a list of no arguments, not one void argument. @@ -186,7 +186,7 @@ private static void Reinitialize(RubyContext/*!*/ context, ConversionStorage/*!*/ fixnumCast, Functi int fixedCount = self._argTypes.Length - 1; if (args.Length < fixedCount || ((args.Length - fixedCount) % 2) != 0) { - throw RubyExceptions.CreateArgumentError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( String.Format("wrong number of arguments (given {0}, expected {1}+ and type/value pairs after them)", - args.Length, fixedCount)); + args.Length, fixedCount))); } int variadicCount = (args.Length - fixedCount) / 2; @@ -389,8 +389,8 @@ private static void SplitVariadic(ConversionStorage/*!*/ fixnumCast, Functi for (int i = 0; i < variadicCount; i++) { int type = ToTypeCode(fixnumCast, args[fixedCount + i * 2]); if (NativeCall.IsFloating(type)) { - throw RubyExceptions.CreateArgumentError( - "a floating-point variadic argument cannot be passed reliably on IronRuby"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( + "a floating-point variadic argument cannot be passed reliably on IronRuby")); } types[fixedCount + i] = type; values[fixedCount + i] = args[fixedCount + i * 2 + 1]; diff --git a/Src/Libraries/Fiddle/FiddleHandle.cs b/Src/Libraries/Fiddle/FiddleHandle.cs index 1944075db..82984e980 100644 --- a/Src/Libraries/Fiddle/FiddleHandle.cs +++ b/Src/Libraries/Fiddle/FiddleHandle.cs @@ -75,7 +75,7 @@ private static void Reinitialize(Handle/*!*/ self, object library, int flags) { MutableString name = library as MutableString; if (library != null && name == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion into String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion into String")); } if (name == null) { diff --git a/Src/Libraries/Fiddle/FiddlePointer.cs b/Src/Libraries/Fiddle/FiddlePointer.cs index aa58e1d56..99ebc7a25 100644 --- a/Src/Libraries/Fiddle/FiddlePointer.cs +++ b/Src/Libraries/Fiddle/FiddlePointer.cs @@ -197,7 +197,7 @@ public static object Malloc(BlockParam block, RubyClass/*!*/ self, [DefaultProto [DefaultParameterValue(null)]object freeFunc) { if (block != null && freeFunc == null) { - throw RubyExceptions.CreateArgumentError("a free function must be supplied to Fiddle::Pointer.malloc with a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("a free function must be supplied to Fiddle::Pointer.malloc with a block")); } var result = new Pointer(self); @@ -286,7 +286,7 @@ public static object WriteMemory(RubyClass/*!*/ self, object address, [NotNull]M internal static MutableString/*!*/ ReadBytes(IntPtr address, int length) { if (address == IntPtr.Zero) { - throw RubyExceptions.CreateArgumentError("NULL pointer given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("NULL pointer given")); } byte[] bytes = new byte[length]; if (length > 0) { @@ -308,7 +308,7 @@ private static int CStringLength(IntPtr address) { public static MutableString/*!*/ ToS(Pointer/*!*/ self) { self.CheckLive(); if (self._address == IntPtr.Zero) { - throw RubyExceptions.CreateArgumentError("NULL pointer given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("NULL pointer given")); } return ReadBytes(self._address, CStringLength(self._address)); } @@ -334,7 +334,7 @@ private static int CStringLength(IntPtr address) { private void CheckIndex(long index, long count) { if (index < 0 || count < 0 || (_size > 0 && index + count > _size)) { - throw RubyExceptions.CreateIndexError("index " + index.ToString(CultureInfo.InvariantCulture) + " out of pointer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index " + index.ToString(CultureInfo.InvariantCulture) + " out of pointer")); } if (_address == IntPtr.Zero) { // #[] and #[]= say DLError where #to_s and #to_str say ArgumentError; @@ -412,7 +412,7 @@ public static object SetBytes(Pointer/*!*/ self, [DefaultProtocol]int start, [De public static Pointer/*!*/ Dereference(RubyContext/*!*/ context, Pointer/*!*/ self) { self.CheckLive(); if (self._address == IntPtr.Zero) { - throw RubyExceptions.CreateArgumentError("NULL pointer given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("NULL pointer given")); } return Create(context, Marshal.ReadIntPtr(self._address), 0, IntPtr.Zero); } diff --git a/Src/Libraries/Iconv/Iconv.cs b/Src/Libraries/Iconv/Iconv.cs index 1f8cc4e51..0b35a1b06 100644 --- a/Src/Libraries/Iconv/Iconv.cs +++ b/Src/Libraries/Iconv/Iconv.cs @@ -90,7 +90,7 @@ private void ResetByteOrderMark() { [DefaultProtocol, NotNull, DefaultParameterValue(-1)]int length) { if (self._isClosed) { - throw RubyExceptions.CreateArgumentError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("closed stream")); } if (str == null) { diff --git a/Src/Libraries/Markly/Markly.cs b/Src/Libraries/Markly/Markly.cs index db4881367..ffe67848e 100644 --- a/Src/Libraries/Markly/Markly.cs +++ b/Src/Libraries/Markly/Markly.cs @@ -177,14 +177,14 @@ internal static void EnsureInitialized() { try { version = CmarkNative.markly_shim_version(); } catch (Exception e) when (e is DllNotFoundException || e is EntryPointNotFoundException || e is BadImageFormatException) { - throw RubyExceptions.CreateLoadError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError( "cannot load such file -- markly/markly (IronRuby runs markly's cmark-gfm as a native library, " + - "libmarkly_cmark, and it was not found: build it with Util/build-markly.sh; " + e.Message + ")"); + "libmarkly_cmark, and it was not found: build it with Util/build-markly.sh; " + e.Message + ")")); } if (version != CmarkNative.ShimVersion) { - throw RubyExceptions.CreateLoadError(String.Format( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(String.Format( "cannot load such file -- markly/markly (libmarkly_cmark is shim version {0}, this IronRuby expects {1}: " + - "rebuild it with Util/build-markly.sh)", version, CmarkNative.ShimVersion)); + "rebuild it with Util/build-markly.sh)", version, CmarkNative.ShimVersion))); } CmarkNative.markly_shim_init(); _initialized = true; @@ -235,7 +235,7 @@ internal static void EnsureInitialized() { internal static byte[]/*!*/ CString(MutableString/*!*/ str) { byte[] bytes = str.ToByteArray(); if (Array.IndexOf(bytes, (byte)0) >= 0) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } return Terminated(bytes); } @@ -258,8 +258,8 @@ internal static int CheckInt(RubyContext/*!*/ context, object value) { } else { throw WrongArgumentType(context, value, "Integer"); } - throw RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", - big, big.Sign < 0 ? "small" : "big")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", + big, big.Sign < 0 ? "small" : "big"))); } /// Check_Type(value, T_SYMBOL): the symbol's name. @@ -335,7 +335,7 @@ private IntPtr Handle { get { if (_parser == IntPtr.Zero) { // markly.c would hand cmark a NULL parser here and crash. - throw RubyExceptions.CreateTypeError("uninitialized Markly::Parser"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Markly::Parser")); } return _parser; } @@ -365,7 +365,7 @@ public static object Enable(RubyContext/*!*/ context, Parser/*!*/ self, object e IntPtr parser = self.Handle; IntPtr ext = FindExtension(name); if (ext == IntPtr.Zero) { - throw RubyExceptions.CreateArgumentError(String.Format("extension {0} not found", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("extension {0} not found", name))); } CmarkNative.cmark_parser_attach_syntax_extension(parser, ext); GC.KeepAlive(self); @@ -375,7 +375,7 @@ public static object Enable(RubyContext/*!*/ context, Parser/*!*/ self, object e [RubyMethod("parse")] public static object Parse(RubyContext/*!*/ context, Parser/*!*/ self, [DefaultProtocol]MutableString text) { if (text == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into String")); } IntPtr parser = self.Handle; byte[] bytes = text.ToByteArray(); @@ -524,7 +524,7 @@ internal Node(RubyClass/*!*/ rubyClass, IntPtr pointer, Tree/*!*/ tree) : base(r } protected override RubyObject/*!*/ CreateInstance() { - throw RubyExceptions.CreateAllocatorUndefinedError(ImmediateClass.NominalClass); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateAllocatorUndefinedError(ImmediateClass.NominalClass)); } // The neighbour is read, and wrapped in the tree that owns self, under Tree.Lock - as Insert, @@ -1009,13 +1009,13 @@ public static bool SetTasklistItemChecked(Node/*!*/ self, object itemChecked) { for (int i = 0; i < result.Length; i++) { var sym = extensions[i] as RubySymbol; if (sym == null) { - throw RubyExceptions.CreateTypeError(String.Format("extension names should be Symbols; got a {0}", - context.GetClassName(extensions[i]))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("extension names should be Symbols; got a {0}", + context.GetClassName(extensions[i])))); } string name = sym.ToString(); IntPtr ext = FindExtension(name); if (ext == IntPtr.Zero) { - throw RubyExceptions.CreateArgumentError(String.Format("extension {0} not found\n", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("extension {0} not found\n", name))); } result[i] = ext; } @@ -1047,7 +1047,7 @@ public static bool SetTasklistItemChecked(Node/*!*/ self, object itemChecked) { /// rb_scan_args(argc, argv, "11", &options, &width), width defaulting to 120. private static void ScanRenderArgs(RubyContext/*!*/ context, object[]/*!*/ args, out int options, out int width) { if (args.Length < 1 || args.Length > 2) { - throw RubyExceptions.CreateArgumentError(String.Format("wrong number of arguments (given {0}, expected 1..2)", args.Length)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("wrong number of arguments (given {0}, expected 1..2)", args.Length))); } width = 120; if (args.Length == 2 && args[1] != null) { diff --git a/Src/Libraries/MessagePack/MessagePack.cs b/Src/Libraries/MessagePack/MessagePack.cs index d7947cd9d..31db8092d 100644 --- a/Src/Libraries/MessagePack/MessagePack.cs +++ b/Src/Libraries/MessagePack/MessagePack.cs @@ -117,7 +117,7 @@ internal static bool OptionTrue(RubyContext/*!*/ context, Hash options, string/* return str; } } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj))); } /// NUM2INT. @@ -130,7 +130,7 @@ internal static int ToInt(RubyContext/*!*/ context, object obj) { if (big >= Int32.MinValue && big <= Int32.MaxValue) { return (int)big; } - throw RubyExceptions.CreateRangeError("integer {0} too big to convert to 'int'", big); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("integer {0} too big to convert to 'int'", big)); } if (obj is long) { return ToInt(context, (BigInteger)(long)obj); @@ -138,20 +138,20 @@ internal static int ToInt(RubyContext/*!*/ context, object obj) { if (obj is double) { double d = (double)obj; if (Double.IsNaN(d) || d < Int32.MinValue || d >= (double)Int32.MaxValue + 1) { - throw RubyExceptions.CreateRangeError("float {0} out of range of integer", d); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("float {0} out of range of integer", d)); } return (int)d; } if (obj == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion from nil to integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion from nil to integer")); } if (obj is bool) { - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj))); } if (RespondTo(context, obj, "to_int")) { return ToInt(context, Call(context, obj, "to_int")); } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj))); } /// NUM2UINT: negative values down to INT_MIN wrap around, as they do in C. @@ -172,7 +172,7 @@ internal static int ToSize(RubyContext/*!*/ context, object obj) { } int value = ToInt(context, obj); if (value < 0) { - throw RubyExceptions.CreateRangeError("integer {0} too small to convert to 'unsigned long'", value); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("integer {0} too small to convert to 'unsigned long'", value)); } return value; } @@ -192,19 +192,19 @@ internal static double ToDouble(RubyContext/*!*/ context, object obj) { return (long)obj; } if (obj == null) { - throw RubyExceptions.CreateTypeError("can't convert nil into Float"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert nil into Float")); } if (obj is bool) { - throw RubyExceptions.CreateTypeError("can't convert {0} into Float", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into Float", TypeName(context, obj))); } if (obj is MutableString) { - throw RubyExceptions.CreateTypeError("no implicit conversion to float from string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion to float from string")); } object f = Call(context, obj, "to_f"); if (f is double) { return (double)f; } - throw RubyExceptions.CreateTypeError("can't convert {0} into Float", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into Float", TypeName(context, obj))); } internal static Exception/*!*/ SignedCharRange(object value) { @@ -455,7 +455,7 @@ public UnknownExtTypeError(string message, Exception inner) : base(message ?? "M ((RubyModule)mp).TryGetConstant(null, name, out cls) && cls is RubyClass) { return (RubyClass)cls; } - throw RubyExceptions.CreateNameError("uninitialized constant MessagePack::" + name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("uninitialized constant MessagePack::" + name)); } internal static RubyArray/*!*/ NewArray(params object[]/*!*/ items) { @@ -469,7 +469,7 @@ public UnknownExtTypeError(string message, Exception inner) : base(message ?? "M internal static object CallProc(object proc, object arg) { var p = proc as Proc; if (p == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Proc)", proc == null ? "nil" : proc.GetType().Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Proc)", proc == null ? "nil" : proc.GetType().Name)); } return p.Call(null, arg); } @@ -477,7 +477,7 @@ internal static object CallProc(object proc, object arg) { internal static object CallProc(object proc, object arg1, object arg2) { var p = proc as Proc; if (p == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Proc)", proc == null ? "nil" : proc.GetType().Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Proc)", proc == null ? "nil" : proc.GetType().Name)); } return p.Call(null, arg1, arg2); } @@ -565,10 +565,10 @@ public static object Initialize(RubyContext/*!*/ context, BufferObject/*!*/ self options = args[1] as Hash; if (options == null) { // sic: upstream names the class of the io here - throw RubyExceptions.CreateArgumentError("expected Hash but found {0}.", context.GetClassName(io)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("expected Hash but found {0}.", context.GetClassName(io))); } } else { - throw RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..1)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..1)", args.Length)); } self.Core.SetOptions(io, options); @@ -674,7 +674,7 @@ private static MutableString CheckOut(RubyContext/*!*/ context, object @out) { str = Sites.Call(context, @out, "to_str") as MutableString; } if (str == null) { - throw RubyExceptions.CreateTypeError("instance of String needed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("instance of String needed")); } return str; } @@ -705,7 +705,7 @@ public static object Skip(RubyContext/*!*/ context, BufferObject/*!*/ self, obje [RubyMethod("read_all")] public static MutableString/*!*/ ReadAll(RubyContext/*!*/ context, BufferObject/*!*/ self, params object[]/*!*/ args) { if (args.Length > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length)); } BufferCore b = self.Core; MutableString @out = args.Length == 2 ? CheckOut(context, args[1]) : null; @@ -727,7 +727,7 @@ public static object Skip(RubyContext/*!*/ context, BufferObject/*!*/ self, obje [RubyMethod("read")] public static MutableString Read(RubyContext/*!*/ context, BufferObject/*!*/ self, params object[]/*!*/ args) { if (args.Length > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length)); } BufferCore b = self.Core; MutableString @out = args.Length == 2 ? CheckOut(context, args[1]) : null; @@ -840,7 +840,7 @@ long IMemorySized.ExtraMemorySize { [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static object Initialize(RubyContext/*!*/ context, PackerObject/*!*/ self, params object[]/*!*/ args) { if (args.Length > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length)); } object io = args.Length >= 1 ? args[0] : null; object options = args.Length == 2 ? args[1] : null; @@ -979,8 +979,8 @@ public static bool IsCompatibilityMode(PackerObject/*!*/ self) { } object rbType = ext[0]; if (!(rbType is int)) { - throw RubyExceptions.CreateRangeError(String.Format("integer {0} too big to convert to `signed char'", - context.Inspect(rbType).ToString())); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too big to convert to `signed char'", + context.Inspect(rbType).ToString()))); } int type = (int)rbType; if (type < -128 || type > 127) { @@ -1012,7 +1012,7 @@ public static bool IsCompatibilityMode(PackerObject/*!*/ self) { public static PackerObject/*!*/ WriteFloat32(RubyContext/*!*/ context, PackerObject/*!*/ self, object value) { if (!(value is int || value is double || value is BigInteger || value is long) && !context.IsKindOf(value, context.GetClass(typeof(Numeric)))) { - throw RubyExceptions.CreateArgumentError("Expected numeric"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Expected numeric")); } self.WriteSingle((float)Sites.ToDouble(context, value)); return self; @@ -1190,7 +1190,7 @@ internal void WriteBignum(BigInteger v) { } } if (v > UInt64.MaxValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long long'")); } WriteU64((ulong)v); } else { @@ -1201,7 +1201,7 @@ internal void WriteBignum(BigInteger v) { } } if (v < _longMin) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long long'")); } WriteLong((long)v); } @@ -1565,11 +1565,11 @@ public static object Initialize(RubyContext/*!*/ context, UnpackerObject/*!*/ se } else if (args.Length == 2) { io = args[0]; if (args[1] != null && !(args[1] is Hash)) { - throw RubyExceptions.CreateArgumentError("expected Hash but found {0}.", context.GetClassName(args[1])); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("expected Hash but found {0}.", context.GetClassName(args[1]))); } options = (Hash)args[1]; } else { - throw RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0..2)", args.Length)); } self.BufferRef = null; @@ -1805,7 +1805,7 @@ private object CallProtected(object proc, object arg, out bool raised) { raised = true; // thrown again once the unpacker unwinds, which starts its CLR trace over: RubyExceptionData.GetInstance(e).CaptureExceptionTrace(Context); - _raised = e; + _raised = RubyExceptionData.MarkKept(e); return null; } } @@ -2308,7 +2308,7 @@ public static object Initialize(FactoryObject/*!*/ self, params object[]/*!*/ ar self.Pkrg = new PackerRegistry(); self.HasSymbolExtType = false; if (args.Length != 0) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments ({0} for 0)", args.Length)); } return null; } @@ -2371,7 +2371,7 @@ public static object RegisterTypeInternal(RubyContext/*!*/ context, FactoryObjec } var mod = module as RubyModule; if (mod == null) { - throw RubyExceptions.CreateArgumentError("expected Module/Class but found {0}.", context.GetClassName(module)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("expected Module/Class but found {0}.", context.GetClassName(module))); } int flags = 0; @@ -2411,7 +2411,7 @@ public static object RegisterTypeInternal(RubyContext/*!*/ context, FactoryObjec if (ReferenceEquals(mod, context.IntegerClass)) { self.HasBigintExtType = true; } else { - throw RubyExceptions.CreateArgumentError("oversized_integer_extension: true is only for Integer class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("oversized_integer_extension: true is only for Integer class")); } } if (Sites.OptionTrue(context, opts, "recursive")) { diff --git a/Src/Libraries/Nio4r/Nio4r.cs b/Src/Libraries/Nio4r/Nio4r.cs index eb7a0929f..63625400f 100644 --- a/Src/Libraries/Nio4r/Nio4r.cs +++ b/Src/Libraries/Nio4r/Nio4r.cs @@ -48,16 +48,16 @@ public static class NioModule { internal static int ToInterest(RubyContext/*!*/ context, object interest, string/*!*/ what) { var symbol = interest as RubySymbol; if (symbol == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected Symbol)", - context.GetClassDisplayName(interest)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected Symbol)", + context.GetClassDisplayName(interest))); } switch (symbol.ToString()) { case "r": return InterestRead; case "w": return InterestWrite; case "rw": return InterestRead | InterestWrite; default: - throw RubyExceptions.CreateArgumentError("invalid {0} type {1} (must be :r, :w, or :rw)", - what, context.Inspect(interest).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid {0} type {1} (must be :r, :w, or :rw)", + what, context.Inspect(interest).ToString())); } } @@ -85,10 +85,10 @@ internal static object ToSymbol(RubyContext/*!*/ context, int interests) { if (io != null) { return io; } - throw RubyExceptions.CreateTypeError("can't convert {0} to IO ({0}#to_io gives {1})", - context.GetClassDisplayName(obj), context.GetClassDisplayName(converted)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to IO ({0}#to_io gives {1})", + context.GetClassDisplayName(obj), context.GetClassDisplayName(converted))); } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into IO", context.GetClassDisplayName(obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into IO", context.GetClassDisplayName(obj))); } #region Selector @@ -163,7 +163,7 @@ public static object Initialize(RubyContext/*!*/ context, Selector/*!*/ self, [O if (backend != null && !(backend is Missing)) { var symbol = backend as RubySymbol; if (symbol == null || Array.IndexOf(SupportedBackends, symbol.ToString()) < 0) { - throw RubyExceptions.CreateArgumentError("unsupported backend: {0}", context.Inspect(backend).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unsupported backend: {0}", context.Inspect(backend).ToString())); } name = symbol.ToString(); } @@ -188,7 +188,7 @@ public static object Initialize(RubyContext/*!*/ context, Selector/*!*/ self, [O private void RequireOpen() { if (_closed) { - throw RubyExceptions.CreateIOError("selector is closed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("selector is closed")); } } @@ -232,7 +232,7 @@ internal void Unlock() { try { self.RequireOpen(); if (io != null && self._selectables.ContainsKey(io)) { - throw RubyExceptions.CreateArgumentError("this IO is already registered with selector"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("this IO is already registered with selector")); } var monitor = new Monitor(context.GetClass(typeof(Monitor))); @@ -319,7 +319,7 @@ public static object Select(ConversionStorage/*!*/ floatConversion, Bloc if (timeout != null && !(timeout is Missing)) { double seconds = Protocols.CastToFloat(floatConversion, timeout); if (seconds < 0) { - throw RubyExceptions.CreateArgumentError("time interval must be positive"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must be positive")); } double ms = Math.Ceiling(seconds * 1000); milliseconds = (Double.IsNaN(ms) || ms >= Int32.MaxValue) ? Timeout.Infinite : (int)ms; @@ -1027,7 +1027,7 @@ public MarkUnsetError(string message, Exception inner) : base(message ?? "MarkUn [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static object Initialize(ByteBuffer/*!*/ self, [DefaultProtocol]int capacity) { if (capacity < 0) { - throw RubyExceptions.CreateArgumentError("negative buffer size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative buffer size")); } self._capacity = capacity; self._buffer = new byte[capacity]; @@ -1052,10 +1052,10 @@ public static int GetPosition(ByteBuffer/*!*/ self) { [RubyMethod("position=")] public static object SetPosition(ByteBuffer/*!*/ self, [DefaultProtocol]int position) { if (position < 0) { - throw RubyExceptions.CreateArgumentError("negative position given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative position given")); } if (position > self._limit) { - throw RubyExceptions.CreateArgumentError("specified position exceeds limit"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("specified position exceeds limit")); } self._position = position; if (self._mark > self._position) { @@ -1072,10 +1072,10 @@ public static int GetLimit(ByteBuffer/*!*/ self) { [RubyMethod("limit=")] public static object SetLimit(ByteBuffer/*!*/ self, [DefaultProtocol]int limit) { if (limit < 0) { - throw RubyExceptions.CreateArgumentError("negative limit given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative limit given")); } if (limit > self._capacity) { - throw RubyExceptions.CreateArgumentError("specified limit exceeds capacity"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("specified limit exceeds capacity")); } self._limit = limit; if (self._position > limit) { @@ -1112,7 +1112,7 @@ public static bool IsFull(ByteBuffer/*!*/ self) { count = Protocols.CastToFixnum(fixnumCast, length); } if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative length given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative length given")); } if (count > self._limit - self._position) { throw new UnderflowError("not enough data in buffer"); @@ -1126,10 +1126,10 @@ public static bool IsFull(ByteBuffer/*!*/ self) { [RubyMethod("[]")] public static int Fetch(ByteBuffer/*!*/ self, [DefaultProtocol]int index) { if (index < 0) { - throw RubyExceptions.CreateArgumentError("negative index given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative index given")); } if (index >= self._limit) { - throw RubyExceptions.CreateArgumentError("specified index exceeds limit"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("specified index exceeds limit")); } return self._buffer[index]; } @@ -1241,7 +1241,7 @@ public static int WriteTo(RespondToStorage/*!*/ respondToStorage, [RubyMethod("each")] public static object Each(BlockParam block, ByteBuffer/*!*/ self) { if (block == null) { - throw RubyExceptions.CreateArgumentError("no block given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no block given")); } for (int i = 0; i < self._limit; i++) { object blockResult; diff --git a/Src/Libraries/Oj/Oj.cs b/Src/Libraries/Oj/Oj.cs index 67bd5371a..aaa76c9e9 100644 --- a/Src/Libraries/Oj/Oj.cs +++ b/Src/Libraries/Oj/Oj.cs @@ -123,7 +123,7 @@ internal static bool RespondTo(RubyContext/*!*/ context, object target, string/* return str; } } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj))); } internal static int ToInt(RubyContext/*!*/ context, object obj) { @@ -135,12 +135,12 @@ internal static int ToInt(RubyContext/*!*/ context, object obj) { if (big >= Int32.MinValue && big <= Int32.MaxValue) { return (int)big; } - throw RubyExceptions.CreateRangeError("integer {0} too big to convert to 'int'", big); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("integer {0} too big to convert to 'int'", big)); } if (obj is double) { return (int)(double)obj; } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj))); } internal static double ToDouble(RubyContext/*!*/ context, object obj) { @@ -157,7 +157,7 @@ internal static double ToDouble(RubyContext/*!*/ context, object obj) { if (f is double) { return (double)f; } - throw RubyExceptions.CreateTypeError("can't convert {0} into Float", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into Float", TypeName(context, obj))); } } @@ -396,7 +396,7 @@ private static char LoadMode(RubyContext/*!*/ context, object[]/*!*/ args, bool [RubyMethod("load", RubyMethodAttributes.PublicSingleton)] public static object Load(RubyContext/*!*/ context, BlockParam block, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("Wrong number of arguments to load()."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Wrong number of arguments to load().")); } switch (LoadMode(context, args, true)) { case OjMode.Strict: @@ -416,7 +416,7 @@ public static object Load(RubyContext/*!*/ context, BlockParam block, RubyModule [RubyMethod("load_file", RubyMethodAttributes.PublicSingleton)] public static object LoadFile(RubyContext/*!*/ context, BlockParam block, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("Wrong number of arguments to load()."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Wrong number of arguments to load().")); } string path = Sites.StringValue(context, args[0]).ToString(); char mode = LoadMode(context, args, false); @@ -424,9 +424,9 @@ public static object LoadFile(RubyContext/*!*/ context, BlockParam block, RubyMo try { content = MutableString.CreateBinary(File.ReadAllBytes(path), RubyEncoding.UTF8); } catch (FileNotFoundException) { - throw RubyExceptions.CreateENOENT(path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(path)); } catch (DirectoryNotFoundException) { - throw RubyExceptions.CreateENOENT(path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(path)); } var newArgs = (object[])args.Clone(); newArgs[0] = content; @@ -464,7 +464,7 @@ public static object SafeLoad(RubyContext/*!*/ context, RubyModule/*!*/ self, ob [RubyMethod("strict_load", RubyMethodAttributes.PublicSingleton)] public static object StrictLoad(RubyContext/*!*/ context, BlockParam block, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("Wrong number of arguments to parse."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Wrong number of arguments to parse.")); } return StrictParse(context, block, args); } @@ -472,7 +472,7 @@ public static object StrictLoad(RubyContext/*!*/ context, BlockParam block, Ruby [RubyMethod("compat_load", RubyMethodAttributes.PublicSingleton)] public static object CompatLoad(RubyContext/*!*/ context, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("Wrong number of arguments to parse."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Wrong number of arguments to parse.")); } return CompatParse(context, args, false); } @@ -511,7 +511,7 @@ public static object WabLoad(RubyModule/*!*/ self, params object[]/*!*/ args) { [RubyMethod("dump", RubyMethodAttributes.PublicSingleton)] public static MutableString/*!*/ Dump(RubyContext/*!*/ context, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1)."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1).")); } Options copts = State(context).Defaults.Clone(); if (OjMode.Compat == copts.Mode) { @@ -537,10 +537,10 @@ internal static void ParseMimicDumpOptions(RubyContext/*!*/ context, object ropt } else if (ropts == null) { return; } else { - throw RubyExceptions.CreateArgumentError("options must be a hash."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("options must be a hash.")); } if (hash == null) { - throw RubyExceptions.CreateArgumentError("options must be a hash."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("options must be a hash.")); } } Func get = name => { @@ -597,7 +597,7 @@ internal static void ParseMimicDumpOptions(RubyContext/*!*/ context, object ropt } byte[] bytes = str.ToByteArray(); if (16 <= bytes.Length) { - throw RubyExceptions.CreateArgumentError(String.Format("{0} string is limited to 16 characters.", what)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("{0} string is limited to 16 characters.", what))); } int nul = Array.IndexOf(bytes, (byte)0); if (nul >= 0) { @@ -609,7 +609,7 @@ internal static void ParseMimicDumpOptions(RubyContext/*!*/ context, object ropt [RubyMethod("to_json", RubyMethodAttributes.PublicSingleton)] public static MutableString/*!*/ ToJson(RubyContext/*!*/ context, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1)."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1).")); } Options copts = State(context).Defaults.Clone(); copts.EscapeMode = Esc.JX; @@ -642,9 +642,9 @@ public static object ToFile(RubyContext/*!*/ context, RubyModule/*!*/ self, para try { File.WriteAllBytes(path, bytes); } catch (IOException e) { - throw RubyExceptions.CreateIOError(e.Message); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError(e.Message)); } catch (UnauthorizedAccessException e) { - throw RubyExceptions.CreateIOError(e.Message); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError(e.Message)); } return null; } @@ -660,7 +660,7 @@ public static object ToStream(RubyContext/*!*/ context, RubyModule/*!*/ self, pa if (Sites.RespondTo(context, stream, "write")) { Sites.Call(context, stream, "write", MutableString.CreateBinary(bytes, RubyEncoding.Binary)); } else { - throw RubyExceptions.CreateArgumentError("to_stream() expected an IO Object."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("to_stream() expected an IO Object.")); } return null; } @@ -671,7 +671,7 @@ public static object ToStream(RubyContext/*!*/ context, RubyModule/*!*/ self, pa internal static MutableString/*!*/ MimicGenerateCore(RubyContext/*!*/ context, object[]/*!*/ args, Options/*!*/ copts) { if (0 == args.Length) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (0))"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (0))")); } OjState state = State(context); copts.NanDump = Nan.Raise; @@ -710,7 +710,7 @@ public static object ToStream(RubyContext/*!*/ context, RubyModule/*!*/ self, pa public static MutableString/*!*/ PrettyGenerate(RubyContext/*!*/ context, RubyModule/*!*/ self, params object[]/*!*/ args) { OjState state = State(context); if (0 == args.Length) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (0))"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (0))")); } Hash h; if (1 == args.Length || args[1] == null) { @@ -718,7 +718,7 @@ public static object ToStream(RubyContext/*!*/ context, RubyModule/*!*/ self, pa } else { h = args[1] as Hash; if (h == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Hash)", Sites.TypeName(context, args[1]))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Hash)", Sites.TypeName(context, args[1])))); } } Action def = (name, value) => { @@ -771,7 +771,7 @@ private static void SetToJson(RubyContext/*!*/ context, object[]/*!*/ args, bool if (on) { object cls; if (!context.ObjectClass.TryGetConstant(null, name, out cls)) { - throw RubyExceptions.CreateNameError(String.Format("uninitialized constant {0}", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("uninitialized constant {0}", name))); } state.SetCodeClass(name, cls); state.ActiveCodes.Add(name); @@ -802,7 +802,7 @@ private static void SetToJson(RubyContext/*!*/ context, object[]/*!*/ args, bool object cls; if (on) { if (!context.ObjectClass.TryGetConstant(null, name, out cls)) { - throw RubyExceptions.CreateNameError(String.Format("uninitialized constant {0}", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("uninitialized constant {0}", name))); } state.SetCodeClass(name, cls); } else { @@ -916,7 +916,7 @@ private static void MimicWalk(RubyContext/*!*/ context, object obj, object proc, [RubyMethod("__mimic_load", RubyMethodAttributes.PublicSingleton)] public static object MimicLoad(RubyContext/*!*/ context, BlockParam block, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("Wrong number of arguments to parse."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Wrong number of arguments to parse.")); } object obj = CompatParse(context, args, true); object p = null; @@ -936,7 +936,7 @@ public static object MimicLoad(RubyContext/*!*/ context, BlockParam block, RubyM [RubyMethod("__mimic_dump_load", RubyMethodAttributes.PublicSingleton)] public static object MimicDumpLoad(RubyContext/*!*/ context, BlockParam block, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1)")); } if (args[0] is MutableString) { return MimicLoad(context, block, self, args); @@ -948,7 +948,7 @@ public static object MimicDumpLoad(RubyContext/*!*/ context, BlockParam block, R public static object MimicParse(RubyContext/*!*/ context, RubyModule/*!*/ self, object bang, params object[]/*!*/ args) { OjState state = State(context); if (args.Length < 1 || args.Length > 2) { - throw RubyExceptions.CreateArgumentError(String.Format("wrong number of arguments (given {0}, expected 1..2)", args.Length)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("wrong number of arguments (given {0}, expected 1..2)", args.Length))); } object ropts = args.Length > 1 ? args[1] : null; var pi = new ParseInfo(context, state.Defaults.Clone()); @@ -968,7 +968,7 @@ public static object MimicParse(RubyContext/*!*/ context, RubyModule/*!*/ self, if (ropts != null) { var hash = ropts as Hash; if (hash == null) { - throw RubyExceptions.CreateArgumentError("options must be a hash."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("options must be a hash.")); } foreach (var pair in OjDump.Snapshot(hash)) { var k = CustomStringDictionary.ObjToNull(pair.Key) as RubySymbol; @@ -1018,7 +1018,7 @@ public static object MimicParse(RubyContext/*!*/ context, RubyModule/*!*/ self, } pi.Opts.ParseMatchString(context, hash); if (YesNo.Yes == pi.Opts.CreateOk && YesNo.Yes == pi.Opts.SymKey) { - throw RubyExceptions.CreateArgumentError(":symbolize_names and :create_additions can not both be true."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":symbolize_names and :create_additions can not both be true.")); } } return OjParse.Parse(pi, new[] { args[0] }, null, false); @@ -1041,7 +1041,7 @@ public static object MimicSetCreateId(RubyContext/*!*/ context, RubyModule/*!*/ } else { byte[] bytes = Sites.StringValue(context, id).ToByteArray(); if (Array.IndexOf(bytes, (byte)0) >= 0) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } state.Defaults.CreateId = bytes; } @@ -1113,7 +1113,7 @@ public static class RailsOps { [RubyMethod("encode", RubyMethodAttributes.PublicSingleton)] public static MutableString/*!*/ Encode(RubyContext/*!*/ context, RubyModule/*!*/ self, params object[]/*!*/ args) { if (1 > args.Length) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1)."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (0 for 1).")); } return OjRails.Encode(context, args[0], null, State(context).Defaults, Rest(args, 1)); } diff --git a/Src/Libraries/Oj/OjDump.cs b/Src/Libraries/Oj/OjDump.cs index 7b59e142d..12e3b334e 100644 --- a/Src/Libraries/Oj/OjDump.cs +++ b/Src/Libraries/Oj/OjDump.cs @@ -932,9 +932,9 @@ private static void DumpStrictHash(Out/*!*/ output, Hash/*!*/ obj, int depth, bo object value = pair.Value; int d = output.Depth; if (!(key is MutableString) && !(key is RubySymbol)) { - throw RubyExceptions.CreateTypeError(String.Format( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format( "In :strict and :null mode all Hash keys must be Strings or Symbols, not {0}.\n", - output.Context.GetClassOf(key).Name)); + output.Context.GetClassOf(key).Name))); } if (output.OmitNil && value == null) { continue; @@ -1175,7 +1175,7 @@ private static void DumpCompatBignum(Out/*!*/ output, object obj) { } else { rs = Sites.Call(output.Context, obj, "to_s") as MutableString; if (rs == null) { - throw RubyExceptions.CreateTypeError("wrong argument type (expected String)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type (expected String)")); } } bool dumpAsString = output.Opts.IntRangeMin != 0 || output.Opts.IntRangeMax != 0; diff --git a/Src/Libraries/Oj/OjOptions.cs b/Src/Libraries/Oj/OjOptions.cs index 67bcf4dec..d377ec8aa 100644 --- a/Src/Libraries/Oj/OjOptions.cs +++ b/Src/Libraries/Oj/OjOptions.cs @@ -238,7 +238,7 @@ private bool SetYesNo(RubyContext/*!*/ context, string/*!*/ name, object value) return false; } if (v == '?') { - throw RubyExceptions.CreateArgumentError(String.Format("{0} must be true, false, or nil.", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("{0} must be true, false, or nil.", name))); } switch (name) { case "circular": Circular = v; break; @@ -273,7 +273,7 @@ private bool SetYesNo(RubyContext/*!*/ context, string/*!*/ name, object value) } byte[] bytes = str.ToByteArray(); if (bytes.Length >= limit) { - throw RubyExceptions.CreateArgumentError(String.Format("{0} string is limited to {1} characters.", what, limit)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("{0} string is limited to {1} characters.", what, limit))); } // strcpy stops at the first NUL int nul = Array.IndexOf(bytes, (byte)0); @@ -302,7 +302,7 @@ private static string MakeOnlyValue(RubyContext/*!*/ context, object v) { } else if (x is MutableString) { names.Add(((MutableString)x).ToString()); } else { - throw RubyExceptions.CreateArgumentError(":only and :except must be nil, symbol, string, or array."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":only and :except must be nil, symbol, string, or array.")); } } int size = 0; @@ -324,7 +324,7 @@ private static string MakeOnlyValue(RubyContext/*!*/ context, object v) { if (v is RubySymbol) { return ":" + ((RubySymbol)v).ToString() + ":"; } - throw RubyExceptions.CreateArgumentError(":only and zzz :except must be nil, symbol, string, or array."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":only and zzz :except must be nil, symbol, string, or array.")); } private static void ValidateFloatFormat(string/*!*/ str) { @@ -338,7 +338,7 @@ private static void ValidateFloatFormat(string/*!*/ str) { continue; } if (1 < ++cnt) { - throw RubyExceptions.CreateArgumentError(":float_format must not have more than one directive."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":float_format must not have more than one directive.")); } for (; s < str.Length && "-+ #0".IndexOf(str[s]) >= 0; s++) { } @@ -352,7 +352,7 @@ private static void ValidateFloatFormat(string/*!*/ str) { s++; } if (str.Length <= s || "aAeEfgG".IndexOf(str[s]) < 0) { - throw RubyExceptions.CreateArgumentError(":float_format directive must be one of aAeEfgG and take no argument of its own."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":float_format directive must be one of aAeEfgG and take no argument of its own.")); } } } @@ -374,24 +374,24 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (v is int) { IndentStr = Empty; if (16 < (int)v) { - throw RubyExceptions.CreateArgumentError("indent is limited to 16 characters."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("indent is limited to 16 characters.")); } Indent = (int)v; } else if (v is MutableString) { byte[] bytes = ((MutableString)v).ToByteArray(); if (16 <= bytes.Length) { - throw RubyExceptions.CreateArgumentError("indent string is limited to 16 characters."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("indent string is limited to 16 characters.")); } IndentStr = bytes; Indent = 0; } else { - throw RubyExceptions.CreateTypeError("indent must be a Fixnum, String, or nil."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("indent must be a Fixnum, String, or nil.")); } break; case "float_precision": { if (!(v is int || v is BigInteger)) { - throw RubyExceptions.CreateArgumentError(":float_precision must be a Integer."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":float_precision must be a Integer.")); } int n = Sites.ToInt(context, v); if (0 >= n) { @@ -410,7 +410,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa case "cache_str": case "cache_string": { if (!(v is int || v is BigInteger)) { - throw RubyExceptions.CreateArgumentError(":cache_str must be a Integer."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":cache_str must be a Integer.")); } int n = Sites.ToInt(context, v); CacheStr = n <= 0 ? 0 : Math.Min(n, 32); @@ -419,7 +419,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa case "second_precision": { if (!(v is int || v is BigInteger)) { - throw RubyExceptions.CreateArgumentError(":second_precision must be a Integer."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":second_precision must be a Integer.")); } int n = Sites.ToInt(context, v); if (0 > n) { @@ -449,7 +449,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (Is(context, v, "ruby")) { TimeFormat = 'r'; } else { - throw RubyExceptions.CreateArgumentError(":time_format must be :unix, :unix_zone, :xmlschema, or :ruby."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":time_format must be :unix, :unix_zone, :xmlschema, or :ruby.")); } break; @@ -467,7 +467,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (Is(context, v, "unicode_xss")) { EscapeMode = Esc.JX; } else { - throw RubyExceptions.CreateArgumentError(":encoding must be :newline, :json, :xss_safe, :unicode_xss, or :ascii."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":encoding must be :newline, :json, :xss_safe, :unicode_xss, or :ascii.")); } break; @@ -484,7 +484,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (Is(context, v, "auto") || (v is bool && !(bool)v)) { BigdecLoad = BigLoad.AutoDec; } else { - throw RubyExceptions.CreateArgumentError(":bigdecimal_load must be :bigdecimal, :float, or :auto."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":bigdecimal_load must be :bigdecimal, :float, or :auto.")); } break; @@ -501,7 +501,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (ReferenceEquals(v, OjState.BigDecimalClass(context))) { CompatBigdec = true; } else { - throw RubyExceptions.CreateArgumentError(":decimal_class must be BigDecimal or Float."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":decimal_class must be BigDecimal or Float.")); } break; @@ -511,7 +511,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (v is MutableString) { CreateId = ((MutableString)v).ToByteArray(); } else { - throw RubyExceptions.CreateArgumentError(":create_id must be string."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":create_id must be string.")); } break; @@ -543,7 +543,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (Is(context, v, "auto")) { NanDump = Nan.Auto; } else { - throw RubyExceptions.CreateArgumentError(":nan must be :null, :huge, :word, :raise, or :auto."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":nan must be :null, :huge, :word, :raise, or :auto.")); } break; @@ -552,7 +552,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa return true; } if (!(v is bool)) { - throw RubyExceptions.CreateArgumentError(":omit_nil must be true or false."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":omit_nil must be true or false.")); } OmitNil = (bool)v; break; @@ -562,7 +562,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa return true; } if (!(v is bool)) { - throw RubyExceptions.CreateArgumentError(":omit_null_byte must be true or false."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":omit_null_byte must be true or false.")); } OmitNullByte = (bool)v; break; @@ -613,12 +613,12 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa object min = Sites.Call(context, v, "begin"); object max = Sites.Call(context, v, "end"); if (!IsFixnum(min) || !IsFixnum(max)) { - throw RubyExceptions.CreateArgumentError(":integer_range range bounds is not Fixnum."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":integer_range range bounds is not Fixnum.")); } IntRangeMin = ToLong(min); IntRangeMax = ToLong(max); } else if (!(v is bool && !(bool)v)) { - throw RubyExceptions.CreateArgumentError(":integer_range must be a range of Fixnum."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":integer_range must be a range of Fixnum.")); } break; @@ -628,11 +628,11 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa } else if (IsFixnum(v)) { long n = ToLong(v); if (n < 0) { - throw RubyExceptions.CreateArgumentError(":max_integer_digits must be >= 0."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":max_integer_digits must be >= 0.")); } MaxIntegerDigits = n; } else { - throw RubyExceptions.CreateArgumentError(":max_integer_digits must be a non-negative Integer."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":max_integer_digits must be a non-negative Integer.")); } break; @@ -665,7 +665,7 @@ internal bool ParseOne(RubyContext/*!*/ context, object k, object v, bool isDefa throw Sites.WrongType(context, v, "String"); } if (6 < str.GetByteCount()) { - throw RubyExceptions.CreateArgumentError(":float_format must be 6 bytes or less."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":float_format must be 6 bytes or less.")); } ValidateFloatFormat(str.ToString()); FloatFmt = str.ToString(); @@ -720,7 +720,7 @@ internal static char ModeFromSymbol(RubyContext/*!*/ context, object v) { } else if (Is(context, v, "rails")) { return OjMode.Rails; } - throw RubyExceptions.CreateArgumentError(":mode must be :object, :strict, :compat, :null, :custom, :rails, or :wab."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(":mode must be :object, :strict, :compat, :null, :custom, :rails, or :wab.")); } /// oj_parse_options_consumed. @@ -759,19 +759,19 @@ internal void ParseMatchString(RubyContext/*!*/ context, Hash/*!*/ ropts) { foreach (var pair in hash) { object key = CustomStringDictionary.ObjToNull(pair.Key); if (!(pair.Value is RubyClass)) { - throw RubyExceptions.CreateArgumentError("for :match_string, the hash values must be a Class."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("for :match_string, the hash values must be a Class.")); } if (key is RubyRegex) { rx.Entries.Add(new KeyValuePair(key, pair.Value)); } else if (key is MutableString) { if (((MutableString)key).GetByteCount() >= 256) { - throw RubyExceptions.CreateArgumentError("expressions must be less than 256 characters"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("expressions must be less than 256 characters")); } // Upstream compiles these with POSIX regcomp (and with Ruby's Regexp on Windows). object regex = Sites.Call(context, context.GetClass(typeof(RubyRegex)), "new", key); rx.Entries.Add(new KeyValuePair(regex, pair.Value)); } else { - throw RubyExceptions.CreateArgumentError("for :match_string, keys must either a String or RegExp."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("for :match_string, keys must either a String or RegExp.")); } } StrRx = rx; diff --git a/Src/Libraries/Oj/OjParse.cs b/Src/Libraries/Oj/OjParse.cs index 3998e5b34..937178342 100644 --- a/Src/Libraries/Oj/OjParse.cs +++ b/Src/Libraries/Oj/OjParse.cs @@ -1242,7 +1242,7 @@ private static bool EmptyOk(Options/*!*/ o) { } else if (OjMode.Compat == pi.Opts.Mode) { return InputBytes(context, OjDump.SafeToS(context, input)); } else { - throw RubyExceptions.CreateArgumentError("parser io argument must be a String or respond to readpartial() or read().\n"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("parser io argument must be a String or respond to readpartial() or read().\n")); } const int request = 4096 - 4; @@ -1256,7 +1256,7 @@ private static bool EmptyOk(Options/*!*/ o) { } byte[] chunk = Sites.StringValue(context, rstr).ToByteArray(); if (chunk.Length > request) { - throw RubyExceptions.CreateIOError("read returned more than the requested number of bytes"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("read returned more than the requested number of bytes")); } if (chunk.Length == 0) { break; @@ -1278,7 +1278,7 @@ private static bool EmptyOk(Options/*!*/ o) { internal static object Parse(ParseInfo/*!*/ pi, object[]/*!*/ argv, BlockParam block, bool yieldOk) { RubyContext context = pi.Context; if (argv.Length < 1) { - throw RubyExceptions.CreateArgumentError("Wrong number of arguments to parse."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Wrong number of arguments to parse.")); } object input = argv[0]; if (2 <= argv.Length) { @@ -1307,7 +1307,7 @@ internal static object Parse(ParseInfo/*!*/ pi, object[]/*!*/ argv, BlockParam b if (YesNo.Yes == pi.Opts.Nilnil) { return null; } - throw RubyExceptions.CreateTypeError("Nil is not a valid JSON source."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Nil is not a valid JSON source.")); } else { RubyClass clas = context.GetClassOf(input); if (ReferenceEquals(clas, pi.State.StringIOClass(context))) { diff --git a/Src/Libraries/Oj/OjRails.cs b/Src/Libraries/Oj/OjRails.cs index 4081d7ee6..4cc80892a 100644 --- a/Src/Libraries/Oj/OjRails.cs +++ b/Src/Libraries/Oj/OjRails.cs @@ -106,11 +106,11 @@ internal static ROpt CreateOpt(RubyContext/*!*/ context, RailsOpts/*!*/ rot, Rub // If not defined let an exception be raised, as upstream does. object ar; if (!context.ObjectClass.TryGetConstant(null, "ActiveRecord", out ar) || !(ar is RubyModule)) { - throw RubyExceptions.CreateNameError("uninitialized constant ActiveRecord"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("uninitialized constant ActiveRecord")); } object arBase; if (!((RubyModule)ar).TryGetConstant(null, "Base", out arBase)) { - throw RubyExceptions.CreateNameError("uninitialized constant ActiveRecord::Base"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError("uninitialized constant ActiveRecord::Base")); } state.ActiveRecordBase = arBase; } diff --git a/Src/Libraries/OpenSSL/OpenSSL.cs b/Src/Libraries/OpenSSL/OpenSSL.cs index 96712f776..77d5d9f12 100644 --- a/Src/Libraries/OpenSSL/OpenSSL.cs +++ b/Src/Libraries/OpenSSL/OpenSSL.cs @@ -176,7 +176,7 @@ internal static int BlockLengthOf(string/*!*/ canonicalName) { return digest._name; } - throw RubyExceptions.CreateTypeConversionError(context.GetClassDisplayName(algorithm), "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(context.GetClassDisplayName(algorithm), "String")); } [RubyConstructor] @@ -369,7 +369,7 @@ public static class KDF { // MRI allocates the result string before anything else is checked if (length < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } string canonical = Digest.CanonicalizeName(hash.ConvertToString()); @@ -402,7 +402,7 @@ public static class KDF { // MRI allocates the result string before anything else is checked if (length < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } if (length == 0) { return MutableString.CreateBinary(new byte[0]); @@ -436,7 +436,7 @@ public static bool FixedLengthSecureCompare(RubyModule/*!*/ self, byte[] x = a.ConvertToBytes(); byte[] y = b.ConvertToBytes(); if (x.Length != y.Length) { - throw RubyExceptions.CreateArgumentError("inputs must be of equal length"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("inputs must be of equal length")); } return Crypto.CryptographicOperations.FixedTimeEquals(x, y); } @@ -458,7 +458,7 @@ public static class RandomModule { [RubyMethod("random_bytes", RubyMethodAttributes.PublicSingleton)] public static MutableString/*!*/ RandomBytes(RubyModule/*!*/ self, [DefaultProtocol]int length) { if (length < 0) { - throw RubyExceptions.CreateArgumentError("negative string size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size")); } if (length == 0) { @@ -616,7 +616,7 @@ public class Transport : IReadinessHook { public static Transport/*!*/ Create(RubyClass/*!*/ self, [NotNull]object/*!*/ io) { var socket = io as RubyBasicSocket; if (socket == null) { - throw RubyExceptions.CreateTypeError("SSLSocket needs a socket to run on"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("SSLSocket needs a socket to run on")); } var result = new Transport(); result._context = self.Context; @@ -642,7 +642,7 @@ public static void Trust(Transport/*!*/ self, [NotNull]IList/*!*/ certificates, foreach (object item in certificates) { var certificate = item as X509Certificate2; if (certificate == null) { - throw RubyExceptions.CreateTypeError("trust anchors must be X509Certificate2s"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("trust anchors must be X509Certificate2s")); } intermediates.Add(certificate); if (certificate.SubjectName.RawData.AsSpan().SequenceEqual(certificate.IssuerName.RawData)) { @@ -723,7 +723,7 @@ private bool Validate(object sender, X509Certificate certificate, X509Chain chai // parked for #connect to throw, by which time the callback's frames are gone: no // Ruby frame between here and the callback saw it go by (they no longer rethrow) RubyExceptionData.GetInstance(error).CaptureExceptionTrace(_context); - _callbackError = error; + _callbackError = RubyExceptionData.MarkKept(error); return false; } } finally { @@ -989,7 +989,7 @@ private SslStream/*!*/ Stream { get { CheckUsable(); if (_closed) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } if (_ssl == null || _pendingConnect != null) { throw new SSLError("SSL session is not started yet"); diff --git a/Src/Libraries/Puma/MiniSsl.cs b/Src/Libraries/Puma/MiniSsl.cs index 2663d6df2..8c00769d9 100644 --- a/Src/Libraries/Puma/MiniSsl.cs +++ b/Src/Libraries/Puma/MiniSsl.cs @@ -311,7 +311,7 @@ private async Task Run(SslServerAuthenticationOptions/*!*/ options) { } } catch (Exception e) { lock (_sync) { - _error = e; + _error = RubyExceptionData.MarkKept(e); } } finally { bool dispose; diff --git a/Src/Libraries/Rbs/RbsParser.cs b/Src/Libraries/Rbs/RbsParser.cs index 0b84d956a..8bd19faa3 100644 --- a/Src/Libraries/Rbs/RbsParser.cs +++ b/Src/Libraries/Rbs/RbsParser.cs @@ -75,7 +75,7 @@ internal RbsSites(RubyContext/*!*/ context) { foreach (string name in path) { object value; if (!module.TryResolveConstant(null, name, out value) || !(value is RubyModule)) { - throw RubyExceptions.CreateNameError(String.Format("uninitialized constant {0}", String.Join("::", path))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("uninitialized constant {0}", String.Join("::", path)))); } module = (RubyModule)value; } @@ -402,7 +402,7 @@ internal object ReadValue() { case LocationTag: return ReadLocation(); default: - throw RubyExceptions.CreateRuntimeError(System.String.Format("Unknown node type: {0}", tag)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError(System.String.Format("Unknown node type: {0}", tag))); } } @@ -410,7 +410,7 @@ private object ReadNode() { int type = U8(); var info = type < RbsNodes.Table.Length ? RbsNodes.Table[type] : null; if (info == null) { - throw RubyExceptions.CreateRuntimeError(System.String.Format("Unknown node type: {0}", type)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError(System.String.Format("Unknown node type: {0}", type))); } var keys = _sites.NodeKeys(type); diff --git a/Src/Libraries/Socket/BasicSocket.cs b/Src/Libraries/Socket/BasicSocket.cs index 5f92291ef..8f4153d5e 100644 --- a/Src/Libraries/Socket/BasicSocket.cs +++ b/Src/Libraries/Socket/BasicSocket.cs @@ -118,7 +118,7 @@ public override void NonBlockingOperation(Action operation, bool isRead) { protected internal Socket/*!*/ Socket { get { if (_socket == null) { - throw RubyExceptions.CreateIOError("uninitialized stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("uninitialized stream")); } return _socket; } @@ -215,7 +215,7 @@ public static void SetDoNotReverseLookup(RubyBasicSocket/*!*/ self, bool value) // restarted puma could not pick up its own listeners. Socket inherited = AdoptKernelSocket(self.Context, fileDescriptor); if (inherited == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } return CreateForClass(self, inherited); } @@ -331,7 +331,7 @@ private static Socket AdoptKernelSocket(RubyContext/*!*/ context, int descriptor return UNIXSocket.ToEndPoint(Encoding.UTF8.GetString(bytes, 2, end - 2)); } if (bytes.Length < 8) { - throw RubyExceptions.CreateArgumentError("not a valid sockaddr"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("not a valid sockaddr")); } int family = bytes[0] | (bytes[1] << 8); bool v6 = family == 10 || family == 23 || family == 28 || family == 30; @@ -486,7 +486,7 @@ public static void CloseWrite(RubyBasicSocket/*!*/ self) { [RubyMethod("shutdown")] public static int Shutdown(RubyBasicSocket/*!*/ self, [DefaultProtocol, DefaultParameterValue(2)]int how) { if (how < 0 || 2 < how) { - throw RubyExceptions.CreateArgumentError("`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR")); } // This used to close() instead, to work around webrick trouble in 2009. Closing is // observably wrong -- the socket stays open after shutdown in every other Ruby, and @@ -797,10 +797,10 @@ private static List ToControlMessages(RubyArray controls) { foreach (object item in controls) { RubyArray triple = item as RubyArray; if (triple == null || triple.Count != 3) { - throw RubyExceptions.CreateArgumentError("ancillary data must be [level, type, data]"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("ancillary data must be [level, type, data]")); } if (!(triple[0] is int) || !(triple[1] is int) || !(triple[2] is MutableString)) { - throw RubyExceptions.CreateArgumentError("ancillary data must be [Integer, Integer, String]"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("ancillary data must be [Integer, Integer, String]")); } result.Add(new ControlMessage((int)triple[0], (int)triple[1], ((MutableString)triple[2]).ConvertToBytes())); } @@ -1168,7 +1168,7 @@ internal static MutableString ToAddressFamilyString(AddressFamily family) { return new IPAddress(bytes).ToString(); } } else { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'unsigned long'")); } } diff --git a/Src/Libraries/Socket/Socket.cs b/Src/Libraries/Socket/Socket.cs index 48314dd25..f4b699e34 100644 --- a/Src/Libraries/Socket/Socket.cs +++ b/Src/Libraries/Socket/Socket.cs @@ -188,7 +188,7 @@ public static int GetServiceByName(RubyClass/*!*/ self, [DefaultProtocol, NotNul public static RubyArray/*!*/ GetNameInfo(ConversionStorage/*!*/ stringCast, ConversionStorage/*!*/ fixnumCast, RubyClass/*!*/ self, [NotNull]RubyArray/*!*/ hostInfo, [Optional]object flags) { if (hostInfo.Count < 3 || hostInfo.Count > 4) { - throw RubyExceptions.CreateArgumentError("First parameter must be a 3 or 4 element array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("First parameter must be a 3 or 4 element array")); } RubyContext context = self.Context; @@ -846,7 +846,7 @@ private static int ParseInteger(RubyContext/*!*/ context, string/*!*/ str) { return isNegative ? -value.Fixnum : value.Fixnum; } } - throw RubyExceptions.CreateImplicitConversionError("String", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("String", "Integer")); } private static readonly System.Text.RegularExpressions.Regex IntegerLiteral = new System.Text.RegularExpressions.Regex( diff --git a/Src/Libraries/Socket/UNIXSocket.cs b/Src/Libraries/Socket/UNIXSocket.cs index 268afbe42..49eec8279 100644 --- a/Src/Libraries/Socket/UNIXSocket.cs +++ b/Src/Libraries/Socket/UNIXSocket.cs @@ -220,7 +220,7 @@ public override AddressFamily AddressFamily { public static void SendDescriptor(UNIXSocket/*!*/ self, [NotNull]RubyIO/*!*/ io) { int descriptor = io.KernelDescriptor; if (descriptor < 0) { - throw RubyExceptions.CreateIOError("cannot send an IO that has no file descriptor"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("cannot send an IO that has no file descriptor")); } io.Flush(); int errno; @@ -240,7 +240,7 @@ public static int ReceiveDescriptor(RubyContext/*!*/ context, UNIXSocket/*!*/ se } if (descriptor < 0) { // The peer sent data but no descriptor, which is what CRuby reports this way. - throw RubyExceptions.CreateIOError("file descriptor was not passed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("file descriptor was not passed")); } IOMode mode; diff --git a/Src/Libraries/Sqlite3/Sqlite3.cs b/Src/Libraries/Sqlite3/Sqlite3.cs index 8ccd24ddf..fbb6dead6 100644 --- a/Src/Libraries/Sqlite3/Sqlite3.cs +++ b/Src/Libraries/Sqlite3/Sqlite3.cs @@ -1073,8 +1073,8 @@ public static int BindParameterCount(Statement/*!*/ self) { } } if (name == null) { - throw RubyExceptions.CreateTypeError(String.Format( - "can't convert {0} into Integer", context.GetClassDisplayName(key))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format( + "can't convert {0} into Integer", context.GetClassDisplayName(key)))); } else { string str = name.ToString(); if (str.Length == 0 || (str[0] != ':' && str[0] != '@' && str[0] != '$')) { @@ -1161,7 +1161,7 @@ private static int StatOp(RubyContext/*!*/ context, object key) { var str = key as MutableString; string name = (symbol != null) ? symbol.ToString() : (str != null) ? str.ToString() : null; if (name == null) { - throw RubyExceptions.CreateTypeError("key must be a Symbol or a String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("key must be a Symbol or a String")); } for (int i = 0; i < _statNames.Length; i++) { if (_statNames[i] == name) { @@ -1170,7 +1170,7 @@ private static int StatOp(RubyContext/*!*/ context, object key) { return i + 1; } } - throw RubyExceptions.CreateArgumentError(String.Format("unknown key: {0}", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("unknown key: {0}", name))); } [RubyMethod("stat_for", RubyMethodAttributes.PrivateInstance)] @@ -1282,10 +1282,10 @@ private sqlite3_backup/*!*/ Handle { [NotNull]Database/*!*/ source, [DefaultProtocol, NotNull]MutableString/*!*/ sourceName) { EnsureInitialized(); if (source._closed) { - throw RubyExceptions.CreateArgumentError("cannot backup from a closed database"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cannot backup from a closed database")); } if (destination._closed) { - throw RubyExceptions.CreateArgumentError("cannot backup to a closed database"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cannot backup to a closed database")); } sqlite3_backup backup = raw.sqlite3_backup_init(destination._db, destinationName.ToString(), source._db, sourceName.ToString()); diff --git a/Src/Libraries/StringIO/StringIO.cs b/Src/Libraries/StringIO/StringIO.cs index a605a9929..fd2366dde 100644 --- a/Src/Libraries/StringIO/StringIO.cs +++ b/Src/Libraries/StringIO/StringIO.cs @@ -75,7 +75,7 @@ public StringIO(MutableString/*!*/ content, IOMode mode) { private void SetPosition(long value) { if (value < 0 || value > Int32.MaxValue) { - throw RubyExceptions.CreateEINVAL(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL()); } _position = (int)value; } @@ -89,21 +89,21 @@ private void SetContent(MutableString content) { private MutableString/*!*/ GetContent() { if (_mode.IsClosed() || _content == null) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } return _content; } private MutableString/*!*/ GetReadableContent() { if (!_mode.CanRead() || _content == null) { - throw RubyExceptions.CreateIOError("not opened for reading"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not opened for reading")); } return _content; } private MutableString/*!*/ GetWritableContent() { if (!_mode.CanWrite() || _content == null) { - throw RubyExceptions.CreateIOError("not opened for writing"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not opened for writing")); } return _content; } @@ -264,13 +264,13 @@ private static void Initialize(ConversionStorage>/*! StringIO/*!*/ self, [NotNull]object/*!*/ other) { if (!Protocols.RespondTo(respondToStorage, other, "to_strio")) { - throw RubyExceptions.CreateImplicitConversionError(respondToStorage.Context.GetClassName(other), "StringIO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(respondToStorage.Context.GetClassName(other), "StringIO")); } var site = toStringIoStorage.GetCallSite("to_strio", 0); var strio = site.Target(site, other) as StringIO; if (strio == null) { - throw RubyExceptions.CreateTypeError("C#to_strio should return StringIO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("C#to_strio should return StringIO")); } return Reopen(respondToStorage.Context, self, strio); @@ -327,7 +327,7 @@ public static void Close(StringIO/*!*/ self) { [RubyMethod("close_read")] public static void CloseRead(StringIO/*!*/ self) { if (!self._initialMode.CanRead()) { - throw RubyExceptions.CreateIOError("closing non-duplex IO for reading"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closing non-duplex IO for reading")); } self._mode = self._mode.CloseRead(); } @@ -335,7 +335,7 @@ public static void CloseRead(StringIO/*!*/ self) { [RubyMethod("close_write")] public static void CloseWrite(StringIO/*!*/ self) { if (!self._initialMode.CanWrite()) { - throw RubyExceptions.CreateIOError("closing non-duplex IO for writing"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closing non-duplex IO for writing")); } self._mode = self._mode.CloseWrite(); } @@ -380,7 +380,7 @@ public static void Pos(StringIO/*!*/ self, [DefaultProtocol]int pos) { public static object SetLength(ConversionStorage/*!*/ fixnumCast, StringIO/*!*/ self, object lengthObj) { int length = Protocols.CastToFixnum(fixnumCast, lengthObj); if (length < 0) { - throw RubyExceptions.CreateEINVAL("negative length"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("negative length")); } self.GetWritableContent().SetByteCount(length); // MRI answers 0, whatever the length @@ -410,7 +410,7 @@ public static int Seek(StringIO/*!*/ self, [DefaultProtocol]int pos, [DefaultPro case RubyIO.SEEK_SET: origin = SeekOrigin.Begin; break; case RubyIO.SEEK_CUR: origin = SeekOrigin.Current; break; case RubyIO.SEEK_END: origin = SeekOrigin.End; break; - default: throw RubyExceptions.CreateEINVAL("invalid whence"); + default: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("invalid whence")); } self.SetPosition(RubyIO.GetSeekPosition(content.GetByteCount(), self._position, pos, origin)); @@ -566,7 +566,7 @@ public static int Write(StringIO/*!*/ self, [NotNull]MutableString/*!*/ value) { try { content.WriteBytes(pos, value, 0, bytesWritten); } catch (InvalidOperationException) { - throw RubyExceptions.CreateIOError("not modifiable string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not modifiable string")); } self._position = pos + bytesWritten; @@ -682,7 +682,7 @@ public static MutableString Read(StringIO/*!*/ self, [DefaultProtocol]int count, public static MutableString Read(StringIO/*!*/ self, [DefaultProtocol]int count, [DefaultProtocol, Optional, NotNull]MutableString buffer) { var content = self.GetReadableContent(); if (count < 0) { - throw RubyExceptions.CreateArgumentError("negative length {0} given", count); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative length {0} given", count)); } // A read of so many bytes answers bytes: MRI tags the result ASCII-8BIT however the @@ -737,7 +737,7 @@ public static MutableString Read(StringIO/*!*/ self, [DefaultProtocol]int count, self.GetReadableContent(); if (count < 0) { - throw RubyExceptions.CreateArgumentError(String.Format("negative string size (or size too big): {0}", count)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("negative string size (or size too big): {0}", count))); } // A zero length read is answered before anything is looked at: MRI neither seeks // nor touches a given buffer, so even a negative offset is accepted here. @@ -745,7 +745,7 @@ public static MutableString Read(StringIO/*!*/ self, [DefaultProtocol]int count, return buffer ?? MutableString.CreateBinary(); } if (offset < 0) { - throw RubyExceptions.CreateEINVAL(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL()); } lock (self._mutex) { @@ -905,7 +905,7 @@ public static void SetPreviousByte(StringIO/*!*/ self, [DefaultProtocol]int b) { } self._position = pos; } catch (InvalidOperationException) { - throw RubyExceptions.CreateIOError("not modifiable string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not modifiable string")); } } } @@ -951,7 +951,7 @@ public static void SetLineNo(StringIO/*!*/ self, [DefaultProtocol]int value) { /// private static void CheckLineLimit(int limit, string/*!*/ methodName) { if (limit == 0) { - throw RubyExceptions.CreateArgumentError("invalid limit: 0 for {0}", methodName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid limit: 0 for {0}", methodName)); } } @@ -1299,7 +1299,7 @@ public static void UngetBytes(StringIO/*!*/ self, [DefaultProtocol, NotNull]Muta self._position = position - count; } } catch (InvalidOperationException) { - throw RubyExceptions.CreateIOError("not modifiable string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not modifiable string")); } } diff --git a/Src/Libraries/StringScanner/StringScanner.cs b/Src/Libraries/StringScanner/StringScanner.cs index 7372eaf84..0e4e5aed1 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -379,7 +379,7 @@ private void ClearMatch() { // still accepts one - a 1.8-ism that survives in ConvertToStrAction - so the // pattern has to be rejected here rather than by the conversion. if (pattern is RubySymbol) { - throw RubyExceptions.CreateTypeError("no implicit conversion of Symbol into String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of Symbol into String")); } return Protocols.CastToString(stringCast, pattern); } @@ -663,7 +663,7 @@ public static MutableString GetMatchSubgroup(ConversionStorage/*!*/ fixnumC // A match with no pattern behind it has no named groups at all, so every name // is undefined rather than merely unmatched. if (self.CurrentMatch == null || !self.CurrentMatch.HasNamedGroup(name)) { - throw RubyExceptions.CreateIndexError("undefined group name reference: {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("undefined group name reference: {0}", name)); } int[] named = self.CurrentMatch.GetGroupOffsets(name, true); return (named == null) ? null : self.ByteSlice(self._matchBase + named[0], named[1] - named[0]); @@ -890,7 +890,7 @@ public static bool WasMatched(StringScanner/*!*/ self) { [RubyMethod("peek")] public static MutableString/*!*/ Peek(StringScanner/*!*/ self, [DefaultProtocol]int len) { if (len < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } int available = self.ByteLength - self._position; return self.ByteSlice(self._position, Math.Min(len, available)); @@ -921,7 +921,7 @@ public static int SetCurrentPosition(StringScanner/*!*/ self, [DefaultProtocol]i position += self.ByteLength; } if (position < 0 || position > self.ByteLength) { - throw RubyExceptions.CreateRangeError("index out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("index out of range")); } self._position = position; return newPosition; @@ -1033,7 +1033,7 @@ public static object ScanInteger(ConversionStorage/*!*/ fixnumCast, RubyCon } } if (numericBase != 10 && numericBase != 16) { - throw RubyExceptions.CreateArgumentError("Unsupported integer base: {0}, expected 10 or 16", numericBase); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Unsupported integer base: {0}, expected 10 or 16", numericBase)); } if (!self._scanString.Encoding.IsAsciiIdentity) { throw new EncodingCompatibilityError( diff --git a/Src/Libraries/Strptime/Strptime.cs b/Src/Libraries/Strptime/Strptime.cs index bcd5c5663..c57360c92 100644 --- a/Src/Libraries/Strptime/Strptime.cs +++ b/Src/Libraries/Strptime/Strptime.cs @@ -185,7 +185,7 @@ private static bool IsDigit(int c) { case 'y': isns.Add(OpY2); break; case 'z': isns.Add(OpZ); break; default: - throw RubyExceptions.CreateArgumentError("invalid format"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid format")); } fi++; break; @@ -483,7 +483,7 @@ private StrftimeProgram(long[]/*!*/ insns, byte[]/*!*/ fmt, int resultLength) { internal static StrftimeProgram/*!*/ Compile(byte[]/*!*/ fmt) { int flen = fmt.Length; if (flen > 65535) { - throw RubyExceptions.CreateArgumentError("too long format string (>65335)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("too long format string (>65335)")); } var isns = new System.Collections.Generic.List(flen + 2); int fi = 0, rlen = 0; @@ -504,7 +504,7 @@ private StrftimeProgram(long[]/*!*/ insns, byte[]/*!*/ fmt, int resultLength) { case 'y': rlen += 2; break; case 'z': rlen += 5; break; default: - throw RubyExceptions.CreateArgumentError("invalid format"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid format")); } isns.Add(c); fi++; @@ -702,10 +702,10 @@ internal static bool RespondTo(RubyContext/*!*/ context, object target, string/* if (str != null) { return str; } - throw RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_str gives {1})", - TypeName(context, obj), TypeName(context, converted)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_str gives {1})", + TypeName(context, obj), TypeName(context, converted))); } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj))); } internal static bool IsRational(RubyContext/*!*/ context, object value) { @@ -728,7 +728,7 @@ internal static bool IsRational(RubyContext/*!*/ context, object value) { } } if (nul) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } } return str; @@ -773,7 +773,7 @@ internal static CompiledFormat Find(object self) { internal static CompiledFormat/*!*/ Get(RubyContext/*!*/ context, object self) { var result = Find(self); if (result == null || result.Program == null) { - throw RubyExceptions.CreateTypeError("uninitialized {0}", context.GetClassName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized {0}", context.GetClassName(self))); } return result; } @@ -784,12 +784,12 @@ internal static object InitializeCopy(RubyContext/*!*/ context, object self, obj return self; } if (context.GetClassOf(other) != context.GetClassOf(self)) { - throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("initialize_copy should take same class object")); } var source = Get(context, other); var target = Find(self); if (target != null && target.Program != null) { - throw RubyExceptions.CreateTypeError("already initialized {0}", context.GetClassName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("already initialized {0}", context.GetClassName(self))); } target = GetOrCreate(self); target.Program = source.Program; @@ -825,7 +825,7 @@ private static void Run(RubyContext/*!*/ context, object self, object str, var s = Support.StringValue(context, str); var state = CompiledFormat.Get(context, self); if (!state.Program.Exec(s.ToByteArray(), out t, out nsec, out gmtoff)) { - throw RubyExceptions.CreateArgumentError("string doesn't match"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string doesn't match")); } } @@ -864,7 +864,7 @@ public static object ExecI(RubyContext/*!*/ context, object self, object str) { if (offset == Int32.MaxValue - 1) { return new RubyTime(sec, subsec, RubyTimeZoneKind.Utc, ExactNum.Zero); } - throw RubyExceptions.CreateArgumentError("utc_offset out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("utc_offset out of range")); } } @@ -899,7 +899,7 @@ public static object InitializeCopy(RubyContext/*!*/ context, object self, objec public static MutableString/*!*/ Exec(RubyContext/*!*/ context, object self, object time) { var t = time as RubyTime; if (t == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected time)", Support.TypeName(context, time)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type {0} (expected time)", Support.TypeName(context, time))); } var state = CompiledFormat.Get(context, self); return Result(state, state.Program.Exec(t.Seconds, t.Nanoseconds, unchecked((int)t.UtcOffsetSeconds))); @@ -932,7 +932,7 @@ public static object InitializeCopy(RubyContext/*!*/ context, object self, objec nsec = (int)ToLong(context, Support.Call(context, m, "to_int")); } else { // the C leaves the timespec uninitialized here; say what it was given instead - throw RubyExceptions.CreateTypeError("can't convert {0} into an exact number", Support.TypeName(context, epoch)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into an exact number", Support.TypeName(context, epoch))); } return Result(state, state.Program.Exec(sec, nsec, 0)); } @@ -947,11 +947,11 @@ private static long ToLong(RubyContext/*!*/ context, object value) { if (value is BigInteger) { var big = (BigInteger)value; if (big > long.MaxValue || big < long.MinValue) { - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } return (long)big; } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", Support.TypeName(context, value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", Support.TypeName(context, value))); } [RubyMethod("source")] diff --git a/Src/Libraries/Thread/RubyConditionVariable.cs b/Src/Libraries/Thread/RubyConditionVariable.cs index d3b7093e0..d80800fff 100644 --- a/Src/Libraries/Thread/RubyConditionVariable.cs +++ b/Src/Libraries/Thread/RubyConditionVariable.cs @@ -161,7 +161,7 @@ private static object DoWait(RubyConditionVariable/*!*/ self, RubyMutex/*!*/ mut [RubyMethod("marshal_dump")] public static object MarshalDump(RubyContext/*!*/ context, RubyConditionVariable/*!*/ self) { - throw RubyExceptions.CreateTypeError("can't dump {0}", context.GetClassDisplayName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't dump {0}", context.GetClassDisplayName(self))); } } } diff --git a/Src/Libraries/Thread/RubyMutex.cs b/Src/Libraries/Thread/RubyMutex.cs index 11fcea372..862747590 100644 --- a/Src/Libraries/Thread/RubyMutex.cs +++ b/Src/Libraries/Thread/RubyMutex.cs @@ -369,13 +369,13 @@ internal static double ToSleepSeconds(RespondToStorage/*!*/ respondToStorage, Bi seconds = ToSecondsByDivmod(respondToStorage, divmodStorage, multiplyStorage, arrayTryCast, integerCast, timeout); } if (Double.IsNaN(seconds)) { - throw RubyExceptions.CreateRangeError("NaN out of Time range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("NaN out of Time range")); } if (Double.IsPositiveInfinity(seconds)) { - throw RubyExceptions.CreateRangeError("Inf out of Time range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("Inf out of Time range")); } if (seconds < 0) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } return seconds; } @@ -395,13 +395,13 @@ private static double ToSecondsByDivmod(RespondToStorage/*!*/ respondToStorage, parts = Protocols.TryCastToArray(arrayTryCast, divmod.Target(divmod, timeout, ScriptingRuntimeHelpers.Int32ToObject(1))); } if (parts == null) { - throw RubyExceptions.CreateTypeError("can't convert {0} into time interval", - respondToStorage.Context.GetClassDisplayName(timeout)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} into time interval", + respondToStorage.Context.GetClassDisplayName(timeout))); } double whole = ToWholeSeconds(integerCast, parts.Count > 0 ? parts[0] : null); if (whole < 0) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } var multiply = multiplyStorage.GetCallSite("*"); double nanoseconds = ToWholeSeconds(integerCast, @@ -425,7 +425,7 @@ private static double ToWholeSeconds(ConversionStorage/*!*/ intege } else if (integer.Bignum.AsInt64(out result)) { return result; } - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } private static object DoSleep(RubyMutex/*!*/ self, double seconds) { diff --git a/Src/Libraries/Thread/RubyQueue.cs b/Src/Libraries/Thread/RubyQueue.cs index bd7da688a..0fc5a2f05 100644 --- a/Src/Libraries/Thread/RubyQueue.cs +++ b/Src/Libraries/Thread/RubyQueue.cs @@ -136,7 +136,7 @@ internal static int GetTimeoutMilliseconds(RubyContext/*!*/ context, object time } else { // The class has to be spelled the way Ruby spells it, not the way the CLR does: // MutableString is String, and true/false are spelled by value. - throw RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(timeout), "Float"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(timeout), "Float")); } double ms = seconds * 1000; return ms > Int32.MaxValue ? Timeout.Infinite : (ms < 0 ? 0 : (int)ms); @@ -180,7 +180,7 @@ private static void Fill(ConversionStorage/*!*/ toA, RubyContext/*!*/ con if (list == null) { list = Protocols.TryConvertToArray(toA, items); if (list == null) { - throw RubyExceptions.CreateTypeConversionError(context.GetClassDisplayName(items), "Array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError(context.GetClassDisplayName(items), "Array")); } } lock (queue._queue) { @@ -231,7 +231,7 @@ public static object Dequeue(RubyContext/*!*/ context, RubyQueue/*!*/ self, [Key [RubyMethod("shift")] public static object Dequeue(RubyContext/*!*/ context, RubyQueue/*!*/ self, bool nonBlocking, [Keywords, NotNull]Hash/*!*/ options) { if (nonBlocking && options.Count > 0) { - throw RubyExceptions.CreateArgumentError("can't set a timeout if non_block is enabled"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't set a timeout if non_block is enabled")); } return Dequeue(context, self, options); } @@ -241,7 +241,7 @@ public static object Dequeue(RubyContext/*!*/ context, RubyQueue/*!*/ self, bool [RubyMethod("pop")] [RubyMethod("shift")] public static object Dequeue(RubyQueue/*!*/ self, object nonBlocking, object other) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 0..1)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given 2, expected 0..1)")); } internal static object GetTimeoutOption(RubyContext/*!*/ context, Hash/*!*/ options) { @@ -300,14 +300,14 @@ public static bool IsClosed(RubyQueue/*!*/ self) { [RubyMethod("freeze")] public static object Freeze(RubyContext/*!*/ context, RubyQueue/*!*/ self) { - throw RubyExceptions.CreateTypeError("cannot freeze {0}", - context.Inspect(self).ToString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("cannot freeze {0}", + context.Inspect(self).ToString())); } /// MRI's Queue (and so SizedQueue) refuses Marshal by name. [RubyMethod("marshal_dump")] public static object MarshalDump(RubyContext/*!*/ context, RubyQueue/*!*/ self) { - throw RubyExceptions.CreateTypeError("can't dump {0}", context.GetClassDisplayName(self)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't dump {0}", context.GetClassDisplayName(self))); } } } diff --git a/Src/Libraries/Thread/SizedQueue.cs b/Src/Libraries/Thread/SizedQueue.cs index d5de6a68f..cf85054b5 100644 --- a/Src/Libraries/Thread/SizedQueue.cs +++ b/Src/Libraries/Thread/SizedQueue.cs @@ -41,7 +41,7 @@ public SizedQueue([DefaultProtocol]int limit) { private void SetLimitChecked(int limit) { if (limit <= 0) { - throw RubyExceptions.CreateArgumentError("queue size must be positive"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("queue size must be positive")); } _limit = limit; } @@ -141,7 +141,7 @@ public static object Enqueue(RubyContext/*!*/ context, SizedQueue/*!*/ self, obj [Keywords, NotNull]Hash/*!*/ options) { if (nonBlocking && options.Count > 0) { - throw RubyExceptions.CreateArgumentError("can't set a timeout if non_block is enabled"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("can't set a timeout if non_block is enabled")); } return Enqueue(context, self, value, options); } diff --git a/Src/Libraries/Yajl/Yajl.cs b/Src/Libraries/Yajl/Yajl.cs index 477dcb3c8..5cac9835b 100644 --- a/Src/Libraries/Yajl/Yajl.cs +++ b/Src/Libraries/Yajl/Yajl.cs @@ -230,7 +230,7 @@ private RubyContext/*!*/ Context { private YajlHandle/*!*/ Handle { get { if (_handle == null) { - throw RubyExceptions.CreateTypeError("uninitialized Yajl::Parser"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Yajl::Parser")); } return _handle; } @@ -703,7 +703,7 @@ private static object BuildSimpleValue(EventStream/*!*/ parser, Event ev) { throw Rb.ParseError("unexpected colon while constructing value"); default: // the C calls rb_bug here - throw RubyExceptions.CreateRuntimeError("[BUG] we should never get here"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("[BUG] we should never get here")); } } @@ -762,7 +762,7 @@ private RubyContext/*!*/ Context { private YajlGen/*!*/ Gen { get { if (_gen == null) { - throw RubyExceptions.CreateTypeError("uninitialized Yajl::Encoder"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Yajl::Encoder")); } return _gen; } diff --git a/Src/Libraries/Zstd/Zstd.cs b/Src/Libraries/Zstd/Zstd.cs index 796f98a9f..a47a8630b 100644 --- a/Src/Libraries/Zstd/Zstd.cs +++ b/Src/Libraries/Zstd/Zstd.cs @@ -120,10 +120,10 @@ private static bool RespondTo(RubyContext/*!*/ context, object target, string/*! if (str != null) { return str; } - throw RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_str gives {1})", - TypeName(context, obj), TypeName(context, converted)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to String ({0}#to_str gives {1})", + TypeName(context, obj), TypeName(context, converted))); } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into String", TypeName(context, obj))); } internal static string/*!*/ Inspect(RubyContext/*!*/ context, object obj) { @@ -136,20 +136,20 @@ internal static int ToInt(RubyContext/*!*/ context, object obj) { return (int)obj; } if (obj == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion from nil to integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion from nil to integer")); } if (obj is double) { double d = (double)obj; if (Double.IsNaN(d) || Double.IsInfinity(d) || d >= 2147483648.0 || d < -2147483648.0) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", Inspect(context, obj))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", Inspect(context, obj)))); } return (int)d; } if (obj is long || obj is BigInteger) { BigInteger big = obj is long ? new BigInteger((long)obj) : (BigInteger)obj; if (big > Int32.MaxValue || big < Int32.MinValue) { - throw RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", - big.ToString(), big.Sign > 0 ? "big" : "small")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", + big.ToString(), big.Sign > 0 ? "big" : "small"))); } return (int)big; } @@ -158,10 +158,10 @@ internal static int ToInt(RubyContext/*!*/ context, object obj) { if (converted is int || converted is long || converted is BigInteger) { return ToInt(context, converted); } - throw RubyExceptions.CreateTypeError("can't convert {0} to Integer ({0}#to_int gives {1})", - TypeName(context, obj), TypeName(context, converted)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert {0} to Integer ({0}#to_int gives {1})", + TypeName(context, obj), TypeName(context, converted))); } - throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", TypeName(context, obj))); } /// @@ -179,9 +179,9 @@ internal static Hash Split(object[]/*!*/ args, int required, int optional, out o } } if (n < required || n > required + optional) { - throw RubyExceptions.CreateArgumentError(optional == 0 + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(optional == 0 ? String.Format("wrong number of arguments (given {0}, expected {1})", n, required) - : String.Format("wrong number of arguments (given {0}, expected {1}..{2})", n, required, required + optional)); + : String.Format("wrong number of arguments (given {0}, expected {1}..{2})", n, required, required + optional))); } positional = new object[required + optional]; Array.Copy(args, positional, n); @@ -217,7 +217,7 @@ internal static Hash Split(object[]/*!*/ args, int required, int optional, out o foreach (var key in unknown) { names.Add(Inspect(context, key)); } - throw RubyExceptions.CreateArgumentError("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", names)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", names))); } return values; } @@ -235,7 +235,7 @@ internal unsafe sealed class CompressContext : IDisposable { internal CompressContext() { Ptr = Z.ZSTD_createCCtx(); if (Ptr == null) { - throw RubyExceptions.CreateRuntimeError("ZSTD_createCCtx error"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_createCCtx error")); } } @@ -262,7 +262,7 @@ internal unsafe sealed class DecompressContext : IDisposable { internal DecompressContext() { Ptr = Z.ZSTD_createDCtx(); if (Ptr == null) { - throw RubyExceptions.CreateRuntimeError("ZSTD_createDCtx failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_createDCtx failed")); } } @@ -310,7 +310,7 @@ internal static void SetCompressParams(RubyContext/*!*/ context, CompressContext if (cdict != null && context.GetClassOf(dict) == CDict.GetClass(context)) { nuint ret = Z.ZSTD_CCtx_refCDict(ctx.Ptr, cdict.Ptr); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("ZSTD_CCtx_refCDict failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_CCtx_refCDict failed")); } ctx.KeepAlive = cdict; } else if (dict is MutableString) { @@ -318,11 +318,11 @@ internal static void SetCompressParams(RubyContext/*!*/ context, CompressContext fixed (byte* p = bytes) { nuint ret = Z.ZSTD_CCtx_loadDictionary(ctx.Ptr, p, (nuint)bytes.Length); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("ZSTD_CCtx_loadDictionary failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_CCtx_loadDictionary failed")); } } } else { - throw RubyExceptions.CreateArgumentError("`dict:` must be a Zstd::CDict or a String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("`dict:` must be a Zstd::CDict or a String")); } } } @@ -336,7 +336,7 @@ internal static void SetDecompressParams(RubyContext/*!*/ context, DecompressCon if (ddict != null && context.GetClassOf(dict) == DDict.GetClass(context)) { nuint ret = Z.ZSTD_DCtx_refDDict(dctx.Ptr, ddict.Ptr); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("ZSTD_DCtx_refDDict failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_DCtx_refDDict failed")); } dctx.KeepAlive = ddict; } else if (dict is MutableString) { @@ -345,11 +345,11 @@ internal static void SetDecompressParams(RubyContext/*!*/ context, DecompressCon nuint ret = Z.ZSTD_DCtx_loadDictionary(dctx.Ptr, p, (nuint)bytes.Length); if (Native.IsError(ret)) { // sic: upstream names the CCtx function here - throw RubyExceptions.CreateRuntimeError("ZSTD_CCtx_loadDictionary failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_CCtx_loadDictionary failed")); } } } else { - throw RubyExceptions.CreateArgumentError("`dict:` must be a Zstd::DDict or a String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("`dict:` must be a Zstd::DDict or a String")); } } } @@ -383,7 +383,7 @@ public static int ZstdVersion(object self) { ret = Z.ZSTD_compress2(ctx.Ptr, dst, bound, src, (nuint)input.Length); } if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("compress error error code: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("compress error error code: " + Native.ErrorName(ret))); } return Native.Binary(output, (int)ret); } @@ -394,7 +394,7 @@ public static int ZstdVersion(object self) { public static MutableString/*!*/ CompressUsingDict(RubyContext/*!*/ context, object self, params object[]/*!*/ args) { context.ReportWarning("Zstd.compress_using_dict is deprecated; use Zstd.compress with `dict:` instead."); if (args.Length < 2 || args.Length > 3) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 2..3)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 2..3)", args.Length)); } int level = ConvertLevel(context, args.Length > 2 ? args[2] : null); byte[] input = Args.StringValue(context, args[0]).ToByteArray(); @@ -406,7 +406,7 @@ public static int ZstdVersion(object self) { cdict = Z.ZSTD_createCDict(d, (nuint)dict.Length, level); } if (cdict == null) { - throw RubyExceptions.CreateRuntimeError("ZSTD_createCDict failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_createCDict failed")); } try { using (var ctx = new CompressContext()) { @@ -417,7 +417,7 @@ public static int ZstdVersion(object self) { size = Z.ZSTD_compress_usingCDict(ctx.Ptr, dst, bound, src, (nuint)input.Length, cdict); } if (Native.IsError(size)) { - throw RubyExceptions.CreateRuntimeError("compress failed: " + Native.ErrorName(size)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("compress failed: " + Native.ErrorName(size))); } return Native.Binary(output, (int)size); } @@ -438,7 +438,7 @@ public static int ZstdVersion(object self) { ZSTD_outBuffer_s outBuf = new ZSTD_outBuffer_s { dst = dst, size = (nuint)outSize, pos = 0 }; nuint ret = Z.ZSTD_decompressStream(dctx.Ptr, &outBuf, &inBuf); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("ZSTD_decompressStream failed: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_decompressStream failed: " + Native.ErrorName(ret))); } result.Write(buffer, 0, (int)outBuf.pos); } @@ -469,7 +469,7 @@ public static int ZstdVersion(object self) { size = Z.ZSTD_getFrameContentSize(src, (nuint)input.Length); } if (size == Native.ContentSizeError) { - throw RubyExceptions.CreateRuntimeError("not compressed by zstd: " + Native.ErrorName(unchecked((nuint)size))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not compressed by zstd: " + Native.ErrorName(unchecked((nuint)size)))); } if (size == Native.ContentSizeUnknown) { return DecompressBuffered(dctx, input); @@ -482,7 +482,7 @@ public static int ZstdVersion(object self) { ret = Z.ZSTD_decompressDCtx(dctx.Ptr, dst, (nuint)size, src, (nuint)input.Length); } if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("decompress error: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("decompress error: " + Native.ErrorName(ret))); } // sic: the whole buffer, sized from the first frame's header return MutableString.CreateBinary(output, RubyEncoding.Binary); @@ -494,7 +494,7 @@ public static int ZstdVersion(object self) { public static MutableString/*!*/ DecompressUsingDict(RubyContext/*!*/ context, object self, params object[]/*!*/ args) { context.ReportWarning("Zstd.decompress_using_dict is deprecated; use Zstd.decompress with `dict:` instead."); if (args.Length != 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 2)", args.Length)); } byte[] input = Args.StringValue(context, args[0]).ToByteArray(); byte[] dict = Args.StringValue(context, args[1]).ToByteArray(); @@ -504,7 +504,7 @@ public static int ZstdVersion(object self) { ddict = Z.ZSTD_createDDict(d, (nuint)dict.Length); } if (ddict == null) { - throw RubyExceptions.CreateRuntimeError("ZSTD_createDDict failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_createDDict failed")); } try { uint expected = Z.ZSTD_getDictID_fromDDict(ddict); @@ -514,7 +514,7 @@ public static int ZstdVersion(object self) { actual = Z.ZSTD_getDictID_fromFrame(src, (nuint)input.Length); } if (expected != actual) { - throw RubyExceptions.CreateRuntimeError("DictID mismatch"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("DictID mismatch")); } using (var dctx = new DecompressContext()) { @@ -522,7 +522,7 @@ public static int ZstdVersion(object self) { size = Z.ZSTD_getFrameContentSize(src, (nuint)input.Length); } if (size == Native.ContentSizeError) { - throw RubyExceptions.CreateRuntimeError("not compressed by zstd: " + Native.ErrorName(unchecked((nuint)size))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("not compressed by zstd: " + Native.ErrorName(unchecked((nuint)size)))); } if (size == Native.ContentSizeUnknown) { // sic: without the dictionary @@ -535,7 +535,7 @@ public static int ZstdVersion(object self) { ret = Z.ZSTD_decompress_usingDDict(dctx.Ptr, dst, (nuint)size, src, (nuint)input.Length, ddict); } if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("decompress error: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("decompress error: " + Native.ErrorName(ret))); } return MutableString.CreateBinary(output, RubyEncoding.Binary); } @@ -571,7 +571,7 @@ public static int ZstdVersion(object self) { size = Z.ZSTD_writeSkippableFrame(dst, (nuint)dstSize, s, (nuint)skip.Length, magicVariant); } if (Native.IsError(size)) { - throw RubyExceptions.CreateRuntimeError("write skippable frame failed: " + Native.ErrorName(size)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("write skippable frame failed: " + Native.ErrorName(size))); } return Native.Binary(output, (int)size); } @@ -592,7 +592,7 @@ public static MutableString ReadSkippableFrame(RubyContext/*!*/ context, object size = Z.ZSTD_readSkippableFrame(dst, skipLen, &readMagic, src, (nuint)input.Length); } if (Native.IsError(size)) { - throw RubyExceptions.CreateRuntimeError("read skippable frame failed: " + Native.ErrorName(size)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("read skippable frame failed: " + Native.ErrorName(size))); } return Native.Binary(output, (int)size); } @@ -634,7 +634,7 @@ public CDict(RubyClass/*!*/ rubyClass) : base(rubyClass) { [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static object Initialize(RubyContext/*!*/ context, CDict/*!*/ self, params object[]/*!*/ args) { if (args.Length < 1 || args.Length > 2) { - throw RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..2)", args.Length); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("wrong number of arguments (given {0}, expected 1..2)", args.Length)); } int level = ConvertLevel(context, args.Length > 1 ? args[1] : null); byte[] dict = Args.StringValue(context, args[0]).ToByteArray(); @@ -643,7 +643,7 @@ public static object Initialize(RubyContext/*!*/ context, CDict/*!*/ self, param cdict = Z.ZSTD_createCDict(d, (nuint)dict.Length, level); } if (cdict == null) { - throw RubyExceptions.CreateRuntimeError("ZSTD_createCDict failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_createCDict failed")); } // DATA_PTR(self) = cdict: a second #initialize leaks the first, as the C does self.Ptr = cdict; @@ -652,7 +652,7 @@ public static object Initialize(RubyContext/*!*/ context, CDict/*!*/ self, param [RubyMethod("initialize_copy")] public static object InitializeCopy(CDict/*!*/ self, object other) { - throw RubyExceptions.CreateRuntimeError("CDict cannot be duplicated"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("CDict cannot be duplicated")); } } @@ -693,7 +693,7 @@ public static object Initialize(RubyContext/*!*/ context, DDict/*!*/ self, objec ddict = Z.ZSTD_createDDict(d, (nuint)dict.Length); } if (ddict == null) { - throw RubyExceptions.CreateRuntimeError("ZSTD_createDDict failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("ZSTD_createDDict failed")); } self.Ptr = ddict; return self; @@ -701,7 +701,7 @@ public static object Initialize(RubyContext/*!*/ context, DDict/*!*/ self, objec [RubyMethod("initialize_copy")] public static object InitializeCopy(DDict/*!*/ self, object other) { - throw RubyExceptions.CreateRuntimeError("CDict cannot be duplicated"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("CDict cannot be duplicated")); } } @@ -731,7 +731,7 @@ public StreamingCompress(RubyClass/*!*/ rubyClass) : base(rubyClass) { private CompressContext/*!*/ Context { get { if (_ctx == null) { - throw RubyExceptions.CreateTypeError("uninitialized Zstd::StreamingCompress"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Zstd::StreamingCompress")); } return _ctx; } @@ -776,7 +776,7 @@ public static object Initialize(RubyContext/*!*/ context, StreamingCompress/*!*/ ZSTD_outBuffer_s outBuf = new ZSTD_outBuffer_s { dst = d, size = (nuint)buf.Length, pos = 0 }; nuint ret = Z.ZSTD_compressStream2(ctx.Ptr, &outBuf, &inBuf, ZSTD_EndDirective.ZSTD_e_continue); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("compress error error code: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("compress error error code: " + Native.ErrorName(ret))); } Append(result, buf, (int)outBuf.pos); } @@ -806,7 +806,7 @@ public static object Write(RubyContext/*!*/ context, StreamingCompress/*!*/ self ZSTD_outBuffer_s outBuf = new ZSTD_outBuffer_s { dst = d, size = (nuint)buf.Length, pos = 0 }; nuint ret = Z.ZSTD_compressStream2(ctx.Ptr, &outBuf, &inBuf, ZSTD_EndDirective.ZSTD_e_continue); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("compress error error code: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("compress error error code: " + Native.ErrorName(ret))); } total += input.Length; } @@ -828,7 +828,7 @@ public static object Write(RubyContext/*!*/ context, StreamingCompress/*!*/ self ZSTD_outBuffer_s outBuf = new ZSTD_outBuffer_s { dst = d, size = (nuint)buf.Length, pos = 0 }; ret = Z.ZSTD_compressStream2(ctx.Ptr, &outBuf, &inBuf, endOp); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("flush error error code: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("flush error error code: " + Native.ErrorName(ret))); } Append(result, buf, (int)outBuf.pos); } while (ret > 0); @@ -898,7 +898,7 @@ public static object Initialize(RubyContext/*!*/ context, StreamingDecompress/*! public static MutableString/*!*/ Decompress(RubyContext/*!*/ context, StreamingDecompress/*!*/ self, object src) { byte[] input = Args.StringValue(context, src).ToByteArray(); if (self._dctx == null) { - throw RubyExceptions.CreateTypeError("uninitialized Zstd::StreamingDecompress"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Zstd::StreamingDecompress")); } var result = new MemoryStream(); byte[] buf = self._buf; @@ -909,7 +909,7 @@ public static object Initialize(RubyContext/*!*/ context, StreamingDecompress/*! ZSTD_outBuffer_s outBuf = new ZSTD_outBuffer_s { dst = d, size = (nuint)buf.Length, pos = 0 }; nuint ret = Z.ZSTD_decompressStream(self._dctx.Ptr, &outBuf, &inBuf); if (Native.IsError(ret)) { - throw RubyExceptions.CreateRuntimeError("decompress error error code: " + Native.ErrorName(ret)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("decompress error error code: " + Native.ErrorName(ret))); } Append(result, buf, (int)outBuf.pos); } diff --git a/Src/Ruby/Builtins/CharacterMap.cs b/Src/Ruby/Builtins/CharacterMap.cs index a08da27c4..8b1f3d2f2 100644 --- a/Src/Ruby/Builtins/CharacterMap.cs +++ b/Src/Ruby/Builtins/CharacterMap.cs @@ -179,9 +179,9 @@ private static BitArray MakeBitmap(MutableString/*!*/ from, int fromLength, bool i++; char last = str.GetChar(i++); if (c > last) { - throw RubyExceptions.CreateArgumentError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError( String.Format("invalid range \"{0}-{1}\" in string transliteration", c, last) - ); + )); } for (char expanded = c; ; expanded++) { yield return expanded; diff --git a/Src/Ruby/Builtins/DescriptorStream.cs b/Src/Ruby/Builtins/DescriptorStream.cs index bd59b0b06..cea3c420b 100644 --- a/Src/Ruby/Builtins/DescriptorStream.cs +++ b/Src/Ruby/Builtins/DescriptorStream.cs @@ -235,7 +235,7 @@ public override int Read(byte[] buffer, int offset, int count) { byte[] chunk = new byte[count]; while (true) { if (_closed) { - throw RubyExceptions.CreateIOError("stream closed in another thread"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("stream closed in another thread")); } // Ask first, without waiting, and only then park in poll(2) - see WaitFor. @@ -268,7 +268,7 @@ public override int Read(byte[] buffer, int offset, int count) { // gone by now, so read(2) would report a bad descriptor rather than the // IOError Ruby defines for a stream closed underneath a blocked read. if (_closed) { - throw RubyExceptions.CreateIOError("stream closed in another thread"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("stream closed in another thread")); } int read = (int)sys_read(_descriptor, chunk, (IntPtr)count); @@ -281,7 +281,7 @@ public override int Read(byte[] buffer, int offset, int count) { } if (error == EISDIR) { // a directory opened by TryOpenDirectory - throw RubyExceptions.CreateEISDIR(_directoryPath ?? "read"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEISDIR(_directoryPath ?? "read")); } if (error == EIO) { // a pty master whose slave side is all closed - see InputOutputError @@ -411,7 +411,7 @@ public static bool IsReadableNow(int descriptor) { public int ReadNonBlocking(byte[]/*!*/ buffer, int offset, int count) { if (_closed) { - throw RubyExceptions.CreateIOError("stream closed in another thread"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("stream closed in another thread")); } SetNonBlocking(); byte[] chunk = new byte[count]; @@ -441,7 +441,7 @@ public int ReadNonBlocking(byte[]/*!*/ buffer, int offset, int count) { /// public int WriteNonBlocking(byte[]/*!*/ buffer, int offset, int count) { if (_closed) { - throw RubyExceptions.CreateIOError("stream closed in another thread"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("stream closed in another thread")); } SetNonBlocking(); return WriteOnce(buffer, offset, count); @@ -454,7 +454,7 @@ public int WriteNonBlocking(byte[]/*!*/ buffer, int offset, int count) { /// public int WriteOnce(byte[]/*!*/ buffer, int offset, int count) { if (_closed) { - throw RubyExceptions.CreateIOError("stream closed in another thread"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("stream closed in another thread")); } byte[] chunk = new byte[count]; Buffer.BlockCopy(buffer, offset, chunk, 0, count); diff --git a/Src/Ruby/Builtins/Hash.Storage.cs b/Src/Ruby/Builtins/Hash.Storage.cs index c98313438..9677367a2 100644 --- a/Src/Ruby/Builtins/Hash.Storage.cs +++ b/Src/Ruby/Builtins/Hash.Storage.cs @@ -475,7 +475,7 @@ private bool Insert(object key, object value, int behavior) { } if (_iterationLevel > 0) { - throw RubyExceptions.CreateRuntimeError("can't add a new key into hash during iteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("can't add a new key into hash during iteration")); } if (_count == _entries.Length) { @@ -633,7 +633,7 @@ public bool TryCopyEntriesFrom(Hash/*!*/ source) { } if (_iterationLevel > 0) { // what the first this[key] = value would raise - throw RubyExceptions.CreateRuntimeError("can't add a new key into hash during iteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("can't add a new key into hash during iteration")); } int size = GetPrime(liveCount); diff --git a/Src/Ruby/Builtins/Hash.cs b/Src/Ruby/Builtins/Hash.cs index 8e33315a8..6c048e9a2 100644 --- a/Src/Ruby/Builtins/Hash.cs +++ b/Src/Ruby/Builtins/Hash.cs @@ -83,7 +83,7 @@ public bool ComparesByIdentity { return this; } if (IsIterating) { - throw RubyExceptions.CreateRuntimeError("compare_by_identity during iteration"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("compare_by_identity during iteration")); } IEqualityComparer comparer = value ? IdentityComparer.Instance : defaultComparer; if (comparer == null) { diff --git a/Src/Ruby/Builtins/IOMode.cs b/Src/Ruby/Builtins/IOMode.cs index d58467235..383f148a3 100644 --- a/Src/Ruby/Builtins/IOMode.cs +++ b/Src/Ruby/Builtins/IOMode.cs @@ -102,7 +102,7 @@ public void RequireBinmodeForAsciiIncompatible(RubyContext/*!*/ context) { if ((@internal != null && @internal != external) || external.IsAsciiIdentity) { return; } - throw RubyExceptions.CreateArgumentError("ASCII incompatible encoding needs binmode"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("ASCII incompatible encoding needs binmode")); } public static IOInfo Parse(RubyContext/*!*/ context, MutableString/*!*/ modeAndEncoding) { @@ -125,7 +125,7 @@ public IOInfo AddModeAndEncoding(RubyContext/*!*/ context, MutableString/*!*/ mo // MRI refuses a second mode before it reads it: File.open(f, "w", mode: "rw+") is // "mode specified twice", not the "invalid access mode" the second one would be. if (_mode.HasValue) { - throw RubyExceptions.CreateArgumentError("mode specified twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("mode specified twice")); } IOInfo info = Parse(context, modeAndEncoding); @@ -137,7 +137,7 @@ public IOInfo AddModeAndEncoding(RubyContext/*!*/ context, MutableString/*!*/ mo return new IOInfo(info.Mode, _externalEncoding, _internalEncoding, info._textOrBinarySpecified); } - throw RubyExceptions.CreateArgumentError("encoding specified twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("encoding specified twice")); } public IOInfo AddEncoding(RubyContext/*!*/ context, MutableString/*!*/ encoding) { @@ -147,7 +147,7 @@ public IOInfo AddEncoding(RubyContext/*!*/ context, MutableString/*!*/ encoding) } if (HasEncoding) { - throw RubyExceptions.CreateArgumentError("encoding specified twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("encoding specified twice")); } string[] parts = encoding.ToString().Split(':'); @@ -235,7 +235,7 @@ public IOInfo AddOptions(ConversionStorage/*!*/ toStr, IDictionar // Encodings that came from the mode argument are a genuine conflict - unlike // :encoding, which MRI merely warns about. if (HasEncoding) { - throw RubyExceptions.CreateArgumentError("encoding specified twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("encoding specified twice")); } // The mode is carried over as the nullable it is: turning it into a concrete mode @@ -267,7 +267,7 @@ public IOInfo AddOptions(ConversionStorage/*!*/ toStr, IDictionar // :newline is a text-mode decorator, so it contradicts "b". if (options.TryGetValue(context.CreateAsciiSymbol("newline"), out optionValue) && (result.Mode & IOMode.PreserveEndOfLines) != 0) { - throw RubyExceptions.CreateArgumentError("newline decorator with binary mode"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("newline decorator with binary mode")); } // :flags is OR'd into whatever the mode argument already said. @@ -284,13 +284,13 @@ private static void CheckConversionOption(RubyContext/*!*/ context, IDictionary< object value; if (options.TryGetValue(context.CreateAsciiSymbol(name), out value) && value != null && !ReferenceEquals(value, context.CreateAsciiSymbol("replace"))) { - throw RubyExceptions.CreateArgumentError(message); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(message)); } } private IOInfo AddMode(RubyContext/*!*/ context, IOMode mode) { if (_mode.HasValue) { - throw RubyExceptions.CreateArgumentError("mode specified twice"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("mode specified twice")); } return new IOInfo(mode, _externalEncoding, _internalEncoding, _textOrBinarySpecified); } @@ -313,13 +313,13 @@ private IOInfo AddTextOrBinaryMode(RubyContext/*!*/ context, IDictionary= GroupCount || index < 0) { - throw RubyExceptions.CreateIndexError("index {0} out of matches", index); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("index {0} out of matches", index)); } } diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index 3ec3cb18f..8294c18cc 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -604,7 +604,7 @@ private uint FrozenOrCopyOnWrite(uint flags, int appendCount = 0) { } if ((flags & IsTemporarilyLockedFlag) != 0) { - throw RubyExceptions.CreateTemporarilyLockedError(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTemporarilyLockedError()); } if (_content.IsOffsetSlice) { @@ -831,7 +831,7 @@ private void MutateAppend(MutableString/*!*/ other, bool whole, int appendCount) // MRI's rb_str_append checks that the receiver can be modified before the encodings (str_modify_keep_cr in // rb_enc_cr_str_buf_cat): a frozen string raises FrozenError whatever it is given. RequireNotFrozen(); - throw RubyExceptions.CreateEncodingCompatibilityError(_encoding, other.Encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEncodingCompatibilityError(_encoding, other.Encoding)); } // an empty string is ASCII and has no surrogates, whether or not that has been worked out: @@ -954,7 +954,7 @@ public static RubyEncoding GetCompatibleEncoding(MutableString str1, RubyEncodin public RubyEncoding/*!*/ RequireCompatibleEncoding(MutableString/*!*/ other) { var result = GetCompatibleEncoding(other); if (result == null) { - throw RubyExceptions.CreateEncodingCompatibilityError(_encoding, other.Encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEncodingCompatibilityError(_encoding, other.Encoding)); } return result; } @@ -1045,7 +1045,7 @@ public void Transcode(RubyEncoding/*!*/ fromEncoding, RubyEncoding/*!*/ toEncodi try { _content.SwitchToBinaryContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (EncoderFallbackException e) { - throw RubyExceptions.CreateInvalidByteSequenceError(e, _encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, _encoding)); } SetEncoding(fromEncoding); switchToChars = true; @@ -1057,7 +1057,7 @@ public void Transcode(RubyEncoding/*!*/ fromEncoding, RubyEncoding/*!*/ toEncodi try { _content.SwitchToStringContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (DecoderFallbackException e) { - throw RubyExceptions.CreateInvalidByteSequenceError(e, fromEncoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, fromEncoding)); } } @@ -1066,7 +1066,7 @@ public void Transcode(RubyEncoding/*!*/ fromEncoding, RubyEncoding/*!*/ toEncodi try { _content.CheckEncoding(); } catch (EncoderFallbackException e) { - throw RubyExceptions.CreateTranscodingError(e, fromEncoding, toEncoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTranscodingError(e, fromEncoding, toEncoding)); } } @@ -1275,7 +1275,7 @@ public void RequireNotFrozen() { /// public MutableString/*!*/ LockTemporarily() { if ((_flags & IsTemporarilyLockedFlag) != 0) { - throw RubyExceptions.CreateTemporarilyLockedError(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTemporarilyLockedError()); } RequireNotFrozen(); _flags |= IsTemporarilyLockedFlag; @@ -1388,7 +1388,7 @@ internal string/*!*/ Dump { try { _content.SwitchToBinaryContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (EncoderFallbackException e) { - throw RubyExceptions.CreateInvalidByteSequenceError(e, _encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, _encoding)); } return this; } @@ -1404,7 +1404,7 @@ internal string/*!*/ Dump { try { _content.SwitchToStringContent(); // published by the switch, if this string still holds what it switched from (PublishSwitch) } catch (DecoderFallbackException e) { - throw RubyExceptions.CreateInvalidByteSequenceError(e, _encoding); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, _encoding)); } return this; } @@ -1474,7 +1474,7 @@ public static explicit operator char(MutableString/*!*/ self) { try { return self.GetChar(0); } catch (IndexOutOfRangeException) { - throw RubyExceptions.CreateTypeConversionError("String", "System::Char"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError("String", "System::Char")); } } diff --git a/Src/Ruby/Builtins/MutableStringStream.cs b/Src/Ruby/Builtins/MutableStringStream.cs index 5b8104150..1bce1c3d6 100644 --- a/Src/Ruby/Builtins/MutableStringStream.cs +++ b/Src/Ruby/Builtins/MutableStringStream.cs @@ -66,7 +66,7 @@ public override long Position { } set { if (value < 0) { - throw RubyExceptions.CreateIOError("Invalid argument"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("Invalid argument")); } _position = (int)value; } diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index bd09da7d6..72d720ca6 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -732,7 +732,7 @@ public object CallN(Proc procArg, object[]/*!*/ args) { var block = new BlockCallTargetUnsplatProcN((blockParam, self, args, unsplat, procArg) => { Debug.Assert(args.Length == 0); if (unsplat.Count == 0) { - throw RubyExceptions.CreateArgumentError("no receiver given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no receiver given")); } object target = unsplat[0]; unsplat.RemoveAt(0); diff --git a/Src/Ruby/Builtins/Range.cs b/Src/Ruby/Builtins/Range.cs index 1f989159c..d81b62af1 100644 --- a/Src/Ruby/Builtins/Range.cs +++ b/Src/Ruby/Builtins/Range.cs @@ -160,7 +160,7 @@ public void Initialize(BinaryOpStorage/*!*/ comparisonStorage, compareResult = site.Target(site, begin, end); if (compareResult == null) { - throw RubyExceptions.CreateArgumentError("bad value for range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("bad value for range")); } } diff --git a/Src/Ruby/Builtins/RubyBufferedStream.cs b/Src/Ruby/Builtins/RubyBufferedStream.cs index abc0b27cd..cd6b1a8c2 100644 --- a/Src/Ruby/Builtins/RubyBufferedStream.cs +++ b/Src/Ruby/Builtins/RubyBufferedStream.cs @@ -196,7 +196,7 @@ public void RequirePushBackRoom(int count) { _pushBackCapacity = Math.Max(count, MinPushBackCapacity); } if (_pushBackCapacity < _bufferCount + count) { - throw RubyExceptions.CreateIOError("ungetbyte failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("ungetbyte failed")); } } diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index eec562fd2..58387c66a 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -393,7 +393,7 @@ protected override bool CanIncludeClrInterface { public override Type/*!*/ GetUnderlyingSystemType() { if (_isSingletonClass) { - throw RubyExceptions.CreateTypeError("A singleton class doesn't have underlying system type."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("A singleton class doesn't have underlying system type.")); } if (_underlyingSystemType == null) { @@ -769,10 +769,10 @@ internal int InvalidateGroupsInSubClasses(string/*!*/ methodName, int maxLevel) object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers) { if (IsSingletonClass) { - throw RubyExceptions.CreateTypeError("can't copy singleton class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't copy singleton class")); } if (IsBasicObjectClass) { - throw RubyExceptions.CreateTypeError("can't copy the root class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't copy the root class")); } using (Context.ClassHierarchyLocker()) { @@ -839,17 +839,17 @@ object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers internal static RubyClass/*!*/ CheckInheritable(RubyContext/*!*/ context, object superClassObject) { RubyClass superClass = superClassObject as RubyClass; if (superClass == null) { - throw RubyExceptions.CreateTypeError("superclass must be an instance of Class (given an instance of {0})", - context.GetClassDisplayName(superClassObject)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("superclass must be an instance of Class (given an instance of {0})", + context.GetClassDisplayName(superClassObject))); } if (superClass.IsSingletonClass) { - throw RubyExceptions.CreateTypeError("can't make subclass of singleton class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't make subclass of singleton class")); } if (superClass == context.ClassClass) { - throw RubyExceptions.CreateTypeError("can't make subclass of Class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't make subclass of Class")); } if (superClass.IsUninitializedAllocation) { - throw RubyExceptions.CreateTypeError("can't inherit uninitialized class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't inherit uninitialized class")); } return superClass; } @@ -1057,7 +1057,7 @@ public bool TryGetClrMember(string/*!*/ name, Type asType, out RubyMemberInfo me // Note: We don't cache results as this API is not used so frequently (e.g. for regular method dispatch). if (asType != null && !asType.IsAssignableFrom(type)) { - throw RubyExceptions.CreateNameError(String.Format("'{0}' does not inherit from '{1}'", cls.Name, Context.GetTypeName(asType, true))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("'{0}' does not inherit from '{1}'", cls.Name, Context.GetTypeName(asType, true)))); } method = null; @@ -2203,7 +2203,7 @@ internal object AllocateBuiltin() { if ((ctor = GetConstructor(type)) != null) { return ctor.Invoke(Array.Empty()); } - throw RubyExceptions.CreateTypeError(String.Format("allocator undefined for {0}", Name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("allocator undefined for {0}", Name))); } internal void SetCAllocator(Func allocator) { diff --git a/Src/Ruby/Builtins/RubyEncoding.cs b/Src/Ruby/Builtins/RubyEncoding.cs index 7a0704012..6d80c48ba 100644 --- a/Src/Ruby/Builtins/RubyEncoding.cs +++ b/Src/Ruby/Builtins/RubyEncoding.cs @@ -362,7 +362,7 @@ private static void AddName(NameEntry entry) { private static void CheckAddable(string/*!*/ name) { if (_codePagesByName.ContainsKey(name)) { - throw RubyExceptions.CreateArgumentError(String.Format("encoding {0} is already registered", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("encoding {0} is already registered", name))); } } diff --git a/Src/Ruby/Builtins/RubyFile.cs b/Src/Ruby/Builtins/RubyFile.cs index ab7ec0115..bb0de0c48 100644 --- a/Src/Ruby/Builtins/RubyFile.cs +++ b/Src/Ruby/Builtins/RubyFile.cs @@ -74,7 +74,7 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO if (String.IsNullOrEmpty(path)) { // MRI treats the empty path as a missing file, not a bad argument. - throw RubyExceptions.CreateENOENT("No such file or directory - {0}", path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT("No such file or directory - {0}", path)); } Stream stream; @@ -84,7 +84,7 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO try { stream = context.DomainManager.Platform.OpenInputFileStream(path, fileMode, access, FileShare.ReadWrite); } catch (FileNotFoundException) { - throw RubyExceptions.CreateENOENT(String.Format("No such file or directory - {0}", path)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(String.Format("No such file or directory - {0}", path))); } catch (DirectoryNotFoundException e) { // The CLR says this for a missing directory on the way to the file and for a // file standing where a directory should be alike; MRI names the path, and @@ -98,34 +98,34 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO break; } } - throw RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", path)); } catch (PathTooLongException e) { // open(2) says ENAMETOOLONG; win32.c maps ERROR_FILENAME_EXCED_RANGE to ENOENT. if (System.IO.Path.DirectorySeparatorChar == '/') { - throw RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ENAMETOOLONG"), path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ENAMETOOLONG"), path)); } - throw RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(e, "No such file or directory - {0}", path)); } catch (IOException e) { if ((mode & IOMode.ErrorIfExists) != 0) { - throw RubyExceptions.CreateEEXIST(path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEEXIST(path)); } // On Unix the CLR puts the raw errno in HResult (Interop.GetExceptionForIoErrno); // on Windows HResult is an HRESULT and is negative. ENXIO is what open(2) answers // for /dev/tty without a controlling terminal, and MRI raises Errno::ENXIO there - // a bare IOException would have surfaced as IOError. if (e.HResult == ENXIO && System.IO.Path.DirectorySeparatorChar == '/') { - throw RubyExceptions.CreateENXIO(path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateENXIO(path)); } // Windows: a name with a character no file name may hold (<, |, ? ...) is // ERROR_INVALID_NAME, which MRI raises as Errno::EINVAL. method_source opens the // path of a method defined in "" and expects a SystemCallError. if (e.HResult == HResultInvalidName) { - throw RubyExceptions.CreateEINVAL(e, "{0}", path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL(e, "{0}", path)); } // Any other errno open(2) gave (ELOOP for a symbolic link loop, ...) is its Errno, // not the IOError a bare IOException surfaces as. if (e.HResult > 0 && System.IO.Path.DirectorySeparatorChar == '/') { - throw RubyExceptions.CreateErrno(context, e.HResult, path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, e.HResult, path)); } throw; } catch (UnauthorizedAccessException e) { @@ -140,13 +140,13 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO return directory; } } - throw RubyExceptions.CreateEISDIR(path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEISDIR(path)); } // Named by the path, as MRI's rb_sysopen does ("Permission denied - /etc/x"), // rather than by the CLR's own sentence about it. throw new UnauthorizedAccessException("Permission denied - " + path, e); } catch (ArgumentException e) { - throw RubyExceptions.CreateEINVAL(e.Message, e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL(e.Message, e)); } } diff --git a/Src/Ruby/Builtins/RubyIO.cs b/Src/Ruby/Builtins/RubyIO.cs index 0eb5ad369..3aaf7ff39 100644 --- a/Src/Ruby/Builtins/RubyIO.cs +++ b/Src/Ruby/Builtins/RubyIO.cs @@ -302,7 +302,7 @@ public bool AutoFlush { public RubyBufferedStream/*!*/ GetStream() { if (Closed) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } RequireInitialized(); @@ -396,7 +396,7 @@ public void RunNonBlocking(Action/*!*/ operation, bool isRead) { public void RequireInitialized() { if (!Closed && _stream == null) { - throw RubyExceptions.CreateIOError("uninitialized stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("uninitialized stream")); } } @@ -419,7 +419,7 @@ public void RequireReadable() { public void RequireByteReadable() { GetReadableStream(); if (_pendingCharCount > 0) { - throw RubyExceptions.CreateIOError("byte oriented read for character buffered IO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("byte oriented read for character buffered IO")); } } @@ -464,7 +464,7 @@ public void PushBackChars(byte[]/*!*/ bytes, int start, int count) { _pendingCharCapacity = Math.Max(count, MinPendingCharCapacity); } if (_pendingCharCapacity - _pendingCharCount < count) { - throw RubyExceptions.CreateIOError("ungetc failed"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("ungetc failed")); } InsertPendingChars(bytes, start, count, true); } @@ -550,10 +550,10 @@ public void ClearPendingChars() { public RubyBufferedStream/*!*/ GetWritableStream() { var result = GetStream(); if (!_mode.CanWrite()) { - throw RubyExceptions.CreateIOError("not opened for writing"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not opened for writing")); } if (!result.CanWrite) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } return result; } @@ -561,10 +561,10 @@ public void ClearPendingChars() { public RubyBufferedStream/*!*/ GetReadableStream() { var result = GetStream(); if (!_mode.CanRead()) { - throw RubyExceptions.CreateIOError("not opened for reading"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not opened for reading")); } if (!result.CanRead) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } return result; } @@ -579,7 +579,7 @@ public long Position { try { return stream.Position; } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } set { @@ -591,7 +591,7 @@ public long Position { try { stream.Position = value; } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } } @@ -608,7 +608,7 @@ public void Seek(long offset, SeekOrigin origin) { } catch (IOException) { throw CreateSeekError(); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -677,7 +677,7 @@ public void Flush() { try { stream.Flush(); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -742,7 +742,7 @@ public bool TryWriteUnbuffered(byte[]/*!*/ buffer, int offset, int count) { try { console.WriteUnbuffered(buffer, offset, count); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } return true; } @@ -753,7 +753,7 @@ public long Length { try { return stream.Length; } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -762,9 +762,9 @@ public long Length { try { stream.SetLength(value); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } catch (NotSupportedException) { - throw RubyExceptions.CreateIOError("not opened for writing"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("not opened for writing")); } } } @@ -814,7 +814,7 @@ private int WriteBytes(byte[] bytes, MutableString str, int index, int count, bo return stream.WriteBytes(str, index, count, preserveEndOfLines); } } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -868,7 +868,7 @@ public void CloseWriter() { return; } if (duplex == null && _mode.CanRead()) { - throw RubyExceptions.CreateIOError("closing non-duplex IO for writing"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closing non-duplex IO for writing")); } if (duplex != null) { @@ -888,7 +888,7 @@ public void CloseReader() { return; } if (duplex == null && _mode.CanWrite()) { - throw RubyExceptions.CreateIOError("closing non-duplex IO for reading"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closing non-duplex IO for reading")); } if (duplex != null) { @@ -912,7 +912,7 @@ public IOMode Mode { public virtual int SetReadTimeout(int timeout) { if (timeout > 0) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } return 0; } @@ -1334,7 +1334,7 @@ public virtual int FileControl(int commandId, int arg) { if (result < 0) { // what fcntl(2) said - EINVAL for an unknown command, EBADF, EAGAIN for a lock - // rather than EBADF whatever it was, as MRI's rb_sys_fail does - throw RubyExceptions.CreateErrno(_context, Marshal.GetLastPInvokeError(), null); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(_context, Marshal.GetLastPInvokeError(), null)); } // The descriptor's own O_APPEND is the answer wherever the kernel has one, but a // stream IronRuby opened in append mode without telling the kernel (the CLR @@ -1354,7 +1354,7 @@ protected static int NativeFileControl(int fd, int commandId, int arg) { } int result = LibcVariadic.Fcntl(fd, commandId, arg); if (result < 0) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } return result; } @@ -1397,7 +1397,7 @@ public int AppendBytes(MutableString/*!*/ buffer, int count) { try { return stream.AppendBytes(buffer, count, PreserveEndOfLines); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -1409,7 +1409,7 @@ public int AppendAvailableBytes(MutableString/*!*/ buffer, int count) { try { return stream.AppendAvailableBytes(buffer, count); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -1424,7 +1424,7 @@ public MutableString ReadLineOrParagraph(MutableString separator, int limit) { try { return stream.ReadLineOrParagraph(separator, ExternalEncoding, PreserveEndOfLines, limit >= 0 ? limit : Int32.MaxValue); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -1433,7 +1433,7 @@ public int ReadByteNormalizeEoln() { try { return stream.ReadByteNormalizeEoln(PreserveEndOfLines); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } @@ -1442,7 +1442,7 @@ public int PeekByteNormalizeEoln() { try { return stream.PeekByteNormalizeEoln(PreserveEndOfLines); } catch (ObjectDisposedException) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 8c333faee..41ad5abed 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -1000,7 +1000,7 @@ private void Mutate() { // `1.instance_eval { }' looks methods up through - is not a place to put one. MRI // refuses the same way, because there is no singleton class to put it in. if (IsDummySingletonClass) { - throw RubyExceptions.CreateTypeError("can't define singleton"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't define singleton")); } if (IsFrozen) { // MRI raises FrozenError and names what is frozen: @@ -1583,8 +1583,8 @@ public void SetConstantVisibility(string/*!*/ name, bool isPrivate) { // inherited from a superclass cannot have its visibility changed from here. ConstantStorage storage; if (!TryGetConstantNoAutoloadCheck(name, out storage)) { - throw RubyExceptions.CreateNameError(String.Format("constant {0}::{1} not defined", - Context.GetModuleDisplayName(this), name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("constant {0}::{1} not defined", + Context.GetModuleDisplayName(this), name))); } if (isPrivate) { @@ -1644,8 +1644,8 @@ public void SetConstantDeprecated(string/*!*/ name) { using (Context.ClassHierarchyLocker()) { ConstantStorage storage; if (!TryGetConstantNoAutoloadCheck(name, out storage)) { - throw RubyExceptions.CreateNameError(String.Format("constant {0}::{1} not defined", - Context.GetModuleDisplayName(this), name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("constant {0}::{1} not defined", + Context.GetModuleDisplayName(this), name))); } if (_deprecatedConstants == null) { @@ -2070,7 +2070,7 @@ private ConstantLookupResult TryLookupConstantNoLock(bool included, bool inherit } if (autoloadScope.Context != Context) { - throw RubyExceptions.CreateTypeError(String.Format("Cannot autoload constants to a foreign runtime #{0}", autoloadScope.Context.RuntimeId)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("Cannot autoload constants to a foreign runtime #{0}", autoloadScope.Context.RuntimeId))); } // Another thread is already running the file. MRI makes this one wait for it rather @@ -2369,7 +2369,7 @@ public void AddMethodAlias(string/*!*/ newName, string/*!*/ oldName, bool warn) } if (method == null) { - throw RubyExceptions.CreateUndefinedMethodError(this, oldName); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(this, oldName)); } // Alias preserves visibility and declaring module even though the alias is declared in a different module (e.g. subclass) => @@ -2552,8 +2552,8 @@ internal void SetMethodNoMutateNoEventNoLock(RubyContext/*!*/ callerContext, str Assert.NotNull(name, method); if (callerContext != _context) { - throw RubyExceptions.CreateTypeError(String.Format("Cannot define a method on a {0} '{1}' defined in a foreign runtime #{2}", - IsClass ? "class" : "module", _name, _context.RuntimeId)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("Cannot define a method on a {0} '{1}' defined in a foreign runtime #{2}", + IsClass ? "class" : "module", _name, _context.RuntimeId))); } if (newEntry) { diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 83c8e068e..c688dd529 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -162,7 +162,7 @@ public RubyRegex(RubyRegex/*!*/ regex) { ContractUtils.RequiresNotNull(regex, "regex"); // Regexp.new(re), #dup and #clone: MRI's rb_reg_init_copy checks the original if (!regex.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Regexp")); } Set(regex.Pattern, regex.Options); } @@ -357,7 +357,7 @@ private void RequireMatchableEncoding(MutableString/*!*/ input, bool allowBroken } if (!allowBroken && input.ContainsInvalidCharacters()) { - throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", input.Encoding.Name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", input.Encoding.Name)); } var patternEncoding = Encoding; @@ -381,7 +381,7 @@ private void RequireMatchableEncoding(MutableString/*!*/ input, bool allowBroken bool pinned; string error = Preprocess(_pattern.ToByteArray(), input.Encoding, (_options & RubyRegexOptions.Extended) != 0, out pinned); if (error != null) { - throw RubyExceptions.CreateArgumentError("regexp preprocess failed: " + error); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("regexp preprocess failed: " + error)); } } } @@ -2029,7 +2029,7 @@ public static MatchData SetCurrentMatchData(RubyScope/*!*/ scope, RubyRegex/*!*/ if (str != null) { // MRI's rb_reg_search checks the regexp (rb_reg_check), a nil subject does not if (!regex.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Regexp")); } regex.WarnHistoricalBinaryMatch(scope.RubyContext, str); } diff --git a/Src/Ruby/Builtins/RubyStruct.cs b/Src/Ruby/Builtins/RubyStruct.cs index 681837efb..feea6b3eb 100644 --- a/Src/Ruby/Builtins/RubyStruct.cs +++ b/Src/Ruby/Builtins/RubyStruct.cs @@ -352,7 +352,7 @@ public void SetValues(object[]/*!*/ items) { ContractUtils.RequiresNotNull(items, "items"); if (items.Length > _data.Length) { - throw RubyExceptions.CreateArgumentError("struct size differs"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("struct size differs")); } Array.Copy(items, _data, items.Length); diff --git a/Src/Ruby/CApi/CApi.Calls.cs b/Src/Ruby/CApi/CApi.Calls.cs index fc3d25ff7..bf2e1fd34 100644 --- a/Src/Ruby/CApi/CApi.Calls.cs +++ b/Src/Ruby/CApi/CApi.Calls.cs @@ -149,7 +149,7 @@ internal static object InvokeMethod(CMethod/*!*/ method, RubyScope/*!*/ scope, o private static void DefineMethod(RubyModule/*!*/ module, string/*!*/ name, IntPtr func, int arity, RubyMemberFlags visibility) { if (arity < -2 || arity > 15) { - throw RubyExceptions.CreateArgumentError(String.Format("arity out of range: {0} for -2..15", arity)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("arity out of range: {0} for -2..15", arity))); } // MRI's rb_define_method makes these private whatever it is asked (vm_method.c) if (name == "initialize" || name == "initialize_copy" || name == "initialize_clone" || @@ -165,7 +165,7 @@ private static void DefineMethod(RubyModule/*!*/ module, string/*!*/ name, IntPt private static RubyModule/*!*/ ToModule(VALUE value) { var module = FromValue(value) as RubyModule; if (module == null) { - throw RubyExceptions.CreateTypeError(String.Format("{0} is not a class/module", Inspect(FromValue(value)))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("{0} is not a class/module", Inspect(FromValue(value))))); } return module; } @@ -223,14 +223,14 @@ internal static void rb_define_attr(VALUE klass, byte* name, int read, int write internal static void rb_define_alloc_func(VALUE klass, IntPtr func) { var cls = FromValue(klass) as RubyClass; if (cls == null) { - throw RubyExceptions.CreateTypeError("allocator for a module"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("allocator for a module")); } _allocFuncs.AddOrUpdate(cls, new StrongBox(func)); var code = CurrentCode(); cls.SetCAllocator(c => { object obj = FromValue(CallFunc1(func, ToValue(c), code)); if (obj == null || !ReferenceEquals(_context.GetClassOf(obj).GetNonSingletonClass(), c) && !(obj is DataObject)) { - throw RubyExceptions.CreateTypeError(String.Format("wrong instance allocation")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong instance allocation"))); } return obj; }); @@ -241,7 +241,7 @@ internal static void rb_undef_alloc_func(VALUE klass) { if (cls != null) { _allocFuncs.AddOrUpdate(cls, new StrongBox(IntPtr.Zero)); cls.SetCAllocator(c => { - throw RubyExceptions.CreateTypeError(String.Format("allocator undefined for {0}", c.Name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("allocator undefined for {0}", c.Name))); }); } } @@ -262,7 +262,7 @@ internal static IntPtr GetAllocFunc(RubyClass/*!*/ cls) { internal static VALUE rb_ir_allocate_builtin(VALUE klass) { var cls = FromValue(klass) as RubyClass; if (cls == null) { - throw RubyExceptions.CreateTypeError("wrong argument type (expected Class)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type (expected Class)")); } return ToValue(cls.AllocateBuiltin()); } @@ -274,7 +274,7 @@ internal static VALUE rb_ir_allocate_builtin(VALUE klass) { internal static VALUE rb_ir_data_new(VALUE klass, int typed) { var cls = klass == 0 ? _context.ObjectClass : FromValue(klass) as RubyClass; if (cls == null) { - throw RubyExceptions.CreateTypeError("wrong argument type (expected Class)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type (expected Class)")); } var obj = new DataObject(cls.GetNonSingletonClass(), typed != 0, CurrentCode()); VALUE value = ToValue(obj); @@ -309,7 +309,7 @@ internal static object SendWith(bool publicOnly, object target, string/*!*/ name RubyScope scope = (_frame != null ? _frame.Scope : null) ?? _context.EmptyScope; if (name == "binding" && _frame != null && IsKernelBinding(target)) { // Kernel#binding would capture the frame of the C method's caller - throw RubyExceptions.CreateRuntimeError("Can't create Binding from C level function"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("Can't create Binding from C level function")); } var released = ReleaseForRuby(); try { @@ -367,11 +367,11 @@ internal static VALUE rb_funcallv_kw(VALUE recv, VALUE mid, int argc, VALUE* arg object converted = Send(last, "to_hash", null); hash = converted as IDictionary; if (hash == null) { - throw RubyExceptions.CreateTypeError(String.Format("can't convert {0} into Hash ({0}#to_hash gives {1})", - _context.GetClassDisplayName(last), _context.GetClassDisplayName(converted))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("can't convert {0} into Hash ({0}#to_hash gives {1})", + _context.GetClassDisplayName(last), _context.GetClassDisplayName(converted)))); } } else if (hash == null) { - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Hash", _context.GetClassDisplayName(last))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Hash", _context.GetClassDisplayName(last)))); } if (hash.Count == 0) { Array.Resize(ref args, args.Length - 1); @@ -407,7 +407,7 @@ internal static VALUE rb_call_super_kw(int argc, VALUE* argv, int kw_splat) { private static VALUE CallSuper(object[]/*!*/ args) { var frame = _frame; if (frame == null) { - throw RubyExceptions.CreateRuntimeError("super called outside of method"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("super called outside of method")); } object unbound = Send(frame.Method.Owner, "instance_method", null, _context.EncodeIdentifier(frame.Method.Name)); object super = Send(unbound, "super_method", null); @@ -471,7 +471,7 @@ internal static void rb_need_block() { internal static VALUE rb_block_proc() { var block = _frame?.Block; if (block == null) { - throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to create Proc object without a block")); } return ToValue(block); } diff --git a/Src/Ruby/CApi/CApi.Collections.cs b/Src/Ruby/CApi/CApi.Collections.cs index 88b2bff0f..e5cde2bde 100644 --- a/Src/Ruby/CApi/CApi.Collections.cs +++ b/Src/Ruby/CApi/CApi.Collections.cs @@ -24,7 +24,7 @@ internal static VALUE rb_ary_new() { internal static VALUE rb_ary_new_capa(long capa) { if (capa < 0) { - throw RubyExceptions.CreateArgumentError("negative array size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size (or size too big)")); } return ToValue(new RubyArray((int)Math.Min(capa, 1 << 20))); } @@ -60,7 +60,7 @@ internal static void rb_ary_store(VALUE ary, long idx, VALUE val) { if (idx < 0) { idx += len; if (idx < 0) { - throw RubyExceptions.CreateIndexError(String.Format("index {0} too small for array; minimum: -{1}", idx - len, len)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError(String.Format("index {0} too small for array; minimum: -{1}", idx - len, len))); } } object value = FromValue(val); @@ -173,7 +173,7 @@ internal static VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val) { internal static VALUE rb_hash_lookup2(VALUE hash, VALUE key, VALUE def) { var h = FromValue(hash) as IDictionary; if (h == null) { - throw RubyExceptions.CreateTypeError("wrong argument type (expected Hash)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type (expected Hash)")); } object value; if (Protocols.IsTrue(Send(h, "key?", null, FromValue(key)))) { diff --git a/Src/Ruby/CApi/CApi.Debug.cs b/Src/Ruby/CApi/CApi.Debug.cs index 1814e60c0..f863d9e77 100644 --- a/Src/Ruby/CApi/CApi.Debug.cs +++ b/Src/Ruby/CApi/CApi.Debug.cs @@ -53,7 +53,7 @@ internal static VALUE rb_tracepoint_new(VALUE target_thread, uint events, IntPtr private static TracePoint/*!*/ ToTracePoint(VALUE tpval) { var tp = FromValue(tpval) as TracePoint; if (tp == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected tracepoint)", ClassName(FromValue(tpval)))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected tracepoint)", ClassName(FromValue(tpval))))); } return tp; } @@ -179,7 +179,7 @@ internal static VALUE rb_debug_inspector_open(IntPtr func, void* data) { var frames = (InspectedFrame[])GCHandle.FromIntPtr((IntPtr)dc).Target; long i = index; if (i < 0 || i >= frames.Length) { - throw RubyExceptions.CreateArgumentError("no such frame"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no such frame")); } return frames[i]; } diff --git a/Src/Ruby/CApi/CApi.Io.cs b/Src/Ruby/CApi/CApi.Io.cs index 3be636c0e..17e49d336 100644 --- a/Src/Ruby/CApi/CApi.Io.cs +++ b/Src/Ruby/CApi/CApi.Io.cs @@ -90,21 +90,21 @@ private static void RefreshFptr(VALUE handle, RubyIO/*!*/ io) { private static RubyIO/*!*/ IoOf(void* fptr) { if (fptr == null) { - throw RubyExceptions.CreateIOError("uninitialized stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("uninitialized stream")); } var io = FromValue(*(VALUE*)((byte*)fptr + IoLayout()[1])) as RubyIO; if (io == null) { - throw RubyExceptions.CreateTypeError("not an IO"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("not an IO")); } return io; } private static RubyIO/*!*/ CheckOpen(RubyIO/*!*/ io) { if (!io.Initialized) { - throw RubyExceptions.CreateIOError("uninitialized stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("uninitialized stream")); } if (io.Closed) { - throw RubyExceptions.CreateIOError("closed stream"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError("closed stream")); } return io; } @@ -112,7 +112,7 @@ private static void RefreshFptr(VALUE handle, RubyIO/*!*/ io) { private static RubyIO/*!*/ OpenIo(VALUE io) { var rio = FromValue(io) as RubyIO; if (rio == null) { - throw RubyExceptions.CreateTypeError("wrong argument type " + _context.GetClassDisplayName(FromValue(io)) + " (expected IO)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type " + _context.GetClassDisplayName(FromValue(io)) + " (expected IO)")); } return CheckOpen(rio); } @@ -120,7 +120,7 @@ private static void RefreshFptr(VALUE handle, RubyIO/*!*/ io) { internal static VALUE rb_io_taint_check(VALUE obj) { object o = FromValue(obj); if (_context.IsObjectFrozen(o)) { - throw RubyExceptions.CreateObjectFrozenError(_context, o); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(_context, o)); } if (o is RubyIO io) { RefreshFptr(obj, io); @@ -139,7 +139,7 @@ internal static void rb_io_check_closed(void* fptr) { private static void CheckMode(void* fptr, int flag, string/*!*/ message) { RubyIO io = CheckOpen(IoOf(fptr)); if ((FileMode(io) & flag) == 0) { - throw RubyExceptions.CreateIOError(message); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIOError(message)); } } diff --git a/Src/Ruby/CApi/CApi.Library.cs b/Src/Ruby/CApi/CApi.Library.cs index 632494e95..0e788c8b8 100644 --- a/Src/Ruby/CApi/CApi.Library.cs +++ b/Src/Ruby/CApi/CApi.Library.cs @@ -71,15 +71,15 @@ private static object ConvertType(object obj, int type, string/*!*/ typeName, st return null; } string what = obj == null ? "nil" : obj is bool b ? (b ? "true" : "false") : ClassName(obj); - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into {1}", what, typeName)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into {1}", what, typeName))); } object result = Call(obj, method); if (result == null && !raise) { return null; } if (!HasType(result, type)) { - throw RubyExceptions.CreateTypeError(String.Format("can't convert {0} to {1} ({0}#{2} gives {3})", - ClassName(obj), typeName, method, ClassName(result))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("can't convert {0} to {1} ({0}#{2} gives {3})", + ClassName(obj), typeName, method, ClassName(result)))); } return result; } @@ -196,7 +196,7 @@ private static object Coerce(VALUE lhs, VALUE rhs, out object y) { object x = FromValue(lhs); var pair = Call(FromValue(rhs), "coerce", x) as RubyArray; if (pair == null || pair.Count != 2) { - throw RubyExceptions.CreateTypeError("coerce must return [x, y]"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("coerce must return [x, y]")); } y = pair[1]; return pair[0]; @@ -454,11 +454,11 @@ internal static VALUE rb_make_exception(int argc, VALUE* argv) { rb_error_arity(argc, 0, 3); } if (!RespondTo(first, "exception")) { - throw RubyExceptions.CreateTypeError("exception class/object expected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("exception class/object expected")); } object exc = argc == 1 ? Call(first, "exception") : Call(first, "exception", FromValue(argv[1])); if (!(exc is Exception)) { - throw RubyExceptions.CreateTypeError("exception object expected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("exception object expected")); } if (argc == 3) { Call(exc, "set_backtrace", FromValue(argv[2])); @@ -501,7 +501,7 @@ internal static VALUE rb_proc_new(IntPtr func, VALUE callback_arg) { internal static VALUE rb_block_lambda() { var block = _frame?.Block; if (block == null) { - throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("tried to create Proc object without a block")); } if (block.Kind == ProcKind.Lambda || _frame.Bfc != null && !_frame.Bfc.IsLiteralBlock) { // a Proc passed with &: CRuby hands it back as it is, lambda or not @@ -513,7 +513,7 @@ internal static VALUE rb_block_lambda() { internal static VALUE rb_yield_splat(VALUE ary) { var array = FromValue(ary) as RubyArray; if (array == null) { - throw RubyExceptions.CreateArgumentError("not an array"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("not an array")); } return Yield(array.ToArray()); } @@ -639,10 +639,10 @@ internal static VALUE rb_marshal_load(VALUE port) { internal static VALUE rb_gc_latest_gc_info(VALUE key) { object k = FromValue(key); if (!(k is RubySymbol) && !(k is IDictionary)) { - throw RubyExceptions.CreateTypeError("non-hash or symbol given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("non-hash or symbol given")); } if (k is RubySymbol sym && !((IDictionary)Call(Constant("GC"), "latest_gc_info")).ContainsKey(sym)) { - throw RubyExceptions.CreateArgumentError("unknown key: " + sym); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown key: " + sym)); } return ToValue(Call(Constant("GC"), "latest_gc_info", k)); } @@ -654,11 +654,11 @@ internal static VALUE rb_struct_initialize(VALUE self, VALUE values) { if (data != null && _context.IsKindOf(obj, data)) { // a Data object takes its members positionally here, the missing ones nil, and is frozen after if (_context.IsObjectFrozen(obj)) { - throw RubyExceptions.CreateObjectFrozenError(_context, obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(_context, obj)); } var members = (RubyArray)Call(_context.GetClassOf(obj), "members"); if (args.Length > members.Count) { - throw RubyExceptions.CreateArgumentError("struct size differs"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("struct size differs")); } var keywords = new Hash(_context.EqualityComparer, members.Count); for (int i = 0; i < members.Count; i++) { @@ -711,7 +711,7 @@ private static VALUE RangeBegLen(VALUE range, long* begp, long* lenp, long len, } VALUE r = RangeComponentBegLen(b, e, excl, begp, lenp, len, err); if (r == Qnil && err != 0) { - throw RubyExceptions.CreateRangeError(String.Format("{0} out of range", ToMutableString(rb_inspect(range)))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("{0} out of range", ToMutableString(rb_inspect(range))))); } return r; } @@ -786,7 +786,7 @@ internal static int rb_arithmetic_sequence_extract(VALUE obj, void* buf) { internal static VALUE rb_arithmetic_sequence_beg_len_step(VALUE obj, System.Runtime.InteropServices.CLong* begp, System.Runtime.InteropServices.CLong* lenp, System.Runtime.InteropServices.CLong* stepp, long len, int err) { if (begp == null || lenp == null || stepp == null) { - throw RubyExceptions.CreateArgumentError("NULL pointer given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("NULL pointer given")); } ArithmeticSequenceComponents aseq; if (rb_arithmetic_sequence_extract(obj, &aseq) == 0) { @@ -829,7 +829,7 @@ internal static VALUE rb_arithmetic_sequence_beg_len_step(VALUE obj, System.Runt } return result; } - throw RubyExceptions.CreateRangeError(String.Format("{0} out of range", ToMutableString(rb_inspect(obj)))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("{0} out of range", ToMutableString(rb_inspect(obj))))); } internal static VALUE rb_reg_new(byte* src, long len, int opts) { @@ -993,7 +993,7 @@ internal static VALUE rb_ary_resize(VALUE ary, long len) { if (len < 0) { len += array.Count; if (len < 0) { - throw RubyExceptions.CreateIndexError(String.Format("index {0} too small for array; minimum: -{1}", len - array.Count, array.Count)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError(String.Format("index {0} too small for array; minimum: -{1}", len - array.Count, array.Count))); } } while (array.Count > len) { @@ -1226,8 +1226,8 @@ internal static int rb_get_kwargs(VALUE keyword_hash, VALUE* table, int required } } if (missing.Count > 0) { - throw RubyExceptions.CreateArgumentError(String.Format("missing keyword{0}: {1}", missing.Count > 1 ? "s" : "", - String.Join(", ", missing.ConvertAll(k => ":" + k)))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("missing keyword{0}: {1}", missing.Count > 1 ? "s" : "", + String.Join(", ", missing.ConvertAll(k => ":" + k))))); } if (!rest && hash != null && hash.Count > (values != null ? 0 : found)) { var known = new HashSet(); @@ -1241,7 +1241,7 @@ internal static int rb_get_kwargs(VALUE keyword_hash, VALUE* table, int required } } if (unknown.Count > 0) { - throw RubyExceptions.CreateArgumentError(String.Format("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", unknown))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("unknown keyword{0}: {1}", unknown.Count > 1 ? "s" : "", String.Join(", ", unknown)))); } } return found; diff --git a/Src/Ruby/CApi/CApi.Mirrors.cs b/Src/Ruby/CApi/CApi.Mirrors.cs index 385c1a2bc..b22de62d3 100644 --- a/Src/Ruby/CApi/CApi.Mirrors.cs +++ b/Src/Ruby/CApi/CApi.Mirrors.cs @@ -315,7 +315,7 @@ private static void LeaveManaged(int unused) { var obj = FromValue(value); var str = obj as MutableString; if (str == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected String)", ClassName(obj))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected String)", ClassName(obj)))); } return str; } @@ -324,7 +324,7 @@ private static void LeaveManaged(int unused) { var obj = FromValue(value); var array = obj as RubyArray; if (array == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Array)", ClassName(obj))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Array)", ClassName(obj)))); } return array; } diff --git a/Src/Ruby/CApi/CApi.Numbers.cs b/Src/Ruby/CApi/CApi.Numbers.cs index 245bf986e..3a6f9e045 100644 --- a/Src/Ruby/CApi/CApi.Numbers.cs +++ b/Src/Ruby/CApi/CApi.Numbers.cs @@ -46,15 +46,15 @@ private static BigInteger ToBigInteger(object obj, string/*!*/ ctype) { } if (obj is double d) { if (Double.IsNaN(d) || Double.IsInfinity(d) || Math.Truncate(d) > 9.3e18 || Math.Truncate(d) < -9.3e18) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", FormatFloat(d))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", FormatFloat(d)))); } return new BigInteger(Math.Truncate(d)); } if (obj == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion from nil to integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion from nil to integer")); } if (obj is bool b) { - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", b ? "true" : "false")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", b ? "true" : "false"))); } // a String is no Integer to C (rb_to_int), whatever Kernel#Integer would make of it if (!(obj is MutableString)) { @@ -63,7 +63,7 @@ private static BigInteger ToBigInteger(object obj, string/*!*/ ctype) { return r.Value; } } - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", ClassName(obj))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", ClassName(obj)))); } // rb_num2long's "%-.10g" @@ -83,7 +83,7 @@ private static long ToLong(VALUE value, string ctype, long min = Int64.MinValue, object obj = FromValue(value); BigInteger b = ToBigInteger(obj, ctype); if (b < min || b > max) { - throw RubyExceptions.CreateRangeError(String.Format("bignum too big to convert into '{0}'", ctype)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("bignum too big to convert into '{0}'", ctype))); } return (long)b; } @@ -95,7 +95,7 @@ private static ulong ToULong(VALUE value, string ctype, ulong max = UInt64.MaxVa BigInteger b = ToBigInteger(FromValue(value), ctype); // CRuby accepts the negative values of the signed type and wraps them if (b < -(BigInteger)max / 2 - 1 || b > max) { - throw RubyExceptions.CreateRangeError(String.Format("bignum out of range of {0}", ctype)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("bignum out of range of {0}", ctype))); } return b < 0 ? (ulong)(long)b & max : (ulong)b; } @@ -118,7 +118,7 @@ internal static ulong rb_num2ull(VALUE num) { private static void CheckInt(long n, string ctype, long min, long max) { if (n < min || n > max) { - throw RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to '{2}'", n, n < min ? "small" : "big", ctype)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to '{2}'", n, n < min ? "small" : "big", ctype))); } } @@ -140,7 +140,7 @@ internal static ulong rb_num2uint(VALUE num) { long n = ToLong(num, "unsigned int"); // CRuby accepts INT_MIN..UINT_MAX and wraps the negatives (check_uint) if (n < Int32.MinValue || n > UInt32.MaxValue) { - throw RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'unsigned int'", n, n < 0 ? "small" : "big")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'unsigned int'", n, n < 0 ? "small" : "big"))); } return (ulong)n; } @@ -158,7 +158,7 @@ internal static short rb_fix2short(VALUE num) { internal static ushort rb_num2ushort(VALUE num) { long n = ToLong(num, "unsigned short"); if (n < -UInt16.MaxValue || n > UInt16.MaxValue) { - throw RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'unsigned short'", n, n < 0 ? "small" : "big")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'unsigned short'", n, n < 0 ? "small" : "big"))); } return (ushort)n; } @@ -169,7 +169,7 @@ internal static VALUE rb_num2fix(VALUE val) { } long n = rb_num2long(val); if (n < FixnumMin || n > FixnumMax) { - throw RubyExceptions.CreateRangeError(String.Format("integer {0} out of range of fixnum", n)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} out of range of fixnum", n))); } return ((VALUE)n << 1) | 1; } @@ -193,15 +193,15 @@ internal static double rb_num2dbl(VALUE num) { case int i: return i; case long l: return l; case BigInteger b: return (double)b; - case null: throw RubyExceptions.CreateTypeError("no implicit conversion to float from nil"); - case bool b: throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion to float from {0}", b ? "true" : "false")); - case MutableString _: throw RubyExceptions.CreateTypeError("no implicit conversion to float from string"); + case null: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion to float from nil")); + case bool b: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion to float from {0}", b ? "true" : "false"))); + case MutableString _: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion to float from string")); } object f = Send(obj, "to_f", null); if (f is double r) { return r; } - throw RubyExceptions.CreateTypeError(String.Format("can't convert {0} into Float", ClassName(obj))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("can't convert {0} into Float", ClassName(obj)))); } internal static VALUE rb_float_new(double d) { @@ -217,7 +217,7 @@ internal static double rb_float_value(VALUE num) { if (obj is double d) { return d; } - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Float)", ClassName(obj))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Float)", ClassName(obj)))); } internal static VALUE rb_dbl2big(double d) { @@ -233,7 +233,7 @@ internal static VALUE rb_dbl2big(double d) { internal static double rb_big2dbl(VALUE x) { var b = AsInteger(FromValue(x)); if (!b.HasValue) { - throw RubyExceptions.CreateTypeError("wrong argument type (expected Integer)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type (expected Integer)")); } return (double)b.Value; } @@ -289,9 +289,9 @@ internal static VALUE rb_to_int(VALUE val) { if (AsInteger(r).HasValue) { return ToValue(r); } - throw RubyExceptions.CreateTypeError(String.Format("can't convert {0} to Integer ({0}#to_int gives {1})", ClassName(obj), ClassName(r))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("can't convert {0} to Integer ({0}#to_int gives {1})", ClassName(obj), ClassName(r)))); } - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", obj == null ? "nil" : ClassName(obj))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into Integer", obj == null ? "nil" : ClassName(obj)))); } internal static VALUE rb_cstr_to_inum(byte* str, int base_, int badcheck) { @@ -341,7 +341,7 @@ internal static VALUE rb_int_positive_pow(long x, ulong y) { /// internal static int rb_integer_pack(VALUE val, void* words, nuint numwords, nuint wordsize, nuint nails, int flags) { if (nails != 0) { - throw RubyExceptions.CreateNotImplementedError("rb_integer_pack with nails is not implemented by IronRuby's C API yet"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNotImplementedError("rb_integer_pack with nails is not implemented by IronRuby's C API yet")); } BigInteger value = ToBigInteger(FromValue(val), "integer"); int sign = value.Sign; diff --git a/Src/Ruby/CApi/CApi.Objects.cs b/Src/Ruby/CApi/CApi.Objects.cs index 4119276f7..8ec4559c2 100644 --- a/Src/Ruby/CApi/CApi.Objects.cs +++ b/Src/Ruby/CApi/CApi.Objects.cs @@ -58,7 +58,7 @@ private static object GetOwnConstant(RubyModule/*!*/ owner, string/*!*/ name, ou private static RubyClass/*!*/ DefineClassUnder(RubyModule/*!*/ owner, string/*!*/ name, VALUE super) { if (super == 0) { // NULL, as opposed to Qnil - throw RubyExceptions.CreateArgumentError(String.Format("no super class for '{0}'", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("no super class for '{0}'", name))); } object superObject = FromValue(super); RubyClass superClass = RubyClass.CheckInheritable(_context, superObject); @@ -67,10 +67,10 @@ private static object GetOwnConstant(RubyModule/*!*/ owner, string/*!*/ name, ou if (found) { var cls = existing as RubyClass; if (cls == null || !cls.IsClass) { - throw RubyExceptions.CreateTypeError(String.Format("{0} is not a class ({1})", name, ClassName(existing))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("{0} is not a class ({1})", name, ClassName(existing)))); } if (!ReferenceEquals(cls.SuperClass, superClass)) { - throw RubyExceptions.CreateTypeError(String.Format("superclass mismatch for class {0}", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("superclass mismatch for class {0}", name))); } return cls; } @@ -83,7 +83,7 @@ private static object GetOwnConstant(RubyModule/*!*/ owner, string/*!*/ name, ou if (found) { var module = existing as RubyModule; if (module == null || module.IsClass) { - throw RubyExceptions.CreateTypeError(String.Format("{0} is not a module ({1})", name, ClassName(existing))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("{0} is not a module ({1})", name, ClassName(existing)))); } return module; } @@ -126,7 +126,7 @@ internal static VALUE rb_class_get_superclass(VALUE klass) { internal static VALUE rb_class_inherited_p(VALUE scion, VALUE ascendant) { if (!(FromValue(ascendant) is RubyModule)) { - throw RubyExceptions.CreateTypeError("compared with non class/module"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("compared with non class/module")); } return ToValue(Send(FromValue(scion), "<=", null, FromValue(ascendant))); } @@ -159,12 +159,12 @@ internal static VALUE rb_path2class(byte* path) { var module = current as RubyModule; // const_get loads an autoload, as CRuby's rb_path_to_class does if (module == null || !Protocols.IsTrue(Send(module, "const_defined?", null, _context.EncodeIdentifier(name), false))) { - throw RubyExceptions.CreateArgumentError(String.Format("undefined class/module {0}", p)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("undefined class/module {0}", p))); } current = Send(module, "const_get", null, _context.EncodeIdentifier(name), false); } if (!(current is RubyModule)) { - throw RubyExceptions.CreateTypeError(String.Format("{0} does not refer to class/module", p)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("{0} does not refer to class/module", p))); } return ToValue(current); } @@ -389,9 +389,9 @@ internal static void rb_check_type(VALUE obj, int t) { internal static void rb_unexpected_type(VALUE self, int t) { string expected; if (!_typeNames.TryGetValue(t, out expected)) { - throw RubyExceptions.CreateRuntimeError(String.Format("unknown type 0x{0:x} ({1} given)", t, ClassName(FromValue(self)))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError(String.Format("unknown type 0x{0:x} ({1} given)", t, ClassName(FromValue(self))))); } - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected {1})", ClassName(FromValue(self)), expected)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected {1})", ClassName(FromValue(self)), expected))); } #endregion @@ -418,7 +418,7 @@ private static RubySymbol CheckSymbol(VALUE* namep) { var str = name as MutableString; if (str == null) { if (!RespondTo(name, "to_str")) { - throw RubyExceptions.CreateTypeError(String.Format("{0} is not a symbol nor a string", Inspect(name))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("{0} is not a symbol nor a string", Inspect(name)))); } str = (MutableString)ConvertType(name, T_STRING, "String", "to_str", true); *namep = ToValue(str); @@ -456,7 +456,7 @@ internal static VALUE rb_to_id(VALUE name) { if (o is MutableString str) { return SymbolToId(_context.CreateSymbol(str)); } - throw RubyExceptions.CreateTypeError(String.Format("{0} is not a symbol nor a string", Inspect(o))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("{0} is not a symbol nor a string", Inspect(o)))); } internal static VALUE rb_id2sym(VALUE id) { @@ -469,7 +469,7 @@ internal static VALUE rb_sym2id(VALUE obj) { } var sym = FromValue(obj) as RubySymbol; if (sym == null) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Symbol)", ClassName(FromValue(obj)))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected Symbol)", ClassName(FromValue(obj))))); } return SymbolToId(sym); } @@ -540,7 +540,7 @@ internal static void rb_jump_tag(int state) { // raised on: the rescue that catches it is Ruby's, which leaves ec->errinfo nil in CRuby _errinfo = null; if (e == null) { - throw RubyExceptions.CreateRuntimeError(String.Format("rb_jump_tag({0}) with nothing to rethrow", state)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError(String.Format("rb_jump_tag({0}) with nothing to rethrow", state))); } System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e).Throw(); } @@ -557,7 +557,7 @@ internal static int rb_ir_rescue_match(int count, VALUE* classes) { // as a rescue clause naming something else does: the exception is lost _caught = null; _errinfo = null; - throw RubyExceptions.CreateTypeError("class or module required for rescue clause"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("class or module required for rescue clause")); } if (!matched && _context.IsKindOf(RubyUtils.GetVisibleException(e), module)) { matched = true; @@ -573,7 +573,7 @@ internal static VALUE rb_errinfo() { internal static void rb_set_errinfo(VALUE err) { object e = FromValue(err); if (e != null && !(e is Exception)) { - throw RubyExceptions.CreateTypeError("assigning non-exception to $!"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("assigning non-exception to $!")); } _errinfo = (Exception)e; } @@ -631,26 +631,26 @@ internal static void rb_memerror() { internal static void rb_error_arity(int argc, int min, int max) { string expected = min == max ? min.ToString() : max == -1 || max == Int32.MaxValue ? min + "+" : min + ".." + max; - throw RubyExceptions.CreateArgumentError(String.Format("wrong number of arguments (given {0}, expected {1})", argc, expected)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("wrong number of arguments (given {0}, expected {1})", argc, expected))); } internal static void rb_error_frozen_object(VALUE what) { object o = FromValue(what); - throw RubyExceptions.CreateObjectFrozenError(_context, o); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(_context, o)); } internal static void rb_scan_args_bad_format(byte* fmt) { - throw RubyExceptions.CreateRuntimeError(String.Format("bad scan arg format: {0}", FromCString(fmt))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError(String.Format("bad scan arg format: {0}", FromCString(fmt)))); } internal static void rb_scan_args_length_mismatch(byte* fmt, int argc) { - throw RubyExceptions.CreateRuntimeError(String.Format("variable argument length mismatch: {0} {1}", argc, FromCString(fmt))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError(String.Format("variable argument length mismatch: {0} {1}", argc, FromCString(fmt)))); } internal static void rb_cmperr(VALUE a, VALUE b) { object y = FromValue(b); string what = (y == null || y is bool || y is int || y is double) ? Inspect(y) : ClassName(y); - throw RubyExceptions.CreateArgumentError(String.Format("comparison of {0} with {1} failed", ClassName(FromValue(a)), what)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("comparison of {0} with {1} failed", ClassName(FromValue(a)), what))); } internal static int rb_cmpint(VALUE val, VALUE a, VALUE b) { @@ -675,7 +675,7 @@ internal static void rb_ir_warn(VALUE message, int verbose_only) { } internal static void rb_ir_raise_notimp(byte* name) { - throw RubyExceptions.CreateNotImplementedError(String.Format("{0}() is not implemented by IronRuby's C API yet", FromCString(name))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNotImplementedError(String.Format("{0}() is not implemented by IronRuby's C API yet", FromCString(name)))); } internal static void rb_ir_bug(byte* message) { diff --git a/Src/Ruby/CApi/CApi.Strings.cs b/Src/Ruby/CApi/CApi.Strings.cs index 96448d528..d624fa4db 100644 --- a/Src/Ruby/CApi/CApi.Strings.cs +++ b/Src/Ruby/CApi/CApi.Strings.cs @@ -64,7 +64,7 @@ internal static int EncodingIndex(RubyEncoding/*!*/ encoding) { lock (_encodingLock) { InitializeEncodings(); if (index < 0 || index >= _encodings.Count) { - throw RubyExceptions.CreateArgumentError(String.Format("invalid encoding index {0}", index)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("invalid encoding index {0}", index))); } return _encodings[index]; } @@ -129,7 +129,7 @@ internal static RubyEncoding FromNativeEncoding(void* enc) { } } } - throw RubyExceptions.CreateArgumentError("not an rb_encoding IronRuby handed out"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("not an rb_encoding IronRuby handed out")); } private static RubyEncoding GetEncoding(object obj) { @@ -167,9 +167,9 @@ private static void SetEncoding(object obj, RubyEncoding/*!*/ encoding) { } return; case RubySymbol _: - throw RubyExceptions.CreateRuntimeError("cannot modify the encoding of a Symbol"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("cannot modify the encoding of a Symbol")); } - throw RubyExceptions.CreateArgumentError(String.Format("cannot set encoding on non-encoding capable object")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("cannot set encoding on non-encoding capable object"))); } internal static void* rb_enc_get(VALUE obj) { @@ -226,7 +226,7 @@ internal static int rb_enc_find_index(byte* name) { var name = FromValue(rb_str_to_str(obj)).ToString(); var found = FindEncoding(name); if (found == null) { - throw RubyExceptions.CreateArgumentError(String.Format("unknown encoding name - {0}", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("unknown encoding name - {0}", name))); } return NativeEncoding(found); } @@ -238,7 +238,7 @@ internal static VALUE rb_enc_from_encoding(void* enc) { internal static VALUE rb_obj_encoding(VALUE obj) { var e = GetEncoding(FromValue(obj)); if (e == null) { - throw RubyExceptions.CreateTypeError("unknown encoding"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("unknown encoding")); } return ToValue(e); } @@ -437,9 +437,9 @@ internal static VALUE rb_str_to_str(VALUE obj) { if (r is MutableString rs) { return rs; } - throw RubyExceptions.CreateTypeError(String.Format("can't convert {0} to String ({0}#to_str gives {1})", ClassName(o), ClassName(r))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("can't convert {0} to String ({0}#to_str gives {1})", ClassName(o), ClassName(r)))); } - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into String", ClassName(o))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into String", ClassName(o)))); } internal static VALUE rb_string_value(VALUE* ptr) { @@ -461,7 +461,7 @@ internal static VALUE rb_string_value(VALUE* ptr) { nul &= bytes[i + j] == 0; } if (nul) { - throw RubyExceptions.CreateArgumentError("string contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("string contains null byte")); } } return GetStringMirror(s).Ptr; @@ -480,7 +480,7 @@ internal static VALUE rb_check_string_type(VALUE obj) { if (r is MutableString) { return ToValue(r); } - throw RubyExceptions.CreateTypeError(String.Format("can't convert {0} to String ({0}#to_str gives {1})", ClassName(o), ClassName(r))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("can't convert {0} to String ({0}#to_str gives {1})", ClassName(o), ClassName(r)))); } return Qnil; } @@ -610,7 +610,7 @@ internal static VALUE rb_str_cat(VALUE dst, byte* src, long srclen) { var s = ToMutableString(dst); s.RequireNotFrozen(); if (srclen < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } s.Append(Bytes(src, srclen)); return dst; @@ -650,7 +650,7 @@ internal static void rb_str_modify_expand(VALUE str, long expand) { var s = ToMutableString(str); s.RequireNotFrozen(); if (expand < 0) { - throw RubyExceptions.CreateArgumentError("negative expanding string size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative expanding string size")); } GetStringMirror(s).EnsureCapacity(checked(s.GetByteCount() + (int)expand)); } @@ -660,7 +660,7 @@ internal static void rb_str_set_len(VALUE str, long len) { s.RequireNotFrozen(); var mirror = GetStringMirror(s); if (len < 0 || len > mirror.Capacity) { - throw RubyExceptions.CreateArgumentError(String.Format("probable buffer overflow: {0} for {1}", len, mirror.Capacity)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("probable buffer overflow: {0} for {1}", len, mirror.Capacity))); } mirror.SetLength((int)len); } @@ -668,7 +668,7 @@ internal static void rb_str_set_len(VALUE str, long len) { internal static VALUE rb_str_resize(VALUE str, long len) { var s = ToMutableString(str); if (len < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } if (len != s.GetByteCount()) { s.RequireNotFrozen(); @@ -682,7 +682,7 @@ internal static VALUE rb_str_resize(VALUE str, long len) { internal static VALUE rb_str_locktmp(VALUE str) { var s = ToMutableString(str); if (s.IsTemporarilyLocked) { - throw RubyExceptions.CreateRuntimeError("temporal locking already locked string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("temporal locking already locked string")); } s.LockTemporarily(); return str; @@ -691,10 +691,10 @@ internal static VALUE rb_str_locktmp(VALUE str) { internal static VALUE rb_str_unlocktmp(VALUE str) { var s = ToMutableString(str); if (s.IsFrozen) { - throw RubyExceptions.CreateObjectFrozenError(_context, s); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenError(_context, s)); } if (!s.IsTemporarilyLocked) { - throw RubyExceptions.CreateRuntimeError("temporal unlocking already unlocked string"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("temporal unlocking already unlocked string")); } s.UnlockTemporarily(); return str; diff --git a/Src/Ruby/CApi/CApi.Values.cs b/Src/Ruby/CApi/CApi.Values.cs index 2e4a2ba68..2ec09fb18 100644 --- a/Src/Ruby/CApi/CApi.Values.cs +++ b/Src/Ruby/CApi/CApi.Values.cs @@ -154,7 +154,7 @@ internal static object FromValue(VALUE value) { case Qfalse: return ScriptingRuntimeHelpers.False; case Qnil: return null; case Qtrue: return ScriptingRuntimeHelpers.True; - case Qundef: throw RubyExceptions.CreateArgumentError("Qundef passed where a Ruby object is expected"); + case Qundef: throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("Qundef passed where a Ruby object is expected")); } if ((value & 3) == 2) { return FlonumToDouble(value); @@ -172,12 +172,12 @@ internal static object FromValue(VALUE value) { } } } - throw RubyExceptions.CreateArgumentError(String.Format("0x{0:x16} is not a VALUE IronRuby handed out", value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("0x{0:x16} is not a VALUE IronRuby handed out", value))); } internal static object[]/*!*/ FromValues(int argc, VALUE* argv) { if (argc < 0) { - throw RubyExceptions.CreateArgumentError("negative argument count"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative argument count")); } var result = new object[argc]; for (int i = 0; i < argc; i++) { @@ -257,7 +257,7 @@ internal static VALUE SymbolToId(RubySymbol/*!*/ symbol) { return _symbols[(int)serial]; } } - throw RubyExceptions.CreateArgumentError(String.Format("{0} is not an ID IronRuby handed out", id)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(String.Format("{0} is not an ID IronRuby handed out", id))); } internal static string/*!*/ IdToString(VALUE id) { diff --git a/Src/Ruby/CApi/CApi.Variables.cs b/Src/Ruby/CApi/CApi.Variables.cs index 4812d9ed0..9197e9600 100644 --- a/Src/Ruby/CApi/CApi.Variables.cs +++ b/Src/Ruby/CApi/CApi.Variables.cs @@ -57,7 +57,7 @@ internal static VALUE rb_time_nano_new(long sec, long nsec) { // offset INT_MAX: local time; INT_MAX - 1: UTC; otherwise seconds east of UTC internal static VALUE rb_time_timespec_new(TimeSpec* ts, int offset) { if (offset != Int32.MaxValue && offset != Int32.MaxValue - 1 && (offset <= -86400 || offset >= 86400)) { - throw RubyExceptions.CreateArgumentError("utc_offset out of range"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("utc_offset out of range")); } object t = TimeFromParts(ts->tv_sec, ts->tv_nsec, 1000000000); if (offset == Int32.MaxValue) { @@ -72,7 +72,7 @@ internal static VALUE rb_time_timespec_new(TimeSpec* ts, int offset) { private static void TimeParts(object obj, bool interval, out long sec, out long nsec) { if (_context.GetClassOf(obj).GetNonSingletonClass() == Constant("Time")) { if (interval) { - throw RubyExceptions.CreateTypeError("can't convert Time into time interval"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't convert Time into time interval")); } sec = Convert.ToInt64(Call(obj, "to_i")); nsec = Convert.ToInt64(Call(obj, "nsec")); @@ -81,7 +81,7 @@ private static void TimeParts(object obj, bool interval, out long sec, out long var i = AsInteger(obj); if (i.HasValue) { if (interval && i.Value < 0) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } sec = (long)i.Value; nsec = 0; @@ -89,7 +89,7 @@ private static void TimeParts(object obj, bool interval, out long sec, out long } if (obj is double d) { if (interval && d < 0) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } double f = Math.Floor(d); sec = (long)f; @@ -97,10 +97,10 @@ private static void TimeParts(object obj, bool interval, out long sec, out long return; } if (obj == null || obj is bool || obj is MutableString || !RespondTo(obj, "divmod")) { - throw RubyExceptions.CreateTypeError(String.Format("can't convert {0} into time{1}", ClassName(obj), interval ? " interval" : "")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("can't convert {0} into time{1}", ClassName(obj), interval ? " interval" : ""))); } if (interval && Protocols.IsTrue(Call(obj, "<", 0))) { - throw RubyExceptions.CreateArgumentError("time interval must not be negative"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("time interval must not be negative")); } var parts = (RubyArray)Call(obj, "divmod", 1); sec = Convert.ToInt64(parts[0]); @@ -152,7 +152,7 @@ internal static VALUE rb_cvar_defined(VALUE klass, VALUE name) { internal static void rb_define_class_variable(VALUE klass, byte* name, VALUE val) { string n = FromCString(name); if (!n.StartsWith("@@", StringComparison.Ordinal)) { - throw RubyExceptions.CreateNameError(String.Format("wrong class variable name {0}", n)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("wrong class variable name {0}", n))); } Call(FromValue(klass), "class_variable_set", ClassVariableName(n), FromValue(val)); } @@ -198,7 +198,7 @@ public override object GetValue(RubyContext/*!*/ context, RubyScope scope) { public override void SetValue(RubyContext/*!*/ context, RubyScope scope, string/*!*/ name, object value) { if (ReadOnly) { - throw RubyExceptions.CreateNameError(String.Format("${0} is a read-only variable", Name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("${0} is a read-only variable", Name))); } if (Setter == IntPtr.Zero) { if (Var != null) { @@ -273,7 +273,7 @@ internal static VALUE rb_ident_hash_new() { internal static VALUE rb_hash_new_capa(long capa) { if (capa < 0) { - throw RubyExceptions.CreateRuntimeError("st_table too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("st_table too big")); } return rb_hash_new(); } diff --git a/Src/Ruby/CApi/CApi.cs b/Src/Ruby/CApi/CApi.cs index 189a95a59..658d2fe2e 100644 --- a/Src/Ruby/CApi/CApi.cs +++ b/Src/Ruby/CApi/CApi.cs @@ -68,7 +68,7 @@ internal static void LoadExtension(RubyContext/*!*/ context, string/*!*/ path) { string error; IntPtr handle = OpenLibrary(path, true, out error); if (handle == IntPtr.Zero) { - throw RubyExceptions.CreateLoadError(error + " - " + path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(error + " - " + path)); } if (!IsWindows) { @@ -85,7 +85,7 @@ internal static void LoadExtension(RubyContext/*!*/ context, string/*!*/ path) { } IntPtr init = Symbol(handle, "Init_" + name); if (init == IntPtr.Zero) { - throw RubyExceptions.CreateLoadError("Init_" + name + " is not defined - " + path); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError("Init_" + name + " is not defined - " + path)); } CallInit(path, init); @@ -190,21 +190,21 @@ int RvaToOffset(int rva) { private static void Initialize(RubyContext/*!*/ context) { if (_context != null) { if (_context != context) { - throw RubyExceptions.CreateLoadError( - "C extensions can only be loaded by one IronRuby runtime per process, and another one has loaded them"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError( + "C extensions can only be loaded by one IronRuby runtime per process, and another one has loaded them")); } return; } bool supported = RuntimeInformation.ProcessArchitecture == Architecture.X64 && (OperatingSystem.IsLinux() || IsWindows); if (!supported) { - throw RubyExceptions.CreateLoadError("IronRuby's C API is only implemented on Linux and Windows x64 so far"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError("IronRuby's C API is only implemented on Linux and Windows x64 so far")); } if (!IsWindows) { IntPtr libc; if (!NativeLibrary.TryLoad("libc.so.6", out libc) && !NativeLibrary.TryLoad("libdl.so.2", out libc)) { - throw RubyExceptions.CreateLoadError("cannot find the C library's dlopen"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError("cannot find the C library's dlopen")); } _dlopen = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(libc, "dlopen"); _dlsym = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(libc, "dlsym"); @@ -214,14 +214,14 @@ private static void Initialize(RubyContext/*!*/ context) { string dir = Path.GetDirectoryName(typeof(CApi).Assembly.Location); string shimPath = Path.Combine(dir, ShimName); if (!File.Exists(shimPath)) { - throw RubyExceptions.CreateLoadError( - "cannot load a C extension: " + shimPath + " is missing (build it with Util/build-capi.sh)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError( + "cannot load a C extension: " + shimPath + " is missing (build it with Util/build-capi.sh)")); } // global: on Unix the extensions' undefined rb_* symbols resolve against it string error; _shim = OpenLibrary(shimPath, true, out error); if (_shim == IntPtr.Zero) { - throw RubyExceptions.CreateLoadError(error + " - " + shimPath); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(error + " - " + shimPath)); } _callMethod = (delegate* unmanaged[Cdecl])ShimExport("rb_ir_call_method"); @@ -234,9 +234,9 @@ private static void Initialize(RubyContext/*!*/ context) { int count = *(int*)ShimExport("rb_ir_function_count"); if (count != FunctionCount) { - throw RubyExceptions.CreateLoadError(String.Format( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(String.Format( "libironruby-capi does not match this IronRuby: it has {0} functions, IronRuby {1} (rebuild it with Util/build-capi.sh)", - count, FunctionCount)); + count, FunctionCount))); } IntPtr* table = (IntPtr*)NativeMemory.Alloc((nuint)(count * sizeof(IntPtr))); FillFunctionTable(table); @@ -252,7 +252,7 @@ private static void Initialize(RubyContext/*!*/ context) { internal static IntPtr ShimExport(string/*!*/ name) { IntPtr result = Symbol(_shim, name); if (result == IntPtr.Zero) { - throw RubyExceptions.CreateLoadError("libironruby-capi has no " + name + " (rebuild it with Util/build-capi.sh)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError("libironruby-capi has no " + name + " (rebuild it with Util/build-capi.sh)")); } return result; } @@ -416,7 +416,7 @@ internal static int CallForeach(IntPtr fn, VALUE key, VALUE value, VALUE arg) { /// innermost trampoline, which rethrows it in managed code. /// private static void SetPending(Exception/*!*/ e) { - _pending = e; + _pending = RubyExceptionData.MarkKept(e); int* flag = _pendingFlag; if (flag == null) { _pendingFlag = flag = _pendingAddress(); @@ -437,14 +437,14 @@ private static void SetPending(Exception/*!*/ e) { internal static string/*!*/ FromCString(byte* str) { if (str == null) { - throw RubyExceptions.CreateArgumentError("NULL pointer given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("NULL pointer given")); } return Marshal.PtrToStringUTF8((IntPtr)str); } internal static byte[]/*!*/ CBytes(byte* str) { if (str == null) { - throw RubyExceptions.CreateArgumentError("NULL pointer given"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("NULL pointer given")); } int n = 0; while (str[n] != 0) { @@ -455,7 +455,7 @@ private static void SetPending(Exception/*!*/ e) { internal static byte[]/*!*/ Bytes(byte* ptr, long len) { if (len < 0) { - throw RubyExceptions.CreateArgumentError("negative string size (or size too big)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative string size (or size too big)")); } if (ptr == null) { return new byte[len]; diff --git a/Src/Ruby/CApi/NativeDigest.cs b/Src/Ruby/CApi/NativeDigest.cs index 012ba0784..397ccec31 100644 --- a/Src/Ruby/CApi/NativeDigest.cs +++ b/Src/Ruby/CApi/NativeDigest.cs @@ -64,7 +64,7 @@ public static NativeDigest TryCreate(object metadata) { return null; } if (meta->ApiVersion != ApiVersion) { - throw RubyExceptions.CreateRuntimeError("Incompatible digest API version"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("Incompatible digest API version")); } var result = new NativeDigest(meta); result.Reset(); @@ -88,7 +88,7 @@ private int Call(int op, byte* ptr, nuint length) { public void Reset() { if (Call(OpInit, null, 0) != 1) { - throw RubyExceptions.CreateRuntimeError("Digest initialization failed."); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("Digest initialization failed.")); } } @@ -110,7 +110,7 @@ public void Update(byte[]/*!*/ data) { public void CopyFrom(NativeDigest/*!*/ other) { if (other._meta != _meta) { - throw RubyExceptions.CreateTypeError("different algorithms"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("different algorithms")); } Buffer.MemoryCopy(other._context, _context, _meta->ContextSize, _meta->ContextSize); GC.KeepAlive(other); diff --git a/Src/Ruby/Runtime/Conversions/Converter.cs b/Src/Ruby/Runtime/Conversions/Converter.cs index 27614dd24..5c93d31b4 100644 --- a/Src/Ruby/Runtime/Conversions/Converter.cs +++ b/Src/Ruby/Runtime/Conversions/Converter.cs @@ -498,35 +498,35 @@ internal static Byte ToByte(int value) { if (value >= Byte.MinValue && value <= Byte.MaxValue) { return (Byte)value; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::Byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::Byte")); } internal static SByte ToSByte(int value) { if (value >= SByte.MinValue && value <= SByte.MaxValue) { return (SByte)value; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::SByte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::SByte")); } internal static Int16 ToInt16(int value) { if (value >= Int16.MinValue && value <= Int16.MaxValue) { return (Int16)value; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::Int16"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::Int16")); } internal static UInt16 ToUInt16(int value) { if (value >= UInt16.MinValue && value <= UInt16.MaxValue) { return (UInt16)value; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::UInt16"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::UInt16")); } internal static UInt32 ToUInt32(int value) { if (value >= UInt32.MinValue) { return (UInt32)value; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::UInt32"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::UInt32")); } internal static UInt32 ToUInt32(BigInteger value) { @@ -534,7 +534,7 @@ internal static UInt32 ToUInt32(BigInteger value) { if (value.AsUInt32(out result)) { return result; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::UInt32"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::UInt32")); } internal static Int64 ToInt64(BigInteger value) { @@ -542,14 +542,14 @@ internal static Int64 ToInt64(BigInteger value) { if (value.AsInt64(out result)) { return result; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::Int64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::Int64")); } internal static UInt64 ToUInt64(int value) { if (value >= 0) { return (UInt64)value; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::UInt64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::UInt64")); } internal static UInt64 ToUInt64(BigInteger value) { @@ -557,7 +557,7 @@ internal static UInt64 ToUInt64(BigInteger value) { if (value.AsUInt64(out result)) { return result; } - throw RubyExceptions.CreateRangeError("number too big to convert into System::UInt64"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("number too big to convert into System::UInt64")); } #endregion diff --git a/Src/Ruby/Runtime/Globals/GlobalVariable.cs b/Src/Ruby/Runtime/Globals/GlobalVariable.cs index 9375bccf3..1105d7c02 100644 --- a/Src/Ruby/Runtime/Globals/GlobalVariable.cs +++ b/Src/Ruby/Runtime/Globals/GlobalVariable.cs @@ -50,7 +50,7 @@ protected GlobalVariable() { internal T RequireType(object value, string/*!*/ variableName, string/*!*/ typeName) { if (!(value is T)) { - throw RubyExceptions.CreateTypeError(String.Format("value of ${0} must be {1}", variableName, typeName)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("value of ${0} must be {1}", variableName, typeName))); } return (T)value; } diff --git a/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs b/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs index 80976a02c..0b4ffcae1 100644 --- a/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs +++ b/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs @@ -180,8 +180,8 @@ public override void SetValue(RubyContext/*!*/ context, RubyScope scope, string/ } if (value != null && !(value is MatchData)) { - throw RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected MatchData)", - context.GetClassDisplayName(value))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("wrong argument type {0} (expected MatchData)", + context.GetClassDisplayName(value)))); } scope.GetInnerMostClosureScope().CurrentMatch = (MatchData)value; return; @@ -249,7 +249,7 @@ public override void SetValue(RubyContext/*!*/ context, RubyScope scope, string/ case GlobalVariableId.StringSeparator: if (value != null && !(value is MutableString) && !(value is RubyRegex)) { - throw RubyExceptions.CreateTypeError(String.Format("value of ${0} must be String or Regexp", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("value of ${0} must be String or Regexp", name))); } context.StringSeparator = value; ReportNonNilDeprecation(context, name, context.StringSeparator); @@ -341,7 +341,7 @@ internal static void SetProcessTitle(byte[]/*!*/ title) { private object RequireWriteProtocol(RubyContext/*!*/ context, object value, string/*!*/ variableName) { if (!context.RespondTo(value, "write")) { - throw RubyExceptions.CreateTypeError(String.Format("${0} must have write method, {1} given", variableName, context.GetClassDisplayName(value))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("${0} must have write method, {1} given", variableName, context.GetClassDisplayName(value)))); } return value; diff --git a/Src/Ruby/Runtime/IntegerValue.cs b/Src/Ruby/Runtime/IntegerValue.cs index 42dc55929..dbd195497 100644 --- a/Src/Ruby/Runtime/IntegerValue.cs +++ b/Src/Ruby/Runtime/IntegerValue.cs @@ -99,7 +99,7 @@ public int ToInt32() { if (IsFixnum) { result = _fixnum; } else if (!_bignum.Value.AsInt32(out result)) { - throw RubyExceptions.CreateRangeError("Integer too big to convert into 32-bit signed integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("Integer too big to convert into 32-bit signed integer")); } return result; } @@ -109,7 +109,7 @@ public long ToInt64() { if (IsFixnum) { result = _fixnum; } else if (!_bignum.Value.AsInt64(out result)) { - throw RubyExceptions.CreateRangeError("Integer too big to convert into 64-bit signed integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("Integer too big to convert into 64-bit signed integer")); } return result; } @@ -125,7 +125,7 @@ public uint ToUInt32Unchecked() { if (_bignum.Value.AsUInt32(out u)) { return u; } - throw RubyExceptions.CreateRangeError("bignum too big to convert into 32-bit unsigned integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 32-bit unsigned integer")); } public bool Equals(IntegerValue other) { diff --git a/Src/Ruby/Runtime/Loader.cs b/Src/Ruby/Runtime/Loader.cs index 4de7a2dc7..73f848abd 100644 --- a/Src/Ruby/Runtime/Loader.cs +++ b/Src/Ruby/Runtime/Loader.cs @@ -361,7 +361,7 @@ private Assembly GetAssembly(string/*!*/ assemblyName, bool throwOnError) { } catch (Exception) when (!throwOnError) { return null; } catch (Exception e) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } } @@ -385,7 +385,7 @@ private bool LoadAssembly(Assembly/*!*/ assembly, string typeName, bool throwOnE DomainManager.LoadAssembly(assembly); } catch (Exception e) { if (throwOnError) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } return false; } @@ -537,7 +537,7 @@ private Assembly LoadAssemblyFromLoadPath(AssemblyName/*!*/ assemblyName, string DomainManager.LoadAssembly(assembly); return assembly; } catch (Exception e) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } } @@ -570,7 +570,7 @@ private Assembly LoadAssemblyNextTo(Assembly requestingAssembly, AssemblyName/*! try { assembly = LoadAssemblyFromFile(path); } catch (Exception e) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } Utils.Log(String.Format("Assembly '{0}' loaded for '{1}' from '{2}'", assembly.FullName, reference.FullName, path), "RESOLVE_ASSEMBLY"); @@ -796,12 +796,12 @@ private bool LoadFromPath(Scope globalScope, object self, string/*!*/ path, Ruby // A gem's compiled CRuby extension. It is not a CLR assembly and never will // be, so say that rather than report a malformed one: "Bad IL format" sends // people looking for a corrupt file. - throw RubyExceptions.CreateLoadError( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError( "cannot load such file -- " + file.Path + " (a C extension; IronRuby has no C extension host)" - ); + )); } catch (Exception e) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } } @@ -927,7 +927,7 @@ private IList FindFile(string/*!*/ path, bool appendExtensions, st try { isAbsolutePath = Platform.IsAbsolutePath(path); } catch (ArgumentException e) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } } @@ -1065,7 +1065,7 @@ private IList FindFile(string/*!*/ path, bool appendExtensions, st for (int i = 0; i < loadPaths.Length; i++) { if (loadPaths[i] == null) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } result[i] = _context.DecodePath(Protocols.CastToPath(toPath, loadPaths[i])); @@ -1102,7 +1102,7 @@ private ResolvedFile ResolveFile(string/*!*/ path, string/*!*/ extension, bool a return GetSourceUnit(path + matchingExtensions[0], expandedPath + matchingExtensions[0], matchingExtensions[0], true); } else if (matchingExtensions.Count > 1) { Exception e = new AmbiguousFileNameException(expandedPath + matchingExtensions[0], expandedPath + matchingExtensions[1]); - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } foreach (string libExtension in _LibraryExtensions) { @@ -1549,7 +1549,7 @@ private bool AnyFileLoaded(IEnumerable/*!*/ paths) { foreach (object file in GetLoadedFiles()) { if (file == null) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } // use case sensitive comparison @@ -1579,7 +1579,7 @@ internal void LoadBuiltins() { Assembly assembly = _context.DomainManager.Platform.LoadAssembly(GetIronRubyAssemblyLongName("IronRuby.Libraries")); initializerType = assembly.GetType(LibraryInitializer.GetBuiltinsFullTypeName()); } catch (Exception e) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } LoadLibrary(initializerType, true); @@ -1606,16 +1606,16 @@ private void LoadLibrary(Type/*!*/ initializerType, bool builtin) { try { initializer = Activator.CreateInstance(initializerType) as LibraryInitializer; } catch (TargetInvocationException e) { - throw RubyExceptions.CreateLoadError(e.InnerException); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e.InnerException)); } catch (Exception e) { - throw RubyExceptions.CreateLoadError(e); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(e)); } if (initializer == null) { - throw RubyExceptions.CreateLoadError(String.Format("Specified type {0} is not a subclass of {1}", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateLoadError(String.Format("Specified type {0} is not a subclass of {1}", initializerType.FullName, typeof(LibraryInitializer).FullName) - ); + )); } // Propagate exceptions from initializers (do not wrap them to LoadError). diff --git a/Src/Ruby/Runtime/Protocols.cs b/Src/Ruby/Runtime/Protocols.cs index 58fe6d3b7..107715ed9 100644 --- a/Src/Ruby/Runtime/Protocols.cs +++ b/Src/Ruby/Runtime/Protocols.cs @@ -197,7 +197,7 @@ public static double ScaleToDouble(BigInteger magnitude, int exponent) { public static MutableString/*!*/ CastToString(CallSite>/*!*/ toStrSite, object obj) { var result = toStrSite.Target(toStrSite, obj); if (result == null) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } return result; } @@ -221,7 +221,7 @@ public static double ScaleToDouble(BigInteger magnitude, int exponent) { public static MutableString/*!*/ CastToPath(CallSite>/*!*/ toPath, object obj) { MutableString result = toPath.Target(toPath, obj); if (result == null) { - throw RubyExceptions.CreateImplicitConversionError("nil", "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError("nil", "String")); } return CheckPath(result); } @@ -240,7 +240,7 @@ public static double ScaleToDouble(BigInteger magnitude, int exponent) { } if (path.IndexOf('\0') >= 0) { - throw RubyExceptions.CreateArgumentError("path name contains null byte"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("path name contains null byte")); } return path; @@ -377,7 +377,7 @@ public static int CastToFixnum(ConversionStorage/*!*/ conversionStorage, ob [CLSCompliant(false)] public static uint CastToUInt32Unchecked(ConversionStorage/*!*/ integerConversion, object obj) { if (obj == null) { - throw RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("no implicit conversion of nil into Integer")); } return CastToInteger(integerConversion, obj).ToUInt32Unchecked(); @@ -397,7 +397,7 @@ public static int Compare(ComparisonStorage/*!*/ comparisonStorage, object lhs, if (result != null) { return Protocols.ConvertCompareResult(comparisonStorage, result); } else { - throw RubyExceptions.MakeComparisonError(comparisonStorage.Context, lhs, rhs); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(comparisonStorage.Context, lhs, rhs)); } } @@ -524,7 +524,7 @@ public static bool CoerceAndRelate(BinaryOpStorage/*!*/ coercionStorage, BinaryO return RubyOps.IsTrue(result); } - throw RubyExceptions.MakeComparisonError(coercionStorage.Context, self, other); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.MakeComparisonError(coercionStorage.Context, self, other)); } /// @@ -713,7 +713,7 @@ private static bool TryCoerce(BinaryOpStorage/*!*/ coercionStorage, object self, if (coercedValues == null || coercedValues.Count != 2) { // #coerce exists but answered something that is not a pair. MRI reports that // as its own error rather than pretending the operand was not coercible. - throw RubyExceptions.CreateTypeError("coerce must return [x, y]"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("coerce must return [x, y]")); } pair = coercedValues; diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index cd1f9427e..697f8e7bc 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -1999,10 +1999,10 @@ private void AddScopedExtensions(List/*!*/ extensions) { Assert.NotNull(owner, superClass); if (superClass.TypeTracker != null && superClass.TypeTracker.Type.ContainsGenericParameters) { - throw RubyExceptions.CreateTypeError(String.Format( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format( "{0}: cannot inherit from open generic instantiation {1}. Only closed instantiations are supported.", name, superClass.Name - )); + ))); } string qualifiedName = owner.MakeNestedModuleName(name); @@ -2077,11 +2077,11 @@ private T PrepareLibraryModuleDefinition(string name, RubyClass super, RubyMo bool isClass = typeof(T) == typeof(RubyClass); if (result == null || result.IsClass != isClass) { // MRI's rb_define_class/rb_define_module: "Zlib is not a module (Class)" - throw RubyExceptions.CreateTypeError("{0} is not a {1} ({2})", name, isClass ? "class" : "module", - GetClassName(c.Value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("{0} is not a {1} ({2})", name, isClass ? "class" : "module", + GetClassName(c.Value))); } if (isClass && (restrictions & ModuleRestrictions.AllowReopening) == 0) { - throw RubyExceptions.CreateTypeError("cannot redefine {1} '{0}'", name, isClass ? "class" : "module"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("cannot redefine {1} '{0}'", name, isClass ? "class" : "module")); } return result; } @@ -2167,11 +2167,11 @@ private T PrepareLibraryModuleDefinition(string name, RubyClass super, RubyMo if (exists) { if (super != null && super != result.SuperClass) { - throw RubyExceptions.CreateTypeError("superclass mismatch for class {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("superclass mismatch for class {0}", name)); } if (factories != null && factories.Length != 0) { - throw RubyExceptions.CreateTypeError("Cannot add factories to an existing class"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot add factories to an existing class")); } result.IncludeLibraryModule(instanceTrait, classTrait, constantsInitializer, mixins, builtin); @@ -3700,7 +3700,7 @@ internal Exception SetCurrentException(object value) { // "$! = nil" is allowed if (value != null && e == null) { - throw RubyExceptions.CreateTypeError("assigning non-exception to $!"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("assigning non-exception to $!")); } Debug.Assert(RubyUtils.GetVisibleException(e) == e); @@ -3737,7 +3737,7 @@ internal object GetCurrentExceptionBacktrace() { } var array = backtrace as RubyArray; if (array == null || !CollectionUtils.TrueForAll(array, (item) => item is MutableString)) { - throw RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location")); } return array; } @@ -3748,7 +3748,7 @@ internal RubyArray SetCurrentExceptionBacktrace(object value) { // first check availability of the current exception: Exception e = _currentException; if (e == null) { - throw RubyExceptions.CreateArgumentError("$! not set"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("$! not set")); } // MRI's errat_setter goes through #set_backtrace, which also takes an Array of @@ -4014,7 +4014,7 @@ public void SetStream(int descriptor, Stream/*!*/ stream) { lock (_fileDescriptors) { var fd = TryGetFileDescriptorNoLock(descriptor); if (fd == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } if (fd.Stream != stream) { fd.Close(); @@ -4027,12 +4027,12 @@ public void RedirectFileDescriptor(int descriptor, int toDescriptor) { lock (_fileDescriptors) { var fd = TryGetFileDescriptorNoLock(descriptor); if (fd == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } var toFd = TryGetFileDescriptorNoLock(toDescriptor); if (toFd == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } if (fd == toFd) { @@ -4071,7 +4071,7 @@ public int DuplicateFileDescriptor(int descriptor) { lock (_fileDescriptors) { var fd = TryGetFileDescriptorNoLock(descriptor); if (fd == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } fd.DuplicateCount++; return AddFileDescriptorNoLock(fd); @@ -4082,7 +4082,7 @@ public void CloseStream(int descriptor) { lock (_fileDescriptors) { var fd = TryGetFileDescriptorNoLock(descriptor); if (fd == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } fd.Close(); _fileDescriptors[descriptor] = null; @@ -4092,7 +4092,7 @@ public void CloseStream(int descriptor) { public void RemoveFileDescriptor(int descriptor) { lock (_fileDescriptors) { if (TryGetFileDescriptorNoLock(descriptor) == null) { - throw RubyExceptions.CreateEBADF(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEBADF()); } _fileDescriptors[descriptor] = null; @@ -4523,13 +4523,13 @@ internal static MutableString TryEncodeRawAsciiPath(string/*!*/ path, RubyEncodi try { return MutableString.Create(path, encoding).CheckEncoding(); } catch (EncoderFallbackException e) { - throw RubyExceptions.CreateEINVAL( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL( e, "Path \"{0}\" contains characters that cannot be represented in encoding {1}: {2}", path.ToAsciiString(), encoding.Name, e.Message - ); + )); } } @@ -4546,7 +4546,7 @@ internal static MutableString TryEncodeRawAsciiPath(string/*!*/ path, RubyEncodi return path.ConvertToString(); } } catch (DecoderFallbackException) { - throw RubyExceptions.CreateEINVAL("Invalid multi-byte sequence in path '{0}'", path.ToAsciiString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateEINVAL("Invalid multi-byte sequence in path '{0}'", path.ToAsciiString())); } } @@ -5593,12 +5593,12 @@ public override Encoding/*!*/ DefaultEncoding { // #encode, Integer#chr and IO as well as from Encoding.find. .NET's own message for an // unknown name talks about Encoding.RegisterProvider, which means nothing in Ruby. if (!name.IsAscii()) { - throw RubyExceptions.CreateArgumentError("invalid encoding name (non ASCII)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid encoding name (non ASCII)")); } try { return GetRubyEncoding(name.ToString()); } catch (ArgumentException) { - throw RubyExceptions.CreateArgumentError("unknown encoding name - {0}", name.ToAsciiString()); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("unknown encoding name - {0}", name.ToAsciiString())); } } @@ -5831,7 +5831,7 @@ internal int CastToFixnum(object value) { } } - throw RubyExceptions.CreateImplicitConversionError(GetClassDisplayName(value), "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(GetClassDisplayName(value), "Integer")); } /// The to_str protocol, for assignment to $0. @@ -5853,7 +5853,7 @@ internal int CastToFixnum(object value) { } } - throw RubyExceptions.CreateImplicitConversionError(GetClassDisplayName(value), "String"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(GetClassDisplayName(value), "String")); } public bool RespondTo(object target, string/*!*/ methodName) { diff --git a/Src/Ruby/Runtime/RubyExceptionData.cs b/Src/Ruby/Runtime/RubyExceptionData.cs index ec831e863..65062d609 100644 --- a/Src/Ruby/Runtime/RubyExceptionData.cs +++ b/Src/Ruby/Runtime/RubyExceptionData.cs @@ -88,6 +88,22 @@ private static bool IsBuiltinConstruction(RubyContext/*!*/ context, RubyClass/*! return UnkeptLibraryErrors ? MarkUnkept(exception) : exception; } + /// + /// Code that keeps an exception to hand it to Ruby again later - a thread's, re-raised by every Thread#join and #value, one a + /// callback threw for a library to throw after, one the C API holds - calls this as it keeps it: whatever made it, it is no + /// longer one nothing can have kept (), so a rescue of it later takes its catch-site walk at once. + /// + public static Exception MarkKept(Exception exception) { + var data = (exception != null) ? TryGetInstance(exception) : null; + if (data != null) { + if (data._pendingCatchSite != null) { + data.ResolveCatchSite(); + } + data.RaisedUnkept = false; + } + return exception; + } + public static Exception/*!*/ MarkUnkept(Exception/*!*/ exception) { GetInstance(exception).RaisedUnkept = true; return exception; diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index fde736fa7..7a6387753 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -174,7 +174,7 @@ public static void SetDataConstant(RubyScope/*!*/ scope, string/*!*/ dataPath, i RubyScope/*!*/ parent, RubyModule/*!*/ module) { if (parent.RubyContext != module.Context) { - throw RubyExceptions.CreateTypeError("Cannot open a module '{0}' defined in a foreign runtime #{1}", module.Name, module.Context.RuntimeId); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("Cannot open a module '{0}' defined in a foreign runtime #{1}", module.Name, module.Context.RuntimeId)); } RubyModuleScope scope = new RubyModuleScope(parent, module); @@ -1331,7 +1331,7 @@ private static void CheckLambdaArity(Proc/*!*/ proc, int argCount, object lastAr keywords = null; } if (keywords != null && keywords.Count > 0 && signature.RefusesKeywords) { - throw RubyExceptions.CreateArgumentError("no keywords accepted"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("no keywords accepted")); } } if (proc.Kind != ProcKind.Lambda) { @@ -1608,7 +1608,7 @@ public static object DefineMethod(object target, RubyScope/*!*/ scope, RubyMetho if (body.HasTarget) { if (!RubyUtils.CanDefineSingletonMethod(target)) { - throw RubyExceptions.CreateTypeError("can't define singleton"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't define singleton")); } instanceOwner = null; @@ -1637,7 +1637,7 @@ public static object DefineMethod(object target, RubyScope/*!*/ scope, RubyMetho // Integer takes no methods, module function or not var dummy = instanceOwner as RubyClass; if (dummy != null && dummy.IsDummySingletonClass) { - throw RubyExceptions.CreateTypeError("can't define singleton"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't define singleton")); } instanceFlags = RubyMemberFlags.Private; @@ -1657,7 +1657,7 @@ public static object DefineMethod(object target, RubyScope/*!*/ scope, RubyMetho if (singleton.IsDummySingletonClass) { // `1.instance_eval { def f; end }' - the dummy stands in for a // singleton class the receiver can never have - throw RubyExceptions.CreateTypeError("can't define singleton"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't define singleton")); } RubyUtils.RequireDefinableSingleton(singleton.SingletonClassOf); } @@ -1864,7 +1864,7 @@ public static void UndefineMethod(RubyScope/*!*/ scope, string/*!*/ name) { owner.WarnIfUndefiningCoreMethod(name); bool inMirror = mirror != null && mirror.ResolveMethod(name, VisibilityContext.AllVisible).Found; if (!inMirror && !owner.ResolveMethod(name, VisibilityContext.AllVisible).Found) { - throw RubyExceptions.CreateUndefinedMethodError(mirror ?? owner, name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUndefinedMethodError(mirror ?? owner, name)); } if (inMirror) { mirror.UndefineMethod(name); @@ -1932,7 +1932,7 @@ private static void CheckConstantVisibility(RubyModule/*!*/ owner, string/*!*/ n if (owner.TryGetConstant(scope.GlobalScope, name, out existing)) { RubyModule module = existing.Value as RubyModule; if (module == null || module.IsClass) { - throw RubyExceptions.CreateTypeError(DescribePreviousDefinition(owner, name, "{0} is not a module")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(DescribePreviousDefinition(owner, name, "{0} is not a module"))); } return module; } else { @@ -1994,11 +1994,11 @@ private static void CheckConstantVisibility(RubyModule/*!*/ owner, string/*!*/ n RubyClass cls = existing.Value as RubyClass; if (cls == null || !cls.IsClass) { - throw RubyExceptions.CreateTypeError(DescribePreviousDefinition(owner, name, "{0} is not a class")); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(DescribePreviousDefinition(owner, name, "{0} is not a class"))); } if (superClassObject != null && !ReferenceEquals(cls.SuperClass, superClass)) { - throw RubyExceptions.CreateTypeError("superclass mismatch for class {0}", name); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("superclass mismatch for class {0}", name)); } return cls; } else { @@ -2586,7 +2586,7 @@ public static object MergeKeywordSplat(RubyScope/*!*/ scope, object keywords, ob [Emitted] public static object/*!*/ MergeKeywordHash(RubyScope/*!*/ scope, object keywords, object splatted) { if (!(splatted is Hash)) { - throw RubyExceptions.CreateUnexpectedTypeError(scope.RubyContext, splatted, "Hash"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateUnexpectedTypeError(scope.RubyContext, splatted, "Hash")); } return MergeKeywordSplat(scope, keywords, splatted); } @@ -2627,7 +2627,7 @@ public static Hash KeywordSplatArgument(RubyScope/*!*/ scope, object hash) { var dict = hash as IDictionary; if (dict == null) { - throw RubyExceptions.CreateImplicitConversionError(scope.RubyContext.GetClassDisplayName(hash), "Hash"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateImplicitConversionError(scope.RubyContext.GetClassDisplayName(hash), "Hash")); } if (dict.Count == 0) { @@ -3309,7 +3309,7 @@ public static object GetTrailingArrayItem(IList/*!*/ array, int index, int expli private static TElement[]/*!*/ CreateVectorInternal(int size) { if (size < 0) { - throw RubyExceptions.CreateArgumentError("negative array size"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("negative array size")); } return new TElement[size]; @@ -3826,12 +3826,12 @@ private static RubyEncoding DynamicRegexEncoding(RubyRegexOptions options, param string error = RubyRegex.Preprocess(fragment.ToByteArray(), sourceEncoding, extended, out pinned, out nonAsciiEscape, out encoding); if (error != null) { - throw RubyExceptions.CreateArgumentError(error); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError(error)); } } else { // rb_reg_preprocess: an ASCII incompatible fragment fixes its encoding if (fragment.ContainsInvalidCharacters()) { - throw RubyExceptions.CreateArgumentError("invalid multibyte character"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid multibyte character")); } encoding = sourceEncoding; } @@ -4597,7 +4597,7 @@ public static void SetCurrentException(RubyScope/*!*/ scope, Exception exception public static bool CompareException(BinaryOpStorage/*!*/ comparisonStorage, RubyScope/*!*/ scope, object classObject) { var context = scope.RubyContext; if (!(classObject is RubyModule)) { - throw RubyExceptions.CreateTypeError("class or module required for rescue clause"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("class or module required for rescue clause")); } // A refinement of `===' active where the rescue clause is written is what MRI's rescue calls (check_match calls @@ -5007,8 +5007,8 @@ private static void RequireSuperSelf(RubyScope/*!*/ methodScope, object currentS } var context = methodScope.RubyContext; if (!context.IsKindOf(currentSelf, declaringModule)) { - throw RubyExceptions.CreateTypeError(String.Format("self has wrong type to call super in this context: {0} (expected {1})", - context.GetClassDisplayName(currentSelf), context.GetModuleMessageName(declaringModule))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("self has wrong type to call super in this context: {0} (expected {1})", + context.GetClassDisplayName(currentSelf), context.GetModuleMessageName(declaringModule)))); } } @@ -5039,7 +5039,7 @@ public static bool IsSuperOutOfMethodScope(RubyScope/*!*/ scope) { public static Proc/*!*/ ToProcValidator(string/*!*/ className, object obj) { Proc result = obj as Proc; if (result == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_proc", "Proc", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_proc", "Proc", obj)); } return result; } @@ -5066,7 +5066,7 @@ public static MutableString TryToStringValidator(string/*!*/ className, object o public static MutableString/*!*/ ToStringValidator(string/*!*/ className, object obj) { MutableString result = obj as MutableString; if (result == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_str", "String", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_str", "String", obj)); } return result; } @@ -5075,7 +5075,7 @@ public static MutableString TryToStringValidator(string/*!*/ className, object o public static string/*!*/ ToSymbolValidator(string/*!*/ className, object obj) { var str = obj as MutableString; if (str == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_str", "String", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_str", "String", obj)); } return str.ConvertToString(); } @@ -5124,7 +5124,7 @@ public static object TrySplatToAryValidator(string/*!*/ className, object splatt public static IList/*!*/ ToArrayValidator(string/*!*/ className, object obj) { var result = obj as IList; if (result == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_ary", "Array", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_ary", "Array", obj)); } return result; } @@ -5133,7 +5133,7 @@ public static object TrySplatToAryValidator(string/*!*/ className, object splatt public static IList/*!*/ ToAValidator(string/*!*/ className, object obj) { var result = obj as IList; if (result == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_a", "Array", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_a", "Array", obj)); } return result; } @@ -5152,7 +5152,7 @@ public static object TrySplatToAryValidator(string/*!*/ className, object splatt } var result = obj as IList; if (result == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_a", "Array", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_a", "Array", obj)); } return result; } @@ -5167,7 +5167,7 @@ public static object TrySplatToAryValidator(string/*!*/ className, object splatt } var result = obj as IList; if (result == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_ary", "Array", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_ary", "Array", obj)); } return result; } @@ -5176,7 +5176,7 @@ public static object TrySplatToAryValidator(string/*!*/ className, object splatt public static IDictionary/*!*/ ToHashValidator(string/*!*/ className, object obj) { var result = obj as IDictionary; if (result == null) { - throw RubyExceptions.CreateReturnTypeError(className, "to_hash", "Hash", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_hash", "Hash", obj)); } return result; } @@ -5190,7 +5190,7 @@ private static int ToIntValidator(string/*!*/ className, string/*!*/ targetType, if (wide >= Int32.MinValue && wide <= Int32.MaxValue) { return (int)wide; } - throw RubyExceptions.CreateRangeError("bignum too big to convert into {0}", targetType); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into {0}", targetType)); } if (obj is BigInteger bignum) { @@ -5198,10 +5198,10 @@ private static int ToIntValidator(string/*!*/ className, string/*!*/ targetType, if (bignum.AsInt32(out fixnum)) { return fixnum; } - throw RubyExceptions.CreateRangeError("bignum too big to convert into {0}", targetType); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into {0}", targetType)); } - throw RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj)); } [Emitted] // ProtocolConversionAction @@ -5243,7 +5243,7 @@ public static UInt32 ToUInt32Validator(string/*!*/ className, object obj) { return Converter.ToUInt32(bignum); } - throw RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj)); } [Emitted] // ProtocolConversionAction @@ -5260,7 +5260,7 @@ public static Int64 ToInt64Validator(string/*!*/ className, object obj) { return Converter.ToInt64(bignum); } - throw RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj)); } [Emitted] // ProtocolConversionAction @@ -5277,7 +5277,7 @@ public static UInt64 ToUInt64Validator(string/*!*/ className, object obj) { return Converter.ToUInt64(bignum); } - throw RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj)); } [Emitted] // ProtocolConversionAction @@ -5294,7 +5294,7 @@ public static BigInteger ToBignumValidator(string/*!*/ className, object obj) { return bignum; } - throw RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_int", "Integer", obj)); } [Emitted] // ProtocolConversionAction @@ -5312,7 +5312,7 @@ private static IntegerValue ToIntegerValue(string/*!*/ className, string/*!*/ me int fixnum => new IntegerValue(fixnum), long wide => new IntegerValue((BigInteger)wide), BigInteger bignum => new IntegerValue(bignum), - _ => throw RubyExceptions.CreateReturnTypeError(className, methodName, "Integer", obj) + _ => throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, methodName, "Integer", obj)) }; } @@ -5326,7 +5326,7 @@ public static double ToDoubleValidator(string/*!*/ className, object obj) { return (double)(float)obj; } - throw RubyExceptions.CreateReturnTypeError(className, "to_f", "Float", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_f", "Float", obj)); } [Emitted] // ProtocolConversionAction @@ -5339,7 +5339,7 @@ public static float ToSingleValidator(string/*!*/ className, object obj) { return (float)obj; } - throw RubyExceptions.CreateReturnTypeError(className, "to_f", "System::Single", obj); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateReturnTypeError(className, "to_f", "System::Single", obj)); } [Emitted] @@ -5874,7 +5874,7 @@ public static int ConvertBignumToFixnum(BigInteger/*!*/ bignum) { if (bignum.AsInt32(out fixnum)) { return fixnum; } - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } [Emitted] // Converter.ExplicitConvert @@ -5884,7 +5884,7 @@ public static int ConvertInt64ToFixnum(long value) { } // Same wording as the BigInteger case: which of the two CLR types happens to carry // the value is an implementation detail Ruby code must not be able to see. - throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); } [Emitted] // ConvertDoubleToFixnum @@ -5892,7 +5892,7 @@ public static int ConvertDoubleToFixnum(double value) { try { return checked((int)value); } catch (OverflowException) { - throw RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(value))); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(value)))); } } @@ -6531,8 +6531,8 @@ public static T CreateDefaultValue() { public static RubyModule/*!*/ ConvertTypeGroupToModule(RubyContext/*!*/ context, Microsoft.Scripting.Actions.TypeGroup/*!*/ typeGroup) { Type type; if (!typeGroup.TryGetNonGenericType(out type)) { - throw RubyExceptions.CreateTypeError(String.Format("{0} has no non-generic type to stand for a module; use {0}[...] or {0}.of(...)", - typeGroup.Name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("{0} has no non-generic type to stand for a module; use {0}[...] or {0}.of(...)", + typeGroup.Name))); } return context.GetModule(type); } @@ -6568,8 +6568,8 @@ private static int GetRangeEndpoint(object value) { if (value is int) { return (int)value; } - throw RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into System::Range (Integer endpoints expected)", - value == null ? "nil" : value.GetType().Name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("no implicit conversion of {0} into System::Range (Integer endpoints expected)", + value == null ? "nil" : value.GetType().Name))); } #region Constructing instances of Ruby classes derived from CLR classes @@ -6598,9 +6598,9 @@ public static object EnsureConstructed(object result, Type/*!*/ baseType) { object unused; if (result != null && _unconstructedInstances.TryGetValue(result, out unused)) { _unconstructedInstances.Remove(result); - throw RubyExceptions.CreateTypeError(String.Format( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format( "{0}.new: initialize did not call super, and {1} has no parameterless constructor to construct the instance with", - ((IRubyObject)result).ImmediateClass.NominalClass.Name, baseType.Name)); + ((IRubyObject)result).ImmediateClass.NominalClass.Name, baseType.Name))); } return result; } diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index a19672e07..b33dcf74c 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -209,7 +209,7 @@ public static bool CanDefineSingletonMethod(object obj) { public static void RequireDefinableSingleton(object obj) { if (!CanDefineSingletonMethod(obj)) { - throw RubyExceptions.CreateTypeError("can't define singleton"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("can't define singleton")); } } @@ -259,10 +259,10 @@ public static bool HasSingletonClass(object obj) { var list = names as IList; if (list == null) { - throw RubyExceptions.CreateTypeError(String.Format( + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format( "Expected #instance_variables_to_inspect to return an Array or nil, but it returned {0}", context.GetClassDisplayName(names) - )); + ))); } var wanted = new List(list.Count); @@ -796,13 +796,13 @@ private static int LetterPair(string/*!*/ str, int index) { public static void CheckConstantName(string name) { if (!Tokenizer.IsConstantName(name)) { - throw RubyExceptions.CreateNameError(String.Format("wrong constant name {0}", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("wrong constant name {0}", name))); } } public static void CheckClassVariableName(string name) { if (!Tokenizer.IsClassVariableName(name)) { - throw RubyExceptions.CreateNameError(String.Format("'{0}' is not allowed as a class variable name", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("'{0}' is not allowed as a class variable name", name))); } } @@ -859,7 +859,7 @@ public static bool IsCoreStateInstanceVariableName(string/*!*/ name) { public static void CheckInstanceVariableName(string name) { if (!Tokenizer.IsInstanceVariableName(name)) { - throw RubyExceptions.CreateNameError(String.Format("'{0}' is not allowed as an instance variable name", name)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateNameError(String.Format("'{0}' is not allowed as an instance variable name", name))); } } @@ -1278,11 +1278,11 @@ internal static int TryMapOperator(string/*!*/ methodName, out ExpressionType op public static void RequireMixins(RubyModule/*!*/ target, params RubyModule[]/*!*/ modules) { foreach (RubyModule module in modules) { if (module == null) { - throw RubyExceptions.CreateTypeError("wrong argument type nil (expected Module)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type nil (expected Module)")); } if (module.IsClass) { - throw RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)")); } // including a module that already has the target among its ancestors would make a cycle @@ -1292,13 +1292,13 @@ public static void RequireMixins(RubyModule/*!*/ target, params RubyModule[]/*!* cyclic = module == target || module.HasAncestorNoLock(target); } if (cyclic) { - throw RubyExceptions.CreateArgumentError("cyclic include detected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cyclic include detected")); } if (module.Context != target.Context) { - throw RubyExceptions.CreateTypeError(String.Format("cannot mix a foreign module '{0}' into '{1}' (runtime mismatch)", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("cannot mix a foreign module '{0}' into '{1}' (runtime mismatch)", module.GetName(target.Context), target.GetName(module.Context) - )); + ))); } } } @@ -1306,11 +1306,11 @@ public static void RequireMixins(RubyModule/*!*/ target, params RubyModule[]/*!* public static void RequirePrepends(RubyModule/*!*/ target, params RubyModule[]/*!*/ modules) { foreach (RubyModule module in modules) { if (module == null) { - throw RubyExceptions.CreateTypeError("wrong argument type nil (expected Module)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type nil (expected Module)")); } if (module.IsClass) { - throw RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("wrong argument type Class (expected Module)")); } // the monitor is reentrant, so this is safe whether or not the caller already holds the lock: @@ -1319,13 +1319,13 @@ public static void RequirePrepends(RubyModule/*!*/ target, params RubyModule[]/* cyclic = module == target || module.HasAncestorNoLock(target); } if (cyclic) { - throw RubyExceptions.CreateArgumentError("cyclic prepend detected"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("cyclic prepend detected")); } if (module.Context != target.Context) { - throw RubyExceptions.CreateTypeError(String.Format("cannot mix a foreign module '{0}' into '{1}' (runtime mismatch)", + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError(String.Format("cannot mix a foreign module '{0}' into '{1}' (runtime mismatch)", module.GetName(target.Context), target.GetName(module.Context) - )); + ))); } } } @@ -3237,7 +3237,7 @@ internal void AddRelativePath(string relPath) { if (length == 1 || path[1] == '/' || (FileSystemUsesDriveLetters && path[1] == '\\')) { string homeDirectory = RubyEnvironment.GetVariable(platform, "HOME"); if (homeDirectory == null) { - throw RubyExceptions.CreateArgumentError("couldn't find HOME environment -- expanding '~'"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("couldn't find HOME environment -- expanding '~'")); } if (length <= 2) { diff --git a/Src/Ruby/Runtime/StackGuard.cs b/Src/Ruby/Runtime/StackGuard.cs index 46273c0b1..215f96bdd 100644 --- a/Src/Ruby/Runtime/StackGuard.cs +++ b/Src/Ruby/Runtime/StackGuard.cs @@ -51,7 +51,7 @@ public static T RunOnFreshStack(Func/*!*/ action) { try { result = action(); } catch (Exception e) { - error = ExceptionDispatchInfo.Capture(e); + error = ExceptionDispatchInfo.Capture(RubyExceptionData.MarkKept(e)); } }, FreshStackSize); thread.Name = "IronRuby deep tree walk"; @@ -135,7 +135,7 @@ private static void RunLargeStackWork() { try { work.Result = work.Action(); } catch (Exception e) { - work.Error = ExceptionDispatchInfo.Capture(e); + work.Error = ExceptionDispatchInfo.Capture(RubyExceptionData.MarkKept(e)); } finally { work.Done.Set(); } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index dfdbd7ed7..415e6c320 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -2405,6 +2405,11 @@ def read_nonblock(len, buf = nil, exception: true) if !exception && len.to_int > 0 && respond_to?(:__ir_readable_now?, true) && !__ir_readable_now? return :wait_readable end + # Raising: what the primitive raises is already an IO::EAGAINWaitReadable (IO.NonBlockingError) or an EOFError, so it + # goes on as it is - rescued here and raised again it was thrown twice and walked for once (perf/unkept3). + if exception + return buf.nil? ? __read_nonblock_raising__(len) : __read_nonblock_raising__(len, buf) + end begin result = buf.nil? ? __read_nonblock_raising__(len) : __read_nonblock_raising__(len, buf) rescue IO::WaitReadable, Errno::EAGAIN => e diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 18f9c124e..cad039235 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1368,10 +1368,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has raise in Ruby's 5-6 (CRuby 0.9-1.8): only an exception Kernel#raise made could defer its catch-site walk. Rule errors (arity, method missing...) and the throw sites of `Array#fetch`, `String#[]=`, a frozen String and a failed numeric coercion are now 4.7-5.5 us. perf/unkept2 (2026-11-29, see Landed) did `1 / 0` and `1 % 0`, `EOFError`, a frozen - Array or Hash and `Integer#chr`'s RangeError (5.0-7.0 us). Left: `read_nonblock` with nothing to read (45.6 us, CRuby 2.3), - `File.open` of a missing file (58.8, 3.4), both errno errors made by helpers, and the other library throw sites; marking - every `throw new`/`throw RubyExceptions.Create...` at once would need the places that keep an exception and hand it on - (a thread's, `Thread#join`/`value`, Ractor, Fiddle, MessagePack...) to clear the mark first. + Array or Hash and `Integer#chr`'s RangeError (5.0-7.0 us). perf/unkept3 (see Landed) made the keepers clear the mark and + marked every other `throw RubyExceptions.Create...`/`Make...` (1,367 sites), and `read_nonblock` with nothing to read 43.6 -> + 10.1 us (CRuby 2.3). Left: `File.open` of a missing file (56 us, CRuby 3.4): the CLR throws DirectoryNotFoundException twice + before the ENOENT; skipping that needs a native stat to tell a missing file from an unsearchable directory (EACCES). 23. **A method made by `define_method` is called at 2.3 times CRuby's time** (64 against 28 ns; a `def` of the same body 31; YJIT 2-5 ns): the method JIT takes no block as a method body. Rails-style code defines most of its small methods this way. @@ -2051,6 +2051,31 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/unkept3 (round thirty-seven, 2026-11-29) - every library error made and thrown at once defers its catch-site walk; + the places that keep an exception clear the mark; `read_nonblock` raises once (gap 22)** - time, not gated. The third round of + perf/unkept. (1) `RubyExceptionData.MarkKept`, called where an exception is kept to be handed to Ruby again: a thread's at its + exit (re-raised by every `Thread#join` and `#value`), Ractor's, Fiddle's callback error, MessagePack's, MiniSsl's, OpenSSL's + verify callback's, the C API's pending one, and StackGuard's two captures. It resolves a pending catch site and clears + `RaisedUnkept`, so a later rescue of the same object walks at once. Most of these already took the backtrace as they kept it; + now nothing depends on that. Fibers hand exceptions over in Ruby (`raise e`, which clears the mark), Enumerator exposes its kept + StopIteration (ExposeCatchSite), and Converter's `last_error` is made with `new` and never marked. (2) Every + `throw RubyExceptions.Create...(...)`/`Make...(...)` statement or throw expression in Src/Ruby (but the compiler) and + Src/Libraries - 1,367 of them in 149 files, a script's rewrite, one line each - throws `RubyExceptionData.Unkept(...)` of it. + (3) IO's `read_nonblock` in the prelude rescued what the primitive raised and raised it again even with `exception: true`: three + .NET exceptions and an exposure per call; it now calls the primitive directly then, which raises an IO::EAGAINWaitReadable + (`IO.NonBlockingError`, now marked) or an EOFError already. Per rescued raise (us, off/on; CRuby): `read_nonblock` with nothing + to read 43.6 / 10.1 (2.3); unchanged by this round, as expected: the earlier rounds' kinds 4.4-6.7, `File.open` of a missing + file 56 (3.4, see gap 22). `IR_UNKEPT_LIB=0` restores the old marks (not the prelude's `read_nonblock`). Census: no method + changed. Checked: `Util/unkept-matrix.rb` with `read_nonblock`, a thread's error joined twice and read through `value`, and an + error raised again with `raise e`, CRuby's output with the switch on and off and the JIT on and off; caller, errinfo, jit-raise, + jit-rescue, raise, rescue-light, set-backtrace, thread-backtrace and unkept in the six modes and with the switch off: PASS, 55 + same; `read_nonblock` against CRuby (the error's class, ancestors, message and backtrace, `exception: false`, a buffer, data, + EOF both ways, a bad `exception:`): the same but for one difference older than this round - with a buffer and nothing to + read, `exception: false` leaves CRuby's buffer as it was and empties IronRuby's. + ruby/spec core/exception, io, kernel, array, hash, string, integer, file, struct and thread on both builds: 13,650 examples, the + same 11 errors and the same failing examples; language in full: 2935 examples, the one known error. IronRuby.Tests in full on + Debug: PASSED. + - **perf/unkept2 (round thirty-seven, 2026-11-29) - more library errors defer their catch-site walk: division by zero, EOFError, frozen objects, `chr`'s RangeError (gap 22)** - time, not gated. perf/unkept's second round. `1 / 0` and `1 % 0` were not thrown by a site at all: `Integer#/` and `#%` on two Fixnums divided and let the CLR raise its DivideByZeroException. They diff --git a/Util/unkept-matrix.rb b/Util/unkept-matrix.rb index 960c94499..66588fb65 100644 --- a/Util/unkept-matrix.rb +++ b/Util/unkept-matrix.rb @@ -8,6 +8,7 @@ # 'IO::generic_readable#readline' and IronRuby 'StringIO#readline'. Both differences are older than perf/unkept. require "stringio" A = []; S = "abc"; SIO = StringIO.new(""); FA = [].freeze; FH = {}.freeze +RP, WP = IO.pipe def bt(e) lines = e.backtrace.reject { |l| l.include?("#readline'") } lines = lines.drop(1) if e.is_a?(FrozenError) && lines.first =~ /in '(String|Array|Hash)#/ @@ -24,7 +25,8 @@ def k_eof = SIO.readline def k_farr = FA << 1 def k_fhash = FH[1] = 2 def k_range = 300.chr -KINDS = %i[k_fetch k_arity k_coerce k_frozen k_strset k_zdiv k_zmod k_eof k_farr k_fhash k_range] +def k_eagain = RP.read_nonblock(1) +KINDS = %i[k_fetch k_arity k_coerce k_frozen k_strset k_zdiv k_zmod k_eof k_farr k_fhash k_range k_eagain] def deep3(m) = deep2(m) def deep2(m) = deep1(m) def deep1(m) = send(m) From ce6bb184ca89a1be58b8cd55d1cc691971a43039 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:32:56 +0000 Subject: [PATCH 409/439] Method JIT: comparisons with a Symbol literal take the identity path `:on_nl == tk[:kind]` and `options[:domain] == :both` were refused: a comparison involving an element read went to the numeric path, which refuses a Symbol literal as an operand (21 methods kept out by it alone). With a Symbol literal on either side, `==`, `!=` and `equal?` now take the identity path. Symbol#== is identity; the other side, when it is the receiver, is taken to be a Symbol and checked by IsIdentical as before (its class's == must be the library's, else it deopts). Not where a refinement is active. IR_JIT_SYMBOL_EQ=0 turns it off. Util/bench/symeq-shapes.rb: 86.6 -> 74.6 ns and 86.5 -> 79.8. Census: 42 methods up (36 to compiles), none down; app-shapes compiles IO#__decorated__, which it used to decline. Util/jit-symeq-matrix.rb (new) and the matrices it touches print CRuby's output in every JIT mode; the equal_value specs and IronRuby.Tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Runtime/Jit/JitCompiler.cs | 20 ++++++- Util/bench/symeq-shapes.rb | 24 ++++++++ Util/jit-symeq-matrix.rb | 85 +++++++++++++++++++++++++++++ Util/perf/LEDGER.md | 28 ++++++++++ 4 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 Util/bench/symeq-shapes.rb create mode 100644 Util/jit-symeq-matrix.rb diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 1d4575392..35c80d8d3 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1554,6 +1554,18 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return IronRuby.Compiler.Methods.MakeArrayOpCall(values); } + // IR_JIT_SYMBOL_EQ=0 turns IsSymbolComparison off + internal static readonly bool SymbolComparisons = Environment.GetEnvironmentVariable("IR_JIT_SYMBOL_EQ") != "0"; + + /// `x == :sym', `:sym != x', `x.equal?(:sym)': a comparison with a Symbol literal on one side. + internal static bool IsSymbolComparison(MethodCall/*!*/ node) { + if (!SymbolComparisons || node.Target == null || node.Block != null) { return false; } + if (node.MethodName != "==" && node.MethodName != "!=" && node.MethodName != "equal?") { return false; } + var args = node.Arguments; + if (args == null || args.Expressions.Length != 1) { return false; } + return node.Target is SymbolLiteral || args.Expressions[0] is SymbolLiteral; + } + // IR_JIT_SPLAT_LITERAL=0 turns EmitSplattingArrayLiteral off internal static readonly bool SplatLiterals = Environment.GetEnvironmentVariable("IR_JIT_SPLAT_LITERAL") != "0"; @@ -3253,6 +3265,10 @@ internal static bool IsTypeTest(MethodCall/*!*/ node) { // x = self or a node walked to): IsIdentical checks the receiver's `==' and deopts where it is not // BasicObject's, as for a profiled one. if (observed == null && JitRuntime.InlineUnsampled && IsLocalObject(node.Target)) { observed = typeof(RubyObject); } + // `:on_nl == tk[:kind]', `options[:domain] == :both': a Symbol literal on either side. Symbol#== is + // identity; the other side, when it is the receiver, is taken to be a Symbol as well, which IsIdentical + // checks (its class's `==' BasicObject's or Symbol's), deopting for anything else (IsSymbolComparison). + if (observed == null && IsSymbolComparison(node)) { observed = typeof(RubySymbol); } if (observed == typeof(void) && node.Target is ConstantVariable && node.MethodName != "equal?" && _refinements.IsEmpty) { // `NO_WORK == x' (Richards), NO_WORK a constant whose value is nil, which the constant // version guard keeps: NilClass#== (and BasicObject#!=, which calls it) being the public @@ -4773,7 +4789,9 @@ private bool WalkCall(MethodCall/*!*/ node) { // which this must not pre-empt (a String literal is no operand Walk takes). if (node.Target != null && ((argc == 0 && node.MethodName == "nil?") || argc == 1 && !JitCompiler.IsStringLiteralComparison(node) && (node.MethodName == "equal?" || node.MethodName == "==" || node.MethodName == "!=") && - !(args.Expressions[0] is SplattedArgument) && !IsElementRead(node.Target) && !IsElementRead(args.Expressions[0]))) { + !(args.Expressions[0] is SplattedArgument) && + // an element read beside a number is a number's comparison (EmitBinary); beside a Symbol literal it is an identity + (JitCompiler.IsSymbolComparison(node) || !IsElementRead(node.Target) && !IsElementRead(args.Expressions[0])))) { return Walk(node.Target) && (argc == 0 || Walk(args.Expressions[0])); } diff --git a/Util/bench/symeq-shapes.rb b/Util/bench/symeq-shapes.rb new file mode 100644 index 000000000..47328df05 --- /dev/null +++ b/Util/bench/symeq-shapes.rb @@ -0,0 +1,24 @@ +# Comparisons with a Symbol literal in hot methods (JitCompiler.IsSymbolComparison): an element read against a Symbol on +# either side. Every line prints the sum of its results next to its time; it must be CRuby's. +# ruby Util/perf/ab.rb Util/bench/symeq-shapes.rb cruby=ruby "base=env IR_CONFIG=Release ../ironruby/ir.sh" "new=env IR_CONFIG=Release ./ir.sh" +$stdout.sync = true +class SES + def right(tk) = tk[:kind] == :on_nl ? 1 : 0 + def left(tk) = :on_nl == tk[:kind] ? 1 : 0 +end +def cpu; Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID); end +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times do + t0 = cpu; sum = yield n; d = cpu - t0 + best = d if d < best + end + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +o = SES.new +TKS = [{ kind: :on_nl }, { kind: :on_sp }] +N = (ENV["N"] || 1_000_000).to_i +t("right", N) { |n| i = 0; r = 0; while i < n; r += o.right(TKS[i & 1]); i += 1; end; r } +t("left", N) { |n| i = 0; r = 0; while i < n; r += o.left(TKS[i & 1]); i += 1; end; r } diff --git a/Util/jit-symeq-matrix.rb b/Util/jit-symeq-matrix.rb new file mode 100644 index 000000000..f6082801c --- /dev/null +++ b/Util/jit-symeq-matrix.rb @@ -0,0 +1,85 @@ +# Differential matrix for comparisons with a Symbol literal in methods the method JIT compiles (`tk[:kind] == :on_nl', +# `:on_nl == tk[:kind]', `options[:domain] == :both'; JitCompiler.IsSymbolComparison, JitRuntime.IsIdentical). Run +# under CRuby and under ./ir.sh in every mode, and diff: +# +# ruby Util/jit-symeq-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-symeq-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-symeq-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-symeq-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep SE +# The traps: the other side is not a Symbol (a String, whose == is its own, nil, a number, an object with an == of its +# own, a BasicObject), Symbol#== redefined or refined, the receiver being the Symbol (whose == is asked) or the other +# side (whose == is). + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +class Eqq + def ==(o) = :custom +end + +class SE + def initialize(h = { domain: :both }); @options = h; end + def options = @options + def nl?(tk) = tk[:kind] == :on_nl + def nl_left?(tk) = :on_nl == tk[:kind] + def not_nl?(tk) = tk[:kind] != :on_nl + def same?(tk) = tk[:kind].equal?(:on_nl) + def both? = options[:domain] == :both + def plain(x) = x == :s +end + +o = SE.new +NL = { kind: :on_nl } +SP = { kind: :on_sp } +t("nl?, hot") { warm { |i| o.nl?(i.odd? ? NL : SP) } } +t("nl? of other kinds") { [:on_nl, :x, "on_nl", nil, 1, 1.5, [:on_nl]].map { |k| o.nl?({ kind: k }) } } +t("nl_left?, hot") { warm { |i| o.nl_left?(i.odd? ? NL : SP) } } +t("nl_left? of other kinds") { [:on_nl, "on_nl", nil, 1, Eqq.new].map { |k| o.nl_left?({ kind: k }) } } +t("not_nl?") { warm { o.not_nl?(SP) }; [o.not_nl?(NL), o.not_nl?({ kind: "on_nl" }), o.not_nl?({})] } +t("same?") { warm { o.same?(NL) }; [o.same?(NL), o.same?({ kind: "on_nl" })] } +t("both?") { warm { o.both? }; [o.both?, SE.new({ domain: :local }).both?, SE.new({}).both?] } +t("plain") { warm { |i| o.plain(i.odd? ? :s : :t) }; [o.plain(:s), o.plain("s"), o.plain(nil), o.plain(Eqq.new)] } +t("an object with its own ==") { o.nl?({ kind: Eqq.new }) } +t("a BasicObject") { [o.nl?({ kind: BasicObject.new }), o.nl_left?({ kind: BasicObject.new })] } +class Symbol + alias_method :__orig_eq, :== + def ==(o) = :symbol_redefined +end +t("Symbol#== redefined") { [o.nl?(NL), o.nl_left?(NL), o.plain(:s)] } +class Symbol + alias_method :==, :__orig_eq +end +t("Symbol#== restored") { [o.nl?(NL), o.nl_left?(NL), o.plain(:s)] } + +module SymEqRefinement + refine Symbol do + def ==(o) = :refined + end +end +class SE + using SymEqRefinement + def refined(tk) = tk[:kind] == :on_nl +end +t("refined") { warm { o.refined(NL) } } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 829cab90e..6c86a7fd8 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,34 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitsymeq (2026-11-29, census and timed, not gated) - a comparison with a Symbol literal in the method JIT's + typed body** (the census's SymbolLiteral: 21 methods refused by it alone; switch `IR_JIT_SYMBOL_EQ`). Built on + perf/jitsplatlit e34abb3. + - **Choosing it, and what was passed over.** The constants left (40 alone) are nearly all dynamic lookups, `self::X` + (21) and `self.class::X` (17). The generic lookup reports deprecations with a warning, refuses private + constants, autoloads, calls const_missing, wraps values for Ractors and needs a scope: much to reproduce for + cold methods, left. Next were the Symbol literals: `:on_nl == tk[:kind]`, `options[:domain] == :both`, + `arguments[0] == :args_add_block`. The screen sends a comparison with an element read to the numeric path (to + speculate numbers), and refuses a Symbol literal there as an operand. + - **What.** `JitCompiler.IsSymbolComparison`: `==`, `!=` or `equal?` with a Symbol literal on either side goes to + the identity path (EmitIdentityCall), element reads included. Symbol#== is identity. The other side, when it is + the receiver, is taken to be a Symbol, and `JitRuntime.IsIdentical` checks it as before: its class's `==` must + be BasicObject's or Symbol's library method, under the method version, else it deopts (a String, a number, an + object with its own `==`). Not where a refinement is active. + - **Census** (Src/StdLib, Util/bench, AWFY, against e34abb3): 42 methods up (21 maybe -> compiles, 15 never -> + compiles, 6 never -> maybe), none down. + - **app-shapes, traced:** specialized 124 -> 128 (IO#__decorated__, ruby4.rb's newline-option test, compiled + where it was declined), declined 29 -> 28. + - **Clock** (ab.rb -r 9, `Util/bench/symeq-shapes.rb`, ns, off -> new; CRuby about 57): `tk[:kind] == :on_nl` 86.6 + -> 74.6, `:on_nl == tk[:kind]` 86.5 -> 79.8. + - **Checks.** `Util/jit-symeq-matrix.rb` (new, 13 rows): both sides, `!=` and `equal?`; the other side a Symbol, a + String, nil, an Integer, a Float, an Array, an object with its own `==`, a BasicObject; an attribute reader's + Hash; Symbol#== redefined, then restored; refined. It prints CRuby's output with the JIT on, -X:NoJIT + -X:NoOSR, -X:NoJITCalls, IR_LIGHT_FRAMES=0 and the switch off. jit, jit-calls, jit-const, jit-isa, + jit-objops, jit-aref and hot-shapes in the same five modes: CRuby's output on both builds (40 runs with + jit-symeq). ruby/spec core/symbol, basicobject and kernel equal_value: no failures on either build. + IronRuby.Tests (Debug), all 1,441: PASSED. + - **perf/jitsplatlit (2026-11-29, census and timed, not gated) - `[*a, x]` Array literals in the method JIT's typed body** (the census's SplattedArgument: 42 methods refused by it alone; switch `IR_JIT_SPLAT_LITERAL`). Built on perf/jitslice 7e258de. From 7cde67ee4fd7cd726f891cb73a7f9716693cc64b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:41:45 +0000 Subject: [PATCH 410/439] Ledger: drop the orphaned header round 13's merge left of perf/jitdefined's entry The merge of claude/perf-jitbody kept round 12's gated header of the entry on its own and the entry's body under the unmarked header; the body takes the gated header. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 3ee891cea..ca2b9d0c0 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2257,8 +2257,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has redefined to keep its block (each call's Proc its own), back, and a deopt: CRuby's output with the JIT on and off. ruby/spec language in full: 2935 examples, the one known error (send_spec's `into`/`to`). IronRuby.Tests in full on Debug: PASSED. -- **perf/jitdefined (2026-11-29, census and timed, gated 2026-11-29 (round 12's gate entry)) - `defined?(@x)` in the method JIT's typed body** (the - - **perf/jitsplatlit (2026-11-29, census and timed, not gated) - `[*a, x]` Array literals in the method JIT's typed body** (the census's SplattedArgument: 42 methods refused by it alone; switch `IR_JIT_SPLAT_LITERAL`). Built on perf/jitslice 7e258de. @@ -2348,7 +2346,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has jit-defined in the same five modes: CRuby's output on both builds (35 runs with jit-masgn). ruby/spec language/variables: 119 examples, no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. -- **perf/jitdefined (2026-11-29, census and timed, not gated) - `defined?(@x)` in the method JIT's typed body** (the +- **perf/jitdefined (2026-11-29, census and timed, gated 2026-11-29 (round 12's gate entry)) - `defined?(@x)` in the method JIT's typed body** (the census's `IsDefinedExpression`: 118 methods refused, 36 by it alone, nearly all `defined?(@ivar)`; switch `IR_JIT_DEFINED_IVAR`). Built on perf/jitcaseeq da02d10 (happy-gauss 50b2427 merged). - **First, the screen refusals passed over.** `@x ||= v` (296 first refusals, 44 alone) is already compiled. The From 10bb673f1cbcaed678ea4718dfd6a424e1de01fb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:45:52 +0000 Subject: [PATCH 411/439] Take an RLIM_ name as a limit in Process.setrlimit Process.setrlimit(:CORE, :INFINITY) raised "no implicit conversion of Symbol into Integer", and so did any other Symbol or String limit. MRI's rlimit_resource_value reads a Symbol, or a String (or what #to_str makes one), as the name of an RLIM_ constant without its prefix - INFINITY, SAVED_MAX, SAVED_CUR - and raises ArgumentError "invalid resource value: FOO" for any other name (and "string contains null byte" for a NUL). The prelude's __rlimit_value__ now does the same. CRuby's TestProcess#test_rlimit_value passes now; ruby/spec's core/process setrlimit and getrlimit specs pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 33 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 14 +++++++++++ 3 files changed, 48 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a26967490..e26944738 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1049,6 +1049,7 @@ public Tests(Driver/*!*/ driver) { AtExit_ErrinfoAfterExit1, String_LinesWideBrokenSeparator1, String_ChilledWarningChangesReceiver1, + Process_SetrlimitValueName1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 50ac022b3..8dbccd320 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10343,5 +10343,38 @@ public void AtExit_ErrinfoAfterExit1() { } Assert(log.Count == 2 && log[0].ToString() == "2:exit" && log[1].ToString() == "1:exit"); } + + /// + /// Process.setrlimit takes a limit as MRI's rlimit_resource_value does: a Symbol or String names one of the RLIM_ + /// constants without its prefix (INFINITY, SAVED_MAX, SAVED_CUR), anything else is an ArgumentError naming it (CRuby's + /// TestProcess#test_rlimit_value). + /// + public void Process_SetrlimitValueName1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } + TestOutput(@" +require 'ruby4' +def t; yield; rescue ArgumentError, TypeError => e; p [e.class, e.message]; end +t { Process.setrlimit(:CORE, :FOO) } +t { Process.setrlimit(:CORE, ""BAR"") } +t { Process.setrlimit(:CORE, ""INFINITY\0"") } +o = Object.new +def o.to_str = ""NOPE"" +t { Process.setrlimit(:CORE, 0, o) } +t { Process.setrlimit(:CORE, 1.5, :x) } +cur, max = Process.getrlimit(:CORE) +p Process.setrlimit(:CORE, cur, max == Process::RLIM_INFINITY ? :INFINITY : max) +p Process.getrlimit(:CORE) == [cur, max] +", @" +[ArgumentError, ""invalid resource value: FOO""] +[ArgumentError, ""invalid resource value: BAR""] +[ArgumentError, ""string contains null byte""] +[ArgumentError, ""invalid resource value: NOPE""] +[ArgumentError, ""invalid resource value: x""] +nil +true +"); + } } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index b18bd291a..602a10b1b 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9451,6 +9451,20 @@ def __rlimit_by_name__(name, original) # __setrlimit__ takes it as a signed long and reinterprets the bits, so anything above # 2**63-1 has to be folded into the negative half first or the conversion overflows. def __rlimit_value__(value) + # rlimit_resource_value: a Symbol, or a String (or what #to_str makes one), names one of + # the RLIM_ constants without the prefix; anything else is a number + name = if value.is_a?(::Symbol) + value.to_s + elsif value.is_a?(::String) || (!value.is_a?(::Integer) && value.respond_to?(:to_str) && (value = value.to_str).is_a?(::String)) + ::Kernel.raise(::ArgumentError, "string contains null byte") if value.include?("\0") + value + end + if name + unless %w[INFINITY SAVED_MAX SAVED_CUR].include?(name) && const_defined?("RLIM_#{name}") + ::Kernel.raise(::ArgumentError, "invalid resource value: #{value}") + end + value = const_get("RLIM_#{name}") + end unless value.is_a?(Integer) unless value.respond_to?(:to_int) raise TypeError, "no implicit conversion of #{value.class} into Integer" From cba6e11d883adc9eb97d5bbbf1a6ebaf9616ed85 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:46:00 +0000 Subject: [PATCH 412/439] Raise Errno::EINVAL from Process.clock_getres for a clock it lacks Process.clock_getres(:foo) answered a resolution for any clock id at all, names it had never heard of and Integers no clock has included. MRI's clock_getres knows the clocks clock_gettime knows: its emulated clocks by Symbol (the Mach one only on macOS) and the clockid_t numbers, read through NUM2CLOCKID; any other is Errno::EINVAL "Invalid argument - clock_getres(:foo)", and nil or a String is a TypeError. The prelude's clock_getres now checks the id as Process.clock_gettime already does. CRuby's TestProcess#test_clock_getres passes now; ruby/spec's core/process clock_getres and clock_gettime specs pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 30 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 21 ++++++++++++++++- 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e26944738..e09c89108 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1050,6 +1050,7 @@ public Tests(Driver/*!*/ driver) { String_LinesWideBrokenSeparator1, String_ChilledWarningChangesReceiver1, Process_SetrlimitValueName1, + Process_ClockGetresInvalid1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 8dbccd320..38ac4ddfa 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10374,6 +10374,36 @@ p Process.getrlimit(:CORE) == [cur, max] [ArgumentError, ""invalid resource value: x""] nil true +"); + } + + /// + /// Process.clock_getres knows the clocks clock_gettime knows and raises Errno::EINVAL naming any other, as MRI's + /// clock_getres does (CRuby's TestProcess#test_clock_getres). + /// + public void Process_ClockGetresInvalid1() { + TestOutput(@" +require 'ruby4' +def t; yield; rescue SystemCallError, TypeError => e; p [e.class, e.message]; end +t { Process.clock_getres(:foo) } +t { Process.clock_getres(12345) } +t { Process.clock_getres(10) } +t { Process.clock_getres(nil) } +t { Process.clock_getres(""x"") } +t { Process.clock_getres(:MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC) } +p Process.clock_getres(:TIMES_BASED_CLOCK_MONOTONIC), Process.clock_getres(:TIME_BASED_CLOCK_REALTIME, :second) +p Process.clock_getres(Process::CLOCK_MONOTONIC).class, Process.clock_getres(1.5).class +", @" +[Errno::EINVAL, ""Invalid argument - clock_getres(:foo)""] +[Errno::EINVAL, ""Invalid argument - clock_getres(12345)""] +[Errno::EINVAL, ""Invalid argument - clock_getres(10)""] +[TypeError, ""no implicit conversion from nil to integer""] +[TypeError, ""no implicit conversion of String into Integer""] +[Errno::EINVAL, ""Invalid argument - clock_getres(:MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC)""] +0.01 +1 +Float +Float "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 602a10b1b..83d44174a 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -8806,7 +8806,26 @@ def self.abort(*args) # We have no way to ask the platform, so report the resolution the source we # actually use has: Stopwatch for the monotonic clocks, and Time for the rest. def clock_getres(clock_id, unit = :float_second) - seconds = CLOCK_RESOLUTIONS__[clock_id.to_s] || 1.0 / System::Diagnostics::Stopwatch.frequency.to_f + # The clocks clock_gettime knows, and Errno::EINVAL for any other (MRI's clock_getres): a + # Symbol names an emulated clock, anything else is a clockid_t (NUM2CLOCKID) + if clock_id.is_a?(::Symbol) + seconds = CLOCK_RESOLUTIONS__[clock_id.to_s] + seconds = nil if clock_id == :MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC && !RUBY_PLATFORM.include?("darwin") + ::Kernel.raise(::Errno::EINVAL, "clock_getres(#{clock_id.inspect})") unless seconds + else + ::Kernel.raise(::TypeError, "no implicit conversion from nil to integer") if clock_id.nil? + id = clock_id + unless id.is_a?(::Integer) + unless id.respond_to?(:to_int, true) + ::Kernel.raise(::TypeError, "no implicit conversion of #{clock_id.class} into Integer") + end + id = id.__send__(:to_int) + end + unless (0..11).include?(id) && id != 10 + ::Kernel.raise(::Errno::EINVAL, "clock_getres(#{clock_id.inspect})") + end + seconds = 1.0 / System::Diagnostics::Stopwatch.frequency.to_f + end case unit when :float_second then seconds when :float_millisecond then seconds * 1_000.0 From 190961def438b12cb3c46150c73f34ebc99f0ab7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:46:08 +0000 Subject: [PATCH 413/439] Check Process.groups= and initgroups arguments as CRuby does Process.groups= with more groups than Process.maxgroups went to setgroups(2) and came back Errno::EINVAL; MRI's proc_setgroups counts them first and raises ArgumentError "too many groups, 65536 max" before it looks at a single one. Process.initgroups took the user name with #to_s, so a Symbol or nil was a user name and "\0" reached initgroups(3); MRI takes it with StringValueCStr: a TypeError for anything that is no String, ArgumentError "string contains null byte" for a NUL. CRuby's TestProcess#test_maxgroups and #test_initgroups pass now; ruby/spec's core/process groups and initgroups specs pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 26 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 13 +++++++++++-- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index e09c89108..a4b89f091 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1051,6 +1051,7 @@ public Tests(Driver/*!*/ driver) { String_ChilledWarningChangesReceiver1, Process_SetrlimitValueName1, Process_ClockGetresInvalid1, + Process_GroupsArgumentChecks1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 38ac4ddfa..cceb13552 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10404,6 +10404,32 @@ p Process.clock_getres(Process::CLOCK_MONOTONIC).class, Process.clock_getres(1.5 1 Float Float +"); + } + + /// + /// Process.groups= refuses more groups than Process.maxgroups before it looks at one, and Process.initgroups takes the + /// user name as StringValueCStr does: a String without a NUL (MRI's proc_setgroups and proc_initgroups; CRuby's + /// TestProcess#test_maxgroups and #test_initgroups). + /// + public void Process_GroupsArgumentChecks1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } + TestOutput(@" +require 'ruby4' +def t; yield; rescue ArgumentError, TypeError => e; p [e.class, e.message]; end +t { Process.initgroups(""\0"", 0) } +t { Process.initgroups(:root, 0) } +t { Process.initgroups(nil, 0) } +t { Process.groups = [0] * (Process.maxgroups + 1) } +t { Process.groups = [""no such group""] * (Process.maxgroups + 1) } +", @" +[ArgumentError, ""string contains null byte""] +[TypeError, ""no implicit conversion of Symbol into String""] +[TypeError, ""no implicit conversion of nil into String""] +[ArgumentError, ""too many groups, 65536 max""] +[ArgumentError, ""too many groups, 65536 max""] "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 83d44174a..e05b3f223 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9560,13 +9560,22 @@ def self.egid=(value) end def self.groups=(list) - gids = list.to_ary.map { |gid| __group_id__(gid) } + list = list.to_ary + # proc_setgroups checks the count before it looks at a single group + if list.size > maxgroups + ::Kernel.raise(::ArgumentError, "too many groups, #{maxgroups} max") + end + gids = list.map { |gid| __group_id__(gid) } __check__(__setgroups__(gids)) list end def self.initgroups(user, group) - __check__(__initgroups__(user.to_s, __group_id__(group))) + # the user name is StringValueCStr's: a String (or #to_str), without a NUL + name = ::String.try_convert(user) + ::Kernel.raise(::TypeError, "no implicit conversion of #{user.nil? ? "nil" : user.class} into String") unless name + ::Kernel.raise(::ArgumentError, "string contains null byte") if name.include?("\0") + __check__(__initgroups__(name, __group_id__(group))) groups end From 847ccd963a98b8d7d2ce67fbe37f1dc1cbefd2de Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:46:21 +0000 Subject: [PATCH 414/439] Name the file a spawn redirection could not open Process.spawn("true", in: "d/notexist") raised Errno::ENOENT naming the command - "No such file or directory - /usr/bin/true" - because the redirection's file is opened in the child by posix_spawn, which reports any failure as the spawn's. MRI opens it in the parent before it forks (rb_execarg_parent_start), so the error names the file, $? is left alone, and Kernel#system raises it whatever exception: says and leaves $? nil, where it answers nil for a command it could not run. A spawn that fails now tries the redirections' files in the parent, with the same flags, and raises the first one's error naming the path; system tells that error from a command it could not start. CRuby's TestProcess#test_execopts_open_failure passes now. ruby/spec's core/process spawn and exec, core/kernel system, spawn and backtick, core/io/popen and library/open3 specs are unchanged (all pass on both builds); the spawn, stdout-buffer and global-light matrices are unchanged in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 38 ++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 53 ++++++++++++++++++++++--- 3 files changed, 87 insertions(+), 5 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index a4b89f091..16e06e8dc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1052,6 +1052,7 @@ public Tests(Driver/*!*/ driver) { Process_SetrlimitValueName1, Process_ClockGetresInvalid1, Process_GroupsArgumentChecks1, + Process_SpawnRedirectOpenFailure1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index cceb13552..dfa477f03 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10430,6 +10430,44 @@ public void Process_GroupsArgumentChecks1() { [TypeError, ""no implicit conversion of nil into String""] [ArgumentError, ""too many groups, 65536 max""] [ArgumentError, ""too many groups, 65536 max""] +"); + } + + /// + /// A redirection whose file cannot be opened is the error, naming the file, as MRI opens it in the parent before it + /// forks: spawn leaves $? alone, and system raises it whatever exception: says and leaves $? nil (CRuby's + /// TestProcess#test_execopts_open_failure). + /// + public void Process_SpawnRedirectOpenFailure1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } + TestOutput(@" +require 'ruby4' +system(""exit 3"") +begin + Process.spawn(""true"", in: ""no/such/dir/file"") +rescue Errno::ENOENT => e + p e.message, $?.exitstatus +end +[true, false].each do |exception| + begin + system(""true"", out: [""no/such/dir/file"", ""w""], exception: exception) + rescue Errno::ENOENT => e + p e.message, $? + end +end +p system(""no-such-command-anywhere"") +p $?.exitstatus +", @" +""No such file or directory - no/such/dir/file"" +3 +""No such file or directory - no/such/dir/file"" +nil +""No such file or directory - no/such/dir/file"" +nil +nil +127 "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index e05b3f223..7c8e98d0a 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9338,7 +9338,34 @@ def self.__with_umask__(mask) end end + # MRI opens a redirection's file in the parent (rb_execarg_parent_start), so a file that cannot + # be opened is the error, naming the file: Errno::ENOENT "d/notexist", not the command. Here + # the child opens it, and a spawn that failed has the files tried in the parent to tell. + def self.__spawn_open_failure__(actions) + (actions || []).each do |action| + next unless action[0] == SPAWN_OPEN + _, _, path, flags, perm = action + mode = [File::RDONLY, File::WRONLY, File::RDWR][flags & 3] || File::RDONLY + mode |= File::CREAT if flags & SPAWN_O_CREAT != 0 + mode |= File::TRUNC if flags & SPAWN_O_TRUNC != 0 + mode |= File::APPEND if flags & SPAWN_O_APPEND != 0 + begin + IO.for_fd(IO.sysopen(path, mode, perm), autoclose: true).close + rescue SystemCallError => e + raise e.class, path.to_s + end + end + end + def self.spawn(*args) + __spawn_reporting__(args, nil) + end + + # Process.spawn. A file a redirection cannot open is the error MRI meets before it forks, so + # $? is left alone and the error is added to parent_failures (when given) for Kernel#system, + # which raises it where it reports a command it could not run as nil. + def self.__spawn_reporting__(args, parent_failures) + parent_failure = nil file, argv, envp, actions, pgroup, options = __spawn_setup__(args) close_others = options[:close_others] ? true : false __with_umask__(options[:umask]) do @@ -9348,12 +9375,21 @@ def self.spawn(*args) if result == -8 && !SPAWN_WINDOWS && file != "/bin/sh" result = __spawn__("/bin/sh", ["sh", file] + argv[1..-1], envp, actions, pgroup, close_others) end + if result.is_a?(Integer) && result < 0 + begin + __spawn_open_failure__(actions) + rescue SystemCallError => e + parent_failure = e + parent_failures << e if parent_failures + raise + end + end __check__(result, file) end - rescue SystemCallError + rescue SystemCallError => e # MRI forks first and only then discovers that the command cannot be run, so the child # it already has exits with 127 and $? says so even though spawn itself raises. - __set_last_status__(__make_status__(-1, 127 << 8)) + __set_last_status__(__make_status__(-1, 127 << 8)) unless e.equal?(parent_failure) raise end @@ -9770,10 +9806,17 @@ def system(*args) ::Kernel.raise(::ArgumentError, "expected true or false as exception: #{exception.inspect}") end + parent_failures = [] begin - pid = Process.spawn(*args) - rescue SystemCallError - # MRI reports "could not even start it" as nil rather than as false. + pid = Process.__spawn_reporting__(args, parent_failures) + rescue SystemCallError => e + # MRI reports "could not even start it" as nil rather than as false. A redirection it could + # not open is raised whatever exception: says, and leaves $? nil (rb_f_system clears the + # status before rb_execarg_parent_start fails). + if parent_failures.any? { |failure| failure.equal?(e) } + Process.__set_last_status__(nil) + raise + end raise if exception return nil end From 5089694decff1b0d172155e4100dbd0dcb279eb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:46:21 +0000 Subject: [PATCH 415/439] Keep $0 frozen, as CRuby does $0 and Process.argv0 are frozen in CRuby: the program name starts out frozen, and assigning to $0 stores a frozen copy of the string (MRI's set_arg0 uses rb_str_new_frozen, which is the string itself when it is already frozen). IronRuby's $0 was an ordinary mutable string, before and after an assignment. The runtime now freezes the program name it sets up and the $0 setter keeps a frozen copy. CRuby's TestProcess#test_argv0_frozen passes now; ruby/spec's core/process/argv0_spec and language/predefined_spec pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 21 +++++++++++++++++++ .../Globals/SpecialGlobalVariableInfo.cs | 4 +++- Src/Ruby/Runtime/RubyContext.cs | 6 +++--- 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 16e06e8dc..cc555cdae 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1053,6 +1053,7 @@ public Tests(Driver/*!*/ driver) { Process_ClockGetresInvalid1, Process_GroupsArgumentChecks1, Process_SpawnRedirectOpenFailure1, + Globals_ProgramNameFrozen1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index dfa477f03..4986407d1 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10468,6 +10468,27 @@ p system(""no-such-command-anywhere"") nil nil 127 +"); + } + + /// + /// $0 holds a frozen copy of what is assigned to it - the string itself if it is frozen - as MRI's set_arg0 does with + /// rb_str_new_frozen (CRuby's TestProcess#test_argv0_frozen). + /// + public void Globals_ProgramNameFrozen1() { + TestOutput(@" +s = +""name"" +$0 = s +p $0.frozen?, s.frozen?, $0.equal?(s), $0 +f = ""frozen"".freeze +$0 = f +p $0.equal?(f) +", @" +true +false +false +""name"" +true "); } } diff --git a/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs b/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs index 80976a02c..18dc3f69d 100644 --- a/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs +++ b/Src/Ruby/Runtime/Globals/SpecialGlobalVariableInfo.cs @@ -277,7 +277,9 @@ public override void SetValue(RubyContext/*!*/ context, RubyScope scope, string/ throw ReadOnlyError(name); case GlobalVariableId.CommandLineProgramPath: - context.CommandLineProgramPath = context.CastToString(value); + // MRI's set_arg0 keeps a frozen copy (rb_str_new_frozen): the string itself if it is frozen + MutableString programPath = context.CastToString(value); + context.CommandLineProgramPath = programPath.IsFrozen ? programPath : programPath.Clone().Freeze(); SetProcessTitle(context.CommandLineProgramPath.ToByteArray()); return; diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 1c51c0104..c82a7c420 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -838,9 +838,9 @@ public RubyContext(ScriptDomainManager/*!*/ manager, IDictionary _itemSeparator = null; _mainThread = Thread.CurrentThread; - // $0 is in the locale's encoding, whatever -K and -E make of the filesystem's (MRI) + // $0 is in the locale's encoding, whatever -K and -E make of the filesystem's, and frozen (MRI) if (_options.MainFile != null) { - CommandLineProgramPath = EncodePath(_options.MainFile, _options.LocaleEncoding); + CommandLineProgramPath = EncodePath(_options.MainFile, _options.LocaleEncoding).Freeze(); } if (_options.Verbosity <= 0) { @@ -4930,7 +4930,7 @@ internal void ApplyWarmStartRequest(string mainFile, ICollection/*!*/ ar } } - CommandLineProgramPath = (mainFile != null) ? EncodePath(mainFile, _options.LocaleEncoding) : null; + CommandLineProgramPath = (mainFile != null) ? EncodePath(mainFile, _options.LocaleEncoding).Freeze() : null; _inputProvider.ReplaceCommandLineArguments(_options.Arguments, CommandLineArgumentEncoding); // The prelude keeps the $0 the program started with for Process.argv0 (in a hidden From 83c96781b968bb33ff3054a038a7c890ebd4bb10 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:53:41 +0000 Subject: [PATCH 416/439] cruby-test: baseline after round eleven test_string and test_process re-swept after the round's fixes: 6,694 tests passing (from 6,684), one file without a summary (test_iseq), as before. Two of the ten are test_string's RSS-ratio memory-leak tests, which flip with load (see PACKAGES.md). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index a5de98b30..22d7ee821 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,684 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,694 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 4b6088f01..8e4b7c57e 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -90,7 +90,7 @@ test_pattern_matching 30 tests 0 failures 0 errors 0 sk test_pipe 12 tests 0 failures 2 errors 0 skips test_primitive 25 tests 0 failures 0 errors 0 skips test_proc 120 tests 2 failures 1 errors 0 skips -test_process 141 tests 25 failures 18 errors 1 skips +test_process 141 tests 19 failures 18 errors 1 skips test_ractor 19 tests 10 failures 0 errors 0 skips test_rand 41 tests 0 failures 0 errors 0 skips test_random_formatter 26 tests 0 failures 0 errors 0 skips @@ -112,7 +112,7 @@ test_sleep 2 tests 0 failures 0 errors 0 sk test_sprintf 35 tests 3 failures 0 errors 0 skips test_sprintf_comb 95 tests 0 failures 0 errors 0 skips test_stack 3 tests 2 failures 1 errors 0 skips -test_string 475 tests 17 failures 4 errors 0 skips +test_string 475 tests 11 failures 6 errors 0 skips test_string_memory 3 tests 0 failures 3 errors 0 skips test_stringchar 4 tests 0 failures 0 errors 0 skips test_struct 102 tests 0 failures 0 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 69 clean, 72 with failures, 1 without a summary -10369 tests, 2552035 assertions, 483 failures, 3132 errors, 70 skips; 6684 passing +10369 tests, 2552057 assertions, 471 failures, 3134 errors, 70 skips; 6694 passing From 13fe1f8f31844d9648650cb53b70a75f8df28814 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:55:34 +0000 Subject: [PATCH 417/439] Take the :hertz unit in Process.clock_getres Process.clock_getres(:TIMES_BASED_CLOCK_MONOTONIC, :hertz) raised "unexpected unit: hertz". MRI's clock_getres takes :hertz - and only it, not clock_gettime - and answers the clock's ticks per second as a Float (timetick2dblnum_reciprocal): 100.0 for the times()-based clocks. The prelude's clock_getres now does, from the resolution it reports, which is one over a whole number of ticks for every clock it has. CRuby's TestProcess#test_clock_getres_TIMES_BASED_CLOCK_MONOTONIC, _TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID and _CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID pass now; ruby/spec's core/process/clock_getres_spec passes on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 25 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 3 +++ 3 files changed, 29 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 5776573d3..1b620302c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1057,6 +1057,7 @@ public Tests(Driver/*!*/ driver) { Process_GroupsArgumentChecks1, Process_SpawnRedirectOpenFailure1, Globals_ProgramNameFrozen1, + Process_ClockGetresHertz1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 4986407d1..44b6ed2ee 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10489,6 +10489,31 @@ public void Globals_ProgramNameFrozen1() { false ""name"" true +"); + } + + /// + /// Process.clock_getres takes the :hertz unit, the clock's ticks per second as a Float, and clock_gettime does not (MRI's + /// clock_getres and timetick2dblnum_reciprocal; CRuby's TestProcess#test_clock_getres_TIMES_BASED_CLOCK_MONOTONIC). + /// + public void Process_ClockGetresHertz1() { + TestOutput(@" +require 'ruby4' +[:GETTIMEOFDAY_BASED_CLOCK_REALTIME, :TIME_BASED_CLOCK_REALTIME, :GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID, + :TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID, :CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID, :TIMES_BASED_CLOCK_MONOTONIC].each do |c| + p [c, Process.clock_getres(c, :hertz)] +end +p Process.clock_getres(Process::CLOCK_MONOTONIC, :hertz).class +p((Process.clock_gettime(Process::CLOCK_MONOTONIC, :hertz) rescue $!)) +", @" +[:GETTIMEOFDAY_BASED_CLOCK_REALTIME, 1000000.0] +[:TIME_BASED_CLOCK_REALTIME, 1.0] +[:GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID, 1000000.0] +[:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID, 100.0] +[:CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID, 1000000.0] +[:TIMES_BASED_CLOCK_MONOTONIC, 100.0] +Float +# "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index dbabcdeb0..e0a5a376f 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -8855,6 +8855,9 @@ def clock_getres(clock_id, unit = :float_second) when :millisecond then (seconds * 1_000).to_i when :microsecond then (seconds * 1_000_000).to_i when :nanosecond then (seconds * 1_000_000_000).to_i + # clock_getres alone takes :hertz, the ticks per second (timetick2dblnum_reciprocal); every + # resolution here is one over a whole number of ticks + when :hertz then (1.0 / seconds).round.to_f when nil then seconds else ::Kernel.raise(::ArgumentError, "unexpected unit: #{unit}") end From 260663fe21fac914608f17bb68764363498175c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:03:41 +0000 Subject: [PATCH 418/439] Marshal Process::Status as CRuby does, and let it be allocated Marshal.dump($?) raised "no _dump_data is defined for class Process::Status", and Process::Status.allocate "allocator undefined". MRI marshals a status through rb_marshal_define_compat: an 'o' record of Process::Status holding the wait status and the pid as "status" and "pid" (process_status_dump), read back into a status equal to the first (process_status_load); Process::Status.allocate makes one with pid 0, which inspects as "#" and dumps with neither. Marshal now writes and reads that record, and Status has a public constructor for allocate. CRuby's TestProcess#test_status, #test_status_kill and #test_pst_inspect pass now. ruby/spec's core/marshal and core/process/status pass on both builds; the marshal matrix is unchanged in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 42 ++++++++++++++++++ Src/Libraries/Builtins/Marshal.cs | 59 ++++++++++++++++++++++++- Src/Libraries/Builtins/RubyProcess.cs | 29 +++++++++++- 4 files changed, 128 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 1b620302c..340ffd6c1 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1058,6 +1058,7 @@ public Tests(Driver/*!*/ driver) { Process_SpawnRedirectOpenFailure1, Globals_ProgramNameFrozen1, Process_ClockGetresHertz1, + Process_StatusMarshal1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 44b6ed2ee..a4b663960 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10514,6 +10514,48 @@ p Process.clock_getres(Process::CLOCK_MONOTONIC, :hertz).class [:TIMES_BASED_CLOCK_MONOTONIC, 100.0] Float # +"); + } + + /// + /// A Process::Status marshals as MRI's rb_marshal_define_compat has it: an 'o' record holding the wait status and the pid + /// (process_status_dump), loaded back into an equal Status; one from Process::Status.allocate has neither and inspects as + /// uninitialized (CRuby's TestProcess#test_status, #test_status_kill and #test_pst_inspect). + /// + public void Process_StatusMarshal1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } + TestOutput(@" +require 'ruby4' +system(""exit 3"") +s = $? +d = Marshal.dump(s) +p d.sub(/pidi.*\z/m, ""pid..."") +t = Marshal.load(d) +p t == s, t.equal?(s), t.exitstatus, t.pid == s.pid, t.class +system(""sh"", ""-c"", ""kill -9 $$"") +k = Marshal.load(Marshal.dump($?)) +p [k.signaled?, k.termsig, k.exited?, k == $?] +a = Process::Status.allocate +p a.inspect, a.to_s, a.pid, a.exitstatus +p Marshal.dump(a), Marshal.load(Marshal.dump(a)).inspect +p Marshal.load(Marshal.dump([s, s])).then { |x, y| x.equal?(y) } +", @" +""\x04\bo:\x14Process::Status\a:\vstatusi\x02\x00\x03:\bpid..."" +true +false +3 +true +Process::Status +[true, 9, false, true] +""#"" +""pid 0 exit 0"" +0 +0 +""\x04\bo:\x14Process::Status\x00"" +""#"" +true "); } } diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 6fa47799e..0f80dfd20 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -319,7 +319,8 @@ internal static bool IsDumpableAsObject(RubyClass/*!*/ theClass) { } Type type = cls.GetUnderlyingSystemType(); - return typeof(Exception).IsAssignableFrom(type) || typeof(Range).IsAssignableFrom(type); + return typeof(Exception).IsAssignableFrom(type) || typeof(Range).IsAssignableFrom(type) || + typeof(RubyProcess.Status).IsAssignableFrom(type); } return true; } @@ -679,6 +680,24 @@ private void TestForAnonymous(RubyModule/*!*/ theModule) { } } + /// + /// MRI marshals a Process::Status through rb_marshal_define_compat: an 'o' record of the class + /// holding the wait status and the pid as "status" and "pid" (process_status_dump), or nothing + /// at all for one with no pid (Process::Status.allocate). + /// + private void WriteProcessStatus(RubyProcess.Status/*!*/ status) { + WriteObject(status); + if (status.ProcessId == 0) { + WriteInt32(0); + return; + } + WriteInt32(2); + WriteSymbol("status", RubyEncoding.Binary); + WriteAnObject(ScriptingRuntimeHelpers.Int32ToObject(status.RawStatus)); + WriteSymbol("pid", RubyEncoding.Binary); + WriteAnObject(ScriptingRuntimeHelpers.Int32ToObject(status.ProcessId)); + } + private void WriteRange(Range/*!*/ range) { WriteObject(range); WriteInt32(3); @@ -1214,6 +1233,8 @@ obj is RubyArray || obj is Hash || obj is RubyRegex || obj is RubyModule || WriteStruct((RubyStruct)obj, theClass); } else if (obj is Range) { WriteRange((Range)obj); + } else if (obj is RubyProcess.Status) { + WriteProcessStatus((RubyProcess.Status)obj); } else if (obj is Exception) { WriteException((Exception)obj, instanceNames); } else { @@ -1859,6 +1880,9 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { if (typeof(Range).IsAssignableFrom(type)) { return ReadRange(theClass, count, objectRef); } + if (typeof(RubyProcess.Status).IsAssignableFrom(type)) { + return ReadProcessStatus(theClass, count, objectRef); + } if (typeof(Exception).IsAssignableFrom(type)) { // built from its attributes, which are not instance variables of the result var attributes = new Dictionary(); @@ -1922,6 +1946,39 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { /// not nil). Any other pair in the record is ignored, as MRI ignores it (IronRuby used to write a /// subclass's instance variables there). /// + // MRI's process_status_load: the "status" and "pid" of the record, each 0 when it is absent + private object/*!*/ ReadProcessStatus(RubyClass/*!*/ theClass, int count, int objectRef) { + var status = (RubyProcess.Status)RubyUtils.CreateObject(theClass); + if (objectRef >= 0) { + _objects[objectRef] = status; + } + int pid = 0, word = 0; + for (int i = 0; i < count; i++) { + string name = ReadIdentifier(); + object value = ReadAnObject(false); + if (value == null) { + continue; + } + switch (name) { + case "status": word = LoadedInt(value); break; + case "pid": pid = LoadedInt(value); break; + } + } + status.InitializeLoaded(pid, word); + return status; + } + + // NUM2INT of a value read back from a dump + private int LoadedInt(object/*!*/ value) { + if (value is int) { + return (int)value; + } + if (value is BigInteger) { + throw RubyExceptions.CreateRangeError("bignum too big to convert into 'int'"); + } + throw RubyExceptions.CreateTypeError("no implicit conversion of {0} into Integer", Context.GetClassDisplayName(value)); + } + private object/*!*/ ReadRange(RubyClass/*!*/ theClass, int count, int objectRef) { return ReadRange(theClass, count, objectRef, false); } diff --git a/Src/Libraries/Builtins/RubyProcess.cs b/Src/Libraries/Builtins/RubyProcess.cs index 4ea04b1f5..9c17dfd7d 100644 --- a/Src/Libraries/Builtins/RubyProcess.cs +++ b/Src/Libraries/Builtins/RubyProcess.cs @@ -331,14 +331,35 @@ private static bool IsShellCommand(string/*!*/ str) { [RubyClass("Status")] [HideMethod("new", IsStatic = true)] public sealed class Status { - private readonly int _pid; - private readonly int _status; + // set once, by the constructor or by Marshal.load (MRI's process_status_load) + private int _pid; + private int _status; + + /// + /// Process::Status.allocate: pid 0, which MRI's pst_inspect calls uninitialized. + /// + public Status() { + } internal Status(int pid, int status) { _pid = pid; _status = status; } + /// The raw wait status, as MRI's process_status_dump writes it. + internal int RawStatus { + get { return _status; } + } + + internal int ProcessId { + get { return _pid; } + } + + internal void InitializeLoaded(int pid, int status) { + _pid = pid; + _status = status; + } + internal Status(Process/*!*/ process) : this(process.Id, process.HasExited ? (process.ExitCode & 0xff) << 8 : 0) { } @@ -450,6 +471,10 @@ public static bool Equals(Status/*!*/ self, object other) { [RubyMethod("inspect")] public static MutableString/*!*/ Inspect(Status/*!*/ self) { + if (self._pid == 0) { + // Process::Status.allocate, or a dump of one (pst_inspect) + return MutableString.Create("#", RubyEncoding.Binary); + } // BINARY, as rb_sprintf makes it in MRI's pst_inspect return MutableString.Create(String.Format(CultureInfo.InvariantCulture, "#", self._pid, Describe(self)), RubyEncoding.Binary); From 661838eee9018858b47cb87c892c9e26c37633ad Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:11:01 +0000 Subject: [PATCH 419/439] Run a command that starts with an assignment through the shell IO.popen("foofoo=barbar env") raised Errno::ENOENT for a program named "foofoo=barbar": a one-string command went to the shell only for a shell metacharacter or a built-in. MRI's rb_exec_fillarg also counts an "=" in the first word, ahead of any "/" (after which it is part of a path), as an assignment preceding the command name, which only a shell can run. The prelude's __spawn_command__ now does the same, off Windows. CRuby's TestProcess#test_sh_env passes now. ruby/spec's core/process spawn and exec, core/kernel system and backtick and core/io/popen specs are unchanged (all pass on both builds); the spawn matrix is unchanged in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 28 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 8 +++++++ 3 files changed, 37 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 340ffd6c1..688e35df1 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1059,6 +1059,7 @@ public Tests(Driver/*!*/ driver) { Globals_ProgramNameFrozen1, Process_ClockGetresHertz1, Process_StatusMarshal1, + Process_SpawnShellAssignment1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index a4b663960..6439beeec 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10556,6 +10556,34 @@ p Marshal.load(Marshal.dump([s, s])).then { |x, y| x.equal?(y) } ""\x04\bo:\x14Process::Status\x00"" ""#"" true +"); + } + + /// + /// A one-string command whose first word assigns a variable - an "=" ahead of any "/" - goes to the shell, as MRI's + /// rb_exec_fillarg sends it (CRuby's TestProcess#test_sh_env). + /// + public void Process_SpawnShellAssignment1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } + TestOutput(@" +require 'ruby4' +p IO.popen(""foofoo=barbar env"") { |f| f.readlines.grep(/\Afoofoo=/) } +p IO.popen("" A1=x B2=y env"") { |f| f.readlines.grep(/\A[AB][12]=/).sort } +p system(""ZZ=1 test 1 = 1"") +begin + system(""./no/such=thing"", exception: true) +rescue Errno::ENOENT => e + p e.message +end +p `echo a=b` +", @" +[""foofoo=barbar\n""] +[""A1=x\n"", ""B2=y\n""] +true +""No such file or directory - ./no/such=thing"" +""a=b\n"" "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index e0a5a376f..f5a6ebdd2 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9291,6 +9291,14 @@ def self.__spawn_command__(args, env) if (command.valid_encoding? ? command : command.b) =~ SPAWN_SHELL_META return __spawn_shell__(command) end + # so does an assignment before the command name - an "=" in the first word, ahead of + # any "/" (rb_exec_fillarg) + unless SPAWN_WINDOWS + first_word = command.b[/\A[ \t]*[^ \t]*/] + assign = first_word.index("=") + slash = first_word.index("/") + return __spawn_shell__(command) if assign && (slash.nil? || assign < slash) + end words = command.split(" ") raise Errno::ENOENT, command if words.empty? builtins = SPAWN_WINDOWS ? SPAWN_CMD_BUILTINS : SPAWN_SHELL_BUILTINS From 21e4ee594044040d63e1e43939031228195e8463 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:12:42 +0000 Subject: [PATCH 420/439] Add Process::UID/GID re_exchangeable? and from_name Process::UID.re_exchangeable? was undefined, and sid_available? said false on Linux. MRI answers both from what the platform has: setreuid or setresuid for re_exchangeable?, setresuid or _POSIX_SAVED_IDS for sid_available? - true on every Unix IronRuby runs on, false on Windows - and from_name looks a user or group name up ("can't find user for x"), taking an Integer as the id itself. The prelude's UID and GID modules now have all three, the same on both modules. The privilege-changing methods (change_privilege, grant_privilege, re_exchange, switch) are still missing. CRuby's TestProcess#test_uid_re_exchangeable_p and #test_gid_re_exchangeable_p pass now; ruby/spec's core/process uid and gid specs pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 28 +++++++++++++++++++++++++ Src/StdLib/ironruby/ruby4.rb | 18 ++++++++++++---- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 688e35df1..9d7478a49 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1060,6 +1060,7 @@ public Tests(Driver/*!*/ driver) { Process_ClockGetresHertz1, Process_StatusMarshal1, Process_SpawnShellAssignment1, + Process_UidGidReExchangeable1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 6439beeec..6cf538a55 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10584,6 +10584,34 @@ p e.message true ""No such file or directory - ./no/such=thing"" ""a=b\n"" +"); + } + + /// + /// Process::UID and ::GID answer re_exchangeable? and sid_available? for the platform (setreuid and setresuid are there + /// on Unix) and look a name up with from_name, as MRI's p_uid_exchangeable, p_uid_have_saved_id and p_uid_from_name do + /// (CRuby's TestProcess#test_uid_re_exchangeable_p and #test_gid_re_exchangeable_p). + /// + public void Process_UidGidReExchangeable1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } + TestOutput(@" +require 'ruby4' +p Process::UID.re_exchangeable?, Process::GID.re_exchangeable?, Process::UID.sid_available?, Process::GID.sid_available? +p Process::UID.from_name(""root""), Process::GID.from_name(""root""), Process::UID.from_name(0) +p((Process::UID.from_name(""nosuchuserx"") rescue $!), (Process::GID.from_name(""nosuchgrpx"") rescue $!), (Process::UID.from_name(:root) rescue $!)) +", @" +true +true +true +true +0 +0 +0 +# +# +# "); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index f5a6ebdd2..a992dbe4c 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -9676,8 +9676,13 @@ def issetugid; Process.__issetugid__; end module UID def rid; Process.uid; end def eid; Process.euid; end - def sid_available?; false; end - module_function :rid, :eid, :sid_available? + # whether the platform has setresuid (a saved id) and setreuid: every Unix IronRuby + # runs on, and not Windows, where MRI has neither + def sid_available?; ::File::ALT_SEPARATOR != "\\"; end + def re_exchangeable?; ::File::ALT_SEPARATOR != "\\"; end + # the id of a name, as OBJ2UID reads it: an Integer is the id itself + def from_name(name); Process.__user_id__(name); end + module_function :rid, :eid, :sid_available?, :re_exchangeable?, :from_name end end @@ -9685,8 +9690,13 @@ def sid_available?; false; end module GID def rid; Process.gid; end def eid; Process.egid; end - def sid_available?; false; end - module_function :rid, :eid, :sid_available? + # whether the platform has setresgid (a saved id) and setregid: every Unix IronRuby + # runs on, and not Windows, where MRI has neither + def sid_available?; ::File::ALT_SEPARATOR != "\\"; end + def re_exchangeable?; ::File::ALT_SEPARATOR != "\\"; end + # the id of a name, as OBJ2GID reads it: an Integer is the id itself + def from_name(name); Process.__group_id__(name); end + module_function :rid, :eid, :sid_available?, :re_exchangeable?, :from_name end end From 528a6d6efe5375a3f34b57f5658804778c5ef760 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:19:55 +0000 Subject: [PATCH 421/439] cruby-test: baseline after round twelve test_process and test_marshal re-swept after the round's fixes: 6,706 tests passing (from 6,694), one file without a summary (test_iseq), as before. test_process counts two more tests, the ones it runs only where Process::UID.sid_available? is true. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index 22d7ee821..5da2f2c7a 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with -failures, 1 without a summary (test_iseq); 10,369 tests counted, 6,694 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,371 tests counted, 6,706 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 8e4b7c57e..191eb88f5 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -90,7 +90,7 @@ test_pattern_matching 30 tests 0 failures 0 errors 0 sk test_pipe 12 tests 0 failures 2 errors 0 skips test_primitive 25 tests 0 failures 0 errors 0 skips test_proc 120 tests 2 failures 1 errors 0 skips -test_process 141 tests 19 failures 18 errors 1 skips +test_process 143 tests 18 failures 9 errors 1 skips test_ractor 19 tests 10 failures 0 errors 0 skips test_rand 41 tests 0 failures 0 errors 0 skips test_random_formatter 26 tests 0 failures 0 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 69 clean, 72 with failures, 1 without a summary -10369 tests, 2552057 assertions, 471 failures, 3134 errors, 70 skips; 6694 passing +10371 tests, 2552072 assertions, 470 failures, 3125 errors, 70 skips; 6706 passing From f89b4791bc7ee0f21480cb61009f2f317bf216bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:23:06 +0000 Subject: [PATCH 422/439] Method JIT: class variable reads and plain writes in the typed body `@@x` and `@@x = v` kept 44 methods out of the method JIT on their own (197 census rows name them). A read now goes through JitRuntime.ClassVariableRead and a write through ClassVariableWrite, starting from the module the generic body would start from (GetInnerMostModuleForClassVariableAccess on the compile-time scope, so singleton classes are passed over as CRuby does). Both use the interpreter's lookup, split in RubyModule into a no-raise form, and deopt before any effect where the generic body would raise or act differently: a variable not found, one overtaken by a superclass's, a write to a frozen class or dummy singleton, and anything once Ractors have started. define_method bodies, outlined loops, `@@x ||=` and `@@x op= v` stay refused. Switch: IR_JIT_CLASS_VARIABLES=0. Census: 57 methods up, none down. app-shapes: 3 more specialized. Clock (cvar-shapes.rb): a read 133.9 -> 108.0 ns. Util/jit-cvar-matrix.rb (new, 23 rows) and jit, jit-calls, jit-const, jit-objops, jit-defined, hot-shapes print CRuby 4.0's output in all five modes and with the switch off; ruby/spec class variable specs pass; IronRuby.Tests passes. CRuby 4.0.10 segfaults reading a class variable after remove_class_variable, so the matrix has no row for that read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Builtins/RubyModule.cs | 27 ++++-- Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs | 2 +- Src/Ruby/Runtime/Jit/JitCompiler.cs | 65 +++++++++++++ Src/Ruby/Runtime/Jit/JitRuntime.cs | 32 +++++++ Util/bench/cvar-shapes.rb | 34 +++++++ Util/jit-cvar-matrix.rb | 116 +++++++++++++++++++++++ Util/perf/LEDGER.md | 26 +++++ 7 files changed, 293 insertions(+), 9 deletions(-) create mode 100644 Util/bench/cvar-shapes.rb create mode 100644 Util/jit-cvar-matrix.rb diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 90f27a14b..4c31c7f3c 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -3867,9 +3867,24 @@ public bool RemoveClassVariable(string/*!*/ name) { } public RubyModule TryResolveClassVariable(string/*!*/ name, out object value) { + RubyModule front; + RubyModule target = TryResolveClassVariableNoRaise(name, out value, out front); + if (front != target) { + throw new RuntimeError(String.Format("class variable {0} of {1} is overtaken by {2}", + name, Context.GetModuleDisplayName(front), Context.GetModuleDisplayName(target))); + } + return target; + } + + /// + /// TryResolveClassVariable without its "overtaken" error: is the nearest module defining the + /// variable, which differs from the result when that error is due (the method JIT's ClassVariableRead deopts then). + /// + internal RubyModule TryResolveClassVariableNoRaise(string/*!*/ name, out object value, out RubyModule front) { Assert.NotNull(name); - RubyModule front = null, target = null; + RubyModule target = null; + RubyModule nearest = null; object targetValue = null; // MRI's CVAR_LOOKUP: the variable is the one furthest up the ancestors; one defined @@ -3878,8 +3893,8 @@ public RubyModule TryResolveClassVariable(string/*!*/ name, out object value) { ForEachAncestor(delegate(RubyModule/*!*/ module) { object moduleValue; if (module.TryGetClassVariable(name, out moduleValue)) { - if (front == null) { - front = module; + if (nearest == null) { + nearest = module; } target = module; targetValue = moduleValue; @@ -3888,11 +3903,7 @@ public RubyModule TryResolveClassVariable(string/*!*/ name, out object value) { }); } - if (front != target) { - throw new RuntimeError(String.Format("class variable {0} of {1} is overtaken by {2}", - name, Context.GetModuleDisplayName(front), Context.GetModuleDisplayName(target))); - } - + front = nearest; value = targetValue; return target; } diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index 463f884c9..4814b0fc1 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs @@ -308,7 +308,7 @@ private MSA.Expression TrySunkIVarRead(string/*!*/ name, out JT type) { // deopt), a type or identity test (a class that resolves the method to anything but the library's deopts) and // `x.to_i' of an Integer, nil or a plain decimal String: no Ruby code, no instance variable, nothing but a deopt "IndexInt", "IndexLong", "IndexObj", "IndexIntChecked", "IndexLongChecked", "IndexObjChecked", "HashKeyInt", - "IsKindOf", "ModuleCaseEquals", "NewArrayOfCapacity", "ArrayAppend", "SplatAppend", "RangeSlice", "DestructuredArray", "ElementOrNil", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", + "IsKindOf", "ModuleCaseEquals", "ClassVariableRead", "NewArrayOfCapacity", "ArrayAppend", "SplatAppend", "RangeSlice", "DestructuredArray", "ElementOrNil", "IsIdentical", "IsNil", "CollectionEqualsNil", "ToIntegerObject", "StringEmpty", "NotObject", "IsEmpty", "IsEmptyOrString", }; // Integer#abs of an Int32 (widened, so it cannot overflow) and Float#abs (JitCompiler.EmitCall) diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index 35c80d8d3..da92fda36 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1362,6 +1362,9 @@ protected override MSA.Expression VisitNew(MSA.NewExpression node) { var isDefined = node as IsDefinedExpression; if (isDefined != null && IsDefinedInstanceVariable(isDefined)) { return EmitDefinedInstanceVariable(isDefined, out type); } + var cvar = node as ClassVariable; + if (cvar != null) { return EmitClassVariableRead(cvar, out type); } + var ivar = node as InstanceVariable; if (ivar != null) { if (_loop != null && _ivarProfile == null) { throw Bail("instance variable in a loop entered without self"); } @@ -1554,6 +1557,55 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return IronRuby.Compiler.Methods.MakeArrayOpCall(values); } + // IR_JIT_CLASS_VARIABLES=0 turns EmitClassVariableRead and EmitClassVariableWrite off + internal static readonly bool ClassVariables = Environment.GetEnvironmentVariable("IR_JIT_CLASS_VARIABLES") != "0"; + + /// + /// The module `@@x' starts from: the method's innermost lexical module, singleton classes, refinements and + /// instance_eval'd code passed over, as the generic body's scope finds it (RubyScope.GetInnerMostModuleForClassVariableAccess) + /// from the scope the method was defined in. Bails at the top level (the generic body raises "class variable access from + /// toplevel") and where the method's defining scope is not known. + /// + private RubyModule/*!*/ ClassVariableOwner() { + if (!ClassVariables) { throw Bail("class variable (IR_JIT_CLASS_VARIABLES=0)"); } + if (_loop != null) { throw Bail("class variable in an outlined loop"); } + // a define_method body finds @@x from its block's scope, not from a method definition's + if (_ast is JitBlockMethod.BlockMethodDefinition) { throw Bail("class variable in a define_method body"); } + var owner = (_ast != null && _constantScope != null) ? _constantScope.GetInnerMostModuleForClassVariableAccess() : null; + if (owner == null) { throw Bail("class variable with no module to start from"); } + return owner; + } + + /// + /// `@@x': read where the generic body reads it (JitRuntime.ClassVariableRead), from the module ClassVariableOwner fixes when + /// the body is compiled - a body belongs to one definition of the method, in one scope. The variable's place is found on + /// every read, under the class hierarchy lock, as the generic body's; one undefined or overtaken deopts. + /// + private MSA.Expression/*!*/ EmitClassVariableRead(ClassVariable/*!*/ node, out JT type) { + var owner = ClassVariableOwner(); + _canDeopt = true; + type = JT.Obj; + return Ast.Call(JitRuntime.M("ClassVariableRead"), Ast.Constant(owner, typeof(RubyModule)), Ast.Constant(node.Name)); + } + + /// + /// `@@x = v': stored where the generic body stores it (JitRuntime.ClassVariableWrite), after v. The store may deopt (overtaken, + /// frozen) before it is made, and is an effect on something that is not self. + /// + private MSA.Expression/*!*/ EmitClassVariableWrite(ClassVariable/*!*/ node, RExpr/*!*/ right, out JT type) { + var owner = ClassVariableOwner(); + JT vt; + var value = Emit(right, out vt); + if (vt == JT.None || vt == JT.Never) { throw Bail("class variable assignment of a value that jumps away"); } + var temp = Ast.Variable(ClrType(vt), "#cvar"); + _canDeopt = true; + var store = Ast.Call(JitRuntime.M("ClassVariableWrite"), Ast.Constant(owner, typeof(RubyModule)), Ast.Constant(node.Name), BoxForStore(temp, vt)); + _pure = false; + _effectNotOnSelf = true; + type = vt; + return Ast.Block(ClrType(vt), new[] { temp }, Ast.Assign(temp, value), store, temp); + } + // IR_JIT_SYMBOL_EQ=0 turns IsSymbolComparison off internal static readonly bool SymbolComparisons = Environment.GetEnvironmentVariable("IR_JIT_SYMBOL_EQ") != "0"; @@ -1999,6 +2051,12 @@ internal static bool IsPlainLiteralKeyed(HashConstructor/*!*/ node) { return EmitGlobalWrite(gvarTarget, node.Right, out type); } + var cvarTarget = node.Left as ClassVariable; + if (cvarTarget != null) { + if (op != null) { throw Bail("class variable op-assign"); } + return EmitClassVariableWrite(cvarTarget, node.Right, out type); + } + var attribute = node.Left as AttributeAccess; if (attribute != null) { return EmitAttributeWrite(attribute, op, node.Right, node, out type); } @@ -4418,6 +4476,8 @@ private bool Walk(RExpr/*!*/ node) { return (v is int || v is long || v is double || v is bool || v == null) || No(node); } if (node is SymbolLiteral) { return true; } + // `@@x' (JitCompiler.EmitClassVariableRead) + if (node is ClassVariable) { return JitCompiler.ClassVariables || No(node); } // `defined?(@x)' (JitCompiler.EmitDefinedInstanceVariable) var isDefined = node as IsDefinedExpression; if (isDefined != null) { return JitCompiler.IsDefinedInstanceVariable(isDefined) || No(node); } @@ -4674,6 +4734,11 @@ private bool WalkAssignment(SimpleAssignmentExpression/*!*/ assign) { if (op != null || _inKeywordDefault) { return No(node); } return Walk(assign.Right); } + // `@@x = v' (JitCompiler.EmitClassVariableWrite) + if (assign.Left is ClassVariable) { + if (op != null || _inKeywordDefault || !JitCompiler.ClassVariables) { return No(node); } + return Walk(assign.Right); + } var target = assign.Left as LocalVariable; if (target == null || target.DefinitionLexicalDepth != _scopeDepth || _inKeywordDefault) { return No(node); } _otherUses.Add(target.Name); diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 4860571ea..dca74d644 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1251,6 +1251,38 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* // An instance variable used as a numeric operand of an outlined loop (JitCompiler.NumericIVar): // unboxed while it holds the type it held when the loop was compiled, a deopt once it does not. + /// + /// `@@x' (JitCompiler.EmitClassVariableRead): the variable as RubyOps.GetClassVariable finds it from , + /// the method's innermost lexical module (its singleton classes passed over). One that is not defined, one "overtaken" + /// (defined below the module that has it, which CRuby raises for) and one read while Ractors run deopt: the generic body + /// raises the NameError or RuntimeError, or checks the Ractor. + /// + public static object ClassVariableRead(RubyModule/*!*/ owner, string/*!*/ name) { + if (owner.Context.RactorsStarted) { throw Deopt(); } + object value; + RubyModule front; + RubyModule target = owner.TryResolveClassVariableNoRaise(name, out value, out front); + if (target == null || front != target) { throw Deopt(); } + return value; + } + + /// + /// `@@x = v' (JitCompiler.EmitClassVariableWrite): stored where RubyOps.SetClassVariable stores it - in the module that + /// already has the variable, or in . An overtaken variable, a frozen module and a running Ractor + /// deopt before anything is stored. + /// + public static object ClassVariableWrite(RubyModule/*!*/ owner, string/*!*/ name, object value) { + if (owner.Context.RactorsStarted) { throw Deopt(); } + object oldValue; + RubyModule front; + RubyModule target = owner.TryResolveClassVariableNoRaise(name, out oldValue, out front); + if (front != target) { throw Deopt(); } + var into = target ?? owner; + if (into.IsFrozen || into.IsDummySingletonClass) { throw Deopt(); } + into.SetClassVariable(name, value); + return value; + } + /// The Array an Array literal with a splat is built in (JitCompiler.EmitSplattingArrayLiteral). public static RubyArray/*!*/ NewArrayOfCapacity(int capacity) { return new RubyArray(capacity); diff --git a/Util/bench/cvar-shapes.rb b/Util/bench/cvar-shapes.rb new file mode 100644 index 000000000..f714e1cfd --- /dev/null +++ b/Util/bench/cvar-shapes.rb @@ -0,0 +1,34 @@ +# Class variables in hot methods (JitCompiler.EmitClassVariableRead/Write): a read, a read in a subclass's method that +# finds it on the superclass, a counter written back. Every line prints the sum of its results next to its time; it +# must be CRuby's. +# ruby Util/perf/ab.rb Util/bench/cvar-shapes.rb cruby=ruby "off=env IR_CONFIG=Release IR_JIT_CLASS_VARIABLES=0 ./ir.sh" "new=env IR_CONFIG=Release ./ir.sh" +$stdout.sync = true +class CVS + @@scale = 3 + @@count = 0 + def read(x) = x * @@scale + def bump(x) + @@count = x + x + end +end +class CVSSub < CVS + def sub_read(x) = x + @@scale +end +def cpu; Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID); end +def t(name, n) + return puts(name) if ARGV == ['--list'] + return unless ARGV.empty? || ARGV.include?(name) + best = 1e9; sum = nil + 7.times do + t0 = cpu; sum = yield n; d = cpu - t0 + best = d if d < best + end + printf "%-16s %9.1f ns %d\n", name, best * 1e9 / n, sum +end +o = CVS.new +s = CVSSub.new +N = (ENV["N"] || 1_000_000).to_i +t("read", N) { |n| i = 0; r = 0; while i < n; r += o.read(i & 7); i += 1; end; r } +t("sub_read", N) { |n| i = 0; r = 0; while i < n; r += s.sub_read(i & 7); i += 1; end; r } +t("write", N) { |n| i = 0; r = 0; while i < n; r += o.bump(i & 7); i += 1; end; r } diff --git a/Util/jit-cvar-matrix.rb b/Util/jit-cvar-matrix.rb new file mode 100644 index 000000000..6bf1182c6 --- /dev/null +++ b/Util/jit-cvar-matrix.rb @@ -0,0 +1,116 @@ +# Differential matrix for `@@x' and `@@x = v' in methods the method JIT compiles (JitCompiler.EmitClassVariableRead and +# EmitClassVariableWrite, JitRuntime.ClassVariableRead and ClassVariableWrite). Run under CRuby and under ./ir.sh in every +# mode, and diff: +# +# ruby Util/jit-cvar-matrix.rb > /tmp/mri.txt +# ./ir.sh Util/jit-cvar-matrix.rb > /tmp/jit.txt +# ./ir.sh -X:NoJIT -X:NoOSR Util/jit-cvar-matrix.rb > /tmp/nojit.txt +# diff /tmp/mri.txt /tmp/jit.txt && diff /tmp/mri.txt /tmp/nojit.txt +# +# Which ones are specialized: +# IR_JIT_VERBOSE=1 ./ir.sh Util/jit-cvar-matrix.rb 2>&1 >/dev/null | grep -a 'jit\]' | grep CV +# The traps: where the lookup starts (the lexical module, singleton classes passed over: `def self.x', `class << self'), +# a variable inherited or from an included module, one not defined (NameError), one overtaken after the body is hot +# (RuntimeError), a frozen class (FrozenError), class_variable_set and remove_class_variable after hot, toplevel access, +# a define_method body and a module_eval'd String, `@@x ||=' and `@@x +='. + +def t(label) + print label.ljust(52), ' => ' + begin + v = yield + puts v.inspect + rescue Exception => e + puts "#{e.class}: #{e.message[0, 70]}" + end +end + +HOT = 300 + +def warm(n = HOT) + i = 0 + r = nil + while i < n + r = yield i + i += 1 + end + r +end + +module CVMixin + @@mixed = :from_module + def mixed = @@mixed +end + +class CVBase + include CVMixin + @@count = 0 + @@name = "base" + def count = @@count + def bump(x) = @@count = @@count + x + def name = @@name + def set_name(v) = @@name = v + def missing = @@missing + def self.class_count = @@count + class << self + def meta_name = @@name + end + define_method(:dm_count) { @@count } + def memo = @@memo ||= :memo + def add(x) = @@count += x +end +class CVSub < CVBase + def sub_name = @@name +end +CVBase.module_eval "def evaled = @@name" + +o = CVBase.new +s = CVSub.new +t("count, hot") { warm { o.count } } +t("bump, hot") { warm { |i| o.bump(1) }; [o.count, CVBase.class_variable_get(:@@count)] } +t("name and set_name") { warm { |i| o.set_name("n#{i}") }; [o.name, s.sub_name, CVBase.meta_name] } +t("inherited") { warm { s.sub_name }; o.set_name("again"); s.sub_name } +t("from an included module") { warm { o.mixed } } +t("def self.x") { warm { CVBase.class_count } } +t("class << self") { warm { CVBase.meta_name } } +t("define_method") { warm { o.dm_count }; o.dm_count } +t("module_eval String") { warm { o.evaled } } +t("missing") { o.missing } +t("missing, hot") { warm { (o.missing rescue $!.class) } } +t("defined later") { CVBase.class_variable_set(:@@missing, 7); o.missing } +# (Read after remove_class_variable, CRuby 4.0.10 crashes - its class variable cache keeps the removed entry - so there is +# no output to compare with; IronRuby raises NameError in every mode.) +t("removed") { CVBase.send(:remove_class_variable, :@@missing); CVBase.class_variable_defined?(:@@missing) } +t("class_variable_set after hot") { warm { o.count }; CVBase.class_variable_set(:@@count, 42); o.count } +t("||=") { [o.memo, o.memo] } +t("+=") { warm { o.add(1) }; o.count } + +# overtaken: a variable defined in a subclass, then in its superclass +class CVOver + def v = @@v + def set_v(x) = @@v = x +end +class CVOverSub < CVOver + @@v = :sub + def sub_v = @@v +end +ov = CVOverSub.new +t("before it is overtaken") { warm { ov.sub_v } } +CVOver.class_variable_set(:@@v, :base) +t("overtaken, read") { ov.sub_v } +t("overtaken, write") { ov.set_v(1); ov.sub_v } + +# a frozen class +class CVFrozen + @@x = 1 + def x = @@x + def set_x(v) = @@x = v +end +f = CVFrozen.new +t("frozen, before") { warm { |i| f.set_x(i) }; f.x } +CVFrozen.freeze +t("frozen, write") { f.set_x(5) } +t("frozen, read") { f.x } + +# at the top level +def toplevel_cvar = @@top +t("toplevel") { toplevel_cvar } diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 6c86a7fd8..61a851c5f 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,32 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitcvar (2026-11-29, census and timed, not gated) - `@@x` and `@@x = v` in the method JIT's typed body** (the + census's ClassVariable: 44 methods refused by it alone, 197 rows naming it; switch `IR_JIT_CLASS_VARIABLES`). Built + on perf/jitsymeq ce6bb18. + - **What.** A read goes through `JitRuntime.ClassVariableRead`, a write through `ClassVariableWrite`, from the + module the generic body would start from (`RubyScope.GetInnerMostModuleForClassVariableAccess` on the compile-time + scope: singleton classes passed over, as `def self.x` and `class << self` need). Both use the lookup the + interpreter uses (`RubyModule.TryResolveClassVariable`, split so the JIT gets a no-raise form) and deopt, before any + effect, where the generic body would raise or behave differently: a variable not found (NameError), one overtaken + by a superclass's (RuntimeError), a write to a frozen class or a dummy singleton, and anything once Ractors have + started (their isolation checks stay in the generic path). A write is an effect not on self. Not taken: a + define_method body (its owner is the block's), a loop outlined for OSR, `@@x ||=` and `@@x op= v` (still refused). + - **Census** (Src/StdLib, Util/bench, AWFY, against ce6bb18): 57 methods up (56 never -> maybe, 1 never -> + compiles), none down. The maybes are the census not having a module to start from (52) - at run time they have + one - and calls after the variable. + - **app-shapes, traced:** specialized 128 -> 131 (Gem::Specification.default_value), rejected 583 -> 582. + - **Clock** (ab.rb -r 9, `Util/bench/cvar-shapes.rb`, ns, off -> new; CRuby about 44): read 133.9 -> 108.0 (0.81), + a subclass's read 124.6 -> 115.9 and a write 148.2 -> 139.9 (both within the spread). The lookup is the + interpreter's dictionary walk on every access; a per-site cache keyed on a class-variable version is the next step. + - **Checks.** `Util/jit-cvar-matrix.rb` (new, 23 rows): own class, inherited, from an included module, `def + self.x` and `class << self`, toplevel, frozen class, class_variable_set after hot, not defined then defined, + overtaken after hot, define_method, a module_eval'd String, `||=` and `+=`. Read after remove_class_variable has no + row: CRuby 4.0.10 segfaults there (its class variable cache keeps the removed entry); IronRuby raises NameError + in every mode. It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, IR_LIGHT_FRAMES=0 and + the switch off. jit, jit-calls, jit-const, jit-objops, jit-defined and hot-shapes in the same five modes: CRuby's output on both builds (35 runs with jit-cvar). ruby/spec language/class_variable and core/module class_variable_get, _set, + _defined, class_variables, remove_class_variable: no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. + - **perf/jitsymeq (2026-11-29, census and timed, not gated) - a comparison with a Symbol literal in the method JIT's typed body** (the census's SymbolLiteral: 21 methods refused by it alone; switch `IR_JIT_SYMBOL_EQ`). Built on perf/jitsplatlit e34abb3. From 677be652108f3b84ee15d09ee30523e67ce56a32 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:27:12 +0000 Subject: [PATCH 423/439] Call a module's own const_missing from Module#const_get klass.const_get("Foo::Bar") with a const_missing on klass that answers klass called it for Foo and then raised NameError for Bar, and c2.const_get("Bar", false) never reached the const_missing c2 inherits from c1. Module#const_get called Module#const_missing's own body for a segment it looked for without the inherited lookup (a later segment of a path, or inherit = false) instead of sending const_missing to the module, as MRI's rb_const_get_0 does with rb_funcall for every segment. It now sends it through RubyModule.ConstantMissing, which the first segment's lookup already used (and which is public for that). CRuby's TestModule#test_nested_get_const_missing and #test_const_get_evaled pass now. ruby/spec's core/module const_get, const_missing and const_defined specs and language/constants_spec pass on both builds; the delegate, error-message, jit-const, lexical-light and loop-const matrices are unchanged in every mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 29 +++++++++++++++++++++++++ Src/Libraries/Builtins/ModuleOps.cs | 6 +++-- Src/Ruby/Builtins/RubyModule.cs | 3 ++- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9d7478a49..9447fb74b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1061,6 +1061,7 @@ public Tests(Driver/*!*/ driver) { Process_StatusMarshal1, Process_SpawnShellAssignment1, Process_UidGidReExchangeable1, + Module_ConstGetPathConstMissing1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 6cf538a55..6722cc4ab 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10612,6 +10612,35 @@ public void Process_UidGidReExchangeable1() { # # # +"); + } + + /// + /// Module#const_get calls the module's own const_missing for every segment of a path it cannot find, inherited or not, + /// as MRI's rb_const_get_0 does with rb_funcall (CRuby's TestModule#test_nested_get_const_missing and + /// #test_const_get_evaled). + /// + public void Module_ConstGetPathConstMissing1() { + TestOutput(@" +classes = [] +klass = Class.new { + define_singleton_method(:const_missing) { |name| classes << name; klass } +} +p klass.const_get(""Foo::Bar::Baz"") == klass, classes +c1 = Class.new +c2 = Class.new(c1) +c1.instance_eval { def const_missing(x) = x } +p c2.const_get(""Bar""), c2.const_get(""Bar"", false), c2.const_get(:Bar, false) +p c2.const_get(""Bar11"", false) +p((Object.const_get(""Foo::Bar"") rescue $!)) +", @" +true +[:Foo, :Bar, :Baz] +:Bar +:Bar +:Bar +:Bar11 +# "); } } diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 1dcd0d00b..1f57f1720 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -1393,13 +1393,15 @@ public static object GetConstantValue(ConversionStorage/*!*/ stri // MRI searches Object for the first segment only (rb_const_get vs rb_const_get_from). bool lookupObject = inherit && !path.IsTopLevel; + // a segment that is not there goes to the module's const_missing, which a program may have + // defined (rb_const_get_0 calls it with rb_funcall), for every segment of a path object value = null; for (int i = 0; i < path.Count; i++) { owner = path.Enter(i, owner, value); string name = path[i]; if (IsHiddenConstant(owner, name, inherit)) { - value = ConstantMissing(owner, name); + value = owner.ConstantMissing(name); } else if (inherit && (i == 0 || IsVisibleFromScope(owner, name))) { value = RubyUtils.GetConstant(scope.GlobalScope, owner, name, lookupObject); } else if (!inherit && owner.TryGetConstant(scope.GlobalScope, name, out value)) { @@ -1407,7 +1409,7 @@ public static object GetConstantValue(ConversionStorage/*!*/ stri context.ReportConstantDeprecation(owner, name); } } else { - value = ConstantMissing(owner, name); + value = owner.ConstantMissing(name); } lookupObject = false; } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index b03397f92..f0120f16a 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -401,7 +401,8 @@ internal ConstantLocation(string/*!*/ sourcePath, int sourceLine) { private CallSite> _methodRemovedCallbackSite; private CallSite> _methodUndefinedCallbackSite; - internal object ConstantMissing(string/*!*/ name) { + /// The module's const_missing, as a constant read that finds nothing calls it. + public object ConstantMissing(string/*!*/ name) { // A light frame checks the stack at its entry only if it has a call site (MethodDefinition.LightFrame.MakesCalls), // and a constant read is none: `def self.const_missing(n) = Zork' recurses through here alone, which has to be a // SystemStackError, not the end of the process. From a583ae42d47cec837c7db370e5c04aee08ea5f01 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:31:44 +0000 Subject: [PATCH 424/439] On Linux, File.open of a missing path asks faccessat(2) before the CLR's open A rescued File.open("/nonexistent/zz") cost 56 us against CRuby's 3.4: the FileStream threw DirectoryNotFoundException, the CLR's frames threw it again, and only then was the Errno thrown. For a read-only open on the operating system's own file system, faccessat(AT_FDCWD, full path, F_OK, AT_EACCESS) resolves the path as open(2) does with the effective ids; ENOENT or ENOTDIR from it is what the open would say, and the same Errno, with the same message, is thrown at once. Anything else (the file is there, EACCES, ELOOP, ENAMETOOLONG) goes on to the open as before. IR_NATIVE_MISSING=0 restores the old code; other platforms keep it. A missing file 55.9 -> 37.3 us, ENOTDIR 55.8 -> 38.3; an open that succeeds and File.read are level. What is left is that every Errno C# throws is replaced by the prelude's SystemCallError.new, which takes the whole trace at once. Util/file-missing-matrix.rb (new) is the same with the switch on and off and on the base build; EACCES under an unsearchable directory, run as nobody, is unchanged and matches CRuby. ruby/spec file, io, dir, Kernel#open and pathname are the same on both builds; IronRuby.Tests on Debug passed; the census is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf79d6kw7Ccmpbk4Muq --- Src/Ruby/Builtins/RubyFile.cs | 55 +++++++++++++++++++++++++++++ Src/Ruby/Hosting/RubyConsoleHost.cs | 2 +- Util/file-missing-matrix.rb | 33 +++++++++++++++++ Util/perf/LEDGER.md | 28 +++++++++++++-- 4 files changed, 115 insertions(+), 3 deletions(-) create mode 100644 Util/file-missing-matrix.rb diff --git a/Src/Ruby/Builtins/RubyFile.cs b/Src/Ruby/Builtins/RubyFile.cs index bb0de0c48..90426c441 100644 --- a/Src/Ruby/Builtins/RubyFile.cs +++ b/Src/Ruby/Builtins/RubyFile.cs @@ -46,6 +46,58 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO private const int ENXIO = 6; private const int HResultInvalidName = unchecked((int)0x8007007B); // HRESULT of ERROR_INVALID_NAME + // IR_NATIVE_MISSING=0: a missing file is found by the CLR's open, as before perf/enoent. + private static readonly bool NativeMissingCheck = Environment.GetEnvironmentVariable("IR_NATIVE_MISSING") != "0" && + System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux); + + private const int AT_FDCWD = -100, AT_EACCESS = 0x200, F_OK = 0; + private static readonly int ENOENT = RubyErrno.GetNumber("ENOENT"), ENOTDIR = RubyErrno.GetNumber("ENOTDIR"); + + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "faccessat", SetLastError = true)] + private static extern int sys_faccessat(int dirfd, byte[] path, int mode, int flags); + + /// + /// Linux: the open of a file that is not there - a rescued `File.open(path) rescue ...', `File.exist?' written as an + /// open - cost two CLR exceptions (the FileStream's DirectoryNotFoundException or FileNotFoundException, thrown again by + /// the CLR's own frames) before the Errno, 56 us against CRuby's 3.4. faccessat(2) with AT_EACCESS resolves the path as + /// open(2) does, with the effective ids: when it says ENOENT or ENOTDIR so would the open (O_RDONLY, no O_CREAT), and + /// the Errno the CLR's exception would have become is thrown at once, with the same message. Anything else - the file is + /// there, EACCES, ELOOP, ENAMETOOLONG - goes on to the open, which reports it as before. Only for the operating system's + /// own file system (not a host's PlatformAdaptationLayer), and the path is made absolute as the FileStream makes it. + /// + private static void ThrowIfMissing(RubyContext/*!*/ context, string/*!*/ path) { + if (!NativeMissingCheck) { + return; + } + var platform = context.DomainManager.Platform; + var type = platform.GetType(); + if (type != typeof(Microsoft.Scripting.PlatformAdaptationLayer) && type != typeof(IronRuby.Hosting.RubyConsoleHost.RubyPlatformAdaptationLayer)) { + return; + } + string full; + try { + full = System.IO.Path.GetFullPath(path); + } catch (ArgumentException) { + return; + } + var bytes = System.Text.Encoding.UTF8.GetBytes(full); + if (Array.IndexOf(bytes, (byte)0) >= 0) { + return; + } + var cpath = new byte[bytes.Length + 1]; + Array.Copy(bytes, cpath, bytes.Length); + if (sys_faccessat(AT_FDCWD, cpath, F_OK, AT_EACCESS) == 0) { + return; + } + int errno = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); + if (errno == ENOENT) { + throw RubyExceptionData.Unkept(RubyExceptions.CreateENOENT(String.Format("No such file or directory - {0}", path))); + } + if (errno == ENOTDIR) { + throw RubyExceptionData.Unkept(new DirectoryNotFoundException(String.Format("Not a directory - {0}", path))); + } + } + public static Stream/*!*/ OpenFileStream(RubyContext/*!*/ context, string/*!*/ path, IOMode mode) { ContractUtils.RequiresNotNull(path, "path"); FileAccess access = mode.ToFileAccess(); @@ -81,6 +133,9 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO if (path == "NUL") { stream = Stream.Null; } else { + if (fileMode == FileMode.Open) { + ThrowIfMissing(context, path); + } try { stream = context.DomainManager.Platform.OpenInputFileStream(path, fileMode, access, FileShare.ReadWrite); } catch (FileNotFoundException) { diff --git a/Src/Ruby/Hosting/RubyConsoleHost.cs b/Src/Ruby/Hosting/RubyConsoleHost.cs index 421f9153a..dfbb65b0c 100644 --- a/Src/Ruby/Hosting/RubyConsoleHost.cs +++ b/Src/Ruby/Hosting/RubyConsoleHost.cs @@ -69,7 +69,7 @@ public override PlatformAdaptationLayer PlatformAdaptationLayer { private static readonly PlatformAdaptationLayer/*!*/ SharedPlatform = new RubyPlatformAdaptationLayer(); - private sealed class RubyPlatformAdaptationLayer : PlatformAdaptationLayer { + internal sealed class RubyPlatformAdaptationLayer : PlatformAdaptationLayer { public override Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) { return base.OpenInputFileStream(path, mode, access, share | FileShare.ReadWrite | FileShare.Delete, bufferSize); } diff --git a/Util/file-missing-matrix.rb b/Util/file-missing-matrix.rb new file mode 100644 index 000000000..f176a4ee8 --- /dev/null +++ b/Util/file-missing-matrix.rb @@ -0,0 +1,33 @@ +# File.open of paths that are not there, not directories, and there (perf/enoent: on Linux a faccessat(2) finds ENOENT and +# ENOTDIR before the CLR's open does, and anything else goes on to that open). The output must be the same with +# IR_NATIVE_MISSING=0 and on the base build. CRuby's messages differ from IronRuby's by "@ rb_sysopen", which is older. +# +# ./ir.sh Util/file-missing-matrix.rb; IR_NATIVE_MISSING=0 ./ir.sh Util/file-missing-matrix.rb +P = __FILE__ +paths = ["/nonexistent/zz", "/tmp/zz_missing_file", P + "/x", "", "zz_rel_missing", "/tmp", "/proc/self/zz", "/tmp/aé_missing", "/dev/null", P] +paths.each do |path| + begin + f = File.open(path); p [path.sub(P, "P"), :ok, f.class]; f.close + rescue SystemCallError, IOError => e + p [path.sub(P, "P"), e.class, e.message.sub(P, "P"), e.errno] + end +end +p((File.read("/nonexistent") rescue $!.class), (File.new("/nope/x", "r") rescue $!.class), (IO.read("/nope") rescue $!.class)) +p((File.open("/tmp/zz_w_missing_#{$$}", "w") { 1 }), File.exist?("/tmp/zz_w_missing_#{$$}")) +File.delete("/tmp/zz_w_missing_#{$$}") +# relative paths after a chdir, a dangling symlink, a symlink loop, a name too long +require "tmpdir" +Dir.mktmpdir do |d| + Dir.chdir(d) do + File.write("here", "x") + File.symlink("gone", "dangling") + File.symlink("loop", "loop") + ["here", "nothere", "here/x", "dangling", "loop", "a" * 300, "./sub/../here"].each do |path| + begin + File.open(path) { |f| p [path[0, 20], :ok, f.read] } + rescue SystemCallError => e + p [path[0, 20], e.class, e.message.sub(d, "D")[0, 60]] + end + end + end +end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index cad039235..e4c511b7a 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -1370,8 +1370,10 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has coercion are now 4.7-5.5 us. perf/unkept2 (2026-11-29, see Landed) did `1 / 0` and `1 % 0`, `EOFError`, a frozen Array or Hash and `Integer#chr`'s RangeError (5.0-7.0 us). perf/unkept3 (see Landed) made the keepers clear the mark and marked every other `throw RubyExceptions.Create...`/`Make...` (1,367 sites), and `read_nonblock` with nothing to read 43.6 -> - 10.1 us (CRuby 2.3). Left: `File.open` of a missing file (56 us, CRuby 3.4): the CLR throws DirectoryNotFoundException twice - before the ENOENT; skipping that needs a native stat to tell a missing file from an unsearchable directory (EACCES). + 10.1 us (CRuby 2.3). perf/enoent (see Landed): on Linux `File.open` of a missing file no longer goes through the CLR's two + exceptions, 56 -> 37 us (CRuby 3.4). Left, for every Errno C# throws: `RubyExceptionData.HandleException` replaces it with + an instance the prelude's `SystemCallError.new` makes, and takes the whole trace at once before that Ruby code runs, so + no mark defers it; a deferred capture there (the compiled frames' lines now, the walk on exposure) is the next step. 23. **A method made by `define_method` is called at 2.3 times CRuby's time** (64 against 28 ns; a `def` of the same body 31; YJIT 2-5 ns): the method JIT takes no block as a method body. Rails-style code defines most of its small methods this way. @@ -2051,6 +2053,28 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/enoent (round thirty-seven, 2026-11-29) - on Linux, `File.open` of a path that is not there asks faccessat(2) before + the CLR's open (gap 22)** - time, not gated. A rescued `File.open("/nonexistent/zz")` cost 56 us against CRuby's 3.4: the + FileStream threw DirectoryNotFoundException (or FileNotFoundException), the CLR's own frames threw it again, and + `RubyFile.OpenFileStream` then threw the Errno. Now, for a read-only open (FileMode.Open) on the operating system's file + system (the PlatformAdaptationLayer itself or the console host's, not a host's own), `faccessat(AT_FDCWD, full path, F_OK, + AT_EACCESS)` resolves the path as open(2) would with the effective ids: ENOENT or ENOTDIR from it is what the open would + say, and the Errno the CLR's exception would have become is thrown at once with the same message; anything else (there, + EACCES, ELOOP, ENAMETOOLONG) goes on to the open as before. The path is made absolute with `Path.GetFullPath`, as the + FileStream makes it. `IR_NATIVE_MISSING=0` is the old code; other platforms keep it. Per call (`ab.rb -r 6`, ns, off/on): + a missing file 55,944 / 37,274, one under /tmp 53,435 / 36,996, a path through a regular file (ENOTDIR) 55,783 / 38,316; + an open that succeeds 4,721 / 4,705, `File.read` 14,595 / 13,578 (both overlapping). What is left of the 37 us is gap + 22's: an Errno C# throws is replaced by the prelude's `SystemCallError.new` in `HandleException`, which takes the trace + at once. Census: no method changed. Checked: `Util/file-missing-matrix.rb` (new: absolute, relative, empty, under /proc, + non-ASCII, a directory, /dev/null, a file, ENOTDIR, `File.read`/`File.new`/`IO.read`, a write that creates, and in a + temporary directory a dangling symlink, a symlink loop, a name too long, `./sub/../here`) the same with the switch on + and off and on the base build; as `nobody`, a file under an unsearchable directory and one in it unreadable: EACCES, as + CRuby, either way. Three differences from CRuby older than this, the same either way: CRuby's messages say + "@ rb_sysopen", its backtrace of `File.open` has an `IO.open` frame, and `File.open("./sub/../here")` with no `sub` is + ENOENT in CRuby (the kernel resolves `..` after `sub`) and opens in IronRuby (.NET normalizes the path first). + ruby/spec core/file, core/io, Kernel#open, core/dir and library/pathname on both builds: 3011 examples, the same one error. + IronRuby.Tests in full on Debug: PASSED. + - **perf/unkept3 (round thirty-seven, 2026-11-29) - every library error made and thrown at once defers its catch-site walk; the places that keep an exception clear the mark; `read_nonblock` raises once (gap 22)** - time, not gated. The third round of perf/unkept. (1) `RubyExceptionData.MarkKept`, called where an exception is kept to be handed to Ruby again: a thread's at its From d9b506af50cf8ab26ccbadc99832cffc2032ce6c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:34:49 +0000 Subject: [PATCH 425/439] Open ARGF's next file before seek, pos, pos= and rewind ARGF.seek(4) before anything had been read raised "no stream to seek", and so did pos, pos= and rewind, where CRuby seeks in the first file. MRI calls next_argv before each of them: it opens the first file, or the next one when the current file has been read to its end, and only once every file is read says there is no stream. ARGF now does the same through prepare_current, which the partial reads already use; pos= says "no stream to set position", as MRI does, not "no stream to tell". CRuby's TestArgf#test_seek, #test_set_pos, #test_rewind and #test_tell pass now; ruby/spec's core/argf passes on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 54 +++++++++++++++++++++++++ Src/StdLib/ironruby/argf.rb | 10 +++-- 3 files changed, 61 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9447fb74b..844c085bc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1062,6 +1062,7 @@ public Tests(Driver/*!*/ driver) { Process_SpawnShellAssignment1, Process_UidGidReExchangeable1, Module_ConstGetPathConstMissing1, + Argf_SeekOpensNextFile1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 6722cc4ab..3e9852709 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10641,6 +10641,60 @@ p c2.const_get(""Bar11"", false) :Bar :Bar11 # +"); + } + + /// + /// ARGF#seek, #pos, #pos= and #rewind open the first file, or the next one when the current file has been read to its + /// end, before they act on it, as MRI's next_argv does, and say there is no stream once every file is read (CRuby's + /// TestArgf#test_seek, #test_set_pos, #test_rewind and #test_tell). + /// + public void Argf_SeekOpensNextFile1() { + TestOutput(@" +require 'ruby4' +require 'tmpdir' +Dir.mktmpdir do |d| + files = [%w[1 2], %w[3 4], %w[5 6]].each_with_index.map do |lines, i| + File.join(d, ""f#{i}"").tap { |f| File.write(f, lines.map { |l| ""#{l}\n"" }.join) } + end + a = ARGF.class.new(*files) + a.seek(4) + p a.gets + a.seek(0, IO::SEEK_END) + p a.gets + a.seek(4) + p a.gets + begin + a.seek(0) + rescue ArgumentError => e + p e.message + end + b = ARGF.class.new(*files) + b.pos = 4 + p b.gets, b.tell + b.rewind + p b.gets + c = ARGF.class.new(*files) + p c.pos + c.read + [-> { c.pos }, -> { c.pos = 1 }, -> { c.rewind }].each do |f| + f.call + rescue ArgumentError => e + p e.message + end +end +", @" +""3\n"" +""5\n"" +nil +""no stream to seek"" +""3\n"" +2 +""3\n"" +0 +""no stream to tell"" +""no stream to set position"" +""no stream to rewind"" "); } } diff --git a/Src/StdLib/ironruby/argf.rb b/Src/StdLib/ironruby/argf.rb index b5365fb91..9d5f08219 100644 --- a/Src/StdLib/ironruby/argf.rb +++ b/Src/StdLib/ironruby/argf.rb @@ -91,25 +91,27 @@ def skip self end + # These four work on the current file, opening the first one - or the next, when the current + # one has been read to its end - as MRI's next_argv does before each of them. def rewind - raise ArgumentError, "no stream to rewind" if @__current__.nil? || @__current__.closed? + raise ArgumentError, "no stream to rewind" unless prepare_current @__lineno__ -= @__current__.lineno @__current__.rewind end def pos - raise ArgumentError, "no stream to tell" if @__current__.nil? || @__current__.closed? + raise ArgumentError, "no stream to tell" unless prepare_current @__current__.pos end alias_method :tell, :pos def pos=(position) - raise ArgumentError, "no stream to tell" if @__current__.nil? || @__current__.closed? + raise ArgumentError, "no stream to set position" unless prepare_current @__current__.pos = position end def seek(amount, whence = IO::SEEK_SET) - raise ArgumentError, "no stream to seek" if @__current__.nil? || @__current__.closed? + raise ArgumentError, "no stream to seek" unless prepare_current @__current__.seek(amount, whence) end From 44506d6e0aedded5099c6c6996692e136ca902aa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:38:23 +0000 Subject: [PATCH 426/439] Answer ARGF#read's buffer, emptied, once every file is read ARGF.read(0, +"") after the last line of the last file had been read answered nil. MRI's argf_read returns its str when next_argv finds no stream: the buffer it was given, emptied, or nil without one. ARGF#read now answers the buffer in both of its branches (with and without a length). CRuby's TestArgf#test_read3 passes now; ruby/spec's core/argf, the Kernel#gets and #readlines specs and language/predefined_spec pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 24 ++++++++++++++++++++++++ Src/StdLib/ironruby/argf.rb | 9 ++++++--- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 844c085bc..b729b8339 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1063,6 +1063,7 @@ public Tests(Driver/*!*/ driver) { Process_UidGidReExchangeable1, Module_ConstGetPathConstMissing1, Argf_SeekOpensNextFile1, + Argf_ReadAtEndBuffer1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 3e9852709..ee7878326 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10695,6 +10695,30 @@ p e.message ""no stream to tell"" ""no stream to set position"" ""no stream to rewind"" +"); + } + + /// + /// ARGF#read with nothing left in any file answers the buffer it was given, emptied, and nil without one, as MRI's + /// argf_read returns its str (CRuby's TestArgf#test_read3). + /// + public void Argf_ReadAtEndBuffer1() { + TestOutput(@" +require 'ruby4' +require 'tmpdir' +Dir.mktmpdir do |d| + f = File.join(d, ""f"") + File.write(f, ""1\n2\n"") + a = ARGF.class.new(f) + nil while a.gets + p a.read, a.read(0, +""""), a.read(4, +""x""), a.read(nil, +""y""), a.read(4) +end +", @" +nil +"""" +"""" +"""" +nil "); } } diff --git a/Src/StdLib/ironruby/argf.rb b/Src/StdLib/ironruby/argf.rb index 9d5f08219..60833bb67 100644 --- a/Src/StdLib/ironruby/argf.rb +++ b/Src/StdLib/ironruby/argf.rb @@ -257,7 +257,8 @@ def readbyte # read spans files; read(length) counts bytes across all of them and comes # back binary, the way IO#read does. Both answer nil - not "" - once every - # file has been read and left behind. + # file has been read and left behind, unless they were given a buffer, which + # comes back empty. def read(length = nil, buffer = nil) buffer = clear_buffer(buffer) @@ -272,7 +273,8 @@ def read(length = nil, buffer = nil) result = result.nil? ? chunk : (result + chunk) leave_current end - return nil if result.nil? + # nothing left at all: the buffer, emptied, when one was given (argf_read returns str) + return buffer if result.nil? buffer ? buffer.replace(result) : result else length = Integer(length) @@ -291,7 +293,8 @@ def read(length = nil, buffer = nil) break if length <= 0 leave_current end - return nil if result.nil? + # nothing left at all: the buffer, emptied, when one was given (argf_read returns str) + return buffer if result.nil? buffer ? buffer.replace(result) : result end end From 1cca1c143cbe75728d20b149472d0738ffb95977 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:38:23 +0000 Subject: [PATCH 427/439] Raise TypeError for an ARGV entry ARGF cannot take as a path ARGV[0] = nil; gets raised Errno::ENOENT for a file named "": ARGF made the name with String(), which turns nil into "" and 1 into "1". MRI's next_argv takes it with FilePathValue - #to_path, then a String or what #to_str makes one - and anything else is a TypeError ("no implicit conversion of nil into String"). ARGF now does the same. CRuby's TestArgf#test_wrong_type passes now; ruby/spec's core/argf, the Kernel#gets and #readlines specs and language/predefined_spec pass on both builds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 31 +++++++++++++++++++++++++ Src/StdLib/ironruby/argf.rb | 8 ++++++- 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index b729b8339..bf1eee421 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1064,6 +1064,7 @@ public Tests(Driver/*!*/ driver) { Module_ConstGetPathConstMissing1, Argf_SeekOpensNextFile1, Argf_ReadAtEndBuffer1, + Argf_NonStringArgv1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index ee7878326..069dc8be1 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10719,6 +10719,37 @@ public void Argf_ReadAtEndBuffer1() { """" """" nil +"); + } + + /// + /// An ARGV entry that is not a String (nor makes one with #to_str) is a TypeError when ARGF comes to open it, as MRI's + /// next_argv takes it with FilePathValue; nil is not the empty name (CRuby's TestArgf#test_wrong_type). + /// + public void Argf_NonStringArgv1() { + TestOutput(@" +require 'ruby4' +require 'tmpdir' +Dir.mktmpdir do |d| + f = File.join(d, ""f"") + File.write(f, ""1\n2\n"") + [nil, 1, :sym].each do |bad| + b = ARGF.class.new(bad) + begin + b.gets + rescue TypeError => e + p e.message + end + end + o = Object.new + o.define_singleton_method(:to_str) { f } + p ARGF.class.new(o).gets +end +", @" +""no implicit conversion of nil into String"" +""no implicit conversion of Integer into String"" +""no implicit conversion of Symbol into String"" +""1\n"" "); } } diff --git a/Src/StdLib/ironruby/argf.rb b/Src/StdLib/ironruby/argf.rb index 60833bb67..5861db678 100644 --- a/Src/StdLib/ironruby/argf.rb +++ b/Src/StdLib/ironruby/argf.rb @@ -434,7 +434,13 @@ def open_next @__started__ = true name = @__argv__.shift name = name.to_path if name.respond_to?(:to_path) - name = String(name) + # a path, as MRI's next_argv takes it (FilePathValue): a String or what #to_str makes one, + # and a TypeError for anything else - nil included, which String() made "" + unless name.is_a?(::String) + converted = ::String.try_convert(name) + raise ::TypeError, "no implicit conversion of #{name.nil? ? "nil" : name.class} into String" unless converted + name = converted + end if name == "-" set_current($stdin, name) From ed7030ec5483b192328211cd75be3bf3bf588063 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:44:14 +0000 Subject: [PATCH 428/439] cruby-test: baseline after round thirteen test_module and test_argf re-swept after the round's fixes: 6,714 tests passing (from 6,706), one file without a summary (test_iseq), as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index 5da2f2c7a..c35ddc0be 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with -failures, 1 without a summary (test_iseq); 10,371 tests counted, 6,706 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,371 tests counted, 6,714 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 191eb88f5..0adff4ca4 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -1,6 +1,6 @@ test_alias 18 tests 0 failures 1 errors 0 skips test_allocation 76 tests 0 failures 76 errors 0 skips -test_argf 73 tests 18 failures 1 errors 1 skips +test_argf 73 tests 12 failures 1 errors 1 skips test_arithmetic_sequence 37 tests 0 failures 0 errors 0 skips test_arity 3 tests 0 failures 0 errors 0 skips test_array 493 tests 0 failures 16 errors 2 skips @@ -74,7 +74,7 @@ test_metaclass 1 tests 0 failures 0 errors 0 sk test_method 99 tests 5 failures 0 errors 0 skips test_method_cache 4 tests 0 failures 0 errors 0 skips test_mixed_unicode_escapes 1 tests 1 failures 0 errors 0 skips -test_module 195 tests 5 failures 8 errors 0 skips +test_module 195 tests 5 failures 6 errors 0 skips test_name_error 11 tests 0 failures 0 errors 0 skips test_nomethod_error 10 tests 0 failures 0 errors 0 skips test_not 2 tests 0 failures 0 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 69 clean, 72 with failures, 1 without a summary -10371 tests, 2552072 assertions, 470 failures, 3125 errors, 70 skips; 6706 passing +10371 tests, 2552116 assertions, 464 failures, 3123 errors, 70 skips; 6714 passing From 5eed1f303f5f4dd222a97411c540b7c757d98bb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:46:21 +0000 Subject: [PATCH 429/439] Class variable lookup: a module comes before the modules prepended to it A class variable defined both in a class and in a module prepended to it is "overtaken", and the error names the nearer one as overtaken by the further one. IronRuby walked #ancestors order, where the prepended module comes first, so it said "@@a of P1 is overtaken by A1" where CRuby 4.0 says "@@a of A1 is overtaken by P1". CRuby's CVAR_LOOKUP walks the superclass chain: the class itself, then the iclasses of its prepended modules, its origin skipped, then its mixins, and an included module that has prepends of its own comes before them the same way. TryResolveClassVariableNoRaise now walks in that order: per class in the superclass chain (or the module itself), the module, its prepends, its mixins, and within a list of mixins or prepends a module ahead of its own prepends. Which variable wins (the one furthest up) and where a write goes are unchanged where nothing is overtaken. The interpreter, class_variable_get/set and the method JIT share the lookup. Checked: a prepend of the class, of a superclass, of an included module, two prepends, a variable only in the prepend and a write to it print CRuby's output (new section of Util/jit-cvar-matrix.rb, read hot, in every mode). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Builtins/RubyModule.cs | 65 +++++++++++++++++++++++++++------ Util/jit-cvar-matrix.rb | 26 +++++++++++++ 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 4c31c7f3c..1f657dadc 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -3888,19 +3888,18 @@ internal RubyModule TryResolveClassVariableNoRaise(string/*!*/ name, out object object targetValue = null; // MRI's CVAR_LOOKUP: the variable is the one furthest up the ancestors; one defined - // lower down as well is "overtaken" by it, which is an error. + // lower down as well is "overtaken" by it, which is an error. The walk is MRI's superclass + // chain, where a class (or the module looked up from) comes before the modules prepended to + // it - its origin, which they sit above, is skipped - and not the order of #ancestors. using (Context.ClassHierarchyLocker()) { - ForEachAncestor(delegate(RubyModule/*!*/ module) { - object moduleValue; - if (module.TryGetClassVariable(name, out moduleValue)) { - if (nearest == null) { - nearest = module; - } - target = module; - targetValue = moduleValue; + var cls = this as RubyClass; + if (cls == null) { + ResolveClassVariableAt(name, ref nearest, ref target, ref targetValue); + } else { + for (RubyClass c = cls; c != null; c = c.SuperClass) { + c.ResolveClassVariableAt(name, ref nearest, ref target, ref targetValue); } - return false; - }); + } } front = nearest; @@ -3908,6 +3907,50 @@ internal RubyModule TryResolveClassVariableNoRaise(string/*!*/ name, out object return target; } + // One level of TryResolveClassVariableNoRaise's walk: this module, then its prepended modules, then its mixins. + private void ResolveClassVariableAt(string/*!*/ name, ref RubyModule nearest, ref RubyModule target, ref object targetValue) { + Context.RequiresClassHierarchyLock(); + ResolveClassVariableIn(this, name, ref nearest, ref target, ref targetValue); + ResolveClassVariableIn(_prepends, name, ref nearest, ref target, ref targetValue); + ResolveClassVariableIn(_mixins, name, ref nearest, ref target, ref targetValue); + } + + // A list of mixins or prepends in #ancestors order, where a module that has prepends of its own follows them: MRI's + // chain has the module's iclass first, so the module is looked at before them. + private static void ResolveClassVariableIn(RubyModule/*!*/[]/*!*/ modules, string/*!*/ name, ref RubyModule nearest, ref RubyModule target, + ref object targetValue) { + int i = 0; + while (i < modules.Length) { + int owner = -1; + for (int k = i + 1; k < modules.Length; k++) { + var prepends = modules[k]._prepends; + if (prepends.Length == k - i && ReferenceEquals(prepends[0], modules[i])) { owner = k; break; } + } + if (owner < 0) { + ResolveClassVariableIn(modules[i], name, ref nearest, ref target, ref targetValue); + i++; + } else { + ResolveClassVariableIn(modules[owner], name, ref nearest, ref target, ref targetValue); + for (int k = i; k < owner; k++) { + ResolveClassVariableIn(modules[k], name, ref nearest, ref target, ref targetValue); + } + i = owner + 1; + } + } + } + + private static void ResolveClassVariableIn(RubyModule/*!*/ module, string/*!*/ name, ref RubyModule nearest, ref RubyModule target, + ref object targetValue) { + object moduleValue; + if (module.TryGetClassVariable(name, out moduleValue)) { + if (nearest == null) { + nearest = module; + } + target = module; + targetValue = moduleValue; + } + } + /// /// Whether the module or an ancestor has the class variable: MRI's rb_cvar_defined, which `defined?(@@x)' and /// Module#class_variable_defined? answer by, walks the ancestors without the "overtaken" check of a read diff --git a/Util/jit-cvar-matrix.rb b/Util/jit-cvar-matrix.rb index 6bf1182c6..cb4ff9ea9 100644 --- a/Util/jit-cvar-matrix.rb +++ b/Util/jit-cvar-matrix.rb @@ -99,6 +99,32 @@ def sub_v = @@v t("overtaken, read") { ov.sub_v } t("overtaken, write") { ov.set_v(1); ov.sub_v } +# the walk is MRI's chain: a class or module before the modules prepended to it, so it is the "front" of an overtaken +# variable (RubyModule.TryResolveClassVariableNoRaise) +module CVOrdP1; @@a = :p1; end +class CVOrdA; @@a = :a; def a = @@a; end +class CVOrdB < CVOrdA; def b = @@a; end +module CVOrdQ2; @@b = :q2; end +module CVOrdM2; @@b = :m2; prepend CVOrdQ2; end +class CVOrdC; include CVOrdM2; def b = @@b; end +module CVOrdP3; @@c = :p3; end +module CVOrdP3b; @@c = :p3b; end +class CVOrdD; prepend CVOrdP3; prepend CVOrdP3b; def c = @@c; end +module CVOrdP5; @@e = :p5; end +class CVOrdE; def e = @@e; def set_e(v) = @@e = v; end +CVOrdE.prepend(CVOrdP5) +oa = CVOrdA.new +ob = CVOrdB.new +t("before a prepend brings it") { warm { [oa.a, ob.b] } } +CVOrdA.prepend(CVOrdP1) +t("own prepend has it too") { oa.a } +t("a superclass's prepend has it too") { ob.b } +t("class_variable_get, the same") { CVOrdA.class_variable_get(:@@a) } +t("an included module's prepend") { warm { (CVOrdC.new.b rescue $!.message) } } +t("two prepends") { warm { (CVOrdD.new.c rescue $!.message) } } +t("only the prepend has it") { warm { CVOrdE.new.e } } +t("written where it is found") { warm { |i| CVOrdE.new.set_e(i) }; [CVOrdP5.class_variable_get(:@@e), CVOrdE.class_variables] } + # a frozen class class CVFrozen @@x = 1 From 7d7c917fbb93701d03da050a34439b7ea891e155 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:56:14 +0000 Subject: [PATCH 430/439] Honor the shareable_constant_value magic comment # shareable_constant_value: literal (or experimental_everything, # experimental_copy) changed nothing: prism wraps each constant write in # its scope in a ShareableConstantNode carrying the mode, and the bridge # unwrapped it. MRI's pm_compile_shareable_constant_value builds the # value written: a literal (scalars, strings, arrays and hashes of them) # deep-frozen whatever the mode; otherwise an array or hash built from its # elements, each treated the same way, and the whole made shareable; any # other value made shareable (a shareable copy, for experimental_copy) # when it is the whole value, and under literal checked to be shareable # already wherever it is, raising Ractor::IsolationError "cannot assign # unshareable object to B::C" (with "::C" for a path from the top and # "...::C" for one whose parent is no constant). The bridge now builds the # same, through two Kernel helpers standing in for RubyVM::FrozenCore's # make_shareable(_copy) and ensure_shareable, for plain, path, ||=, &&= # and operator writes. CRuby's TestParse#test_shareable_constant_value_simple, _literal_const_refs, _nested, _hash_with_keyword_splat, _unshareable_literal, _nonliteral, _literal_op_assign and _unfrozen pass now. ruby/spec's language suite is unchanged (the same on both builds). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 2 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 126 ++++++++++++++++++++++++ Src/Libraries/Builtins/KernelOps.cs | 28 ++++++ Src/Prism/PrismAstBridge.cs | 126 +++++++++++++++++++++++- 4 files changed, 281 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index bf1eee421..dd9209438 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1065,6 +1065,8 @@ public Tests(Driver/*!*/ driver) { Argf_SeekOpensNextFile1, Argf_ReadAtEndBuffer1, Argf_NonStringArgv1, + Compiler_ShareableConstantValue1, + Compiler_ShareableConstantValue2, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 069dc8be1..e35ead877 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10750,6 +10750,132 @@ p ARGF.class.new(o).gets ""no implicit conversion of Integer into String"" ""no implicit conversion of Symbol into String"" ""1\n"" +"); + } + + /// + /// A constant written under a shareable_constant_value magic comment takes its value as MRI's + /// pm_compile_shareable_constant_value builds it: experimental_everything makes it shareable, experimental_copy a shareable + /// copy, and literal deep-freezes literals and raises Ractor::IsolationError naming the constant for any other value that is + /// not shareable (CRuby's TestParse#test_shareable_constant_value_*). + /// + public void Compiler_ShareableConstantValue1() { + TestOutput(@" +require 'ruby4' +# shareable_constant_value: experimental_everything +A = [[1]] +# shareable_constant_value: none +B = [[2]] +# shareable_constant_value: literal +C = [[""shareable"", ""constant#{nil}""]] +D = A +p [A, B, C].map { |x| Ractor.shareable?(x) }, Ractor.shareable?(A[0]), A[0], C +# shareable_constant_value: experimental_copy +obj = [[""unshareable""]] +E = obj +p Ractor.shareable?(E), Ractor.shareable?(obj), E == obj, E.equal?(obj) +# shareable_constant_value: literal +foo = 1 +bar = 2 +F = { foo => bar } +G = [foo, bar] +p Ractor.shareable?(F), Ractor.shareable?(G), F, G +H = { 'Object' => Object, 'String' => String } +p Ractor.shareable?(H) +def t + yield +rescue Ractor::IsolationError => e + p [e.class, e.message] +end +t { I = [""Not "" + ""shareable""] } +t { J = Class.new; J::K = [""Not "" + ""shareable""] } +t { ::L = [""Not "" + ""shareable""] } +t { ::J::M ||= [""Not "" + ""shareable""] } +t { N ||= [""Not "" + ""shareable""] } +O = true +t { O &&= [""Not "" + ""shareable""] } +P = [].freeze +t { P += [""Not "" + ""shareable""] } +var = [:shareable].freeze +Q ||= var +p Q, Ractor.shareable?(Q) +def self.expr = J +t { expr::R ||= [""Not "" + ""shareable""] } +v2 = [:not_frozen] +t { S = v2 } +t { T = begin [] end } +p U = ""str"", U.frozen?, (V = 1..2).frozen? +", @" +[true, false, true] +true +[1] +[[""shareable"", ""constant""]] +true +false +true +false +true +true +{1 => 2} +[1, 2] +true +[Ractor::IsolationError, ""cannot assign unshareable object to I""] +[Ractor::IsolationError, ""cannot assign unshareable object to J::K""] +[Ractor::IsolationError, ""cannot assign unshareable object to ::L""] +[Ractor::IsolationError, ""cannot assign unshareable object to ::J::M""] +[Ractor::IsolationError, ""cannot assign unshareable object to N""] +[Ractor::IsolationError, ""cannot assign unshareable object to O""] +[Ractor::IsolationError, ""cannot assign unshareable object to P""] +[:shareable] +true +[Ractor::IsolationError, ""cannot assign unshareable object to ...::R""] +[Ractor::IsolationError, ""cannot assign unshareable object to S""] +[Ractor::IsolationError, ""cannot assign unshareable object to T""] +""str"" +true +true +"); + } + + /// + /// The shareable_constant_value magic comment holds for the section of the file it starts, inside a class body too, a + /// hash with a keyword splat is made shareable whole, and an object whose #freeze does not freeze it is a Ractor::Error + /// (CRuby's TestParse#test_shareable_constant_value_nested, _hash_with_keyword_splat and _unfrozen). + /// + public void Compiler_ShareableConstantValue2() { + TestOutput(@" +require 'ruby4' +# shareable_constant_value: none +class X + # shareable_constant_value: experimental_everything + var = [[1]] + A = var +end +B = [] +p Ractor.shareable?(X::A), Ractor.shareable?(B), X::A[0] +# shareable_constant_value: experimental_everything +x = { x: {} } +y = { y: {} } +C = { **x } +D = { x: {}, **y } +p Ractor.shareable?(C), Ractor.shareable?(D), C, D +o = Object.new +def o.freeze; self; end +begin + E = [o] +rescue Ractor::Error => e + p e.class, e.message +end +", @" +true +false +[1] +true +true +{x: {}} +{x: {}, y: {}} +Ractor::Error +""#freeze does not freeze object correctly"" "); } } diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index ab148ad2b..b411f2401 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1183,6 +1183,34 @@ public static object Loop(BlockParam/*!*/ block, object self) { #region raise, fail + // What a constant written under a `# shareable_constant_value:` magic comment goes through + // (PrismAstBridge.ShareableConstantValue): MRI's RubyVM::FrozenCore.make_shareable and + // make_shareable_copy, under a name of its own that a program does not redefine. + [RubyMethod("__ir_make_shareable__", RubyMethodAttributes.PublicSingleton)] + public static object MakeShareableConstant( + CallSiteStorage>/*!*/ cloneStorage, + CallSiteStorage>/*!*/ allocateStorage, + CallSiteStorage>/*!*/ freezeStorage, + RubyModule/*!*/ self, object obj, bool copy) { + + var context = self.Context; + if (copy) { + obj = new Copier(context, cloneStorage, allocateStorage, false).Copy(obj); + } + new Shareability(context, freezeStorage).MakeShareable(obj); + return obj; + } + + // MRI's RubyVM::FrozenCore.ensure_shareable (rb_ractor_ensure_shareable): under + // `# shareable_constant_value: literal` a value that is no literal must be shareable already. + [RubyMethod("__ir_ensure_shareable__", RubyMethodAttributes.PublicSingleton)] + public static object EnsureShareableConstant(RubyModule/*!*/ self, object obj, [NotNull]RubySymbol/*!*/ name) { + if (!Shareability.IsShareable(self.Context, obj)) { + throw new RactorIsolationError("cannot assign unshareable object to " + name.ToString()); + } + return obj; + } + [RubyMethod("raise", RubyMethodAttributes.PrivateInstance)] [RubyMethod("raise", RubyMethodAttributes.PublicSingleton)] [RubyMethod("fail", RubyMethodAttributes.PrivateInstance)] diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index acd569216..52b039fed 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Numerics; using IronRuby.Builtins; using IronRuby.Compiler; @@ -742,7 +743,7 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.ImplicitNode implicitNode: return Expr(implicitNode.Value); // hash shorthand {x:} / omitted values case Pm.ShareableConstantNode shareable: - return Expr(shareable.Write); + return ShareableConstantWrite(shareable, span); case Pm.ArrayNode array: { var items = new List(); @@ -3282,6 +3283,129 @@ private Arguments ZSuperArguments(Pm.ParametersNode/*!*/ node, List /// `ArgumentError` a constant of that name in the lexical scope. /// The method called on it is Kernel.__ir_raise__, Kernel.raise under a name a program does not redefine. /// + /// + /// A constant written under a `# shareable_constant_value:` magic comment (prism wraps the write + /// in a ShareableConstantNode that carries the mode). The write is the plain one; only the value + /// differs, as MRI's pm_compile_shareable_constant_value builds it. + /// + private Expression/*!*/ ShareableConstantWrite(Pm.ShareableConstantNode/*!*/ node, SourceSpan span) { + uint flags = node.Flags & (Pm.ShareableConstantNodeFlags.Literal | Pm.ShareableConstantNodeFlags.ExperimentalEverything | + Pm.ShareableConstantNodeFlags.ExperimentalCopy); + LeftValue target; + Pm.PmNode value; + string operation; + string path; + switch (node.Write) { + case Pm.ConstantWriteNode w: + target = new ConstantVariable(IdentifierText(w.Name), span); value = w.Value; operation = null; path = IdentifierText(w.Name); + break; + case Pm.ConstantOperatorWriteNode w: + target = new ConstantVariable(IdentifierText(w.Name), span); value = w.Value; operation = w.BinaryOperator; path = IdentifierText(w.Name); + break; + case Pm.ConstantOrWriteNode w: + target = new ConstantVariable(IdentifierText(w.Name), span); value = w.Value; operation = "||"; path = IdentifierText(w.Name); + break; + case Pm.ConstantAndWriteNode w: + target = new ConstantVariable(IdentifierText(w.Name), span); value = w.Value; operation = "&&"; path = IdentifierText(w.Name); + break; + case Pm.ConstantPathWriteNode w: + target = ConstantPath(w.Target, Span(w.Target)); value = w.Value; operation = null; path = ShareableConstantPath(w.Target); + break; + case Pm.ConstantPathOrWriteNode w: + target = ConstantPath(w.Target, Span(w.Target)); value = w.Value; operation = "||"; path = ShareableConstantPath(w.Target); + break; + case Pm.ConstantPathAndWriteNode w: + target = ConstantPath(w.Target, Span(w.Target)); value = w.Value; operation = "&&"; path = ShareableConstantPath(w.Target); + break; + case Pm.ConstantPathOperatorWriteNode w: + target = ConstantPath(w.Target, Span(w.Target)); value = w.Value; operation = w.BinaryOperator; path = ShareableConstantPath(w.Target); + break; + default: + return Expr(node.Write); + } + return new SimpleAssignmentExpression(target, ShareableConstantValue(value, flags, path, true), operation, span); + } + + // MRI's pm_constant_path_path: the names of the path, "" for a path from the top (::C) and "..." + // for one whose parent is no constant (expr::C) + private string/*!*/ ShareableConstantPath(Pm.PmNode/*!*/ target) { + var node = (Pm.ConstantPathNode)target; + var parts = new List { IdentifierText(node.Name) }; + Pm.PmNode current = node.Parent; + while (current is Pm.ConstantPathNode parent) { + parts.Insert(0, IdentifierText(parent.Name)); + current = parent.Parent; + } + if (current == null) { + parts.Insert(0, ""); + } else if (current is Pm.ConstantReadNode read) { + parts.Insert(0, IdentifierText(read.Name)); + } else { + parts.Insert(0, "..."); + } + return String.Join("::", parts); + } + + /// + /// MRI's pm_compile_shareable_constant_value. A literal - scalars, strings, and arrays and hashes of + /// literals - is made shareable (deep-frozen) whatever the mode. Otherwise an array or a hash is built + /// from its elements, each treated the same way, and the whole made shareable; any other value is + /// made shareable (copied first, for experimental_copy) when it is the whole value, and under + /// literal must be shareable already (ensure_shareable), wherever it is. + /// + private Expression/*!*/ ShareableConstantValue(Pm.PmNode/*!*/ node, uint flags, string/*!*/ path, bool top) { + var span = Span(node); + bool copy = (flags & Pm.ShareableConstantNodeFlags.ExperimentalCopy) != 0; + if (IsShareableConstantLiteral(node)) { + return top ? MakeShareable(Expr(node), false, span) : Expr(node); + } + switch (node) { + case Pm.ArrayNode array when array.Elements.All(e => !(e is Pm.SplatNode || e is Pm.KeywordHashNode)): { + var items = array.Elements.Select(e => ShareableConstantValue(e, flags, path, false)).ToArray(); + Expression result = new ArrayConstructor(new Arguments(items), span); + return top ? MakeShareable(result, copy, span) : result; + } + case Pm.HashNode hash when hash.Elements.All(e => e is Pm.AssocNode): { + var maplets = hash.Elements.Cast().Select(assoc => new Maplet( + ShareableConstantValue(assoc.Key, flags, path, false), ShareableConstantValue(assoc.Value, flags, path, false), Span(assoc) + )).ToArray(); + Expression result = new HashConstructor(maplets, span); + return top ? MakeShareable(result, copy, span) : result; + } + } + Expression value = Expr(node); + if (node is Pm.InterpolatedStringNode) { + value = new MethodCall(value, "-@", null, span); + } + if ((flags & Pm.ShareableConstantNodeFlags.Literal) != 0) { + return new MethodCall(KernelModule(span), "__ir_ensure_shareable__", + new Arguments(new Expression[] { value, new SymbolLiteral(path, RubyEncoding.UTF8, span) }), span); + } + return top ? MakeShareable(value, copy, span) : value; + } + + private static Expression/*!*/ MakeShareable(Expression/*!*/ value, bool copy, SourceSpan span) { + return new MethodCall(KernelModule(span), "__ir_make_shareable__", + new Arguments(new Expression[] { value, copy ? Literal.True(span) : Literal.False(span) }), span); + } + + // MRI's pm_compile_shareable_constant_literal: what it can build, deep-frozen, while it compiles + private static bool IsShareableConstantLiteral(Pm.PmNode/*!*/ node) { + switch (node) { + case Pm.TrueNode _: case Pm.FalseNode _: case Pm.NilNode _: case Pm.SymbolNode _: + case Pm.RegularExpressionNode _: case Pm.SourceLineNode _: case Pm.IntegerNode _: case Pm.FloatNode _: + case Pm.RationalNode _: case Pm.ImaginaryNode _: case Pm.SourceEncodingNode _: + case Pm.StringNode _: case Pm.SourceFileNode _: + return true; + case Pm.ArrayNode array: + return array.Elements.All(IsShareableConstantLiteral); + case Pm.HashNode hash: + return hash.Elements.All(e => e is Pm.AssocNode assoc && IsShareableConstantLiteral(assoc.Key) && IsShareableConstantLiteral(assoc.Value)); + default: + return false; + } + } + private static Expression/*!*/ KernelModule(SourceSpan span) { return new ConstantVariable(null, "Kernel", span); } From 75a55ce2b52e2e06b856e296ab512ac551c22bd6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:00:41 +0000 Subject: [PATCH 431/439] A chilled string literal warns at every frozen check, even where the method then changes nothing MRI's str_modifiable and rb_check_frozen report a chilled string ("literal string will be frozen in the future") before a method looks at anything. So "ABC".upcase!, "abc".strip!, "abc".sub!(/z/, ""), "abc".force_encoding("UTF-8"), "abc".encode!("UTF-8"), s.replace(s), "abc".delete_prefix!("z"), "".reverse! and some 15 more warn although they change nothing. IronRuby warned only on a write to the characters, so all of those were silent. MutableString.RequireNotFrozen, the check those methods make first, now reports a chilled string as well as refusing a frozen one: the same single flag test as before, with both bits in the mask. The prelude's __ir_require_unfrozen__ (#prepend, #delete_prefix!, #delete_suffix!) is now that check, in C#. #delete_prefix! and #delete_suffix! make it before they convert their argument, as the comment above them already said and as MRI does: "a".freeze.delete_prefix!(1) is a FrozenError, not a TypeError. claude/cruby-test's ReportChilledMutation (409e75f, for setbyte and <<) stays as it is. Checked against CRuby 4.0: 36 no-op and ordinary calls on chilled literals, including scrub! and freeze, which warn in neither. ruby/spec core/string, symbol, language/string, io read, readpartial and sysread, library/stringio, sprintf and marshal match the base. New IronRuby.Tests: String_ChilledNoOpBang1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/StringTests.cs | 53 ++++++++++++++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 9 ++++ Src/Ruby/Builtins/MutableString.cs | 13 +++++- Src/StdLib/ironruby/ruby4.rb | 10 +--- 5 files changed, 76 insertions(+), 10 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fa4b48669..4eaeedc0b 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -176,6 +176,7 @@ public Tests(Driver/*!*/ driver) { String_NonCharacter1, String_SuccSeparators1, String_AppendFrozenFirst1, + String_ChilledNoOpBang1, String_AppendFrozenAnyArgument1, String_CountDeleteSqueeze1, String_CountDeleteSqueeze2, diff --git a/Src/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index 81a548087..d676d59d8 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -389,6 +389,59 @@ class S < String; end "); } + /// + /// A chilled literal warns at the first method that checks it can be changed, as MRI's str_modifiable does, even where the + /// method then changes nothing (force_encoding to its own encoding, upcase! of an upper-case string, sub! with no match); a + /// frozen string is refused before the argument is converted. Expected output is CRuby 4.0's. + /// + public void String_ChilledNoOpBang1() { + TestOutput(@" +require 'ruby4' +Warning[:deprecated] = true +module Warning + def self.warn(message, category: nil) + print message.sub(/\A.*?warning: /, ""warning: "").sub(/ \(run with.*/, """") + end +end +def t(name) + puts name + yield +end +t(:force_encoding_same) { ""abc"".force_encoding(""UTF-8"") } +t(:upcase_unchanged) { ""ABC"".upcase! } +t(:strip_unchanged) { ""abc"".strip! } +t(:sub_no_match) { ""abc"".sub!(/z/, """") } +t(:tr_no_match) { ""abc"".tr!(""z"", ""y"") } +t(:replace_self) { s = ""abc""; s.replace(s) } +t(:delete_prefix_none) { ""abc"".delete_prefix!(""z"") } +t(:encode_same) { ""abc"".encode!(""UTF-8"") } +t(:scrub_nothing) { ""abc"".scrub! } +t(:freeze) { ""abc"".freeze } +t(:frozen_first) { p((""a"".freeze.delete_prefix!(1) rescue $!.class)) } +", @" +force_encoding_same +warning: literal string will be frozen in the future +upcase_unchanged +warning: literal string will be frozen in the future +strip_unchanged +warning: literal string will be frozen in the future +sub_no_match +warning: literal string will be frozen in the future +tr_no_match +warning: literal string will be frozen in the future +replace_self +warning: literal string will be frozen in the future +delete_prefix_none +warning: literal string will be frozen in the future +encode_same +warning: literal string will be frozen in the future +scrub_nothing +freeze +frozen_first +FrozenError +"); + } + /// /// #count, #delete and #squeeze answer an ASCII character from a bitmask CharacterSelector /// computes when it is parsed, negation and intersection included; anything else goes diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 6f8ae6c48..e69b337f1 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1944,6 +1944,15 @@ private static MutableString CaseMapInPlace(MutableString/*!*/ self, CaseMapping return (self.IsFrozen || self.IsChilled) ? self.Clone() : self; } + /// + /// MRI's str_modifiable, for the prelude's String methods (#prepend, #delete_prefix!, #delete_suffix!): a frozen + /// String refuses, and a chilled one warns, before the method looks at its arguments. + /// + [RubyMethod("__ir_require_unfrozen__", RubyMethodAttributes.PrivateInstance)] + public static void RequireUnfrozen(MutableString/*!*/ self) { + self.RequireNotFrozen(); + } + // String#-@ (ruby4.rb) interns a bare String here: MRI's fstring table is the one that // frozen string literals and "literal".freeze come from, so -str can answer the very // object a literal evaluates to. diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index a9d65bae9..34ec51286 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -1277,9 +1277,18 @@ public void ReportChilledMutation() { } } + /// + /// MRI's str_modifiable and rb_check_frozen: a frozen string refuses, and a chilled one is reported (once) as a write to + /// it would be - a method that checks before it looks, such as "ABC".upcase! or "abc".force_encoding("UTF-8"), warns + /// even where it then changes nothing. + /// public void RequireNotFrozen() { - if (IsFrozen) { - throw RubyExceptions.CreateStringFrozenError(this); + uint flags = _flags; + if ((flags & (IsFrozenFlag | IsChilledFlag)) != 0) { + if ((flags & IsFrozenFlag) != 0) { + throw RubyExceptions.CreateStringFrozenError(this); + } + ReportChilledChange(this); } } diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index a506cd86e..3cb192203 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3919,25 +3919,19 @@ def prepend(*others) # The frozen check happens before the affix is even looked at: MRI raises # FrozenError even when nothing would have been removed. def delete_prefix!(prefix) - prefix = __affix__(prefix) __ir_require_unfrozen__ + prefix = __affix__(prefix) result = delete_prefix(prefix) result == self ? nil : replace(result) end unless method_defined?(:delete_prefix!) def delete_suffix!(suffix) - suffix = __affix__(suffix) __ir_require_unfrozen__ + suffix = __affix__(suffix) result = delete_suffix(suffix) result == self ? nil : replace(result) end unless method_defined?(:delete_suffix!) - def __ir_require_unfrozen__ - return unless frozen? - ::Kernel.raise(::FrozenError.new("can't modify frozen String: #{inspect}", receiver: self)) - end - private :__ir_require_unfrozen__ - # 3.4's name for -@. Spelled out rather than aliased: String#-@ is itself # defined further down this file. From d649c45e5e0a5fbd221a47761494c4c6e47ea295 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:05:38 +0000 Subject: [PATCH 432/439] Check a library's nested class against what is already defined module Zlib; end; Zlib::Error = 1; require "zlib" replaced the 1 with the library's class, and so it did a Zlib::Error the program had defined with another superclass. A library sets each class or module it nests in another as a constant of the outer one, without looking at what is there. MRI's rb_define_class_id_under raises TypeError for a constant that is no class ("Zlib::Error is not a class (Integer)") and for a class with another superclass ("superclass mismatch for class Zlib::Error (Object is given but was StandardError)", the existing superclass first, as MRI words it); rb_define_module_id_under for one that is no module. LibraryInitializer.SetConstant now makes the same checks for a class or module it is given, without running the outer module's constant initializer to look. A class with the same superclass is replaced as before. CRuby's TestRequire#test_define_class_under passes now. Requiring every C#-backed library and gem gives the same result on both builds, and ruby/spec's library zlib, digest, stringio and openssl specs pass on both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 26 +++++++++++++++ Src/Ruby/Builtins/LibraryInitializer.cs | 43 +++++++++++++++++++++++++ 3 files changed, 70 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index dd9209438..f14dfd78c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1067,6 +1067,7 @@ public Tests(Driver/*!*/ driver) { Argf_NonStringArgv1, Compiler_ShareableConstantValue1, Compiler_ShareableConstantValue2, + Library_NestedDefinitionConflict1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index e35ead877..869e54ce6 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -10876,6 +10876,32 @@ class X {x: {}, y: {}} Ractor::Error ""#freeze does not freeze object correctly"" +"); + } + + /// + /// A library's class or module nested in another meets what the program already put under its name as MRI's + /// rb_define_class_id_under does: a constant that is no class is a TypeError, and so is a class with another superclass + /// (CRuby's TestRequire#test_define_class_under). + /// + public void Library_NestedDefinitionConflict1() { + TestOutput(@" +module Zlib; end +Zlib::Error = 1 +begin + require ""zlib"" +rescue TypeError => e + p e +end +module Digest; class Base; end; end +begin + require ""digest"" +rescue TypeError => e + p e +end +", @" +# +# "); } } diff --git a/Src/Ruby/Builtins/LibraryInitializer.cs b/Src/Ruby/Builtins/LibraryInitializer.cs index 99cbaadcc..b931630fc 100644 --- a/Src/Ruby/Builtins/LibraryInitializer.cs +++ b/Src/Ruby/Builtins/LibraryInitializer.cs @@ -255,9 +255,52 @@ public static void SetConstant(RubyModule/*!*/ module, string/*!*/ name, object if (value == Undefined) { return; } + var definition = value as RubyModule; + if (definition != null) { + CheckNestedDefinition(module, name, definition); + } module.SetConstant(name, value); } + /// + /// A library's class or module nested in another (Zlib::Error) meets what a program may already have put + /// under that name, as MRI's rb_define_class_id_under and rb_define_module_id_under do: a constant that is + /// no class (no module) is a TypeError, and so is a class with another superclass - worded as MRI words it, + /// the superclass the existing class has first. + /// + private static void CheckNestedDefinition(RubyModule/*!*/ owner, string/*!*/ name, RubyModule/*!*/ definition) { + var context = owner.Context; + object existing; + using (context.ClassHierarchyLocker()) { + // not running the owner's constant initializer, which may be what is setting this one + ConstantStorage storage; + if (!owner.TryGetConstantNoAutoloadNoInit(name, out storage)) { + return; + } + existing = storage.Value; + } + if (existing == null || ReferenceEquals(existing, definition) || RubyModule.IsAutoload(existing)) { + return; + } + string path = context.GetModuleDisplayName(owner) + "::" + name; + var existingModule = existing as RubyModule; + if (existingModule == null || existingModule.IsClass != definition.IsClass) { + throw RubyExceptions.CreateTypeError("{0} is not a {1} ({2})", path, definition.IsClass ? "class" : "module", + context.GetClassName(existing)); + } + if (definition.IsClass) { + RubyClass existingSuper = ((RubyClass)existingModule).SuperClass, definedSuper = ((RubyClass)definition).SuperClass; + while (existingSuper != null && existingSuper.IsSingletonClass) { + existingSuper = existingSuper.SuperClass; + } + if (existingSuper != definedSuper) { + throw RubyExceptions.CreateTypeError("superclass mismatch for class {0} ({1} is given but was {2})", path, + existingSuper != null ? context.GetModuleDisplayName(existingSuper) : "nil", + definedSuper != null ? context.GetModuleDisplayName(definedSuper) : "nil"); + } + } + } + #endregion protected RubyClass/*!*/ GetClass(Type/*!*/ type) { From a744dbd63e526296a2ef3a5be6755ede0f3507d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:11:01 +0000 Subject: [PATCH 433/439] cruby-test: baseline after round fourteen test_parse and test_require re-swept after the round's fixes: 6,724 tests passing (from 6,714), one file without a summary (test_iseq), as before. One of the ten, TestRequire#test_require_with_loaded_features_pop, is no fix of this round's and may flip back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf5QpbMBfRqQTwBzNiD --- Util/cruby-test/PACKAGES.md | 2 +- Util/cruby-test/baseline.txt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index c35ddc0be..e4bb49676 100644 --- a/Util/cruby-test/PACKAGES.md +++ b/Util/cruby-test/PACKAGES.md @@ -1,7 +1,7 @@ # Work packages: passing more of CRuby's test/ruby Baseline (`baseline.txt`, CRuby v4.0.10's tests, net10.0, Linux): 142 files, 69 clean, 72 with -failures, 1 without a summary (test_iseq); 10,371 tests counted, 6,714 passing. (The first sweep, of v4.0.9: +failures, 1 without a summary (test_iseq); 10,371 tests counted, 6,724 passing. (The first sweep, of v4.0.9: 48 clean, 11 without a summary, 6,903 counted, 4,939 passing.) Each package is a set of test files one person (or agent) takes, in a build tree of their own. diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 0adff4ca4..e3c5eaa08 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -84,7 +84,7 @@ test_object_id 132 tests 0 failures 0 errors 0 sk test_objectspace 37 tests 10 failures 8 errors 0 skips test_optimization 90 tests 47 failures 23 errors 0 skips test_pack 56 tests 1 failures 0 errors 0 skips -test_parse 107 tests 16 failures 1 errors 0 skips +test_parse 107 tests 8 failures 1 errors 0 skips test_path 6 tests 0 failures 0 errors 0 skips test_pattern_matching 30 tests 0 failures 0 errors 0 skips test_pipe 12 tests 0 failures 2 errors 0 skips @@ -100,7 +100,7 @@ test_rational2 1 tests 0 failures 0 errors 0 sk test_readpartial 4 tests 1 failures 0 errors 0 skips test_refinement 122 tests 6 failures 2 errors 0 skips test_regexp 167 tests 29 failures 8 errors 0 skips -test_require 52 tests 10 failures 5 errors 1 skips +test_require 52 tests 8 failures 5 errors 1 skips test_require_lib 39 tests 0 failures 0 errors 0 skips test_rubyoptions 68 tests 51 failures 1 errors 0 skips test_rubyvm 3 tests 1 failures 2 errors 0 skips @@ -142,4 +142,4 @@ test_yjit_exit_locations 0 tests 0 failures 0 errors 0 sk test_zjit 0 tests 0 failures 0 errors 0 skips 142 files: 69 clean, 72 with failures, 1 without a summary -10371 tests, 2552116 assertions, 464 failures, 3123 errors, 70 skips; 6714 passing +10371 tests, 2552197 assertions, 454 failures, 3123 errors, 70 skips; 6724 passing From bc0d5acb58b651e0a708b1a97fb7afc75b1ad1e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:11:40 +0000 Subject: [PATCH 434/439] Method JIT: class variable sites keep the module they found the variable in Every `@@x` the method JIT compiled looked the variable up as the interpreter does: the class hierarchy lock, then a walk of the ancestors with a table lock each. A read cost about 105 ns where CRuby, which caches the lookup per instruction, takes about 45. RubyContext.ClassVariableVersion now moves whenever what a class variable name resolves to could change: a variable added to or removed from any module, a module's table copied, a mixin changing ancestors. JitRuntime.ClassVariableSite keeps the module the lookup found with the version read before it; while the version holds, an access goes to that module's table directly. The value is never cached, and the pair is one object replaced whole, so threads share a site. Frozen, dummy-singleton and Ractor checks stay on every access. IR_JIT_CVAR_CACHE=0 turns the cache off. Clock (Util/bench/cvar-shapes.rb, cache off -> on): a read 103.2 -> 69.1 ns, a subclass's read 106.7 -> 68.3, a write 134.1 -> 80.7. Util/jit-cvar-matrix.rb gains rows that move the version under a hot site (include and prepend bringing the variable above, an unrelated class gaining the name, writes from threads, class_variable_set) and prints CRuby 4.0's output in every mode and with the cache off, as do jit, jit-calls, jit-const, jit-defined and hot-shapes. ruby/spec class variable, prepend and include specs pass; IronRuby.Tests passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Src/Ruby/Builtins/RubyModule.cs | 12 +++- Src/Ruby/Runtime/Jit/JitCompiler.cs | 9 +-- Src/Ruby/Runtime/Jit/JitRuntime.cs | 88 +++++++++++++++++++++++------ Src/Ruby/Runtime/RubyContext.cs | 12 ++++ Util/jit-cvar-matrix.rb | 31 ++++++++++ Util/perf/LEDGER.md | 27 +++++++++ 6 files changed, 157 insertions(+), 22 deletions(-) diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 1f657dadc..1580409cf 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -935,6 +935,7 @@ internal void InitializeMembersFrom(RubyModule/*!*/ module) { } else { _classVariables = null; } + _context.ClassVariablesChanged(); _mixins = ArrayUtils.Copy(module._mixins); _prepends = ArrayUtils.Copy(module._prepends); _inheritedLookups = null; @@ -1824,6 +1825,8 @@ private bool IsOnFoldedPathNoLock(string/*!*/ name) { /// keyed on the lookups' paths, a constant of that name anywhere else (rminor's epoch move fired for those) does not. /// private void MixinsChangedConstantsNoLock() { + // the ancestors a class variable is looked up through moved as well + _context.ClassVariablesChanged(); if (_foldedConstantNames != null && (BringsFoldedConstantNoLock(_prepends) || BringsFoldedConstantNoLock(_mixins))) { _context.ConstantReassigned(); } else { @@ -3840,9 +3843,13 @@ public void SetClassVariable(string/*!*/ name, object value) { Mutate(); var table = _classVariables; + bool added; lock (table) { + added = !table.ContainsKey(name); table[name] = value; } + // after the variable is in: a site that sees the new version finds it + if (added) { _context.ClassVariablesChanged(); } } public bool TryGetClassVariable(string/*!*/ name, out object value) { @@ -3861,9 +3868,12 @@ public bool RemoveClassVariable(string/*!*/ name) { if (table == null) { return false; } + bool removed; lock (table) { - return table.Remove(name); + removed = table.Remove(name); } + if (removed) { _context.ClassVariablesChanged(); } + return removed; } public RubyModule TryResolveClassVariable(string/*!*/ name, out object value) { diff --git a/Src/Ruby/Runtime/Jit/JitCompiler.cs b/Src/Ruby/Runtime/Jit/JitCompiler.cs index da92fda36..d02c2517a 100644 --- a/Src/Ruby/Runtime/Jit/JitCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitCompiler.cs @@ -1578,14 +1578,15 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { /// /// `@@x': read where the generic body reads it (JitRuntime.ClassVariableRead), from the module ClassVariableOwner fixes when - /// the body is compiled - a body belongs to one definition of the method, in one scope. The variable's place is found on - /// every read, under the class hierarchy lock, as the generic body's; one undefined or overtaken deopts. + /// the body is compiled - a body belongs to one definition of the method, in one scope. The variable's place is found as the + /// generic body finds it, under the class hierarchy lock, and kept by the site until a class variable or a mixin changes + /// anywhere (JitRuntime.ClassVariableSite); one undefined or overtaken deopts. /// private MSA.Expression/*!*/ EmitClassVariableRead(ClassVariable/*!*/ node, out JT type) { var owner = ClassVariableOwner(); _canDeopt = true; type = JT.Obj; - return Ast.Call(JitRuntime.M("ClassVariableRead"), Ast.Constant(owner, typeof(RubyModule)), Ast.Constant(node.Name)); + return Ast.Call(JitRuntime.M("ClassVariableRead"), Ast.Constant(new JitRuntime.ClassVariableSite(owner, node.Name))); } /// @@ -1599,7 +1600,7 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { if (vt == JT.None || vt == JT.Never) { throw Bail("class variable assignment of a value that jumps away"); } var temp = Ast.Variable(ClrType(vt), "#cvar"); _canDeopt = true; - var store = Ast.Call(JitRuntime.M("ClassVariableWrite"), Ast.Constant(owner, typeof(RubyModule)), Ast.Constant(node.Name), BoxForStore(temp, vt)); + var store = Ast.Call(JitRuntime.M("ClassVariableWrite"), Ast.Constant(new JitRuntime.ClassVariableSite(owner, node.Name)), BoxForStore(temp, vt)); _pure = false; _effectNotOnSelf = true; type = vt; diff --git a/Src/Ruby/Runtime/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index dca74d644..243a6f0be 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -1252,34 +1252,88 @@ public static void WriteSelfAttrDouble(object self, double value, SelfAttrSite/* // unboxed while it holds the type it held when the loop was compiled, a deopt once it does not. /// - /// `@@x' (JitCompiler.EmitClassVariableRead): the variable as RubyOps.GetClassVariable finds it from , - /// the method's innermost lexical module (its singleton classes passed over). One that is not defined, one "overtaken" - /// (defined below the module that has it, which CRuby raises for) and one read while Ractors run deopt: the generic body - /// raises the NameError or RuntimeError, or checks the Ractor. + /// A class variable access in a typed body (JitCompiler.EmitClassVariableRead and EmitClassVariableWrite): the method's + /// innermost lexical module the lookup starts from, the name, and the module the lookup last found the variable in, kept + /// with the RubyContext.ClassVariableVersion it was found under. While the version stays, the variable is still there + /// and nothing above it has one of the name (no variable added or removed, no mixin), so an access goes straight to that + /// module's table; the value is never kept. Several threads share a site: the pair is one object, replaced whole. /// - public static object ClassVariableRead(RubyModule/*!*/ owner, string/*!*/ name) { - if (owner.Context.RactorsStarted) { throw Deopt(); } + public sealed class ClassVariableSite { + public readonly RubyModule/*!*/ Owner; + public readonly string/*!*/ Name; + private Resolution _resolved; + + private sealed class Resolution { + public readonly RubyModule/*!*/ Target; + public readonly int Version; + public Resolution(RubyModule/*!*/ target, int version) { Target = target; Version = version; } + } + + public ClassVariableSite(RubyModule/*!*/ owner, string/*!*/ name) { + Owner = owner; + Name = name; + } + + /// The module the variable was found in, if nothing has moved the version since; else null. + internal RubyModule Cached(int version) { + if (!ClassVariableCache) { return null; } + var resolved = System.Threading.Volatile.Read(ref _resolved); + return (resolved != null && resolved.Version == version) ? resolved.Target : null; + } + + /// is the one read before the lookup: a change during it leaves the entry stale. + internal void Remember(RubyModule/*!*/ target, int version) { + System.Threading.Volatile.Write(ref _resolved, new Resolution(target, version)); + } + } + + // IR_JIT_CVAR_CACHE=0: every class variable access in a typed body looks the variable up (ClassVariableSite.Cached) + internal static readonly bool ClassVariableCache = Environment.GetEnvironmentVariable("IR_JIT_CVAR_CACHE") != "0"; + + /// + /// `@@x' (JitCompiler.EmitClassVariableRead): the variable as RubyOps.GetClassVariable finds it from the site's owner, + /// the method's innermost lexical module (its singleton classes passed over), or from the module the site found it in + /// (ClassVariableSite). One that is not defined, one "overtaken" (defined below the module that has it, which CRuby + /// raises for) and one read while Ractors run deopt: the generic body raises the NameError or RuntimeError, or checks + /// the Ractor. + /// + public static object ClassVariableRead(ClassVariableSite/*!*/ site) { + var owner = site.Owner; + var context = owner.Context; + if (context.RactorsStarted) { throw Deopt(); } + int version = System.Threading.Volatile.Read(ref context.ClassVariableVersion); object value; + var cached = site.Cached(version); + if (cached != null && cached.TryGetClassVariable(site.Name, out value)) { return value; } RubyModule front; - RubyModule target = owner.TryResolveClassVariableNoRaise(name, out value, out front); + RubyModule target = owner.TryResolveClassVariableNoRaise(site.Name, out value, out front); if (target == null || front != target) { throw Deopt(); } + site.Remember(target, version); return value; } /// /// `@@x = v' (JitCompiler.EmitClassVariableWrite): stored where RubyOps.SetClassVariable stores it - in the module that - /// already has the variable, or in . An overtaken variable, a frozen module and a running Ractor - /// deopt before anything is stored. + /// already has the variable (the one the site found it in, while that holds), or in the site's owner. An overtaken + /// variable, a frozen module and a running Ractor deopt before anything is stored. /// - public static object ClassVariableWrite(RubyModule/*!*/ owner, string/*!*/ name, object value) { - if (owner.Context.RactorsStarted) { throw Deopt(); } - object oldValue; - RubyModule front; - RubyModule target = owner.TryResolveClassVariableNoRaise(name, out oldValue, out front); - if (front != target) { throw Deopt(); } - var into = target ?? owner; + public static object ClassVariableWrite(ClassVariableSite/*!*/ site, object value) { + var owner = site.Owner; + var context = owner.Context; + if (context.RactorsStarted) { throw Deopt(); } + int version = System.Threading.Volatile.Read(ref context.ClassVariableVersion); + var into = site.Cached(version); + if (into == null) { + object oldValue; + RubyModule front; + RubyModule target = owner.TryResolveClassVariableNoRaise(site.Name, out oldValue, out front); + if (front != target) { throw Deopt(); } + // a variable new here is added below, which moves the version: nothing to keep + if (target != null) { site.Remember(target, version); } + into = target ?? owner; + } if (into.IsFrozen || into.IsDummySingletonClass) { throw Deopt(); } - into.SetClassVariable(name, value); + into.SetClassVariable(site.Name, value); return value; } diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 7749f0f72..c0bc6331e 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -289,6 +289,18 @@ internal void ConstantsChanged() { ConstantAccessVersion++; } + /// + /// Moves when a class variable is added to or removed from any module, a module's table is copied, or a mixin + /// changes the ancestors a lookup goes through: what a class variable name resolves to (the module that has it) + /// can only change with it. The method JIT's class variable sites keep the module they found under it + /// (JitRuntime.ClassVariableSite); the value is read from that module on every access. + /// + public int ClassVariableVersion = 1; + + internal void ClassVariablesChanged() { + System.Threading.Interlocked.Increment(ref ClassVariableVersion); + } + /// /// An existing constant was assigned again or removed: the one change to constants that a running /// compiled loop which folded the constant must see at its next iteration, as CRuby's next read does. diff --git a/Util/jit-cvar-matrix.rb b/Util/jit-cvar-matrix.rb index cb4ff9ea9..e82171c75 100644 --- a/Util/jit-cvar-matrix.rb +++ b/Util/jit-cvar-matrix.rb @@ -99,6 +99,37 @@ def sub_v = @@v t("overtaken, read") { ov.sub_v } t("overtaken, write") { ov.set_v(1); ov.sub_v } +# the module a hot site found the variable in, then a change above it (JitRuntime.ClassVariableSite keeps the module) +module CVIncM; @@w = :mixin; end +module CVPreM; @@u = :prepended; end +class CVKeep + @@w = :keep + @@u = :keep + @@z = 0 + def w = @@w + def u = @@u + def z = @@z + def set_z(x) = @@z = x +end +class CVKeepSub < CVKeep + def sub_w = @@w +end +k = CVKeep.new +ks = CVKeepSub.new +t("kept, read and subclass read") { warm { [k.w, ks.sub_w] } } +class CVKeepTop; @@w = :top; end +t("an unrelated class gains it") { [k.w, ks.sub_w] } +CVKeep.include(CVIncM) +t("include brings it above, read") { k.w } +t("include brings it above, subclass") { ks.sub_w } +t("include brings it above, write") { CVKeep.class_variable_get(:@@w) rescue $!.class } +t("kept, before prepend") { warm { k.u } } +CVKeep.prepend(CVPreM) +t("prepend: the class is the front") { k.u } +t("written from threads") { warm { |i| k.set_z(i) }; 4.times.map { |j| Thread.new { 1000.times { |i| k.set_z(j * 1000 + i) } } }.each(&:join); k.z.is_a?(Integer) } +CVKeep.class_variable_set(:@@z, 99) +t("class_variable_set, then hot read") { k.z } + # the walk is MRI's chain: a class or module before the modules prepended to it, so it is the "front" of an overtaken # variable (RubyModule.TryResolveClassVariableNoRaise) module CVOrdP1; @@a = :p1; end diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 61a851c5f..6015cfd2d 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2043,6 +2043,33 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **perf/jitcvarcache (2026-11-29, timed, not gated) - the method JIT's class variable sites keep the module they found + the variable in** (switch `IR_JIT_CVAR_CACHE`). Built on perf/jitcvar f89b479. No census change: it makes the + accesses jitcvar compiled cheaper, which the ledger entry below named as the next step. + - **What.** `RubyContext.ClassVariableVersion` moves when a class variable is added to or removed from any module, a + module's table is copied (initialize_copy), or a mixin changes the ancestors (include, prepend, extend: where + `MixinsChangedConstantsNoLock` already runs). `JitRuntime.ClassVariableSite` keeps the module a lookup found, with + the version read before the lookup; while the version holds, an access reads or writes that module's table and + skips the hierarchy lock and the ancestor walk. The value is never kept. The pair is one object replaced whole, so + threads share a site safely. Frozen, dummy-singleton and Ractor checks stay on every access. + - **Found on the way, fixed as its own commit:** the lookup walked `#ancestors` order, so a variable in a class and in + a module prepended to it said "@@a of P1 is overtaken by A1" where CRuby 4.0 says "@@a of A1 is overtaken by P1". + CRuby's CVAR_LOOKUP walks the superclass chain (the class, its prepends' iclasses, its origin skipped, its + mixins); `TryResolveClassVariableNoRaise` now does the same, including an included module ahead of its own + prepends. The interpreter and class_variable_get/set share it. + - **Census:** 0 methods changed. **app-shapes, traced:** unchanged (specialized 131, declined 28). + - **Clock** (ab.rb -r 9, `Util/bench/cvar-shapes.rb`, ns, cache off -> on; CRuby about 45): a read 103.2 -> 69.1 + (0.67), a subclass's read 106.7 -> 68.3 (0.64), a write 134.1 -> 80.7 (0.60). An earlier run gave 0.56/0.57/0.52. + What is left is the table's lock and the Ractor and frozen checks. + - **Checks.** `Util/jit-cvar-matrix.rb` grows to 40 rows: a hot site, then an unrelated class gaining the name, + include and prepend bringing it above (RuntimeError, from the read, the subclass's read and class_variable_get), + writes from four threads, class_variable_set then a hot read; and the prepend order (a class's prepend, a + superclass's, an included module's, two prepends, only the prepend has it, written where found). It prints CRuby's output with the JIT on, -X:NoJIT -X:NoOSR, -X:NoJITCalls, + IR_LIGHT_FRAMES=0 and the cache off; f89b479 differs on the five prepend-order rows only. jit, jit-calls, + jit-const, jit-defined and hot-shapes in the same five modes: CRuby's output on both builds (30 runs with jit-cvar). + ruby/spec language/class_variable, core/module class_variable_get, _set, _defined, class_variables, + remove_class_variable, prepend and include: no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. + - **perf/jitcvar (2026-11-29, census and timed, not gated) - `@@x` and `@@x = v` in the method JIT's typed body** (the census's ClassVariable: 44 methods refused by it alone, 197 rows naming it; switch `IR_JIT_CLASS_VARIABLES`). Built on perf/jitsymeq ce6bb18. From 71f1a11963f88665e47b90922cb40793a24b76f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:17:07 +0000 Subject: [PATCH 435/439] IO#read_nonblock with nothing to read leaves its buffer as it was MRI's io_getpartial makes the buffer modifiable (io_setstrbuf), reads, and sets the buffer's length only once read(2) has answered. A read that would block raises IO::EAGAINWaitReadable, or answers :wait_readable with exception: false, and leaves the buffer as it was: a buffer holding "keep" still holds "keep". IronRuby emptied it before trying, so a caller's buffer lost its contents on every EAGAIN. perf/iter found this. ReadOnceWithoutWaiting now checks the buffer can be changed up front (a frozen buffer is still refused first) and empties it only right before data goes in, or at the end of the stream or for a length of 0, which MRI's io_set_read_length empties it for too. Checked against CRuby 4.0: a pipe and a UNIX socket pair, raising and with exception: false, data, a length of 0, end of file, and a frozen buffer. ruby/spec io read_nonblock, readpartial, read and sysread, library/socket, stringio and openssl match the base. New IronRuby.Tests: IO_ReadNonblockKeepsBuffer1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf6ogoTAvVP9SXaSH7L --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IoTests.cs | 38 +++++++++++++++++++++++++++ Src/Libraries/Builtins/IoOps.cs | 21 ++++++++++++++- 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 4eaeedc0b..b55347b63 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1530,6 +1530,7 @@ public Tests(Driver/*!*/ driver) { IOBuffer_CopyAndMasks1, File_FnmatchEscapedInBracket1, File_FnmatchNullPattern1, + IO_ReadNonblockKeepsBuffer1, Array_Cycle1, Range_Recursive1, Array_JoinRecursive1, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index 5241365dd..60f4b2e4d 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -1232,6 +1232,44 @@ 0x00000008 35 36 56 "); } + /// + /// IO#read_nonblock with nothing to read leaves its buffer as it was, raising or not: MRI's io_getpartial sets the buffer's + /// length only once read(2) has answered. Data replaces it, and the end of the stream and a length of 0 empty it; a frozen + /// buffer is refused first. Expected output is CRuby 4.0's. + /// + public void IO_ReadNonblockKeepsBuffer1() { + TestOutput(@" +require 'ruby4' +r, w = IO.pipe +buf = +""keep"" +p r.read_nonblock(5, buf, exception: false), buf +begin + r.read_nonblock(5, buf) +rescue IO::WaitReadable => e + p e.class, buf +end +w << ""hi"" +p r.read_nonblock(5, buf), buf +p r.read_nonblock(0, buf), buf +w.close +buf = +""keep"" +p r.read_nonblock(5, buf, exception: false), buf +p((IO.pipe[0].read_nonblock(1, ""keep"".freeze, exception: false) rescue $!.class)) +", @" +:wait_readable +""keep"" +IO::EAGAINWaitReadable +""keep"" +""hi"" +""hi"" +"""" +"""" +nil +"""" +FrozenError +"); + } + /// /// An escaped character in a bracket expression is that character: "[a\-c]" is 'a', '-' and 'c', not the range /// a-c, and an escaped '!' does not negate (CRuby's TestFnmatch#test_escape). diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 7c43aa370..9eeefac8a 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -2255,8 +2255,23 @@ private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, M } var stream = io.GetReadableStream(); - buffer = PrepareReadBuffer(io, buffer); + // MRI's io_getpartial makes the buffer modifiable first and sets its length only once read(2) has answered, so a read + // that would block leaves it as it was ("keep" stays "keep"); the end of the stream empties it, as data replaces it. + // Empty() is called before anything is put in it, or at the end. + bool empty = buffer == null; + if (empty) { + buffer = MutableString.CreateBinary(); + } else { + buffer.RequireNotFrozen(); + } + void Empty() { + if (!empty) { + buffer.Clear(); + empty = true; + } + } if (count == 0) { + Empty(); return buffer; } @@ -2265,6 +2280,7 @@ private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, M // for the rest. int buffered = 0; if (stream.DataBuffered) { + Empty(); buffered = io.AppendAvailableBytes(buffer, count); count -= buffered; if (count == 0) { @@ -2283,6 +2299,7 @@ private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, M } throw NonBlockingError(io.Context, true, "read would block"); } + Empty(); int queued = io.AppendAvailableBytes(buffer, count); return (queued == 0 && buffered == 0) ? null : buffer; } @@ -2315,6 +2332,7 @@ private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, M if (buffered == 0 && IoReadiness.IsQuietDescriptor(io, stream.BaseStream)) { throw NonBlockingError(io.Context, true, "read would block"); } + Empty(); int more = io.AppendBytes(buffer, count); return (more == 0 && buffered == 0) ? null : buffer; } @@ -2329,6 +2347,7 @@ private static MutableString ReadOnceWithoutWaiting(RubyIO/*!*/ io, int count, M } throw NonBlockingError(io.Context, true, "read would block"); } + Empty(); if (read == 0) { return (buffered > 0) ? buffer : null; } From ef86765d9d745f502ba8baab6d1d0c64178044a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:24:44 +0000 Subject: [PATCH 436/439] Ledger: a call into a pure typed callee from a typed body, counted and not built Stage 4's first piece of Docs/jit-resume-deopt.md, the one sound without resume: a typed body entering another receiver's typed body when that body is pure but too complex to inline. Counted on all of AWFY and on app-shapes with a temporary trace of each specialized body's purity: 7 pure non-inlinable bodies in AWFY, and the only callers they would let through are DeltaBlue's setup methods, which call through a constant. Richards and schedule have no such callee. Recorded under Rejected with the numbers; not built. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf7SFyMuNS8hE1vrTP2 --- Util/perf/LEDGER.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 6015cfd2d..13210f611 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -9321,6 +9321,25 @@ after master (#228 to #233) had been merged into both trees. ## Rejected +- **perf/jitpurecall (2026-11-29) - a typed body calling a pure typed callee on another receiver (stage 4's first + piece, without resume): counted, not built** (gap 1). The idea: `o.m(args)` from a typed body, o's class seen by the + profile, m's typed body known pure (`JitCode.Pure`: no effect, so a deopt inside it may still restart the caller) but + not inlinable (a loop, constants, direct calls), entered directly with unboxed arguments behind a class and method + version check. Counted dynamically, with a temporary trace (not committed) of each specialized body's `Pure` and + `Inlinable` at bc0d5ac: + - **AWFY** (all 14, small iteration counts): 88 specialized bodies, 38 pure and inlinable (already inlined where + the screen lets the call through), 43 impure, 7 pure and not inlinable - `Dictionary#at` (a loop), + `RedBlackTree#find_node`, `#get`, `Node#successor`, `tree_minimum`, `CollisionDetector#is_in_voxel`, + `Vector3D#magnitude`. Callers refused at the screen by one of those calls (`census.rb -u` on the same runs, every + refusal listed): 5, and only two have nothing else in the way - DeltaBlue's `Strength.of` and `Strength#initialize`, + setup code whose receiver is a constant (`STRENGTH_TABLE.at(sym)`), not a local or instance variable. Richards has + no pure non-inlinable callee at all, and `schedule`'s `t.step` is impure; the callers CD and Havlak would need + (`put_into_map`, `find_intersection`, `create_node`) also call `new`, `put`, `append`, `at_put`, `dot`, `plus`. + - **app-shapes:** 111 specialized, 9 pure and not inlinable; one caller (of `tax_rate`) is refused by such a call first. + This confirms the second round's finding above with counts: what keeps AWFY's hot methods out is the effect rule, + not a missing call into a pure body. What is next on gap 1 is unchanged: stage 3a's suffix compiler and the resume + at a statement, then calls after an effect. + - **perf/ownerpark (round thirty-seven, 2026-11-28) - a parked scope the thread that parked first takes and parks with plain loads and stores: measured, not kept** (gap 13). The take of a parked scope is the cycle's one atomic left after perf/endpark. The prototype (`IR_PARK_OWNER`) gave `ParkedScopeSlot` an `Owner` (the first thread to park, set once by From e5eb7f61b2180e891be4a01a530e9a73391af44e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:36:33 +0000 Subject: [PATCH 437/439] Ledger: round 13's gate, PASS Round 13 of round thirty-seven (claude/cruby-test's rounds 8-10, perf/aotosr, perf/unkept and unkept2, perf/jitmasgn1, perf/jitslice and perf/jitsplatlit, at 7cde67ee against master c4719ea) passed the gate: IronRuby.Tests 1,488 run, none failed; the matrices in seven modes with only the two known DIFFs; a probe file for the round as CRuby in four modes, the R2R host among them; ruby/spec's five suites with no unlisted failure; the census with 88 method-JIT ups and nothing down; AWFY 12 at a geomean of 0.905 and 0.891, and sum_blk at 0.83 of master's on the R2R host; start-up at 0.87-0.98 of master's. perf/crubydiff's round 23 waits for round 14. The round's entries are marked gated, and perf/yieldloop2's and 3's marks, which the merge undid, are put back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 49 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index ca2b9d0c0..2c9b185cd 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2051,6 +2051,39 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-29 for round 13 of round thirty-seven** (claude/cruby-test's rounds 8-10 - test/ruby 6,676 -> + 6,684 passing, perf/aotosr, perf/unkept and perf/unkept2, perf/jitmasgn1, perf/jitslice and perf/jitsplatlit): the + branch at 7cde67ee against master c4719ea, Release net10.0, the composite R2R host on both, four cores: **PASS**. + perf/crubydiff's round 23 was held out of the round: its Array#sum change met perf/yieldloop3's Integer front loop + and its defined? change perf/jitdefined's screen; reconciled on its branch since (8c9285eb), for round 14. Gated in + a worktree of its own and pushed after. + The merge itself: only the ledger conflicted; it left perf/jitdefined's gated header orphaned (fixed, 7cde67ee) and + took perf/yieldloop2's and 3's entries back to "not gated" (marked again here). ReflectionCache.Generated.cs is + what ClassInitGenerator writes. No new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,488 tests, every one executed, none failed. + `gate-matrices.rb --all` in 7 modes (the six default ones, and IR_JIT_DESTRUCTURE, IR_JIT_RANGE_SLICE, + IR_JIT_SPLAT_LITERAL and IR_UNKEPT_LIB off at once): 1,375 same, 116 baseline, 14 DIFF, the two known ones: + regexp-binary-ctype as at round 12; string-race-matrix over five runs of each tree (rows not always ok 109 -> 89, + lost writes 105 -> 1). The one lost write is `=~` against `encode!`; round 8's new build lost two, `scan` against + `encode!`, and the other rounds none: a rare race in encode! that the round did not bring (a lead). The one row + failing only on the new build, `index` against `slice!` of the front, fails on master in earlier rounds. + A probe file for the round - one-value destructuring hot and then of an Array subclass (no to_ary), nil, an + object with to_ary, a short Array and a non-Array; range slices hot and then a non-ASCII String, past the end, + negative, broken bytes and a String subclass; splatted Array literals hot and then nil, a Hash, a Range, an Array + subclass, a String and a Struct; seven rescued library errors kept and read (class, message, a backtrace and its + locations), $! in an ensure, 1/0 rescued 200 times and then one read; defined?(super) at the top level, + alias_method of a zsuper name, autoload?(name, false), Marshal of a Time of year 0 and 1850 and a recursive + _dump; sum and take_while hot - prints CRuby's output with the JIT on and off, with the round's switches off and + on the R2R host. Master aborts on the recursive _dump (a stack overflow, the crash claude/cruby-test fixed). + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against round 12: method JIT 88 up, nothing down; light frames unchanged. + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.905 and 0.891; none more + than 5% slower in both. micro-table in both orders: no line more than 5% slower in both. On the R2R host + (core-small, three rounds, against master): sum_blk 0.83, take_while 0.89, drop_while 0.88, inject 0.93, + each_slice 0.97 (perf/aotosr). + Start-up on the composite R2R host, best of ten alternating, two runs, base -> new ms: `-e 1` 404 -> 362 and + 397 -> 352, `gem --version` 463 -> 452 and 449 -> 463, `gem list` 870 -> 785 and 873 -> 763, `require "irb"` + 863 -> 769 and 849 -> 779, irb 1+1 939 -> 877 and 943 -> 923: 0.87-0.98 (`gem --version` 1.03 in one run). - **Gate of 2026-11-29 for round 12 of round thirty-seven** (perf/crubydiff's twenty-first and twenty-second rounds with the attr_* source locations reconciled with claude/cruby-test's, claude/cruby-test's rounds 5-7 (test/ruby 6,660 -> 6,676 passing), perf/yieldloop2 and perf/yieldloop3, perf/ignoredblock with literalcode's census reason and @@ -2081,7 +2114,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 366 -> 349, `gem --version` 466 -> 437 and 441 -> 412, `gem list` 864 -> 725 and 811 -> 709, `require "irb"` 888 -> 739 and 854 -> 774, irb 1+1 973 -> 869 and 966 -> 821: 0.83-0.96. - **perf/aotosr (2026-11-29) - the startup library's defs with a loop are compiled from source where OSR is on (gap 18 - on the shipped host)** - not gated. The R2R host (what `./ir.sh` picks when it is newest, and the release download) + on the shipped host)** - gated 2026-11-29 (round 13's gate entry). The R2R host (what `./ir.sh` picks when it is newest, and the release download) runs the startup library, IronRuby.Startup.dll, which the compiler makes with `SavePath` set: `AstGenerator. CanReplaceLoops` is false there (an OsrLoopSite is a runtime object), so every `while`/`until` in ruby4.rb, rubygems and the rest ran in generic code for good, and stage 3a's copies (sum, take_while, drop_while) never ran on @@ -2107,7 +2140,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the R2R host: 11,733 examples, the same counts on both. IronRuby.Tests (Debug, the whole suite): PASSED. - **perf/yieldloop3 (2026-11-29) - Array#sum with a block: its Integer case in a loop of its own that the compiled copy - runs (gap 18)** - not gated. `__array_sum__`'s loop could not be compiled: its tail has `next`, `return`, calls and a + runs (gap 18)** - gated 2026-11-29 (round 12's gate entry). `__array_sum__`'s loop could not be compiled: its tail has `next`, `return`, calls and a nested `while true` with a second yield. The common case, Integers all along, now has a loop of its own in front of it (`x = yield(__ary_at__(i)); i = i.succ; break unless ::Integer === x && ::Integer === acc; acc = acc + x; j = i`): it leaves at the first value that is not an Integer (or once acc is not one, as a redefined Integer#+ can make it), @@ -2132,7 +2165,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the whole suite was not run (the session's permission check refuses it). - **perf/yieldloop2 (2026-11-29) - the prelude's `take_while` and `drop_while` run in their loops' compiled copies (gap - 18, stage 3a's own measure)** - not gated. Stage 3a's design names its measure as the prelude's `while ... yield` + 18, stage 3a's own measure)** - gated 2026-11-29 (round 12's gate entry). Stage 3a's design names its measure as the prelude's `while ... yield` methods, which round one did not reach. Of the prelude's 16 loops with one yield, 6 have it as a statement, 3 as a condition (`break unless yield(x)`), 7 in an expression; the hot iterators (`take_while`, `sum`, `to_h`, `uniq`) all stopped first at `__ary_size__`. Chosen over stage 3's method resume, which my design round measured at about 2% @@ -2193,7 +2226,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 856 -> 727 and 817 -> 726, irb 1+1 894 -> 807 and 954 -> 828: 0.83-0.98. - **perf/unkept2 (round thirty-seven, 2026-11-29) - more library errors defer their catch-site walk: division by zero, EOFError, - frozen objects, `chr`'s RangeError (gap 22)** - time, not gated. perf/unkept's second round. `1 / 0` and `1 % 0` were not + frozen objects, `chr`'s RangeError (gap 22)** - time, gated 2026-11-29 (round 13's gate entry). perf/unkept's second round. `1 / 0` and `1 % 0` were not thrown by a site at all: `Integer#/` and `#%` on two Fixnums divided and let the CLR raise its DivideByZeroException. They now test the divisor and throw a marked one with the CRuby message ("divided by 0", as the CLR's was mapped to), as the Float overload already did. And 61 sites that throw what they have just made are marked (`RubyExceptionData.Unkept`, one line @@ -2215,7 +2248,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has in full on Debug: PASSED. - **perf/unkept (round thirty-seven, 2026-11-29) - errors that rules and a few library methods throw defer their catch-site - walk, as Kernel#raise's do (gap 22)** - time, not gated. A rescued `[].fetch(1)` cost 23.8-28.8 us against a rescued + walk, as Kernel#raise's do (gap 22)** - time, gated 2026-11-29 (round 13's gate entry). A rescued `[].fetch(1)` cost 23.8-28.8 us against a rescued `raise` in Ruby's 5.4-6.0 (CRuby 1.0 and 0.8). dotnet-trace (sampled thread time): `StackTrace..ctor` and `StackFrameHelper.InitializeSourceInfo` under `CanRescueDeferTrace` -> `CaptureExceptionTrace` -> `CaptureTrace`, the eager catch-site walk of the whole CLR stack. Deferring that walk until the exception is exposed (`TryDeferCatchSite`) is only for an @@ -2257,7 +2290,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has redefined to keep its block (each call's Proc its own), back, and a deopt: CRuby's output with the JIT on and off. ruby/spec language in full: 2935 examples, the one known error (send_spec's `into`/`to`). IronRuby.Tests in full on Debug: PASSED. -- **perf/jitsplatlit (2026-11-29, census and timed, not gated) - `[*a, x]` Array literals in the method JIT's typed +- **perf/jitsplatlit (2026-11-29, census and timed, gated 2026-11-29 (round 13's gate entry)) - `[*a, x]` Array literals in the method JIT's typed body** (the census's SplattedArgument: 42 methods refused by it alone; switch `IR_JIT_SPLAT_LITERAL`). Built on perf/jitslice 7e258de. - **Choosing it.** The splats left are nearly all in Array literals: `[*@fixed, Type::Builtin::VARARGS]`, @@ -2284,7 +2317,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has output on both builds (40 runs with jit-splatlit). ruby/spec language/array and core/array/constructor: no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. -- **perf/jitslice (2026-11-29, census and timed, not gated) - `s[a..b]` and `ary[a...b]` in the method JIT's typed body** +- **perf/jitslice (2026-11-29, census and timed, gated 2026-11-29 (round 13's gate entry)) - `s[a..b]` and `ary[a...b]` in the method JIT's typed body** (the census's RangeExpression: 47 first refusals, 32 alone; switch `IR_JIT_RANGE_SLICE`). Built on perf/jitmasgn1 530202d. - **Choosing it.** After parallel assignment, the refusals keeping the most methods out alone are interpolation @@ -2316,7 +2349,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has element_reference and slice, core/array element_reference and slice: no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. -- **perf/jitmasgn1 (2026-11-29, census and timed, not gated) - `a, b = v` of an Array in the method JIT's typed body** +- **perf/jitmasgn1 (2026-11-29, census and timed, gated 2026-11-29 (round 13's gate entry)) - `a, b = v` of an Array in the method JIT's typed body** (the census's ParallelAssignmentExpression: 367 first refusals, 67 alone; switch `IR_JIT_DESTRUCTURE`). Built on perf/jitdefined 67ac8ea. - **Choosing it.** Of the refusals that keep the most methods out on their own, StringLiteral (82) and From 9242a1ee0f2e58a74a1d8caefffe24f660ddfcfc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 05:48:36 +0000 Subject: [PATCH 438/439] Ledger: drop the orphaned header round 14's merge left of perf/jitsplatlit's entry Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 102a3b589..780d555ff 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2339,8 +2339,6 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has redefined to keep its block (each call's Proc its own), back, and a deopt: CRuby's output with the JIT on and off. ruby/spec language in full: 2935 examples, the one known error (send_spec's `into`/`to`). IronRuby.Tests in full on Debug: PASSED. -- **perf/jitsplatlit (2026-11-29, census and timed, gated 2026-11-29 (round 13's gate entry)) - `[*a, x]` Array literals in the method JIT's typed - - **perf/jitcvarcache (2026-11-29, timed, not gated) - the method JIT's class variable sites keep the module they found the variable in** (switch `IR_JIT_CVAR_CACHE`). Built on perf/jitcvar f89b479. No census change: it makes the accesses jitcvar compiled cheaper, which the ledger entry below named as the next step. @@ -2422,7 +2420,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has jit-symeq). ruby/spec core/symbol, basicobject and kernel equal_value: no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. -- **perf/jitsplatlit (2026-11-29, census and timed, not gated) - `[*a, x]` Array literals in the method JIT's typed +- **perf/jitsplatlit (2026-11-29, census and timed, gated 2026-11-29 (round 13's gate entry)) - `[*a, x]` Array literals in the method JIT's typed body** (the census's SplattedArgument: 42 methods refused by it alone; switch `IR_JIT_SPLAT_LITERAL`). Built on perf/jitslice 7e258de. - **Choosing it.** The splats left are nearly all in Array literals: `[*@fixed, Type::Builtin::VARARGS]`, From 16dd2a9e11a2834591b5cdb4a7a88e01755c9b6b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:50:36 +0000 Subject: [PATCH 439/439] Ledger: round 14's gate, PASS; a start-up cost of perf/aotosr found Round 14 of round thirty-seven (perf/crubydiff's rounds 23-24, claude/cruby-test's rounds 11-14, perf/unkept3 and perf/enoent, perf/jitsymeq and perf/jitcvar with its cache, at 9242a1ee against master c4719ea) passed the gate: IronRuby.Tests 1,511 run, none failed; the matrices in seven modes with only the two known DIFFs; a probe file for the round as CRuby in three modes; ruby/spec's five suites with no unlisted failure; the census with 99 method-JIT ups and nothing down; AWFY 12 at a geomean of 0.900 and 0.913. gem list's start-up is level with master again, where round 13 had it at 0.87-0.90: perf/aotosr compiles a startup-library def with a loop from source at its first call, nine of them for gem list now. perf/dmethjit is to move that compile behind its tier-up. The round's entries are marked gated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KPwZf72QWuzxr68CADMiwZ --- Util/perf/LEDGER.md | 52 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 780d555ff..eaecbbe47 100644 --- a/Util/perf/LEDGER.md +++ b/Util/perf/LEDGER.md @@ -2053,6 +2053,46 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ## Landed +- **Gate of 2026-11-29 for round 14 of round thirty-seven** (perf/crubydiff's twenty-third and twenty-fourth rounds - + defined?'s interned String, Array#sum and Enumerable#sum without a redefined Integer#+ reconciled with perf/yieldloop3's + front loop, operator frames, chilled literals at every frozen check, read_nonblock's buffer; claude/cruby-test's + rounds 11-14 - test/ruby 6,684 -> 6,724 passing; perf/unkept3 and perf/enoent; perf/jitsymeq, perf/jitcvar and + perf/jitcvarcache with the cvar lookup's prepend order): the branch at 9242a1ee against master c4719ea, Release + net10.0, the composite R2R host on both, four cores: **PASS**, with one finding on start-up (below). Gated in a + worktree of its own and pushed after. + The merge itself, five files by hand: MutableString.RequireNotFrozen takes perf/crubydiff's chilled check with + perf/unkept's mark on its FrozenError; JitCompiler keeps perf/jitslice's range slice and drops the `.freeze' form of + defined? the bridge no longer writes; RubyEncoder and RubyTimeOps keep claude/cruby-test's code (pack's + format-modified check, Time#_dump of any year) with perf/unkept3's marks; RubyModule's class variable lookup does + both claude/cruby-test's f68873f (a singleton class's own table, then its class's - cvar_front_klass) and + perf/jitbody's 5eed1f3 (a class before its prepends), in TryResolveClassVariableNoRaise, which the read and the + method JIT share - checked against CRuby on both and on an extended module's variable. The ledger left + perf/jitsplatlit's gated header orphaned (fixed, 9242a1ee, by a new scratch fixer for that pattern). + ReflectionCache.Generated.cs is what ClassInitGenerator writes. No new DLR patch. + IronRuby.Tests (`parallel-tests.sh`, Debug): 1,511 tests, every one executed, none failed. + `gate-matrices.rb --all` in 7 modes (the six default ones, and IR_JIT_CLASS_VARIABLES, IR_JIT_CVAR_CACHE, + IR_JIT_SYMBOL_EQ, IR_NATIVE_MISSING and IR_UNKEPT_LIB off at once): 1,396 same, 116 baseline, 14 DIFF, the two known + ones (regexp-binary-ctype as at round 12; string-race-matrix over five runs of each tree: rows not always ok 107 -> + 87, lost writes 99 -> 0; `=~` and `rindex` against `slice!` of the front, the two rows failing only on the new + build, fail on master in earlier rounds). + A probe file for the round - defined?'s String (identity, US-ASCII, frozen), sum with a redefined Integer#+, + FrozenError's frames for an operator `<<` and a sent one, String#lines in UTF-16LE, a frozen $0, const_get's + const_missing, shareable_constant_value literal, Symbol-literal comparisons and class variables hot (through a + subclass, and overtaken after warm-up), File.open of a missing file and ENOTDIR, a rescued Errno kept and read, a + thread's error joined twice, read_nonblock with nothing to read - prints CRuby's output with the JIT on and off and + with the round's switches off (master: 16 lines). On the R2R host one row differs: a sent `<<` loses its + 'String#<<' frame, as it does on master's R2R host - the startup library's frames, perf/crubydiff's lead. + ruby/spec, all five suites (32,285 examples): no failure the known list does not name. + Census against round 13: method JIT 99 up, light frames 1 up, nothing down. + AWFY, 8 iterations: all fourteen verify. AWFY 12 in both orders: geomean new/base 0.900 and 0.913; none more than + 5% slower in both (CD 0.948 and 1.068). micro-table in both orders: no line more than 5% slower in both. + The finding, start-up on the composite R2R host (best of ten alternating, four runs): `-e 1` 0.88-0.92, `require + "irb"` 0.86-0.92, irb 1+1 0.88-0.98, but `gem list` 0.98-1.02 and `gem --version` 0.98-1.05, where round 13 had + 0.87-0.90 and 0.93-0.98. None of the round's switches gives it back; -X:NoOSR does (gem list 0.86 of master's): + perf/aotosr (round 13) compiles a startup-library def that has a loop from source at its first call, and gem list + now runs nine of them (rubygems' Version#<=> and #release, optparse's parse_in_order, the prelude's + __array_select_bang__, each_line, rstrip, to_h, uniq...), about 50 ms. Level with master rather than worse; perf/dmethjit + is to fold the from-source compile into its tier-up (counted calls, not the first one). - **Gate of 2026-11-29 for round 13 of round thirty-seven** (claude/cruby-test's rounds 8-10 - test/ruby 6,676 -> 6,684 passing, perf/aotosr, perf/unkept and perf/unkept2, perf/jitmasgn1, perf/jitslice and perf/jitsplatlit): the branch at 7cde67ee against master c4719ea, Release net10.0, the composite R2R host on both, four cores: **PASS**. @@ -2228,7 +2268,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has 856 -> 727 and 817 -> 726, irb 1+1 894 -> 807 and 954 -> 828: 0.83-0.98. - **perf/enoent (round thirty-seven, 2026-11-29) - on Linux, `File.open` of a path that is not there asks faccessat(2) before - the CLR's open (gap 22)** - time, not gated. A rescued `File.open("/nonexistent/zz")` cost 56 us against CRuby's 3.4: the + the CLR's open (gap 22)** - time, gated 2026-11-29 (round 14's gate entry). A rescued `File.open("/nonexistent/zz")` cost 56 us against CRuby's 3.4: the FileStream threw DirectoryNotFoundException (or FileNotFoundException), the CLR's own frames threw it again, and `RubyFile.OpenFileStream` then threw the Errno. Now, for a read-only open (FileMode.Open) on the operating system's file system (the PlatformAdaptationLayer itself or the console host's, not a host's own), `faccessat(AT_FDCWD, full path, F_OK, @@ -2250,7 +2290,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has IronRuby.Tests in full on Debug: PASSED. - **perf/unkept3 (round thirty-seven, 2026-11-29) - every library error made and thrown at once defers its catch-site walk; - the places that keep an exception clear the mark; `read_nonblock` raises once (gap 22)** - time, not gated. The third round of + the places that keep an exception clear the mark; `read_nonblock` raises once (gap 22)** - time, gated 2026-11-29 (round 14's gate entry). The third round of perf/unkept. (1) `RubyExceptionData.MarkKept`, called where an exception is kept to be handed to Ruby again: a thread's at its exit (re-raised by every `Thread#join` and `#value`), Ractor's, Fiddle's callback error, MessagePack's, MiniSsl's, OpenSSL's verify callback's, the C API's pending one, and StackGuard's two captures. It resolves a pending catch site and clears @@ -2339,7 +2379,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has redefined to keep its block (each call's Proc its own), back, and a deopt: CRuby's output with the JIT on and off. ruby/spec language in full: 2935 examples, the one known error (send_spec's `into`/`to`). IronRuby.Tests in full on Debug: PASSED. -- **perf/jitcvarcache (2026-11-29, timed, not gated) - the method JIT's class variable sites keep the module they found +- **perf/jitcvarcache (2026-11-29, timed, gated 2026-11-29 (round 14's gate entry)) - the method JIT's class variable sites keep the module they found the variable in** (switch `IR_JIT_CVAR_CACHE`). Built on perf/jitcvar f89b479. No census change: it makes the accesses jitcvar compiled cheaper, which the ledger entry below named as the next step. - **What.** `RubyContext.ClassVariableVersion` moves when a class variable is added to or removed from any module, a @@ -2366,7 +2406,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has ruby/spec language/class_variable, core/module class_variable_get, _set, _defined, class_variables, remove_class_variable, prepend and include: no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. -- **perf/jitcvar (2026-11-29, census and timed, not gated) - `@@x` and `@@x = v` in the method JIT's typed body** (the +- **perf/jitcvar (2026-11-29, census and timed, gated 2026-11-29 (round 14's gate entry)) - `@@x` and `@@x = v` in the method JIT's typed body** (the census's ClassVariable: 44 methods refused by it alone, 197 rows naming it; switch `IR_JIT_CLASS_VARIABLES`). Built on perf/jitsymeq ce6bb18. - **What.** A read goes through `JitRuntime.ClassVariableRead`, a write through `ClassVariableWrite`, from the @@ -2392,7 +2432,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has the switch off. jit, jit-calls, jit-const, jit-objops, jit-defined and hot-shapes in the same five modes: CRuby's output on both builds (35 runs with jit-cvar). ruby/spec language/class_variable and core/module class_variable_get, _set, _defined, class_variables, remove_class_variable: no failures on either build. IronRuby.Tests (Debug), all 1,441: PASSED. -- **perf/jitsymeq (2026-11-29, census and timed, not gated) - a comparison with a Symbol literal in the method JIT's +- **perf/jitsymeq (2026-11-29, census and timed, gated 2026-11-29 (round 14's gate entry)) - a comparison with a Symbol literal in the method JIT's typed body** (the census's SymbolLiteral: 21 methods refused by it alone; switch `IR_JIT_SYMBOL_EQ`). Built on perf/jitsplatlit e34abb3. - **Choosing it, and what was passed over.** The constants left (40 alone) are nearly all dynamic lookups, `self::X` @@ -4969,7 +5009,7 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has both. - **perf/crubydiff (round thirty-seven, 2026-11-26) - differences from CRuby, not speed** - not - gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's), its eleventh to fifteenth 2026-11-28 (round 10's), its sixteenth to twentieth 2026-11-29 (round 11's), its twenty-first and twenty-second 2026-11-29 (round 12's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. + gated when merged; gated 2026-11-27 (round 5's gate entry), its third and fourth rounds 2026-11-28 (round 6's), its fifth and sixth 2026-11-28 (round 7's), its seventh 2026-11-28 (round 8's), its eighth to tenth 2026-11-28 (round 9's), its eleventh to fifteenth 2026-11-28 (round 10's), its sixteenth to twentieth 2026-11-29 (round 11's), its twenty-first and twenty-second 2026-11-29 (round 12's), its twenty-third and twenty-fourth 2026-11-29 (round 14's); one commit each, every one with CRuby 4.0's output as a registered IronRuby.Tests case. - `Class#new` handed a library `initialize` (Struct's, Array's) the caller's scope, whose refinements then reached it: `Util/struct-matrix.rb`'s `UsingRefine.make` (after 200 calls, when the rule was compiled) and an Array subclass from the first call. The inner site now takes no scope