diff --git a/src/core/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs b/src/core/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs --- a/src/core/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs +++ b/src/core/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs @@ -30,6 +30,35 @@ namespace Microsoft.Scripting.Interpreter { public readonly StrongBox[] Closure; + /// + /// What the language handed a frame it runs to carry on at a point of its own choosing (LightLambda.Interpret, see + /// ResumeTarget); null otherwise. The language's instruction that takes it clears it. + /// + public object ResumeState; + + /// + /// Jumps from , the point the current instruction stands at, to , + /// entering the regions on the way as running into them would have (see ResumeTarget): returns the offset for the + /// current instruction's Run to return. is the language's code that the regions on the + /// way run when they are entered, as ranges of instructions [start, end) in order (or null): straight-line code that + /// leaves the evaluation stack as it found it. What the jump does is worked out the first time and kept on the target. + /// + public int GotoResume(ResumeTarget source, ResumeTarget target, int[] entryCode) { + var plan = target.GetPlan(Interpreter, source, entryCode); + int from = InstructionIndex; + var run = plan.Run; + for (int i = 0; i < run.Length; i++) { + // where an exception the instruction throws is handled, as when it runs in its place + InstructionIndex = plan.Indexes[i]; + if (run[i].Run(this) != 1) { + throw new InvalidOperationException("resume: the entry code of a region on the way jumps"); + } + } + InstructionIndex = from; + SetStackDepth(target.StackDepth); + return target.Index - from; + } + public int StackIndex; public int InstructionIndex; diff --git a/src/core/Microsoft.Dynamic/Interpreter/LightCompiler.cs b/src/core/Microsoft.Dynamic/Interpreter/LightCompiler.cs --- a/src/core/Microsoft.Dynamic/Interpreter/LightCompiler.cs +++ b/src/core/Microsoft.Dynamic/Interpreter/LightCompiler.cs @@ -159,6 +159,12 @@ namespace Microsoft.Scripting.Interpreter { private readonly Stack _exceptionForRethrowStack = new(); + // For MarkResumeTarget: the EnterTryFinally instructions of the try bodies being compiled, outermost first, and what + // kind of handler or finally block is being compiled, innermost last (a fault emulated by a catch is compiled in the + // try's label scope, so the label scopes do not say). + private readonly List _openTryFinallies = new(); + private readonly List _openHandlers = new(); + // Set to true to force compiliation of this lambda. // This disables the interpreter for this lambda. We still need to // walk it, however, to resolve variables closed over from the parent @@ -206,6 +212,15 @@ namespace Microsoft.Scripting.Interpreter { public InstructionList Instructions { get; } + /// + /// Marks the current point of the instructions as one a frame may carry on at without having run the instructions + /// before it (see ResumeTarget): a point inside a catch or fault handler or a finally block is marked refused. + /// + public ResumeTarget MarkResumeTarget() { + return new ResumeTarget(Instructions.Count, Instructions.CurrentStackDepth, Instructions.CurrentContinuationsDepth, + _openTryFinallies.ToArray(), _openHandlers.Count > 0 ? _openHandlers[_openHandlers.Count - 1] : null); + } + public LocalVariables Locals => _locals; internal static Expression Unbox(Expression strongBoxExpression) { @@ -1282,11 +1297,15 @@ namespace Microsoft.Scripting.Interpreter { BranchLabel startOfFinally = null; if (node.Finally is not null) { startOfFinally = Instructions.MakeLabel(); + _openTryFinallies.Add(Instructions.Count); Instructions.EmitEnterTryFinally(startOfFinally); } PushLabelBlock(LabelScopeKind.Try); Compile(node.Body); + if (startOfFinally is not null) { + _openTryFinallies.RemoveAt(_openTryFinallies.Count - 1); + } bool hasValue = node.Body.Type != typeof(void); int tryEnd = Instructions.Count; @@ -1312,7 +1331,9 @@ namespace Microsoft.Scripting.Interpreter { int handlerLabel = Instructions.MarkRuntimeLabel(); int handlerStart = Instructions.Count; + _openHandlers.Add("in a fault handler"); CompileAsVoidRemoveRethrow(handler.Body); + _openHandlers.RemoveAt(_openHandlers.Count - 1); Instructions.EmitLeaveFault(hasValue); Instructions.MarkLabel(end); @@ -1349,7 +1370,9 @@ namespace Microsoft.Scripting.Interpreter { int handlerStart = Instructions.Count; CompileSetVariable(parameter, true); + _openHandlers.Add("in a catch handler"); Compile(handler.Body); + _openHandlers.RemoveAt(_openHandlers.Count - 1); _exceptionForRethrowStack.Pop(); @@ -1374,7 +1397,9 @@ namespace Microsoft.Scripting.Interpreter { Instructions.MarkLabel(startOfFinally); Instructions.EmitEnterFinally(); + _openHandlers.Add("in a finally block"); CompileAsVoid(node.Finally); + _openHandlers.RemoveAt(_openHandlers.Count - 1); Instructions.EmitLeaveFinally(); PopLabelBlock(LabelScopeKind.Finally); 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 @@ -240,6 +240,38 @@ namespace Microsoft.Scripting.Interpreter { } } + /// + /// Whether the lambda has an interpreted form that can run: false for one that was compiled to IL + /// at once, which the light compiler could not take. + /// + public bool CanInterpret => EnsureInterpreter() is not null; + + private Interpreter EnsureInterpreter() { + // a lambda whose light compile was put off has its interpreter once that is done (see LightDelegateCreator) + return _interpreter ??= _delegateCreator.EnsureLightCompiled(); + } + + /// + /// Runs the lambda in the interpreter, whether or not it has been compiled to IL since, with + /// on its frame (): a language that gives up on code of its own compiled from + /// the same source hands the rest of the call to the lambda this way, and an instruction of its own near the start takes + /// the state and jumps to where its code had got to (see ResumeTarget). Returns what the lambda returns (null for void). + /// + public object Interpret(object resumeState, params object[] arguments) { + var interpreter = EnsureInterpreter() ?? throw new InvalidOperationException("the lambda has no interpreted form"); + var frame = new InterpretedFrame(interpreter, _closure) { ResumeState = resumeState }; + for (int i = 0; i < arguments.Length; i++) { + frame.Data[i] = arguments[i]; + } + var currentFrame = frame.Enter(); + try { + interpreter.Run(frame); + } finally { + frame.Leave(currentFrame); + } + return frame.StackIndex > interpreter.LocalCount ? frame.Pop() : null; + } + public object Run(params object[] arguments) { if (_compiled is not null || TryGetCompiled()) { try { diff --git a/src/core/Microsoft.Dynamic/Interpreter/ResumeTarget.cs b/src/core/Microsoft.Dynamic/Interpreter/ResumeTarget.cs new file mode 100644 --- /dev/null +++ b/src/core/Microsoft.Dynamic/Interpreter/ResumeTarget.cs @@ -0,0 +1,156 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Microsoft.Scripting.Interpreter { + /// + /// A point in a lambda's instructions where a frame can carry on that did not get there by running the instructions before + /// it: a language that compiles code of its own from the same source, and gives up on it part way (a guard of a type it + /// assumed fails), hands the rest of the call to the interpreter at the point its own code had reached. The language marks + /// such points while the lambda is light-compiled (), runs the lambda in the + /// interpreter with a state of its own (), and an instruction of its own near the + /// lambda's start takes the state and jumps (). + /// + /// + /// The jump enters the regions on the way as running into them would have. A try region with a finally block is entered + /// by its EnterTryFinally instruction, which the jump runs in its place (the continuation the finally block returns + /// through); a region with only handlers needs nothing, its handlers are found by instruction index; a block's variables + /// are initialized by its InitializeLocal instructions, which the jump runs too (the slot of a variable is shared with the + /// variables of blocks that do not overlap it, so it may hold another's value). Code of the language that a region runs + /// when it is entered - state it sets up for its handlers, say - is named by the language (the entry ranges of + /// GotoResume) and is run on the way as well. All of it runs in instruction order, each instruction at its own index, so + /// that an exception the entry code throws meets the handlers and finally blocks of the regions entered so far. A point + /// inside a catch or fault handler or a finally block cannot be jumped to (): the handler would run + /// without the exception it handles, a finally block without the jump or exception it is finishing. Nor can a jump leave + /// a try region with a finally block (). + /// + public sealed class ResumeTarget { + // the EnterTryFinally instructions of the try bodies the point is in, outermost first + private readonly int[] _tryFinallies; + + // the plan of the last jump to here: the same source and entry code each time in practice (one dispatch per lambda) + private Plan _plan; + + internal ResumeTarget(int index, int stackDepth, int continuationDepth, int[] tryFinallies, string refusal) { + Index = index; + StackDepth = stackDepth; + ContinuationDepth = continuationDepth; + _tryFinallies = tryFinallies; + Refusal = refusal; + } + + /// The index of the first instruction after the point. + public int Index { get; } + + /// How many values the evaluation stack holds at the point. + public int StackDepth { get; } + + /// How many finally blocks are pending at the point (try regions with a finally block it is in). + public int ContinuationDepth { get; } + + /// Why a jump cannot enter the point (it is in a catch or fault handler or a finally block), or null if it can. + public string Refusal { get; } + + /// + /// Whether a frame at can jump here: neither point is refused, this one is further on, the + /// evaluation stack is as deep at both, and every try region with a finally block that holds the source holds this + /// point too (a jump can enter such regions, not leave them). + /// + public bool CanJumpFrom(ResumeTarget source) { + if (Refusal is not null || source is null || source.Refusal is not null || source.Index >= Index || source.StackDepth != StackDepth || + source._tryFinallies.Length > _tryFinallies.Length) { + return false; + } + for (int i = 0; i < source._tryFinallies.Length; i++) { + if (source._tryFinallies[i] != _tryFinallies[i]) { + return false; + } + } + return true; + } + + internal Plan GetPlan(Interpreter interpreter, ResumeTarget source, int[] entryCode) { + var plan = Volatile.Read(ref _plan); + if (plan is not null && plan.Interpreter == interpreter && plan.Source == source && SameRanges(plan.EntryCode, entryCode)) { + return plan; + } + plan = new Plan(interpreter, source, this, entryCode); + Volatile.Write(ref _plan, plan); + return plan; + } + + private static bool SameRanges(int[] a, int[] b) { + if (a is null || b is null) { + return a == b; + } + if (a.Length != b.Length) { + return false; + } + for (int i = 0; i < a.Length; i++) { + if (a[i] != b[i]) { + return false; + } + } + return true; + } + + public override string ToString() { + return $"resume target {Index} (stack {StackDepth}, finally {ContinuationDepth}{(Refusal is null ? "" : ", refused: " + Refusal)})"; + } + + /// + /// What a jump from one point to this one does on the way, worked out once from the instructions between them: the + /// instructions to run, in instruction order, with their indexes - the EnterTryFinally of each try region it enters, + /// the variable initializers of the blocks on the way, the language's entry code. Run in order, so that what the entry + /// code of a region throws finds the handlers and finally blocks of the regions entered so far, as it would have. + /// + internal sealed class Plan { + internal readonly Interpreter Interpreter; + internal readonly ResumeTarget Source; + // a copy: the caller's array may be changed after the plan is made + internal readonly int[] EntryCode; + internal readonly Instruction[] Run; + internal readonly int[] Indexes; + + internal Plan(Interpreter interpreter, ResumeTarget source, ResumeTarget target, int[] entryCode) { + if (!target.CanJumpFrom(source)) { + throw new InvalidOperationException($"cannot jump from {source} to {target}"); + } + Interpreter = interpreter; + Source = source; + EntryCode = (int[])entryCode?.Clone(); + + var instructions = interpreter.Instructions.Instructions; + var run = new List(); + var indexes = new List(); + int entered = source._tryFinallies.Length; + int range = 0; + for (int i = source.Index; i < target.Index; i++) { + var instruction = instructions[i]; + // the language's entry code: ranges [start, end) in order + while (entryCode is not null && range + 1 < entryCode.Length && entryCode[range + 1] <= i) { + range += 2; + } + bool entry = entryCode is not null && range + 1 < entryCode.Length && entryCode[range] <= i && i < entryCode[range + 1]; + if (entered < target._tryFinallies.Length && i == target._tryFinallies[entered]) { + // a try region with a finally block that holds the point + entered++; + } else if (!entry && instruction is not InitializeLocalInstruction) { + continue; + } + run.Add(instruction); + indexes.Add(i); + } + if (entered != target._tryFinallies.Length || source.ContinuationDepth + entered - source._tryFinallies.Length != target.ContinuationDepth) { + throw new InvalidOperationException($"cannot jump from {source} to {target}: the try regions on the way do not add up"); + } + Run = run.ToArray(); + Indexes = indexes.ToArray(); + } + } + } +}