Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Bytecode_Interpreter.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
54#ifndef BYTECODE_INTERPRETER_H
55#define BYTECODE_INTERPRETER_H
56
57#include <sstream>
58#include <string>
59#include <utility>
60
61#include <Bytecode.H>
62#include <Interpreter_Runtime.H>
63
64namespace Aleph
65{
74 {
75 Invalid,
76 Value,
78 };
79
87
89 inline const char *
91 {
92 switch (kind)
93 {
95 return "Invalid";
97 return "Value";
99 return "FunctionRef";
100 }
101
102 return "Unknown";
103 }
104
106 inline const char *
108 {
109 switch (kind)
110 {
112 return "Returned";
114 return "Halted";
116 return "RuntimeError";
117 }
118
119 return "Unknown";
120 }
121
130 {
134
138 {
139 return {};
140 }
141
145 {
148 result.runtime_value = value;
149 return result;
150 }
151
155 {
158 result.runtime_value = std::move(value);
159 return result;
160 }
161
168
171 make_bool(const bool value)
172 {
174 }
175
178 make_integer(const long long value)
179 {
181 }
182
185 make_string(std::string text)
186 {
187 return make_value(Interpreter_Value::make_string(std::move(text)));
188 }
189
192 make_character(const char ch)
193 {
195 }
196
203 make_host_function(std::string name,
204 const Interpreter_Host_Function callback,
205 void * user_data = nullptr)
206 {
208 callback,
209 user_data));
210 }
211
215 {
218 result.function_id = id;
219 return result;
220 }
221
223 [[nodiscard]] bool
224 is_invalid() const noexcept
225 {
227 }
228
230 [[nodiscard]] bool
231 is_runtime_value() const noexcept
232 {
234 }
235
237 [[nodiscard]] bool
238 is_function_ref() const noexcept
239 {
241 }
242 };
243
246 {
247 std::string code;
248 std::string message;
249 std::string function_name;
252
254 [[nodiscard]] bool
255 has_error() const noexcept
256 {
257 return not code.empty() or not message.empty();
258 }
259 };
260
263 {
268
270 [[nodiscard]] bool
271 ok() const noexcept
272 {
274 }
275
287
299
312 };
313
319 inline bool
321 const Compiler_Bytecode_Value & rhs)
322 {
323 if (lhs.kind != rhs.kind)
324 return false;
325
326 switch (lhs.kind)
327 {
329 return true;
333 return lhs.function_id == rhs.function_id;
334 }
335
336 return false;
337 }
338
346 inline std::string
348 const Compiler_Bytecode_Module * module = nullptr)
349 {
350 switch (value.kind)
351 {
353 return "Invalid";
354
356 return interpreter_value_to_string(value.runtime_value);
357
359 {
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;
364 out << ')';
365 return out.str();
366 }
367 }
368
369 return "Unknown";
370 }
371
378 inline std::string
380 const DynArray<Compiler_Bytecode_Value> & globals)
381 {
382 std::ostringstream out;
383 if (module == nullptr)
384 {
385 out << "<null-bytecode-globals>\n";
386 return out.str();
387 }
388
389 out << "BytecodeGlobals\n";
390 if (module->global_slots.is_empty())
391 {
392 out << " <none>\n";
393 return out.str();
394 }
395
396 for (size_t i = 0; i < module->global_slots.size(); ++i)
397 {
398 const auto & slot = module->global_slots.access(i);
399 out << " g" << slot.id << ' ' << slot.name << " = ";
400 if (slot.id < globals.size())
401 out << compiler_bytecode_value_to_string(globals.access(slot.id), module);
402 else
403 out << "<missing>";
404 out << '\n';
405 }
406 return out.str();
407 }
408
409 namespace Compiler_Bytecode_Interpreter_Detail
410 {
411 inline void
413 const size_t count,
415 {
416 values.clear();
417 for (size_t i = 0; i < count; ++i)
418 values.append(fill);
419 }
420
421 inline size_t
423 {
424 size_t count = 0;
425 for (size_t i = 0; i < function.local_slots.size(); ++i)
426 if (function.local_slots.access(i).kind == Compiler_IR_Slot_Kind::Parameter)
427 ++count;
428 return count;
429 }
430
431 inline bool
434 std::string & error)
435 {
436 switch (constant.kind)
437 {
440 return true;
441
444 return true;
445
448 return true;
449
451 {
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);
455 value = Compiler_Bytecode_Value::make_string(std::move(decoded));
456 return true;
457 }
458
461 return true;
462
464 error = "unsupported raw constant payload '" + constant.text + "'";
465 return false;
466 }
467
468 error = "unknown constant kind";
469 return false;
470 }
471 }
472
484 {
495
499
500 [[nodiscard]] const Frame &
502 {
503 return call_stack.get_last();
504 }
505
506 Frame &
508 {
509 return call_stack.get_last();
510 }
511
513 make_error(const std::string & code,
514 const std::string & message,
515 const size_t executed_instructions,
516 const Frame * frame = nullptr,
517 const Compiler_Bytecode_Instruction * inst = nullptr) const
518 {
520 error.code = code;
521 error.message = message;
522 if (frame != nullptr and frame->function != nullptr)
523 {
524 error.function_name = frame->function->name;
525 error.pc = frame->pc;
526 }
527 if (inst != nullptr)
528 error.span = inst->span;
530 executed_instructions);
531 }
532
536 const size_t executed_instructions,
537 const Frame & frame,
538 const Compiler_Bytecode_Instruction & inst) const
539 {
540 switch (status)
541 {
543 return make_error("BCV013", "division by zero", executed_instructions, &frame, &inst);
545 return make_error("BCV014", "modulo by zero", executed_instructions, &frame, &inst);
546 default:
547 break;
548 }
549
550 return make_error("BCV023", "integer overflow", executed_instructions, &frame, &inst);
551 }
552
555 const size_t executed_instructions = 0) const
556 {
557 const std::string message = report.errors.is_empty()
558 ? "invalid bytecode module"
559 : report.errors.access(0);
560 return make_error("BCV001", message, executed_instructions);
561 }
562
563 [[nodiscard]] bool
565 {
566 const auto report = validate_bytecode_module(*bytecode_module);
567 if (report.valid)
568 return true;
569
571 return false;
572 }
573
574 [[nodiscard]] bool
576 const DynArray<Compiler_Bytecode_Value> & arguments,
577 const bool returns_to_caller,
578 const Compiler_Bytecode_PC caller_resume_pc,
579 const Compiler_Bytecode_Register_Id caller_destination,
580 const size_t executed_instructions,
582 {
583 const auto expected_arity
585 if (arguments.size() != expected_arity)
586 {
587 error = make_error("BCV004",
588 "function '" + function.name + "' expects "
589 + std::to_string(expected_arity) + " arguments but received "
590 + std::to_string(arguments.size()),
591 executed_instructions);
592 return false;
593 }
594
595 Frame frame;
596 frame.function = &function;
597 frame.pc = function.entry_pc;
598 frame.caller_resume_pc = caller_resume_pc;
599 frame.caller_destination = caller_destination;
600 frame.returns_to_caller = returns_to_caller;
601
603 function.register_count);
605 function.local_slots.size());
606
607 size_t arg_index = 0;
608 for (size_t i = 0; i < function.local_slots.size(); ++i)
609 {
610 const auto & slot = function.local_slots.access(i);
611 if (slot.kind == Compiler_IR_Slot_Kind::Parameter)
612 {
613 if (slot.id >= frame.locals.size())
614 {
615 error = make_error("BCV006",
616 "parameter slot id " + std::to_string(slot.id)
617 + " is out of bounds in function '" + function.name + "'",
618 executed_instructions);
619 return false;
620 }
621 frame.locals.access(slot.id) = arguments.access(arg_index++);
622 }
623 }
624
625 call_stack.append(std::move(frame));
626 return true;
627 }
628
629 [[nodiscard]] bool
630 read_register(const Frame & frame,
633 const size_t executed_instructions,
636 {
637 if (id >= frame.registers.size())
638 {
639 error = make_error("BCV006",
640 "invalid register r" + std::to_string(id),
641 executed_instructions,
642 &frame,
643 &inst);
644 return false;
645 }
646
647 value = frame.registers.access(id);
648 if (value.is_invalid())
649 {
650 error = make_error("BCV007",
651 "read from uninitialized register r" + std::to_string(id),
652 executed_instructions,
653 &frame,
654 &inst);
655 return false;
656 }
657
658 return true;
659 }
660
661 [[nodiscard]] bool
666 const size_t executed_instructions,
668 {
669 if (id >= frame.registers.size())
670 {
671 error = make_error("BCV006",
672 "invalid register r" + std::to_string(id),
673 executed_instructions,
674 &frame,
675 &inst);
676 return false;
677 }
678
679 frame.registers.access(id) = value;
680 return true;
681 }
682
683 [[nodiscard]] bool
684 read_local(const Frame & frame,
687 const size_t executed_instructions,
690 {
691 if (id >= frame.locals.size())
692 {
693 error = make_error("BCV006",
694 "invalid local slot s" + std::to_string(id),
695 executed_instructions,
696 &frame,
697 &inst);
698 return false;
699 }
700
701 value = frame.locals.access(id);
702 if (value.is_invalid())
703 {
704 error = make_error("BCV008",
705 "read from uninitialized local slot s" + std::to_string(id),
706 executed_instructions,
707 &frame,
708 &inst);
709 return false;
710 }
711
712 return true;
713 }
714
715 [[nodiscard]] bool
720 const size_t executed_instructions,
722 {
723 if (id >= frame.locals.size())
724 {
725 error = make_error("BCV006",
726 "invalid local slot s" + std::to_string(id),
727 executed_instructions,
728 &frame,
729 &inst);
730 return false;
731 }
732
733 frame.locals.access(id) = value;
734 return true;
735 }
736
737 [[nodiscard]] bool
738 read_global(const Frame & frame,
741 const size_t executed_instructions,
744 {
745 if (id >= globals.size())
746 {
747 error = make_error("BCV006",
748 "invalid global slot g" + std::to_string(id),
749 executed_instructions,
750 &frame,
751 &inst);
752 return false;
753 }
754
755 value = globals.access(id);
756 if (value.is_invalid())
757 {
758 error = make_error("BCV009",
759 "read from uninitialized global slot g" + std::to_string(id),
760 executed_instructions,
761 &frame,
762 &inst);
763 return false;
764 }
765
766 return true;
767 }
768
769 [[nodiscard]] bool
774 const size_t executed_instructions,
776 {
777 if (id >= globals.size())
778 {
779 error = make_error("BCV006",
780 "invalid global slot g" + std::to_string(id),
781 executed_instructions,
782 &frame,
783 &inst);
784 return false;
785 }
786
787 globals.access(id) = value;
788 return true;
789 }
790
791 [[nodiscard]] bool
793 const Frame & frame,
795 const size_t executed_instructions,
796 const std::string & context,
797 long long & result,
799 {
800 if (not value.is_runtime_value()
801 or value.runtime_value.kind != Interpreter_Value_Kind::Integer)
802 {
803 error = make_error("BCV011",
804 context + " expects Integer but received "
806 executed_instructions,
807 &frame,
808 &inst);
809 return false;
810 }
811
812 result = value.runtime_value.integer_value;
813 return true;
814 }
815
816 [[nodiscard]] bool
818 const Frame & frame,
820 const size_t executed_instructions,
821 const std::string & context,
822 bool & result,
824 {
825 if (not value.is_runtime_value()
826 or value.runtime_value.kind != Interpreter_Value_Kind::Bool)
827 {
828 error = make_error("BCV012",
829 context + " expects Bool but received "
831 executed_instructions,
832 &frame,
833 &inst);
834 return false;
835 }
836
837 result = value.runtime_value.bool_value;
838 return true;
839 }
840
841 [[nodiscard]] bool
844 const size_t executed_instructions,
848 {
849 if (inst.operands.is_empty())
850 {
851 error = make_error("BCV017",
852 "call instruction has no callee operand",
853 executed_instructions,
854 &frame,
855 &inst);
856 return false;
857 }
858
859 if (not read_register(frame,
860 inst.operands.access(0),
861 inst,
862 executed_instructions,
863 callee,
864 error))
865 return false;
866
867 arguments.clear();
868 for (size_t i = 1; i < inst.operands.size(); ++i)
869 {
871 if (not read_register(frame,
872 inst.operands.access(i),
873 inst,
874 executed_instructions,
875 argument,
876 error))
877 return false;
878 arguments.append(argument);
879 }
880
881 return true;
882 }
883
884 [[nodiscard]] bool
887 const size_t executed_instructions,
890 {
891 const auto finished = call_stack.pop();
892 if (not finished.returns_to_caller)
893 {
896 : Compiler_Bytecode_Execution_Result::halted(value, executed_instructions);
897 return true;
898 }
899
900 auto & caller = current_frame();
901 if (not write_register(caller,
902 finished.caller_destination,
903 value,
904 caller.function->code.access(caller.pc),
905 executed_instructions,
906 error))
907 return true;
908
909 caller.pc = finished.caller_resume_pc;
910 return false;
911 }
912
913 [[nodiscard]] bool
916 const Compiler_Bytecode_Value & callee,
917 const DynArray<Compiler_Bytecode_Value> & arguments,
918 const size_t executed_instructions,
920 {
921 DynArray<Interpreter_Value> runtime_arguments;
922 for (size_t i = 0; i < arguments.size(); ++i)
923 {
924 if (not arguments.access(i).is_runtime_value())
925 {
926 error = make_error("BCV019",
927 "host function arguments cannot contain bytecode function references",
928 executed_instructions,
929 &frame,
930 &inst);
931 return false;
932 }
933 runtime_arguments.append(arguments.access(i).runtime_value);
934 }
935
937 Interpreter_Runtime_Error host_error;
938 const bool ok = callee.runtime_value.host_function(callee.runtime_value.host_user_data,
939 runtime_arguments,
940 runtime_result,
941 host_error);
942 if (not ok)
943 {
944 error = make_error(host_error.code.empty() ? "BCV021" : host_error.code,
945 host_error.message.empty()
946 ? "host function call failed"
947 : host_error.message,
948 executed_instructions,
949 &frame,
950 &inst);
951 if (host_error.has_error() and not host_error.code.empty())
952 error.error.span = host_error.span;
953 return false;
954 }
955
956 if (not write_register(frame,
957 inst.destination,
958 Compiler_Bytecode_Value::make_value(std::move(runtime_result)),
959 inst,
960 executed_instructions,
961 error))
962 return false;
963
964 ++frame.pc;
965 return true;
966 }
967
969 execute_loop(const size_t max_steps)
970 {
971 size_t executed_instructions = 0;
972
973 while (not call_stack.is_empty())
974 {
975 if (max_steps != 0 and executed_instructions >= max_steps)
976 return make_error("BCV020",
977 "bytecode step limit exceeded",
978 executed_instructions,
979 &current_frame());
980
981 auto & frame = current_frame();
982 if (frame.pc >= frame.function->code.size())
983 return make_error("BCV005",
984 "program counter " + std::to_string(frame.pc)
985 + " is out of bounds in function '" + frame.function->name + "'",
986 executed_instructions,
987 &frame);
988
989 const auto & inst = frame.function->code.access(frame.pc);
990 ++executed_instructions;
991
992 switch (inst.opcode)
993 {
995 {
996 if (inst.constant_id >= frame.function->constants.size())
997 return make_error("BCV006",
998 "invalid constant id k"
999 + std::to_string(inst.constant_id),
1000 executed_instructions,
1001 &frame,
1002 &inst);
1003
1005 std::string conversion_error;
1007 frame.function->constants.access(inst.constant_id),
1008 value,
1009 conversion_error))
1010 return make_error("BCV010",
1011 conversion_error,
1012 executed_instructions,
1013 &frame,
1014 &inst);
1015
1017 if (not write_register(frame,
1018 inst.destination,
1019 value,
1020 inst,
1021 executed_instructions,
1022 error))
1023 return error;
1024
1025 ++frame.pc;
1026 break;
1027 }
1028
1030 {
1033 if (not read_local(frame,
1034 inst.local_slot_id,
1035 inst,
1036 executed_instructions,
1037 value,
1038 error))
1039 return error;
1040 if (not write_register(frame,
1041 inst.destination,
1042 value,
1043 inst,
1044 executed_instructions,
1045 error))
1046 return error;
1047
1048 ++frame.pc;
1049 break;
1050 }
1051
1053 {
1054 if (inst.operands.is_empty())
1055 return make_error("BCV006",
1056 "StoreLocal requires one source operand",
1057 executed_instructions,
1058 &frame,
1059 &inst);
1060
1063 if (not read_register(frame,
1064 inst.operands.access(0),
1065 inst,
1066 executed_instructions,
1067 value,
1068 error))
1069 return error;
1070 if (not write_local(frame,
1071 inst.local_slot_id,
1072 value,
1073 inst,
1074 executed_instructions,
1075 error))
1076 return error;
1077
1078 ++frame.pc;
1079 break;
1080 }
1081
1083 {
1086 if (not read_global(frame,
1087 inst.global_slot_id,
1088 inst,
1089 executed_instructions,
1090 value,
1091 error))
1092 return error;
1093 if (not write_register(frame,
1094 inst.destination,
1095 value,
1096 inst,
1097 executed_instructions,
1098 error))
1099 return error;
1100
1101 ++frame.pc;
1102 break;
1103 }
1104
1106 {
1107 if (inst.operands.is_empty())
1108 return make_error("BCV006",
1109 "StoreGlobal requires one source operand",
1110 executed_instructions,
1111 &frame,
1112 &inst);
1113
1116 if (not read_register(frame,
1117 inst.operands.access(0),
1118 inst,
1119 executed_instructions,
1120 value,
1121 error))
1122 return error;
1123 if (not write_global(frame,
1124 inst.global_slot_id,
1125 value,
1126 inst,
1127 executed_instructions,
1128 error))
1129 return error;
1130
1131 ++frame.pc;
1132 break;
1133 }
1134
1136 {
1138 if (not write_register(frame,
1139 inst.destination,
1141 inst,
1142 executed_instructions,
1143 error))
1144 return error;
1145
1146 ++frame.pc;
1147 break;
1148 }
1149
1151 {
1152 if (inst.operands.is_empty())
1153 return make_error("BCV006",
1154 "Unary requires one source operand",
1155 executed_instructions,
1156 &frame,
1157 &inst);
1158
1161 if (not read_register(frame,
1162 inst.operands.access(0),
1163 inst,
1164 executed_instructions,
1165 operand,
1166 error))
1167 return error;
1168
1170 switch (inst.op)
1171 {
1173 {
1174 long long integer_value = 0;
1175 if (not require_integer(operand,
1176 frame,
1177 inst,
1178 executed_instructions,
1179 "unary '-'",
1180 integer_value,
1181 error))
1182 return error;
1183 const auto negated = compiler_integer_negate(integer_value);
1184 if (negated.status != Compiler_Integer_Status::Ok)
1185 return make_integer_error(negated.status,
1186 executed_instructions,
1187 frame,
1188 inst);
1189 result = Compiler_Bytecode_Value::make_integer(negated.value);
1190 break;
1191 }
1192
1194 {
1195 bool bool_value = false;
1196 if (not require_bool(operand,
1197 frame,
1198 inst,
1199 executed_instructions,
1200 "unary '!'",
1201 bool_value,
1202 error))
1203 return error;
1204 result = Compiler_Bytecode_Value::make_bool(not bool_value);
1205 break;
1206 }
1207
1209 {
1210 long long integer_value = 0;
1211 if (not require_integer(operand,
1212 frame,
1213 inst,
1214 executed_instructions,
1215 "unary '~'",
1216 integer_value,
1217 error))
1218 return error;
1219 result = Compiler_Bytecode_Value::make_integer(~integer_value);
1220 break;
1221 }
1222
1223 default:
1224 return make_error("BCV015",
1225 "unsupported unary operator '"
1226 + std::string(Compiler_Bytecode_Detail::token_name(inst.op))
1227 + "'",
1228 executed_instructions,
1229 &frame,
1230 &inst);
1231 }
1232
1233 if (not write_register(frame,
1234 inst.destination,
1235 result,
1236 inst,
1237 executed_instructions,
1238 error))
1239 return error;
1240
1241 ++frame.pc;
1242 break;
1243 }
1244
1246 {
1247 if (inst.operands.size() < 2)
1248 return make_error("BCV006",
1249 "Binary requires two source operands",
1250 executed_instructions,
1251 &frame,
1252 &inst);
1253
1254 Compiler_Bytecode_Value lhs_value;
1255 Compiler_Bytecode_Value rhs_value;
1257 if (not read_register(frame,
1258 inst.operands.access(0),
1259 inst,
1260 executed_instructions,
1261 lhs_value,
1262 error))
1263 return error;
1264 if (not read_register(frame,
1265 inst.operands.access(1),
1266 inst,
1267 executed_instructions,
1268 rhs_value,
1269 error))
1270 return error;
1271
1273 switch (inst.op)
1274 {
1283 {
1284 long long lhs = 0;
1285 long long rhs = 0;
1286 if (not require_integer(lhs_value,
1287 frame,
1288 inst,
1289 executed_instructions,
1290 "binary operator",
1291 lhs,
1292 error))
1293 return error;
1294 if (not require_integer(rhs_value,
1295 frame,
1296 inst,
1297 executed_instructions,
1298 "binary operator",
1299 rhs,
1300 error))
1301 return error;
1302
1303 const auto computed = compiler_integer_binary(inst.op, lhs, rhs);
1304 if (computed.status != Compiler_Integer_Status::Ok)
1305 return make_integer_error(computed.status,
1306 executed_instructions,
1307 frame,
1308 inst);
1309 result = Compiler_Bytecode_Value::make_integer(computed.value);
1310 break;
1311 }
1312
1317 {
1318 long long lhs = 0;
1319 long long rhs = 0;
1320 if (not require_integer(lhs_value,
1321 frame,
1322 inst,
1323 executed_instructions,
1324 "comparison",
1325 lhs,
1326 error))
1327 return error;
1328 if (not require_integer(rhs_value,
1329 frame,
1330 inst,
1331 executed_instructions,
1332 "comparison",
1333 rhs,
1334 error))
1335 return error;
1336
1337 bool comparison = false;
1338 switch (inst.op)
1339 {
1341 comparison = lhs < rhs;
1342 break;
1344 comparison = lhs <= rhs;
1345 break;
1347 comparison = lhs > rhs;
1348 break;
1350 comparison = lhs >= rhs;
1351 break;
1352 default:
1353 break;
1354 }
1355 result = Compiler_Bytecode_Value::make_bool(comparison);
1356 break;
1357 }
1358
1361 {
1362 bool lhs = false;
1363 bool rhs = false;
1364 if (not require_bool(lhs_value,
1365 frame,
1366 inst,
1367 executed_instructions,
1368 "logical operator",
1369 lhs,
1370 error))
1371 return error;
1372 if (not require_bool(rhs_value,
1373 frame,
1374 inst,
1375 executed_instructions,
1376 "logical operator",
1377 rhs,
1378 error))
1379 return error;
1380 result = Compiler_Bytecode_Value::make_bool(inst.op
1382 ? lhs and rhs
1383 : lhs or rhs);
1384 break;
1385 }
1386
1389 compiler_bytecode_values_equal(lhs_value, rhs_value));
1390 break;
1391
1394 not compiler_bytecode_values_equal(lhs_value, rhs_value));
1395 break;
1396
1397 default:
1398 return make_error("BCV016",
1399 "unsupported binary operator '"
1400 + std::string(Compiler_Bytecode_Detail::token_name(inst.op))
1401 + "'",
1402 executed_instructions,
1403 &frame,
1404 &inst);
1405 }
1406
1407 if (not write_register(frame,
1408 inst.destination,
1409 result,
1410 inst,
1411 executed_instructions,
1412 error))
1413 return error;
1414
1415 ++frame.pc;
1416 break;
1417 }
1418
1420 {
1424 if (not read_callee_and_arguments(frame,
1425 inst,
1426 executed_instructions,
1427 callee,
1428 arguments,
1429 error))
1430 return error;
1431
1432 if (callee.is_function_ref())
1433 {
1434 if (callee.function_id >= bytecode_module->functions.size())
1435 return make_error("BCV003",
1436 "invalid function id f"
1437 + std::to_string(callee.function_id),
1438 executed_instructions,
1439 &frame,
1440 &inst);
1441
1442 if (not push_frame(*bytecode_module->functions.access(callee.function_id),
1443 arguments,
1444 true,
1445 frame.pc + 1,
1446 inst.destination,
1447 executed_instructions,
1448 error))
1449 return error;
1450 break;
1451 }
1452
1453 if (not callee.is_runtime_value())
1454 return make_error("BCV017",
1455 "callee is not callable: "
1457 executed_instructions,
1458 &frame,
1459 &inst);
1460
1462 {
1463 if (not execute_host_call(frame,
1464 inst,
1465 callee,
1466 arguments,
1467 executed_instructions,
1468 error))
1469 return error;
1470 break;
1471 }
1472
1474 return make_error("BCV018",
1475 "HIR function values are not callable from bytecode VM",
1476 executed_instructions,
1477 &frame,
1478 &inst);
1479
1480 return make_error("BCV017",
1481 "callee is not callable: "
1483 executed_instructions,
1484 &frame,
1485 &inst);
1486 }
1487
1489 frame.pc = inst.target_pc;
1490 break;
1491
1493 {
1494 if (inst.operands.is_empty())
1495 return make_error("BCV006",
1496 "Branch requires one condition operand",
1497 executed_instructions,
1498 &frame,
1499 &inst);
1500
1501 Compiler_Bytecode_Value condition;
1503 if (not read_register(frame,
1504 inst.operands.access(0),
1505 inst,
1506 executed_instructions,
1507 condition,
1508 error))
1509 return error;
1510
1511 bool branch = false;
1512 if (not require_bool(condition,
1513 frame,
1514 inst,
1515 executed_instructions,
1516 "branch condition",
1517 branch,
1518 error))
1519 return error;
1520
1521 frame.pc = branch ? inst.target_pc : inst.false_target_pc;
1522 break;
1523 }
1524
1526 {
1529 if (not inst.operands.is_empty()
1530 and not read_register(frame,
1531 inst.operands.access(0),
1532 inst,
1533 executed_instructions,
1534 value,
1535 error))
1536 return error;
1537
1541 executed_instructions,
1542 completed,
1543 error))
1544 return error.ok() ? completed : error;
1545 break;
1546 }
1547
1549 {
1554 executed_instructions,
1555 completed,
1556 error))
1557 return error.ok() ? completed : error;
1558 break;
1559 }
1560
1562 return make_error("BCV022",
1563 "executed trap/unreachable instruction",
1564 executed_instructions,
1565 &frame,
1566 &inst);
1567 }
1568 }
1569
1571 }
1572
1575 const DynArray<Compiler_Bytecode_Value> & arguments,
1576 const size_t max_steps)
1577 {
1578 call_stack.clear();
1579
1581 if (not module_is_valid(error))
1582 return error;
1583
1584 if (not push_frame(function,
1585 arguments,
1586 false,
1588 0,
1589 0,
1590 error))
1591 return error;
1592
1593 return execute_loop(max_steps);
1594 }
1595
1596 public:
1604 {
1605 reset();
1606 }
1607
1609 void
1611 {
1612 call_stack.clear();
1614 bytecode_module != nullptr
1616 : 0);
1617 }
1618
1620 [[nodiscard]] const Compiler_Bytecode_Module &
1621 module() const noexcept
1622 {
1623 return *bytecode_module;
1624 }
1625
1627 [[nodiscard]] const DynArray<Compiler_Bytecode_Value> &
1628 global_values() const noexcept
1629 {
1630 return globals;
1631 }
1632
1634 [[nodiscard]] const Compiler_Bytecode_Value *
1635 global_slot(const Compiler_IR_Global_Slot_Id slot_id) const noexcept
1636 {
1637 if (slot_id >= globals.size())
1638 return nullptr;
1639 return &globals.access(slot_id);
1640 }
1641
1643 [[nodiscard]] size_t
1644 call_stack_depth() const noexcept
1645 {
1646 return call_stack.size();
1647 }
1648
1655 bool
1658 {
1659 if (slot_id >= globals.size())
1660 return false;
1661 globals.access(slot_id) = value;
1662 return true;
1663 }
1664
1671 run_top_level(const size_t max_steps = 0)
1672 {
1673 if (bytecode_module == nullptr)
1674 return make_error("BCV001", "null bytecode module", 0);
1675
1676 if (bytecode_module->top_level == nullptr)
1677 return make_error("BCV002", "bytecode module has no top-level body", 0);
1678
1680 return execute_entry(*bytecode_module->top_level, arguments, max_steps);
1681 }
1682
1692 const DynArray<Compiler_Bytecode_Value> & arguments,
1693 const size_t max_steps = 0)
1694 {
1695 if (bytecode_module == nullptr)
1696 return make_error("BCV001", "null bytecode module", 0);
1697
1698 if (function_id >= bytecode_module->functions.size())
1699 return make_error("BCV003",
1700 "invalid function id f" + std::to_string(function_id),
1701 0);
1702
1703 return execute_entry(*bytecode_module->functions.access(function_id),
1704 arguments,
1705 max_steps);
1706 }
1707
1709 [[nodiscard]] std::string
1714 };
1715}
1716
1717#endif
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
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
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
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
Definition Bytecode.H:358
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.
Definition Bytecode.H:84
@ 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.
Definition ah-zip.H:183
@ 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.
Definition ahDefs.C:95
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.
Definition ahAlgo.H:707
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
Definition Bytecode.H:76
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.
Definition Bytecode.H:900
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.
Definition ahDefs.C:100
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
Definition Bytecode.H:80
size_t Compiler_Bytecode_Function_Id
Definition Bytecode.H:78
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.
Definition ahAlgo.H:127
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.
Definition Bytecode.H:183
bool bool_value
Boolean payload when kind == Boolean.
Definition Bytecode.H:188
std::string text
Canonical textual payload for dumps/debugging.
Definition Bytecode.H:186
char char_value
Character payload when kind == Character.
Definition Bytecode.H:189
Compiler_Bytecode_Constant_Kind kind
Logical constant category.
Definition Bytecode.H:184
long long integer_value
Integer payload when kind == Integer.
Definition Bytecode.H:187
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.
Definition Bytecode.H:222
std::string name
Debug/source name.
Definition Bytecode.H:224
Compiler_Bytecode_PC entry_pc
Entry PC used to start execution.
Definition Bytecode.H:233
size_t register_count
Number of virtual registers required by the function.
Definition Bytecode.H:235
DynArray< Compiler_IR_Slot > local_slots
Local/parameter slot metadata preserved for the VM.
Definition Bytecode.H:229
One lowered bytecode instruction.
Definition Bytecode.H:194
Compiler_Bytecode_Register_Id destination
Destination register, or 0 for void instructions.
Definition Bytecode.H:197
DynArray< Compiler_Bytecode_Register_Id > operands
Source registers in deterministic order.
Definition Bytecode.H:205
Bytecode module sharing global slot layout with the source IR module.
Definition Bytecode.H:246
DynArray< Compiler_IR_Slot > global_slots
Global slots preserved from the source IR module.
Definition Bytecode.H:247
Compiler_Bytecode_Function * top_level
Optional lowered top-level body.
Definition Bytecode.H:249
DynArray< Compiler_Bytecode_Function * > functions
Lowered non-top-level functions.
Definition Bytecode.H:248
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
DynArray< Compiler_Bytecode_Value > registers
Structural validation report for one bytecode function or module.
Definition Bytecode.H:313
DynArray< std::string > errors
Hard validation failures.
Definition Bytecode.H:315
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.
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.
Definition ah-source.H:100