54#ifndef BYTECODE_INTERPRETER_H
55#define BYTECODE_INTERPRETER_H
116 return "RuntimeError";
205 void * user_data =
nullptr)
360 std::ostringstream
out;
361 out <<
"BytecodeFunction(f" <<
value.function_id;
362 if (module !=
nullptr and value.function_id < module->functions.size())
363 out <<
", " <<
module->functions.access(value.function_id)->name;
382 std::ostringstream
out;
383 if (module ==
nullptr)
385 out <<
"<null-bytecode-globals>\n";
389 out <<
"BytecodeGlobals\n";
396 for (
size_t i = 0; i <
module->global_slots.size(); ++i)
398 const auto & slot =
module->global_slots.access(i);
399 out <<
" g" << slot.id <<
' ' << slot.name <<
" = ";
400 if (slot.id < globals.
size())
409 namespace Compiler_Bytecode_Interpreter_Detail
417 for (
size_t i = 0; i <
count; ++i)
425 for (
size_t i = 0; i < function.local_slots.size(); ++i)
436 switch (constant.
kind)
452 std::string decoded = constant.
text;
453 if (decoded.size() >= 2
and decoded.front() ==
'"' and decoded.back() ==
'"')
454 decoded = decoded.substr(1, decoded.size() - 2);
464 error =
"unsupported raw constant payload '" + constant.
text +
"'";
468 error =
"unknown constant kind";
500 [[nodiscard]]
const Frame &
515 const size_t executed_instructions,
516 const Frame * frame =
nullptr,
522 if (frame !=
nullptr and frame->function !=
nullptr)
524 error.function_name = frame->function->name;
525 error.pc = frame->pc;
528 error.span = inst->span;
530 executed_instructions);
536 const size_t executed_instructions,
543 return make_error(
"BCV013",
"division by zero", executed_instructions, &frame, &inst);
545 return make_error(
"BCV014",
"modulo by zero", executed_instructions, &frame, &inst);
550 return make_error(
"BCV023",
"integer overflow", executed_instructions, &frame, &inst);
555 const size_t executed_instructions = 0)
const
558 ?
"invalid bytecode module"
577 const bool returns_to_caller,
580 const size_t executed_instructions,
583 const auto expected_arity
585 if (arguments.
size() != expected_arity)
588 "function '" + function.
name +
"' expects "
589 + std::to_string(expected_arity) +
" arguments but received "
590 + std::to_string(arguments.
size()),
591 executed_instructions);
607 size_t arg_index = 0;
608 for (
size_t i = 0; i < function.
local_slots.size(); ++i)
610 const auto & slot = function.
local_slots.access(i);
613 if (slot.id >= frame.
locals.size())
616 "parameter slot id " + std::to_string(slot.id)
617 +
" is out of bounds in function '" + function.
name +
"'",
618 executed_instructions);
621 frame.
locals.access(slot.id) = arguments.
access(arg_index++);
633 const size_t executed_instructions,
640 "invalid register r" + std::to_string(
id),
641 executed_instructions,
648 if (
value.is_invalid())
651 "read from uninitialized register r" + std::to_string(
id),
652 executed_instructions,
666 const size_t executed_instructions,
672 "invalid register r" + std::to_string(
id),
673 executed_instructions,
687 const size_t executed_instructions,
691 if (
id >= frame.
locals.size())
694 "invalid local slot s" + std::to_string(
id),
695 executed_instructions,
702 if (
value.is_invalid())
705 "read from uninitialized local slot s" + std::to_string(
id),
706 executed_instructions,
720 const size_t executed_instructions,
723 if (
id >= frame.
locals.size())
726 "invalid local slot s" + std::to_string(
id),
727 executed_instructions,
741 const size_t executed_instructions,
748 "invalid global slot g" + std::to_string(
id),
749 executed_instructions,
756 if (
value.is_invalid())
759 "read from uninitialized global slot g" + std::to_string(
id),
760 executed_instructions,
774 const size_t executed_instructions,
780 "invalid global slot g" + std::to_string(
id),
781 executed_instructions,
795 const size_t executed_instructions,
796 const std::string & context,
800 if (not
value.is_runtime_value()
804 context +
" expects Integer but received "
806 executed_instructions,
812 result =
value.runtime_value.integer_value;
820 const size_t executed_instructions,
821 const std::string & context,
825 if (not
value.is_runtime_value()
829 context +
" expects Bool but received "
831 executed_instructions,
837 result =
value.runtime_value.bool_value;
844 const size_t executed_instructions,
852 "call instruction has no callee operand",
853 executed_instructions,
862 executed_instructions,
874 executed_instructions,
878 arguments.
append(argument);
887 const size_t executed_instructions,
892 if (not finished.returns_to_caller)
902 finished.caller_destination,
904 caller.function->code.access(caller.pc),
905 executed_instructions,
909 caller.pc = finished.caller_resume_pc;
918 const size_t executed_instructions,
922 for (
size_t i = 0; i < arguments.
size(); ++i)
924 if (not arguments.
access(i).is_runtime_value())
927 "host function arguments cannot contain bytecode function references",
928 executed_instructions,
933 runtime_arguments.
append(arguments.
access(i).runtime_value);
946 ?
"host function call failed"
948 executed_instructions,
960 executed_instructions,
971 size_t executed_instructions = 0;
975 if (max_steps != 0
and executed_instructions >= max_steps)
977 "bytecode step limit exceeded",
978 executed_instructions,
982 if (frame.pc >= frame.function->code.size())
984 "program counter " + std::to_string(frame.pc)
985 +
" is out of bounds in function '" + frame.function->name +
"'",
986 executed_instructions,
989 const auto & inst = frame.function->code.access(frame.pc);
990 ++executed_instructions;
996 if (inst.constant_id >= frame.function->constants.size())
998 "invalid constant id k"
999 + std::to_string(inst.constant_id),
1000 executed_instructions,
1005 std::string conversion_error;
1007 frame.function->constants.access(inst.constant_id),
1012 executed_instructions,
1021 executed_instructions,
1036 executed_instructions,
1044 executed_instructions,
1054 if (inst.operands.is_empty())
1056 "StoreLocal requires one source operand",
1057 executed_instructions,
1064 inst.operands.access(0),
1066 executed_instructions,
1074 executed_instructions,
1087 inst.global_slot_id,
1089 executed_instructions,
1097 executed_instructions,
1107 if (inst.operands.is_empty())
1109 "StoreGlobal requires one source operand",
1110 executed_instructions,
1117 inst.operands.access(0),
1119 executed_instructions,
1124 inst.global_slot_id,
1127 executed_instructions,
1142 executed_instructions,
1152 if (inst.operands.is_empty())
1154 "Unary requires one source operand",
1155 executed_instructions,
1162 inst.operands.access(0),
1164 executed_instructions,
1174 long long integer_value = 0;
1178 executed_instructions,
1186 executed_instructions,
1195 bool bool_value =
false;
1199 executed_instructions,
1210 long long integer_value = 0;
1214 executed_instructions,
1225 "unsupported unary operator '"
1228 executed_instructions,
1237 executed_instructions,
1247 if (inst.operands.size() < 2)
1249 "Binary requires two source operands",
1250 executed_instructions,
1258 inst.operands.access(0),
1260 executed_instructions,
1265 inst.operands.access(1),
1267 executed_instructions,
1289 executed_instructions,
1297 executed_instructions,
1306 executed_instructions,
1323 executed_instructions,
1331 executed_instructions,
1337 bool comparison =
false;
1341 comparison = lhs < rhs;
1344 comparison = lhs <= rhs;
1347 comparison = lhs > rhs;
1350 comparison = lhs >= rhs;
1367 executed_instructions,
1375 executed_instructions,
1399 "unsupported binary operator '"
1402 executed_instructions,
1411 executed_instructions,
1426 executed_instructions,
1436 "invalid function id f"
1438 executed_instructions,
1447 executed_instructions,
1455 "callee is not callable: "
1457 executed_instructions,
1467 executed_instructions,
1475 "HIR function values are not callable from bytecode VM",
1476 executed_instructions,
1481 "callee is not callable: "
1483 executed_instructions,
1489 frame.pc = inst.target_pc;
1494 if (inst.operands.is_empty())
1496 "Branch requires one condition operand",
1497 executed_instructions,
1504 inst.operands.access(0),
1506 executed_instructions,
1511 bool branch =
false;
1515 executed_instructions,
1521 frame.pc = branch ? inst.target_pc : inst.false_target_pc;
1529 if (not inst.operands.is_empty()
1531 inst.operands.access(0),
1533 executed_instructions,
1541 executed_instructions,
1554 executed_instructions,
1563 "executed trap/unreachable instruction",
1564 executed_instructions,
1576 const size_t max_steps)
1637 if (slot_id >=
globals.size())
1639 return &
globals.access(slot_id);
1643 [[nodiscard]]
size_t
1659 if (slot_id >=
globals.size())
1674 return make_error(
"BCV001",
"null bytecode module", 0);
1677 return make_error(
"BCV002",
"bytecode module has no top-level body", 0);
1693 const size_t max_steps = 0)
1696 return make_error(
"BCV001",
"null bytecode module", 0);
1700 "invalid function id f" + std::to_string(function_id),
1709 [[nodiscard]] std::string
Reusable bytecode format and lowering from Compiler_IR_Model.H.
Reusable runtime and structured evaluator for HIR-based interpreters.
size_t size_t int32_t value
size_t size_t int32_t * out
Small portable VM for executing one Compiler_Bytecode_Module.
bool execute_host_call(Frame &frame, const Compiler_Bytecode_Instruction &inst, const Compiler_Bytecode_Value &callee, const DynArray< Compiler_Bytecode_Value > &arguments, const size_t executed_instructions, Compiler_Bytecode_Execution_Result &error)
Compiler_Bytecode_Execution_Result make_integer_error(const Compiler_Integer_Status status, const size_t executed_instructions, const Frame &frame, const Compiler_Bytecode_Instruction &inst) const
Runtime error for an integer operation that has no result.
bool require_bool(const Compiler_Bytecode_Value &value, const Frame &frame, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, const std::string &context, bool &result, Compiler_Bytecode_Execution_Result &error) const
std::string dump_globals() const
Returns a deterministic dump of the current global state.
Compiler_Bytecode_Execution_Result make_error(const std::string &code, const std::string &message, const size_t executed_instructions, const Frame *frame=nullptr, const Compiler_Bytecode_Instruction *inst=nullptr) const
bool require_integer(const Compiler_Bytecode_Value &value, const Frame &frame, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, const std::string &context, long long &result, Compiler_Bytecode_Execution_Result &error) const
bool read_global(const Frame &frame, const Compiler_IR_Global_Slot_Id id, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, Compiler_Bytecode_Value &value, Compiler_Bytecode_Execution_Result &error) const
bool read_callee_and_arguments(const Frame &frame, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, Compiler_Bytecode_Value &callee, DynArray< Compiler_Bytecode_Value > &arguments, Compiler_Bytecode_Execution_Result &error) const
DynArray< Frame > call_stack
bool write_local(Frame &frame, const Compiler_IR_Local_Slot_Id id, const Compiler_Bytecode_Value &value, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, Compiler_Bytecode_Execution_Result &error) const
bool read_local(const Frame &frame, const Compiler_IR_Local_Slot_Id id, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, Compiler_Bytecode_Value &value, Compiler_Bytecode_Execution_Result &error) const
const Compiler_Bytecode_Module & module() const noexcept
Returns the immutable bytecode module executed by this VM.
Compiler_Bytecode_Execution_Result execute_loop(const size_t max_steps)
bool module_is_valid(Compiler_Bytecode_Execution_Result &error) const
Compiler_Bytecode_Execution_Result call_function(const Compiler_Bytecode_Function_Id function_id, const DynArray< Compiler_Bytecode_Value > &arguments, const size_t max_steps=0)
Executes one bytecode function directly.
const Compiler_Bytecode_Module * bytecode_module
const DynArray< Compiler_Bytecode_Value > & global_values() const noexcept
Returns the current global slot values.
bool set_global(const Compiler_IR_Global_Slot_Id slot_id, const Compiler_Bytecode_Value &value)
Writes one global slot before or after execution.
size_t call_stack_depth() const noexcept
Returns the current dynamic call-stack depth.
void reset()
Resets globals to Invalid and clears any pending call stack.
Compiler_Bytecode_Execution_Result execute_entry(const Compiler_Bytecode_Function &function, const DynArray< Compiler_Bytecode_Value > &arguments, const size_t max_steps)
Compiler_Bytecode_Execution_Result run_top_level(const size_t max_steps=0)
Executes the module top-level body.
bool read_register(const Frame &frame, const Compiler_Bytecode_Register_Id id, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, Compiler_Bytecode_Value &value, Compiler_Bytecode_Execution_Result &error) const
bool write_global(Frame &frame, const Compiler_IR_Global_Slot_Id id, const Compiler_Bytecode_Value &value, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, Compiler_Bytecode_Execution_Result &error)
const Compiler_Bytecode_Value * global_slot(const Compiler_IR_Global_Slot_Id slot_id) const noexcept
Returns one global slot value if the slot id is valid.
Compiler_Bytecode_VM(const Compiler_Bytecode_Module &module)
Builds a VM over one immutable bytecode module.
const Frame & current_frame() const
Compiler_Bytecode_Execution_Result make_validation_error(const Compiler_Bytecode_Validation_Report &report, const size_t executed_instructions=0) const
bool write_register(Frame &frame, const Compiler_Bytecode_Register_Id id, const Compiler_Bytecode_Value &value, const Compiler_Bytecode_Instruction &inst, const size_t executed_instructions, Compiler_Bytecode_Execution_Result &error) const
DynArray< Compiler_Bytecode_Value > globals
bool push_frame(const Compiler_Bytecode_Function &function, const DynArray< Compiler_Bytecode_Value > &arguments, const bool returns_to_caller, const Compiler_Bytecode_PC caller_resume_pc, const Compiler_Bytecode_Register_Id caller_destination, const size_t executed_instructions, Compiler_Bytecode_Execution_Result &error)
bool complete_current_frame(const Compiler_Bytecode_Value &value, const Compiler_Bytecode_Completion_Kind kind, const size_t executed_instructions, Compiler_Bytecode_Execution_Result &completed, Compiler_Bytecode_Execution_Result &error)
void clear() noexcept
Empties the container.
size_t size() const noexcept
Return the current dimension of array.
T & access(const size_t i) noexcept
Fast access without checking allocation and bound_min_clock checking.
T & append()
Allocate a new entry to the end of array.
bool is_empty() const noexcept
Return true if the array is empty.
const char * token_name(const Compiler_Operator_Kind kind) noexcept
size_t count_parameters(const Compiler_Bytecode_Function &function) noexcept
bool constant_to_value(const Compiler_Bytecode_Constant &constant, Compiler_Bytecode_Value &value, std::string &error)
void reset_values(DynArray< Compiler_Bytecode_Value > &values, const size_t count, const Compiler_Bytecode_Value &fill=Compiler_Bytecode_Value::make_invalid())
Main namespace for Aleph-w library functions.
Compiler_Bytecode_Completion_Kind
Final status produced by one VM execution request.
@ Halted
Execution reached Halt and therefore produced Unit.
@ Runtime_Error
Execution failed with a structured runtime error.
@ Returned
Execution finished with an explicit Return.
std::string compiler_dump_bytecode_globals(const Compiler_Bytecode_Module *module, const DynArray< Compiler_Bytecode_Value > &globals)
Dumps the current global state associated with one bytecode module.
constexpr size_t compiler_bytecode_invalid_id() noexcept
Returns the sentinel invalid bytecode id.
@ Load_Local
dst <- locals[slot]
@ Halt
Canonical exit instruction.
@ Load_Function
dst <- function_ref[id]
@ Store_Global
globals[slot] <- src
@ Binary
dst <- op(lhs, rhs)
@ Load_Global
dst <- globals[slot]
@ Trap
Unreachable code path marker.
@ Return
Return one register value.
@ Load_Constant
dst <- constant_pool[id]
@ Call
dst <- callee(args...)
@ Store_Local
locals[slot] <- src
@ Branch
pc <- condition ? true_target : false_target
bool completed() const noexcept
Return true if all underlying iterators are finished.
@ String
String literal payload.
@ Character
Character literal payload.
@ Integer
Signed integer literal.
@ Raw_Text
Fallback textual payload when the literal cannot be classified better.
Compiler_Bytecode_Value_Kind
Runtime categories that can live inside bytecode registers/slots.
@ Invalid
Uninitialized register/slot or explicit invalid placeholder.
@ Value
Regular runtime payload stored as Interpreter_Value.
@ Function_Ref
Reference to one bytecode function in the current module.
void message(const char *file, int line, const char *format,...)
Print an informational message with file and line info.
bool interpreter_values_equal(const Interpreter_Value &lhs, const Interpreter_Value &rhs)
Returns whether two runtime values compare equal.
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Compiler_Integer_Result compiler_integer_negate(const long long operand) noexcept
Negates one integer of the language.
Compiler_Integer_Status
Outcome of one integer operation of the language.
@ Division_By_Zero
/ with a zero divisor.
@ Modulo_By_Zero
% with a zero divisor.
@ Ok
The result is in value.
bool compiler_bytecode_values_equal(const Compiler_Bytecode_Value &lhs, const Compiler_Bytecode_Value &rhs)
Returns whether two bytecode values compare equal.
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
size_t Compiler_Bytecode_Register_Id
and
Check uniqueness with explicit hash + equality functors.
Compiler_Bytecode_Validation_Report validate_bytecode_module(const Compiler_Bytecode_Module &module)
Validates all bytecode functions in one module.
Compiler_Integer_Result compiler_integer_binary(const Compiler_Operator_Kind op, const long long lhs, const long long rhs) noexcept
Applies one integer operator of the language to two values.
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
size_t Compiler_IR_Global_Slot_Id
const char * compiler_bytecode_value_kind_name(const Compiler_Bytecode_Value_Kind kind) noexcept
Stable debug name for one bytecode runtime value kind.
size_t Compiler_Bytecode_PC
size_t Compiler_Bytecode_Function_Id
bool(*)(void *user_data, const DynArray< Interpreter_Value > &arguments, Interpreter_Value &result, Interpreter_Runtime_Error &error) Interpreter_Host_Function
Host callback signature used by runtime built-ins or embeddings.
std::string interpreter_value_to_string(const Interpreter_Value &value)
Formats one runtime value deterministically for dumps and tests.
std::string compiler_bytecode_value_to_string(const Compiler_Bytecode_Value &value, const Compiler_Bytecode_Module *module=nullptr)
Renders one bytecode value deterministically.
size_t Compiler_IR_Local_Slot_Id
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
const char * compiler_bytecode_completion_kind_name(const Compiler_Bytecode_Completion_Kind kind) noexcept
Stable debug name for one execution completion kind.
One constant stored in a function-level constant pool.
bool bool_value
Boolean payload when kind == Boolean.
std::string text
Canonical textual payload for dumps/debugging.
char char_value
Character payload when kind == Character.
Compiler_Bytecode_Constant_Kind kind
Logical constant category.
long long integer_value
Integer payload when kind == Integer.
Result of one bytecode execution request.
static Compiler_Bytecode_Execution_Result runtime_error(const Compiler_Bytecode_Runtime_Error &error, const size_t executed_instructions)
Builds a failed runtime result.
static Compiler_Bytecode_Execution_Result returned(const Compiler_Bytecode_Value &value, const size_t executed_instructions)
Builds a successful return result.
Compiler_Bytecode_Runtime_Error error
Structured failure when kind == Runtime_Error.
size_t executed_instructions
Number of bytecode instructions observed by the VM.
bool ok() const noexcept
Returns whether execution completed without runtime errors.
Compiler_Bytecode_Completion_Kind kind
Final completion category.
static Compiler_Bytecode_Execution_Result halted(const Compiler_Bytecode_Value &value, const size_t executed_instructions)
Builds a successful halt result.
Compiler_Bytecode_Value value
Produced return value or final Unit.
Bytecode for one lowered function or top-level body.
std::string name
Debug/source name.
Compiler_Bytecode_PC entry_pc
Entry PC used to start execution.
size_t register_count
Number of virtual registers required by the function.
DynArray< Compiler_IR_Slot > local_slots
Local/parameter slot metadata preserved for the VM.
One lowered bytecode instruction.
Compiler_Bytecode_Register_Id destination
Destination register, or 0 for void instructions.
DynArray< Compiler_Bytecode_Register_Id > operands
Source registers in deterministic order.
Bytecode module sharing global slot layout with the source IR module.
DynArray< Compiler_IR_Slot > global_slots
Global slots preserved from the source IR module.
Compiler_Bytecode_Function * top_level
Optional lowered top-level body.
DynArray< Compiler_Bytecode_Function * > functions
Lowered non-top-level functions.
Structured runtime error produced by the bytecode VM.
bool has_error() const noexcept
Returns whether this error object is populated.
std::string message
Human-readable runtime message.
Compiler_Bytecode_PC pc
Program counter active at the failure point, when known.
Source_Span span
Source span associated with the current instruction, when known.
std::string function_name
Function active at the failure point, when known.
std::string code
Stable runtime code such as BCV013.
DynArray< Compiler_Bytecode_Value > locals
const Compiler_Bytecode_Function * function
Compiler_Bytecode_Register_Id caller_destination
Compiler_Bytecode_PC caller_resume_pc
DynArray< Compiler_Bytecode_Value > registers
Structural validation report for one bytecode function or module.
DynArray< std::string > errors
Hard validation failures.
One value stored in bytecode registers, locals, or globals.
static Compiler_Bytecode_Value make_value(const Interpreter_Value &value)
Wraps one regular runtime value.
static Compiler_Bytecode_Value make_character(const char ch)
Builds a character runtime value.
Compiler_Bytecode_Value_Kind kind
Active payload category.
Compiler_Bytecode_Function_Id function_id
Referenced bytecode function when kind == Function_Ref.
static Compiler_Bytecode_Value make_host_function(std::string name, const Interpreter_Host_Function callback, void *user_data=nullptr)
Builds a callable value backed by host code.
bool is_invalid() const noexcept
Returns whether this value is invalid.
bool is_function_ref() const noexcept
Returns whether this value is a bytecode function reference.
static Compiler_Bytecode_Value make_function_ref(const Compiler_Bytecode_Function_Id id)
Builds a reference to one bytecode function in the current module.
static Compiler_Bytecode_Value make_unit()
Builds the Unit singleton.
static Compiler_Bytecode_Value make_invalid()
Builds an invalid placeholder value.
Interpreter_Value runtime_value
Wrapped scalar/tuple/host-function value.
static Compiler_Bytecode_Value make_bool(const bool value)
Builds a boolean runtime value.
static Compiler_Bytecode_Value make_integer(const long long value)
Builds an integer runtime value.
static Compiler_Bytecode_Value make_value(Interpreter_Value &&value)
Wraps one regular runtime value by move.
bool is_runtime_value() const noexcept
Returns whether this value wraps an Interpreter_Value.
static Compiler_Bytecode_Value make_string(std::string text)
Builds a string runtime value.
Structured runtime error.
Source_Span span
Source region associated with the failure.
std::string code
Stable runtime code such as RUN004.
std::string message
Human-readable runtime message.
bool has_error() const noexcept
Returns whether this error object is populated.
void * host_user_data
Embedding-specific payload for host functions.
Interpreter_Host_Function host_function
Payload for host function values.
static Interpreter_Value make_bool(const bool b)
Builds a boolean runtime value.
static Interpreter_Value make_character(const char ch)
Builds a character runtime value.
static Interpreter_Value make_invalid()
Builds an invalid value placeholder.
Interpreter_Value_Kind kind
Active value kind.
static Interpreter_Value make_host_function(std::string name, const Interpreter_Host_Function callback, void *user_data=nullptr)
Builds a callable value backed by host code.
static Interpreter_Value make_integer(const long long i)
Builds an integer runtime value.
static Interpreter_Value make_unit()
Builds the Unit value.
static Interpreter_Value make_string(std::string text)
Builds a string runtime value.
Half-open byte range inside a source file.