Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
interpreter_runtime_test.cc
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
36#include <gtest/gtest.h>
37
39#include <Compiler_Parser.H>
40#include <Interpreter_Runtime.H>
41
42using namespace Aleph;
43
44namespace
45{
47 lower_to_hir(const std::string & source,
48 Source_Manager & sm,
50 Compiler_Ast_Context & ast_ctx,
51 Compiler_HIR_Context & hir_ctx,
53 {
54 const auto file_id = sm.add_virtual_file("main.aw", source);
55 Compiler_Parser parser(ast_ctx, sm, file_id, &dx);
56 const auto * module = parser.parse_module();
57 EXPECT_FALSE(dx.has_errors());
58
59 typed.analyze_module(module);
60 EXPECT_FALSE(dx.has_errors());
61
62 Compiler_HIR_Lowering lowering(hir_ctx, typed);
63 return lowering.lower_module(module);
64 }
65
66 bool
67 host_pair(void *,
68 const DynArray<Interpreter_Value> & arguments,
69 Interpreter_Value & result,
71 {
72 if (arguments.size() != 2)
73 {
74 error.code = "HOST001";
75 error.message = "pair expects exactly 2 arguments";
76 return false;
77 }
78
80 tuple.append(arguments.access(0));
81 tuple.append(arguments.access(1));
82 result = Interpreter_Value::make_tuple(std::move(tuple));
83 return true;
84 }
85}
86
87TEST(InterpreterRuntime, EvaluatesTopLevelBindingsAndCallsFunctions)
88{
90 Diagnostic_Engine dx(sm);
91 Compiler_Ast_Context ast_ctx(1 << 16);
92 Compiler_HIR_Context hir_ctx(1 << 16);
94
95 const auto * hir = lower_to_hir(
96 "fn add(x, y) {\n"
97 " return x + y;\n"
98 "}\n"
99 "let value = add(20, 22);\n",
100 sm, dx, ast_ctx, hir_ctx, typed);
101
102 Interpreter_Runtime runtime(&dx);
103 const auto evaluated = runtime.evaluate_module(hir);
104 ASSERT_TRUE(evaluated.ok());
105 EXPECT_FALSE(dx.has_errors());
106
107 const auto dump = interpreter_dump_globals(runtime);
108 EXPECT_EQ(
109 dump,
110 "Globals\n"
111 " add = Function(add)\n"
112 " value = Int(42)\n");
113
117 const auto called = runtime.call("add", arguments);
118 ASSERT_TRUE(called.ok());
119 EXPECT_EQ(called.value.kind, Interpreter_Value_Kind::Integer);
120 EXPECT_EQ(called.value.integer_value, 12);
121}
122
123TEST(InterpreterRuntime, SupportsLoopsAssignmentsAndLocalMutation)
124{
126 Diagnostic_Engine dx(sm);
127 Compiler_Ast_Context ast_ctx(1 << 16);
128 Compiler_HIR_Context hir_ctx(1 << 16);
130
131 const auto * hir = lower_to_hir(
132 "fn countdown(n) {\n"
133 " while (n > 0) {\n"
134 " n = n - 1;\n"
135 " }\n"
136 " return n;\n"
137 "}\n"
138 "let result = countdown(3);\n",
139 sm, dx, ast_ctx, hir_ctx, typed);
140
141 Interpreter_Runtime runtime(&dx);
142 const auto evaluated = runtime.evaluate_module(hir);
143 ASSERT_TRUE(evaluated.ok());
144 EXPECT_FALSE(dx.has_errors());
145
146 const auto * result = runtime.global_environment().lookup("result");
147 ASSERT_NE(result, nullptr);
148 EXPECT_EQ(result->kind, Interpreter_Value_Kind::Integer);
149 EXPECT_EQ(result->integer_value, 0);
150}
151
152TEST(InterpreterRuntime, BindsHostFunctionsInPrelude)
153{
154 Interpreter_Runtime runtime;
155 ASSERT_TRUE(runtime.bind_host_function("pair", host_pair));
156
160
161 const auto called = runtime.call("pair", arguments);
162 ASSERT_TRUE(called.ok());
163 EXPECT_EQ(called.value.kind, Interpreter_Value_Kind::Tuple);
164 ASSERT_EQ(called.value.tuple_elements().size(), 2u);
165 EXPECT_EQ(called.value.tuple_elements().access(0).integer_value, 1);
166 EXPECT_EQ(called.value.tuple_elements().access(1).integer_value, 2);
167 EXPECT_EQ(interpreter_value_to_string(called.value), "Tuple(Int(1), Int(2))");
168}
169
170TEST(InterpreterRuntime, TupleValuesKeepDeepCopySemantics)
171{
175
176 const auto original = Interpreter_Value::make_tuple(std::move(elements));
177 auto copied = original;
178 copied.tuple_storage->elements.access(0) = Interpreter_Value::make_integer(99);
179
180 EXPECT_EQ(original.tuple_elements().access(0).integer_value, 1);
181 EXPECT_EQ(copied.tuple_elements().access(0).integer_value, 99);
182
183 auto moved = std::move(copied);
184 EXPECT_EQ(moved.tuple_elements().access(0).integer_value, 99);
185 EXPECT_EQ(copied.kind, Interpreter_Value_Kind::Invalid);
186}
187
188TEST(InterpreterRuntime, ReportsStructuredRuntimeErrors)
189{
191 Diagnostic_Engine dx(sm);
192 Compiler_Ast_Context ast_ctx(1 << 16);
193 Compiler_HIR_Context hir_ctx(1 << 16);
195
196 const auto * hir = lower_to_hir(
197 "fn explode(x) {\n"
198 " return x / 0;\n"
199 "}\n"
200 "let doomed = explode(5);\n",
201 sm, dx, ast_ctx, hir_ctx, typed);
202
203 Interpreter_Runtime runtime(&dx);
204 const auto evaluated = runtime.evaluate_module(hir);
205 ASSERT_FALSE(evaluated.ok());
206 EXPECT_EQ(evaluated.flow, Interpreter_Control_Flow_Kind::Runtime_Error);
207 EXPECT_EQ(evaluated.error.code, "RUN007");
208 EXPECT_EQ(evaluated.error.message, "division by zero");
209 EXPECT_TRUE(dx.has_errors());
210}
211
212// The compound assignments computed with the overflow of C++, undefined
213// behaviour; now a result that does not fit is the runtime error RUN013,
214// as with the binary operators, and the variable keeps its value.
215TEST(InterpreterRuntime, CompoundAssignmentThatOverflowsIsARuntimeError)
216{
217 struct Case
218 {
219 const char * statement;
220 bool overflows;
221 const char * value;
222 };
223
224 const Case cases[] = {
225 {"x += 1;", true, nullptr},
226 {"x -= -1;", true, nullptr},
227 {"x *= 2;", true, nullptr},
228 {"x += 0;", false, "Int(9223372036854775807)"},
229 {"x = -x - 1; x -= 1;", true, nullptr},
230 {"x = -x - 1; x /= -1;", true, nullptr},
231 {"x = -x - 1; x %= -1;", false, "Int(0)"},
232 {"x = -x - 1; x *= 1;", false, "Int(-9223372036854775808)"},
233 };
234
235 for (const auto & c : cases)
236 {
238 Diagnostic_Engine dx(sm);
239 Compiler_Ast_Context ast_ctx(1 << 16);
240 Compiler_HIR_Context hir_ctx(1 << 16);
242
243 const auto * hir = lower_to_hir(std::string("fn f() {\n"
244 " let x = 9223372036854775807;\n ")
245 + c.statement + "\n"
246 " return x;\n"
247 "}\n"
248 "let value = f();\n",
249 sm, dx, ast_ctx, hir_ctx, typed);
250
251 Interpreter_Runtime runtime(&dx);
252 const auto evaluated = runtime.evaluate_module(hir);
253 if (c.overflows)
254 {
255 ASSERT_FALSE(evaluated.ok()) << c.statement;
256 EXPECT_EQ(evaluated.error.code, "RUN013") << c.statement;
257 EXPECT_EQ(evaluated.error.message, "integer overflow") << c.statement;
258 }
259 else
260 {
261 ASSERT_TRUE(evaluated.ok()) << c.statement;
262 EXPECT_NE(interpreter_dump_globals(runtime).find(std::string("value = ") + c.value),
263 std::string::npos) << c.statement;
264 }
265 }
266}
Lowering from the current MVP typed AST into the reusable HIR model.
Recursive-descent parser for the compiler-support MVP grammar.
Reusable runtime and structured evaluator for HIR-based interpreters.
size_t size_t int32_t value
Definition ca-c-api.h:116
Arena-backed ownership context for AST nodes.
Arena-backed ownership context for HIR nodes.
Lowers the MVP typed AST into HIR.
Recursive-descent parser that produces an AST in Compiler_Ast_Context.
Inference-oriented semantic pass for the MVP compiler front-end.
void analyze_module(const Compiler_Module *module)
Runs the typed semantic analysis for module.
Diagnostic accumulator and renderer.
bool has_errors() const noexcept
Returns whether any error or fatal diagnostic was emitted.
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.
Interpreter_Value * lookup(const std::string &name) noexcept
Finds a visible binding recursively.
Structured runtime for executing typed HIR.
const Interpreter_Environment & global_environment() const noexcept
Returns the globals environment for the last evaluated module.
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.
Interpreter_Execution_Result evaluate_module(const Compiler_HIR_Module *module)
Evaluates one HIR module and leaves its globals installed.
Stores source files and resolves offsets into human-readable data.
Definition ah-source.H:184
Source_File_Id add_virtual_file(const std::string &name, const std::string &text)
Registers an in-memory source file.
Definition ah-source.H:258
#define TEST(name)
Main namespace for Aleph-w library functions.
Itor find(const Itor &beg, const Itor &end, const T &value)
Find the first element equal to a value.
Definition ahAlgo.H:230
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
Definition ahDefs.C:100
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.
static Interpreter_Value make_tuple(const DynArray< Interpreter_Value > &elements)
Builds a tuple runtime value by copying elements.
long long integer_value
Payload for Int values.
Interpreter_Value_Kind kind
Active value kind.
static Interpreter_Value make_integer(const long long i)
Builds an integer runtime value.