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/0112-compile-rewriter.patch b/Build/dlr-patches/0112-compile-rewriter.patch new file mode 100644 index 000000000..b7b877ea7 --- /dev/null +++ b/Build/dlr-patches/0112-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..61f101069 100644 --- a/Build/dlr-patches/README.md +++ b/Build/dlr-patches/README.md @@ -33,6 +33,8 @@ 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. | +| `0112-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/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/Docs/block-calling-convention.md b/Docs/block-calling-convention.md new file mode 100644 index 000000000..185c16526 --- /dev/null +++ b/Docs/block-calling-convention.md @@ -0,0 +1,270 @@ +# A block that is not a Proc until it escapes: design + +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 +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 | + +## 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). + +### 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. + +**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/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md index fddd4cd43..ff1d92034 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 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 method JIT. @@ -377,3 +378,316 @@ 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 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 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) + +**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`. + +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 `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: +`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/Docs/light-frame-literal-blocks.md b/Docs/light-frame-literal-blocks.md new file mode 100644 index 000000000..d54fb96f9 --- /dev/null +++ b/Docs/light-frame-literal-blocks.md @@ -0,0 +1,177 @@ +# 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 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). + +## 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. + +## 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. + +## 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 + (`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/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/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/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..17577c900 --- /dev/null +++ b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs @@ -0,0 +1,461 @@ +/* **************************************************************************** + * + * 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 { + internal static long ProtoNew; + 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 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 } + 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_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 +"; + + 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; + }); + + // ---- 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", "ept", "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; + 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 {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) { + 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); + 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 {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 + // 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/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index fe0f92281..37568ca10 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -63,6 +63,8 @@ public Tests(Driver/*!*/ driver) { MutableString_SliceAppend1, MutableString_SipHash1, MutableString_WideBrokenLength1, + MutableString_RegexpSetModified1, + MutableString_EachLineModifiedSeparator1, RubyArray_Ctors, RubyArray_Basic, RubyArray_Add, @@ -149,6 +151,10 @@ public Tests(Driver/*!*/ driver) { Scenario_Globals3, Scenario_InspectRecursive1, Scenario_InspectObjectId1, + Scenario_DescriptionEncoding1, + Scenario_DescriptionEncoding2, + Scenario_DescriptionEncoding3, + Scenario_DescriptionEncoding4, Scenario_RubyMethodMissing1, Scenario_RubyMethodMissing2, @@ -169,6 +175,9 @@ public Tests(Driver/*!*/ driver) { String_CharacterBoundaries1, String_NonCharacter1, String_SuccSeparators1, + String_AppendFrozenFirst1, + String_ChilledNoOpBang1, + String_AppendFrozenAnyArgument1, String_CountDeleteSqueeze1, String_CountDeleteSqueeze2, String_CountDeleteSqueeze3, @@ -180,6 +189,7 @@ public Tests(Driver/*!*/ driver) { IO_PopenDuplexBytes1, IO_PipeWithoutPipe2, File_AppendBytes1, + File_PathUnderAsciiLocale1, File_WriteBytes1, File_ReadLine1, File_LoadBufferOffset1, @@ -211,6 +221,14 @@ public Tests(Driver/*!*/ driver) { Regex_LiteralEncodings1, Regex_PropertyEncoding1, Regex_BinaryCtype1, + Regex_CaseFoldGroups1, + Regex_TimeoutNanoseconds1, + Regex_Latin1Ctype1, + StringScanner_InsideCharacter1, + StringScanner_ShorterSubject1, + StringScanner_LiteralEncoding1, + StringScanner_DotOnSplitByte1, + StringScanner_NegatedClassOnSplitByte1, Regex_InspectResultEncoding1, Regex_EscapedByteEncoding1, Regex_EscapedByteEncoding2, @@ -319,6 +337,7 @@ public Tests(Driver/*!*/ driver) { RubyBlocks14A, RubyBlocks14B, RubyBlocks14C, + UnusedBlock_LaterDefinition1, RubyBlocks16, RubyBlocks18, @@ -363,6 +382,7 @@ public Tests(Driver/*!*/ driver) { MethodToProc1, DefineMethod1, DefineMethod2, + DefineMethodEquality1, DefineMethodBlockBreak1, ProcPosition1, @@ -413,6 +433,9 @@ public Tests(Driver/*!*/ driver) { FloatObjectId1, JitCensus1, BlockLoopEachIndex1, + OsrYieldLoop1, + OsrYieldLoop2, + OsrYieldLoop3, BlockLoopNested1, RangeConditionInclusive1, @@ -449,6 +472,7 @@ public Tests(Driver/*!*/ driver) { Array_SplatBlockYield1, Array_NumericSumMinShift1, Array_SumFloatInit1, + Array_SumRedefinedPlus1, Enumerable_TallyGroupBy1, Enumerable_ZipEnumerated1, IListOps_EnumerateRecursively1, @@ -547,9 +571,14 @@ public Tests(Driver/*!*/ driver) { Require_PathLoadedDependency6, Require_UnreadableExtensions1, Require_UnreadableExtensions2, + Require_EncTransShims1, + Require_NonAsciiFeatureBytes1, + Load_WrappedMainVisibility1, + Autoload_QueryNotInherited1, CaseEquals1, CaseEquals2, CaseEquals3, + CaseEquals4, ComparableEqual1, Hooks1, Hooks2, @@ -594,6 +623,8 @@ public Tests(Driver/*!*/ driver) { ClrScopedExtensions8, ClrOverloadInheritance1, LibraryInitializerOverloadAttributes1, + LibraryCopiedModuleAttributes1, + ClrFieldAndEventNamesFromMetadata1, ClrOverloadInheritance2, ClrOverloadInheritance3, ClrOverloadInheritance4, @@ -847,9 +878,13 @@ public Tests(Driver/*!*/ driver) { Exception_RescueRefinedCaseEquality1, ClassVariables1, + ClassVariables_DefinedOvertaken1, + ClassVariables_Refinement1, UnqualifiedConstants2, AliasMethodLookup1, + AliasRedefinitionWarningLine1, + AliasTopLevelWarnsOnce1, AliasMethodLookup3, UndefMethodLookup1, @@ -877,6 +912,8 @@ public Tests(Driver/*!*/ driver) { DefineMethodVisibility1, DefineMethodVisibility2B, AliasedMethodVisibility1, + AliasVisibilityKeepsAlias1, + MethodRedefinitionWarningMessage1, AttributeAccessorsVisibility1, AttributeAccessorsVisibility2, ModuleFunctionVisibility1, @@ -887,6 +924,7 @@ public Tests(Driver/*!*/ driver) { MethodDefinitionInModuleEval1A, MainSingleton1, + SingletonClass_ToS1, MainSingleton2, Singletons1A, Singletons1B, @@ -922,6 +960,8 @@ public Tests(Driver/*!*/ driver) { Refinements13, Refinements14, Refinements15, + Refinements16, + Refinements17, Super1, SuperParameterless1, @@ -930,6 +970,7 @@ public Tests(Driver/*!*/ driver) { SuperParameterless3, SuperParameterlessKeywordRest1, SuperMethodForwarder1, + Super_ArgumentsBeforeBlockArgument1, SuperKeywordSplat1, SuperKeywordRestPassOn1, SuperParameterlessKeywordRest2, @@ -939,6 +980,7 @@ public Tests(Driver/*!*/ driver) { SuperToAttribute1, SuperAndMethodMissing1, SuperAndMethodMissing2, + SuperAndMethodMissing3, SuperCaching1, SuperInBlocks1, SuperInDefineMethod1, @@ -963,6 +1005,8 @@ public Tests(Driver/*!*/ driver) { DefinedOperator_Yield1, DefinedOperator_Locals1, DefinedOperator_Super1, + DefinedOperator_Parens1, + DefinedOperator_SuperOutsideMethod1, Scenario_ModuleOps_Methods, InstanceMethods_NotInherited1, @@ -971,10 +1015,19 @@ public Tests(Driver/*!*/ driver) { HiddenConstants1, PreludeHiddenState1, ExtendMany1, + ConstSet_AsciiIncompatibleName1, + ClassVariable_SingletonOfClass1, + ConstSet_FrozenSingletonReceiver1, Scenario_MainSingleton, Time_LoadZone1, Time_DumpLoadedZone1, Time_MachineZone1, + Time_StrftimeColon1, + Time_StrftimeNoZone1, + Date_ZoneToDiffUt1, + Date_StrptimeEncoding1, + Date_StrptimeSubclass1, + Date_ParseDayFirst1, Time_OlsonZone1, Zlib_Streams1, Process_SpawnKill1, @@ -987,6 +1040,36 @@ public Tests(Driver/*!*/ driver) { Fiddle_AnsiSuffix1, PackPointer_RealAddress1, PackPointer_RelineWin32Api1, + Pack_FloatOfNonNumeric1, + Unpack_AtEnd1, + String_UndumpUnknownEscapes1, + Warning_UndefinedWarn1, + Warning_InstanceMethods1, + Encoding_UnicodeVersion1, + Marshal_ProcPartialObject1, + Marshal_TimeAnyYear1, + Marshal_RecursiveUserDef1, + Eval_WarningLineBelowOne1, + Kernel_SystemExceptionMessage1, + AtExit_ErrinfoAfterExit1, + String_LinesWideBrokenSeparator1, + String_ChilledWarningChangesReceiver1, + Process_SetrlimitValueName1, + Process_ClockGetresInvalid1, + Process_GroupsArgumentChecks1, + Process_SpawnRedirectOpenFailure1, + Globals_ProgramNameFrozen1, + Process_ClockGetresHertz1, + Process_StatusMarshal1, + Process_SpawnShellAssignment1, + Process_UidGidReExchangeable1, + Module_ConstGetPathConstMissing1, + Argf_SeekOpensNextFile1, + Argf_ReadAtEndBuffer1, + Argf_NonStringArgv1, + Compiler_ShareableConstantValue1, + Compiler_ShareableConstantValue2, + Library_NestedDefinitionConflict1, IoConsole_WinsizeOffTerminal1, Ripper_Filter1, Require_ExtensionByLibraryName1, @@ -1003,8 +1086,15 @@ public Tests(Driver/*!*/ driver) { Puma_Tls1, Sprintf_MriTieRounding1, Sprintf_CharacterBytes1, + Sprintf_CharacterSingleByte1, Float_NegativeZero1, Math_CLibrary1, + Math_LogBaseAndOrder1, + Float_DivmodInfinite1, + Rational_CoerceAndDivmod1, + Kernel_IntegerSignOnlyAndInspect1, + Kernel_RationalComplexSpecialMessage1, + Sprintf_MalformedEnd1, Errno_MessageNotDoubled1, Process_ClockGetTime1, Process_ThreadCpuTime1, @@ -1024,6 +1114,13 @@ public Tests(Driver/*!*/ driver) { Backtrace_RaiseInRescue1, Backtrace_RedefinedSetBacktrace1, Backtrace_ArityCalleeFrame1, + Backtrace_SendHidden1, + Backtrace_CallLine1, + Backtrace_InterpolatedLocalLine1, + Backtrace_CompiledModuleBody1, + Backtrace_LocationEncoding1, + Backtrace_NonAsciiLabelFrame1, + Eval_FileNameEncoding1, Backtrace_RaiseInEnsure1, Backtrace_CompiledLoopLine1, Backtrace_CompiledLoopLineFrameReleased1, @@ -1031,13 +1128,19 @@ public Tests(Driver/*!*/ driver) { Enumerator_ExternalCursor1, Enumerator_ExternalFiber1, Enumerator_LazyEachResult1, + Enumerator_LazyAncestors1, Enumerator_ChainNoNext1, + Enumerator_SingletonAfterInstanceVariable1, + Enumerator_ToEnumSize1, Io_Messages1, Encoding_Misc1, Encoding_List1, Encoding_InvalidBytes1, Encoding_Converter1, Encoding_Converter2, + Encoding_ErrorMessageBinary1, + Encoding_ConvPathDecoratorBinary1, + Module_NameEncoding1, Encoding_StatelessIso2022Jp1, Encoding_AsciiIncompatible1, Encoding_AsciiIncompatibleLines1, @@ -1047,15 +1150,18 @@ public Tests(Driver/*!*/ driver) { Marshal_LoadFloat1, Marshal_SetIVars1, Marshal_NameError1, + Marshal_ExceptionBtLocations1, Marshal_LoadChecks1, Integer_SqrtPowDigits1, Prelude_DataStructErrors1, + Prelude_DataUndefinedAllocator1, Prelude_AliasNames1, Visibility_DefaultScope1, Main_PrivateAndInitializeCopy1, Module_CopyInvalidatesConstantLookups1, Kernel_PutsToStdoutWriter1, Prelude_HiddenHelpers1, + Kernel_StringCheckFuncall1, Prelude_HiddenState1, Prelude_HiddenState2, SyntaxError_MessageLocation1, @@ -1093,6 +1199,7 @@ public Tests(Driver/*!*/ driver) { Io_LineReaders2, Io_LineReaders3, Io_UngetcConverted1, + Io_WriteViaAsciiCompat1, Io_GetsLongLineFromPipe1, Io_UnreadPushedBack1, Io_WideLineReaders1, @@ -1105,6 +1212,8 @@ public Tests(Driver/*!*/ driver) { DidYouMean_LazyThreads1, DidYouMean_LazyRequire1, NameError_LocalVariables1, + NameError_MessageEncoding1, + Exception_DetailedMessageEncoding1, ErrorHighlight_Spots1, ErrorHighlight_Report1, ErrorHighlight_Threads1, @@ -1112,6 +1221,11 @@ public Tests(Driver/*!*/ driver) { Kernel_ConversionsInjectZip1, Kernel_ConversionsRoundingStep1, Method_OptionalAndKeywordParameters1, + Method_BindingNonRubyCaller1, + Method_UnbindForwarder1, + Method_ToProcSourceLocation1, + Method_InternalSourceLine1, + Eval_InstanceEvalSpecialVariables1, Method_OptionalAndKeywordParameters2, Range_MinMaxInclude1, Integer_StepMatchString1, @@ -1122,10 +1236,17 @@ public Tests(Driver/*!*/ driver) { Rational_CSharp1, Complex_CSharp1, Rational_ComplexConventions1, + Rational_StringEncoding1, Method_LightFrame1, Method_LightFrame2, Block_RegisterLocals1, + TracePoint_EndlessDefLine1, + TracePoint_AttrAccessorCCall1, + Float_OutOfRangeMessage1, + Float_RoundDigitsRange1, + Enumerable_SortByOwnPush1, Defined_ConditionNoFreeze1, + Defined_FrozenUsAsciiString1, Block_OptionalBeforeRest1, LoweredRaise_IgnoresOwnRaise1, Review212_1, @@ -1137,6 +1258,19 @@ public Tests(Driver/*!*/ driver) { Method_LightFrameBlockGuard1, Method_LightFrameBlockGiven1, Method_LightFrameRest1, + Method_LightFrameMemberOpAssign1, + Method_LightFrameLambda1, + Method_LightFrameMatchSink1, + Method_LightFrameMatchSinkRetention1, + Method_LightFrameKeywordRest1, + Method_KeywordHashIntoRest1, + Method_Ruby2KeywordsExplicitSplat1, + Struct_Ruby2KeywordsHash1, + Method_KeywordRestTakeover1, + Method_KeywordRestJit1, + Method_KeywordPrologue1, + Method_LightFrameGlobal1, + Method_LightFrameLexical1, Method_ParkedScope1, Method_ParkedScopeLeak1, Method_LightFrameBlockPass1, @@ -1177,10 +1311,14 @@ public Tests(Driver/*!*/ driver) { Block_ReturnTraceFrameCleanup1, Thread_SetTraceFunc1, Fiber_ReclamationClrBoundary1, + Fiber_OwnSpecialVariables1, Fiber_Keywords1, WeakMap_NoBlock1, Fiber_ThreadRaiseReachesRunningFiber1, Thread_HandleInterruptOtherRuntime1, + Thread_BlockedMethodFrame1, + SizedQueue_OwnMethods1, + SizedQueue_Subclass1, Thread_HandleInterruptInherited1, Thread_HandleInterruptIoWrite1, Thread_RaiseBetweenBlockCallsMeetsRescue1, @@ -1202,11 +1340,19 @@ public Tests(Driver/*!*/ driver) { Methods1, MethodDef1, MethodInspect_LibraryParameters1, + MethodInspect_Encoding1, + MethodInspect_Modules1, + Method_SourceLocationInLibraryFile1, + Method_SourceLocationOfAttributes1, + Methods_OwnedByClass1, MethodArity_CoreMethods1, MethodArity_LibraryArguments1, MethodArity_PreludeMethods1, MethodDef_SymbolInBody1, KeywordsOmitted1, + DefineMethodCallee1, + CurrentMethod_ClassBody1, + AttrAccessor_SourceLocation1, ToIntegerConversion1, Kernel_IntegerFloat1, Kernel_FloatOptions1, @@ -1229,6 +1375,7 @@ public Tests(Driver/*!*/ driver) { ErrorMessages_Ruby40, MethodAliasExpression, AliasUndefWithQuotedSymbols, + Alias_SuperForwarderWithoutTarget1, BasicObject1, BasicObject2, ClassDuplication1, @@ -1243,6 +1390,8 @@ public Tests(Driver/*!*/ driver) { Clone1, Dup1, CloneConstantLookup1, + ModuleCopyBeforeInitializeCopy1, + MatchDataInitializeCopyFrozen1, Structs1, MetaModules1, MetaModulesDuplication1, @@ -1270,6 +1419,9 @@ public Tests(Driver/*!*/ driver) { Binding1, TopLevelBinding_RubyProgram, EvalWithProcBinding1, + Eval_LocalVariableSites1, + Eval_SharedDefined1, + Eval_SharedLiterals1, ModuleEvalProc1, ModuleEvalProc2, ModuleEvalProc3, @@ -1285,6 +1437,7 @@ public Tests(Driver/*!*/ driver) { ModuleEvalString2, InstanceEvalString2, ModuleInstanceEvalString3, + EvalSourceEncoding1, AliasInModuleEval1, MethodAliasInModuleEval1, SuperInModuleEval1, @@ -1323,6 +1476,7 @@ public Tests(Driver/*!*/ driver) { Backtrace_AsciiLocalePaths1, Backtrace_LibraryErrors1, Backtrace_PreludeCallerSkip1, + Backtrace_OperatorFrames1, Dlr_RubySnippet, Dlr_ClrSubtype, @@ -1375,10 +1529,16 @@ public Tests(Driver/*!*/ driver) { Continuation_CrossThread1, RbConfig_ExecutableExts1, IOBuffer_ExperimentalWarning1, + IOBuffer_Values1, + IOBuffer_CopyAndMasks1, + File_FnmatchEscapedInBracket1, + File_FnmatchNullPattern1, + IO_ReadNonblockKeepsBuffer1, Array_Cycle1, Range_Recursive1, Array_JoinRecursive1, Array_JoinNested1, + Pack_FormatModifiedTrailing1, Array_RangeLongEnd1, Array_DuckRangeIndex1, Array_HashRecursiveElement1, @@ -1389,6 +1549,7 @@ public Tests(Driver/*!*/ driver) { Hash_FetchErrorEllipsis1, Hash_InitializeCopyIsReplace1, Hash_UpdateStringKey1, + Hash_StringSubclassKey1, Hash_EqlHashRehash1, Enumerable_PatternUnusedBlockWarning1, Enumerable_PredicatePattern1, @@ -1411,6 +1572,9 @@ public Tests(Driver/*!*/ driver) { String_ToIntAsciiIncompatible1, String_UndumpUnicodeEncoding1, String_OrdWide1, + Integer_ChrSingleByte1, + String_TranslateCheckOrder1, + String_EncodeKeywordOptionsOnly1, Integer_ChrMultibyte1, String_Cesu8_1, String_EmacsMule1, @@ -1426,6 +1590,8 @@ public Tests(Driver/*!*/ driver) { Kernel_IsAModuleRequired1, Struct_InspectMemberNames1, Integer_BitwiseCoerce1, + Integer_FDivCoerced1, + Integer_RemainderCoerced1, Comparison_AnonymousClassName1, }; } diff --git a/Src/IronRuby.Tests/Runtime/AliasTests.cs b/Src/IronRuby.Tests/Runtime/AliasTests.cs index 54ffba2ef..677205e6b 100644 --- a/Src/IronRuby.Tests/Runtime/AliasTests.cs +++ b/Src/IronRuby.Tests/Runtime/AliasTests.cs @@ -136,6 +136,45 @@ 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); + } + + /// + /// 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. /// @@ -310,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/IronRuby.Tests/Runtime/ArrayTests.cs b/Src/IronRuby.Tests/Runtime/ArrayTests.cs index a6d5097f4..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, @@ -678,6 +726,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/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/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index a38775df0..32a0f64a5 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. @@ -2432,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/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/IronRuby.Tests/Runtime/CloningTests.cs b/Src/IronRuby.Tests/Runtime/CloningTests.cs index da88fb02b..af5011fa5 100644 --- a/Src/IronRuby.Tests/Runtime/CloningTests.cs +++ b/Src/IronRuby.Tests/Runtime/CloningTests.cs @@ -184,6 +184,70 @@ 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 +[] +# +"); + } + + /// + /// 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/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/IronRuby.Tests/Runtime/DefinedTests.cs b/Src/IronRuby.Tests/Runtime/DefinedTests.cs index bb40f9118..d3bf64359 100644 --- a/Src/IronRuby.Tests/Runtime/DefinedTests.cs +++ b/Src/IronRuby.Tests/Runtime/DefinedTests.cs @@ -342,6 +342,50 @@ 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 +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/EnumeratorTests.cs b/Src/IronRuby.Tests/Runtime/EnumeratorTests.cs index ca1f38584..2dd366c1e 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' @@ -209,6 +240,71 @@ 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 +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/ErrorReportingTests.cs b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs index 8230e6891..28c2c4979 100644 --- a/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs +++ b/Src/IronRuby.Tests/Runtime/ErrorReportingTests.cs @@ -202,6 +202,51 @@ 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 +", @" +# +# +# +# +# +# +# +# +# +"); + } + + /// + /// 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 @@ -339,6 +384,345 @@ 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 ""]] +"); + } + + /// + /// 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 +"); + } + + /// + /// 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 '
'""] +"); + } + + /// + /// 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 +"); + } + + /// + /// 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 +"); + } + + /// + /// 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. + /// + 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. + /// + 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/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/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index 72e8b2969..37540a40c 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))); @@ -121,6 +168,90 @@ 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 +"); + } + + /// + /// 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, + /// 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/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/IronRuby.Tests/Runtime/IntegerTests.cs b/Src/IronRuby.Tests/Runtime/IntegerTests.cs index 63e6c9a47..f05a760fc 100644 --- a/Src/IronRuby.Tests/Runtime/IntegerTests.cs +++ b/Src/IronRuby.Tests/Runtime/IntegerTests.cs @@ -1603,6 +1603,56 @@ 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 +# +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index 2a03b3cc5..60f4b2e4d 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; @@ -839,6 +865,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 @@ -1068,6 +1133,184 @@ 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! +"); + } + + /// + /// 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). + /// + 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 +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/LibraryInitializerTests.cs b/Src/IronRuby.Tests/Runtime/LibraryInitializerTests.cs index 61b940e5d..29e800f4b 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,52 @@ 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); + } + + /// + /// 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/IronRuby.Tests/Runtime/LoaderTests.cs b/Src/IronRuby.Tests/Runtime/LoaderTests.cs index 79b7b4320..bb4ca5ede 100644 --- a/Src/IronRuby.Tests/Runtime/LoaderTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoaderTests.cs @@ -519,5 +519,90 @@ 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 +"); + } + + /// + /// 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 +"); + } + + /// + /// 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 +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/LoopTests.cs b/Src/IronRuby.Tests/Runtime/LoopTests.cs index 9dac20ca2..256da6d64 100644 --- a/Src/IronRuby.Tests/Runtime/LoopTests.cs +++ b/Src/IronRuby.Tests/Runtime/LoopTests.cs @@ -353,6 +353,128 @@ 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 + /// 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, + /// 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 @@ -864,6 +986,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 +1007,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/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 04bb2df05..8b54321fb 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1403,6 +1403,55 @@ 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 +[] +"); + } + + /// + /// "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. /// @@ -1646,6 +1695,120 @@ 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 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 +", @" +# +# +# +# +# +"); + } + + /// + /// 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 +"); + } + + /// + /// 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] +"); + } + + /// + /// 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 @@ -1856,6 +2019,94 @@ 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]] +"); + } + + /// + /// __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 +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 19e10dfbc..94b3ef5d8 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -64,6 +64,98 @@ 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 +", @" +# +# +# +# +# +# +# +# +# +"); + } + + /// + /// 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 +", @" +# +# +# +# +# +# +# +"); + } + + /// + /// 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 +", @" +# +# +# +# +# +# +# +# +# +"); + } + + /// + /// 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... ...>". /// @@ -846,6 +938,67 @@ 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"" +"); + } + + /// + /// 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(@" @@ -887,6 +1040,141 @@ 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% +"); + } + + /// + /// 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|"" +""|"" +"); + } + + /// + /// 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) +"); + } + + /// + /// 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 $!)) +", @" +# +# +# +# +# +"); + } + + /// + /// 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] +"); + } + + /// + /// 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 @@ -1971,7 +2259,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 @@ -1993,6 +2281,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 @@ -2058,6 +2386,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) "); } @@ -2992,6 +3367,82 @@ 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"" +"); + } + + /// + /// 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 +", @" +[#] +[#] +# +# +# +"); + } + + /// + /// 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 @@ -3641,6 +4092,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, @@ -3755,6 +4238,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 @@ -4046,6 +4559,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 @@ -5726,6 +6276,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, @@ -6009,30 +6578,197 @@ public void Range_MinMaxInclude1() { } /// - /// 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 - /// into place before the defaults run, in the generic body and in the JIT's entry (the loop at the - /// end runs the methods specialized). Arity errors name the positionals and required keywords as - /// MRI does, and #parameters lists required keywords first. The expected output is CRuby's. + /// 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_OptionalAndKeywordParameters1() { + public void Method_BindingNonRubyCaller1() { TestOutput(@" require 'ruby4' -def t(l); r = begin; yield; rescue => e; [e.class, e.message]; end; puts ""#{l}: #{r.inspect}""; end -def m1(a, b = 2, k: 3) = [a, b, k] -def m2(a, b = 2, c = a + b, k: 3, j:) = [a, b, c, k, j] -def m3(a, b = {x: 1}, **kw) = [a, b, kw] -def m4(b = 1, k: 2) = [b, k] -def m5(a, b = nil, exception: true) = [a, b, exception] -t(1) { [m1(1), m1(1, 5), m1(1, k: 9), m1(1, 5, k: 9)] } -t(2) { m1(1, {k: 9}) } -t(3) { m1(1, 5, {k: 9}) } -t(4) { m1(1, 5, 6) } -t(5) { m1(k: 1) } -t(6) { m1() } -t(7) { m1(1, z: 2) } -t(8) { [m2(1, j: 0), m2(1, 4, j: 0), m2(1, 4, 5, j: 0, k: 7)] } -t(9) { m2(1, 4) } +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 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] +"); + } + + /// + /// 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 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 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 + /// into place before the defaults run, in the generic body and in the JIT's entry (the loop at the + /// end runs the methods specialized). Arity errors name the positionals and required keywords as + /// MRI does, and #parameters lists required keywords first. The expected output is CRuby's. + /// + public void Method_OptionalAndKeywordParameters1() { + TestOutput(@" +require 'ruby4' +def t(l); r = begin; yield; rescue => e; [e.class, e.message]; end; puts ""#{l}: #{r.inspect}""; end +def m1(a, b = 2, k: 3) = [a, b, k] +def m2(a, b = 2, c = a + b, k: 3, j:) = [a, b, c, k, j] +def m3(a, b = {x: 1}, **kw) = [a, b, kw] +def m4(b = 1, k: 2) = [b, k] +def m5(a, b = nil, exception: true) = [a, b, exception] +t(1) { [m1(1), m1(1, 5), m1(1, k: 9), m1(1, 5, k: 9)] } +t(2) { m1(1, {k: 9}) } +t(3) { m1(1, 5, {k: 9}) } +t(4) { m1(1, 5, 6) } +t(5) { m1(k: 1) } +t(6) { m1() } +t(7) { m1(1, z: 2) } +t(8) { [m2(1, j: 0), m2(1, 4, j: 0), m2(1, 4, 5, j: 0, k: 7)] } +t(9) { m2(1, 4) } t(10) { m2(1, 4, 5, 6, j: 0) } t(11) { [m3(1), m3(1, z: 2), m3(1, {y: 2}), m3(1, {y: 2}, z: 3), m3(1, **{})] } t(12) { h = {k: 7}; [m1(1, **h), m1(1, 2, **h), m4, m4(5), m4(k: 6), m4(5, k: 6), m4({k: 6})] } @@ -7310,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 @@ -7710,658 +8471,2462 @@ p method(:rest).arity, method(:lead).arity, method(:rest).parameters } /// - /// 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 #** - /// take any real exponent and a precision, round takes half:, and a BigDecimal is frozen and has no - /// public constructor. + /// 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 BigDecimal_Ruby4_1() { + public void Method_LightFrameMatchSink1() { TestOutput(@" require 'ruby4' -require 'bigdecimal' -def t(label) - r = begin; v = yield; v.is_a?(BigDecimal) ? v.to_s : v.inspect; rescue => e; ""#{e.class}: #{e.message}""; end - puts ""#{label}: #{r}"" +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 -t('==') { BigDecimal('0.5') == Rational(1, 2) } -t('<=>') { BigDecimal('0.5') <=> Rational(1, 3) } -t('r+') { Rational(1, 3) + BigDecimal('0.5') } -t('div') { BigDecimal('1').div(Rational(1, 3), 5) } -t('power') { BigDecimal('2').power(BigDecimal('0.5'), 20) } -t('**') { BigDecimal('4') ** Rational(1, 2) } -t('round') { BigDecimal('1.25').round(1, half: :even) } -t('quo') { BigDecimal('1').quo(3, 5) } -t('sqrt') { BigDecimal('-2').sqrt(10) } -t('frozen') { BigDecimal('1').frozen? } -t('new') { BigDecimal.new('1') } -t('allocate') { BigDecimal.allocate } -t('_dump') { BigDecimal('1.5')._dump } -t('BASE') { BigDecimal::BASE.class } -z = %w[-0 0 NaN Infinity -Infinity 1.5].map { |s| BigDecimal(s) } -t('specials') { z.product(z).map { |x, y| [x + y, x * y, x / y, x <=> y].map { |v| v.is_a?(BigDecimal) && v.zero? ? v.sign : v.to_s } }.flatten.join(',') } -t('x/inf raises') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_INFINITY, true); BigDecimal('1') / BigDecimal('Infinity') } } -", @" -==: true -<=>: 1 -r+: 0.83333333333333333333333333333333e0 -div: 0.3e1 -power: 0.14142135623730950488e1 -**: 0.2e1 -round: 0.12e1 -quo: 0.33333e0 -sqrt: FloatDomainError: sqrt of negative value -frozen: true -new: NoMethodError: undefined method 'new' for class BigDecimal -allocate: TypeError: allocator undefined for BigDecimal -_dump: ""18:0.15e1"" -BASE: Integer -specials: ""-1,1,NaN,0,1,-1,NaN,0,NaN,NaN,NaN,,Infinity,NaN,-1,-1,-Infinity,NaN,1,1,0.15e1,-1,-1,-1,1,-1,NaN,0,1,1,NaN,0,NaN,NaN,NaN,,Infinity,NaN,1,-1,-Infinity,NaN,-1,1,0.15e1,1,1,-1,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,Infinity,NaN,-Infinity,1,Infinity,NaN,Infinity,1,NaN,NaN,NaN,,Infinity,Infinity,NaN,0,NaN,-Infinity,NaN,1,Infinity,Infinity,Infinity,1,-Infinity,NaN,Infinity,-1,-Infinity,NaN,-Infinity,-1,NaN,NaN,NaN,,NaN,-Infinity,NaN,-1,-Infinity,Infinity,NaN,0,-Infinity,-Infinity,-Infinity,-1,0.15e1,-1,-Infinity,1,0.15e1,1,Infinity,1,NaN,NaN,NaN,,Infinity,Infinity,1,-1,-Infinity,-Infinity,-1,1,0.3e1,0.225e1,0.1e1,0"" -x/inf raises: FloatDomainError: Computation results in 'Infinity' +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"" "); } /// - /// The BigDecimal engine (sign, BigInteger digits and exponent) against CRuby 4.0's bigdecimal 4.0.1: - /// Float conversion as MRI's dtoa does it (shortest digits cut to 16; mode 2's rounding quirk), - /// parsing, to_s formats, round's ROUND_UP quirk, BigDecimal.limit, division precision, divmod and - /// remainder, the exception modes, precision/scale, sqrt's Newton iteration, and an exponent beyond Int32. + /// 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 BigDecimal_Engine1() { + public void Method_LightFrameMatchSinkRetention1() { TestOutput(@" -require 'ruby4' -require 'bigdecimal' -def t(label) - r = begin; v = yield; v.is_a?(BigDecimal) ? v.to_s : v.inspect; rescue => e; ""#{e.class}: #{e.message}""; end - puts ""#{label}: #{r}"" +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 -t('float') { [BigDecimal(0.1 + 0.2), BigDecimal(2.0**70), BigDecimal(1.25, 2), BigDecimal(4.383733694592053e-09, 14)].join(' ') } -t('float+') { BigDecimal('1') + (0.1 + 0.2) } -t('parse') { %w[1_000 1_ 5. .5 1e5 1E-5 1d2 +1.5 -0].map { |s| BigDecimal(s).to_s }.join(' ') } -t('parse spaces') { BigDecimal("" 1.5 \n"") } -t('invalid') { %w[_1 1__2 1.5x 1e . 1e_5].map { |s| BigDecimal(s, exception: false).inspect }.join(' ') } -t('loose') { ['1.5x', '_1', '1 2', '12e', '0x1f'].map { |s| BigDecimal.interpret_loosely(s).to_s }.join(' ') } -t('huge exponent') { [BigDecimal('1e3000000000').exponent, (BigDecimal('1e3000000000') * BigDecimal('1e3000000000')).exponent].inspect } -t('exponent overflow') { BigDecimal('1e99999999999999999999') } -t('to_s') { [BigDecimal('-1234567.891').to_s('3F'), BigDecimal('0.000123').to_s('+2F'), BigDecimal('1234.5').to_s(' 2E'), BigDecimal('1e10').to_s('F')].inspect } -t('to_s 0') { BigDecimal('1').to_s(0) } -t('round up') { [BigDecimal('0.04').round(-1, :up), BigDecimal('0.0004').round(1, :up), BigDecimal('-0.04').round(1)].join(' ') } -t('round modes') { %w[up down half_up half_down half_even ceiling floor].map { |m| BigDecimal('-2.5').round(0, m.to_sym).to_s }.join(' ') } -t('round nil') { BigDecimal('1.5').round(nil) } -t('round string mode') { BigDecimal('1.5').round(0, 'up') } -t('limit') { BigDecimal.save_limit { BigDecimal.limit(5); [BigDecimal('1.23456789') + 1, BigDecimal('1') / 3, BigDecimal('1.23456789') * 1, BigDecimal('1.23456789').add(0, 3)].join(' ') } } -t('div') { [BigDecimal('1') / 3, BigDecimal('1').div(3, 5), BigDecimal('2').div(3, 0), BigDecimal('7').div(2), BigDecimal('-7').divmod(2)].map(&:to_s).join(' ') } -t('remainder') { [BigDecimal('-7').remainder(2), BigDecimal('7') % -2, BigDecimal('1e100') % 3].join(' ') } -t('mode') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_INFINITY, true); BigDecimal.mode(BigDecimal::EXCEPTION_NaN) } } -t('divmod nan mode') { BigDecimal.save_exception_mode { i = BigDecimal('-Infinity'); BigDecimal.mode(BigDecimal::EXCEPTION_NaN, true); i.divmod(1) } } -t('precision') { %w[0 1e20 1e-20 123.456 -0.001].map { |s| x = BigDecimal(s); [x.precision, x.scale, x.n_significant_digits, x.exponent] }.inspect } -t('shift') { [BigDecimal('1.5')._decimal_shift(3), BigDecimal('1.5')._decimal_shift(-12)].join(' ') } -t('sqrt') { [BigDecimal('2').sqrt(20), BigDecimal('4').sqrt(0), BigDecimal('0.01').sqrt(5)].join(' ') } -t('sqrt down') { BigDecimal.save_rounding_mode { BigDecimal.mode(BigDecimal::ROUND_MODE, :down); [BigDecimal('2').sqrt(10), BigDecimal('16').sqrt(3)].join(' ') } } -t('frac fix') { [BigDecimal('-1.5').frac, BigDecimal('-0.5').fix, BigDecimal('12').frac, BigDecimal('123.456').fix].join(' ') } -t('to_f') { [BigDecimal('1e400').to_f, BigDecimal('-1e-400').to_f, BigDecimal('0.1').to_f].inspect } -t('to_i') { [BigDecimal('-12.9').to_i, BigDecimal('1e20').to_i, BigDecimal('0.5').to_i].inspect } -t('hash') { [BigDecimal('0.1').hash == BigDecimal('0.10').hash, BigDecimal('1').eql?(BigDecimal('1.0'))].inspect } -t('coerce') { BigDecimal('1').add('x', 3) } -t('kernel') { [BigDecimal(Rational(1, 3), 0), BigDecimal(Complex(2, 0)), BigDecimal(nil, exception: false).inspect].join(' ') } -t('precision too large') { BigDecimal(1.5, 17) } -t('exception kwarg') { BigDecimal('1', exception: 1) } -t('identity') { a = BigDecimal('1.5'); [a.equal?(BigDecimal('1.50')), a.equal?(a), { a => 1 }[BigDecimal('1.50')]] } +refs = make +3.times { System::GC.Collect; System::GC.WaitForPendingFinalizers } +puts refs.count { |r| r.IsAlive } ", @" -float: ""0.3e0 0.1180591620717411e22 0.12e1 0.4383733694592e-8"" -float+: 0.13e1 -parse: ""0.1e4 0.1e1 0.5e1 0.5e0 0.1e6 0.1e-4 0.1e3 0.15e1 -0.0"" -parse spaces: 0.15e1 -invalid: ""nil nil nil nil nil nil"" -loose: ""0.15e1 0.0 0.1e1 0.12e2 0.0"" -huge exponent: ""[3000000001, 6000000001]"" -exponent overflow: Infinity -to_s: ""[\""-1 234 567.891\"", \""+0.00 01 23\"", \"" 0.12 34 5e4\"", \""10000000000.0\""]"" -to_s 0: ArgumentError: argument must be positive -round up: ""0.0 0.1e0 -0.0"" -round modes: ""-0.3e1 -0.2e1 -0.3e1 -0.2e1 -0.2e1 -0.2e1 -0.3e1"" -round nil: TypeError: no implicit conversion from nil to integer -round string mode: TypeError: no implicit conversion of String into Integer -limit: ""0.22346e1 0.33333e0 0.12346e1 0.123e1"" -div: ""0.33333333333333333333333333333333e0 0.33333e0 0.66666666666666666666666666666667e0 3 [-4, 0.1e1]"" -remainder: ""-0.1e1 -0.1e1 0.1e1"" -mode: 1 -divmod nan mode: FloatDomainError: Computation results in 'NaN' (Not a Number) -precision: ""[[0, 0, 0, 0], [21, 0, 1, 21], [20, 20, 1, -19], [6, 3, 6, 3], [3, 3, 1, -2]]"" -shift: ""0.15e4 0.15e-11"" -sqrt: ""0.14142135623730950488e1 0.2e1 0.1e0"" -sqrt down: ""0.1414213562e1 0.4e1"" -frac fix: ""-0.5e0 -0.0 0.0 0.123e3"" -to_f: ""[Infinity, -0.0, 0.1]"" -to_i: ""[-12, 100000000000000000000, 0]"" -hash: ""[true, true]"" -coerce: TypeError: String can't be coerced into BigDecimal -kernel: ""0.33333333333333333333333333333333e0 0.2e1 nil"" -precision too large: ArgumentError: precision too large. -exception kwarg: ArgumentError: expected true or false as exception: 1 -identity: [false, true, 1] +0 "); } /// - /// Exponents at the ends of MRI's 64-bit range: a scale (the exponent less the digit count) below - /// long.MinValue, and a product or quotient beyond either end, underflow or overflow as bigdecimal - /// 4.0.1 does instead of wrapping around to a huge exponent of the other sign. + /// 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 BigDecimal_ExponentLimits1() { + public void Method_LightFrameLambda1() { TestOutput(@" -require 'ruby4' -require 'bigdecimal' -def t(label) - r = begin; v = yield; v.is_a?(BigDecimal) ? v.to_s : v.inspect; rescue => e; ""#{e.class}: #{e.message}""; end - puts ""#{label}: #{r}"" +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 -tiny = BigDecimal('1e-9223372036854775800') -t('pow') { BigDecimal('1e-5000000000000000000') ** 2 } -t('mul') { tiny * BigDecimal('1e-100') } -t('div') { tiny / BigDecimal('1e100') } -t('mul over') { BigDecimal('1e9223372036854775700') * BigDecimal('1e1000') } -t('underflow mode') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_UNDERFLOW, true); tiny * BigDecimal('1e-100') } } -t('underflow mode div') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_UNDERFLOW, true); tiny / BigDecimal('1e100') } } -t('parse') { [BigDecimal('0.123456e-9223372036854775805'), BigDecimal('0.1e-9223372036854775808'), BigDecimal('17e-9223372036854775809')].join(' ') } -t('small ops') { x = BigDecimal('0.123456e-9223372036854775805'); [x / 3, x * 3, x + x, x.frac, BigDecimal('0.1e-9223372036854775807') / 10].join(' ') } -t('small dump') { BigDecimal('0.123456e-9223372036854775805')._dump } +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 ", @" -pow: 0.0 -mul: 0.0 -div: 0.0 -mul over: Infinity -underflow mode: FloatDomainError: Exponent underflow -underflow mode div: FloatDomainError: Exponent underflow -parse: ""0.123456e-9223372036854775805 0.1e-9223372036854775808 0.0"" -small ops: ""0.41152e-9223372036854775806 0.370368e-9223372036854775805 0.246912e-9223372036854775805 0.123456e-9223372036854775805 0.1e-9223372036854775808"" -small dump: ""18:0.123456e-9223372036854775805"" +30 +12 +-1 +7 +nil +""wrong number of arguments (given 1, expected 2)"" +[80, 39] "); } /// - /// BigDecimal#to_s and #split write a long digit string in pieces split at powers of ten (BigInteger.ToString - /// is quadratic); the pieces keep their leading zeros, at and around the split sizes. + /// `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 BigDecimal_LongDigits1() { + public void Method_LightFrameMemberOpAssign1() { TestOutput(@" require 'ruby4' -require 'bigdecimal' -srand(3) -ok = [1999, 2000, 2001, 4001, 9000, 20000].map do |d| - s = '1' + (1...d - 1).map { rand(10).to_s }.join + '7' +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 + /// (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"" +"); + } + + /// + /// 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 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 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 **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} +"); + } + + /// + /// 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). + /// + 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 +"); + } + + /// + /// 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] +"); + } + + /// + /// 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 +"); + } + + /// + /// 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 $_ + /// 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 +"); + } + + /// + /// 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 #** + /// take any real exponent and a precision, round takes half:, and a BigDecimal is frozen and has no + /// public constructor. + /// + public void BigDecimal_Ruby4_1() { + TestOutput(@" +require 'ruby4' +require 'bigdecimal' +def t(label) + r = begin; v = yield; v.is_a?(BigDecimal) ? v.to_s : v.inspect; rescue => e; ""#{e.class}: #{e.message}""; end + puts ""#{label}: #{r}"" +end +t('==') { BigDecimal('0.5') == Rational(1, 2) } +t('<=>') { BigDecimal('0.5') <=> Rational(1, 3) } +t('r+') { Rational(1, 3) + BigDecimal('0.5') } +t('div') { BigDecimal('1').div(Rational(1, 3), 5) } +t('power') { BigDecimal('2').power(BigDecimal('0.5'), 20) } +t('**') { BigDecimal('4') ** Rational(1, 2) } +t('round') { BigDecimal('1.25').round(1, half: :even) } +t('quo') { BigDecimal('1').quo(3, 5) } +t('sqrt') { BigDecimal('-2').sqrt(10) } +t('frozen') { BigDecimal('1').frozen? } +t('new') { BigDecimal.new('1') } +t('allocate') { BigDecimal.allocate } +t('_dump') { BigDecimal('1.5')._dump } +t('BASE') { BigDecimal::BASE.class } +z = %w[-0 0 NaN Infinity -Infinity 1.5].map { |s| BigDecimal(s) } +t('specials') { z.product(z).map { |x, y| [x + y, x * y, x / y, x <=> y].map { |v| v.is_a?(BigDecimal) && v.zero? ? v.sign : v.to_s } }.flatten.join(',') } +t('x/inf raises') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_INFINITY, true); BigDecimal('1') / BigDecimal('Infinity') } } +", @" +==: true +<=>: 1 +r+: 0.83333333333333333333333333333333e0 +div: 0.3e1 +power: 0.14142135623730950488e1 +**: 0.2e1 +round: 0.12e1 +quo: 0.33333e0 +sqrt: FloatDomainError: sqrt of negative value +frozen: true +new: NoMethodError: undefined method 'new' for class BigDecimal +allocate: TypeError: allocator undefined for BigDecimal +_dump: ""18:0.15e1"" +BASE: Integer +specials: ""-1,1,NaN,0,1,-1,NaN,0,NaN,NaN,NaN,,Infinity,NaN,-1,-1,-Infinity,NaN,1,1,0.15e1,-1,-1,-1,1,-1,NaN,0,1,1,NaN,0,NaN,NaN,NaN,,Infinity,NaN,1,-1,-Infinity,NaN,-1,1,0.15e1,1,1,-1,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,NaN,NaN,NaN,,Infinity,NaN,-Infinity,1,Infinity,NaN,Infinity,1,NaN,NaN,NaN,,Infinity,Infinity,NaN,0,NaN,-Infinity,NaN,1,Infinity,Infinity,Infinity,1,-Infinity,NaN,Infinity,-1,-Infinity,NaN,-Infinity,-1,NaN,NaN,NaN,,NaN,-Infinity,NaN,-1,-Infinity,Infinity,NaN,0,-Infinity,-Infinity,-Infinity,-1,0.15e1,-1,-Infinity,1,0.15e1,1,Infinity,1,NaN,NaN,NaN,,Infinity,Infinity,1,-1,-Infinity,-Infinity,-1,1,0.3e1,0.225e1,0.1e1,0"" +x/inf raises: FloatDomainError: Computation results in 'Infinity' +"); + } + + /// + /// The BigDecimal engine (sign, BigInteger digits and exponent) against CRuby 4.0's bigdecimal 4.0.1: + /// Float conversion as MRI's dtoa does it (shortest digits cut to 16; mode 2's rounding quirk), + /// parsing, to_s formats, round's ROUND_UP quirk, BigDecimal.limit, division precision, divmod and + /// remainder, the exception modes, precision/scale, sqrt's Newton iteration, and an exponent beyond Int32. + /// + public void BigDecimal_Engine1() { + TestOutput(@" +require 'ruby4' +require 'bigdecimal' +def t(label) + r = begin; v = yield; v.is_a?(BigDecimal) ? v.to_s : v.inspect; rescue => e; ""#{e.class}: #{e.message}""; end + puts ""#{label}: #{r}"" +end +t('float') { [BigDecimal(0.1 + 0.2), BigDecimal(2.0**70), BigDecimal(1.25, 2), BigDecimal(4.383733694592053e-09, 14)].join(' ') } +t('float+') { BigDecimal('1') + (0.1 + 0.2) } +t('parse') { %w[1_000 1_ 5. .5 1e5 1E-5 1d2 +1.5 -0].map { |s| BigDecimal(s).to_s }.join(' ') } +t('parse spaces') { BigDecimal("" 1.5 \n"") } +t('invalid') { %w[_1 1__2 1.5x 1e . 1e_5].map { |s| BigDecimal(s, exception: false).inspect }.join(' ') } +t('loose') { ['1.5x', '_1', '1 2', '12e', '0x1f'].map { |s| BigDecimal.interpret_loosely(s).to_s }.join(' ') } +t('huge exponent') { [BigDecimal('1e3000000000').exponent, (BigDecimal('1e3000000000') * BigDecimal('1e3000000000')).exponent].inspect } +t('exponent overflow') { BigDecimal('1e99999999999999999999') } +t('to_s') { [BigDecimal('-1234567.891').to_s('3F'), BigDecimal('0.000123').to_s('+2F'), BigDecimal('1234.5').to_s(' 2E'), BigDecimal('1e10').to_s('F')].inspect } +t('to_s 0') { BigDecimal('1').to_s(0) } +t('round up') { [BigDecimal('0.04').round(-1, :up), BigDecimal('0.0004').round(1, :up), BigDecimal('-0.04').round(1)].join(' ') } +t('round modes') { %w[up down half_up half_down half_even ceiling floor].map { |m| BigDecimal('-2.5').round(0, m.to_sym).to_s }.join(' ') } +t('round nil') { BigDecimal('1.5').round(nil) } +t('round string mode') { BigDecimal('1.5').round(0, 'up') } +t('limit') { BigDecimal.save_limit { BigDecimal.limit(5); [BigDecimal('1.23456789') + 1, BigDecimal('1') / 3, BigDecimal('1.23456789') * 1, BigDecimal('1.23456789').add(0, 3)].join(' ') } } +t('div') { [BigDecimal('1') / 3, BigDecimal('1').div(3, 5), BigDecimal('2').div(3, 0), BigDecimal('7').div(2), BigDecimal('-7').divmod(2)].map(&:to_s).join(' ') } +t('remainder') { [BigDecimal('-7').remainder(2), BigDecimal('7') % -2, BigDecimal('1e100') % 3].join(' ') } +t('mode') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_INFINITY, true); BigDecimal.mode(BigDecimal::EXCEPTION_NaN) } } +t('divmod nan mode') { BigDecimal.save_exception_mode { i = BigDecimal('-Infinity'); BigDecimal.mode(BigDecimal::EXCEPTION_NaN, true); i.divmod(1) } } +t('precision') { %w[0 1e20 1e-20 123.456 -0.001].map { |s| x = BigDecimal(s); [x.precision, x.scale, x.n_significant_digits, x.exponent] }.inspect } +t('shift') { [BigDecimal('1.5')._decimal_shift(3), BigDecimal('1.5')._decimal_shift(-12)].join(' ') } +t('sqrt') { [BigDecimal('2').sqrt(20), BigDecimal('4').sqrt(0), BigDecimal('0.01').sqrt(5)].join(' ') } +t('sqrt down') { BigDecimal.save_rounding_mode { BigDecimal.mode(BigDecimal::ROUND_MODE, :down); [BigDecimal('2').sqrt(10), BigDecimal('16').sqrt(3)].join(' ') } } +t('frac fix') { [BigDecimal('-1.5').frac, BigDecimal('-0.5').fix, BigDecimal('12').frac, BigDecimal('123.456').fix].join(' ') } +t('to_f') { [BigDecimal('1e400').to_f, BigDecimal('-1e-400').to_f, BigDecimal('0.1').to_f].inspect } +t('to_i') { [BigDecimal('-12.9').to_i, BigDecimal('1e20').to_i, BigDecimal('0.5').to_i].inspect } +t('hash') { [BigDecimal('0.1').hash == BigDecimal('0.10').hash, BigDecimal('1').eql?(BigDecimal('1.0'))].inspect } +t('coerce') { BigDecimal('1').add('x', 3) } +t('kernel') { [BigDecimal(Rational(1, 3), 0), BigDecimal(Complex(2, 0)), BigDecimal(nil, exception: false).inspect].join(' ') } +t('precision too large') { BigDecimal(1.5, 17) } +t('exception kwarg') { BigDecimal('1', exception: 1) } +t('identity') { a = BigDecimal('1.5'); [a.equal?(BigDecimal('1.50')), a.equal?(a), { a => 1 }[BigDecimal('1.50')]] } +", @" +float: ""0.3e0 0.1180591620717411e22 0.12e1 0.4383733694592e-8"" +float+: 0.13e1 +parse: ""0.1e4 0.1e1 0.5e1 0.5e0 0.1e6 0.1e-4 0.1e3 0.15e1 -0.0"" +parse spaces: 0.15e1 +invalid: ""nil nil nil nil nil nil"" +loose: ""0.15e1 0.0 0.1e1 0.12e2 0.0"" +huge exponent: ""[3000000001, 6000000001]"" +exponent overflow: Infinity +to_s: ""[\""-1 234 567.891\"", \""+0.00 01 23\"", \"" 0.12 34 5e4\"", \""10000000000.0\""]"" +to_s 0: ArgumentError: argument must be positive +round up: ""0.0 0.1e0 -0.0"" +round modes: ""-0.3e1 -0.2e1 -0.3e1 -0.2e1 -0.2e1 -0.2e1 -0.3e1"" +round nil: TypeError: no implicit conversion from nil to integer +round string mode: TypeError: no implicit conversion of String into Integer +limit: ""0.22346e1 0.33333e0 0.12346e1 0.123e1"" +div: ""0.33333333333333333333333333333333e0 0.33333e0 0.66666666666666666666666666666667e0 3 [-4, 0.1e1]"" +remainder: ""-0.1e1 -0.1e1 0.1e1"" +mode: 1 +divmod nan mode: FloatDomainError: Computation results in 'NaN' (Not a Number) +precision: ""[[0, 0, 0, 0], [21, 0, 1, 21], [20, 20, 1, -19], [6, 3, 6, 3], [3, 3, 1, -2]]"" +shift: ""0.15e4 0.15e-11"" +sqrt: ""0.14142135623730950488e1 0.2e1 0.1e0"" +sqrt down: ""0.1414213562e1 0.4e1"" +frac fix: ""-0.5e0 -0.0 0.0 0.123e3"" +to_f: ""[Infinity, -0.0, 0.1]"" +to_i: ""[-12, 100000000000000000000, 0]"" +hash: ""[true, true]"" +coerce: TypeError: String can't be coerced into BigDecimal +kernel: ""0.33333333333333333333333333333333e0 0.2e1 nil"" +precision too large: ArgumentError: precision too large. +exception kwarg: ArgumentError: expected true or false as exception: 1 +identity: [false, true, 1] +"); + } + + /// + /// Exponents at the ends of MRI's 64-bit range: a scale (the exponent less the digit count) below + /// long.MinValue, and a product or quotient beyond either end, underflow or overflow as bigdecimal + /// 4.0.1 does instead of wrapping around to a huge exponent of the other sign. + /// + public void BigDecimal_ExponentLimits1() { + TestOutput(@" +require 'ruby4' +require 'bigdecimal' +def t(label) + r = begin; v = yield; v.is_a?(BigDecimal) ? v.to_s : v.inspect; rescue => e; ""#{e.class}: #{e.message}""; end + puts ""#{label}: #{r}"" +end +tiny = BigDecimal('1e-9223372036854775800') +t('pow') { BigDecimal('1e-5000000000000000000') ** 2 } +t('mul') { tiny * BigDecimal('1e-100') } +t('div') { tiny / BigDecimal('1e100') } +t('mul over') { BigDecimal('1e9223372036854775700') * BigDecimal('1e1000') } +t('underflow mode') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_UNDERFLOW, true); tiny * BigDecimal('1e-100') } } +t('underflow mode div') { BigDecimal.save_exception_mode { BigDecimal.mode(BigDecimal::EXCEPTION_UNDERFLOW, true); tiny / BigDecimal('1e100') } } +t('parse') { [BigDecimal('0.123456e-9223372036854775805'), BigDecimal('0.1e-9223372036854775808'), BigDecimal('17e-9223372036854775809')].join(' ') } +t('small ops') { x = BigDecimal('0.123456e-9223372036854775805'); [x / 3, x * 3, x + x, x.frac, BigDecimal('0.1e-9223372036854775807') / 10].join(' ') } +t('small dump') { BigDecimal('0.123456e-9223372036854775805')._dump } +", @" +pow: 0.0 +mul: 0.0 +div: 0.0 +mul over: Infinity +underflow mode: FloatDomainError: Exponent underflow +underflow mode div: FloatDomainError: Exponent underflow +parse: ""0.123456e-9223372036854775805 0.1e-9223372036854775808 0.0"" +small ops: ""0.41152e-9223372036854775806 0.370368e-9223372036854775805 0.246912e-9223372036854775805 0.123456e-9223372036854775805 0.1e-9223372036854775808"" +small dump: ""18:0.123456e-9223372036854775805"" +"); + } + + /// + /// BigDecimal#to_s and #split write a long digit string in pieces split at powers of ten (BigInteger.ToString + /// is quadratic); the pieces keep their leading zeros, at and around the split sizes. + /// + public void BigDecimal_LongDigits1() { + TestOutput(@" +require 'ruby4' +require 'bigdecimal' +srand(3) +ok = [1999, 2000, 2001, 4001, 9000, 20000].map do |d| + s = '1' + (1...d - 1).map { rand(10).to_s }.join + '7' s[d / 3, d / 4] = '0' * (d / 4) x = BigDecimal(""0.#{s}e3"") [x.split[1] == s, x.to_s == ""0.#{s}e3"", x.to_s('F') == ""#{s[0, 3]}.#{s[3..]}"", (-x).to_s('5F').delete(' ') == ""-#{s[0, 3]}.#{s[3..]}""] end -p ok.flatten.uniq -p (BigDecimal('1e10000') + 1).to_s('F') == '1' + '0' * 9999 + '1.0' +p ok.flatten.uniq +p (BigDecimal('1e10000') + 1).to_s('F') == '1' + '0' * 9999 + '1.0' +", @" +[true] +true +"); + } + + /// + /// BasicObject#equal? is identity, separate from #== - a class whose == calls equal? + /// (Set#==) must not recurse through BaseEquals into its own ==. + /// + public void BasicObject_EqualIdentity1() { + TestOutput(@" +# Set#== in set.rb (not loadable here: no prelude) has this shape +class MySet + attr_reader :h + def initialize(*a); @h = {}; a.each { |x| @h[x] = true }; end + def ==(other); if self.equal?(other) then true elsif other.instance_of?(self.class) then @h == other.h else false end; end +end +class Eq; def ==(o); equal?(o); end; end +class Str < String; def ==(o); equal?(o); end; end +p MySet.new(1).equal?(MySet.new(1)), (s = MySet.new(1)).equal?(s), s == MySet.new(1) +e = Eq.new; p e.equal?(e), e.equal?(Eq.new), e == e, e == Eq.new +t = Str.new('a'); p t.equal?(t), t.equal?(Str.new('a')), 'a'.equal?('a') +p 1.equal?(1), 1.5.equal?(1.5), :a.equal?(:a), nil.equal?(nil), true.equal?(true) +p BasicObject.new.equal?(BasicObject.new) +p BasicObject.instance_method(:equal?) == BasicObject.instance_method(:==) +", @" +false +true +true +true +false +true +false +true +false +false +true +true +true +true +true +false +true +"); + } + + /// + /// RbConfig::CONFIG["EXECUTABLE_EXTS"] was missing, and CRuby's tool/lib/find_executable.rb splits it, which + /// stopped test_rubyoptions before its first test. configure sets it on Windows only. + /// + public void RbConfig_ExecutableExts1() { + TestOutput(@" +require 'rbconfig' +p RbConfig::CONFIG['EXECUTABLE_EXTS'].split | [RbConfig::CONFIG['EXEEXT']] +", Environment.OSVersion.Platform == PlatformID.Win32NT ? @"["".exe"", "".com"", "".cmd"", "".bat""]" : @"[""""]"); + } + + /// + /// all?, any?, none? and one? given a pattern and a block warn "given block not used" at the line that called + /// them, as MRI does. The prelude asked for the location two frames up, past the end of a top-level script's + /// backtrace, so the warning had none there, and named the wrong line inside a method. The pattern forms are + /// C# now (Enumerable.cs) and warn with ReportWarning at the running line, which ir writes to $stderr and + /// this host counts in its error sink, so what is checked here is that each call warns once. + /// + public void Enumerable_PatternUnusedBlockWarning1() { + TestOutput(@" +require 'ruby4' +a = [1, 2].all?(1) { } +def m + [1].none?(1) { } +end +b = m +c = (1..2).one?(1) { } +p a, b, c +", @" +false +false +true +", 0, 3); + } + + /// + /// Array#rotate and #rotate! take their count as a long (MRI's NUM2LONG): a count past an int still rotates, + /// one past a long is a RangeError, for an empty or a frozen Array too. + /// + public void Array_RotateLongCount1() { + TestOutput(@" +a = [1, 2, 3] +p a.rotate(2**40), a.rotate(-(2**40) - 1), a.dup.rotate!(2**40 + 1) +p((a.rotate(2**64) rescue $!.class), ([].rotate(2**64) rescue $!.class), ([].freeze.rotate!(2**64) rescue $!.class)) +", @" +[2, 3, 1] +[2, 3, 1] +[3, 1, 2] +RangeError +RangeError +RangeError +"); + } + + /// + /// Hash#transform_values transforms a copy of the receiver (rb_hash_transform_values): keys the block adds to + /// the receiver are not visited, and keys it deletes are still in the result. + /// + public void Hash_TransformValuesSnapshot1() { + TestOutput(@" +h = { a: 1, b: 2, c: 3 } +p h.transform_values { |v| h[:z] = 9; h.delete(:c); v * 2 }, h +i = { a: 1 } +p i.transform_values { |v| i.clear; v }, i +", @" +{a: 2, b: 4, c: 6} +{a: 1, b: 2, z: 9} +{a: 1} +{} +"); + } + + /// + /// String#lines with a separator reads the receiver's length after the search for the separator, which + /// switches a receiver held as bytes (after #bytesize or #getbyte) to characters: a length kept from + /// before counted bytes, and the copy of the last line ran past the end (review of #218). + /// + public void String_LinesAfterByteRead1() { + TestOutput(@" +require 'ruby4' +s = ""\u00E9\nab\n\u00FC""; s.bytesize +p s.lines(""\n"").map(&:bytes), s.lines(""\n"", chomp: true).map(&:bytes) +t = ""a\u00E9\r\nb\r\n""; t.getbyte(0) +p t.lines(""\r\n"").map(&:bytes), t.lines(chomp: true).map(&:bytes) +u = ""\u00E9\u00FCab\u00FC\u00FC""; u.bytesize +p u.lines(""\u00FC"").map(&:bytes), u.each_line(""\u00FC"").map(&:size) +", @" +[[195, 169, 10], [97, 98, 10], [195, 188]] +[[195, 169], [97, 98], [195, 188]] +[[97, 195, 169, 13, 10], [98, 13, 10]] +[[97, 195, 169], [98]] +[[195, 169, 195, 188], [97, 98, 195, 188], [195, 188]] +[2, 3, 1] +"); + } + + /// + /// Hash#dig asks a Hash or an Array whose #dig is redefined - in a subclass or on the object itself - whether it + /// has #dig, as it asks any other object, and does not ask one whose #dig is the built-in one, whatever its + /// respond_to? says (rb_obj_dig takes its short cut while rb_method_basic_definition_p). A #dig the program + /// defines in Array itself is a redefinition too. + /// + public void Hash_DigSubclass1() { + TestOutput(@" +require 'ruby4' +class H2 < Hash; def dig(*k) = [:over, k]; def respond_to?(m, priv = false) = m == :dig ? false : super; end +class A2 < Array; def dig(*k) = [:over, k]; def respond_to?(m, priv = false) = m == :dig ? false : super; end +class H3 < Hash; def dig(*k) = [:over, k]; end +p(({ a: H2.new }.dig(:a, 1) rescue $!.message), ({ a: A2.new }.dig(:a, 1, 2, 3, 4) rescue $!.message)) +p({ a: H3.new }.dig(:a, 1), { a: H3.new }.dig(:a, 1, 2, 3, 4), { a: H3[b: 1] }.dig(:a), { a: { b: [5, 6] } }.dig(:a, :b, 1)) +class H4 < Hash; def respond_to?(m, priv = false) = m == :dig ? false : super; end +class A4 < Array; def respond_to?(m, priv = false) = m == :dig ? false : super; end +p({ a: H4[:x, 3] }.dig(:a, :x), { a: A4[7, 8] }.dig(:a, 1)) +h = {}; def h.dig(*) = :over; def h.respond_to?(m, priv = false) = m == :dig ? false : super +g = { b: 1 }; def g.respond_to?(m, priv = false) = m == :dig ? false : super +p(({ a: h }.dig(:a, :b) rescue $!.class), { a: g }.dig(:a, :b)) +a = [5]; def a.respond_to?(m, priv = false) = m == :dig ? false : super +p({ a: a }.dig(:a, 0)) +class Array; alias_method :dig0, :dig; def dig(*) = :over; end +p(({ a: a }.dig(:a, 0) rescue $!.class), { a: [5] }.dig(:a, 0)) +", @" +""H2 does not have #dig method"" +""A2 does not have #dig method"" +[:over, [1]] +[:over, [1, 2, 3, 4]] +{b: 1} +6 +3 +8 +TypeError +1 +5 +TypeError +:over +"); + } + + /// + /// Hash#transform_values replaces each value where its entry is (rb_hash_stlike_foreach_with_replace), not through + /// its key: keys the block makes equal stay two entries. compare_by_identity carries over, the default does not. + /// + public void Hash_TransformValuesMutatedKey1() { + TestOutput(@" +require 'ruby4' +a = [1]; b = [2]; h = { a => 10, b => 20 } +r = h.transform_values { |v| b.replace([1]); v + 1 } +p r.size, r.to_a, h.size +k = { a: 1 }.compare_by_identity; k[""x"".dup] = 2; k[""x"".dup] = 3 +t = k.transform_values { |v| v * 10 } +p t, t.compare_by_identity?, Hash.new(5).merge(a: 1).transform_values { |v| v }.default +p({ a: 1, b: 2 }.transform_values { |v| break :out if v == 2; v }, { nil => 1 }.transform_values { |v| v + 1 }) +", @" +2 +[[[1], 11], [[1], 21]] +2 +{a: 10, ""x"" => 20, ""x"" => 30} +true +nil +:out +{nil => 2} +"); + } + + /// + /// The KeyError of Hash#fetch may leave its backtrace until a rescue exposes it only while nothing can have kept + /// it. A TracePoint on :raise or on :c_call (which sees it being initialized) that keeps it and disables itself, + /// and a KeyError.new of the program's that keeps it and removes itself, all have: read after the rescuing frame + /// is gone, the backtrace is still the raise's. + /// + public void Hash_FetchKeptKeyError1() { + TestOutput(@" +require 'ruby4' +H = {} +def f1 = H.fetch(:x) +def g1 = (begin; f1; rescue KeyError; nil; end) +20000.times { g1 } +kept = nil +tp = TracePoint.new(:raise) { |t| kept = t.raised_exception; t.disable } +tp.enable +g1 +tp.disable +p kept.class, kept.backtrace.map { |l| l[/'(.*)'/, 1] } +seen = nil +tc = TracePoint.new(:c_call) { |t| if KeyError === t.self then seen = t.self; t.disable end } +tc.enable +g1 +tc.disable +p seen.backtrace.map { |l| l[/'(.*)'/, 1] } +made = nil +make = KeyError.method(:new) +KeyError.define_singleton_method(:new) { |*a| made = make.call(*a); KeyError.singleton_class.send(:remove_method, :new); made } +g1 +p(made.nil? || made.backtrace.none? { |l| l.include?('Exception#backtrace') }) +", @" +KeyError +[""Hash#fetch"", ""Object#f1"", ""Object#g1"", ""
""] +[""Hash#fetch"", ""Object#f1"", ""Object#g1"", ""
""] +true +"); + } + + /// + /// The pattern forms of all?, any?, none? and one? are C# overloads, not prelude wrappers: the pattern's #=== + /// is called as MRI's rb_funcall calls it, a private one included; an Array walks itself and does not call + /// #each; and a later Array#any? (prepended here, run hot) still takes over. + /// + public void Enumerable_PredicatePattern1() { + TestOutput(@" +require 'ruby4' +class Pat; private def ===(o) = o == 2; end +class A < Array; def each = raise('each called'); end +def f(a) = [a.any? { |x| x > 2 }, a.any?(Pat.new), a.all?(Integer), a.none?(2..2), a.one?(3)] +r = [] +3000.times do |i| + r << f(i < 2000 ? [1, 2, 3] : A[1, 2, 3]) + Array.prepend(Module.new { def any?(*, &) = :redef }) if i == 2500 +end +p r.tally +p({a: 1}.any?(Array), (1..4).one?(4), [[1, 2]].all? { |a, b| b == 2 }) +b = [] +p A[1, 2].one? { |x| x }, A[1, nil].one?, A[nil, 2].one? { |x| x }, A[1, 2].one? { |x| break :brk } +p [1, 2].one? { |x| b << x; b.size < 4 ? (b << 9; false) : false }, b +", @" +{[true, true, true, false, true] => 2501, [:redef, :redef, true, false, true] => 499} +true +true +true +false +true +true +:brk +false +[1, 9, 2, 9] +"); + } + + /// + /// Enumerable#tally given a BasicObject to count into raises MRI's TypeError: the prelude asked it #nil? and + /// #is_a?, which a BasicObject does not answer, and raised NoMethodError. + /// + public void Enumerable_TallyBasicObject1() { + TestOutput(@" +require 'ruby4' +p(([1].tally(BasicObject.new) rescue $!), ((1..2).tally(BasicObject.new) rescue $!), ([1].tally(Object.new) rescue $!)) +p [1, 1].tally({1 => 1}), (1..2).tally +", @" +# +# +# +{1 => 3} +{1 => 1, 2 => 1} +"); + } + + /// + /// inject(:op) calls the operator publicly, as MRI's rb_funcallv_public does since [Bug #13592]: a private #+ + /// is a NoMethodError, for an Array's fast path too. + /// + public void Enumerable_InjectPrivateOp1() { + TestOutput(@" +require 'ruby4' +k = Class.new { include Enumerable; def each; yield 1; yield 2; yield 3; end } +%i[+ *].each do |op| + begin + Integer.class_eval { private op } + p((k.new.inject(op) rescue $!), ([1, 2, 3].inject(op) rescue $!), ((1..3).inject(op) rescue $!)) + ensure + Integer.class_eval { public op } + end +end +p k.new.inject(:+), [1, 2, 3].inject(:+), [1, 2, 3].inject(10, :*) +", @" +# +# +# +# +# +# +6 +6 +60 +"); + } + + /// + /// A Range is an 'o' record of excl, begin and end, and a subclass's instance variables go in an "I" wrapper + /// around it, as MRI writes them; they were written into the record and lost on loading. The range is in the + /// link table before its ends are read (range_loader), so one that is its own begin and end comes back as one. + /// + public void Marshal_RangeRecord1() { + TestOutput(@" +class MyRange < Range; def initialize(v, *args) super(*args); @v = v; end end +d = Marshal.dump(MyRange.new(4, 5, 8, false)) +p d +r = Marshal.load(d) +p r.class, r.instance_variables, r, r.frozen?, Marshal.load(Marshal.dump(1..2)).frozen? +p Marshal.load(""\x04\bo:\fMyRange\t:\texclF:\nbegini\n:\bendi\r:\a@vi\t"").instance_variables +class CyclicRange < Range; def <=>(o); true; end; end +c = CyclicRange.allocate +c.instance_eval { initialize(c, c) } +l = Marshal.load(Marshal.dump(c)) +p l.class, l.begin.equal?(l), l.end.equal?(l) +", @" +""\x04\bIo:\fMyRange\b:\texclF:\nbegini\n:\bendi\r\x06:\a@vi\t"" +MyRange +[:@v] +5..8 +false +true +[] +CyclicRange +true +true +"); + } + + /// + /// Marshal.load of a Time subclass's dump answers an instance of the subclass (MRI's time_mload allocates the + /// receiver of _load); a Regexp record without an encoding is a Ruby 1.8 one, whose escapes of letters 1.8 did + /// not define lose their backslash; and a class defined in a singleton class, whose path starts with "#", is + /// anonymous to Marshal.dump. + /// + public void Marshal_LoadedClasses1() { + TestOutput(@" +class MyTime < Time; def initialize(v, *args) super(*args); @v = v; end end +t = Marshal.load(Marshal.dump(MyTime.new(10))) +p t.class, t.instance_variables +r = Marshal.load(""\004\b/\fa\\u3042\000"") +p r.source, Marshal.load(Marshal.dump(/a\\u3042/)) == /a\\u3042/ +o = Object.new +c = class << o; class C; self; end; end +p((Marshal.dump(c) rescue $!.class), (Marshal.dump(c.new) rescue $!.class)) +", @" +MyTime +[:@v] +""au3042"" +true +TypeError +TypeError +"); + } + + /// + /// Time.new takes :dst and :std for the zone, as MRI's time_init_args does: a local time, the symbol choosing + /// between the two readings of an hour the clocks go back over. They were "can't convert Symbol into an exact + /// number", which failed 47 of CRuby's test_time_tz tests. + /// + public void Time_NewDstStdZone1() { + TestOutput(@" +local = Time.new(2000, 1, 1, 12, 0, 0) +p Time.new(2000, 1, 1, 12, 0, 0, :std) == local, Time.new(2000, 1, 1, 12, 0, 0, :dst) == local +p Time.new(2000, 1, 1, 12, 0, 0, :std).utc?, Time.new(2000, 7, 1, 12, 0, 0, :dst).utc_offset == Time.new(2000, 7, 1, 12, 0, 0).utc_offset +p((Time.new(2000, 1, 1, 0, 0, 0, :foo) rescue $!)) +p Time.new(2019, 1, 1, 0, 0, 0, 'utc').utc?, Time.new(2019, 1, 1, 0, 0, 0, 'Utc').utc?, (Time.new(2019, 1, 1, 0, 0, 0, 'z') rescue $!.class) +", @" +true +true +false +true +# +true +true +ArgumentError +"); + } + + /// + /// nil, true and false cannot be cloned unfrozen, as MRI's special_object_p says of them: clone(freeze: false) + /// is "can't unfreeze NilClass" and the like, as for an Integer or a Symbol. + /// + public void Kernel_CloneSpecialConstants1() { + TestOutput(@" +require 'ruby4' +p((true.clone(freeze: false) rescue $!), (nil.clone(freeze: false) rescue $!), (false.clone(freeze: false) rescue $!)) +p nil.clone, true.clone(freeze: true), (nil.clone(freeze: 1) rescue $!) +", @" +# +# +# +nil +true +# +"); + } + + /// + /// Struct#inspect and Data#inspect write a member that is not a local or constant name as its Symbol, as MRI's + /// rb_struct_inspect does (#<struct :@a=1>); and a Struct member writer reports its parameter as `_`. + /// + public void Struct_InspectMemberNames1() { + TestOutput(@" +require 'ruby4' +k = Struct.new(:@a, :b, :c?, :E, :""f g"") +p k.new(1, 2, 3, 4, 5) +d = Data.define(:@a, :b) +p d.new(1, 2) +s = Struct.new(:a) +p s.instance_method(:a=).parameters, s.instance_method(:a).parameters +", @" +# +# +[[:req, :_]] +[] +"); + } + + /// + /// "comparison of X with Y failed" names an anonymous class by its #to_s, as MRI's rb_cmperr does (PRIsVALUE): + /// a class that says what it is (EnvUtil.labeled_class) is named so, not #<Class:0x...>. + /// + public void Comparison_AnonymousClassName1() { + TestOutput(@" +e = Class.new { singleton_class.class_eval { define_method(:to_s) { 'Labeled' }; alias inspect to_s } } +begin; 1.0 < e.new; rescue => x; puts x.message; end +begin; 1 < e.new; rescue => x; puts x.message; end +begin; 1 < nil; rescue => x; puts x.message; end +", @" +comparison of Float with Labeled failed +comparison of Integer with Labeled failed +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 +"); + } + + /// + /// 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""] +"); + } + + /// + /// 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""] +"); + } + + /// + /// 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. + /// (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]] +"); + } + + /// + /// 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] +"); + } + + /// + /// 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)] +"); + } + + /// + /// 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 +# +"); + } + + /// + /// 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"" +"); + } + + /// + /// 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 ", @" -[true] +[""%-"", ""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""] +"); + } + + /// + /// 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?"" +# +"); + } + + /// + /// 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] +"); + } + + /// + /// 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 "); } /// - /// BasicObject#equal? is identity, separate from #== - a class whose == calls equal? - /// (Set#==) must not recurse through BaseEquals into its own ==. + /// 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 BasicObject_EqualIdentity1() { + public void Warning_UndefinedWarn1() { TestOutput(@" -# Set#== in set.rb (not loadable here: no prelude) has this shape -class MySet - attr_reader :h - def initialize(*a); @h = {}; a.each { |x| @h[x] = true }; end - def ==(other); if self.equal?(other) then true elsif other.instance_of?(self.class) then @h == other.h else false end; end +require 'ruby4' +Warning.undef_method(:warn) +begin + warn ""x"" +rescue NoMethodError => e + p e.class, e.message end -class Eq; def ==(o); equal?(o); end; end -class Str < String; def ==(o); equal?(o); end; end -p MySet.new(1).equal?(MySet.new(1)), (s = MySet.new(1)).equal?(s), s == MySet.new(1) -e = Eq.new; p e.equal?(e), e.equal?(Eq.new), e == e, e == Eq.new -t = Str.new('a'); p t.equal?(t), t.equal?(Str.new('a')), 'a'.equal?('a') -p 1.equal?(1), 1.5.equal?(1.5), :a.equal?(:a), nil.equal?(nil), true.equal?(true) -p BasicObject.new.equal?(BasicObject.new) -p BasicObject.instance_method(:equal?) == BasicObject.instance_method(:==) ", @" -false -true -true -true -false -true -false +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 +"); + } + + /// + /// 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 +# +"); + } + + /// + /// 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 -false -true +[TrueClass, MyString] "); } /// - /// RbConfig::CONFIG["EXECUTABLE_EXTS"] was missing, and CRuby's tool/lib/find_executable.rb splits it, which - /// stopped test_rubyoptions before its first test. configure sets it on Windows only. + /// 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 RbConfig_ExecutableExts1() { + public void Marshal_TimeAnyYear1() { TestOutput(@" -require 'rbconfig' -p RbConfig::CONFIG['EXECUTABLE_EXTS'].split | [RbConfig::CONFIG['EXEEXT']] -", Environment.OSVersion.Platform == PlatformID.Win32NT ? @"["".exe"", "".com"", "".cmd"", "".bat""]" : @"[""""]"); +[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 +"); } /// - /// all?, any?, none? and one? given a pattern and a block warn "given block not used" at the line that called - /// them, as MRI does. The prelude asked for the location two frames up, past the end of a top-level script's - /// backtrace, so the warning had none there, and named the wrong line inside a method. The pattern forms are - /// C# now (Enumerable.cs) and warn with ReportWarning at the running line, which ir writes to $stderr and - /// this host counts in its error sink, so what is checked here is that each call warns once. + /// 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 Enumerable_PatternUnusedBlockWarning1() { + 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]] +"); + } + + /// + /// 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); + } + + /// + /// 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' -a = [1, 2].all?(1) { } -def m - [1].none?(1) { } +[[""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 -b = m -c = (1..2).one?(1) { } -p a, b, c +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 -false -true -", 0, 3); +"); } /// - /// Array#rotate and #rotate! take their count as a long (MRI's NUM2LONG): a count past an int still rotates, - /// one past a long is a RangeError, for an empty or a frozen Array too. + /// 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 Array_RotateLongCount1() { + 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"); + } + + /// + /// 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(@" -a = [1, 2, 3] -p a.rotate(2**40), a.rotate(-(2**40) - 1), a.dup.rotate!(2**40 + 1) -p((a.rotate(2**64) rescue $!.class), ([].rotate(2**64) rescue $!.class), ([].freeze.rotate!(2**64) rescue $!.class)) -", @" -[2, 3, 1] -[2, 3, 1] -[3, 1, 2] -RangeError -RangeError -RangeError +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 "); } /// - /// Hash#transform_values transforms a copy of the receiver (rb_hash_transform_values): keys the block adds to - /// the receiver are not visited, and keys it deletes are still in the result. + /// 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 Hash_TransformValuesSnapshot1() { + public void Process_ClockGetresInvalid1() { TestOutput(@" -h = { a: 1, b: 2, c: 3 } -p h.transform_values { |v| h[:z] = 9; h.delete(:c); v * 2 }, h -i = { a: 1 } -p i.transform_values { |v| i.clear; v }, i -", @" -{a: 2, b: 4, c: 6} -{a: 1, b: 2, z: 9} -{a: 1} -{} +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 "); } /// - /// String#lines with a separator reads the receiver's length after the search for the separator, which - /// switches a receiver held as bytes (after #bytesize or #getbyte) to characters: a length kept from - /// before counted bytes, and the copy of the last line ran past the end (review of #218). + /// 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 String_LinesAfterByteRead1() { + public void Process_GroupsArgumentChecks1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } TestOutput(@" require 'ruby4' -s = ""\u00E9\nab\n\u00FC""; s.bytesize -p s.lines(""\n"").map(&:bytes), s.lines(""\n"", chomp: true).map(&:bytes) -t = ""a\u00E9\r\nb\r\n""; t.getbyte(0) -p t.lines(""\r\n"").map(&:bytes), t.lines(chomp: true).map(&:bytes) -u = ""\u00E9\u00FCab\u00FC\u00FC""; u.bytesize -p u.lines(""\u00FC"").map(&:bytes), u.each_line(""\u00FC"").map(&:size) +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) } ", @" -[[195, 169, 10], [97, 98, 10], [195, 188]] -[[195, 169], [97, 98], [195, 188]] -[[97, 195, 169, 13, 10], [98, 13, 10]] -[[97, 195, 169], [98]] -[[195, 169, 195, 188], [97, 98, 195, 188], [195, 188]] -[2, 3, 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""] "); } /// - /// Hash#dig asks a Hash or an Array whose #dig is redefined - in a subclass or on the object itself - whether it - /// has #dig, as it asks any other object, and does not ask one whose #dig is the built-in one, whatever its - /// respond_to? says (rb_obj_dig takes its short cut while rb_method_basic_definition_p). A #dig the program - /// defines in Array itself is a redefinition too. + /// 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 Hash_DigSubclass1() { + public void Process_SpawnRedirectOpenFailure1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } TestOutput(@" require 'ruby4' -class H2 < Hash; def dig(*k) = [:over, k]; def respond_to?(m, priv = false) = m == :dig ? false : super; end -class A2 < Array; def dig(*k) = [:over, k]; def respond_to?(m, priv = false) = m == :dig ? false : super; end -class H3 < Hash; def dig(*k) = [:over, k]; end -p(({ a: H2.new }.dig(:a, 1) rescue $!.message), ({ a: A2.new }.dig(:a, 1, 2, 3, 4) rescue $!.message)) -p({ a: H3.new }.dig(:a, 1), { a: H3.new }.dig(:a, 1, 2, 3, 4), { a: H3[b: 1] }.dig(:a), { a: { b: [5, 6] } }.dig(:a, :b, 1)) -class H4 < Hash; def respond_to?(m, priv = false) = m == :dig ? false : super; end -class A4 < Array; def respond_to?(m, priv = false) = m == :dig ? false : super; end -p({ a: H4[:x, 3] }.dig(:a, :x), { a: A4[7, 8] }.dig(:a, 1)) -h = {}; def h.dig(*) = :over; def h.respond_to?(m, priv = false) = m == :dig ? false : super -g = { b: 1 }; def g.respond_to?(m, priv = false) = m == :dig ? false : super -p(({ a: h }.dig(:a, :b) rescue $!.class), { a: g }.dig(:a, :b)) -a = [5]; def a.respond_to?(m, priv = false) = m == :dig ? false : super -p({ a: a }.dig(:a, 0)) -class Array; alias_method :dig0, :dig; def dig(*) = :over; end -p(({ a: a }.dig(:a, 0) rescue $!.class), { a: [5] }.dig(:a, 0)) +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 ", @" -""H2 does not have #dig method"" -""A2 does not have #dig method"" -[:over, [1]] -[:over, [1, 2, 3, 4]] -{b: 1} -6 +""No such file or directory - no/such/dir/file"" 3 -8 -TypeError -1 -5 -TypeError -:over +""No such file or directory - no/such/dir/file"" +nil +""No such file or directory - no/such/dir/file"" +nil +nil +127 "); } /// - /// Hash#transform_values replaces each value where its entry is (rb_hash_stlike_foreach_with_replace), not through - /// its key: keys the block makes equal stay two entries. compare_by_identity carries over, the default does not. + /// $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 Hash_TransformValuesMutatedKey1() { + public void Globals_ProgramNameFrozen1() { TestOutput(@" -require 'ruby4' -a = [1]; b = [2]; h = { a => 10, b => 20 } -r = h.transform_values { |v| b.replace([1]); v + 1 } -p r.size, r.to_a, h.size -k = { a: 1 }.compare_by_identity; k[""x"".dup] = 2; k[""x"".dup] = 3 -t = k.transform_values { |v| v * 10 } -p t, t.compare_by_identity?, Hash.new(5).merge(a: 1).transform_values { |v| v }.default -p({ a: 1, b: 2 }.transform_values { |v| break :out if v == 2; v }, { nil => 1 }.transform_values { |v| v + 1 }) +s = +""name"" +$0 = s +p $0.frozen?, s.frozen?, $0.equal?(s), $0 +f = ""frozen"".freeze +$0 = f +p $0.equal?(f) ", @" -2 -[[[1], 11], [[1], 21]] -2 -{a: 10, ""x"" => 20, ""x"" => 30} true -nil -:out -{nil => 2} +false +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 +# "); } /// - /// The KeyError of Hash#fetch may leave its backtrace until a rescue exposes it only while nothing can have kept - /// it. A TracePoint on :raise or on :c_call (which sees it being initialized) that keeps it and disables itself, - /// and a KeyError.new of the program's that keeps it and removes itself, all have: read after the rescuing frame - /// is gone, the backtrace is still the raise's. + /// 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 Hash_FetchKeptKeyError1() { + public void Process_StatusMarshal1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } TestOutput(@" require 'ruby4' -H = {} -def f1 = H.fetch(:x) -def g1 = (begin; f1; rescue KeyError; nil; end) -20000.times { g1 } -kept = nil -tp = TracePoint.new(:raise) { |t| kept = t.raised_exception; t.disable } -tp.enable -g1 -tp.disable -p kept.class, kept.backtrace.map { |l| l[/'(.*)'/, 1] } -seen = nil -tc = TracePoint.new(:c_call) { |t| if KeyError === t.self then seen = t.self; t.disable end } -tc.enable -g1 -tc.disable -p seen.backtrace.map { |l| l[/'(.*)'/, 1] } -made = nil -make = KeyError.method(:new) -KeyError.define_singleton_method(:new) { |*a| made = make.call(*a); KeyError.singleton_class.send(:remove_method, :new); made } -g1 -p(made.nil? || made.backtrace.none? { |l| l.include?('Exception#backtrace') }) -", @" -KeyError -[""Hash#fetch"", ""Object#f1"", ""Object#g1"", ""
""] -[""Hash#fetch"", ""Object#f1"", ""Object#g1"", ""
""] +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 "); } /// - /// The pattern forms of all?, any?, none? and one? are C# overloads, not prelude wrappers: the pattern's #=== - /// is called as MRI's rb_funcall calls it, a private one included; an Array walks itself and does not call - /// #each; and a later Array#any? (prepended here, run hot) still takes over. + /// 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 Enumerable_PredicatePattern1() { + public void Process_SpawnShellAssignment1() { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) { + return; + } TestOutput(@" require 'ruby4' -class Pat; private def ===(o) = o == 2; end -class A < Array; def each = raise('each called'); end -def f(a) = [a.any? { |x| x > 2 }, a.any?(Pat.new), a.all?(Integer), a.none?(2..2), a.one?(3)] -r = [] -3000.times do |i| - r << f(i < 2000 ? [1, 2, 3] : A[1, 2, 3]) - Array.prepend(Module.new { def any?(*, &) = :redef }) if i == 2500 +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 r.tally -p({a: 1}.any?(Array), (1..4).one?(4), [[1, 2]].all? { |a, b| b == 2 }) -b = [] -p A[1, 2].one? { |x| x }, A[1, nil].one?, A[nil, 2].one? { |x| x }, A[1, 2].one? { |x| break :brk } -p [1, 2].one? { |x| b << x; b.size < 4 ? (b << 9; false) : false }, b +p `echo a=b` ", @" -{[true, true, true, false, true] => 2501, [:redef, :redef, true, false, true] => 499} +[""foofoo=barbar\n""] +[""A1=x\n"", ""B2=y\n""] 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 -false true true -:brk -false -[1, 9, 2, 9] +0 +0 +0 +# +# +# "); } /// - /// Enumerable#tally given a BasicObject to count into raises MRI's TypeError: the prelude asked it #nil? and - /// #is_a?, which a BasicObject does not answer, and raised NoMethodError. + /// 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 Enumerable_TallyBasicObject1() { + public void Module_ConstGetPathConstMissing1() { TestOutput(@" -require 'ruby4' -p(([1].tally(BasicObject.new) rescue $!), ((1..2).tally(BasicObject.new) rescue $!), ([1].tally(Object.new) rescue $!)) -p [1, 1].tally({1 => 1}), (1..2).tally +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 $!)) ", @" -# -# -# -{1 => 3} -{1 => 1, 2 => 1} +true +[:Foo, :Bar, :Baz] +:Bar +:Bar +:Bar +:Bar11 +# "); } /// - /// inject(:op) calls the operator publicly, as MRI's rb_funcallv_public does since [Bug #13592]: a private #+ - /// is a NoMethodError, for an Array's fast path too. + /// 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 Enumerable_InjectPrivateOp1() { + public void Argf_SeekOpensNextFile1() { TestOutput(@" require 'ruby4' -k = Class.new { include Enumerable; def each; yield 1; yield 2; yield 3; end } -%i[+ *].each do |op| +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 - Integer.class_eval { private op } - p((k.new.inject(op) rescue $!), ([1, 2, 3].inject(op) rescue $!), ((1..3).inject(op) rescue $!)) - ensure - Integer.class_eval { public op } + 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 -p k.new.inject(:+), [1, 2, 3].inject(:+), [1, 2, 3].inject(10, :*) ", @" -# -# -# -# -# -# -6 -6 -60 +""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"" "); } /// - /// A Range is an 'o' record of excl, begin and end, and a subclass's instance variables go in an "I" wrapper - /// around it, as MRI writes them; they were written into the record and lost on loading. The range is in the - /// link table before its ends are read (range_loader), so one that is its own begin and end comes back as one. + /// 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 Marshal_RangeRecord1() { + public void Argf_ReadAtEndBuffer1() { TestOutput(@" -class MyRange < Range; def initialize(v, *args) super(*args); @v = v; end end -d = Marshal.dump(MyRange.new(4, 5, 8, false)) -p d -r = Marshal.load(d) -p r.class, r.instance_variables, r, r.frozen?, Marshal.load(Marshal.dump(1..2)).frozen? -p Marshal.load(""\x04\bo:\fMyRange\t:\texclF:\nbegini\n:\bendi\r:\a@vi\t"").instance_variables -class CyclicRange < Range; def <=>(o); true; end; end -c = CyclicRange.allocate -c.instance_eval { initialize(c, c) } -l = Marshal.load(Marshal.dump(c)) -p l.class, l.begin.equal?(l), l.end.equal?(l) +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 ", @" -""\x04\bIo:\fMyRange\b:\texclF:\nbegini\n:\bendi\r\x06:\a@vi\t"" -MyRange -[:@v] -5..8 -false -true -[] -CyclicRange -true -true +nil +"""" +"""" +"""" +nil "); } /// - /// Marshal.load of a Time subclass's dump answers an instance of the subclass (MRI's time_mload allocates the - /// receiver of _load); a Regexp record without an encoding is a Ruby 1.8 one, whose escapes of letters 1.8 did - /// not define lose their backslash; and a class defined in a singleton class, whose path starts with "#", is - /// anonymous to Marshal.dump. + /// 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 Marshal_LoadedClasses1() { + public void Argf_NonStringArgv1() { TestOutput(@" -class MyTime < Time; def initialize(v, *args) super(*args); @v = v; end end -t = Marshal.load(Marshal.dump(MyTime.new(10))) -p t.class, t.instance_variables -r = Marshal.load(""\004\b/\fa\\u3042\000"") -p r.source, Marshal.load(Marshal.dump(/a\\u3042/)) == /a\\u3042/ -o = Object.new -c = class << o; class C; self; end; end -p((Marshal.dump(c) rescue $!.class), (Marshal.dump(c.new) rescue $!.class)) +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 ", @" -MyTime -[:@v] -""au3042"" -true -TypeError -TypeError +""no implicit conversion of nil into String"" +""no implicit conversion of Integer into String"" +""no implicit conversion of Symbol into String"" +""1\n"" "); } /// - /// Time.new takes :dst and :std for the zone, as MRI's time_init_args does: a local time, the symbol choosing - /// between the two readings of an hour the clocks go back over. They were "can't convert Symbol into an exact - /// number", which failed 47 of CRuby's test_time_tz tests. + /// 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 Time_NewDstStdZone1() { + public void Compiler_ShareableConstantValue1() { TestOutput(@" -local = Time.new(2000, 1, 1, 12, 0, 0) -p Time.new(2000, 1, 1, 12, 0, 0, :std) == local, Time.new(2000, 1, 1, 12, 0, 0, :dst) == local -p Time.new(2000, 1, 1, 12, 0, 0, :std).utc?, Time.new(2000, 7, 1, 12, 0, 0, :dst).utc_offset == Time.new(2000, 7, 1, 12, 0, 0).utc_offset -p((Time.new(2000, 1, 1, 0, 0, 0, :foo) rescue $!)) -p Time.new(2019, 1, 1, 0, 0, 0, 'utc').utc?, Time.new(2019, 1, 1, 0, 0, 0, 'Utc').utc?, (Time.new(2019, 1, 1, 0, 0, 0, 'z') rescue $!.class) +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 -ArgumentError -"); - } - - /// - /// nil, true and false cannot be cloned unfrozen, as MRI's special_object_p says of them: clone(freeze: false) - /// is "can't unfreeze NilClass" and the like, as for an Integer or a Symbol. - /// - public void Kernel_CloneSpecialConstants1() { - TestOutput(@" -require 'ruby4' -p((true.clone(freeze: false) rescue $!), (nil.clone(freeze: false) rescue $!), (false.clone(freeze: false) rescue $!)) -p nil.clone, true.clone(freeze: true), (nil.clone(freeze: 1) rescue $!) -", @" -# -# -# -nil +{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 -# "); } /// - /// Struct#inspect and Data#inspect write a member that is not a local or constant name as its Symbol, as MRI's - /// rb_struct_inspect does (#<struct :@a=1>); and a Struct member writer reports its parameter as `_`. + /// 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 Struct_InspectMemberNames1() { + public void Compiler_ShareableConstantValue2() { TestOutput(@" require 'ruby4' -k = Struct.new(:@a, :b, :c?, :E, :""f g"") -p k.new(1, 2, 3, 4, 5) -d = Data.define(:@a, :b) -p d.new(1, 2) -s = Struct.new(:a) -p s.instance_method(:a=).parameters, s.instance_method(:a).parameters +# 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 ", @" -# -# -[[:req, :_]] -[] +true +false +[1] +true +true +{x: {}} +{x: {}, y: {}} +Ractor::Error +""#freeze does not freeze object correctly"" "); } /// - /// "comparison of X with Y failed" names an anonymous class by its #to_s, as MRI's rb_cmperr does (PRIsVALUE): - /// a class that says what it is (EnvUtil.labeled_class) is named so, not #<Class:0x...>. + /// 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 Comparison_AnonymousClassName1() { + public void Library_NestedDefinitionConflict1() { TestOutput(@" -e = Class.new { singleton_class.class_eval { define_method(:to_s) { 'Labeled' }; alias inspect to_s } } -begin; 1.0 < e.new; rescue => x; puts x.message; end -begin; 1 < e.new; rescue => x; puts x.message; end -begin; 1 < nil; rescue => x; puts x.message; end +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 ", @" -comparison of Float with Labeled failed -comparison of Integer with Labeled failed -comparison of Integer with nil failed +# +# "); } } diff --git a/Src/IronRuby.Tests/Runtime/ModuleTests.cs b/Src/IronRuby.Tests/Runtime/ModuleTests.cs index e5a203775..fef04b3f1 100644 --- a/Src/IronRuby.Tests/Runtime/ModuleTests.cs +++ b/Src/IronRuby.Tests/Runtime/ModuleTests.cs @@ -1020,6 +1020,94 @@ 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"" +"); + } + + /// + /// 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 +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/MutableStringTests.cs b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs index 5ec040eeb..bd99f5d17 100644 --- a/Src/IronRuby.Tests/Runtime/MutableStringTests.cs +++ b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs @@ -2113,6 +2113,75 @@ 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"" +"); + } + + /// + /// 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/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/IronRuby.Tests/Runtime/RefinementTests.cs b/Src/IronRuby.Tests/Runtime/RefinementTests.cs index b257c7f34..52cd88a17 100644 --- a/Src/IronRuby.Tests/Runtime/RefinementTests.cs +++ b/Src/IronRuby.Tests/Runtime/RefinementTests.cs @@ -592,6 +592,57 @@ 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]]] +"); + } + + /// + /// "#{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/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 328a22ee8..10e6adfb9 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -895,6 +895,186 @@ 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 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 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 +# +"); + } + + /// + /// 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"" +"); + } + + /// + /// 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 @@ -902,6 +1082,68 @@ 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 +"); + } + + /// + /// 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' @@ -949,6 +1191,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/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/IronRuby.Tests/Runtime/StringTests.cs b/Src/IronRuby.Tests/Runtime/StringTests.cs index e6cf1649f..d676d59d8 100644 --- a/Src/IronRuby.Tests/Runtime/StringTests.cs +++ b/Src/IronRuby.Tests/Runtime/StringTests.cs @@ -351,11 +351,130 @@ 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"" +"); + } + + /// + /// 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 /// 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). @@ -731,6 +850,72 @@ 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. + /// + 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 - @@ -920,16 +1105,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 @@ -948,7 +1133,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 @@ -1246,7 +1431,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 @@ -1291,6 +1476,97 @@ 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 $!)) } +", @" +# +# +""?"" +# +# +# +"); + } + + /// + /// 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]] +"); + } + + /// + /// 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/IronRuby.Tests/Runtime/SuperTests.cs b/Src/IronRuby.Tests/Runtime/SuperTests.cs index f64075a72..695de125f 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 @@ -1040,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/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..2660963c8 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 @@ -160,12 +168,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 +199,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 +214,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 +291,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 +299,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 +365,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 +676,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; } @@ -701,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) { @@ -711,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) { @@ -781,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)) { @@ -803,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); @@ -834,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/BasicObjectOps.cs b/Src/Libraries/Builtins/BasicObjectOps.cs index a7b050054..164aa3494 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; @@ -74,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 @@ -89,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) { @@ -103,6 +116,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName) { @@ -111,6 +125,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -120,6 +135,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -129,6 +145,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -138,6 +155,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -147,6 +165,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -156,6 +175,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -165,6 +185,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -174,6 +195,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -260,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]); @@ -293,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 a895508af..b67796d89 100644 --- a/Src/Libraries/Builtins/ClassOps.cs +++ b/Src/Libraries/Builtins/ClassOps.cs @@ -35,24 +35,22 @@ 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")); } - // 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) + /// 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); @@ -78,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; } @@ -108,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; } @@ -128,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 e4c5de422..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 @@ -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")] @@ -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 bb7b2c83a..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(); } @@ -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; } @@ -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); } @@ -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; } @@ -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,10 +1719,10 @@ 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.CreateAscii(name).Freeze()); + reported.Add(MutableString.CreateBinary(Encoding.ASCII.GetBytes(name)).Freeze()); } var result = new RubyConverter(path.Count != 0 ? path.ToArray() : null, flags); @@ -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 39d605543..64206cdb7 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 @@ -194,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); } @@ -214,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); } @@ -239,12 +282,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 +296,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); @@ -914,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); @@ -1204,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)); @@ -1261,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(); @@ -1379,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")] @@ -1411,7 +1568,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 80fde7a4b..e8cbc5e00 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, SlowRaiseEnd = 4; /// /// Where the iteration of a built-in method has got to. A cursor belongs to the Ruby thread @@ -292,6 +292,197 @@ 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(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; } + } + } + + // 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. + // #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. + 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(CallSiteStorage>/*!*/ sites, 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(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(); + } + + internal override object Result { + get { return _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 @@ -397,6 +588,75 @@ 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(CallSiteStorage>/*!*/ sites, object fed) { + _inner.Resume(sites, fed); + } + + internal override bool ResumesWithRubyCode { + get { return _inner.ResumesWithRubyCode; } + } + + 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 { @@ -579,6 +839,12 @@ private sealed class PreludeMethods { internal RubyMemberInfo StructEach; internal RubyMemberInfo EachSlice; 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(); @@ -598,12 +864,24 @@ 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") { 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; } } return null; @@ -631,7 +909,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")) { @@ -655,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; } @@ -668,6 +949,27 @@ 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 "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; @@ -690,10 +992,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")) { @@ -713,6 +1024,102 @@ 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; + } + // 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"); + 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; + } + + // 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); + } + + // 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; @@ -795,6 +1202,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)) { @@ -820,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; @@ -851,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) { @@ -869,6 +1298,11 @@ 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; + } + + /// + /// 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)] + private static void ResumeWithRubyCode(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; + } + + // The StopIteration that ended the fiber's iteration (__iter_raise_stop__), the cause of the ones raised after it. + private StopIteration _fiberStop; + + /// + /// 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) { @@ -940,40 +1481,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); } /// @@ -983,16 +1528,36 @@ 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"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("feed value already set")); } self._feedValue = value; self._hasFeed = true; 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. /// @@ -1011,6 +1576,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/Libraries/Builtins/ExceptionOps.cs b/Src/Libraries/Builtins/ExceptionOps.cs index 2d6b790ed..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 @@ -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/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 b0fc3c8f1..faf4bc255 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)); } } @@ -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); } @@ -1235,7 +1239,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 +1252,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 +1267,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 +1358,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 +1513,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 +1524,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 +1534,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 +1544,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 +1748,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 +1874,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 +1900,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")); } } @@ -1977,19 +1981,23 @@ 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)"); } else { result.Append("fd ").Append(self.GetFileDescriptor().ToString(CultureInfo.InvariantCulture)); } - return result.Append('>'); + return RubyUtils.BinaryIfAscii(result.Append('>')); } [RubyMethod("path")] @@ -2026,12 +2034,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 @@ -2144,7 +2156,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()); } } @@ -2291,7 +2303,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; } @@ -2319,11 +2331,11 @@ 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)) { - 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; @@ -2741,9 +2753,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 +2771,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/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..a80c5cd46 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] @@ -70,13 +78,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 +96,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 +128,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 +139,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 +160,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 +189,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 +200,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 +243,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))); } /// @@ -257,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)) { @@ -355,7 +364,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 +436,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 +448,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 fbcac2f42..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 @@ -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); } @@ -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 }; } @@ -417,17 +421,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 +482,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); } @@ -572,21 +565,24 @@ 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, 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); @@ -1119,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 @@ -1153,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); } @@ -1189,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) { @@ -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) { @@ -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; @@ -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); @@ -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; @@ -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/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/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index f75e643e0..7a8d53d4a 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'); - return result; + return RubyUtils.BinaryIfAscii(result); } #endregion @@ -1752,7 +1753,7 @@ public static RubyEncoding GetInternalEncoding(RubyIO/*!*/ self) { if (external == null) { // set_encoding(nil, ) 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. @@ -2193,7 +2194,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; } @@ -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(); @@ -2229,7 +2230,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; } @@ -2251,12 +2252,27 @@ 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(); - 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 +2281,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 +2300,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 +2333,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 +2348,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; } @@ -2354,11 +2374,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 @@ -2387,7 +2407,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 +2417,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 +2445,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; } @@ -2493,7 +2513,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 +2695,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 +2895,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 +3249,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 +3288,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 +3469,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 +3681,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 97e201e2f..a7917ed09 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -47,13 +47,13 @@ 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); 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; @@ -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; @@ -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; } @@ -277,13 +277,13 @@ 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) { return null; } - throw RubyExceptions.CreateTypeConversionError("NilClass", "Integer"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeConversionError("NilClass", "Integer")); } // rb_protect(rb_check_to_int) @@ -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) { @@ -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) { @@ -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,20 +612,20 @@ 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 // 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; 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) { @@ -925,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); @@ -967,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); } @@ -1016,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 @@ -1142,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 @@ -1152,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); @@ -1162,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; @@ -1172,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)] @@ -1292,11 +1331,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; @@ -1315,7 +1354,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]); @@ -1355,7 +1394,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; @@ -1371,7 +1410,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; } @@ -1440,7 +1479,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 { @@ -1460,7 +1499,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")); } } } @@ -1536,6 +1575,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. @@ -1600,7 +1656,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; @@ -1614,12 +1670,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); } @@ -1637,6 +1693,35 @@ 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; + } + + /// + /// 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). @@ -1746,6 +1831,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 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) { + 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) { @@ -1754,6 +1905,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, @@ -1838,7 +2006,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; } @@ -1854,10 +2022,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")); } } @@ -1915,6 +2083,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) { @@ -1940,7 +2109,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 @@ -2248,7 +2417,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; } @@ -2277,7 +2446,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); @@ -2446,8 +2615,9 @@ 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"); + 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 @@ -2455,7 +2625,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 @@ -2493,6 +2663,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) { @@ -2504,6 +2675,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName) { @@ -2515,6 +2687,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2529,6 +2702,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2542,6 +2716,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2556,6 +2731,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2569,6 +2745,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2583,6 +2760,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2596,6 +2774,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2610,6 +2789,7 @@ public static object SendMessage(SendSiteStorage>/*!*/ storage, RubyScope/*!*/ scope, BlockParam block, object self, [DefaultProtocol, NotNull]string/*!*/ methodName, @@ -2675,7 +2855,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); @@ -2708,7 +2888,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)); } /// @@ -2729,9 +2909,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 @@ -2746,7 +2926,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)); } /// @@ -2947,7 +3127,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 @@ -2973,7 +3153,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; @@ -2985,10 +3165,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; @@ -3004,10 +3184,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))); } } @@ -3018,7 +3198,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); } @@ -3067,7 +3247,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)); } } @@ -3077,7 +3257,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); } @@ -3090,7 +3270,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); @@ -3129,7 +3309,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)] @@ -3215,7 +3395,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); @@ -3289,10 +3469,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; } @@ -3638,7 +3818,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) - ); + )); + } + } + + /// + /// 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) { @@ -702,9 +721,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() - ); + )); } } @@ -730,8 +749,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 +791,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,12 +799,33 @@ 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); + } } + // 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"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("_dump() must return string")); } // What gets written are the instance variables of the string _dump returned, and @@ -797,7 +845,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); + } } } @@ -811,15 +867,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); } @@ -980,12 +1036,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))); } } @@ -999,7 +1055,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")); } } } @@ -1013,9 +1069,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); @@ -1028,9 +1084,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); } @@ -1039,7 +1095,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--; @@ -1177,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 { @@ -1184,7 +1242,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); @@ -1396,10 +1454,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) { @@ -1414,11 +1472,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; } @@ -1435,7 +1493,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 @@ -1447,7 +1505,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); } @@ -1684,7 +1742,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++) { @@ -1720,13 +1778,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 { @@ -1814,7 +1872,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(); @@ -1822,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(); @@ -1885,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); } @@ -1895,7 +1989,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) { @@ -1906,7 +2000,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) { @@ -1922,7 +2016,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))); @@ -2016,8 +2110,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())); } } @@ -2026,7 +2120,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); @@ -2034,8 +2128,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); @@ -2055,8 +2149,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); @@ -2091,9 +2185,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; } @@ -2103,10 +2197,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; } @@ -2122,7 +2216,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); @@ -2139,14 +2233,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); @@ -2165,13 +2259,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); @@ -2245,7 +2339,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; } @@ -2266,8 +2367,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; } @@ -2286,8 +2387,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 { @@ -2308,8 +2409,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; @@ -2410,7 +2511,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; } @@ -2471,13 +2572,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 @@ -2566,8 +2667,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; @@ -2642,14 +2743,14 @@ 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); + 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)); } } } @@ -2706,7 +2807,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); @@ -2737,7 +2838,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; @@ -2791,7 +2892,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 d521ca4b0..ff481db75 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; } @@ -59,7 +63,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; } @@ -298,7 +302,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/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 0e505d38b..4d87bf10f 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 ); } @@ -158,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; } @@ -170,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")] @@ -185,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/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 18e33562d..92e0fa2df 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -36,38 +36,14 @@ 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; } - [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 @@ -95,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")); } } @@ -142,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: @@ -150,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")); } } @@ -197,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); @@ -229,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; @@ -237,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; @@ -246,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;' @@ -257,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); @@ -265,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. @@ -410,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); @@ -448,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: @@ -525,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: @@ -590,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); @@ -775,15 +751,26 @@ private static void DefineAccessor(RubyScope/*!*/ scope, RubyModule/*!*/ self, s } } + // the methods are located where attr_* was called, as MRI's are (Method#source_location): where the interpreted frame + // or a precompiled call's note says, else where the frame records say - code of the startup library, for which the + // first gives up (Pathname#path, in a file of it, is :205) + string sourcePath; + int sourceLine; + if (scope.IsEmpty || !RubyUtils.TryGetCallerSourceLocation(scope, out sourcePath, out sourceLine) && + !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 }); } } @@ -910,9 +897,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: @@ -927,8 +914,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; @@ -944,7 +931,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); } @@ -1071,7 +1058,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: @@ -1114,7 +1101,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); @@ -1155,7 +1142,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 @@ -1165,7 +1152,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]); @@ -1192,7 +1179,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); } @@ -1229,8 +1216,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; } @@ -1274,9 +1260,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; @@ -1407,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)) { @@ -1421,13 +1409,24 @@ public static object GetConstantValue(ConversionStorage/*!*/ stri context.ReportConstantDeprecation(owner, name); } } else { - value = ConstantMissing(owner, name); + value = owner.ConstantMissing(name); } lookupObject = false; } 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) { @@ -1447,9 +1446,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) { @@ -1533,8 +1532,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; @@ -1618,16 +1617,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; } @@ -1758,7 +1757,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); @@ -1971,7 +1970,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; @@ -1990,13 +1989,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); @@ -2009,6 +2008,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); } @@ -2040,7 +2052,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) { @@ -2050,10 +2062,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); @@ -2074,9 +2086,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) - ); + )); } } @@ -2084,7 +2096,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; @@ -2096,23 +2108,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); @@ -2123,20 +2135,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 5dbf80244..498e194f4 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; @@ -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 @@ -163,7 +176,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; } @@ -206,7 +219,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 +446,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); @@ -699,6 +712,33 @@ 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)) { + // the copy constructor: what CreateInstance().Replace(self) leaves, without the empty content made for it + return self.Clone(); + } + 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.HasNoInstanceVariablesOrSingleton(self); + } + [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static MutableString/*!*/ Reinitialize(MutableString/*!*/ self, [NotNull]byte[] other) { self.Clear(); @@ -727,7 +767,7 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { [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. @@ -737,7 +777,7 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { 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); } @@ -750,10 +790,10 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { [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. @@ -761,7 +801,7 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { if (self.IsEmpty) { return result; } - throw RubyExceptions.CreateArgumentError("argument too big"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("argument too big")); } // encoding aware @@ -779,16 +819,42 @@ public int CopyUnselected(ReadOnlySpan bytes, byte[]/*!*/ kept) { // encoding aware [RubyMethod("<<")] - [RubyMethod("concat")] + [RubyStackTraceOperator] 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); } - [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) { - throw RubyExceptions.CreateRangeError("{0} out of char range", c); + // MRI's rb_str_concat checks the receiver first: a frozen string raises FrozenError whatever it is given + self.RequireNotFrozen(); + 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 @@ -807,22 +873,48 @@ 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(); + 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 IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("{0} out of char range", c)); + } + } + [RubyMethod("<<")] - [RubyMethod("concat")] + [RubyStackTraceOperator] 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. 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)) { - 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")); + } + + /// + /// 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("<<")] + [RubyStackTraceOperator] + 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 @@ -1131,8 +1223,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 @@ -1196,7 +1289,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; @@ -1293,7 +1386,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); @@ -1319,7 +1412,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 @@ -1350,7 +1443,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 @@ -1394,11 +1487,13 @@ 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) { - 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. @@ -1411,10 +1506,10 @@ 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 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)). @@ -1443,7 +1538,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; @@ -1467,7 +1562,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) { @@ -1491,13 +1586,13 @@ 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); 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; @@ -1507,6 +1602,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; @@ -1535,8 +1641,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; @@ -1559,7 +1665,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); @@ -1598,14 +1704,14 @@ 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); - 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). @@ -1613,7 +1719,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; } @@ -1627,7 +1733,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) { @@ -1635,12 +1741,12 @@ 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); - return ReplaceClrRange(self, match.GetGroupStart(groupIndex), match.GetGroupLength(groupIndex), replacement); + return ReplaceMatchedRange(self, match.GetGroupStart(groupIndex), match.GetGroupLength(groupIndex), replacement); } #endregion @@ -1662,7 +1768,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; @@ -1672,23 +1778,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; } @@ -1749,7 +1855,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")); } } @@ -1838,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. @@ -1960,7 +2075,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)); } @@ -2049,7 +2164,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); @@ -2722,7 +2837,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))); } @@ -2744,7 +2859,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; @@ -2800,6 +2915,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 @@ -2822,6 +2943,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 @@ -3005,7 +3228,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; @@ -3170,8 +3404,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; @@ -3186,8 +3420,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; @@ -3205,8 +3439,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; @@ -3244,7 +3478,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)); } } @@ -3365,7 +3599,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; @@ -3474,7 +3708,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)); } } } @@ -3512,8 +3746,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; @@ -3536,7 +3770,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; @@ -3555,7 +3789,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); } @@ -3632,7 +3866,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; @@ -3998,12 +4232,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); @@ -4333,7 +4567,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); } @@ -4377,7 +4611,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); @@ -4463,15 +4706,160 @@ 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); + Utf8OffsetMap map = null; + 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 charOffset; + if (singleByte) { + int size = GetCharacterLength(self); + 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; + } + charOffset = offset; + } 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 += map.ByteLength; + if (offset < 0) { + return true; + } + } + clrOffset = (map != null) ? map.ClrOf(offset) : Utf8OffsetToClrIndex(chars, offset); + if (clrOffset == -2) { + if (!reverse) { + return true; + } + clrOffset = chars.Length; + } else if (clrOffset < 0) { + throw IronRuby.Runtime.RubyExceptionData.Unkept(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; + } + int foundByte = (map != null) ? map.ByteOf(foundClr) : -1; + result = ScriptingRuntimeHelpers.Int32ToObject(foundByte >= 0 ? foundByte : 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): -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; + 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 : (bytes < byteOffset) ? -2 : -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)); } @@ -4534,7 +4922,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; @@ -4714,7 +5120,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)); } } @@ -4727,7 +5133,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(); } @@ -4739,7 +5145,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) { @@ -4784,7 +5190,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); } @@ -4854,8 +5260,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("=~")] @@ -4865,7 +5271,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("=~")] @@ -4920,7 +5326,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); } @@ -4935,7 +5341,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)); } @@ -5785,7 +6191,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")); } } @@ -5878,7 +6284,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)) { @@ -6416,7 +6822,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); @@ -6504,12 +6910,26 @@ private static void AppendCodePoint(MutableString/*!*/ str, int c) { } // encoding aware, TODO: KCODE + // 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; + } + [RubyMethod("tr!")] 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; } @@ -6528,7 +6948,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; } @@ -6645,10 +7067,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; }); @@ -6684,16 +7106,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; } @@ -6715,7 +7137,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(); @@ -6724,7 +7146,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]; @@ -6735,7 +7157,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); @@ -6771,7 +7193,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 2aaad3f15..0170863fd 100644 --- a/Src/Libraries/Builtins/ObjectSpace.cs +++ b/Src/Libraries/Builtins/ObjectSpace.cs @@ -207,14 +207,14 @@ 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 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; @@ -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 2150e1126..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 @@ -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) { @@ -154,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) { @@ -163,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)); } @@ -177,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; @@ -212,6 +229,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) { @@ -341,7 +372,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); @@ -368,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")); } } @@ -391,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 31e7b4675..10fce2446 100644 --- a/Src/Libraries/Builtins/RefinementOps.cs +++ b/Src/Libraries/Builtins/RefinementOps.cs @@ -55,17 +55,21 @@ 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; } [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")); } /// @@ -78,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) - ); + )); } } @@ -107,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/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/RubyEncoder.cs b/Src/Libraries/Builtins/RubyEncoder.cs index 4197a6fa6..b2f9ac939 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,16 @@ 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) + 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 IronRuby.Runtime.RubyExceptionData.Unkept(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 @@ -915,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 @@ -1031,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)); } } @@ -1147,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 == '#') { @@ -1178,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 == '_') { @@ -1211,18 +1220,21 @@ 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--; } 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; } } @@ -1240,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; @@ -1290,7 +1315,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; @@ -1418,7 +1443,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 @@ -1440,7 +1465,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, @@ -1466,10 +1491,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); } @@ -1479,7 +1504,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; @@ -1505,8 +1530,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) { @@ -1536,9 +1561,11 @@ 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) { - throw RubyExceptions.CreateRuntimeError("format string modified"); + // 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 IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRuntimeError("format string modified")); } parsed.ThrowIfInvalid(formatString, true); stream.SetLength(stream.Position); @@ -1599,7 +1626,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') { @@ -1619,7 +1646,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]; } @@ -1719,7 +1746,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 { @@ -1931,7 +1958,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; @@ -1939,7 +1966,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..f82979565 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()) { @@ -292,7 +295,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 +307,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 +427,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/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/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 43aba68d7..578a220f0 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; @@ -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) { } @@ -443,14 +464,20 @@ 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))); + 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); } } @@ -703,11 +730,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: @@ -723,7 +750,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))); } } @@ -757,7 +784,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())); } } @@ -773,7 +800,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/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 RequireInitialized(RubyRegex/*!*/ self) { if (!self.IsInitialized) { - throw RubyExceptions.CreateTypeError("uninitialized Regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("uninitialized Regexp")); } } @@ -165,14 +165,27 @@ 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; + + // 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; } /// @@ -202,7 +215,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); @@ -214,11 +227,11 @@ public static object SetGlobalTimeout(RubyClass/*!*/ self, object value) { /// 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) { - throw RubyExceptions.CreateTypeError("already initialized regexp"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("already initialized regexp")); } } @@ -307,7 +320,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 +444,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 +520,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,9 +556,15 @@ 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; } - return str != null && self.MatchFromCharacter(str, start, false) != null; + // 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?")] @@ -668,9 +687,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; @@ -718,7 +737,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); } @@ -897,7 +916,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); @@ -905,7 +924,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 f266190da..cfc00e480 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]); } @@ -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,8 +1308,8 @@ 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) { - throw RubyExceptions.CreateTypeError("marshaled time format differ"); + if (data.Length < 8) { + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTypeError("marshaled time format differ")); } uint dword1 = GetUint(data, 0); @@ -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) @@ -1351,7 +1391,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 +1412,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 +1436,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); } @@ -1453,7 +1493,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 +1505,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); @@ -1665,12 +1705,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 +1830,8 @@ public static object ToRational(CallSiteStorage/*!*/ 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); } @@ -60,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; @@ -84,7 +95,7 @@ public static object SetPrivateVisibility(ConversionStorage/*!*/ 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); @@ -200,7 +211,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 236385cb1..8986ca43f 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 IronRuby.Runtime.RubyExceptionData.Unkept(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 IronRuby.Runtime.RubyExceptionData.Unkept(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) { @@ -134,11 +154,13 @@ 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. - throw RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ERANGE"), format); + // otherwise ask for a 4 GB string. A %Z with no zone name writes nothing, + // so it asks for no room. + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ERANGE"), format)); } string piece = FormatDirective(context, time, directive, modifiers, modifiers.Width, depth); @@ -233,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); diff --git a/Src/Libraries/Builtins/StringFormatter.cs b/Src/Libraries/Builtins/StringFormatter.cs index 818676d57..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"); @@ -236,13 +236,17 @@ 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); } 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(); @@ -262,12 +266,17 @@ 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) { - 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 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]; @@ -275,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; @@ -298,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; @@ -324,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] == '*') { @@ -337,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'); } @@ -354,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; @@ -394,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) { @@ -428,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; @@ -453,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; @@ -497,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 @@ -520,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. @@ -539,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]; @@ -631,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) { @@ -655,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); @@ -1398,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))); } } @@ -1442,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); @@ -1457,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) { @@ -1496,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); } /// @@ -1514,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; @@ -1523,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(); @@ -1553,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; } @@ -1623,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 5663d6533..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. @@ -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,32 +100,48 @@ 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 // before any of the arguments is looked at. A struct being constructed is never frozen. if (self.IsFrozen) { - throw RubyExceptions.CreateObjectFrozenErrorFor(self, "Struct"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateObjectFrozenErrorFor(self, "Struct")); } int count = self.ItemCount; - if (items.Length == count && (count == 0 || !(items[count - 1] is IronRuby.Builtins.Hash)) && !self.IsKeywordInit) { + object keywordInit = self.KeywordInit; + if (items.Length == count && (count == 0 || !(items[count - 1] is IronRuby.Builtins.Hash)) && !RubyOps.IsTrue(keywordInit)) { self.SetValues(items); return null; } int positional = items.Length; - Hash keywords = null; - if (positional > 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 (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]); + 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,34 @@ public static object Initialize(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/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 33209830b..0d7df313c 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 { @@ -957,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); } @@ -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 @@ -1389,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); @@ -1419,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; } @@ -1434,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. @@ -1450,8 +1500,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; @@ -1607,7 +1657,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. @@ -1619,7 +1669,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); @@ -1714,7 +1764,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() { @@ -1785,7 +1840,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) { @@ -1840,7 +1895,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; @@ -1929,7 +1984,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]; @@ -1943,7 +1998,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 e2ad65386..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; } @@ -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/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index e64480a90..1ee3d04a7 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) { @@ -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('#'); @@ -273,7 +274,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); @@ -282,17 +283,21 @@ 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; } // 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")] @@ -302,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")] @@ -317,7 +322,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,26 +333,65 @@ 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; + } + } 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), - rubyInfo.SourceSpan.Start.Line + line }; } + // 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; @@ -358,6 +402,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/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/Builtins/WarningOps.cs b/Src/Libraries/Builtins/WarningOps.cs index a27753407..bcca0539f 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) { @@ -67,19 +66,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 +94,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 97de71f2d..97ba20f7a 100644 --- a/Src/Libraries/Extensions/ClrBigInteger.cs +++ b/Src/Libraries/Extensions/ClrBigInteger.cs @@ -256,7 +256,7 @@ public static object DivideOp(RubyContext/*!*/ context, BigInteger/*!*/ self, do public static object Divide(RubyContext/*!*/ context, BigInteger/*!*/ self, double other) { // rb_big_divide: the zero check comes before the conversion, so it does not warn. if (other == 0.0) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } return ClrFloat.Floor(Protocols.ConvertToDouble(context, self) / other); } @@ -422,7 +422,7 @@ public static object Power(CallSiteStorage= 2, so from here on the exponent is below 2**34 @@ -703,11 +703,16 @@ 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"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(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); } @@ -1165,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)); } @@ -1178,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/ClrFloat.cs b/Src/Libraries/Extensions/ClrFloat.cs index 09de507bb..990dec3a9 100644 --- a/Src/Libraries/Extensions/ClrFloat.cs +++ b/Src/Libraries/Extensions/ClrFloat.cs @@ -1247,7 +1247,7 @@ private static RubyArray InternalDivMod(double self, double other) { if (Double.IsNaN(other)) { div = mod = other; } else if (other == 0.0) { - throw new DivideByZeroException("divided by 0"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(new DivideByZeroException("divided by 0")); } else { if (self == 0.0 || (Double.IsInfinity(other) && !Double.IsInfinity(self))) { mod = self; @@ -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); } diff --git a/Src/Libraries/Extensions/ClrInteger.cs b/Src/Libraries/Extensions/ClrInteger.cs index 69c24cb60..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); @@ -759,6 +759,10 @@ public static double Subtract(int self, double other) { /// [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); @@ -869,14 +873,20 @@ 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. /// [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); } @@ -885,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/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 29f917cf4..74a8fbf9c 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) { @@ -393,6 +411,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 @@ -698,7 +808,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, @@ -732,7 +842,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 ac3f42196..ffc39f7b8 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")); } } @@ -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,12 +649,20 @@ 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. 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 +675,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 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); @@ -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); @@ -776,7 +806,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 +839,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 +862,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 +874,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 +931,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) { @@ -1516,8 +1546,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; } @@ -1536,7 +1566,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 +1584,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 +1630,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 +1668,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 +1705,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 +1733,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) { @@ -1712,6 +1742,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 IronRuby.Runtime.RubyExceptionData.Unkept(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 IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError("bignum too big to convert into 'long'")); + } + if (count.Sign < 0) { + throw IronRuby.Runtime.RubyExceptionData.Unkept(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]; @@ -1720,7 +1774,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) { @@ -1846,7 +1900,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) { @@ -1939,13 +1993,123 @@ 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; } #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 +2135,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; @@ -2146,7 +2312,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) { @@ -2384,7 +2550,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) { @@ -2422,7 +2588,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) { @@ -2457,7 +2623,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) { @@ -2485,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; @@ -2691,7 +2858,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 @@ -3106,7 +3273,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 { @@ -3132,7 +3299,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; @@ -3210,7 +3377,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/Libraries/Extensions/IronRubyOps.cs b/Src/Libraries/Extensions/IronRubyOps.cs index 89bc661f5..eb75261b6 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,56 @@ 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; + } + + /// + /// 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()); @@ -83,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()); } @@ -95,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); @@ -108,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 48225f091..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) { double d = (double)ndigits; - if (Double.IsNaN(d)) { - throw new FloatDomainError("NaN"); + // 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 IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(d)))); } - if (d >= 2147483648.0 || d <= -2147483649.0) { - throw RubyExceptions.CreateRangeError("float {0} out of range of integer", d); + long whole = (long)d; + if (whole > Int32.MaxValue || whole < Int32.MinValue) { + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("integer {0} too {1} to convert to 'int'", whole, whole < 0 ? "small" : "big"))); } - return (int)d; + return (int)whole; } IntegerValue value = Protocols.CastToInteger(integerCast, ndigits); @@ -109,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 e0f27767e..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; @@ -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. @@ -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) { @@ -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; } @@ -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")); } } } @@ -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++); @@ -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)); } } @@ -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; @@ -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 8eca6153e..0e4e5aed1 100644 --- a/Src/Libraries/StringScanner/StringScanner.cs +++ b/Src/Libraries/StringScanner/StringScanner.cs @@ -16,9 +16,11 @@ using System; using System.Collections.Generic; using System.Numerics; +using System.Runtime.CompilerServices; 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,17 +157,88 @@ 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 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 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 Utf8OffsetMap Map { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { + // 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; + return subject.HasByteCharacters ? null : MapFor(subject); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + 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(); + Utf8OffsetMap map = _map; + if (map != null && ReferenceEquals(map.Text, text)) { + return map; + } + if (ReferenceEquals(text, _unmappedText) || subject.ContainsInvalidCharacters()) { + _unmappedText = text; + return null; + } + return _map = new Utf8OffsetMap(text); + } + private int ByteLength { - get { return _scanString.GetByteCount(); } + get { + Utf8OffsetMap map = Map; + return (map != null) ? map.ByteLength : _scanString.GetByteCount(); + } } private MutableString/*!*/ ByteSlice(int start, int count) { if (count <= 0) { return MutableString.CreateEmpty(_scanString.Encoding); } + Utf8OffsetMap map = Map; + if (map != null) { + 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(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; + } + private MutableString/*!*/ RestString() { return ByteSlice(_position, ByteLength - _position); } @@ -185,6 +258,14 @@ private int CharWidthAtPosition() { if (available <= 0) { return 0; } + Utf8OffsetMap 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 +299,22 @@ private int CharacterCountOf(int byteIndex) { if (_scanString.DetectSingleByteCharacters()) { return byteIndex; } + Utf8OffsetMap 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 +332,13 @@ private int CharIndexOf(int byteIndex) { // every scan cost a pass over everything already scanned. return byteIndex; } + Utf8OffsetMap 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 +355,7 @@ private void ClearMatch() { _matchBase = 0; _matchStart = 0; _matchEnd = 0; + _matchMap = null; } #endregion @@ -274,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); } @@ -286,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) @@ -306,9 +417,62 @@ 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(Utf8OffsetMap/*!*/ 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(); + Utf8OffsetMap map = Map; + if (map != null) { + int mapped = MatchRegexMapped(map, pattern, anchored, advance); + 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) { int boundsStart, boundsEnd; RubyRegex.PendingMatch pending; @@ -356,12 +520,71 @@ 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(); + 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. + Utf8OffsetMap 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; @@ -440,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]); @@ -463,6 +686,16 @@ public static MutableString GetMatchSubgroup(ConversionStorage/*!*/ fixnumC return null; } int start, end; + Utf8OffsetMap 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; @@ -534,8 +767,20 @@ 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'); + 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) { + return map.Text[clr - 1] == '\n'; + } + return self._scanString.GetByte(self._position - 1) == (byte)'\n'; } [RubyMethod("check")] @@ -645,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)); @@ -659,6 +904,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); } @@ -670,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; @@ -782,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 297a9cfc9..d80800fff 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,14 +150,18 @@ 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; } [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 c5f1e3870..862747590 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(); } } @@ -367,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; } @@ -393,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, @@ -423,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 17649a40b..0fc5a2f05 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); } } @@ -133,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); @@ -177,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) { @@ -228,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); } @@ -238,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) { @@ -297,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 f8b3fc961..f7ce7246d 100644 --- a/Src/Libraries/Thread/SizedQueue.cs +++ b/Src/Libraries/Thread/SizedQueue.cs @@ -39,9 +39,15 @@ 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"); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("queue size must be positive")); } _limit = limit; } @@ -55,6 +61,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 +74,8 @@ private bool Enqueue(object value, int timeoutMilliseconds) { } catch (ThreadInterruptedException) { RubyUtils.TranslateThreadInterrupt(); continue; + } finally { + IronRuby.Builtins.ThreadOps.ExitBlockingMethod(previous); } CheckOpen(); if (!signalled) { @@ -138,9 +147,57 @@ 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); } + + // 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; + } } } 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/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 58bc5d9dd..7052ba357 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; @@ -34,6 +35,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 +253,20 @@ private static SourceUnitTree ParseText(string/*!*/ code, string path, List - /// `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 ---- @@ -714,6 +701,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. @@ -724,7 +712,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(); @@ -773,16 +761,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); @@ -805,7 +793,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); @@ -1175,7 +1169,8 @@ private int StatementLine(Pm.PmNode/*!*/ node) { return StatementsAsExpression(preExec.Statements, span); case Pm.SourceFileNode sourceFile: - return new StringLiteral(_path ?? LiteralText(sourceFile.Filepath), _encoding, span); + string file = _path ?? LiteralText(sourceFile.Filepath); + return new StringLiteral(file, file.IsAscii() ? _fileEncoding : _encoding, span); case Pm.SourceLineNode _: return Literal.Integer(span.Start.Line + _lineOffset, span); case Pm.SourceEncodingNode _: @@ -1325,6 +1320,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) { @@ -1445,6 +1460,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; @@ -1458,7 +1476,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 @@ -1514,12 +1531,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 @@ -1538,6 +1553,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. @@ -1583,7 +1607,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); @@ -1605,7 +1629,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); } } @@ -1613,9 +1637,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 @@ -1833,7 +1856,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); } @@ -2059,8 +2084,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 +2106,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 +2141,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); } @@ -2211,15 +2256,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); - return new MethodDefinition(scope, target, node.Name, parameters, body, span) { UsesBlock = _usesBlock }; + var body = DefinitionBody(node.Body, span, prologue, node.EqualLoc != null); + return NoteUsesBlock(new MethodDefinition(scope, target, node.Name, parameters, body, span) { UsesBlock = _usesBlock }); } finally { _zsuperArguments = enclosingZSuperArguments; } @@ -2229,6 +2274,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 @@ -2273,7 +2327,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; @@ -2388,13 +2442,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; } @@ -2421,8 +2478,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) { @@ -3191,6 +3248,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); } 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/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/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); } diff --git a/Src/Ruby/Builtins/Hash.Keywords.cs b/Src/Ruby/Builtins/Hash.Keywords.cs index bfc6e506a..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; @@ -225,6 +266,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/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 cee75e746..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) { @@ -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/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 + /// 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) { diff --git a/Src/Ruby/Builtins/MatchData.cs b/Src/Ruby/Builtins/MatchData.cs index 7b773b8e1..6d54ba40e 100644 --- a/Src/Ruby/Builtins/MatchData.cs +++ b/Src/Ruby/Builtins/MatchData.cs @@ -259,9 +259,28 @@ 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); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateIndexError("undefined group name reference: {0}", name)); } return OffsetsOf(GetNamedGroup(name), inBytes); } @@ -479,7 +498,7 @@ public int GetGroupEnd(int groupIndex) { public void RequireExistingGroup(int index) { if (index >= 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.BinaryContent.cs b/Src/Ruby/Builtins/MutableString.BinaryContent.cs index 67fd9ac89..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() { @@ -555,12 +603,31 @@ 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 + // 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); + } + } + + // 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 (Utils.IsSharedSlice(_data.Length, sliceCount)) { + if (start + sliceCount == _count && Utils.IsSharedSlice(_data.Length, sliceCount, true)) { shared = true; return new BinaryContent(_data, _start + start, sliceCount, _owner); } @@ -568,7 +635,7 @@ public override byte GetByte(int index) { ContentState.Exit(ref _state, shared); } } - return Create(Utils.GetSlice(GetDataSpan(), start, count), _owner); + return GetSlice(start, count); } public override CharacterEnumerator/*!*/ GetCharacters() { @@ -660,7 +727,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 +777,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 @@ -765,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 { @@ -775,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 { @@ -792,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 { @@ -863,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 { @@ -880,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 { @@ -899,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 { @@ -921,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 @@ -935,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); @@ -947,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 2115da470..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)); @@ -390,12 +415,31 @@ 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 + // 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); + } + } + + // 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 (Utils.IsSharedSlice(_data.Length, sliceCount)) { + if (start + sliceCount == _count && Utils.IsSharedSlice(_data.Length, sliceCount, true)) { shared = true; return new CharArrayContent(_data, _start + start, sliceCount, _owner, null); } @@ -403,7 +447,7 @@ public override byte GetByte(int index) { ContentState.Exit(ref _state, shared); } } - return new CharArrayContent(Utils.GetSlice(GetDataSpan(), start, count), _owner); + return GetSlice(start, count); } public override CharacterEnumerator/*!*/ GetCharacters() { @@ -554,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 { @@ -567,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 { @@ -576,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 { @@ -634,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 { @@ -651,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 { @@ -660,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 { @@ -697,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 f073aea8e..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 @@ -325,6 +347,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 d35427371..cddc937db 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; @@ -574,11 +600,11 @@ 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) { - throw RubyExceptions.CreateTemporarilyLockedError(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTemporarilyLockedError()); } if (_content.IsOffsetSlice) { @@ -800,7 +826,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 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: bool isEmpty = _content.IsEmpty; @@ -922,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; } @@ -938,30 +970,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 +1028,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,9 +1043,9 @@ 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); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, _encoding)); } SetEncoding(fromEncoding); switchToChars = true; @@ -1008,9 +1055,9 @@ 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); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, fromEncoding)); } } @@ -1019,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)); } } @@ -1216,9 +1263,32 @@ 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); + } + } + + /// + /// 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 RubyExceptionData.Unkept(RubyExceptions.CreateStringFrozenError(this)); + } + ReportChilledChange(this); } } @@ -1228,7 +1298,7 @@ public void RequireNotFrozen() { /// public MutableString/*!*/ LockTemporarily() { if ((_flags & IsTemporarilyLockedFlag) != 0) { - throw RubyExceptions.CreateTemporarilyLockedError(); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateTemporarilyLockedError()); } RequireNotFrozen(); _flags |= IsTemporarilyLockedFlag; @@ -1339,9 +1409,9 @@ 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); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, _encoding)); } return this; } @@ -1355,9 +1425,9 @@ 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); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateInvalidByteSequenceError(e, _encoding)); } return this; } @@ -1427,7 +1497,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")); } } @@ -1492,6 +1562,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) { @@ -1647,6 +1740,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; @@ -1994,12 +2133,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) && @@ -2010,7 +2160,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/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 116d394fe..72d720ca6 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -75,6 +75,27 @@ 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; + + // 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"; + /// /// The state few procs have, out of line: a Proc is allocated for every call with a literal block. /// @@ -83,6 +104,9 @@ private sealed class RareState { public RefinementActivation RefinementOverride; 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; @@ -124,12 +148,28 @@ 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; } + /// + /// 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. /// @@ -138,6 +178,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. /// @@ -153,15 +222,53 @@ 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; + } + + /// + /// 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 & 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; } } /// @@ -201,7 +308,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; } @@ -250,6 +357,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. @@ -259,6 +376,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; } } @@ -277,7 +403,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) @@ -285,6 +412,7 @@ protected Proc(Proc/*!*/ proc) Converter = proc.Converter; IsIsolated = proc.IsIsolated; SymbolName = proc.SymbolName; + EvalLiterals = proc.EvalLiterals; } /// @@ -296,6 +424,7 @@ protected Proc(Proc/*!*/ proc) result.Converter = Converter; result.SymbolName = SymbolName; result.IsIsolated = true; + result.EvalLiterals = EvalLiterals; return result; } @@ -503,6 +632,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); @@ -562,18 +718,21 @@ 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) ) ); 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 66803c5af..d81b62af1 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 @@ -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/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index f379491cb..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 @@ -115,6 +119,10 @@ private sealed class SharedState { public bool AstralSafe; // see Transform(..., asciiCtype) 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. @@ -246,6 +254,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,12 +278,29 @@ 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; 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); @@ -289,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; } @@ -694,9 +733,13 @@ private static bool HasInlineIgnoreCase(string/*!*/ pattern) { for (int depth = DefaultMaxCallDepth; ; depth /= 2) { 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; _state.MayIgnoreCase = asciiCtype && ((_clrOptions & RegexOptions.IgnoreCase) != 0 || HasInlineIgnoreCase(_rubyPattern)); _state.MaxCallDepth = depth; @@ -706,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; @@ -722,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(); @@ -899,7 +944,17 @@ 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() == '^'; + 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; case '.': @@ -935,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("(?:"); @@ -950,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 == '{'; @@ -1377,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; @@ -1406,6 +1496,7 @@ private void ParseGroup() { _characterClassMode = savedMode; _dotAll = savedDotAll; _extended = savedExtended; + _ignoreCase = savedIgnoreCase; if (groupNumber >= 0) { CloseGroup("#" + groupNumber); if (groupName != null) { @@ -1443,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; @@ -1458,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; @@ -1488,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(')'); } @@ -1498,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(')'); } @@ -1627,12 +1725,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|\\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; @@ -1680,8 +1782,9 @@ private void ParseEscape(int escape) { // A generic line break: CRLF as a unit, or any single line terminator. // Atomic so that CRLF never backtracks into matching just the CR. // In a BINARY subject (SharedState.AsciiCtype) 0x85 is no line terminator. - _state.AsciiCtypeApplied |= _state.AsciiCtype; - _sb.Append(_state.AsciiCtype ? "(?>\\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': @@ -1734,7 +1837,19 @@ private void ParseEscape(int escape) { var latin1Word = CharacterSet.MakeSet(_latin1WordQuirk, null); set = (escape == 'w') ? set.Union(latin1Word) : set.Subtract(latin1Word); } - AppendCharacterSet(set, false); + 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; } } @@ -2260,6 +2375,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) { @@ -2273,7 +2392,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 @@ -2311,6 +2441,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 +2452,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); @@ -2429,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 { @@ -2514,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); @@ -2925,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; @@ -2976,20 +3158,24 @@ 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); } + 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; @@ -3041,6 +3227,7 @@ private CharacterSet ParseCharacter(ref IEnumerator codepoints, out bool ma return MakeCodePointSet(codepoint); } else { mayStartRange = true; + _memberFolds = !IsCtypeEscape(escape); return ParseCharacterEscape(escape); } @@ -3052,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; } @@ -3162,6 +3351,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 +3374,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/RubyArray.cs b/Src/Ruby/Builtins/RubyArray.cs index 12344849d..602d3e576 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() { @@ -152,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() { @@ -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/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 6e7f9b5ba..58387c66a 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; @@ -75,15 +76,23 @@ 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; 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; @@ -384,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) { @@ -760,32 +769,23 @@ 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()) { 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. @@ -839,17 +839,17 @@ public void InitializeClassCopy(RubyClass/*!*/ rubyClass) { 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; } @@ -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); } } @@ -1028,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; @@ -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>(); @@ -1692,6 +1768,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)))); } @@ -1756,10 +1835,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 +1859,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 +1900,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()); @@ -1976,14 +2115,21 @@ 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: + // 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 = 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 ); } @@ -2057,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..fe8e20945 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))); } } @@ -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; diff --git a/Src/Ruby/Builtins/RubyFile.cs b/Src/Ruby/Builtins/RubyFile.cs index ab7ec0115..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(); @@ -74,17 +126,20 @@ 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; 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) { - 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 +153,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 +195,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/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/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 98a665651..e5cc56809 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. @@ -935,8 +936,10 @@ internal void InitializeMembersFrom(RubyModule/*!*/ module) { } else { _classVariables = null; } + _context.ClassVariablesChanged(); _mixins = ArrayUtils.Copy(module._mixins); _prepends = ArrayUtils.Copy(module._prepends); + _inheritedLookups = null; // dependentModules - skip // tracker - skip, .NET members not copied @@ -949,7 +952,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()) { @@ -978,22 +981,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; } @@ -1007,7 +1002,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: @@ -1017,9 +1012,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)); } } @@ -1045,6 +1040,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 @@ -1582,8 +1585,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) { @@ -1643,8 +1646,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) { @@ -1682,7 +1685,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; @@ -1797,7 +1800,60 @@ 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() { + // the ancestors a class variable is looked up through moved as well + _context.ClassVariablesChanged(); + 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) { + // 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); } @@ -1811,6 +1867,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(); } @@ -1884,7 +1943,12 @@ public MutableString GetAutoloadedConstantPath(string/*!*/ name) { public MutableString GetAutoloadedConstantPath(string/*!*/ name, bool inherit) { using (Context.ClassHierarchyLocker()) { MutableString result = null; - ForEachAncestor(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)) { @@ -2021,7 +2085,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 @@ -2085,12 +2149,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 { @@ -2272,16 +2357,33 @@ 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); } 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. @@ -2291,7 +2393,7 @@ public void AddMethodAlias(string/*!*/ newName, string/*!*/ oldName) { } 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) => @@ -2387,16 +2489,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: @@ -2415,7 +2510,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)); } @@ -2454,24 +2559,38 @@ 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); 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) { WarnIfRedefiningCoreMethodNoLock(name, method); } - PrepareMethodUpdate(name, method); + if (prepareUpdate) { + PrepareMethodUpdate(name, method); + } InitializeMethodsNoLock(); _methods[name] = method; + _inheritedLookups = null; if (IsHelperName(name)) { if (_context.Loader.IsLoadingCorePrelude) { @@ -2577,6 +2696,7 @@ internal void AddMethodNoCacheInvalidation(string/*!*/ name, RubyMemberInfo/*!*/ Context.RequiresClassHierarchyLock(); Debug.Assert(_methods != null); _methods.Add(name, method); + _inheritedLookups = null; } /// @@ -2585,6 +2705,7 @@ internal void AddMethodNoCacheInvalidation(string/*!*/ name, RubyMemberInfo/*!*/ internal bool RemoveMethodNoCacheInvalidation(string/*!*/ name) { Context.RequiresClassHierarchyLock(); Debug.Assert(_methods != null); + _inheritedLookups = null; return _methods.Remove(name); } @@ -2622,6 +2743,7 @@ private bool RemoveMethodNoEvent(string/*!*/ name) { } _methods.Remove(name); + _inheritedLookups = null; if (_refinedModule != null) { _context.RefinedMethodChanged(_refinedModule, name); @@ -2766,6 +2888,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); } @@ -3359,12 +3484,13 @@ 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) : TryGetClrMember(_typeTracker.Type, name, mapNames, unmangleNames, out method)) { _methods.Add(name, method); + _inheritedLookups = null; return true; } } @@ -3373,15 +3499,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; @@ -3696,7 +3813,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; } @@ -3731,10 +3848,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; @@ -3747,9 +3882,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) { @@ -3768,42 +3907,126 @@ 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) { + 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 - // 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. + // A singleton class of a class or module starts at its own table and goes on with the class or module it + // belongs to (cvar_front_klass, as ForEachClassVariableOwner): the modules it was extended with are not + // looked in. using (Context.ClassHierarchyLocker()) { - ForEachAncestor(delegate(RubyModule/*!*/ module) { - object moduleValue; - if (module.TryGetClassVariable(name, out moduleValue)) { - if (front == null) { - front = module; - } - target = module; - targetValue = moduleValue; + RubyModule start = this; + var singleton = this as RubyClass; + RubyModule attached; + if (singleton != null && singleton.IsSingletonClass && (attached = singleton.SingletonClassOf as RubyModule) != null) { + ResolveClassVariableIn(this, name, ref nearest, ref target, ref targetValue); + start = attached; + } + var cls = start as RubyClass; + if (cls == null) { + start.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; - }); - } - - 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; } + // 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 + /// (TryResolveClassVariable). + /// + public bool IsClassVariableDefined(string/*!*/ name) { + Assert.NotNull(name); + bool found = false; + using (Context.ClassHierarchyLocker()) { + ForEachClassVariableOwner(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) { @@ -3926,7 +4149,8 @@ internal void PrependModulesNoLock(RubyModule[]/*!*/ modules) { } PrependsUpdated(oldPrepends, _prepends = expanded); - _context.ConstantsChanged(); + _inheritedLookups = null; + MixinsChangedConstantsNoLock(); } /// @@ -4011,6 +4235,7 @@ internal void SpliceAncestorUpdate(RubyModule/*!*/ owner, RubyModule/*!*/[]/*!*/ var expanded = SpliceBefore(oldMixins, mixinIndex, added); if (expanded.Length != oldMixins.Length) { MixinsUpdated(oldMixins, _mixins = expanded); + _inheritedLookups = null; } } @@ -4020,10 +4245,11 @@ internal void SpliceAncestorUpdate(RubyModule/*!*/ owner, RubyModule/*!*/[]/*!*/ var expanded = SpliceBefore(old, prependIndex, added); if (expanded.Length != old.Length) { PrependsUpdated(old, _prepends = expanded); + _inheritedLookups = null; } } - _context.ConstantsChanged(); + MixinsChangedConstantsNoLock(); } private static RubyModule[]/*!*/ SpliceBefore(RubyModule/*!*/[]/*!*/ list, int index, RubyModule/*!*/[]/*!*/ added) { @@ -4073,7 +4299,8 @@ internal void IncludeModulesNoLock(RubyModule[]/*!*/ modules) { } MixinsUpdated(_mixins, _mixins = expanded); - _context.ConstantsChanged(); + _inheritedLookups = null; + MixinsChangedConstantsNoLock(); if (!IsClass) { PropagateMixinsToDependentsNoLock(); @@ -4119,7 +4346,8 @@ private void ReexpandMixinNoLock(RubyModule/*!*/ mixin) { } MixinsUpdated(_mixins, _mixins = expanded); - _context.ConstantsChanged(); + _inheritedLookups = null; + MixinsChangedConstantsNoLock(); if (!IsClass) { PropagateMixinsToDependentsNoLock(); @@ -4322,16 +4550,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; @@ -4378,12 +4615,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(':'); @@ -4392,7 +4635,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)); } } diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 14d275b16..c688dd529 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 @@ -61,6 +63,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. @@ -155,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); } @@ -171,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; @@ -341,15 +349,15 @@ 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()) { - throw RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", input.Encoding.Name); + if (!allowBroken && input.ContainsInvalidCharacters()) { + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateArgumentError("invalid byte sequence in {0}", input.Encoding.Name)); } var patternEncoding = Encoding; @@ -373,7 +381,7 @@ private void RequireMatchableEncoding(MutableString/*!*/ input) { 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)); } } } @@ -427,22 +435,29 @@ 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 astral = input.HasSurrogatePairs(); RubyRegex target = RecompiledFor(input); + if (allowBroken && input.ContainsInvalidCharacters()) { + astral = true; + return target.TransformEscapedBytesPattern(); + } if (astral) { return target.TransformAstralPattern(); } 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 +510,58 @@ 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; + } + + /// + /// 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) { @@ -1462,18 +1529,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 +1564,6 @@ private bool ToSearchStart(MutableString/*!*/ input, ref int start, bool clamp) } start = length; } - - start = input.ToClrIndex(start); return true; } @@ -1517,6 +1593,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 . /// @@ -1604,12 +1703,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; @@ -1921,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 67d586853..feea6b3eb 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)] @@ -279,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); } @@ -305,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); @@ -329,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")); } } @@ -338,16 +385,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/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 9a376e1d7..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,11 +63,12 @@ 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" 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 @@ -82,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; } @@ -94,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; } @@ -117,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))); } } @@ -139,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; } @@ -157,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; } @@ -168,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; } @@ -192,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) { @@ -216,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) { @@ -232,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; } @@ -288,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) { @@ -340,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/Compiler/Ast/Arguments.cs b/Src/Ruby/Compiler/Ast/Arguments.cs index 18dca6bb2..8f1362766 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 { @@ -53,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; @@ -62,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( @@ -88,7 +112,31 @@ 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 == 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/BlockDefinition.cs b/Src/Ruby/Compiler/Ast/BlockDefinition.cs index dbcf43ec3..3d543785d 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; @@ -86,6 +92,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; @@ -143,8 +178,16 @@ 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); + // 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) { @@ -171,6 +214,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); @@ -233,7 +284,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) { @@ -288,18 +341,33 @@ 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). - bool reusesProc = !isLambda && !hasNestedReturn && !gen.CurrentBlock.HasNestedBlock && + // 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 && (!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) - 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 @@ -311,7 +379,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( @@ -377,11 +458,13 @@ 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 (assignedOuterVariables == null && !hasNestedReturn && !gen.TraceEnabled && !gen.CompilerOptions.IsEval && + IronRuby.Runtime.Jit.JitBlockMethod.Enabled && gen.Context.RubyOptions.Jit && IsJitMethodShape()) { + // -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; } var dispatcher = Ast.Constant(blockDispatcher, typeof(BlockDispatcher)); @@ -397,10 +480,28 @@ 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); + 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 (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); } @@ -419,9 +520,29 @@ public BlockDefinition(LexicalScope/*!*/ definedScope, Parameters parameters, St ) ) ); + 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); + } + // 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; } + // 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/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/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 + /// 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 { + // 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; + 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 3b5b47761..5e21d60e8 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 }; } /// @@ -237,6 +238,9 @@ 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); + 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 && @@ -304,7 +308,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); } @@ -312,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); } @@ -340,7 +347,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 ); @@ -482,17 +489,32 @@ 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 only yields too, + // but parking a method around it cost more instructions than the bytes it saved: Util/perf/LEDGER.md, gap 13, + // perf/iter2. #downto is parked since perf/permute, whose deeper slots serve a recursion's levels: below.) + private static readonly bool ParkedFindEnabled = Environment.GetEnvironmentVariable("IR_PARKED_FIND") != "0"; + internal static bool IsNeverParkedIterator(string/*!*/ name) { - return NeverParkedIterators.Contains(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) || + !ParkedFindEnabled && (name == "find" || name == "detect" || name == "find_index" || name == "index" || + name == "any?" || name == "all?" || name == "none?"); } + 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). @@ -510,6 +532,18 @@ 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_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). @@ -553,6 +587,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). @@ -583,6 +624,37 @@ 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"; + + /// + /// 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"; + + /// + /// 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 + /// 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, @@ -592,6 +664,151 @@ 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 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", + }; + + // 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 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. + /// 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) { + return false; + } + var finder = new MatchObserverFinder(); + foreach (var optional in _parameters.Optional) { + optional.Walk(finder); + } + Body.Walk(finder); + 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; } + 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; } + } + + // 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; @@ -621,6 +838,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 @@ -632,7 +851,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) ); } @@ -672,8 +898,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 { @@ -698,8 +932,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 @@ -711,7 +947,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) { @@ -723,7 +959,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); @@ -737,7 +973,15 @@ 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, 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; + } } // The most calls a body with a multiple assignment may make and still be a light frame. A light frame's lambda grows @@ -759,6 +1003,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 +1065,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) { @@ -877,27 +1136,37 @@ 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) { 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"; } + 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)"; } @@ -919,11 +1188,139 @@ 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); } + /// + /// 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 @@ -936,7 +1333,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; } } @@ -973,7 +1370,15 @@ 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, 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; + } } // Finds a `begin' with rescue, else or ensure, a rescue modifier or a `retry' in a node, outside its blocks and definitions. @@ -1050,6 +1455,46 @@ 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; + } + // `@@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"); @@ -1060,7 +1505,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 []= @@ -1077,12 +1523,23 @@ 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); } + // `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; @@ -1094,6 +1551,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); @@ -1125,10 +1591,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); @@ -1175,6 +1643,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); @@ -1186,7 +1668,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)) { @@ -1206,6 +1688,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 @@ -1242,7 +1736,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; @@ -1354,6 +1849,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) { @@ -1369,7 +1868,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); @@ -1377,12 +1876,32 @@ 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; 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) { @@ -1429,6 +1948,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 { @@ -1451,14 +1972,26 @@ 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 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); + } + light.LazyScope = Ast.Coalesce(scopeVariable, Ast.Assign(scopeVariable, lateScope)); var rewriter = new LightFrameRewriter(scopeVariable, light.LazyScope, light.Rfc, declaringScope, inLoop, HasBlockGuard) { - BlockLiterals = LightBlocksEnabled && HasLightBlockLiteral(), + BlockLiterals = blockLiterals, + LiteralCalls = LightLiteralCallsEnabled && LightBlockPassEnabled && HasOnlyNarrowLiterals(), + MatchSlot = matchSlot, 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) { @@ -1492,6 +2025,32 @@ 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/*!*/ _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"); @@ -1515,6 +2074,16 @@ 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 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; + + // 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; @@ -1533,6 +2102,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 +2137,21 @@ private static int ScopeOperandIndex(MethodInfo/*!*/ method) { if (method == Methods.SetInstanceVariable) { return 2; } + if (LightGlobalsEnabled && method == Methods.IsDefinedGlobalVariable) { + return 0; + } + // 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; @@ -1575,9 +2163,25 @@ 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 || + method == Methods.MergeKeywordSplat || method == Methods.MergeKeywordHash)) { + return 0; + } 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; } @@ -1684,6 +2288,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 +2357,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 @@ -1879,7 +2551,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; @@ -1889,9 +2561,14 @@ 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)); - return MakeLightCall(reduced, action, lightAction, DispatchIntrinsics.IsLightBlockGivenSite(action.MethodName, lightAction.Signature)); + var lightFlags = signature.Flags | RubyCallFlags.HasLightScope; + // (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), sink); } /// @@ -1949,7 +2626,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(); @@ -1967,6 +2644,16 @@ 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) + 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))); MSA.Expression needsScope = Ast.ReferenceEqual(result, AstUtils.Constant(RubyOps.LightScopeRequired)); if (blockGiven && BlockParameter == null) { @@ -1974,6 +2661,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 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)), + 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), + 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/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/CaseExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/CaseExpression.cs index 2a5f666ac..d2cf07118 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,42 @@ 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) { + // a SymbolLiteral is a StringLiteral too, and `:all === "all"' is false: Strings only + var literal = comparison as StringLiteral; + if (literal == null || literal is SymbolLiteral) { + 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 +180,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/Ast/Expressions/Expression.cs b/Src/Ruby/Compiler/Ast/Expressions/Expression.cs index f14f46b0a..b547c6844 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?". @@ -124,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; } 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/Compiler/Ast/Expressions/MethodCall.cs b/Src/Ruby/Compiler/Ast/Expressions/MethodCall.cs index 33776e7df..16e2a7ef6 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; @@ -60,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); @@ -156,6 +178,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 @@ -173,6 +201,7 @@ private static bool IsStaticLiteral(Expression/*!*/ expression) { assignments.Add(Ast.Assign(targetTemp, AstUtils.Box(transformedTarget))); var ordered = new CallSiteBuilder(gen, targetTemp, blockArgVariable); + ordered.HasExplicitKeywords = scratch.HasExplicitKeywords; int index = 0; foreach (var argument in scratch) { // skip the scope, the instance and the block @@ -183,13 +212,34 @@ 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 + // 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; @@ -218,6 +268,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); } @@ -225,6 +285,38 @@ 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 + /// a few more shapes, such as `[]', that no #to_proc could tell apart). + /// + internal 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/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/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/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))); } } diff --git a/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs b/Src/Ruby/Compiler/Ast/Expressions/SuperCall.cs index beacc51d7..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 @@ -256,7 +300,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": @@ -296,23 +345,30 @@ 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)); - var without = new CallSiteBuilder(gen, gen.CurrentSelfVariable, blockArgVariable); + // both pass their keywords explicitly - a `**' that passes nothing, or the hash - so a ruby2_keywords hash ending + // the positionals stays one (RubyCallFlags.HasExplicitKeywords) + var without = new CallSiteBuilder(gen, gen.CurrentSelfVariable, blockArgVariable) { HasExplicitKeywords = true }; AddArguments(without, values, splatted, null); - var with = new CallSiteBuilder(gen, gen.CurrentSelfVariable, blockArgVariable); + 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); } diff --git a/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/WhileLoopExpression.cs index 1b2169237..2fa3bd448 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; @@ -69,6 +70,179 @@ 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++) { + YieldStatementKind kind; + var yieldCall = GetYieldOf(_statements[i], out kind); + 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) { + YieldStatementKind kind; + var args = GetYieldOf(_statements[i], out kind).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; + } + + /// 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; } + 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; } + // 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; } + 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, 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))), + Ast.Block( + Ast.IfThen( + Ast.AndAlso( + Ast.NotEqual(bfc, AstUtils.Constant(null, typeof(BlockParam))), + Methods.MethodYield.OpCall(gen.CurrentScopeVariable, bfc, result) + ), + gen.Return(result) + ), + rest, + 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)); @@ -106,10 +280,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(); @@ -143,6 +331,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); } @@ -162,6 +355,8 @@ 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, 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/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/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( 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/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/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/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)); } } } diff --git a/Src/Ruby/Compiler/AstGenerator.cs b/Src/Ruby/Compiler/AstGenerator.cs index 2df842a60..8e6d6eb9d 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; } } @@ -356,6 +382,17 @@ 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; + + // 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; @@ -432,9 +469,17 @@ 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; + + // 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; @@ -1220,6 +1265,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); diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 78461b40d..4a79efcc7 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)); } } @@ -60,6 +62,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)); } } @@ -124,6 +128,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 +266,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 +298,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)); } } @@ -312,6 +324,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)); } } @@ -360,6 +374,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)); } } @@ -432,6 +448,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)); } } @@ -570,6 +588,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)); } } @@ -622,6 +642,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)); } } @@ -740,6 +762,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/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)); } 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/Src/Ruby/Runtime/Attributes.cs b/Src/Ruby/Runtime/Attributes.cs index af85c597c..a361acbd6 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; @@ -315,6 +342,26 @@ 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 + /// (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/BlockParam.cs b/Src/Ruby/Runtime/BlockParam.cs index 903ee6176..9db9b640a 100644 --- a/Src/Ruby/Runtime/BlockParam.cs +++ b/Src/Ruby/Runtime/BlockParam.cs @@ -524,6 +524,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/Calls/ArgsBuilder.cs b/Src/Ruby/Runtime/Calls/ArgsBuilder.cs index 2d680fa67..7fe3d0a9c 100644 --- a/Src/Ruby/Runtime/Calls/ArgsBuilder.cs +++ b/Src/Ruby/Runtime/Calls/ArgsBuilder.cs @@ -230,6 +230,7 @@ public void AddCallArguments(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/* var list = (IList)splattedArg.Value; _restTakesListFrom = GetRestTakesListFrom(args, list.Count); metaBuilder.AddSplattedArgumentTest(list, splattedArg.Expression, (_restTakesListFrom >= 0) ? _restTakesListFrom + 1 : -1, + args.Signature.HasRuby2KeywordsSplat, out _listLength, out _listVariable); _actualArgumentCount += _listLength; } diff --git a/Src/Ruby/Runtime/Calls/BlockDispatcher.cs b/Src/Ruby/Runtime/Calls/BlockDispatcher.cs index 18e326743..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): @@ -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/CallArguments.cs b/Src/Ruby/Runtime/Calls/CallArguments.cs index d8212a433..13d63df0a 100644 --- a/Src/Ruby/Runtime/Calls/CallArguments.cs +++ b/Src/Ruby/Runtime/Calls/CallArguments.cs @@ -89,6 +89,13 @@ 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 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; + /// /// 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 +106,10 @@ internal Expression/*!*/ ContextScopeExpression { public DynamicMetaObject/*!*/ MetaScope { get { + if (MatchSink) { + Debug.Assert(_scope != null && _signature.HasScope); + return _scope; + } if (_signature.HasLightScope) { ScopeRead = true; } @@ -203,6 +214,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; } 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/Calls/DispatchIntrinsics.cs b/Src/Ruby/Runtime/Calls/DispatchIntrinsics.cs index 696d55507..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) { @@ -324,12 +333,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/LibraryDispatcher.cs b/Src/Ruby/Runtime/Calls/LibraryDispatcher.cs index 5a11e77fa..5d9f2a68a 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, @@ -1216,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) { @@ -1223,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; } @@ -1267,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; } @@ -1275,7 +1282,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; } @@ -1295,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; @@ -1323,7 +1331,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; } @@ -1408,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]; @@ -1482,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..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); @@ -461,8 +467,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 +476,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/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/RubyAccessorInfo.cs b/Src/Ruby/Runtime/Calls/RubyAccessorInfo.cs index ff7be0ccc..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 @@ -84,7 +97,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,11 +120,14 @@ 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); + } } } 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) { @@ -123,7 +141,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,11 +164,14 @@ 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); + } } } 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/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 84ecc49d5..47132c356 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 | RubyCallFlags.HasRuby2KeywordsSplat)) != 0 || Signature.HasSplattedArgument && Signature.HasRhsArgument) { return null; } @@ -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 @@ -263,7 +269,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: @@ -290,7 +297,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)) ? @@ -306,7 +315,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 @@ -366,9 +376,15 @@ 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; + RubyCallFlags.HasLightScope | RubyCallFlags.HasFreshSplat | RubyCallFlags.HasRuby2KeywordsSplat; private static readonly object _SharedRulesLock = new object(); private SharedRule[] _sharedRules; @@ -444,7 +460,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; } @@ -467,6 +483,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; @@ -479,6 +499,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, target)) { + return false; + } + + versionSet.TryAdd(version); + return true; + } + internal override T BindShared(object[]/*!*/ args, bool beforeDispatcher, out bool deferred) { deferred = false; RubyContext context = Context; @@ -516,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; + } } } } @@ -576,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; } @@ -721,6 +806,9 @@ 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); // MRI 3.4+: a block passed to a method that never uses it may be ignored @@ -903,7 +991,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; } @@ -916,6 +1007,33 @@ 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 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) { + var library = method as RubyLibraryMethodInfo; + if (library == null || TracePoint.CCallTracing) { + return false; + } + // 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; + } + + internal static MethodResolutionResult Resolve(MetaObjectBuilder/*!*/ metaBuilder, string/*!*/ methodName, CallArguments/*!*/ args, out RubyMemberInfo methodMissing) { @@ -1073,10 +1191,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/Calls/RubyCallSignature.cs b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs index 0d880a199..53b0e71bc 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallSignature.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallSignature.cs @@ -77,13 +77,28 @@ 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 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, + + // 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 = 8192, } /// /// RubyScope/RubyContext, (self), (argument){ArgumentCount}, (splatted-argument)?, (block)? /// public struct RubyCallSignature : IEquatable { - private const int FlagsCount = 12; + private const int FlagsCount = 14; private const int ResolveOnlyArgumentCount = (int)(UInt32.MaxValue >> FlagsCount); private const int MaxArgumentCount = ResolveOnlyArgumentCount - 1; @@ -104,6 +119,8 @@ 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; } } + 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; } } @@ -191,7 +208,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/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); + } } } diff --git a/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs b/Src/Ruby/Runtime/Calls/RubyLambdaMethodInfo.cs index d140e3412..4bb1b5e5b 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,54 @@ 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 { + 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; } } @@ -119,11 +168,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 { @@ -179,6 +239,47 @@ 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. + // The value of an assignment call (o.x = v, o[k] = v) is its last argument, as the rule passes it (Methods.Yield). + if (!aliasCall && !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 + (rhs != null ? 1 : 0) <= 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]); + } + if (rhs != null) { + jitArgs[2 + k] = AstUtils.Box(rhs); + 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. @@ -187,11 +288,15 @@ 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 ); + 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/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/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; } /// 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/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/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(IListInstalls 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) { + 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) { + // 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/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/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/Ruby/Runtime/EvalCodeCache.cs b/Src/Ruby/Runtime/EvalCodeCache.cs index dafa2c6cd..1e5298eaa 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,50 @@ 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"; + + /// + /// 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; @@ -94,12 +139,18 @@ 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(); - 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/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/Globals/GlobalVariable.cs b/Src/Ruby/Runtime/Globals/GlobalVariable.cs index 50b0875ca..1105d7c02 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); @@ -43,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/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..6ff835ede 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 @@ -162,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; @@ -231,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); @@ -259,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; @@ -323,7 +343,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/Jit/JitBlockMethod.cs b/Src/Ruby/Runtime/Jit/JitBlockMethod.cs new file mode 100644 index 000000000..dd9a9dd7c --- /dev/null +++ b/Src/Ruby/Runtime/Jit/JitBlockMethod.cs @@ -0,0 +1,332 @@ +/* **************************************************************************** + * + * -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 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 + * 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; } + + 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); + } + return null; + } + + var location = block.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. + 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; + } + + /// + /// 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); + 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; + 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, out List captured) { + var screen = new BlockScreen { _depth = block.DefinedScope.Depth }; + 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"; + } + captured = screen._captured; + 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(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); + } + return true; + } + } + } +} 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/JitCompiler.Inline.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Inline.cs index af0aa8432..38a71cccf 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 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 @@ -47,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; } @@ -56,23 +59,37 @@ 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; + } + NoteUnsampledObject(receiverLocal); + (_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; } + 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 +188,42 @@ 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 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. + /// 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 = JitStub.ClassesDefining(_context, name); + 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 74fb7bf24..54dc6d5e3 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 @@ -168,17 +171,23 @@ 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)); _usesConstants = true; + // 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; } + } return value; } /// 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); } @@ -660,6 +669,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; @@ -1197,6 +1250,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; @@ -1204,6 +1266,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?": @@ -1265,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. @@ -1273,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); } @@ -1281,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; @@ -1354,7 +1441,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; } @@ -1370,7 +1457,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) { @@ -1413,7 +1501,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; } @@ -1673,7 +1761,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); @@ -1745,7 +1834,19 @@ 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 (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; } + NoteUnsampledObject(target as LocalVariable); + 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) { @@ -1777,6 +1878,72 @@ 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). + /// + // 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; + 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) { + 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; } + 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 @@ -1789,9 +1956,18 @@ 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"); } + NoteUnsampledObject(target as LocalVariable); + } 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); } @@ -2179,8 +2355,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; @@ -2191,7 +2372,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; } @@ -2203,6 +2384,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; @@ -2217,6 +2399,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 { @@ -2224,6 +2407,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; @@ -2241,6 +2425,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/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs b/Src/Ruby/Runtime/Jit/JitCompiler.Sink.cs index b806de9fa..4814b0fc1 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) { @@ -85,8 +90,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; } @@ -108,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 { @@ -132,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; } @@ -183,7 +199,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) { @@ -288,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", "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 6b8ce93ec..ed82e8377 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; @@ -94,6 +97,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; } /// @@ -104,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 { @@ -111,6 +120,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 @@ -188,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 @@ -222,6 +239,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; @@ -279,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; @@ -343,6 +367,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; @@ -352,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; @@ -368,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; @@ -402,10 +436,14 @@ 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; 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. @@ -580,6 +618,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); @@ -594,6 +633,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; @@ -622,6 +662,17 @@ internal static JitCode TryCompile(MethodDeclaration/*!*/ ast, RubyContext/*!*/ return null; } + // 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) { // an Integer variable written in both representations: another round holding it as a long @@ -632,6 +683,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--; @@ -776,6 +838,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 && @@ -784,6 +847,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"); @@ -837,7 +901,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 @@ -1020,6 +1092,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) { @@ -1039,7 +1267,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); } @@ -1131,6 +1359,12 @@ private bool IsInitialIVarValue(RExpr/*!*/ value) { 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 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"); } @@ -1172,10 +1406,20 @@ 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 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) { - throw JitBailout.Instance; + return EmitExceptionBody(body, out type); } return EmitStatements(body.Statements, out type); } @@ -1302,6 +1546,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; @@ -1312,6 +1557,273 @@ 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 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(new JitRuntime.ClassVariableSite(owner, 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(new JitRuntime.ClassVariableSite(owner, 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"; + + /// `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"; + + /// 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 + /// 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)); + } + + /// + /// `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 (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; + 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); + } + + // 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) { 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; } + } + 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?). + /// + 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)); } @@ -1369,7 +1881,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; @@ -1417,6 +1936,64 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { return EmitAndOr(node.Left, node, node.Operation == "&&", out type); } + /// + /// 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") != "0"; + + /// + /// `@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; @@ -1425,8 +2002,12 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { 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) { 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) { @@ -1471,6 +2052,12 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { 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); } @@ -1551,6 +2138,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 +2176,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 +2200,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'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) { + 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; } + 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; + } + + // 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 + /// 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. @@ -1627,7 +2276,8 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { 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; @@ -1674,6 +2324,135 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { ); } + /// + /// 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; + + 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) { + JT at; + args.Add(Coerce(Emit(arg, out at), at, JT.Obj)); + } + } + + // `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(); + 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)))); + // 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, 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, 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 @@ -1713,6 +2492,9 @@ private void TakeGlobals(JitCode/*!*/ code, string/*!*/ name) { // 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). @@ -1746,6 +2528,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, @@ -1912,6 +2703,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; @@ -2009,6 +2807,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, "!"); @@ -2054,8 +2857,231 @@ 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); + } + + // 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_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"; + + /// `defined?(@x)'. + internal static bool IsDefinedInstanceVariable(IsDefinedExpression/*!*/ node) { + return DefinedInstanceVariables && node.Expression is InstanceVariable; + } + + /// + /// `defined?(@x)' where its value is used: whether self has the instance variable (JitRuntime.HasInstanceVariable, + /// which reads what RubyOps.IsDefinedInstanceVariable reads), and then the String the generic body answers, made as it + /// makes it (Expression.TransformIsDefined: the deduplicated frozen US-ASCII "instance-variable", with no call of + /// #freeze), 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) { + if (_loop != null) { throw Bail("defined?(@x) in an outlined loop"); } + var name = ((InstanceVariable)node.Expression).Name; + type = JT.Obj; + MSA.Expression str = StringLiteral.TransformFrozen("instance-variable", RubyEncoding.Ascii, null); + 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"; + + /// + /// `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"; + + /// `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?")); + } + + /// `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) { + 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); @@ -2068,9 +3094,21 @@ 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); } + // `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); } + + // `s[a..b]', `ary[a...b]' (EmitRangeSlice) + if (IsRangeSlice(node)) { return EmitRangeSlice(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) { @@ -2210,6 +3248,37 @@ internal static bool IsRaiseCall(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; @@ -2222,6 +3291,13 @@ internal static bool IsRaiseCall(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); } @@ -2269,6 +3345,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; @@ -2304,6 +3385,14 @@ internal static bool IsRaiseCall(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); } + // `: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 @@ -2392,6 +3481,11 @@ internal static bool IsRaiseCall(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 @@ -2638,6 +3732,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); @@ -3028,6 +4140,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; @@ -3062,12 +4196,34 @@ 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; _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) @@ -3077,6 +4233,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 +4248,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; @@ -3151,23 +4314,174 @@ 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) { - return No(body); + // 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); } + /// + /// 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; } @@ -3205,6 +4519,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 { @@ -3244,6 +4560,11 @@ 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); } // 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 @@ -3266,10 +4587,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; @@ -3288,6 +4610,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; @@ -3363,11 +4699,42 @@ 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) || JitCompiler.IsDestructuringAssignment(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) { + 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; 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; @@ -3451,6 +4818,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); @@ -3461,6 +4833,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) { @@ -3505,12 +4882,18 @@ 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; 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) { @@ -3537,15 +4920,31 @@ 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)); + } + // `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). 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])); } + // `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) @@ -3586,6 +4985,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..5a2b074f1 100644 --- a/Src/Ruby/Runtime/Jit/JitIntrinsics.cs +++ b/Src/Ruby/Runtime/Jit/JitIntrinsics.cs @@ -422,6 +422,119 @@ 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); + } + + /// + /// `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(); + } + + /// + /// `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); + } + + /// + /// `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 + /// 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 @@ -444,6 +557,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; @@ -505,6 +644,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); @@ -655,6 +819,66 @@ 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; } + 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 @@ -845,7 +1069,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(); } @@ -974,6 +1198,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/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/JitLoopCompiler.cs b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs index 8e1dfbb5a..457ac615f 100644 --- a/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs +++ b/Src/Ruby/Runtime/Jit/JitLoopCompiler.cs @@ -54,12 +54,32 @@ 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_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"; + + /// + /// 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 +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) { + out JitLoopGuard loopGuard, bool longRuns = false, bool lightFrame = false, ICollection deadAtExit = null, + int blockArgIndex = -1) { loopGuard = null; @@ -175,6 +196,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, }; }; @@ -207,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; @@ -231,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 @@ -267,10 +296,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"))) )); } @@ -339,6 +374,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); } @@ -348,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) { @@ -383,6 +437,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/Jit/JitRuntime.cs b/Src/Ruby/Runtime/Jit/JitRuntime.cs index 08bbc6657..c6af2cdff 100644 --- a/Src/Ruby/Runtime/Jit/JitRuntime.cs +++ b/Src/Ruby/Runtime/Jit/JitRuntime.cs @@ -39,6 +39,28 @@ 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"; + + /// + /// 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"; + + /// + /// 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. /// @@ -346,6 +368,12 @@ public static long MethodLoopSafePointSlow(JitLoopGuard/*!*/ guard, StrongBox + /// 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; + } + + /// `__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); } @@ -434,6 +496,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) { @@ -588,7 +655,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); } /// @@ -599,7 +670,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); } /// @@ -744,13 +818,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) { @@ -1176,6 +1267,152 @@ 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. + /// + /// 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 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(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 (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(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(site.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); + } + + /// 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. + /// + 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. + /// + 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; } @@ -1183,6 +1420,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) { @@ -1252,6 +1501,47 @@ 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; + } + + /// + /// 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); } @@ -1274,6 +1564,10 @@ 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, 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"); @@ -1288,6 +1582,43 @@ internal void Set(long epoch, int version, RubyContext constantsOf, int constant System.Threading.Volatile.Write(ref Epoch, epoch); } + /// + /// 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; + } + + /// + /// 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/Jit/JitStub.cs b/Src/Ruby/Runtime/Jit/JitStub.cs index c83d7a13a..012e8c3a3 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) { @@ -248,12 +250,25 @@ 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) { 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(); } } @@ -350,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; } @@ -430,6 +446,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 +591,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; @@ -605,6 +630,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); @@ -680,8 +713,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(); @@ -697,8 +734,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, @@ -708,9 +758,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; @@ -771,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; @@ -778,11 +861,25 @@ 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; + // 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++; @@ -794,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() { @@ -806,6 +920,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 @@ -822,6 +942,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 @@ -837,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) { @@ -874,7 +1007,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(); } @@ -991,7 +1124,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 }; } /// @@ -1101,9 +1234,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; } @@ -1182,7 +1323,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 ------------------------------------------------------------------ @@ -1239,6 +1385,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) { @@ -1254,7 +1404,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; @@ -1263,7 +1413,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))); @@ -1296,6 +1447,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. @@ -1325,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); @@ -1648,8 +1820,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"; } @@ -1657,11 +1832,59 @@ 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. 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 +1946,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; } @@ -1838,17 +2061,18 @@ 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) { + // 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. + // 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()) { - context.ObjectClass.EnumerateConstants((module, constantName, value) => { - var cls = value as RubyClass; + foreach (var cls in ClassesDefining(context, name, false)) { 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); } - } - return false; - }); + if (cls.TryGetDefinedMethod(name, out method) && method is RubyMethodInfo info) { candidates.Add(info); } + } } foreach (var info in candidates) { if (IsLeafMethod(info, true)) { return true; } @@ -1856,6 +2080,48 @@ internal static bool IsLeafMethodOfSomeClass(RubyContext/*!*/ context, string/*! 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()) { + 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 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); + } + /// /// Decides, statically and cheaply, whether a method is worth putting a stub on, and /// returns the trampoline that replaces the generic delegate. Returns the generic @@ -1872,6 +2138,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) { @@ -1898,7 +2165,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) { @@ -1975,6 +2253,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); @@ -2015,6 +2294,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); @@ -2055,6 +2335,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); @@ -2095,6 +2376,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); @@ -2135,6 +2417,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); @@ -2175,6 +2458,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); @@ -2215,6 +2499,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/Src/Ruby/Runtime/Loader.cs b/Src/Ruby/Runtime/Loader.cs index 4de7a2dc7..827a072d6 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; } @@ -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) { @@ -1544,17 +1544,31 @@ 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)); 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 MutableString loadedPath = Protocols.CastToPath(toPath, file); - if (paths.Any((path) => loadedPath.Equals(path))) { + if (paths.Any((path) => SameFeaturePath(loadedPath, path))) { return true; } } @@ -1579,7 +1593,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 +1620,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/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/Osr/BlockLoopSite.cs b/Src/Ruby/Runtime/Osr/BlockLoopSite.cs index 4a5713929..f936aa5e2 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) { @@ -243,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) { @@ -289,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); } } @@ -448,6 +512,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() { @@ -667,6 +737,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/Osr/OsrLoopSite.cs b/Src/Ruby/Runtime/Osr/OsrLoopSite.cs index a9dcc817f..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; + 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; @@ -141,6 +166,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; @@ -204,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 @@ -216,10 +252,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(); @@ -281,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); + var typed = JitLoopCompiler.TryCompile(LoopAst, Context, ScopeDepth, TupleArgIndex, tuples, SelfArgIndex, ScopeArgIndex, out guard, LongRuns, InLightFrame, DeadAtExit, BlockArgIndex); _guard = guard; _typed = typed; } catch (Exception e) { @@ -318,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} 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} 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/Src/Ruby/Runtime/PrecompiledCode.cs b/Src/Ruby/Runtime/PrecompiledCode.cs index 9c1b30e62..039bf3277 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. @@ -227,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); } /// @@ -322,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; @@ -358,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); } @@ -536,6 +568,181 @@ 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), 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, + string evalModule) { + 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)).Append('\u0001').Append(evalModule ?? "\u0003"); + 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. 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)); + } + + // 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, _runtimeRoot ?? _compiledRoot); + 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 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). + /// + 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, string evalModule) { + 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)), + ["module"] = evalModule, + }; + 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 +798,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 +835,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/Protocols.cs b/Src/Ruby/Runtime/Protocols.cs index b128a35d7..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)); } /// @@ -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)); } } } @@ -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 45a135cd9..389eb0429 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. @@ -289,6 +296,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. @@ -353,6 +372,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(); @@ -770,6 +801,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) : @@ -823,9 +857,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) { @@ -1984,10 +2018,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); @@ -2062,11 +2096,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; } @@ -2152,11 +2186,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); @@ -2429,6 +2463,19 @@ 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; + } + // 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) { @@ -2936,14 +2983,53 @@ 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; } + 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. @@ -2993,13 +3079,23 @@ 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)) { return result; } + // marked before the entry is added: see TryGetClrTypeInstanceData + var array = obj as RubyArray; + if (array != null) { + array.MarkMayHaveInstanceData(); + } + NoteTableInstanceData(obj); return _referenceTypeInstanceData.GetValue(obj, _CreateInstanceData); } @@ -3012,6 +3108,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 @@ -3094,7 +3210,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 @@ -3236,6 +3352,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 @@ -3403,6 +3528,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). @@ -3568,9 +3707,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; } } @@ -3579,7 +3719,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); @@ -3616,7 +3756,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; } @@ -3627,7 +3767,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 @@ -3893,7 +4033,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(); @@ -3906,12 +4046,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) { @@ -3950,7 +4090,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); @@ -3961,7 +4101,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; @@ -3971,7 +4111,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; @@ -4002,6 +4142,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 /// @@ -4263,6 +4432,26 @@ 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 - precompiled startup-library code included, which + /// RubyUtils.TryGetCallerSourceLocation does not answer for. + /// + public bool TryGetCallerSourceLocation(out string path, out int line) { + // The core prelude's frames are left out of a backtrace, so while it loads the innermost frame is the require + // of it (gem_prelude.rb), which is not where its code is; a library file it loads (pathname_builtin.rb) has + // frames of its own, which are. + if (Loader.IsLoadingCorePrelude) { + if (TryGetCurrentSourceLocation(true, out path, out line) && Loader.IsIronRubyLibraryFile(path)) { + return true; + } + path = null; + line = 0; + return false; + } + 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 @@ -4309,6 +4498,41 @@ internal bool TryGetCurrentSourceLocation(bool fromFrameRecords, out string path #endregion + // The encodings of the strings sources were named with that are not the default for the name (see + // GetSourcePathEncoding): an eval's file name given in another. A name eval is given once per place it is written. + private readonly ConcurrentDictionary/*!*/ _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. @@ -4373,13 +4597,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 - ); + )); } } @@ -4396,7 +4620,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())); } } @@ -4745,7 +4969,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 @@ -4984,6 +5208,7 @@ private void RunShutdownHandlers(ref SystemExit lastSystemExit, ref Exception la try { exitHandler(); } catch (SystemExit e) { + CurrentException = e; lastSystemExit = e; } catch (Exception e) { CurrentException = e; @@ -5010,6 +5235,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; @@ -5443,12 +5671,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())); } } @@ -5681,7 +5909,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. @@ -5703,7 +5931,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 5ff0cafc8..65062d609 100644 --- a/Src/Ruby/Runtime/RubyExceptionData.cs +++ b/Src/Ruby/Runtime/RubyExceptionData.cs @@ -80,6 +80,30 @@ 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; + } + + /// + /// 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; @@ -516,6 +540,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; @@ -768,7 +802,18 @@ 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 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); + } } return _message; } diff --git a/Src/Ruby/Runtime/RubyOps.FlowControl.cs b/Src/Ruby/Runtime/RubyOps.FlowControl.cs index 4165c659e..a9cad89cd 100644 --- a/Src/Ruby/Runtime/RubyOps.FlowControl.cs +++ b/Src/Ruby/Runtime/RubyOps.FlowControl.cs @@ -32,15 +32,41 @@ public static partial class RubyOps { /// [Emitted] 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) { + 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. 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.MatchSink.cs b/Src/Ruby/Runtime/RubyOps.MatchSink.cs new file mode 100644 index 000000000..c1b4a786d --- /dev/null +++ b/Src/Ruby/Runtime/RubyOps.MatchSink.cs @@ -0,0 +1,82 @@ +/* **************************************************************************** + * + * 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): 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 { + private const int MaxFreeMatchSinks = 8; + + // 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 MatchSinkPool t_matchSinks; + + /// + /// 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; + } + } + return new RubyTopLevelScope(context); + } + + /// + /// Called as the frame that took returns: its $~ is no one's any more. + /// + 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; + } + } + + /// + /// 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, RubyScope sink) { + if (sink != null) { + scope.CurrentMatch = ((RubyTopLevelScope)sink).CurrentMatch; + } + return scope; + } + } +} diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index aa7b60caf..51c6ff9fd 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); @@ -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) { @@ -235,7 +229,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 @@ -253,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); } @@ -264,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; @@ -286,14 +297,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) { @@ -311,7 +316,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); @@ -404,6 +409,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) { @@ -414,10 +422,29 @@ 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); methodScope.ClearCallState(); parked.Scope = methodScope; parked.ThreadId = Environment.CurrentManagedThreadId; - if (Interlocked.CompareExchange(ref slot.Parked, parked, null) == null) { + 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. + // A slot that holds a scope already - the caller's level of a recursion, or another thread's - is left to + // it, and this call parks into a free entry of Deeper by exchange (perf/permute), or keeps its ParkedProcs + // as Spare when there is none, as the exchange did; two calls that both read the slot empty both write, + // and the first one's scope is dropped, as above. + if (Volatile.Read(ref slot.Parked) == null) { + Volatile.Write(ref slot.Parked, parked); + return; + } + if (TryParkDeeper(slot, parked)) { + return; + } + } else if (Interlocked.CompareExchange(ref slot.Parked, parked, null) == null || TryParkDeeper(slot, parked)) { return; } } else { @@ -427,6 +454,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 @@ -457,9 +502,14 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R /// 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; } @@ -470,9 +520,46 @@ public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, R 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. @@ -480,13 +567,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; } @@ -520,9 +610,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); @@ -569,7 +659,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 @@ -577,7 +675,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; @@ -743,6 +845,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) { @@ -798,6 +990,62 @@ 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. + /// + /// 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); + 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; @@ -839,12 +1087,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 @@ -950,6 +1222,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)); @@ -1041,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) { @@ -1318,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; @@ -1347,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; @@ -1367,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); } @@ -1553,7 +1843,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; @@ -1573,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); @@ -1641,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 { @@ -1703,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 { @@ -2295,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); } @@ -2336,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) { @@ -2347,9 +2638,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; } @@ -2395,6 +2691,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); @@ -2684,9 +2990,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 @@ -2736,6 +3058,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; @@ -2743,6 +3081,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 @@ -2965,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]; @@ -3089,6 +3433,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; @@ -3412,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; } @@ -4183,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 @@ -4386,12 +4800,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); @@ -4572,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)))); } } @@ -4604,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; } @@ -4631,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; } @@ -4640,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(); } @@ -4689,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; } @@ -4698,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; } @@ -4717,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; } @@ -4732,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; } @@ -4741,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; } @@ -4755,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) { @@ -4763,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 @@ -4808,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 @@ -4825,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 @@ -4842,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 @@ -4859,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 @@ -4877,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)) }; } @@ -4891,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 @@ -4904,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] @@ -5439,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 @@ -5449,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 @@ -5457,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", value)); + throw IronRuby.Runtime.RubyExceptionData.Unkept(RubyExceptions.CreateRangeError(String.Format("float {0} out of range of integer", RubyUtils.FormatFloatG10(value)))); } } @@ -5822,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); } @@ -5896,8 +6338,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] @@ -6097,8 +6538,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); } @@ -6134,8 +6575,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 @@ -6164,9 +6605,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/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 9c64af656..938b3a1af 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; } @@ -390,6 +395,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; @@ -422,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; } } @@ -441,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; } @@ -463,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); } } } @@ -693,14 +720,87 @@ 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 #region Refinements @@ -902,7 +1002,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; @@ -938,8 +1041,12 @@ 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; + // 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; } @@ -1302,35 +1409,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--) { @@ -1357,6 +1472,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; @@ -1550,7 +1677,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) @@ -1582,7 +1731,7 @@ internal void Reinitialize(MutableTuple locals, object selfObject, Proc blockPar _activeFlowControlScope = rfc.IsActiveMethod ? rfc : this; } else { _activeFlowControlScope = this; - InitializeRfc(blockParameter); + InitializeMethodRfc(blockParameter); } } @@ -1783,6 +1932,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/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); diff --git a/Src/Ruby/Runtime/RubyStackTraceBuilder.cs b/Src/Ruby/Runtime/RubyStackTraceBuilder.cs index ee15e6af0..cd7e0ff5a 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; @@ -53,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; @@ -161,7 +170,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; @@ -169,7 +178,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; @@ -468,11 +477,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)); } } @@ -495,6 +504,26 @@ 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); + } + // 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); + } + private void SetCompiledFrames(Precompiled.PrecompiledFrames.Frame[] frames) { _compiledFrames = frames; _compiledFrameIndex = (frames != null) ? frames.Length - 1 : -1; @@ -507,6 +536,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; @@ -731,56 +769,90 @@ private void AddBacktrace(IEnumerable stackTrace, int skipFrames, bo _libraryRun++; } _callSiteSinceLastLibrary = false; + _operatorFrameLast = _isOperatorFrame; continue; } } else { if (_libraryRun > 0 && IsCallSiteFrame(frame.GetMethod())) { _callSiteSinceLastLibrary = true; } - 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); + if (_isHiddenFrame) { + _operatorFrameLast = false; } continue; } - foreach (var deferred in _deferredMethodNames) { - if (skipFrames == 0) { - _trace.Add(CreateFrame(FormatFrame(file, line, deferred))); - } else { - skipFrames--; - skippedAny = true; + // 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; + } + } + } + _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; + } + + DropOperatorFrame(); + foreach (var deferred in _deferredMethodNames) { + if (skipFrames == 0) { + _trace.Add(CreateFrame(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(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 @@ -815,6 +887,7 @@ private int AddInternalFrame(string methodName) { return 0; } int deferred = _deferredMethodNames.Count; + DropOperatorFrame(); string owner, name; SplitLabel(methodName, out owner, out name); @@ -839,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); @@ -926,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; @@ -953,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: @@ -986,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); } } @@ -1078,6 +1170,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 +1185,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 { diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 3ccf38f53..a31981196 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 /// @@ -186,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")); } } @@ -236,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); @@ -261,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(':'); @@ -285,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(">"); @@ -302,8 +329,43 @@ 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); + } + } + + /// + /// 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 = MutableString.CreateMutable(context.GetIdentifierEncoding()); + MutableString str = CreateObjectDescription(context, className); str.Append("#<"); str.Append(className); @@ -734,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))); } } @@ -797,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))); } } @@ -1216,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 @@ -1230,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) - )); + ))); } } } @@ -1244,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: @@ -1257,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) - )); + ))); } } } @@ -1381,14 +1443,15 @@ public static object SetHashElement(RubyContext/*!*/ context, IDictionary + /// 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) { @@ -74,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); 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/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/Src/StdLib/ironruby/argf.rb b/Src/StdLib/ironruby/argf.rb index b5365fb91..5861db678 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 @@ -255,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) @@ -270,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) @@ -289,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 @@ -429,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) 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/date/format.rb b/Src/StdLib/ironruby/date/format.rb index 92945cf9c..49eb07335 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. @@ -400,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) @@ -856,6 +861,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 @@ -864,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) || @@ -1073,7 +1081,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(':') 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. diff --git a/Src/StdLib/ironruby/ironruby/complex.rb b/Src/StdLib/ironruby/ironruby/complex.rb index 57ccb77a0..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. @@ -810,7 +812,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 9ab1de5b4..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#**. @@ -282,7 +284,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 @@ -550,7 +553,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 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}" diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 329b23a18..f7acc1607 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 @@ -237,15 +237,18 @@ 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 } 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. @@ -284,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) @@ -356,7 +343,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 @@ -470,10 +457,16 @@ 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 = {} + # 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) @@ -483,10 +476,16 @@ 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? - each { |*values| yield(__enum_item__(values), memo) } + 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) } + 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) # Ruby 2.2 added the `n` form: the n smallest/largest, as an Array. # @@ -500,7 +499,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 @@ -536,8 +535,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) @@ -578,7 +577,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) @@ -598,29 +597,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 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__? - decorated = [] - index = 0 + return __list_sort_by_key__(&block) if __plain_each__? + 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.__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 - 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__ @@ -633,8 +630,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] } @@ -649,14 +646,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) @@ -698,10 +695,22 @@ 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 = {} 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 @@ -1337,6 +1346,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. @@ -1470,17 +1483,36 @@ 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 - if ::Integer === x && ::Integer === acc + pending = false + if ::Integer === acc && __builtin_exact_plus__? + # 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. Its #+ is the built-in one (asked once a call): MRI's rb_ary_sum calls no + # Integer#+ a program has defined, and with one the loop below adds with __exact_add__ instead. + j = 0 + while i < __ary_size__ + x = yield(__ary_at__(i)) + i = i.succ + break unless ::Integer === x && ::Integer === acc acc = acc + x - next + j = i 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) + 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 + # 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 @@ -1488,31 +1520,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 @@ -1534,47 +1550,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 @@ -1678,7 +1676,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 @@ -1706,7 +1704,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) @@ -1718,7 +1716,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 @@ -2376,6 +2374,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 @@ -3009,7 +3012,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 @@ -3311,7 +3314,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 @@ -3454,8 +3458,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 @@ -3587,7 +3594,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) @@ -3899,6 +3908,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) @@ -3913,25 +3924,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. @@ -3992,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/ @@ -5520,7 +5524,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 @@ -5562,10 +5566,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 +5600,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) @@ -5613,7 +5623,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) @@ -5786,10 +5795,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 @@ -5846,7 +5856,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__ @@ -5891,9 +5906,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 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), 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 @@ -6006,6 +6026,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) @@ -6069,10 +6114,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 @@ -6560,23 +6605,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 @@ -6619,8 +6663,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 @@ -6715,14 +6759,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? @@ -6849,6 +6893,7 @@ def __set_result__(value) def result @__result__ end + ::Enumerator.__iter_cursor_method__(self, :result) end module Kernel @@ -6856,7 +6901,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 @@ -6865,7 +6931,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. @@ -6873,8 +6939,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 @@ -6893,17 +6960,30 @@ 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 "&"). 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 @@ -7327,7 +7407,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". @@ -7524,14 +7604,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) @@ -7623,7 +7700,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 @@ -7656,14 +7733,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) @@ -7943,7 +8016,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 @@ -8218,13 +8291,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) @@ -8372,8 +8445,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) @@ -8434,6 +8508,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 @@ -8475,14 +8560,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) @@ -8533,8 +8624,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? @@ -8682,7 +8774,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 @@ -8691,6 +8802,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 @@ -9124,6 +9238,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 @@ -9195,7 +9317,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 @@ -9205,12 +9354,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 @@ -9327,6 +9485,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" @@ -9403,13 +9575,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 @@ -9442,8 +9623,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 @@ -9451,8 +9637,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 @@ -9604,10 +9795,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 @@ -9616,11 +9814,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 @@ -9725,8 +9930,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) @@ -10203,7 +10412,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. @@ -10400,7 +10609,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) @@ -10413,6 +10621,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 @@ -10448,6 +10658,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 @@ -10490,6 +10704,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__ @@ -10628,10 +10863,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__ @@ -10740,22 +10978,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 @@ -10777,90 +11007,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 + + # 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 :__value_size__ + private :__offset_length__ - def __directive__(type) + 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 @@ -10896,16 +11368,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 @@ -10925,15 +11397,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 @@ -10983,9 +11465,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) @@ -11353,6 +11858,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__ @@ -11406,7 +11915,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 @@ -12015,7 +12524,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 # 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 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 @@ -12377,7 +12906,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. @@ -12386,7 +12915,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 @@ -12424,37 +12953,33 @@ 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 - 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 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 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 @@ -12474,17 +12999,27 @@ 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, **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__ @@ -12523,6 +13058,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 @@ -12564,7 +13102,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 @@ -12578,7 +13116,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) @@ -12599,7 +13138,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) @@ -12809,7 +13349,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) @@ -13460,22 +14000,25 @@ 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 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? ::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 @@ -13483,25 +14026,49 @@ 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 + # 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 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 @@ -13769,5 +14336,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" 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 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/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 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/aot/IronRuby.Aot/AotCompiler.cs b/Util/aot/IronRuby.Aot/AotCompiler.cs index b3afb7173..153499221 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 + "/"; @@ -229,6 +231,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 +549,107 @@ 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; + // 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; + } + + /// 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 = 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, + 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); + // 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}"); + 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); + 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, RootPrefix)); + 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 +675,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(); } @@ -997,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)"); @@ -1036,6 +1172,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); @@ -1117,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)); } /// @@ -1315,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; @@ -1378,6 +1549,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 ce60eb9e8..0bbfb07f0 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,63 @@ 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}"; + + 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(); + 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 { + // 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"], + 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"), + Module = (string)o["module"], + }); + } + 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 +106,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 +124,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 +205,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 +242,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/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/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..873c404e5 --- /dev/null +++ b/Util/aot/startup-evals.txt @@ -0,0 +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"],"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":"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":"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":"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/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/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":"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/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/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":"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":"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":"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/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":"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/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":"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":"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/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":"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":"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 aa3e3f05e..5f52e159f 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,32 @@ 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}/") + # 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 +end + sections = [] seen = {} COMMANDS.each do |title, args, stdin| @@ -62,6 +93,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 +107,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 +130,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" 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) } 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/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 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/bench/core-small.rb b/Util/bench/core-small.rb index 9ec13f7e4..f1e45ffaf 100644 --- a/Util/bench/core-small.rb +++ b/Util/bench/core-small.rb @@ -99,6 +99,17 @@ 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 + 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 + 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 @@ -203,3 +214,14 @@ 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 } +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 } +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/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/bench/deadconst-shapes.rb b/Util/bench/deadconst-shapes.rb new file mode 100644 index 000000000..2b082051e --- /dev/null +++ b/Util/bench/deadconst-shapes.rb @@ -0,0 +1,114 @@ +# 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 +FSTEP = 0.5 + +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 + + # 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 + 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 } +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/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/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/dmeth-shapes.rb b/Util/bench/dmeth-shapes.rb new file mode 100644 index 000000000..1791a3432 --- /dev/null +++ b/Util/bench/dmeth-shapes.rb @@ -0,0 +1,85 @@ +# 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: `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 = 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 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 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 + 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 } +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 } +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/bench/dup-shapes.rb b/Util/bench/dup-shapes.rb new file mode 100644 index 000000000..b87a47580 --- /dev/null +++ b/Util/bench/dup-shapes.rb @@ -0,0 +1,55 @@ +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 +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" +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 } +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/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/erb-shapes.rb b/Util/bench/erb-shapes.rb index 8803f7c73..47c4b22d9 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,18 @@ 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 } +# 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/bench/extiter-abandoned.rb b/Util/bench/extiter-abandoned.rb new file mode 100644 index 000000000..9931a9b38 --- /dev/null +++ b/Util/bench/extiter-abandoned.rb @@ -0,0 +1,43 @@ +# 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 }, + "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] +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/bench/extiter-shapes.rb b/Util/bench/extiter-shapes.rb new file mode 100644 index 000000000..81b397521 --- /dev/null +++ b/Util/bench/extiter-shapes.rb @@ -0,0 +1,81 @@ +# 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("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("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 } +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/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/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/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/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/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/bench/havlak-shapes.rb b/Util/bench/havlak-shapes.rb new file mode 100644 index 000000000..f3d55fc49 --- /dev/null +++ b/Util/bench/havlak-shapes.rb @@ -0,0 +1,137 @@ +# 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 + +# 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) + 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 } +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/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(/(? 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/bench/isa-shapes.rb b/Util/bench/isa-shapes.rb new file mode 100644 index 000000000..e9939e467 --- /dev/null +++ b/Util/bench/isa-shapes.rb @@ -0,0 +1,51 @@ +# is_a?, kind_of? and instance_of? in hot methods (JitCompiler.EmitTypeTest): one receiver class, two, four, a module +# 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 +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 + 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) + 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 } +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/bench/iter-shapes.rb b/Util/bench/iter-shapes.rb new file mode 100644 index 000000000..0d240928d --- /dev/null +++ b/Util/bench/iter-shapes.rb @@ -0,0 +1,100 @@ +# 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). +# 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 + def nyl(a) = ny { 1 } + 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 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 + 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 + 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 } +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/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/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/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/bench/jit-masgn-shapes.rb b/Util/bench/jit-masgn-shapes.rb new file mode 100644 index 000000000..362f48d8e --- /dev/null +++ b/Util/bench/jit-masgn-shapes.rb @@ -0,0 +1,68 @@ +# 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); +# 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" +# 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 + 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 +# 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 } +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/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/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/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/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/bench/loopivar-shapes.rb b/Util/bench/loopivar-shapes.rb new file mode 100644 index 000000000..3b98b782c --- /dev/null +++ b/Util/bench/loopivar-shapes.rb @@ -0,0 +1,69 @@ +# 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. +# +# 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) +# 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 + # 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) + 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/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/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/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/bench/prelude-cost.rb b/Util/bench/prelude-cost.rb index 7ef869e50..0dac3e1d6 100644 --- a/Util/bench/prelude-cost.rb +++ b/Util/bench/prelude-cost.rb @@ -305,6 +305,45 @@ 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 + +# 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) + 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 + # 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 File.read("/proc/thread-self/schedstat").to_i / 1e9 rescue SystemCallError @@ -451,3 +490,62 @@ 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 } + +# 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 } +# 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 } +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 } +# `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/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/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/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/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/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/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/bench/strsearch-shapes.rb b/Util/bench/strsearch-shapes.rb new file mode 100644 index 000000000..baa064e59 --- /dev/null +++ b/Util/bench/strsearch-shapes.rb @@ -0,0 +1,336 @@ +# 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" +require 'strscan' +SS_U = ("héllo wörld, " * 800)[0, 10000] +SS_A = ("hello world, " * 800)[0, 10000] + +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) + # 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 + +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 +# 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 } +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 } +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/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/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/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/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/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/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/block-loop-matrix.rb b/Util/block-loop-matrix.rb index 5fb16db28..613d91f72 100644 --- a/Util/block-loop-matrix.rb +++ b/Util/block-loop-matrix.rb @@ -602,3 +602,105 @@ 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 + +# ---------------------------------------------------------------- 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/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 diff --git a/Util/case-string-matrix.rb b/Util/case-string-matrix.rb new file mode 100644 index 000000000..fd72d947e --- /dev/null +++ b/Util/case-string-matrix.rb @@ -0,0 +1,165 @@ +# 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] + +# 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| + 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)" 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 diff --git a/Util/cruby-test/PACKAGES.md b/Util/cruby-test/PACKAGES.md index 722e4cb01..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, 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, 69 clean, 72 with +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. @@ -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) | diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 506d31e8e..e3c5eaa08 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 0 failures 1 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 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 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 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 4 failures 25 errors 31 skips -test_call 65 tests 2 failures 0 errors 0 skips +test_box 65 tests 5 failures 22 errors 31 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 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 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 -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 7 failures 0 errors 1 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 -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_fnmatch 15 tests 3 failures 0 errors 0 skips +test_float 63 tests 0 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_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_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 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 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 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_marshal 234 tests 8 failures 3 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 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 -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 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 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_pack 56 tests 1 failures 0 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 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 2 failures 1 errors 0 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 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_require_lib 39 tests 0 failures 2 errors 0 skips -test_rubyoptions 68 tests 50 failures 1 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 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 -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 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 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_system 8 tests 2 failures 1 errors 0 skips -test_thread 98 tests 5 failures 6 errors 4 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 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 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 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 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: 69 clean, 72 with failures, 1 without a summary +10371 tests, 2552197 assertions, 454 failures, 3123 errors, 70 skips; 6724 passing diff --git a/Util/deadconst-matrix.rb b/Util/deadconst-matrix.rb new file mode 100644 index 000000000..e66fe0319 --- /dev/null +++ b/Util/deadconst-matrix.rb @@ -0,0 +1,359 @@ +# 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}" + +# ---------------------------------------------------------------- 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/dmeth-jit-matrix.rb b/Util/dmeth-jit-matrix.rb new file mode 100644 index 000000000..9389c5181 --- /dev/null +++ b/Util/dmeth-jit-matrix.rb @@ -0,0 +1,302 @@ +# 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) }] + +# 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/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/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/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) } 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"]) } 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) } diff --git a/Util/extiter-matrix.rb b/Util/extiter-matrix.rb new file mode 100644 index 000000000..ceada98fc --- /dev/null +++ b/Util/extiter-matrix.rb @@ -0,0 +1,728 @@ +# 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 } + +# --- collecting methods (#map, #select, #reject...) taken with #next: results from what was fed ------ +def fed_result(e, feeds) + out = [] + feeds.each { |f| out << e.next; e.feed(f) unless f.nil? } + [out, stop_of(e).result] +end +probe("coll_ary_map") { fed_result([1, 2, 3].map, [:a, nil, :c]) } +probe("coll_ary_collect") { fed_result([1, 2].collect, [nil, 5]) } +probe("coll_ary_select") { fed_result([1, 2, 3].select, [true, false, 1]) } +probe("coll_ary_filter") { fed_result([1, 2, 3].filter, [nil, :x, nil]) } +probe("coll_ary_reject") { fed_result([1, 2, 3].reject, [true, nil, false]) } +probe("coll_ary_find_all") { fed_result([1, 2, 3].find_all, [true, nil, 2]) } +probe("coll_range_map") { fed_result((1..3).map, [:a, :b, nil]) } +probe("coll_range_select") { fed_result((1..4).select, [true, false, true, nil]) } +probe("coll_range_reject") { fed_result((1...3).reject, [nil, true]) } +probe("coll_range_find_all") { fed_result((1..2).find_all, [1, nil]) } +probe("coll_hash_map") { fed_result({ a: 1, b: 2 }.map, [:x, :y]) } +probe("coll_hash_find_all"){ fed_result({ a: 1, b: 2 }.find_all, [true, nil]) } +probe("coll_hash_select") { fed_result({ a: 1, b: 2 }.select, [true, nil]) } +probe("coll_hash_reject") { fed_result({ a: 1, b: 2 }.reject, [true, nil]) } +probe("coll_struct_map") { S2 = Struct.new(:p, :q) unless defined?(S2); fed_result(S2.new(1, 2).map, [:m, nil]) } +probe("coll_times_map") { fed_result(3.times.map, [:a, :b, :c]) } +probe("coll_empty") { [stop_of([].map).result, stop_of([].select).result, stop_of((1...1).map).result] } +probe("coll_no_feed") { [stop_of([1, 2].map).result, stop_of([1, 2].select).result, stop_of([1, 2].reject).result] } +probe("coll_feed_first") { e = [1, 2].map; e.feed :early; [e.next, e.next, stop_of(e).result] } +probe("coll_feed_last") { e = [1, 2].map; e.next; e.next; e.feed :last; stop_of(e).result } +probe("coll_peek") { e = [1, 2].select; [e.peek, e.next, e.peek].tap { e.feed true; e.next }; stop_of(e).result } +probe("coll_next_values") { e = { a: 1 }.map; [e.peek_values, e.next_values] } +probe("coll_hash_next_values") { e = { a: 1 }.find_all; [e.peek_values, e.next_values] } +probe("coll_range_nv") { e = (1..2).map; [e.next_values, e.peek_values] } +probe("coll_loop") { e = [1, 2].map; loop { e.feed(e.next * 10) } } +probe("coll_loop_select") { e = [1, 2, 3, 4].select; loop { v = e.next; e.feed v.even? } } +probe("coll_again") { e = [1].map; e.next; e.feed :f; s1 = (e.next rescue $!); s2 = (e.next rescue $!); [s1.result, s2.result, s2.cause.equal?(s1)] } +probe("coll_result_fresh") { e = [1].map; r1 = stop_of(e).result; e.rewind; r2 = stop_of(e).result; [r1, r2, r1.equal?(r2)] } +probe("coll_rewind_mid") { e = [1, 2].map; e.next; e.feed :a; e.rewind; e.next; e.feed :b; e.next; stop_of(e).result } +probe("coll_append") { a = [1, 2]; e = a.map; out = [e.next]; a << 3; out << e.next << e.next; [out, stop_of(e).result] } +probe("coll_shrink_select") { a = [1, 2, 3]; e = a.select; e.next; e.feed true; e.next; a.clear; e.feed true; [(e.next rescue :stop), (e.next rescue $!.result)] } +probe("coll_replace_select") { a = [1, 2, 3]; e = a.select; e.next; a[0] = :z; e.feed true; e.next; a[1] = :w; e.feed true; e.next; stop_of(e).result } +probe("coll_replace_reject") { a = [1, 2]; e = a.reject; e.next; a[0] = :z; e.next; stop_of(e).result } +probe("coll_hash_mutate_value") { h = { a: 1 }; e = h.find_all; v = e.next; v << :extra; e.feed true; stop_of(e).result } +probe("coll_range_select_value") { e = (1..2).select; v = e.next; e.feed true; e.next; [v, stop_of(e).result] } +probe("coll_subclass") { c = Class.new(Array); r = stop_of(c.new([1, 2]).select).result; [r, r.class == Array] } +probe("coll_redef_map") do + c = Class.new(Array) { def map; return to_enum(:map) unless block_given?; super { |x| yield(x) }.reverse; end } + e = c.new([1, 2]).map + e.next; e.feed :a; e.next; e.feed :b + stop_of(e).result +end +probe("coll_singleton_select") { a = [1, 2]; def a.select; yield 9; [:own]; end; e = a.select; [e.next, stop_of(e).result] } +probe("coll_each_redef_range") { r = (1..2); def r.each; yield :x; self; end; e = r.map; [e.next, stop_of(e).result] } +probe("coll_hash_each_redef") { h = { a: 1 }; def h.each; yield [:q, 0]; self; end; e = h.map; [e.next, stop_of(e).result] } +probe("coll_map_redef_after") do + k = Class.new(Array) + e = k.new([1, 2]).map + k.class_eval { def map; return to_enum(:map) unless block_given?; [:late]; end } + [e.next, stop_of(e).result] +end +probe("coll_with_index") { e = [5, 6].map.with_index(1); [e.next, e.next] } +probe("coll_size") { [[1, 2].map.size, (1..3).select.size, { a: 1 }.map.size] } +probe("coll_dup_started") { e = [1, 2].map; e.next; (e.dup rescue "#{$!.class}: #{$!.message}") } +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 }] } + +# --- 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] } + +# --- 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 } + +# --- 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 } +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/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 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/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/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}" 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" } 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 } 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/hash-literal-matrix.rb b/Util/hash-literal-matrix.rb index 85527ddc9..9dcf196f6 100644 --- a/Util/hash-literal-matrix.rb +++ b/Util/hash-literal-matrix.rb @@ -122,8 +122,8 @@ def o_dup_str(a, b) = { a => 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 } diff --git a/Util/hash-walk-matrix.rb b/Util/hash-walk-matrix.rb new file mode 100644 index 000000000..d3425d240 --- /dev/null +++ b/Util/hash-walk-matrix.rb @@ -0,0 +1,225 @@ +# 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) }, + 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 +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 + +# ---------------------------------------------------------------- 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 } } + +# ---------------------------------------------------------------- 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 } } 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 +} diff --git a/Util/interpolation-matrix.rb b/Util/interpolation-matrix.rb index eb5c148d1..5b34d801c 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 @@ -283,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}"] } diff --git a/Util/ivar-matrix.rb b/Util/ivar-matrix.rb index f6e6303ec..aca43aa9b 100644 --- a/Util/ivar-matrix.rb +++ b/Util/ivar-matrix.rb @@ -169,6 +169,114 @@ 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 +# 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 + 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..c56240411 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) # 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) 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}" @@ -343,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: 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. +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/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/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/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/jit-cvar-matrix.rb b/Util/jit-cvar-matrix.rb new file mode 100644 index 000000000..e82171c75 --- /dev/null +++ b/Util/jit-cvar-matrix.rb @@ -0,0 +1,173 @@ +# 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 } + +# 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 +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 + 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/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/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/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/jit-masgn-matrix.rb b/Util/jit-masgn-matrix.rb new file mode 100644 index 000000000..fe48029e1 --- /dev/null +++ b/Util/jit-masgn-matrix.rb @@ -0,0 +1,212 @@ +# 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. +# 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), ' => ' + 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) } + +# 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/jit-matrix.rb b/Util/jit-matrix.rb index 9af86ef3f..3398ac6d4 100644 --- a/Util/jit-matrix.rb +++ b/Util/jit-matrix.rb @@ -4774,3 +4774,74 @@ 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. 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 + 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)] } 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/jit-rescue-matrix.rb b/Util/jit-rescue-matrix.rb new file mode 100644 index 000000000..e7643964f --- /dev/null +++ b/Util/jit-rescue-matrix.rb @@ -0,0 +1,467 @@ +# 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. +# 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), ' => ' + 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 } + +# 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/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/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/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/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/kernel-string-matrix.rb b/Util/kernel-string-matrix.rb new file mode 100644 index 000000000..68c2082c6 --- /dev/null +++ b/Util/kernel-string-matrix.rb @@ -0,0 +1,234 @@ +# 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 + +# ---------------------------------------------------------------- 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) } 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 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] } 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}) } diff --git a/Util/kwsplat-forward-matrix.rb b/Util/kwsplat-forward-matrix.rb new file mode 100644 index 000000000..3bbc83e00 --- /dev/null +++ b/Util/kwsplat-forward-matrix.rb @@ -0,0 +1,233 @@ +# 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 +# +# 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. + +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) } +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 + +# ---------------------------------------------------------------- 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 } + +# ---------------------------------------------------------------- 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}) } + +# ---------------------------------------------------------------- 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/lexical-light-matrix.rb b/Util/lexical-light-matrix.rb new file mode 100644 index 000000000..c91150bf6 --- /dev/null +++ b/Util/lexical-light-matrix.rb @@ -0,0 +1,317 @@ +# 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 }, co.ov_defined, CvOver.class_variable_defined?(:@@ov)] +end + +# 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 + @@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] } 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/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/light-match-sink-matrix.rb b/Util/light-match-sink-matrix.rb new file mode 100644 index 000000000..ff02b42eb --- /dev/null +++ b/Util/light-match-sink-matrix.rb @@ -0,0 +1,291 @@ +# 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. +# +# 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 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 +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 + +# 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)] + +# 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/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/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/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/loop-const-matrix.rb b/Util/loop-const-matrix.rb new file mode 100644 index 000000000..78047a57e --- /dev/null +++ b/Util/loop-const-matrix.rb @@ -0,0 +1,200 @@ +# 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 } } +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 +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 +# (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.() } + +# ---------------------------------------------------------------- 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" 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] +} diff --git a/Util/loop-ivar-matrix.rb b/Util/loop-ivar-matrix.rb new file mode 100644 index 000000000..450b97db0 --- /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 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 /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/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/nested-proc-matrix.rb b/Util/nested-proc-matrix.rb new file mode 100644 index 000000000..00016fa7b --- /dev/null +++ b/Util/nested-proc-matrix.rb @@ -0,0 +1,335 @@ +# 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)] +} + +# ---------------------------------------------------------------- 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 +} 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] } diff --git a/Util/parked-scope-matrix.rb b/Util/parked-scope-matrix.rb index 3f1a0a3e1..8aa5e0faa 100644 --- a/Util/parked-scope-matrix.rb +++ b/Util/parked-scope-matrix.rb @@ -149,4 +149,89 @@ 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 } + +# 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' diff --git a/Util/passed-block-matrix.rb b/Util/passed-block-matrix.rb new file mode 100644 index 000000000..2e28444de --- /dev/null +++ b/Util/passed-block-matrix.rb @@ -0,0 +1,188 @@ +# 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 +} + +# 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) } +} diff --git a/Util/perf/LEDGER.md b/Util/perf/LEDGER.md index 1d5d75aee..eaecbbe47 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 @@ -604,7 +605,27 @@ 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. 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 @@ -668,6 +689,35 @@ 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 + 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. + 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. 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 @@ -720,6 +770,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 @@ -742,6 +797,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 @@ -765,6 +836,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); @@ -773,6 +846,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 @@ -795,9 +878,15 @@ 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); + 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 and Util/regex-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 @@ -824,6 +913,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% @@ -833,6 +926,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): 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 @@ -866,6 +961,22 @@ 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): 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 @@ -914,6 +1025,43 @@ 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) 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. + 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 + 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 @@ -942,10 +1090,15 @@ 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), + `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, @@ -971,11 +1124,19 @@ 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. 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 @@ -1004,15 +1165,120 @@ 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. + 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. + 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 + 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. + 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. + 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). + 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. + 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. + + **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`). **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. - 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 `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). + 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). @@ -1037,6 +1303,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) 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 @@ -1056,32 +1329,85 @@ 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 (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 + (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 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. 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. + 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. 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). 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. 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): 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): 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 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): 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`). + 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 @@ -1108,6 +1434,32 @@ 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). + 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. + 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. + 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 @@ -1215,6 +1567,129 @@ 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. + 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. + 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): 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. + 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, 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 + 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, 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 + 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). + 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. 2026-11-26, perf/composite-r2r: the R2R host is now the release's configuration (self-contained composite with the framework and a current startup profile): `-e 1` 449 -> 389 ms median, the tools -10% (Landed). JIT at `-e 1` 500 -> 133 methods; what is @@ -1224,11 +1699,11 @@ loop of its own): `b.local_variable_set(:x, 1)` 0.1 -> 436, `erb.result_with_has is left of it is coreclr preparing code later start-up needs anyway, so deferring init work moves its cost and saves nothing; the yield helpers lost AggressiveOptimization (JIT at `-e 1` 133 -> 111 methods, -2% instructions on all four commands). -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 @@ -1268,6 +1743,32 @@ 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. + 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). + 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. 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 `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 `_` @@ -1306,6 +1807,23 @@ 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. + 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. + 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 @@ -1342,6 +1860,25 @@ 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): 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 (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 + 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 @@ -1350,6 +1887,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 @@ -1357,6 +1901,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). @@ -1368,8 +1914,49 @@ 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; 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, 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: 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 + 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`). 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). + 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 @@ -1390,9 +1977,4790 @@ 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. + +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). 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. + 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. + +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. + 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 +- **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**. + 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 + 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. +- **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)** - 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 + 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)** - 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), + 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)** - 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% + 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-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. + +- **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, 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, + 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, 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 + `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, 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 + 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, 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 + 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; 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 + 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. + +- **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 + 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, 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 + 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, 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` + (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, 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]`, + `[: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, 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 + (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, 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 + 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, 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 + 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, 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 + 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, 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`, + 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. + - **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 + 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 + `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/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 + 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`)** - 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 + 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. + +- **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). 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 + 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. 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 + 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. + +- **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, 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) + 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, 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 + 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/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 + 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. + +- **perf/sharedargs (round forty-one, 2026-11-28) - a call of another shape gets a shared rule of its + 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 + 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). + +- **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)** - 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 + 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)** - 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 + 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. + +- **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 + (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. + +- **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: + - **`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/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 + (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/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. 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 + 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; + 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 + 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). 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 + 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/kinteger (2026-11-28, on 33818f7 + 51f5637) - `Kernel#String` asks for #to_str as + 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 + 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, 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. + `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. + - 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, 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"). + - **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. + - **Later** (perf/loopivar2): the slowdown was where a GC collection fell, not the stores; on by + default since, block loops included. + +- **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)** - 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, + `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-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. + +- **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, 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` + 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, 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 + 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, 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 + 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). +- **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). 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. + 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/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, + 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/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 + 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/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, 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 + 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, + 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. + - 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/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)** - 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 + 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). + +- **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)** - 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 + 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`** - 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`, `$&`, + `` $` ``, `$'`, `$+`, 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. + - `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, 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. + +- **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)** - 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 + 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, + 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). +- **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 + 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/intivar then tried raw Integer variables: + rejected; `permute` is not typed code, so they would not have reached `@count` anyway.) + +- **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, + 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. +- **perf/arymin (/perf-step, 2026-11-27, on ed49c52) - `Array#take` is Array's own, as MRI's + `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 + 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** (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 + 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, 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 + 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, 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 + 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, 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 + 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/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** (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, + 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, 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 + 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. + + +- **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)** - 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 + 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)** - 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 + 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/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 + 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/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 + 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)** - + 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 + 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/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/requirecold (2026-11-28) - module_evals in the startup library; eval texts that name the tree (gap 26)** + - 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 + 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)** + - 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, + 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)** + - 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 + (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 + 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/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 + (`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, 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 + `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, 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 + 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, 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 + 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. Edge for the gate: the bare test is no instance variables now and no singleton + class, so a string whose last instance variable was removed counts as bare and skips its hooks; + 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, 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 + `: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; + `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, 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 + 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, 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 + 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/twospeed (2026-11-27) - an interpreted rule stuck before its compiled one runs compiled + (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 + 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** - 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 + 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/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`, + 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)** - 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 + 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)** - 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 + 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/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), 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 + (`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 (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 + 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). + 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. + 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. + 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. + 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. + 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). + 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). + 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. + 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 + 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)** - 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: + 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/startup4 (2026-11-27) - RubyGems' boot files are precompiled already; rbconfig asks the host + 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 + `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, 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 + `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. +- **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)** - + 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 + 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` + 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). + +- **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 + 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)** - 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 }`, + `{ |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/jitstr (2026-11-26) - `s + "lit"` and `s << "lit"` in a body the method JIT compiles** - + 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 + 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 `==`). +- **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)** - 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 + (`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). + +- **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, 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 + `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, 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. + - **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/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)** - 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 + 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 + 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/extiter3 (2026-11-26) - `with_index`, `each_with_index` and `with_object` enumerators + 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 + `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)** - 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 + #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/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, 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 + 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 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, + 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/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)** - 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. + 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/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, 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 + 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, 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 + (`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, 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 + `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/strsearch2 (2026-11-26) - `#start_with?` with one String prefix takes no scope; an + 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 + 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/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, 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?`, + `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`). + 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 + 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/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)** - 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 + 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)** - 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 + (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/singleton (round thirty-seven, 2026-11-26) - lookups on a re-versioned singleton class + 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 - + 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 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, + 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/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 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 + 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 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 + 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/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)** - 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 + 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/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)** - 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, + 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/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 + (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; 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 + 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/dmethjit (2026-11-26) - the method JIT takes the body of a method made by `define_method` + (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 + 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/lazy-builtins (2026-11-26) - runtime init of `ir -e 1`, split; the yield helpers are no longer AggressiveOptimization, so ReadyToRun precompiles them (gap 26).** Master 5cbf9fda, composite R2R host with the startup library on both trees. Asked: what runtime init does @@ -1680,7 +7048,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 @@ -3467,6 +8837,7 @@ passes; 21 odd receivers of a store, one process each, as CRuby; start-up is unc `EmitMethodAttrWrite`, so `c = self.a; c.v = x` is compiled too, which the commit does not say: jit-matrix has the cases (frozen leaf, a writer of its own, redefined, singleton, a failing call or ivar write after the store). + - **perf/permute, d027dbe6 ff744878 - an element store before a method's last one goes unlogged** when nothing between it and the last store can deopt or run Ruby code. In `tmp = @v[i]; @v[i] = @v[j]; @v[j] = tmp` the first store went through the thread's @@ -3643,6 +9014,7 @@ in 2.2 s on both. one class and deopts too often profiles again, twice at most, instead of being retired. `treefind` 889-989 -> 529-548 ns (CRuby 1508); CD's time does not move measurably (gap 3). + - **perf/iter, 9bbc9157 6b4e5960 - the pattern forms of `all?`, `any?`, `none?` and `one?` are C# overloads, not prelude wrappers** (gap 13). The C# `Array#any?` walked the Array directly all along; the prelude redefined the four methods as `(*args, &block)` @@ -4285,6 +9657,820 @@ 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/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 + 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`, + `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 + 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 + 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: + 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/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/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/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 + 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/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/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 + 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 + 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/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/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 + 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/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 + 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 + 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`, + `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 + 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 + 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 + `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/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 + 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/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. + Taken later for `downto` (perf/permute of 2026-11-27, Landed): with a parked scope per level of + recursion the saving covers the whole recursion, not one level, and Permute's time is 0.933. + +- **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/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 + 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/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. @@ -5247,3 +11433,40 @@ 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. + +### 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. 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 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' 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 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 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" diff --git a/Util/sdef-matrix.rb b/Util/sdef-matrix.rb index 6aebf7402..7a4bc1db4 100644 --- a/Util/sdef-matrix.rb +++ b/Util/sdef-matrix.rb @@ -270,5 +270,91 @@ 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) + +# ---------------------------------------------------------------- 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" 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] } 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 } } 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) 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" diff --git a/Util/string-race-matrix.rb b/Util/string-race-matrix.rb new file mode 100644 index 000000000..2441885b5 --- /dev/null +++ b/Util/string-race-matrix.rb @@ -0,0 +1,126 @@ +# 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 ", 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 -*- + +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 + # 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 + puts "#{rname} / #{wname}: #{result}" + end +end +puts "done" diff --git a/Util/string-search-matrix.rb b/Util/string-search-matrix.rb new file mode 100644 index 000000000..fea29d0ce --- /dev/null +++ b/Util/string-search-matrix.rb @@ -0,0 +1,252 @@ +# 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, $~] } + +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 + +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 + +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 diff --git a/Util/struct-matrix.rb b/Util/struct-matrix.rb new file mode 100644 index 000000000..1582d823e --- /dev/null +++ b/Util/struct-matrix.rb @@ -0,0 +1,214 @@ +# 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. +# +# 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) +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 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 +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 + 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) + 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" 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 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 } } diff --git a/Util/unkept-matrix.rb b/Util/unkept-matrix.rb new file mode 100644 index 000000000..66588fb65 --- /dev/null +++ b/Util/unkept-matrix.rb @@ -0,0 +1,53 @@ +# 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) +# +# 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 +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)#/ + 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") +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 +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) +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 diff --git a/Util/unsampled-matrix.rb b/Util/unsampled-matrix.rb new file mode 100644 index 000000000..9e0a6b823 --- /dev/null +++ b/Util/unsampled-matrix.rb @@ -0,0 +1,485 @@ +# 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, 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 + 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 + succ succ_eq_redefined succ_eq_singleton succ_eq_subclass succ_eq_missing + phases phases_redefined] + +if ARGV[0] == 'list' + puts CASES + exit +end +c = ARGV[0] + +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 + +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 + + # 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 + +# 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 + 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 +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) } +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' + 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 } }) +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 '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)) + 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 diff --git a/Util/yield-loop-matrix.rb b/Util/yield-loop-matrix.rb new file mode 100644 index 000000000..5e3ededa6 --- /dev/null +++ b/Util/yield-loop-matrix.rb @@ -0,0 +1,271 @@ +# 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 } } +# 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) } +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] +} +# 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] +} + +# 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)] }