/* ****************************************************************************
*
* 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 MSA = System.Linq.Expressions;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using IronRuby.Builtins;
using Range = IronRuby.Builtins.Range;
using IronRuby.Compiler;
using IronRuby.Compiler.Generation;
using IronRuby.Runtime.Calls;
using Microsoft.Scripting;
using Microsoft.Scripting.Interpreter;
using System.Numerics;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronRuby.Runtime.Conversions;
namespace IronRuby.Runtime {
[ReflectionCached, CLSCompliant(false)]
public static partial class RubyOps {
[Emitted]
public static readonly object DefaultArgument = new object();
// Returned by a virtual site if a base call should be performed.
[Emitted]
public static readonly object ForwardToBase = new object();
// Returned by the rule of a call site in a light-frame method that would have read the method's scope
// (RubyCallFlags.HasLightScope): the method makes the scope and calls through an ordinary site.
public static readonly object LightScopeRequired = new object();
// Returned by the rule of a `block_given?' site in a light frame when the call is Kernel#block_given? itself
// (DispatchIntrinsics.TryBuildBlockGiven): the answer is whether the frame has a block, which a light-frame method
// reads from its block parameter without making its scope to be asked through; a block's frame has no block
// parameter to read, and makes the call with its scope as for LightScopeRequired.
public static readonly object LightBlockGiven = new object();
// How many refine blocks are running in the process (RubyUtils.EvaluateRefinementBlock). While none is, no Proc
// has a refine block's override, so the lexical walk steps over block scopes (RubyScope.GetLexicalRefinements),
// and the rule of a refined call made in a block written in a method can test the method's record instead
// (RubyCallAction.Resolve) - with this test.
[Emitted]
public static int RefineBlocksRunning;
// an instance of a dummy type that causes any rule based on instance type check to fail
private sealed class _NeedsUpdate {
}
[Emitted]
public static readonly object NeedsUpdate = new _NeedsUpdate();
#region Scopes
[Emitted]
public static MutableTuple GetLocals(RubyScope/*!*/ scope) {
return scope.Locals;
}
[Emitted]
public static MutableTuple GetParentLocals(RubyScope/*!*/ scope) {
return scope.Parent.Locals;
}
[Emitted]
public static RubyScope/*!*/ GetParentScope(RubyScope/*!*/ scope) {
return scope.Parent;
}
[Emitted]
public static Proc GetMethodBlockParameter(RubyScope/*!*/ scope) {
var methodScope = scope.GetInnerMostMethodScope();
return methodScope != null ? methodScope.BlockParameter : null;
}
[Emitted]
public static object GetMethodBlockParameterSelf(RubyScope/*!*/ scope) {
Proc proc = scope.GetInnerMostMethodScope().BlockParameter;
Debug.Assert(proc != null, "CreateBfcForYield is called before this method and it checks non-nullity");
return proc.Self;
}
[Emitted]
public static object GetProcSelf(Proc/*!*/ proc) {
return proc.Self;
}
[Emitted]
public static int GetProcArity(Proc/*!*/ proc) {
return proc.Dispatcher.Arity;
}
[Emitted]
public static void InitializeScope(RubyScope/*!*/ scope, MutableTuple locals, string[] variableNames,
InterpretedFrame interpretedFrame) {
if (!scope.LocalsInitialized) {
scope.SetLocals(locals, variableNames ?? ArrayUtils.EmptyStrings);
}
scope.InterpretedFrame = interpretedFrame;
// While a file's top level runs, a proc created in it can return from it, as MRI's
// `proc { return }.call` at the top of a file does (see IsTopLevelReturn).
var topLevel = scope as RubyTopLevelScope;
if (topLevel != null) {
topLevel._activeFlowControlScope = topLevel;
topLevel.ActiveThreadId = Environment.CurrentManagedThreadId;
}
}
[Emitted]
public static void InitializeScopeNoLocals(RubyScope/*!*/ scope, InterpretedFrame interpretedFrame) {
scope.InterpretedFrame = interpretedFrame;
}
///
/// An eval's own locals exist from the start, as in any other scope - `if false; a = 1; end'
/// leaves `a' defined as nil for the next eval through the same binding - so the ones the
/// string declares are defined up front rather than on their first assignment.
///
[Emitted]
public static void InitializeEvalScope(RubyScope/*!*/ scope, string/*!*/[]/*!*/ declaredNames, InterpretedFrame interpretedFrame) {
scope.InterpretedFrame = interpretedFrame;
// Declared last to first: a scope lists the variables it was given later first
// (RubyScope.GetDeclaredLocalSymbols), and MRI lists the ones of a single eval in
// the order the string has them.
for (int i = declaredNames.Length - 1; i >= 0; i--) {
scope.DeclareLocalVariable(declaredNames[i]);
}
}
[Emitted]
public static void SetDataConstant(RubyScope/*!*/ scope, string/*!*/ dataPath, int dataOffset) {
Debug.Assert(dataOffset >= 0);
RubyContext context = scope.RubyContext;
if (!context.DomainManager.Platform.FileExists(dataPath)) {
// -e and stdin scripts also compile as TopScopeFactoryKind.Main and can contain
// __END__. MRI does not define DATA for those; defining it as nil would make
// defined?(DATA) truthy, so leave the constant undefined instead.
return;
}
RubyFile dataFile = new RubyFile(context, dataPath, IOMode.ReadOnly);
dataFile.Seek(dataOffset, SeekOrigin.Begin);
context.ObjectClass.SetConstant("DATA", dataFile);
}
[Emitted]
public static RubyModuleScope/*!*/ CreateModuleScope(MutableTuple locals, string[] variableNames,
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);
}
RubyModuleScope scope = new RubyModuleScope(parent, module);
scope.SetDebugName((module.IsClass ? "class" : "module") + " " + module.Name);
scope.SetLocals(locals, variableNames ?? ArrayUtils.EmptyStrings);
return scope;
}
///
/// MRI's stack check at a method or block entry: a recursion too deep is a SystemStackError, which a program can
/// rescue, not a CLR stack overflow, which ends the process (#128). Asked where a Ruby frame starts - method
/// and block scopes here, JIT-compiled methods in JitRuntime.CheckStack - and cheap: it compares the stack
/// pointer with a limit it keeps per thread (StackLimit, which says why the runtime's own check is not enough).
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RequireSufficientStack() {
if (!StackLimit.IsSufficient()) {
ThrowStackLevelTooDeep();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowStackLevelTooDeep() {
throw new SystemStackError("stack level too deep");
}
[Emitted]
public static RubyMethodScope/*!*/ CreateMethodScope(MutableTuple locals, string[] variableNames, int visibleParameterCount,
RubyScope/*!*/ parentScope, RubyModule/*!*/ declaringModule, string/*!*/ definitionName,
object selfObject, Proc blockParameter, InterpretedFrame interpretedFrame) {
// Method entry is a safe point, as in MRI: a thread that recurses or calls methods in a
// loop is reachable by Thread#raise / Thread#kill even where no back edge is.
RubyUtils.SafePoint();
RequireSufficientStack();
var scope = new RubyMethodScope(
locals, variableNames ?? ArrayUtils.EmptyStrings, visibleParameterCount,
parentScope, declaringModule, definitionName, selfObject, blockParameter,
interpretedFrame
);
if (_aliasCallSeen) {
string callee = _pendingCallee;
if (callee != null) {
_pendingCallee = null;
if (_pendingCalleeDefinition == definitionName) {
scope.CalleeName = callee;
}
}
}
if ((TracePoint.ActiveEvents & (int)(TraceEvents.Call | TraceEvents.CCall)) != 0) {
TracePoint.OnMethodCall(scope);
}
return scope;
}
#region Parked method scopes
// A method whose block literals all reuse their Procs (BlockDispatcher.ReusesProc: no lambda or nested block in them)
// 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
// each literal is one only the frame holds (Proc.IsReusableAndInactive: given to light frames and [BlockNotKept]
// iterators only, and no scope it ran in captured), nothing can reach the scope or its Procs: they are parked in the
// body's ParkedScopeSlot, cleared of everything of the call that ended, and the next call takes them with an atomic
// exchange into a variable of its frame. A call that does not get them - a recursive call, one on another thread, or one
// after a call that could not park - makes a plain scope and Procs exactly as before. IR_PARKED_SCOPES=0 turns it off.
///
/// The parked scope and Procs of the slot, now this call's, if they were parked by a call of the same definition.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ParkedProcs TakeParkedScope(ParkedScopeSlot/*!*/ slot, RubyScope/*!*/ parentScope, RubyModule/*!*/ declaringModule) {
var parked = slot.Parked;
if (parked == null) {
return null;
}
return TakeParkedScopeSlow(slot, parked, parentScope, declaringModule);
}
private static ParkedProcs TakeParkedScopeSlow(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, RubyScope/*!*/ parentScope,
RubyModule/*!*/ declaringModule) {
// Taken first, looked at after: until the exchange succeeds another call may take it, fail to park it and empty it.
if (Interlocked.CompareExchange(ref slot.Parked, null, parked) != parked) {
return null;
}
// 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;
if (scope._parent != parentScope || scope.DeclaringModule != declaringModule) {
Interlocked.CompareExchange(ref slot.Parked, parked, null);
return null;
}
return parked;
}
///
/// CreateMethodScope with the parked scope TakeParkedScope took: that scope, made the scope of this call.
///
[Emitted]
public static RubyMethodScope/*!*/ ReuseParkedScope(ParkedProcs/*!*/ parked, MutableTuple locals, object selfObject, Proc blockParameter,
InterpretedFrame interpretedFrame) {
RubyUtils.SafePoint();
RequireSufficientStack();
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 ((TracePoint.ActiveEvents & (int)(TraceEvents.Call | TraceEvents.CCall)) != 0) {
TracePoint.OnMethodCall(scope);
}
return scope;
}
///
/// CreateMethodScopeLazy of a light-frame body with the parked scope TakeParkedScope took.
///
[Emitted]
public static RubyMethodScope/*!*/ ReuseParkedScopeLazy(ParkedProcs/*!*/ parked, MutableTuple locals, object selfObject,
Proc blockParameter, InterpretedFrame interpretedFrame, RuntimeFlowControl/*!*/ rfc, string calleeName) {
// (as CreateMethodScopeLazy: the scope holds the block, and whatever asked for the scope may keep it)
if (blockParameter != null) {
blockParameter.ClearReusable();
}
var scope = parked.Scope;
scope.Reinitialize(locals, selfObject, blockParameter, interpretedFrame, rfc, calleeName);
return scope;
}
///
/// InstantiateReusableBlock of a literal (the index-th) of a body with a parking slot: the Proc parked with the scope, if
/// this call took that scope, and a previous Proc that cannot be made again marks the scope captured - it may be held
/// somewhere, and it reaches the scope.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Proc InstantiateParkedBlock(Proc previous, RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher,
ParkedProcs parked, int index) {
// the first evaluation of the literal in a call that took nothing: InstantiateReusableBlock's own
if (previous == null && parked == null) {
return dispatcher.HasMethod ? new Proc(ProcKind.Block, self, scope, dispatcher) : null;
}
return InstantiateParkedBlockSlow(previous, scope, self, dispatcher, parked, index);
}
private static Proc InstantiateParkedBlockSlow(Proc previous, RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher,
ParkedProcs parked, int index) {
if (previous != null) {
if (previous.TryReuse()) {
return previous;
}
scope.IsCaptured = true;
} else if (parked != null && parked.Scope == scope) {
var procs = parked.Procs;
var proc = procs[index];
if (proc != null) {
procs[index] = null;
proc.ReuseParked(self, parked.ThreadId != Environment.CurrentManagedThreadId);
if (proc.TryReuse()) {
return proc;
}
}
}
return dispatcher.HasMethod ? new Proc(ProcKind.Block, self, scope, dispatcher) : null;
}
///
/// The normal end of a call of a body with a parking slot (an exception, a throw, Thread#kill skip it): if its scope may
/// be parked, where to stage its Procs (StageParkedProc, then EndPark) - what the call took, or an emptied one.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ParkedProcs BeginPark(ParkedScopeSlot/*!*/ slot, RubyScope scope, ParkedProcs taken) {
// a call that made no scope, or a slot that gave up: nothing to do, inlined into the body
if (scope == null || slot.Failures > ParkedScopeSlot.MaxFailures) {
return null;
}
return BeginParkSlow(slot, scope, taken);
}
private static ParkedProcs BeginParkSlow(ParkedScopeSlot/*!*/ slot, RubyScope/*!*/ scope, ParkedProcs taken) {
var methodScope = scope as RubyMethodScope;
if (methodScope == null || slot.IsOff || TracePoint.ActiveEvents != 0) {
return null;
}
if (methodScope.IsCaptured || methodScope.HasRareState || methodScope._activeFlowControlScope == methodScope) {
slot.Failures++;
return null;
}
if (taken != null) {
return taken;
}
var spare = slot.Spare;
if (spare != null && Interlocked.CompareExchange(ref slot.Spare, null, spare) == spare) {
return spare;
}
return new ParkedProcs(slot.ProcCount);
}
///
/// The last Proc of the index-th literal, staged for parking; false if something else may hold it.
///
[Emitted]
public static bool StageParkedProc(ParkedProcs/*!*/ parked, int index, Proc proc) {
if (proc != null && !proc.IsReusableAndInactive) {
return false;
}
parked.Procs[index] = proc;
return true;
}
///
/// 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.
///
[Emitted]
public static void EndPark(ParkedScopeSlot/*!*/ slot, ParkedProcs/*!*/ parked, RubyScope/*!*/ scope, bool procsParkable) {
if (procsParkable) {
if (slot.Failures != 0) {
slot.Failures = 0;
}
foreach (var proc in parked.Procs) {
proc?.ClearForPark();
}
var methodScope = (RubyMethodScope)scope;
methodScope.ClearCallState();
parked.Scope = methodScope;
parked.ThreadId = Environment.CurrentManagedThreadId;
if (Interlocked.CompareExchange(ref slot.Parked, parked, null) == null) {
return;
}
} else {
slot.Failures++;
}
parked.Clear();
Volatile.Write(ref slot.Spare, parked);
}
#endregion
#region Light method frames
// A method whose body never needs its scope - yield and return over self, its parameters, its
// locals and literals (MethodDefinition.TransformLightBody) - makes none on a call. Its flow-control
// frame is the literal block it was called with, converted as a library method's is
// (CreateRfcForMethod), or the shared inactive frame; the scope is made only when something asks
// for one: a TracePoint hook, or the exception filter. That is the 160-byte RubyMethodScope every
// other call of a Ruby method allocates.
///
/// The entry of a light-frame method: the safe point CreateMethodScope makes, then the call's
/// flow-control frame.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeFlowControl/*!*/ EnterLightMethod(Proc blockParameter) {
RubyUtils.SafePoint();
// a call without a block, the common case, is inlined into the method body
return (blockParameter == null) ? InactiveRfc : EnterLightMethodWithBlock(blockParameter);
}
///
/// EnterLightMethod of a method with a block parameter (`def m(&b)'): the body can hand the block on or keep
/// it without making a scope - `def capture(&b); b; end' - so the block is converted as any call's is, and is
/// never made again for the next evaluation of its literal.
///
public static RuntimeFlowControl/*!*/ EnterLightMethodNamingBlock(Proc blockParameter) {
RubyUtils.SafePoint();
if (blockParameter != null && blockParameter.Kind == ProcKind.Block) {
blockParameter.ConvertAsMethodFrame();
return blockParameter;
}
return InactiveRfc;
}
private static RuntimeFlowControl/*!*/ EnterLightMethodWithBlock(Proc/*!*/ blockParameter) {
// A light frame can only yield to its block: a literal one may be made again once the call returns (Proc.TryReuse).
if (blockParameter.Kind == ProcKind.Block) {
blockParameter.ConvertAsLightFrame();
return blockParameter;
}
return InactiveRfc;
}
///
/// 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.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string TakePendingCallee(string/*!*/ definitionName) {
return _aliasCallSeen ? TakePendingCalleeSlow(definitionName) : null;
}
private static string TakePendingCalleeSlow(string/*!*/ definitionName) {
string callee = _pendingCallee;
if (callee != null) {
_pendingCallee = null;
if (_pendingCalleeDefinition == definitionName) {
return callee;
}
}
return null;
}
///
/// The scope of a light-frame method made at its entry because a TracePoint listens for calls, which
/// it is then reported to; null otherwise.
///
[Emitted]
public static RubyMethodScope CreateMethodScopeIfTraced(MethodFrameShape/*!*/ shape, RubyScope/*!*/ parentScope,
RubyModule/*!*/ declaringModule, MutableTuple locals, object selfObject, Proc blockParameter,
InterpretedFrame interpretedFrame, RuntimeFlowControl/*!*/ rfc, string calleeName) {
if ((TracePoint.ActiveEvents & (int)(TraceEvents.Call | TraceEvents.CCall)) != 0) {
var scope = CreateMethodScopeLazy(shape, parentScope, declaringModule, locals, selfObject, blockParameter,
interpretedFrame, rfc, calleeName);
TracePoint.OnMethodCall(scope);
return scope;
}
return null;
}
///
/// The scope of a light-frame method, made when something asks for it (see the RubyMethodScope constructor).
///
[Emitted]
public static RubyMethodScope/*!*/ CreateMethodScopeLazy(MethodFrameShape/*!*/ shape, RubyScope/*!*/ parentScope,
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
if (blockParameter != null) {
blockParameter.ClearReusable();
}
return new RubyMethodScope(shape, parentScope, declaringModule, locals, selfObject, blockParameter,
interpretedFrame, rfc, calleeName);
}
///
/// MethodYield of a light-frame method: the frame is the scope's if one was made, the call's otherwise.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static bool LightMethodYield(RuntimeFlowControl/*!*/ rfc, RubyScope scope, BlockParam/*!*/ yieldedBlockFlowControl, object returnValue) {
if (yieldedBlockFlowControl.ReturnReason == BlockReturnReason.Undefined) {
return false;
}
return MethodYieldRfc((scope != null) ? scope.FlowControlScope : rfc, yieldedBlockFlowControl, returnValue);
}
///
/// LeaveMethodFrame of a light-frame method: the call's frame, and the scope if one was made.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LeaveLightMethodFrame(RuntimeFlowControl/*!*/ rfc, RubyScope scope) {
// nothing to do for a call without a block that made no scope, the common case, inlined into the method body
if (rfc._activeFlowControlScope != null || scope != null) {
LeaveLightMethodFrameSlow(rfc, scope);
}
}
private static void LeaveLightMethodFrameSlow(RuntimeFlowControl/*!*/ rfc, RubyScope scope) {
LeaveMethodFrame(rfc);
if (scope != null) {
if (scope.IsActiveMethod) {
scope.LeaveMethod();
}
ReleaseScopeFrame(scope);
}
}
#endregion
// The name an aliased method was called by, handed from the call site to the scope the
// method body creates first thing (MRI keeps it in the frame for __callee__).
[ThreadStatic]
private static string _pendingCallee;
[ThreadStatic]
private static string _pendingCalleeDefinition;
private static bool _aliasCallSeen;
///
/// Wraps the last argument of a call to a method through an alias, so that the name is
/// recorded after every argument has been evaluated, just before the method body runs.
///
[Emitted]
public static object MarkAliasCall(object lastArgument, string/*!*/ calleeName, string/*!*/ definitionName) {
_aliasCallSeen = true;
_pendingCallee = calleeName;
_pendingCalleeDefinition = definitionName;
return lastArgument;
}
[Emitted]
public static RubyScope/*!*/ CreateFileInitializerScope(MutableTuple locals, string[] variableNames, RubyScope/*!*/ parent) {
return new RubyFileInitializerScope(locals, variableNames ?? ArrayUtils.EmptyStrings, parent);
}
[Emitted]
public static RubyBlockScope/*!*/ CreateBlockScope(MutableTuple locals, string[] variableNames,
BlockParam/*!*/ blockParam, object selfObject, InterpretedFrame interpretedFrame) {
// Block entry too: `n.times { }` and `each { }` loop in C#, where no back edge is emitted.
RubyUtils.SafePoint();
return CreateBlockScopeSafePointInBody(locals, variableNames, blockParam, selfObject, interpretedFrame);
}
///
/// for a block whose whole body is `begin ... rescue ... end`
/// (`n.times do ... rescue ... end`): its entry safe point is the first thing inside the
/// rescued statements (Body.SafePointFirst). At the entry, a Thread#raise that came in while
/// the previous call was returning would be raised outside the rescue written for it - MRI
/// has no check there, only at the block's `leave` and the loop's back edge, which leaves it
/// a window of a few instructions where IronRuby's was a block return and a C# loop step.
///
[Emitted]
public static RubyBlockScope/*!*/ CreateBlockScopeSafePointInBody(MutableTuple locals, string[] variableNames,
BlockParam/*!*/ blockParam, object selfObject, InterpretedFrame interpretedFrame) {
RequireSufficientStack();
var scope = new RubyBlockScope(locals, variableNames ?? ArrayUtils.EmptyStrings, blockParam, selfObject, interpretedFrame);
if ((TracePoint.ActiveEvents & (int)(TraceEvents.BCall | TraceEvents.Call)) != 0) {
TracePoint.OnBlockCall(scope);
}
return scope;
}
///
/// The entry of a block whose body never uses its scope (see BlockDefinition.IsScopeFreeBody):
/// the safe point, and the scope only if a TracePoint wants the call event. Null otherwise; a
/// TracePoint hook enabled later makes it then ().
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static RubyBlockScope CreateBlockScopeIfTraced(MutableTuple locals, string[] variableNames,
BlockParam/*!*/ blockParam, object selfObject, InterpretedFrame interpretedFrame) {
RubyUtils.SafePoint();
RequireSufficientStack();
if ((TracePoint.ActiveEvents & (int)(TraceEvents.BCall | TraceEvents.Call)) != 0) {
var scope = new RubyBlockScope(locals, variableNames ?? ArrayUtils.EmptyStrings, blockParam, selfObject, interpretedFrame);
TracePoint.OnBlockCall(scope);
return scope;
}
return null;
}
///
/// of a block that keeps its locals in CLR variables (ScopeBuilder.TryUseRegisterLocals),
/// whose tuple is made only with the scope: the safe point, and whether a TracePoint wants the call event, in which case the
/// block makes its scope and reports it ().
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static bool EnterScopeFreeBlock() {
RubyUtils.SafePoint();
RequireSufficientStack();
return (TracePoint.ActiveEvents & (int)(TraceEvents.BCall | TraceEvents.Call)) != 0;
}
[Emitted]
public static RubyBlockScope/*!*/ TraceBlockCall(RubyBlockScope/*!*/ scope) {
TracePoint.OnBlockCall(scope);
return scope;
}
///
/// Whether a TracePoint wants the call event of a light-frame method, which then makes its scope (CreateMethodScopeIfTraced)
/// and, if it keeps its locals in CLR variables, their tuple first.
///
[Emitted, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsMethodCallTraced() {
return (TracePoint.ActiveEvents & (int)(TraceEvents.Call | TraceEvents.CCall)) != 0;
}
///
/// The first step of the entry of a block whose body needs its scope but does not define a closure
/// over it: the safe point, then the scope the last finished call through this BlockParam left there
/// (each, map, times, a yield in a loop; see BlockParam.ParkScope) unless something captured it, or null.
/// The scope comes off the BlockParam here, after the safe point (which can run a trap handler or a
/// finalizer) and together with its locals tuple: a call that starts in between finds nothing kept and
/// makes a scope and tuple of its own, and a call that does not finish normally keeps nothing.
/// The block reuses the scope's tuple (see ) and hands the scope to
/// ; parks it again.
///
[Emitted, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RubyBlockScope TakeReusableBlockScope(BlockParam/*!*/ blockParam) {
// Block entry too: `n.times { }` and `each { }` loop in C#, where no back edge is emitted.
RubyUtils.SafePoint();
return TakeReusableBlockScopeSafePointInBody(blockParam);
}
///
/// for a block whose safe point is inside its body (see
/// ). Whatever that safe point runs - a trap
/// handler, a finalizer - runs after the scope is taken, so a call of the block it makes finds
/// nothing kept and makes a scope of its own.
///
[Emitted, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RubyBlockScope TakeReusableBlockScopeSafePointInBody(BlockParam/*!*/ blockParam) {
if (blockParam.MayHaveReusableScope) {
var scope = blockParam.ReusableScope;
if (scope != null && !scope.IsCaptured) {
blockParam.TakeReusableScope();
return scope;
}
}
return null;
}
///
/// The locals tuple of a scope took, for the block to reuse (the
/// last call cleared it); null if it took none.
///
[Emitted, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MutableTuple GetReusableLocals(RubyBlockScope reusable) {
return (reusable != null) ? reusable._locals : null;
}
///
/// The scope of a block call that began: the scope it took, made the
/// scope of this call, or a new one.
///
[Emitted, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RubyBlockScope/*!*/ CreateReusableBlockScope(MutableTuple locals, string[] variableNames,
BlockParam/*!*/ blockParam, object selfObject, InterpretedFrame interpretedFrame, RubyBlockScope reusable) {
RequireSufficientStack();
RubyBlockScope scope;
if (reusable != null) {
scope = reusable;
scope.Reinitialize(locals, blockParam, selfObject, interpretedFrame);
} else {
scope = new RubyBlockScope(locals, variableNames ?? ArrayUtils.EmptyStrings, blockParam, selfObject, interpretedFrame);
}
if ((TracePoint.ActiveEvents & (int)(TraceEvents.BCall | TraceEvents.Call)) != 0) {
scope.MarkCaptured();
TracePoint.OnBlockCall(scope);
}
return scope;
}
///
/// The normal exit of a block that made its scope by .
/// An exception leaving the body skips this, and the scope is simply not reused. True if the
/// scope was kept on the BlockParam, with its locals tuple when : the
/// block then clears the tuple, so that the next call finds its locals nil. The first call through
/// a BlockParam keeps nothing (see BlockParam.ParkScope): a block called once pays no more than a flag.
///
[Emitted, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool LeaveReusableBlockScope(RubyBlockScope/*!*/ scope, bool keepLocals) {
return scope.BlockFlowControl.ParkScope(scope);
}
[Emitted]
public static RubyBlockScope/*!*/ CreateBlockScopeLazy(MutableTuple locals, string[] variableNames,
BlockParam/*!*/ blockParam, object selfObject, InterpretedFrame interpretedFrame) {
return new RubyBlockScope(locals, variableNames ?? ArrayUtils.EmptyStrings, blockParam, selfObject, interpretedFrame);
}
// TracePoint hooks; emitted code only calls them when TracePoint.ActiveEvents has the event.
// Emitted behind a test of TracePoint.ActiveEvents in front of every statement: kept out of
// line, the never-taken branch is one call; inlined, it was a few hundred bytes of machine
// code per statement in every compiled method body.
[Emitted, MethodImpl(MethodImplOptions.NoInlining)]
public static void TraceLineEvent(RubyScope scope, string path, int line) {
// objspace's allocation tracing forces this event on and takes the allocation site of
// every object created by the statement from here.
if (ObjectTracking.IsTracingAllocations) {
ObjectTracking.SetCurrentLine(scope, path, line);
}
TracePoint.OnLine(scope, path, line);
}
[Emitted]
public static void TraceReturnEvent(RubyScope scope, object value, string path, int line) {
TracePoint.OnReturn(scope, value, path, line);
}
[Emitted]
public static void TraceClassEvent(RubyScope scope, string path, int line) {
if ((TracePoint.ActiveEvents & (int)TraceEvents.Class) != 0) {
TracePoint.OnClass(scope, path, line);
}
}
[Emitted]
public static void PrintInteractiveResult(RubyScope/*!*/ scope, MutableString/*!*/ value) {
var writer = scope.RubyContext.DomainManager.SharedIO.OutputStream;
writer.WriteByte((byte)'=');
writer.WriteByte((byte)'>');
writer.WriteByte((byte)' ');
var bytes = value.ToByteArray();
writer.Write(bytes, 0, bytes.Length);
writer.WriteByte((byte)'\r');
writer.WriteByte((byte)'\n');
}
[Emitted]
public static object GetLocalVariable(RubyScope/*!*/ scope, string/*!*/ name) {
return scope.ResolveLocalVariable(name);
}
[Emitted]
public static object SetLocalVariable(object value, RubyScope/*!*/ scope, string/*!*/ name) {
return scope.ResolveAndSetLocalVariable(name, value);
}
[Emitted]
public static VersionHandle/*!*/ GetSelfClassVersionHandle(RubyScope/*!*/ scope) {
return scope.SelfImmediateClass.Version;
}
///
/// Emitted into the guard of any call-site rule whose target class has been refined. The rule is
/// valid exactly while the calling scope's lexical refinement activation is the same instance it
/// was bound against.
///
[Emitted]
public static RefinementActivation/*!*/ GetActiveRefinements(RubyScope/*!*/ scope) {
return scope.GetActiveRefinements();
}
///
/// The same for the guard of a call-site rule, which is only built once a refinement exists: in a
/// runtime where one ever has, GetActiveRefinements' first test is always false.
///
[Emitted]
public static RefinementActivation/*!*/ GetLexicalRefinements(RubyScope/*!*/ scope) {
return scope.GetLexicalRefinements();
}
// The implicit calls a conversion site makes carry no scope, so they cannot see refinements.
// The two below run ahead of such a site where MRI honours the refinements of the lexical
// position - "#{x}" and &x - and answer null (use the site) unless one is actually in play.
// Unless some refinement has the method in question they cost a field read and a hash lookup.
///
/// "#{x}" where a refinement of x's class defines #to_s.
///
[Emitted]
public static MutableString TryConvertToSWithRefinements(RubyScope/*!*/ scope, object value) {
var context = scope.RubyContext;
if (!context.HasRefinements || value is MutableString || !context.IsRefinedMethodName("to_s")) {
return null;
}
if (!IsRefinedHere(scope, value, "to_s")) {
return null;
}
var site = context.GetOrCreateSendSite>(
"to_s", new RubyCallSignature(0, RubyCallFlags.HasScope | RubyCallFlags.HasImplicitSelf)
);
return ToSDefaultConversion(context, value, site.Target(site, scope, value));
}
///
/// 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
/// is the one that converts.
///
[Emitted]
public static Proc TryConvertBlockWithRefinements(RubyScope/*!*/ scope, object value) {
var context = scope.RubyContext;
if (!context.HasRefinements || value == null || value is Proc) {
return null;
}
// Only a refinement with #to_proc, or - for a Symbol - with the method the proc calls, makes a
// difference to what &x passes.
var symbol = value as RubySymbol;
bool toProcRefined = context.IsRefinedMethodName(Symbols.ToProc);
if (!toProcRefined && (symbol == null || !context.IsRefinedMethodName(symbol.ToString()))) {
return null;
}
if (scope.GetActiveRefinements().IsEmpty) {
return null;
}
if (!toProcRefined || !IsRefinedHere(scope, value, Symbols.ToProc)) {
// Symbol#to_proc, but with the calls it makes bound to this scope:
return (symbol != null) ? Proc.CreateMethodInvoker(scope, symbol.ToString()) : null;
}
var site = context.GetOrCreateSendSite>(
Symbols.ToProc, new RubyCallSignature(0, RubyCallFlags.HasScope | RubyCallFlags.HasImplicitSelf)
);
return ToProcValidator(context.GetClassName(value), site.Target(site, scope, value));
}
// True if a refinement active in scope supplies value's method of that name.
private static bool IsRefinedHere(RubyScope/*!*/ scope, object value, string/*!*/ name) {
var context = scope.RubyContext;
if (scope.GetActiveRefinements().IsEmpty) {
return false;
}
var method = context.ResolveMethodWithRefinements(value, name, VisibilityContext.AllVisible, scope);
return method.Found && method.Info.DeclaringModule.IsRefinement;
}
#endregion
#region Context
[Emitted]
public static RubyContext/*!*/ GetContextFromModule(RubyModule/*!*/ module) {
return module.Context;
}
[Emitted]
public static RubyContext/*!*/ GetContextFromIRubyObject(IRubyObject/*!*/ obj) {
return obj.ImmediateClass.Context;
}
[Emitted]
public static RubyContext/*!*/ GetContextFromScope(RubyScope/*!*/ scope) {
return scope.RubyContext;
}
[Emitted]
public static RubyContext/*!*/ GetContextFromMethod(RubyMethod/*!*/ method) {
return method.Info.Context;
}
[Emitted]
public static RubyContext/*!*/ GetContextFromBlockParam(BlockParam/*!*/ block) {
return block.RubyContext;
}
[Emitted]
public static RubyContext/*!*/ GetContextFromProc(Proc/*!*/ proc) {
return proc.LocalScope.RubyContext;
}
[Emitted]
public static Scope/*!*/ GetGlobalScopeFromScope(RubyScope/*!*/ scope) {
return scope.GlobalScope.Scope;
}
#endregion
#region Blocks
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static Proc InstantiateBlock(RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher) {
return dispatcher.HasMethod ? new Proc(ProcKind.Block, self, scope, dispatcher) : null;
}
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static Proc InstantiateLambda(RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher) {
return dispatcher.HasMethod ? new Proc(ProcKind.Lambda, self, scope, dispatcher) : null;
}
///
/// InstantiateBlock of a literal that may reuse its Proc (BlockDispatcher.ReusesProc): is the
/// Proc this frame made for the literal last time, kept in a variable of the frame, made again if nothing kept it.
///
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static Proc InstantiateReusableBlock(Proc previous, RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher) {
if (previous != null && previous.TryReuse()) {
return previous;
}
return dispatcher.HasMethod ? new Proc(ProcKind.Block, self, scope, dispatcher) : null;
}
[Emitted]
public static Proc/*!*/ DefineBlock(RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher, object/*!*/ clrMethod) {
return new Proc(ProcKind.Block, self, scope, dispatcher.SetMethod(clrMethod));
}
[Emitted]
public static Proc/*!*/ DefineLambda(RubyScope/*!*/ scope, object self, BlockDispatcher/*!*/ dispatcher, object/*!*/ clrMethod) {
return new Proc(ProcKind.Lambda, self, scope, dispatcher.SetMethod(clrMethod));
}
///
/// Used in a method call with a block to reset proc-kind when the call is retried
///
[Emitted]
public static void InitializeBlock(Proc/*!*/ proc) {
Assert.NotNull(proc);
proc.Kind = ProcKind.Block;
// a retried call may hand the block to a method that keeps it: only a light frame marks it reusable again
proc.ClearReusable();
}
///
/// Implements END block - like if it was a call to at_exit { ... } library method.
///
[Emitted]
public static void RegisterShutdownHandler(Proc/*!*/ proc) {
proc.LocalScope.RubyContext.RegisterShutdownHandler(proc);
}
#endregion
#region Yield: TODO: generate
// AggressiveOptimization, here and on the other helpers a yield, a Proc#call or a light-frame method goes through
// (block dispatchers, BlockParam and RuntimeFlowControl factories): they are called from compiled Ruby code from
// the first iteration on, but tiered compilation leaves them Tier-0 for the first second or two of a process -
// its call counting waits until no method has been jitted for 100 ms, which a program that keeps compiling Ruby
// code does not give it - so a short script ran its yields through unoptimized getters and casts. Steady state
// is the same either way (Util/bench, best of 6 after a warm-up); a short run is 5-15% faster.
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static object Yield0(Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 0);
try {
result = proc.Dispatcher.Invoke(blockParam, self, procArg);
} catch(EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
///
/// A lambda checks the number of arguments wherever it is called, including when it is
/// the block a method yields to. A plain block does not.
///
public static void RequireLambdaArity(Proc/*!*/ proc, int argCount) {
RequireLambdaArity(proc, argCount, null);
}
///
/// is the last of the arguments. A
/// block whose keywords were lowered onto positional parameters cannot tell a keyword hash
/// from a positional one by the count alone, so its declared signature decides: MRI counts
/// only the positional arguments against a lambda, and `|**nil|` refuses keywords in a
/// proc as well as in a lambda.
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RequireLambdaArity(Proc/*!*/ proc, int argCount, object lastArg) {
// A plain block takes any arguments - the common case, so it does not make the call:
// only a lambda, or a signature with keywords or **nil, has anything to check.
if (proc.Kind == ProcKind.Lambda || proc.Dispatcher.ChecksKeywords) {
CheckLambdaArity(proc, argCount, lastArg);
}
}
private static void CheckLambdaArity(Proc/*!*/ proc, int argCount, object lastArg) {
var signature = proc.Dispatcher.ParameterSignature;
// A symbol proc reports [[:req], [:rest]] but checks for its receiver itself
// ("no receiver given").
if (signature != null && proc.SymbolName == null) {
Hash keywords = null;
// = signature.TakesKeywords || signature.RefusesKeywords, cached
if (proc.Dispatcher.ChecksKeywords) {
keywords = argCount > 0 ? lastArg as Hash : null;
if (keywords != null && !keywords.IsKeywordArguments) {
keywords = null;
}
if (keywords != null && keywords.Count > 0 && signature.RefusesKeywords) {
throw RubyExceptions.CreateArgumentError("no keywords accepted");
}
}
if (proc.Kind != ProcKind.Lambda) {
return;
}
// The signature knows the positional bounds exactly ("1..2" for |a, b = 1|), where
// the arity alone would only say "1+".
int positional = argCount - (keywords != null ? 1 : 0);
int min = signature.MinPositionalCount, max = signature.MaxPositionalCount;
if (positional < min || (max >= 0 && positional > max)) {
throw MakeWrongNumberOfArgumentsErrorN(positional, signature.DescribeExpectedArguments());
}
return;
}
if (proc.Kind != ProcKind.Lambda) {
return;
}
int arity = proc.Dispatcher.Arity;
if (argCount == arity) {
return;
}
if (arity >= 0) {
throw MakeWrongNumberOfArgumentsError(argCount, arity);
}
if (argCount < -arity - 1) {
// MRI spells an unbounded arity "expected 1+".
throw MakeWrongNumberOfArgumentsErrorN(argCount,
(-arity - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) + "+");
}
}
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static object Yield1(object arg1, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 1, arg1);
try {
// a lambda takes the single argument as it is: no auto-splatting
result = proc.Kind == ProcKind.Lambda
? proc.Dispatcher.InvokeNoAutoSplat(blockParam, self, procArg, arg1)
: proc.Dispatcher.Invoke(blockParam, self, procArg, arg1);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
// YieldNoAutoSplat1 uses InvokeNoAutoSplat instead of Invoke (used by Call1)
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
internal static object YieldNoAutoSplat1(object arg1, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
try {
result = proc.Dispatcher.InvokeNoAutoSplat(blockParam, self, procArg, arg1);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static object Yield2(object arg1, object arg2, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 2, arg2);
try {
result = proc.Dispatcher.Invoke(blockParam, self, procArg, arg1, arg2);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static object Yield3(object arg1, object arg2, object arg3, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 3, arg3);
try {
result = proc.Dispatcher.Invoke(blockParam, self, procArg, arg1, arg2, arg3);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static object Yield4(object arg1, object arg2, object arg3, object arg4, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 4, arg4);
try {
result = proc.Dispatcher.Invoke(blockParam, self, procArg, arg1, arg2, arg3, arg4);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static object YieldN(object[]/*!*/ args, Proc procArg, object self, BlockParam/*!*/ blockParam) {
Debug.Assert(args.Length > BlockDispatcher.MaxBlockArity);
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, args.Length, args[args.Length - 1]);
try {
result = proc.Dispatcher.Invoke(blockParam, self, procArg, args);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
internal static object Yield(object[]/*!*/ args, Proc procArg, object self, BlockParam/*!*/ blockParam) {
switch (args.Length) {
case 0: return RubyOps.Yield0(procArg, self, blockParam);
case 1: return RubyOps.Yield1(args[0], procArg, self, blockParam);
case 2: return RubyOps.Yield2(args[0], args[1], procArg, self, blockParam);
case 3: return RubyOps.Yield3(args[0], args[1], args[2], procArg, self, blockParam);
case 4: return RubyOps.Yield4(args[0], args[1], args[2], args[3], procArg, self, blockParam);
default: return RubyOps.YieldN(args, procArg, self, blockParam);
}
}
[Emitted]
public static object YieldSplat0(IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 0 + splattee.Count, splattee.Count > 0 ? splattee[splattee.Count - 1] : null);
try {
result = proc.Dispatcher.InvokeSplat(blockParam, self, procArg, splattee);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
public static object YieldSplat1(object arg1, IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 1 + splattee.Count, splattee.Count > 0 ? splattee[splattee.Count - 1] : arg1);
try {
result = proc.Dispatcher.InvokeSplat(blockParam, self, procArg, arg1, splattee);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
public static object YieldSplat2(object arg1, object arg2, IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 2 + splattee.Count, splattee.Count > 0 ? splattee[splattee.Count - 1] : arg2);
try {
result = proc.Dispatcher.InvokeSplat(blockParam, self, procArg, arg1, arg2, splattee);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
public static object YieldSplat3(object arg1, object arg2, object arg3, IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 3 + splattee.Count, splattee.Count > 0 ? splattee[splattee.Count - 1] : arg3);
try {
result = proc.Dispatcher.InvokeSplat(blockParam, self, procArg, arg1, arg2, arg3, splattee);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
public static object YieldSplat4(object arg1, object arg2, object arg3, object arg4, IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, 4 + splattee.Count, splattee.Count > 0 ? splattee[splattee.Count - 1] : arg4);
try {
result = proc.Dispatcher.InvokeSplat(blockParam, self, procArg, arg1, arg2, arg3, arg4, splattee);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
public static object YieldSplatN(object[]/*!*/ args, IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, args.Length + splattee.Count, splattee.Count > 0 ? splattee[splattee.Count - 1] : args[args.Length - 1]);
try {
result = proc.Dispatcher.InvokeSplat(blockParam, self, procArg, args, splattee);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
[Emitted]
public static object YieldSplatNRhs(object[]/*!*/ args, IList/*!*/ splattee, object rhs, Proc procArg, object self, BlockParam/*!*/ blockParam) {
object result;
var proc = blockParam.Proc;
RequireLambdaArity(proc, args.Length + splattee.Count + 1, rhs);
try {
result = proc.Dispatcher.InvokeSplatRhs(blockParam, self, procArg, args, splattee, rhs);
} catch (EvalUnwinder evalUnwinder) {
result = blockParam.GetUnwinderResult(evalUnwinder);
}
return result;
}
#endregion
#region Methods
[Emitted] // MethodDeclaration:
public static object DefineMethod(object target, RubyScope/*!*/ scope, RubyMethodBody/*!*/ body) {
Assert.NotNull(body, scope);
RubyModule instanceOwner, singletonOwner;
RubyMemberFlags instanceFlags, singletonFlags;
bool moduleFunction = false;
// a top-level `def' of code run in a host's scope: see below
bool hostedTopLevel = false;
if (body.HasTarget) {
if (!RubyUtils.CanDefineSingletonMethod(target)) {
throw RubyExceptions.CreateTypeError("can't define singleton");
}
instanceOwner = null;
instanceFlags = RubyMemberFlags.Invalid;
singletonOwner = scope.RubyContext.GetOrCreateSingletonClass(target);
singletonFlags = RubyMemberFlags.Public;
} else {
var attributesScope = scope.GetMethodAttributesDefinitionScope();
if ((attributesScope.MethodAttributes & RubyMethodAttributes.ModuleFunction) == RubyMethodAttributes.ModuleFunction) {
// Singleton module-function's scope points to the instance method's RubyMemberInfo.
// This affects:
// 1) super call
// Super call is looking for Method.DeclaringModule while searching MRO, which would fail if the singleton module-function
// was in MRO. Since module-function can only be used on module the singleton method could only be on module's singleton.
// Module's singleton is never part of MRO so we are safe.
// 2) trace
// Method call trace reports non-singleton module.
// The instance method owner is GetMethodDefinitionOwner. That can be a class: Class has no
// #module_function, but the default a module's `module_function' sets reaches the class body
// it is called from (RubyScope.GetVisibilityScope), and MRI then defines both halves there
// too (#133).
instanceOwner = scope.GetMethodDefinitionOwner();
// `1.instance_eval { M.send(:module_function); def x; end }': the dummy singleton of an
// 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");
}
instanceFlags = RubyMemberFlags.Private;
singletonOwner = instanceOwner.GetOrCreateSingletonClass();
singletonFlags = RubyMemberFlags.Public;
moduleFunction = true;
} else {
bool atTopLevel;
instanceOwner = scope.GetMethodDefinitionOwner(out atTopLevel);
hostedTopLevel = GetHostedTopLevelMirror(scope, instanceOwner, atTopLevel) != null;
// A `def' inside `1.5.instance_eval { }' lands on the singleton class of the
// number, which is as far as MRI lets it get: running the block is fine,
// defining a method in it is not.
var singleton = instanceOwner as RubyClass;
if (singleton != null && singleton.IsSingletonClass) {
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");
}
RubyUtils.RequireDefinableSingleton(singleton.SingletonClassOf);
}
instanceFlags = (RubyMemberFlags)RubyUtils.GetSpecialMethodVisibility(attributesScope.Visibility, body.Name);
singletonOwner = null;
singletonFlags = RubyMemberFlags.Invalid;
}
}
RubyMethodInfo instanceMethod = null, singletonMethod = null;
if (body.Ast.UsesBlock) {
scope.RubyContext.NoteMethodUsingBlock(body.Name);
}
if (instanceOwner != null) {
var definitionScope = DefinitionScope(scope, instanceOwner);
if (scope.RubyContext.HasRefinements) {
body.SetDefinitionRefinements(instanceOwner, definitionScope.GetActiveRefinements());
} else {
body.SetDefinedWithoutRefinements();
}
SetMethod(scope.RubyContext, instanceMethod = hostedTopLevel
// the scope's copy of Object's method, below: compiled and labelled as Object's (issue 177)
? new RubyMethodInfo(body, definitionScope, instanceOwner, instanceFlags, scope.RubyContext.ObjectClass)
: new RubyMethodInfo(body, definitionScope, instanceOwner, instanceFlags)
);
}
// Code run in a host's scope (ScriptCode.Run(Scope), ScriptEngine.Execute(code, scope)) defines a top-level
// method in main's singleton class, so that the host reads it from the scope and the top level of another
// scope does not see it (RubyHosting1D). Ruby code expects it to be a private method of Object, which an
// instance of any class calls (issue 163): `class Foo; def bar = many; end' raised NameError. So it is
// defined there too. Object's is the one CRuby has, and so last-one-wins across scopes, as in CRuby; the
// top level of each scope still finds its own first.
RubyMethodInfo objectMethod = null;
if (hostedTopLevel) {
var objectClass = scope.RubyContext.ObjectClass;
var definitionScope = DefinitionScope(scope, objectClass);
if (scope.RubyContext.HasRefinements) {
body.SetDefinitionRefinements(objectClass, definitionScope.GetActiveRefinements());
} else {
body.SetDefinedWithoutRefinements();
}
SetMethod(scope.RubyContext, objectMethod =
new RubyMethodInfo(body, definitionScope, objectClass, instanceFlags)
);
}
if (singletonOwner != null) {
if (scope.RubyContext.HasRefinements) {
body.SetDefinitionRefinements(singletonOwner, scope.GetActiveRefinements());
} else {
body.SetDefinedWithoutRefinements();
}
SetMethod(scope.RubyContext, singletonMethod =
new RubyMethodInfo(body, scope, singletonOwner, singletonFlags)
);
}
if (instanceOwner != null && scope.RubyContext.IsWarningEnabled("performance")) {
WarnOptimizedMethodRedefinition(scope.RubyContext, instanceOwner, body.Name);
}
// the method's scope saves the result => singleton module-function uses instance-method
var method = instanceMethod ?? singletonMethod;
// :methods coverage records the definition, so that a method that is never called is
// still reported (with 0); the body's prologue does the counting.
var coverage = body.Coverage;
if (coverage != null && (coverage.State.Modes & CoverageModes.Methods) != 0) {
var location = body.Ast.Location;
coverage.AddMethod(body, method.BodyModule, body.Name,
location.Start.Line, location.Start.Column - 1, location.End.Line, location.End.Column - 1);
}
// Ruby 2.1+: def returns the method name as a symbol (enables `private def foo`). Interned before
// method_added, which interns the name as well: the hook then finds it in the identifier cache.
object result = scope.RubyContext.StringifyIdentifier(body.Name);
if (objectMethod != null) {
objectMethod.DeclaringModule.MethodAdded(body.Name);
}
method.DeclaringModule.MethodAdded(body.Name);
if (moduleFunction) {
method.DeclaringModule.GetOrCreateSingletonClass().MethodAdded(body.Name);
}
return result;
}
// MRI's vm_init_redefined_flag: the core methods its instructions inline, by class.
private static readonly Dictionary/*!*/ _optimizedMethods = new Dictionary {
{ "Integer", new[] { "+", "-", "*", "/", "%", "==", "===", "<", "<=", ">", ">=", "[]", "succ", "&", "|" } },
{ "Float", new[] { "+", "-", "*", "/", "%", "==", "===", "<", "<=", ">", ">=" } },
{ "String", new[] { "+", "==", "===", "<<", "length", "size", "empty?", "succ", "=~", "freeze", "-@" } },
{ "Array", new[] { "+", "<<", "[]", "[]=", "length", "size", "empty?", "max", "min", "hash", "pack", "include?" } },
{ "Hash", new[] { "[]", "[]=", "length", "size", "empty?" } },
{ "Symbol", new[] { "==", "===" } },
{ "NilClass", new[] { "===", "nil?" } },
{ "TrueClass", new[] { "===" } },
{ "FalseClass", new[] { "===" } },
{ "Regexp", new[] { "=~" } },
{ "Proc", new[] { "call" } },
{ "BasicObject", new[] { "!", "!=" } },
};
///
/// Warning[:performance]: redefining a core method MRI's interpreter optimises is reported.
///
private static void WarnOptimizedMethodRedefinition(RubyContext/*!*/ context, RubyModule/*!*/ owner, string/*!*/ name) {
string[] names;
if (owner.IsClass && owner.Name != null && _optimizedMethods.TryGetValue(owner.Name, out names)
&& Array.IndexOf(names, name) >= 0) {
context.ReportCategoryWarning("performance",
String.Format("Redefining '{0}#{1}' disables interpreter and JIT optimizations", owner.Name, name));
}
}
///
/// The scope a method body is compiled against. Normally the one the `def' was written
/// in; for a method of a refinement, one that also has the refinement's holder in use, so
/// that the body sees the other refinements the same module declares. The refine block
/// had them active while it ran, but that activation goes away with the block, and the
/// body runs later.
///
private static RubyScope/*!*/ DefinitionScope(RubyScope/*!*/ scope, RubyModule/*!*/ owner) {
if (!owner.IsRefinement || owner.RefinementHolder == null) {
return scope;
}
var result = new RubyModuleScope(scope, owner);
result.ActivateRefinements(owner.RefinementHolder);
return result;
}
private static void SetMethod(RubyContext/*!*/ callerContext, RubyMethodInfo/*!*/ method) {
var owner = method.DeclaringModule;
// Do not trigger the add-method event just yet, we need to assign the result into closure before executing any user code.
// If the method being defined is "method_added" itself, we would call that method before the info gets assigned to the closure.
owner.SetMethodNoEvent(callerContext, method.DefinitionName, method);
// expose RubyMethod in the scope (the method is bound to the main singleton instance):
if (owner.GlobalScope != null) {
RubyOps.ScopeSetMember(
owner.GlobalScope.Scope,
method.DefinitionName,
new RubyMethod(owner.GlobalScope.MainObject, method, method.DefinitionName)
);
}
}
[Emitted] // AliasStatement:
public static void AliasMethod(RubyScope/*!*/ scope, string/*!*/ newName, string/*!*/ oldName) {
bool atTopLevel;
RubyModule owner = scope.GetMethodDefinitionOwner(out atTopLevel);
// Object's alias is the one CRuby makes, and so is its NameError when neither has the method. One that only
// main's singleton class has (`def self.x') is aliased there alone, as it was before.
// And main's singleton class leaves out a method it no longer has (`undef'ed there) that Object has from another
// scope: CRuby has that one and aliases it.
RubyModule mirror = GetHostedTopLevelMirror(scope, owner, atTopLevel);
if (mirror != null) {
bool inOwner = owner.ResolveMethod(oldName, VisibilityContext.AllVisible).Found;
if (!inOwner || mirror.ResolveMethod(oldName, VisibilityContext.AllVisible).Found) {
mirror.AddMethodAlias(newName, oldName);
}
if (!inOwner) {
return;
}
}
owner.AddMethodAlias(newName, oldName);
}
[Emitted] // UndefineMethod:
public static void UndefineMethod(RubyScope/*!*/ scope, string/*!*/ name) {
bool atTopLevel;
RubyModule owner = scope.GetMethodDefinitionOwner(out atTopLevel);
RubyModule mirror = GetHostedTopLevelMirror(scope, owner, atTopLevel);
// as for `alias': Object's, and its NameError, as in CRuby; a singleton method of main only in main's singleton class
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);
}
if (inMirror) {
mirror.UndefineMethod(name);
}
owner.UndefineMethod(name);
}
///
/// Code run in a host's scope (ScriptCode.Run(Scope), ScriptEngine.Execute(code, scope), ScriptSource.Execute(scope))
/// has main's singleton class, the scope's, for the owner of its top-level methods (RubyScope.MethodLookupModule), so
/// that the host reads them from the scope and the top level of another scope does not see them (RubyHosting1D). Ruby
/// code expects them in Object, where CRuby has them and an instance of any class calls them (issues 163, 177). So a
/// top-level `def', `alias', `undef', `public :x'/`private :x' and main.define_method act on Object as well: this is
/// Object when is such a scope's owner, reached from its top level (not from a `def' in
/// main.instance_eval, which defines a singleton method of main), and null otherwise.
///
internal static RubyModule GetHostedTopLevelMirror(RubyScope/*!*/ scope, RubyModule/*!*/ owner, bool atTopLevel) {
return atTopLevel && owner is RubyClass cls && cls.IsHostedTopLevelMethodOwner ? scope.RubyContext.ObjectClass : null;
}
#endregion
#region Modules
[Emitted]
public static RubyModule/*!*/ DefineGlobalModule(RubyScope/*!*/ scope, string/*!*/ name, string sourcePath, int sourceLine) {
return DefineModule(scope, scope.Top.TopModuleOrObject, name, sourcePath, sourceLine);
}
[Emitted]
public static RubyModule/*!*/ DefineNestedModule(RubyScope/*!*/ scope, string/*!*/ name, string sourcePath, int sourceLine) {
return DefineModule(scope, scope.GetInnerMostModuleForConstantLookup(), name, sourcePath, sourceLine);
}
[Emitted]
public static RubyModule/*!*/ DefineModule(RubyScope/*!*/ scope, object target, string/*!*/ name, string sourcePath, int sourceLine) {
var owner = RubyUtils.GetModuleFromObject(scope, target);
CheckConstantVisibility(owner, name);
return DefineModule(scope, owner, name, sourcePath, sourceLine);
}
///
/// `module Owner::Name` and `class Owner::Name` name the constant explicitly, so a
/// private one is out of reach here just as it is for a reference.
///
private static void CheckConstantVisibility(RubyModule/*!*/ owner, string/*!*/ name) {
bool isPrivate;
RubyModule declaringOwner;
using (owner.Context.ClassHierarchyLocker()) {
isPrivate = owner.IsPrivateConstantInAncestors(name);
declaringOwner = isPrivate ? owner.GetConstantOwnerNoLock(name) : null;
}
if (isPrivate) {
RubyContext.SetPrivateConstantReference(declaringOwner ?? owner);
owner.Context.ResolveMissingConstant(owner, name);
}
}
// thread-safe:
private static RubyModule/*!*/ DefineModule(RubyScope/*!*/ scope, RubyModule/*!*/ owner, string/*!*/ name,
string sourcePath, int sourceLine) {
Assert.NotNull(scope, owner);
ConstantStorage existing;
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"));
}
return module;
} else {
// create class/module object:
var result = owner.Context.DefineModule(owner, name);
owner.SetConstantLocation(name, sourcePath, sourceLine);
return result;
}
}
#endregion
#region Classes
[Emitted]
public static RubyClass/*!*/ DefineSingletonClass(RubyScope/*!*/ scope, object obj) {
RubyUtils.RequireDefinableSingleton(obj);
var result = scope.RubyContext.GetOrCreateSingletonClass(obj);
// MRI's rb_singleton_class: a class's singleton class, once exposed, gets a singleton of its
// own, which descends from the superclass's - so D.singleton_class responds to methods
// defined in `class << self; class << self` of D's superclass.
if (obj is RubyClass) {
result.GetOrCreateSingletonClass();
}
return result;
}
[Emitted]
public static RubyModule/*!*/ DefineGlobalClass(RubyScope/*!*/ scope, string/*!*/ name, object superClassObject,
string sourcePath, int sourceLine) {
return DefineClass(scope, scope.Top.TopModuleOrObject, name, superClassObject, sourcePath, sourceLine);
}
[Emitted]
public static RubyModule/*!*/ DefineNestedClass(RubyScope/*!*/ scope, string/*!*/ name, object superClassObject,
string sourcePath, int sourceLine) {
return DefineClass(scope, scope.GetInnerMostModuleForConstantLookup(), name, superClassObject, sourcePath, sourceLine);
}
[Emitted]
public static RubyModule/*!*/ DefineClass(RubyScope/*!*/ scope, object target, string/*!*/ name, object superClassObject,
string sourcePath, int sourceLine) {
var owner = RubyUtils.GetModuleFromObject(scope, target);
CheckConstantVisibility(owner, name);
return DefineClass(scope, owner, name, superClassObject, sourcePath, sourceLine);
}
// thread-safe:
private static RubyClass/*!*/ DefineClass(RubyScope/*!*/ scope, RubyModule/*!*/ owner, string/*!*/ name, object superClassObject,
string sourcePath, int sourceLine) {
Assert.NotNull(owner);
RubyClass superClass = ToSuperClass(owner.Context, superClassObject);
// only the owner's own constants: a class of that name in a module Object includes is
// not reopened, a new one is defined (MRI's rb_const_defined_at)
ConstantStorage existing;
if (owner.TryGetConstant(scope.GlobalScope, name, out existing)) {
RubyClass cls = existing.Value as RubyClass;
if (cls == null || !cls.IsClass) {
throw 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);
}
return cls;
} else {
var result = owner.Context.DefineClass(owner, name, superClass, null);
owner.SetConstantLocation(name, sourcePath, sourceLine);
return result;
}
}
///
/// MRI points at the existing definition when a class/module name is already taken:
/// Foo is not a class
/// foo.rb:2: previous definition of Foo was here
///
private static string/*!*/ DescribePreviousDefinition(RubyModule/*!*/ owner, string/*!*/ name, string/*!*/ format) {
var message = String.Format(format, name);
string path;
int line;
if (owner.TryGetConstantLocation(name, out path, out line)) {
message += String.Format("\n{0}:{1}: previous definition of {2} was here", path, line, name);
}
return message;
}
private static RubyClass/*!*/ ToSuperClass(RubyContext/*!*/ ec, object superClassObject) {
return (superClassObject != null) ? RubyClass.CheckInheritable(ec, superClassObject) : ec.ObjectClass;
}
#endregion
#region Constants
///
/// A
/// ::A
///
[Emitted]
public static object GetUnqualifiedConstant(RubyScope/*!*/ scope, ConstantSiteCache/*!*/ cache, string/*!*/ name, bool isGlobal) {
object result = null;
RubyModule missingConstantOwner;
RubyModule owner = null;
var context = scope.RubyContext;
using (context.ClassHierarchyLocker()) {
// Thread safety:
// Another thread could have already updated the value, so the site version might be the same as CAV.
// We do the lookup anyways since it is no-op and this only happens rarely.
//
// An important invariant holds here: in any time after initialized for the first time the Value field contains a valid value.
// Threads can read an older value (the previous version) but that is still correct since we don't guarantee immediate
// propagation of the constant write to all readers.
//
// if (site.Version = CAV) {
// <- another thread could increment CAV here - we may return old or new value (both are ok)
// value = site.Value;
// } else {
// <- another thread could get here as well and update the site before we get to update it.
// GetConstant(...)
// }
// Constants might be updated during constant resolution due to autoload.
// Any such updates need to invalidate the cache hence we need to capture the version before resolving the constant.
int newVersion = context.ConstantAccessVersion;
ConstantStorage storage;
bool isPrivateGlobal = false;
if (!isGlobal) {
missingConstantOwner = scope.TryResolveConstantNoLock(scope.GlobalScope, name, out storage, out owner);
} else if (context.ObjectClass.TryResolveConstantNoLock(scope.GlobalScope, name, out storage)) {
if (context.ObjectClass.IsPrivateConstant(name)) {
// `::NAME' is a qualified reference, which a private constant of Object is out of reach of
RubyContext.SetPrivateConstantReference(context.ObjectClass);
missingConstantOwner = context.ObjectClass;
storage = default(ConstantStorage);
// a cached miss would lose the private-constant message
isPrivateGlobal = true;
} else {
missingConstantOwner = null;
owner = context.ObjectClass;
}
} else {
missingConstantOwner = context.ObjectClass;
}
object newCacheValue;
bool deprecated = false;
if (missingConstantOwner == null) {
result = storage.Value;
newCacheValue = MakeConstantCacheValue(context, storage, owner, name, cache.IsCoreLibrary);
deprecated = ReportConstantDeprecation(context, owner, name);
} else {
newCacheValue = ConstantSiteCache.WeakMissingConstant;
}
if (!context.IsAutoloadInProgress && !deprecated && !isPrivateGlobal && (isGlobal || !IsLexicallyInObjectSingleton(scope))) {
cache.Update(newCacheValue, newVersion);
}
}
if (missingConstantOwner != null) {
result = missingConstantOwner.ConstantMissing(name);
} else if (context.RactorsStarted && !cache.IsCoreLibrary) {
RactorIsolation.CheckConstantRead(context, owner, name, result);
}
return result;
}
///
/// What a constant site caches for a constant's value: its weak reference if it has one.
/// Once the runtime has started Ractors, a value a non-main Ractor might not be allowed
/// to see is wrapped, so that a cached read checks ().
///
private static object/*!*/ MakeConstantCacheValue(RubyContext/*!*/ context, ConstantStorage storage, RubyModule owner, string/*!*/ name,
bool isCoreLibrary) {
object cached = storage.WeakValue ?? storage.Value;
if (context.RactorsStarted && !isCoreLibrary && !RactorIsolation.IsTriviallyShareable(storage.Value)) {
return new RactorCheckedConstant(context, cached, owner, name);
}
return cached;
}
///
/// A cached constant read of a value wrapped: the value,
/// if the current Ractor may see it.
///
[Emitted]
public static object ReadRactorCheckedConstant(object/*!*/ cached) {
var constant = (RactorCheckedConstant)cached;
var weak = constant.Value as WeakReference;
object value = (weak != null) ? weak.Target : constant.Value;
return RactorIsolation.CheckConstantRead(constant.Context, constant.Owner, constant.Name, value);
}
///
/// A1::..::AN
/// ::A1::..::AN
///
[Emitted]
public static object GetQualifiedConstant(RubyScope/*!*/ scope, ConstantSiteCache/*!*/ cache, string/*!*/[]/*!*/ qualifiedName, bool isGlobal) {
// The lookup may call Ruby code - #inspect for the TypeError of a qualifier that is no module, const_missing - from a
// light frame that has no call site and so checked no stack at its entry (MethodDefinition.LightFrame.MakesCalls):
// `def inspect = Obj::X' with Obj not a module recurses through here alone. Only a read the cache cannot answer gets here.
RequireSufficientStack();
var globalScope = scope.GlobalScope;
var context = globalScope.Context;
using (context.ClassHierarchyLocker()) {
int newVersion = context.ConstantAccessVersion;
ConstantStorage storage;
bool anyMissing;
RubyModule topModule = isGlobal ? context.ObjectClass : null;
RubyModule owner;
object result = ResolveQualifiedConstant(scope, qualifiedName, topModule, true, out storage, out anyMissing, out owner);
string name = qualifiedName[qualifiedName.Length - 1];
// cache result only if no constant was missing:
if (!anyMissing && !context.IsAutoloadInProgress && (isGlobal || !IsLexicallyInObjectSingleton(scope))) {
Debug.Assert(result == storage.Value);
cache.Update(MakeConstantCacheValue(context, storage, owner, name, cache.IsCoreLibrary), newVersion);
}
return (context.RactorsStarted && !cache.IsCoreLibrary) ? RactorIsolation.CheckConstantRead(context, owner, name, result) : result;
}
}
///
/// {expr}::A1::..::AN
///
[Emitted]
public static object GetExpressionQualifiedConstant(object target, RubyScope/*!*/ scope, ExpressionQualifiedConstantSiteCache/*!*/ cache,
string/*!*/[]/*!*/ qualifiedName) {
RubyModule module = target as RubyModule;
if (module == null) {
throw RubyUtils.CreateNotModuleException(scope, target);
}
var condition = cache.Condition;
RubyContext context = module.Context;
// Note that the module can be bound to another runtime:
if (module.Id == condition.ModuleId && context.ConstantAccessVersion == condition.Version) {
object value = cache.Value;
if (value.GetType() == typeof(WeakReference)) {
return ((WeakReference)value).Target;
} else if (value.GetType() == typeof(RactorCheckedConstant)) {
return ReadRactorCheckedConstant(value);
} else {
return value;
}
}
using (context.ClassHierarchyLocker()) {
int newVersion = context.ConstantAccessVersion;
ConstantStorage storage;
bool anyMissing;
RubyModule owner;
object result = ResolveQualifiedConstant(scope, qualifiedName, module, true, out storage, out anyMissing, out owner);
string name = qualifiedName[qualifiedName.Length - 1];
// cache result only if no constant was missing:
if (!anyMissing && !context.IsAutoloadInProgress) {
Debug.Assert(result == storage.Value);
cache.Update(MakeConstantCacheValue(context, storage, owner, name, cache.IsCoreLibrary), newVersion, module);
}
return (context.RactorsStarted && !cache.IsCoreLibrary) ? RactorIsolation.CheckConstantRead(context, owner, name, result) : result;
}
}
///
/// Code in `class << obj' runs once per obj when it sits in a loop or a method, and every run
/// has its own singleton class - and its own classes nested in it - to find constants in,
/// while a constant site's cache is keyed only on the constant version. Such lookups are not
/// cached. `class << self' in a class or module body, the common form, keeps the cache.
///
internal static bool IsLexicallyInObjectSingleton(RubyScope/*!*/ scope) {
for (RubyScope s = scope; s != null; s = s.Parent) {
var cls = s.Module as RubyClass;
if (cls != null && cls.IsSingletonClass && !(cls.SingletonClassOf is RubyModule)) {
return true;
}
}
return false;
}
///
/// defined? A
///
[Emitted]
public static bool IsDefinedUnqualifiedConstant(RubyScope/*!*/ scope, IsDefinedConstantSiteCache/*!*/ cache, string/*!*/ name) {
var context = scope.RubyContext;
using (context.ClassHierarchyLocker()) {
int newVersion = context.ConstantAccessVersion;
ConstantStorage storage;
bool exists = scope.TryResolveConstantNoLock(null, name, out storage) == null;
if (!context.IsAutoloadInProgress && !IsLexicallyInObjectSingleton(scope)) {
cache.Update(exists, newVersion);
}
return exists;
}
}
///
/// defined? ::A
///
[Emitted]
public static bool IsDefinedGlobalConstant(RubyScope/*!*/ scope, IsDefinedConstantSiteCache/*!*/ cache, string/*!*/ name) {
var context = scope.RubyContext;
using (context.ClassHierarchyLocker()) {
int newVersion = context.ConstantAccessVersion;
ConstantStorage storage;
bool exists = context.ObjectClass.TryResolveConstantNoLock(null, name, out storage) &&
!context.ObjectClass.IsPrivateConstant(name);
if (!context.IsAutoloadInProgress) {
cache.Update(exists, newVersion);
}
return exists;
}
}
///
/// defined? A1::..::AN
/// defined? ::A1::..::AN
///
[Emitted]
public static bool IsDefinedQualifiedConstant(RubyScope/*!*/ scope, IsDefinedConstantSiteCache/*!*/ cache,
string/*!*/[]/*!*/ qualifiedName, bool isGlobal) {
var context = scope.RubyContext;
using (context.ClassHierarchyLocker()) {
int newVersion = context.ConstantAccessVersion;
ConstantStorage storage;
bool anyMissing;
RubyModule topModule = isGlobal ? context.ObjectClass : null;
RubyModule owner;
try {
owner = ResolveQualifiedConstant(scope, qualifiedName, topModule, false, out storage, out anyMissing, out _) as RubyModule;
} catch {
// autoload can raise an exception
scope.RubyContext.SetCurrentException(null);
return false;
}
// Note that the owner could be another runtime's module:
bool exists = IsVisibleConstantDefined(owner, context, qualifiedName[qualifiedName.Length - 1], out storage);
// cache result only if no constant was missing:
if (!anyMissing && !context.IsAutoloadInProgress && (isGlobal || !IsLexicallyInObjectSingleton(scope))) {
cache.Update(exists, newVersion);
}
return exists;
}
}
///
/// defined? {expr}::A
/// defined? {expr}::A1::..::AN
///
[Emitted]
public static bool IsDefinedExpressionQualifiedConstant(object target, RubyScope/*!*/ scope,
ExpressionQualifiedIsDefinedConstantSiteCache/*!*/ cache, string/*!*/[]/*!*/ qualifiedName) {
RubyModule module = target as RubyModule;
if (module == null) {
return false;
}
var condition = cache.Condition;
RubyContext context = module.Context;
// Note that the module can be bound to another runtime:
if (module.Id == condition.ModuleId && context.ConstantAccessVersion == condition.Version) {
return cache.Value;
}
using (context.ClassHierarchyLocker()) {
int newVersion = context.ConstantAccessVersion;
ConstantStorage storage;
bool exists;
if (qualifiedName.Length == 1) {
// Note that the owner could be another runtime's module:
exists = IsVisibleConstantDefined(module, context, qualifiedName[0], out storage);
} else {
bool anyMissing;
RubyModule owner;
try {
owner = ResolveQualifiedConstant(scope, qualifiedName, module, false, out storage, out anyMissing, out _) as RubyModule;
} catch {
// autoload can raise an exception:
return false;
}
// Note that the owner could be another runtime's module:
exists = IsVisibleConstantDefined(owner, context, qualifiedName[qualifiedName.Length - 1], out storage);
// cache result only if no constant was missing:
if (anyMissing) {
return exists;
}
}
if (!context.IsAutoloadInProgress) {
cache.Update(exists, newVersion, module);
}
return exists;
}
}
private static object ResolveQualifiedConstant(RubyScope/*!*/ scope, string/*!*/[]/*!*/ qualifiedName, RubyModule topModule, bool isGet,
out ConstantStorage storage, out bool anyMissing, out RubyModule resultOwner) {
Debug.Assert(qualifiedName.Length >= 2 || qualifiedName.Length == 1 && isGet);
RubyContext context = scope.RubyContext;
context.RequiresClassHierarchyLock();
RubyModule missingConstantOwner;
RubyGlobalScope globalScope = scope.GlobalScope;
int nameCount = (isGet) ? qualifiedName.Length : qualifiedName.Length - 1;
string name = qualifiedName[0];
RubyModule firstOwner = null;
if (topModule == null) {
// the first name of `A::B` is an ordinary lexical lookup, where a private
// constant of an enclosing module is perfectly visible
missingConstantOwner = scope.TryResolveConstantNoLock(globalScope, name, out storage, out firstOwner);
} else if (TryResolveVisibleConstant(topModule, context, globalScope, name, out storage)) {
missingConstantOwner = null;
firstOwner = topModule;
} else {
missingConstantOwner = topModule;
}
// defined?(A::B::C) never calls const_missing (MRI): a name that is not there makes the
// whole path undefined. Only the get does what evaluating A::B would.
object result;
resultOwner = firstOwner ?? missingConstantOwner;
if (missingConstantOwner == null) {
result = storage.Value;
anyMissing = ReportConstantDeprecation(context, firstOwner, name);
} else if (!isGet) {
anyMissing = true;
RubyContext.ClearPrivateConstantReference();
return null;
} else {
anyMissing = true;
using (context.ClassHierarchyUnlocker()) {
result = missingConstantOwner.ConstantMissing(name);
}
}
for (int i = 1; i < nameCount; i++) {
RubyModule owner = RubyUtils.GetModuleFromObject(scope, result);
resultOwner = owner;
// Note that the owner could be another runtime's module:
name = qualifiedName[i];
if (TryResolveVisibleConstant(owner, context, globalScope, name, out storage)) {
// Constant write updates constant version in a single runtime only.
// Therefore if the chain mixes modules from different runtimes we cannot cache the result.
if (owner.Context != context) {
anyMissing = true;
}
if (ReportConstantDeprecation(context, owner, name)) {
anyMissing = true;
}
result = storage.Value;
} else if (!isGet) {
anyMissing = true;
RubyContext.ClearPrivateConstantReference();
return null;
} else {
anyMissing = true;
using (context.ClassHierarchyUnlocker()) {
result = owner.ConstantMissing(name);
}
}
}
return result;
}
///
/// Emits the warning Module#deprecate_constant asks for, if the constant that just
/// resolved is deprecated, and reports whether it did - the caller uses that to leave the
/// call site uncached, so the warning is not swallowed by the second reference onwards.
///
/// Warning.warn can be overridden in Ruby, so the class hierarchy lock is dropped around
/// the call exactly as the #const_missing dispatches here do.
///
private static bool ReportConstantDeprecation(RubyContext/*!*/ context, RubyModule owner, string/*!*/ name) {
if (!context.HasDeprecatedConstants || owner == null || owner.Context != context) {
return false;
}
RubyModule deprecatedOwner = owner.GetDeprecatedConstantOwnerNoLock(name);
if (deprecatedOwner == null) {
return false;
}
using (context.ClassHierarchyUnlocker()) {
context.ReportConstantDeprecation(deprecatedOwner, name);
}
return true;
}
///
/// A qualified constant reference - `Mod::NAME` - does not see a constant the owner
/// declared private. MRI reports it as missing, which routes it through #const_missing,
/// and remembers that it was really there so the default #const_missing can say so.
///
private static bool TryResolveVisibleConstant(RubyModule/*!*/ owner, RubyContext/*!*/ context, RubyGlobalScope globalScope,
string/*!*/ name, out ConstantStorage storage) {
if (!owner.TryResolveConstant(context, globalScope, name, out storage)) {
return false;
}
if (owner.Context != context) {
return true;
}
if (owner.IsPrivateConstantInAncestors(name)) {
// the NameError names the module that made the constant private, as MRI's does
RubyContext.SetPrivateConstantReference(owner.GetConstantOwnerNoLock(name) ?? owner);
storage = default(ConstantStorage);
return false;
}
if (owner.IsTopLevelConstantOnly(name)) {
storage = default(ConstantStorage);
return false;
}
return true;
}
///
/// `defined?(Mod::NAME)` is nil for a constant the owner declared private - and unlike a
/// reference it must not leave a private-constant reference behind for #const_missing.
///
private static bool IsVisibleConstantDefined(RubyModule owner, RubyContext/*!*/ context, string/*!*/ name, out ConstantStorage storage) {
storage = default(ConstantStorage);
if (owner == null || !owner.TryResolveConstant(context, null, name, out storage)) {
return false;
}
return owner.Context != context
|| (!owner.IsPrivateConstantInAncestors(name) && !owner.IsTopLevelConstantOnly(name));
}
[Emitted]
public static object GetMissingConstant(RubyScope/*!*/ scope, ConstantSiteCache/*!*/ cache, string/*!*/ name) {
return scope.GetInnerMostModuleForConstantLookup().ConstantMissing(name);
}
[Emitted]
public static object GetGlobalMissingConstant(RubyScope/*!*/ scope, ConstantSiteCache/*!*/ cache, string/*!*/ name) {
return scope.RubyContext.ObjectClass.ConstantMissing(name);
}
[Emitted] // ConstantVariable:
public static object SetGlobalConstant(object value, RubyScope/*!*/ scope, string/*!*/ name, string sourcePath, int sourceLine,
RubyEncoding/*!*/ encoding) {
RubyUtils.SetConstant(scope.RubyContext.ObjectClass, name, value, sourcePath, sourceLine, encoding);
return value;
}
[Emitted] // ConstantVariable:
public static object SetUnqualifiedConstant(object value, RubyScope/*!*/ scope, string/*!*/ name, string sourcePath, int sourceLine,
RubyEncoding/*!*/ encoding) {
RubyUtils.SetConstant(scope.GetInnerMostModuleForConstantLookup(), name, value, sourcePath, sourceLine, encoding);
return value;
}
[Emitted] // ConstantVariable:
public static object SetQualifiedConstant(object value, object target, RubyScope/*!*/ scope, string/*!*/ name,
string sourcePath, int sourceLine, RubyEncoding/*!*/ encoding) {
RubyUtils.SetConstant(RubyUtils.GetModuleFromObject(scope, target), name, value, sourcePath, sourceLine, encoding);
return value;
}
#endregion
// MakeArray*
public const int OptimizedOpCallParamCount = 5;
#region MakeArray
[Emitted]
public static RubyArray/*!*/ MakeArray0() {
return new RubyArray(0);
}
///
/// Ruby 3 semantics for a call-site `**splat`: the keyword hash is passed as a trailing
/// positional argument, but an *empty* one is dropped entirely -- `f(1, **{})` calls
/// `f(1)`, not `f(1, {})`. A literal `f(1, {})` still passes the hash, which is why this
/// is only emitted for argument hashes that actually contain a `**` splat.
/// The result is fed to the ordinary splatting machinery, so it is either [] or [hash].
///
///
/// `f(k: v, **h)`: h's entries added to the keyword hash being built for the call - the
/// call's own, so it is filled in place - which is returned; nil adds nothing. Null if h is
/// anything else: that goes through Hash#merge, for #to_hash.
///
[Emitted]
public static object MergeKeywordSplat(RubyScope/*!*/ scope, object keywords, object splatted) {
if (splatted == null) {
return keywords;
}
var source = splatted as Hash;
var target = keywords as Hash;
if (source == null || target == null) {
return null;
}
foreach (var entry in source) {
RubyUtils.SetHashElement(scope.RubyContext, target, entry.Key, entry.Value);
}
return target;
}
///
/// for a that has to be a Hash - nil
/// included, anything else raises TypeError - and a that is one: what
/// the parameterless super of `def m(k: 1, **rest)` does with rest (KeywordSplatMerge.HashOnly).
///
[Emitted]
public static object/*!*/ MergeKeywordHash(RubyScope/*!*/ scope, object keywords, object splatted) {
if (!(splatted is Hash)) {
throw RubyExceptions.CreateUnexpectedTypeError(scope.RubyContext, splatted, "Hash");
}
return MergeKeywordSplat(scope, keywords, splatted);
}
///
/// `f(**h)` with h a Hash or nil: what makes of it. Null for
/// anything else, which the call site first converts with #to_hash (by way of Hash#merge).
///
[Emitted]
public static RubyArray SplatKeywordHashIfHash(RubyScope/*!*/ scope, object hash) {
return (hash == null || hash is Hash) ? SplatKeywordHash(scope, hash) : null;
}
[Emitted]
public static RubyArray/*!*/ SplatKeywordHash(RubyScope/*!*/ scope, object hash) {
var keywords = KeywordSplatArgument(scope, hash);
if (keywords == null) {
return new RubyArray(0);
}
var result = new RubyArray(1);
result.Add(keywords);
return result;
}
///
/// `f(**h)` with h a Hash or nil, as the one argument it passes: null when it passes none at
/// all (nil, or an empty Hash), and a copy marked as keyword arguments otherwise. A call
/// site that tests for null and passes the hash plainly (SuperCall) avoids the one-or-zero
/// element array makes and the splatted call it takes.
///
[Emitted]
public static Hash KeywordSplatArgument(RubyScope/*!*/ scope, object hash) {
// `f(**nil)` passes no keywords at all
if (hash == null) {
return null;
}
var dict = hash as IDictionary