Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Interpreter_Runtime.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
55#ifndef INTERPRETER_RUNTIME_H
56#define INTERPRETER_RUNTIME_H
57
58#include <cctype>
59#include <cerrno>
60#include <cstdint>
61#include <cstdlib>
62#include <limits>
63#include <memory>
64#include <sstream>
65#include <string>
66#include <string_view>
67#include <utility>
68
69#include <Compiler_HIR_Model.H>
70#include <ah-diagnostics.H>
71#include <ah-errors.H>
72#include <tpl_dynArray.H>
73
74namespace Aleph {
79
82{
83 Invalid,
84 Unit,
85 Bool,
86 Integer,
87 String,
89 Tuple,
92};
93
96{
97 None,
98 Return,
99 Break,
100 Continue,
102};
103
105inline const char *interpreter_value_kind_name(const Interpreter_Value_Kind kind) noexcept
106{
107 switch (kind)
108 {
110 return "Invalid";
112 return "Unit";
114 return "Bool";
116 return "Int";
118 return "String";
120 return "Char";
122 return "Tuple";
124 return "Function";
126 return "HostFunction";
127 }
128
129 return "Unknown";
130}
131
134{
135 switch (kind)
136 {
138 return "None";
140 return "Return";
142 return "Break";
144 return "Continue";
146 return "RuntimeError";
147 }
148
149 return "Unknown";
150}
151
159{
160 std::string code;
161 std::string message;
163
165 [[nodiscard]] bool has_error() const noexcept
166 {
167 return not code.empty() or not message.empty();
168 }
169};
170
179using Interpreter_Host_Function = bool (*)(void *user_data,
180 const DynArray<Interpreter_Value> &arguments,
181 Interpreter_Value &result,
183
191{
193 bool bool_value = false;
194 long long integer_value = 0;
195 char character_value = '\0';
196 std::string string_value;
197 std::unique_ptr<Interpreter_Tuple_Storage> tuple_storage;
200 = nullptr;
202 void *host_user_data = nullptr;
203 std::string callable_name;
204
206 Interpreter_Value() = default;
207
210
212 Interpreter_Value(Interpreter_Value &&other) noexcept;
213
216
218 Interpreter_Value &operator=(const Interpreter_Value &other);
219
221 Interpreter_Value &operator=(Interpreter_Value &&other) noexcept;
222
225 {
226 return {};
227 }
228
236
238 static Interpreter_Value make_bool(const bool b)
239 {
242 value.bool_value = b;
243 return value;
244 }
245
247 static Interpreter_Value make_integer(const long long i)
248 {
251 value.integer_value = i;
252 return value;
253 }
254
256 static Interpreter_Value make_string(std::string text)
257 {
260 value.string_value = std::move(text);
261 return value;
262 }
263
265 static Interpreter_Value make_character(const char ch)
266 {
269 value.character_value = ch;
270 return value;
271 }
272
275
278
281 Interpreter_Environment *env = nullptr)
282 {
285 value.function = fn;
286 value.closure_environment = env;
287 value.callable_name = fn != nullptr ? fn->name : "<null-function>";
288 return value;
289 }
290
292 static Interpreter_Value make_host_function(std::string name,
293 const Interpreter_Host_Function callback,
294 void *user_data = nullptr)
295 {
298 value.host_function = callback;
299 value.host_user_data = user_data;
300 value.callable_name = std::move(name);
301 return value;
302 }
303
305 [[nodiscard]] bool is_unit() const noexcept
306 {
308 }
309
311 [[nodiscard]] bool is_callable() const noexcept
312 {
314 }
315
321 [[nodiscard]] const DynArray<Interpreter_Value> &tuple_elements() const noexcept;
322};
323
326{
328
330
331 explicit Interpreter_Tuple_Storage(const DynArray<Interpreter_Value> &values) : elements(values)
332 {}
333
335 : elements(std::move(values))
336 {}
337};
338
340 : kind(other.kind), bool_value(other.bool_value), integer_value(other.integer_value),
345{
346 if (other.tuple_storage != nullptr)
347 tuple_storage = std::make_unique<Interpreter_Tuple_Storage>(*other.tuple_storage);
348}
349
351 : kind(other.kind), bool_value(other.bool_value), integer_value(other.integer_value),
352 character_value(other.character_value), string_value(std::move(other.string_value)),
353 tuple_storage(std::move(other.tuple_storage)), function(other.function),
354 closure_environment(other.closure_environment), host_function(other.host_function),
355 host_user_data(other.host_user_data), callable_name(std::move(other.callable_name))
356{
358}
359
360inline Interpreter_Value::~Interpreter_Value() noexcept = default;
361
363{
364 if (this == &other)
365 return *this;
366
367 tuple_storage.reset();
368
369 kind = other.kind;
370 bool_value = other.bool_value;
371 integer_value = other.integer_value;
372 character_value = other.character_value;
373 string_value = other.string_value;
374 function = other.function;
375 closure_environment = other.closure_environment;
376 host_function = other.host_function;
377 host_user_data = other.host_user_data;
378 callable_name = other.callable_name;
379
380 if (other.tuple_storage != nullptr)
381 tuple_storage = std::make_unique<Interpreter_Tuple_Storage>(*other.tuple_storage);
382 return *this;
383}
384
386{
387 if (this == &other)
388 return *this;
389
390 kind = other.kind;
391 bool_value = other.bool_value;
392 integer_value = other.integer_value;
393 character_value = other.character_value;
394 string_value = std::move(other.string_value);
395 tuple_storage = std::move(other.tuple_storage);
396 function = other.function;
397 closure_environment = other.closure_environment;
398 host_function = other.host_function;
399 host_user_data = other.host_user_data;
400 callable_name = std::move(other.callable_name);
401
403 return *this;
404}
405
407{
410 value.tuple_storage = std::make_unique<Interpreter_Tuple_Storage>(elements);
411 return value;
412}
413
415{
418 value.tuple_storage = std::make_unique<Interpreter_Tuple_Storage>(std::move(elements));
419 return value;
420}
421
423{
424 return tuple_storage->elements;
425}
426
437{
438 if (lhs.kind != rhs.kind)
439 return false;
440
441 switch (lhs.kind)
442 {
444 return false;
445
447 return true;
448
450 return lhs.bool_value == rhs.bool_value;
451
453 return lhs.integer_value == rhs.integer_value;
454
456 return lhs.string_value == rhs.string_value;
457
459 return lhs.character_value == rhs.character_value;
460
462 if (lhs.tuple_elements().size() != rhs.tuple_elements().size())
463 return false;
464 for (size_t i = 0; i < lhs.tuple_elements().size(); ++i)
466 rhs.tuple_elements().access(i)))
467 return false;
468 return true;
469
471 return lhs.function == rhs.function and lhs.closure_environment == rhs.closure_environment;
472
474 return lhs.host_function == rhs.host_function and lhs.host_user_data == rhs.host_user_data;
475 }
476
477 return false;
478}
479
486{
487 auto escape_text = [](std::string_view text)
488 {
489 std::string escaped;
490 escaped.reserve(text.size());
491 for (const char ch : text)
492 switch (ch)
493 {
494 case '\\':
495 escaped += "\\\\";
496 break;
497 case '"':
498 escaped += "\\\"";
499 break;
500 case '\'':
501 escaped += "\\'";
502 break;
503 case '\n':
504 escaped += "\\n";
505 break;
506 case '\r':
507 escaped += "\\r";
508 break;
509 case '\t':
510 escaped += "\\t";
511 break;
512 default:
513 escaped.push_back(ch);
514 }
515 return escaped;
516 };
517
518 std::ostringstream out;
519 switch (value.kind)
520 {
522 out << "Invalid";
523 break;
524
526 out << "Unit";
527 break;
528
530 out << "Bool(" << (value.bool_value ? "true" : "false") << ")";
531 break;
532
534 out << "Int(" << value.integer_value << ")";
535 break;
536
538 out << "String(\"" << escape_text(value.string_value) << "\")";
539 break;
540
542 out << "Char('" << escape_text(std::string(1, value.character_value)) << "')";
543 break;
544
546 out << "Tuple(";
547 for (size_t i = 0; i < value.tuple_elements().size(); ++i)
548 {
549 if (i > 0)
550 out << ", ";
551 out << interpreter_value_to_string(value.tuple_elements().access(i));
552 }
553 out << ')';
554 break;
555
557 out << "Function(" << value.callable_name << ")";
558 break;
559
561 out << "HostFunction(" << value.callable_name << ")";
562 break;
563 }
564
565 return out.str();
566}
567
574
577{
580
581 Interpreter_Value *find_local(const std::string &name) noexcept
582 {
583 for (size_t i = bindings_.size(); i > 0; --i)
584 if (bindings_.access(i - 1).name == name)
585 return &bindings_.access(i - 1).value;
586 return nullptr;
587 }
588
589 const Interpreter_Value *find_local(const std::string &name) const noexcept
590 {
591 for (size_t i = bindings_.size(); i > 0; --i)
592 if (bindings_.access(i - 1).name == name)
593 return &bindings_.access(i - 1).value;
594 return nullptr;
595 }
596
597public:
601 {}
602
605 {
607 }
608
611 {
612 return parent_env;
613 }
614
616 void clear() noexcept
617 {
618 bindings_.clear();
619 }
620
622 bool is_empty() const noexcept
623 {
624 return bindings_.is_empty();
625 }
626
628 size_t size() const noexcept
629 {
630 return bindings_.size();
631 }
632
639 {
640 return bindings_;
641 }
642
649 bool define(const std::string &name, const Interpreter_Value &value)
650 {
651 if (find_local(name) != nullptr)
652 return false;
653 bindings_.append({name, value});
654 return true;
655 }
656
662 Interpreter_Value *lookup(const std::string &name) noexcept
663 {
664 if (auto *value = find_local(name); value != nullptr)
665 return value;
666 return parent_env != nullptr ? parent_env->lookup(name) : nullptr;
667 }
668
674 const Interpreter_Value *lookup(const std::string &name) const noexcept
675 {
676 if (const auto *value = find_local(name); value != nullptr)
677 return value;
678 return parent_env != nullptr ? parent_env->lookup(name) : nullptr;
679 }
680
687 bool assign(const std::string &name, const Interpreter_Value &value)
688 {
689 if (auto *slot = find_local(name); slot != nullptr)
690 {
691 *slot = value;
692 return true;
693 }
694 return parent_env != nullptr ? parent_env->assign(name, value) : false;
695 }
696};
697
700{
701 size_t max_call_depth = 256;
702};
703
727
735{
741
747
756
760 {
762 result.flow = flow;
763 result.value = value;
764 return result;
765 }
766
768 const std::string &code,
769 const std::string &message,
770 const std::string &note = "",
771 const std::string &help = "") const
772 {
773 if (diagnostics != nullptr)
774 {
775 auto builder = diagnostics->error(span, message).code(code);
776 if (not note.empty())
777 builder.note(note);
778 if (not help.empty())
779 builder.help(help);
780 builder.emit();
781 }
782
786 result.error = {code, message, span};
787 return result;
788 }
789
792 const Source_Span &span) const
793 {
794 switch (status)
795 {
797 return runtime_error(span, "RUN007", "division by zero");
799 return runtime_error(span, "RUN007", "modulo by zero");
800 default:
801 break;
802 }
803
804 return runtime_error(span, "RUN013", "integer overflow");
805 }
806
807 static bool strip_quotes(std::string_view text, const char quote, std::string_view &body) noexcept
808 {
809 if (text.size() < 2)
810 return false;
811 if (text.front() != quote or text.back() != quote)
812 return false;
813 body = text.substr(1, text.size() - 2);
814 return true;
815 }
816
817 static bool decode_escaped_text(const std::string_view body, std::string &out, std::string &error)
818 {
819 out.clear();
820 out.reserve(body.size());
821
822 for (size_t i = 0; i < body.size(); ++i)
823 {
824 const char ch = body[i];
825 if (ch != '\\')
826 {
827 out.push_back(ch);
828 continue;
829 }
830
831 if (i + 1 >= body.size())
832 {
833 error = "unterminated escape sequence";
834 return false;
835 }
836
837 switch (const char esc = body[++i])
838 {
839 case '\\':
840 out.push_back('\\');
841 break;
842 case '"':
843 out.push_back('"');
844 break;
845 case '\'':
846 out.push_back('\'');
847 break;
848 case 'n':
849 out.push_back('\n');
850 break;
851 case 'r':
852 out.push_back('\r');
853 break;
854 case 't':
855 out.push_back('\t');
856 break;
857 case '0':
858 out.push_back('\0');
859 break;
860 default:
861 error = std::string("unsupported escape sequence \\") + esc;
862 return false;
863 }
864 }
865
866 return true;
867 }
868
870 {
871 std::string digits;
872 digits.reserve(node->text.size());
873 for (const char ch : node->text)
874 if (ch != '_')
875 digits.push_back(ch);
876
877 if (digits.empty())
878 return runtime_error(node->span, "RUN012", "malformed integer literal");
879
880 char *end = nullptr;
881 errno = 0;
882 const long long value = std::strtoll(digits.c_str(), &end, 10);
883 if (errno == ERANGE or end == nullptr or *end != '\0')
884 return runtime_error(node->span,
885 "RUN012",
886 "integer literal is out of range for the interpreter");
887
889 }
890
892 {
893 std::string_view body;
894 if (not strip_quotes(node->text, '"', body))
895 return runtime_error(node->span, "RUN012", "malformed string literal");
896
897 std::string decoded;
898 std::string error_message;
899 if (not decode_escaped_text(body, decoded, error_message))
900 return runtime_error(node->span, "RUN012", error_message);
901 return ok(Interpreter_Value::make_string(std::move(decoded)));
902 }
903
905 {
906 std::string_view body;
907 if (not strip_quotes(node->text, '\'', body))
908 return runtime_error(node->span, "RUN012", "malformed character literal");
909
910 std::string decoded;
911 std::string error_message;
912 if (not decode_escaped_text(body, decoded, error_message))
913 return runtime_error(node->span, "RUN012", error_message);
914 if (decoded.size() != 1)
915 return runtime_error(node->span,
916 "RUN012",
917 "character literals must decode to exactly one character");
918
919 return ok(Interpreter_Value::make_character(decoded[0]));
920 }
921
923 const Source_Span &span,
924 const std::string &context) const
925 {
927 return ok(value);
928
929 return runtime_error(span,
930 "RUN008",
931 context + " requires Int but received "
932 + std::string(interpreter_value_kind_name(value.kind)));
933 }
934
936 const Source_Span &span,
937 const std::string &context) const
938 {
940 return ok(value);
941
942 return runtime_error(span,
943 "RUN003",
944 context + " requires Bool but received "
945 + std::string(interpreter_value_kind_name(value.kind)));
946 }
947
950 {
951 if (expr == nullptr)
952 return runtime_error({}, "RUN001", "null HIR expression");
953
954 switch (expr->kind)
955 {
957 return runtime_error(expr->span, "RUN001", "invalid HIR expression");
958
960 {
961 const auto *node = static_cast<const Compiler_HIR_Constant_Expr *>(expr);
962 switch (node->constant_kind)
963 {
967 return ok(Interpreter_Value::make_bool(node->bool_value));
969 return parse_integer_literal(node);
971 return parse_string_literal(node);
973 return parse_char_literal(node);
974 }
975 return runtime_error(node->span, "RUN001", "unknown HIR constant kind");
976 }
977
979 {
980 const auto *node = static_cast<const Compiler_HIR_Variable_Expr *>(expr);
981 if (auto *value = env.lookup(node->name); value != nullptr)
982 return ok(*value);
983 return runtime_error(node->span,
984 "RUN002",
985 "unknown runtime identifier '" + node->name + "'");
986 }
987
989 {
990 const auto *node = static_cast<const Compiler_HIR_Unary_Expr *>(expr);
991 auto operand = evaluate_expr(node->operand, env);
992 if (not operand.ok())
993 return operand;
994
995 switch (node->op)
996 {
998 return require_integer(operand.value, node->span, "unary '+'");
999
1001 {
1002 auto checked = require_integer(operand.value, node->span, "unary '-'");
1003 if (not checked.ok())
1004 return checked;
1005 const auto negated = compiler_integer_negate(checked.value.integer_value);
1006 if (negated.status != Compiler_Integer_Status::Ok)
1007 return integer_error(negated.status, node->span);
1008 return ok(Interpreter_Value::make_integer(negated.value));
1009 }
1010
1012 {
1013 auto checked = require_bool(operand.value, node->span, "unary '!'");
1014 if (not checked.ok())
1015 return checked;
1016 return ok(Interpreter_Value::make_bool(not checked.value.bool_value));
1017 }
1018
1019 default:
1020 return runtime_error(node->span,
1021 "RUN008",
1022 "unsupported unary operator '"
1023 + std::string(compiler_operator_name(node->op)) + "'");
1024 }
1025 }
1026
1028 {
1029 const auto *node = static_cast<const Compiler_HIR_Binary_Expr *>(expr);
1030
1031 if (node->op == Compiler_Operator_Kind::AndAnd or node->op == Compiler_Operator_Kind::OrOr)
1032 {
1033 auto left = evaluate_expr(node->left, env);
1034 if (not left.ok())
1035 return left;
1036 auto left_bool = require_bool(left.value, node->span, "logical operator");
1037 if (not left_bool.ok())
1038 return left_bool;
1039
1040 if (node->op == Compiler_Operator_Kind::AndAnd and not left_bool.value.bool_value)
1041 return ok(Interpreter_Value::make_bool(false));
1042 if (node->op == Compiler_Operator_Kind::OrOr and left_bool.value.bool_value)
1043 return ok(Interpreter_Value::make_bool(true));
1044
1045 auto right = evaluate_expr(node->right, env);
1046 if (not right.ok())
1047 return right;
1048 auto right_bool = require_bool(right.value, node->span, "logical operator");
1049 if (not right_bool.ok())
1050 return right_bool;
1051 return ok(Interpreter_Value::make_bool(right_bool.value.bool_value));
1052 }
1053
1054 const bool is_compound_assignment
1056
1057 if (node->op == Compiler_Operator_Kind::Assign or is_compound_assignment)
1058 {
1059 if (node->left == nullptr or node->left->kind != Compiler_HIR_Expr_Kind::Variable)
1060 return runtime_error(node->span,
1061 "RUN006",
1062 "assignment requires a variable on the left-hand side");
1063 const auto *lhs = static_cast<const Compiler_HIR_Variable_Expr *>(node->left);
1064
1065 if (node->op == Compiler_Operator_Kind::Assign)
1066 {
1067 auto rhs = evaluate_expr(node->right, env);
1068 if (not rhs.ok())
1069 return rhs;
1070
1071 if (not env.assign(lhs->name, rhs.value))
1072 return runtime_error(lhs->span,
1073 "RUN002",
1074 "unknown runtime identifier '" + lhs->name + "'");
1075 return ok(rhs.value);
1076 }
1077
1078 auto current_ptr = env.lookup(lhs->name);
1079 if (current_ptr == nullptr)
1080 return runtime_error(lhs->span,
1081 "RUN002",
1082 "unknown runtime identifier '" + lhs->name + "'");
1083
1084 auto current = require_integer(*current_ptr, lhs->span, "compound assignment");
1085 if (not current.ok())
1086 return current;
1087
1088 auto rhs = evaluate_expr(node->right, env);
1089 if (not rhs.ok())
1090 return rhs;
1091 auto rhs_int = require_integer(rhs.value, node->right->span, "compound assignment");
1092 if (not rhs_int.ok())
1093 return rhs_int;
1094
1095 const auto base = compiler_operator_compound_base(node->op);
1097 return runtime_error(node->span,
1098 "RUN008",
1099 "unsupported compound assignment operator");
1100
1101 const auto computed = compiler_integer_binary(base,
1102 current.value.integer_value,
1103 rhs_int.value.integer_value);
1104 if (computed.status != Compiler_Integer_Status::Ok)
1105 return integer_error(computed.status, node->span);
1106
1107 const auto result = Interpreter_Value::make_integer(computed.value);
1108 (void) env.assign(lhs->name, result);
1109 return ok(result);
1110 }
1111
1112 auto left = evaluate_expr(node->left, env);
1113 if (not left.ok())
1114 return left;
1115 auto right = evaluate_expr(node->right, env);
1116 if (not right.ok())
1117 return right;
1118
1119 switch (node->op)
1120 {
1129 {
1130 auto lhs = require_integer(left.value, node->left->span, "binary operator");
1131 if (not lhs.ok())
1132 return lhs;
1133 auto rhs = require_integer(right.value, node->right->span, "binary operator");
1134 if (not rhs.ok())
1135 return rhs;
1136
1137 const auto computed = compiler_integer_binary(node->op,
1138 lhs.value.integer_value,
1139 rhs.value.integer_value);
1140 if (computed.status != Compiler_Integer_Status::Ok)
1141 return integer_error(computed.status, node->span);
1142 return ok(Interpreter_Value::make_integer(computed.value));
1143 }
1144
1149 {
1150 auto lhs = require_integer(left.value, node->left->span, "comparison");
1151 if (not lhs.ok())
1152 return lhs;
1153 auto rhs = require_integer(right.value, node->right->span, "comparison");
1154 if (not rhs.ok())
1155 return rhs;
1156
1157 bool result = false;
1158 switch (node->op)
1159 {
1161 result = lhs.value.integer_value < rhs.value.integer_value;
1162 break;
1164 result = lhs.value.integer_value <= rhs.value.integer_value;
1165 break;
1167 result = lhs.value.integer_value > rhs.value.integer_value;
1168 break;
1170 result = lhs.value.integer_value >= rhs.value.integer_value;
1171 break;
1172 default:
1173 break;
1174 }
1175
1176 return ok(Interpreter_Value::make_bool(result));
1177 }
1178
1180 return ok(
1181 Interpreter_Value::make_bool(interpreter_values_equal(left.value, right.value)));
1182
1184 return ok(
1185 Interpreter_Value::make_bool(not interpreter_values_equal(left.value, right.value)));
1186
1187 default:
1188 return runtime_error(node->span,
1189 "RUN008",
1190 "unsupported binary operator '"
1191 + std::string(compiler_operator_name(node->op)) + "'");
1192 }
1193 }
1194
1196 {
1197 const auto *node = static_cast<const Compiler_HIR_Call_Expr *>(expr);
1198 auto callee = evaluate_expr(node->callee, env);
1199 if (not callee.ok())
1200 return callee;
1201
1203 for (size_t i = 0; i < node->arguments.size(); ++i)
1204 {
1205 auto arg = evaluate_expr(node->arguments.access(i), env);
1206 if (not arg.ok())
1207 return arg;
1208 arguments.append(arg.value);
1209 }
1210
1211 return call_value(callee.value, arguments, node->span);
1212 }
1213 }
1214
1215 return runtime_error(expr->span, "RUN001", "unknown HIR expression kind");
1216 }
1217
1220 {
1221 if (stmt == nullptr)
1222 return runtime_error({}, "RUN001", "null HIR statement");
1223
1224 switch (stmt->kind)
1225 {
1227 return runtime_error(stmt->span, "RUN001", "invalid HIR statement");
1228
1230 {
1231 const auto *node = static_cast<const Compiler_HIR_Eval_Stmt *>(stmt);
1232 auto value = evaluate_expr(node->expr, env);
1233 if (not value.ok())
1234 return value;
1235 return ok(value.value);
1236 }
1237
1239 {
1240 const auto *node = static_cast<const Compiler_HIR_Let_Stmt *>(stmt);
1242 if (node->initializer != nullptr)
1243 {
1244 auto init = evaluate_expr(node->initializer, env);
1245 if (not init.ok())
1246 return init;
1247 value = init.value;
1248 }
1249
1250 if (not env.define(node->name, value))
1251 return runtime_error(node->span,
1252 "RUN011",
1253 "duplicate runtime binding '" + node->name + "'");
1254 return ok(value);
1255 }
1256
1258 {
1259 const auto *node = static_cast<const Compiler_HIR_Return_Stmt *>(stmt);
1260 if (node->value == nullptr)
1262 auto value = evaluate_expr(node->value, env);
1263 if (not value.ok())
1264 return value;
1266 }
1267
1269 {
1270 const auto *node = static_cast<const Compiler_HIR_Block_Stmt *>(stmt);
1271 Interpreter_Environment block_env(&env);
1272 for (size_t i = 0; i < node->statements.size(); ++i)
1273 {
1274 auto result = evaluate_stmt(node->statements.access(i), block_env);
1275 if (result.flow != Interpreter_Control_Flow_Kind::None)
1276 return result;
1277 }
1278 return ok();
1279 }
1280
1282 {
1283 const auto *node = static_cast<const Compiler_HIR_If_Stmt *>(stmt);
1284 auto cond = evaluate_expr(node->condition, env);
1285 if (not cond.ok())
1286 return cond;
1287 auto checked = require_bool(cond.value, node->condition->span, "if condition");
1288 if (not checked.ok())
1289 return checked;
1290
1291 if (checked.value.bool_value)
1292 return node->then_branch != nullptr ? evaluate_stmt(node->then_branch, env) : ok();
1293
1294 return node->else_branch != nullptr ? evaluate_stmt(node->else_branch, env) : ok();
1295 }
1296
1298 {
1299 const auto *node = static_cast<const Compiler_HIR_While_Stmt *>(stmt);
1300 while (true)
1301 {
1302 auto cond = evaluate_expr(node->condition, env);
1303 if (not cond.ok())
1304 return cond;
1305 auto checked = require_bool(cond.value, node->condition->span, "while condition");
1306 if (not checked.ok())
1307 return checked;
1308 if (not checked.value.bool_value)
1309 return ok();
1310
1311 auto body = node->body != nullptr ? evaluate_stmt(node->body, env) : ok();
1314 return body;
1315 if (body.flow == Interpreter_Control_Flow_Kind::Break)
1316 return ok();
1319 continue;
1320 }
1321 }
1322
1325
1328 }
1329
1330 return runtime_error(stmt->span, "RUN001", "unknown HIR statement kind");
1331 }
1332
1334 const DynArray<Interpreter_Value> &arguments,
1335 const Source_Span &span)
1336 {
1337 const auto *function = callee.function;
1338 if (function == nullptr)
1339 return runtime_error(span, "RUN004", "null HIR function");
1340
1341 if (function->parameters.size() != arguments.size())
1342 return runtime_error(span,
1343 "RUN005",
1344 "function '" + function->name + "' expects "
1345 + std::to_string(function->parameters.size())
1346 + " arguments but received " + std::to_string(arguments.size()));
1347
1348 if (call_stack.size() >= options.max_call_depth)
1349 return runtime_error(span,
1350 "RUN010",
1351 "maximum call depth exceeded while calling '" + function->name + "'");
1352
1354 frame.function = function;
1355 frame.locals.set_parent(callee.closure_environment != nullptr ? callee.closure_environment
1356 : &globals);
1357
1358 for (size_t i = 0; i < function->parameters.size(); ++i)
1359 (void) frame.locals.define(function->parameters.access(i).name, arguments.access(i));
1360
1361 call_stack.append(std::move(frame));
1362 auto result = evaluate_stmt(function->body, call_stack.access(call_stack.size() - 1).locals);
1363 (void) call_stack.pop();
1364
1365 if (result.flow == Interpreter_Control_Flow_Kind::Return)
1366 return ok(result.value);
1367 if (result.flow == Interpreter_Control_Flow_Kind::Break
1369 return runtime_error(function->span,
1370 "RUN009",
1371 "control-flow escaped function '" + function->name + "'");
1372 return result;
1373 }
1374
1376 const DynArray<Interpreter_Value> &arguments,
1377 const Source_Span &span) const
1378 {
1379 if (callee.host_function == nullptr)
1380 return runtime_error(span, "RUN004", "null host function");
1381
1384 if (callee.host_function(callee.host_user_data, arguments, result, error))
1385 return ok(result);
1386
1387 auto code = error.code.empty() ? std::string("RUN004") : error.code;
1388 auto message = error.message.empty() ? "host function '" + callee.callable_name + "' failed"
1389 : error.message;
1390 return runtime_error(error.span.is_valid() ? error.span : span, code, message);
1391 }
1392
1394 const DynArray<Interpreter_Value> &arguments,
1395 const Source_Span &span)
1396 {
1397 switch (callee.kind)
1398 {
1400 return call_hir_function(callee, arguments, span);
1401
1403 return call_host_function(callee, arguments, span);
1404
1405 default:
1406 return runtime_error(span,
1407 "RUN004",
1408 "attempted to call a non-callable value of kind "
1409 + std::string(interpreter_value_kind_name(callee.kind)));
1410 }
1411 }
1412
1414 {
1415 if (function == nullptr)
1416 return false;
1417 return globals.define(function->name, Interpreter_Value::make_function(function, &globals));
1418 }
1419
1420public:
1427 const Interpreter_Runtime_Options &opts = {}) noexcept
1428 : options(opts), diagnostics(dx), prelude(nullptr), globals(&prelude)
1429 {}
1430
1433 {
1434 diagnostics = dx;
1435 }
1436
1439 {
1440 return prelude;
1441 }
1442
1445 {
1446 return globals;
1447 }
1448
1450 size_t call_depth() const noexcept
1451 {
1452 return call_stack.size();
1453 }
1454
1456 void reset() noexcept
1457 {
1458 globals.clear();
1460 call_stack.clear();
1461 }
1462
1470 bool bind_host_function(const std::string &name,
1471 const Interpreter_Host_Function callback,
1472 void *user_data = nullptr)
1473 {
1474 ah_runtime_error_unless(callback != nullptr)
1475 << "Interpreter_Runtime::bind_host_function(): callback is null";
1476 return prelude.define(name, Interpreter_Value::make_host_function(name, callback, user_data));
1477 }
1478
1488 {
1489 if (module == nullptr)
1490 return runtime_error({}, "RUN001", "null HIR module");
1491
1492 reset();
1493
1494 for (size_t i = 0; i < module->functions.size(); ++i)
1495 if (not install_module_function(module->functions.access(i)))
1496 return runtime_error(module->functions.access(i)->span,
1497 "RUN011",
1498 "duplicate global function '" + module->functions.access(i)->name
1499 + "'");
1500
1501 for (size_t i = 0; i < module->statements.size(); ++i)
1502 {
1503 auto result = evaluate_stmt(module->statements.access(i), globals);
1505 return result;
1506 if (result.flow == Interpreter_Control_Flow_Kind::Return
1507 or result.flow == Interpreter_Control_Flow_Kind::Break
1509 return runtime_error(module->statements.access(i)->span,
1510 "RUN009",
1511 "top-level control-flow statement is not allowed");
1512 }
1513
1514 return ok();
1515 }
1516
1525 Interpreter_Execution_Result call(const std::string &name,
1526 const DynArray<Interpreter_Value> &arguments)
1527 {
1528 if (auto *value = globals.lookup(name); value != nullptr)
1529 return call_value(*value, arguments, {});
1530 if (auto *value = prelude.lookup(name); value != nullptr)
1531 return call_value(*value, arguments, {});
1532 return runtime_error({}, "RUN002", "unknown runtime identifier '" + name + "'");
1533 }
1534};
1535
1542{
1543 std::ostringstream out;
1544 out << "Environment\n";
1545 for (size_t i = 0; i < env.bindings().size(); ++i)
1546 {
1547 const auto &binding = env.bindings().access(i);
1548 out << " " << binding.name << " = " << interpreter_value_to_string(binding.value) << '\n';
1549 }
1550 return out.str();
1551}
1552
1554inline std::string interpreter_dump_globals(const Interpreter_Runtime &runtime)
1555{
1556 std::ostringstream out;
1557 out << "Globals\n";
1558 const auto &env = runtime.global_environment();
1559 for (size_t i = 0; i < env.bindings().size(); ++i)
1560 {
1561 const auto &binding = env.bindings().access(i);
1562 out << " " << binding.name << " = " << interpreter_value_to_string(binding.value) << '\n';
1563 }
1564 return out.str();
1565}
1566} // namespace Aleph
1567
1568#endif
Reusable typed high-level IR model independent from any concrete frontend.
Plain-text diagnostic engine for compiler-style tooling.
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
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
Diagnostic_Builder & code(const std::string &value)
Sets the stable diagnostic code.
size_t emit() const noexcept
Finalizes the builder and returns the diagnostic index.
Diagnostic_Builder & help(const std::string &msg)
Appends a help line.
Diagnostic_Builder & note(const std::string &msg)
Appends a note line.
Diagnostic accumulator and renderer.
Diagnostic_Builder error(const Source_Span &span, const std::string &msg)
Starts an error diagnostic.
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.
Nested runtime environment with lexical lookup semantics.
void clear() noexcept
Drops all bindings from this environment only.
Interpreter_Environment(Interpreter_Environment *parent=nullptr) noexcept
Builds an environment with optional lexical parent.
const Interpreter_Value * find_local(const std::string &name) const noexcept
size_t size() const noexcept
Returns the number of bindings in this environment.
Interpreter_Value * lookup(const std::string &name) noexcept
Finds a visible binding recursively.
bool define(const std::string &name, const Interpreter_Value &value)
Defines one local binding.
void set_parent(Interpreter_Environment *parent) noexcept
Changes the lexical parent for this environment.
bool assign(const std::string &name, const Interpreter_Value &value)
Assigns an existing visible binding.
DynArray< Interpreter_Binding > bindings_
const Interpreter_Value * lookup(const std::string &name) const noexcept
Finds a visible binding recursively.
Interpreter_Environment * parent() const noexcept
Returns the lexical parent, if any.
const DynArray< Interpreter_Binding > & bindings() const noexcept
Returns read-only access to the local bindings.
Interpreter_Value * find_local(const std::string &name) noexcept
Interpreter_Environment * parent_env
bool is_empty() const noexcept
Returns whether this environment is empty.
Structured runtime for executing typed HIR.
Interpreter_Execution_Result parse_integer_literal(const Compiler_HIR_Constant_Expr *node) const
Interpreter_Environment prelude
static Interpreter_Execution_Result control(const Interpreter_Control_Flow_Kind flow, const Interpreter_Value &value=Interpreter_Value::make_unit())
Interpreter_Environment globals
Interpreter_Execution_Result parse_string_literal(const Compiler_HIR_Constant_Expr *node) const
DynArray< Interpreter_Call_Frame > call_stack
Interpreter_Execution_Result call_hir_function(const Interpreter_Value &callee, const DynArray< Interpreter_Value > &arguments, const Source_Span &span)
Interpreter_Execution_Result require_integer(const Interpreter_Value &value, const Source_Span &span, const std::string &context) const
void set_diagnostics(Diagnostic_Engine *dx) noexcept
Sets the optional diagnostic sink for runtime failures.
Interpreter_Execution_Result call_value(const Interpreter_Value &callee, const DynArray< Interpreter_Value > &arguments, const Source_Span &span)
Interpreter_Runtime(Diagnostic_Engine *dx=nullptr, const Interpreter_Runtime_Options &opts={}) noexcept
Builds a fresh interpreter runtime.
size_t call_depth() const noexcept
Returns the current call depth.
Interpreter_Execution_Result require_bool(const Interpreter_Value &value, const Source_Span &span, const std::string &context) const
const Interpreter_Environment & global_environment() const noexcept
Returns the globals environment for the last evaluated module.
Interpreter_Execution_Result runtime_error(const Source_Span &span, const std::string &code, const std::string &message, const std::string &note="", const std::string &help="") const
bool bind_host_function(const std::string &name, const Interpreter_Host_Function callback, void *user_data=nullptr)
Defines one host function in the persistent prelude.
Interpreter_Execution_Result call(const std::string &name, const DynArray< Interpreter_Value > &arguments)
Calls one visible function by name.
static Interpreter_Execution_Result ok(const Interpreter_Value &value=Interpreter_Value::make_unit())
void reset() noexcept
Clears globals and the call stack while preserving host bindings.
Interpreter_Execution_Result evaluate_expr(const Compiler_HIR_Expr *expr, Interpreter_Environment &env)
bool install_module_function(const Compiler_HIR_Function *function)
static bool strip_quotes(std::string_view text, const char quote, std::string_view &body) noexcept
static bool decode_escaped_text(const std::string_view body, std::string &out, std::string &error)
const Interpreter_Environment & prelude_environment() const noexcept
Returns the persistent prelude environment.
Interpreter_Execution_Result evaluate_stmt(const Compiler_HIR_Stmt *stmt, Interpreter_Environment &env)
Interpreter_Execution_Result integer_error(const Compiler_Integer_Status status, const Source_Span &span) const
Runtime error for an integer operation that has no result.
Interpreter_Execution_Result evaluate_module(const Compiler_HIR_Module *module)
Evaluates one HIR module and leaves its globals installed.
Interpreter_Runtime_Options options
Interpreter_Execution_Result call_host_function(const Interpreter_Value &callee, const DynArray< Interpreter_Value > &arguments, const Source_Span &span) const
Interpreter_Execution_Result parse_char_literal(const Compiler_HIR_Constant_Expr *node) const
Main namespace for Aleph-w library functions.
@ Runtime_Error
Execution failed with a structured runtime error.
@ Return
Return one register value.
@ String
String literal payload.
@ Character
Character literal payload.
@ Invalid
Uninitialized register/slot or explicit invalid placeholder.
void message(const char *file, int line, const char *format,...)
Print an informational message with file and line info.
Definition ahDefs.C:95
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Interpreter_Value_Kind
Runtime categories supported by the interpreter MVP.
const char * interpreter_value_kind_name(const Interpreter_Value_Kind kind) noexcept
Stable debug name for one runtime value kind.
const char * compiler_operator_name(const Compiler_Operator_Kind kind) noexcept
Returns a stable debug name for one operator kind.
@ Continue
Skip to the next iteration of the innermost loop.
@ Break
Immediate exit from the innermost loop.
bool interpreter_values_equal(const Interpreter_Value &lhs, const Interpreter_Value &rhs)
Returns whether two runtime values compare equal.
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.
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
const char * interpreter_control_flow_name(const Interpreter_Control_Flow_Kind kind) noexcept
Stable debug name for one control-flow outcome.
and
Check uniqueness with explicit hash + equality functors.
std::string interpreter_dump_environment(const Interpreter_Environment &env)
Dumps one environment deterministically.
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
Interpreter_Control_Flow_Kind
Structured control-flow outcomes during evaluation.
Compiler_Operator_Kind compiler_operator_compound_base(const Compiler_Operator_Kind kind) noexcept
Returns the arithmetic operator underlying one compound assignment.
Field< int > Integer
Definition ahField.H:136
bool compiler_operator_is_compound_assignment(const Compiler_Operator_Kind kind) noexcept
Returns whether kind is one compound-assignment operator.
static std::atomic< bool > init
Definition hash-fct.C:54
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_dump_globals(const Interpreter_Runtime &runtime)
Dumps the globals currently installed in one runtime.
std::string interpreter_value_to_string(const Interpreter_Value &value)
Formats one runtime value deterministically for dumps and tests.
@ Function
Function type such as fn(Int) -> Bool.
@ Tuple
Tuple type such as (Int, Bool).
STL namespace.
Structured block statement.
Typed function call expression.
std::string text
Original or normalized constant spelling.
Expression statement in HIR.
Base class for HIR expressions.
Compiler_HIR_Expr_Kind kind
Runtime node kind.
std::string name
Function name.
DynArray< Compiler_HIR_Param > parameters
Parameters in declaration order.
Compiler_HIR_Block_Stmt * body
Function body.
Structured conditional statement.
Typed lexical binding statement.
DynArray< Compiler_HIR_Function * > functions
Lowered top-level functions.
DynArray< Compiler_HIR_Stmt * > statements
Lowered top-level statements.
Source_Span span
Source region associated with the HIR node.
Base class for HIR statements.
Compiler_HIR_Stmt_Kind kind
Runtime node kind.
Typed variable reference expression.
Structured while-loop statement.
One lexical binding inside an interpreter environment.
std::string name
Binding name.
Interpreter_Value value
Stored runtime value.
Result of evaluating one expression, statement, module, or call.
bool has_control_flow() const noexcept
Returns whether this result carries non-local control flow.
Interpreter_Runtime_Error error
Structured runtime failure when flow == Runtime_Error.
Interpreter_Value value
Produced runtime value when relevant.
Interpreter_Control_Flow_Kind flow
Control-flow outcome.
bool ok() const noexcept
Returns whether this result represents a runtime failure.
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.
Runtime options for the HIR evaluator.
size_t max_call_depth
Maximum nested HIR calls before RUN010.
Heap-owned tuple payload for recursive runtime values.
DynArray< Interpreter_Value > elements
Tuple members in lexical order.
Interpreter_Tuple_Storage(DynArray< Interpreter_Value > &&values)
Interpreter_Tuple_Storage(const DynArray< Interpreter_Value > &values)
std::string callable_name
Stable debug name for callable values.
void * host_user_data
Embedding-specific payload for host functions.
Interpreter_Environment * closure_environment
Captured lexical parent for function values.
static Interpreter_Value make_tuple(const DynArray< Interpreter_Value > &elements)
Builds a tuple runtime value by copying elements.
bool is_unit() const noexcept
Returns whether this value is the Unit singleton.
Interpreter_Host_Function host_function
Payload for host function values.
std::string string_value
Payload for String values.
char character_value
Payload for Char values.
const Compiler_HIR_Function * function
Payload for HIR function values.
long long integer_value
Payload for Int values.
static Interpreter_Value make_bool(const bool b)
Builds a boolean runtime value.
Interpreter_Value & operator=(const Interpreter_Value &other)
Assigns one runtime value by deep copy.
bool is_callable() const noexcept
Returns whether this value is callable.
static Interpreter_Value make_character(const char ch)
Builds a character runtime value.
static Interpreter_Value make_invalid()
Builds an invalid value placeholder.
std::unique_ptr< Interpreter_Tuple_Storage > tuple_storage
Payload for Tuple values.
~Interpreter_Value() noexcept
Releases tuple storage if present.
static Interpreter_Value make_function(const Compiler_HIR_Function *fn, Interpreter_Environment *env=nullptr)
Builds a callable value backed by HIR function code.
bool bool_value
Payload for Bool values.
Interpreter_Value_Kind kind
Active value kind.
Interpreter_Value()=default
Builds a fresh value with no tuple storage.
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.
const DynArray< Interpreter_Value > & tuple_elements() const noexcept
Returns the tuple payload.
static Interpreter_Value make_unit()
Builds the Unit value.
static Interpreter_Value make_string(std::string text)
Builds a string runtime value.
Represents a missing value.
Half-open byte range inside a source file.
Definition ah-source.H:100
Lazy and scalable dynamic array implementation.