Skip to content

Commit

Permalink
feat: make RETURN opcode throw ReturnHook exception
Browse files Browse the repository at this point in the history
  • Loading branch information
R-unic committed Jan 13, 2025
1 parent 9ee3129 commit 82c3d52
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
4 changes: 2 additions & 2 deletions Heir/Runtime/HookedExceptions.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
namespace Heir.Runtime.HookedExceptions;

public class Return<TValue>(TValue value) : HookedException
public class ReturnHook(object? value) : HookedException
{
public TValue Value { get; } = value;
public object? Value { get; } = value;
}

public abstract class HookedException() : Exception("BUG: Unhooked hooked exception");
23 changes: 12 additions & 11 deletions Heir/VirtualMachine.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using Heir.AST;
using Heir.AST.Abstract;
using Heir.AST.Abstract;
using Heir.CodeGeneration;
using Heir.Runtime;
using Heir.Runtime.HookedExceptions;

namespace Heir;

Expand Down Expand Up @@ -62,8 +62,12 @@ public VirtualMachine(Bytecode bytecode, Scope? scope = null)
case OpCode.NOOP:
Advance();
break;

case OpCode.RETURN:
return _stack.Pop();
{
var frame = _stack.Pop();
throw new ReturnHook(frame.Value);
}

case OpCode.BEGINSCOPE:
_enclosingScope = Scope;
Expand Down Expand Up @@ -410,25 +414,25 @@ public VirtualMachine(Bytecode bytecode, Scope? scope = null)
case OpCode.JZ:
{
var frame = _stack.Pop();
if (frame.Value is int n && n == 0)
if (frame.Value is 0)
{
if (instruction.Operand is int index)
_pointer = index;
else
NonIntegerOperand(instruction);
}
else
{
Advance();
}

break;
}

default:
{
Diagnostics.Error(DiagnosticCode.H001D, $"Unhandled opcode \"{instruction.OpCode}\"",
Diagnostics.Error(DiagnosticCode.H001D,
$"Unhandled opcode \"{instruction.OpCode}\"",
instruction.Root.GetFirstToken());

return new StackFrame(instruction.Root, new ExitMarker());
}
}
Expand All @@ -447,8 +451,5 @@ private StackFrame CreateStackFrameFromInstruction(int offset = 0)
return new StackFrame(instruction.Root, instruction.Operand);
}

private void Advance(int amount = 1)
{
_pointer += amount;
}
private void Advance(int amount = 1) => _pointer += amount;
}

0 comments on commit 82c3d52

Please sign in to comment.