Bug Summary

File:eval_cps.c
Warning:line 1726, column 3
Value stored to 'r' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple i386-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name eval_cps.c -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu i686 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/home/joels/Current/lispbm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -I .//include -I .//include/extensions -I .//src -I .//utils -I platform/linux/include -D _PRELUDE -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/i386-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -std=c99 -fdebug-compilation-dir=/home/joels/Current/lispbm -ferror-limit 19 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/joels/Current/lispbm/test_reports/version_0.41.0/scan-build/2026-10-16-144956-1359644-1 -x c src/eval_cps.c
1/*
2 Copyright 2018, 2020 - 2026 Joel Svensson svenssonjoel@yahoo.se
3 2025 - 2026 Rasmus Söderhielm rasmus.soderhielm@gmail.com
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17*/
18
19/*
20 eval_cps uses setjmp/longjmp for error handling.
21
22 setjmp/longjmp behavior is undefined:
23 * If the function which called setjmp() returns before longjmp() is
24 called, the behavior is undefined. Some kind of subtle or unsubtle
25 chaos is sure to result.
26
27 * If, in a multithreaded program, a longjmp() call employs an env buffer
28 that was initialized by a call to setjmp() in a different thread, the
29 behavior is undefined.
30
31 As I understand it MISRA C guidelines prohibit (quite completely) any use
32 of setjmp/longjmp for safety-critical applications.
33
34 The LispBM eval_cps evaluator is careful to not fall into either of the
35 undefined behavior situations by:
36 1. setjmp is called in the lbm_run_eval() function which is responsible
37 for running all evaluation.
38 2. longjmp is called as part of the ERROR_CTX/ERROR_AT_CTX macros which
39 are executed by the evaluator in error cases.
40 3. the jump buffers are static (error_jmp_buf).
41 4. The error_ctx/error_at_ctx functions are static.
42 5. The ERROR_CTX/ERROR_AT_CTX/READ_ERROR_CTX macros are only called in
43 static functions.
44 TODO Check static functions that call ERROR_CTX are not called by any
45 non-static function, The only call-chain that leads to a longjmp must
46 originate in lbm_run_eval().
47 => (if the TODO is dealt with) it is impossible to trigger the undefined
48 conditions.
49
50 Possible alternative to setjmp/longjmp is to cram all of the stuff
51 that eval_cps does into a single function and use GOTO to jump between the
52 different continuation and evaluation and error cases. This would be even
53 worse from a "structured programming" viewpoint, but it would also possibly
54 be a bit a faster.
55
56 The setjmp/longjmp error handling applied here is well contained and has
57 been rigorously tested over time. There is a bit more to do in terms of
58 documenting the error handling choices and it would also be nice to statically
59 check/verify that we are ruling out the undefined use cases.
60*/
61
62/* A short NOTE on Dependability and Fault-Tolerance
63
64 LispBM does not aim to be resilient to bit flips in memory caused by cosmic rays
65 or to externally corrupted or broken memory.
66 The goal is to ensure that LispBM itself does not cause memory corruption.
67*/
68
69#include <lbm_memory.h>
70#include <lbm_types.h>
71#include "symrepr.h"
72#include "heap.h"
73#include "env.h"
74#include "eval_cps.h"
75#include "stack.h"
76#include "fundamental.h"
77#include "extensions.h"
78#include "tokpar.h"
79#include "lbm_channel.h"
80#include "print.h"
81#include "platform_mutex.h"
82#include "platform_timestamp.h"
83#include "lbm_flat_value.h"
84
85#include <setjmp.h>
86#include <stdarg.h>
87#include <stdnoreturn.h>
88
89#if __STDC_VERSION__199901L < 201112L
90// Lower than C11
91#undef noreturn__attribute__ ((__noreturn__))
92#define noreturn__attribute__ ((__noreturn__)) __attribute__ ((__noreturn__))
93#endif
94
95// The cold attribute is a hint for the compiler to do the following:
96// - Optimize function for size.
97// - Possibly move cold functions to a separate area of memory.
98// - Act as a branch predition hint for branches leading to "cold" calls.
99#ifdef __clang__1
100#define sizeopt__attribute__((cold, noinline)) __attribute__((cold, noinline))
101#else
102#define sizeopt__attribute__((cold, noinline)) __attribute__((cold, noinline, optimize("Os")))
103#endif
104
105static jmp_buf error_jmp_buf;
106
107#define S_TO_US(X)(lbm_uint)((X) * 1000000) (lbm_uint)((X) * 1000000)
108
109#define DEC_CONTINUATION(x)(((x) & ~0xF8000001u) >> 2) (((x) & ~LBM_CONTINUATION_INTERNAL0xF8000001u) >> LBM_ADDRESS_SHIFT2)
110#define IS_CONTINUATION(x)(((x) & 0xF8000001u) == 0xF8000001u) (((x) & LBM_CONTINUATION_INTERNAL0xF8000001u) == LBM_CONTINUATION_INTERNAL0xF8000001u)
111#define CONTINUATION(x)(((x) << 2) | 0xF8000001u) (((x) << LBM_ADDRESS_SHIFT2) | LBM_CONTINUATION_INTERNAL0xF8000001u)
112
113#define DONE(((0) << 2) | 0xF8000001u) CONTINUATION(0)(((0) << 2) | 0xF8000001u)
114#define SET_GLOBAL_ENV(((1) << 2) | 0xF8000001u) CONTINUATION(1)(((1) << 2) | 0xF8000001u)
115#define BIND_TO_KEY_REST(((2) << 2) | 0xF8000001u) CONTINUATION(2)(((2) << 2) | 0xF8000001u)
116#define IF(((3) << 2) | 0xF8000001u) CONTINUATION(3)(((3) << 2) | 0xF8000001u)
117#define PROGN_REST(((4) << 2) | 0xF8000001u) CONTINUATION(4)(((4) << 2) | 0xF8000001u)
118#define APPLICATION_ARGS(((5) << 2) | 0xF8000001u) CONTINUATION(5)(((5) << 2) | 0xF8000001u)
119#define AND(((6) << 2) | 0xF8000001u) CONTINUATION(6)(((6) << 2) | 0xF8000001u)
120#define OR(((7) << 2) | 0xF8000001u) CONTINUATION(7)(((7) << 2) | 0xF8000001u)
121#define WAIT(((8) << 2) | 0xF8000001u) CONTINUATION(8)(((8) << 2) | 0xF8000001u)
122#define MATCH(((9) << 2) | 0xF8000001u) CONTINUATION(9)(((9) << 2) | 0xF8000001u)
123#define APPLICATION_START(((10) << 2) | 0xF8000001u) CONTINUATION(10)(((10) << 2) | 0xF8000001u)
124#define EVAL_R(((11) << 2) | 0xF8000001u) CONTINUATION(11)(((11) << 2) | 0xF8000001u)
125#define RESUME(((12) << 2) | 0xF8000001u) CONTINUATION(12)(((12) << 2) | 0xF8000001u)
126#define CLOSURE_ARGS(((13) << 2) | 0xF8000001u) CONTINUATION(13)(((13) << 2) | 0xF8000001u)
127#define EXIT_ATOMIC(((14) << 2) | 0xF8000001u) CONTINUATION(14)(((14) << 2) | 0xF8000001u)
128#define READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u) CONTINUATION(15)(((15) << 2) | 0xF8000001u)
129#define READ_APPEND_CONTINUE(((16) << 2) | 0xF8000001u) CONTINUATION(16)(((16) << 2) | 0xF8000001u)
130#define READ_EVAL_CONTINUE(((17) << 2) | 0xF8000001u) CONTINUATION(17)(((17) << 2) | 0xF8000001u)
131#define READ_EXPECT_CLOSEPAR(((18) << 2) | 0xF8000001u) CONTINUATION(18)(((18) << 2) | 0xF8000001u)
132#define READ_DOT_TERMINATE(((19) << 2) | 0xF8000001u) CONTINUATION(19)(((19) << 2) | 0xF8000001u)
133#define READ_DONE(((20) << 2) | 0xF8000001u) CONTINUATION(20)(((20) << 2) | 0xF8000001u)
134#define READ_START_BYTEARRAY(((21) << 2) | 0xF8000001u) CONTINUATION(21)(((21) << 2) | 0xF8000001u)
135#define READ_APPEND_BYTEARRAY(((22) << 2) | 0xF8000001u) CONTINUATION(22)(((22) << 2) | 0xF8000001u)
136#define MAP(((23) << 2) | 0xF8000001u) CONTINUATION(23)(((23) << 2) | 0xF8000001u)
137#define MATCH_GUARD(((24) << 2) | 0xF8000001u) CONTINUATION(24)(((24) << 2) | 0xF8000001u)
138#define TERMINATE(((25) << 2) | 0xF8000001u) CONTINUATION(25)(((25) << 2) | 0xF8000001u)
139#define PROGN_VAR(((26) << 2) | 0xF8000001u) CONTINUATION(26)(((26) << 2) | 0xF8000001u)
140#define SETQ(((27) << 2) | 0xF8000001u) CONTINUATION(27)(((27) << 2) | 0xF8000001u)
141#define MOVE_TO_FLASH(((28) << 2) | 0xF8000001u) CONTINUATION(28)(((28) << 2) | 0xF8000001u)
142#define MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u) CONTINUATION(29)(((29) << 2) | 0xF8000001u)
143#define MOVE_LIST_TO_FLASH(((30) << 2) | 0xF8000001u) CONTINUATION(30)(((30) << 2) | 0xF8000001u)
144#define CLOSE_LIST_IN_FLASH(((31) << 2) | 0xF8000001u) CONTINUATION(31)(((31) << 2) | 0xF8000001u)
145#define QQ_EXPAND_START(((32) << 2) | 0xF8000001u) CONTINUATION(32)(((32) << 2) | 0xF8000001u)
146#define QQ_EXPAND(((33) << 2) | 0xF8000001u) CONTINUATION(33)(((33) << 2) | 0xF8000001u)
147#define QQ_APPEND(((34) << 2) | 0xF8000001u) CONTINUATION(34)(((34) << 2) | 0xF8000001u)
148#define QQ_EXPAND_LIST(((35) << 2) | 0xF8000001u) CONTINUATION(35)(((35) << 2) | 0xF8000001u)
149#define QQ_LIST(((36) << 2) | 0xF8000001u) CONTINUATION(36)(((36) << 2) | 0xF8000001u)
150#define KILL(((37) << 2) | 0xF8000001u) CONTINUATION(37)(((37) << 2) | 0xF8000001u)
151#define LOOP(((38) << 2) | 0xF8000001u) CONTINUATION(38)(((38) << 2) | 0xF8000001u)
152#define LOOP_CONDITION(((39) << 2) | 0xF8000001u) CONTINUATION(39)(((39) << 2) | 0xF8000001u)
153#define MERGE_REST(((40) << 2) | 0xF8000001u) CONTINUATION(40)(((40) << 2) | 0xF8000001u)
154#define MERGE_LAYER(((41) << 2) | 0xF8000001u) CONTINUATION(41)(((41) << 2) | 0xF8000001u)
155#define CLOSURE_ARGS_REST(((42) << 2) | 0xF8000001u) CONTINUATION(42)(((42) << 2) | 0xF8000001u)
156#define MOVE_ARRAY_ELTS_TO_FLASH(((43) << 2) | 0xF8000001u) CONTINUATION(43)(((43) << 2) | 0xF8000001u)
157#define POP_READER_FLAGS(((44) << 2) | 0xF8000001u) CONTINUATION(44)(((44) << 2) | 0xF8000001u)
158#define EXCEPTION_HANDLER(((45) << 2) | 0xF8000001u) CONTINUATION(45)(((45) << 2) | 0xF8000001u)
159#define RECV_TO(((46) << 2) | 0xF8000001u) CONTINUATION(46)(((46) << 2) | 0xF8000001u)
160#define WRAP_RESULT(((47) << 2) | 0xF8000001u) CONTINUATION(47)(((47) << 2) | 0xF8000001u)
161#define RECV_TO_RETRY(((48) << 2) | 0xF8000001u) CONTINUATION(48)(((48) << 2) | 0xF8000001u)
162#define READ_START_ARRAY(((49) << 2) | 0xF8000001u) CONTINUATION(49)(((49) << 2) | 0xF8000001u)
163#define READ_APPEND_ARRAY(((50) << 2) | 0xF8000001u) CONTINUATION(50)(((50) << 2) | 0xF8000001u)
164#define LOOP_ENV_PREP(((51) << 2) | 0xF8000001u) CONTINUATION(51)(((51) << 2) | 0xF8000001u)
165#define READ_NEXT_TOKEN_GRAB_ROW(((52) << 2) | 0xF8000001u) CONTINUATION(52)(((52) << 2) | 0xF8000001u)
166#define NUM_CONTINUATIONS53 53
167
168#define FM_NEED_GC-1 -1
169#define FM_NO_MATCH-2 -2
170#define FM_PATTERN_ERROR-3 -3
171
172typedef enum {
173 BL_OK = 0,
174 BL_NO_MEMORY,
175 BL_INCORRECT_KEY
176} binding_location_status;
177
178#define FB_OK0 0
179#define FB_TYPE_ERROR-1 -1
180
181#ifdef LBM_USE_ERROR_LINENO
182#define ERROR_AT_CTX(err_val, at)error_at_ctx(err_val, at) error_at_ctx(err_val, at, __LINE__182)
183#define ERROR_CTX(err_val)error_ctx(err_val) error_ctx(err_val, __LINE__183)
184#define READ_ERROR_CTX(row, col)read_error_ctx(row, col) read_error_ctx(row, col, __LINE__184)
185#else
186#define ERROR_AT_CTX(err_val, at)error_at_ctx(err_val, at) error_at_ctx(err_val, at)
187#define ERROR_CTX(err_val)error_ctx(err_val) error_ctx(err_val)
188#define READ_ERROR_CTX(row, col)read_error_ctx(row, col) read_error_ctx(row, col)
189#endif
190
191// ////////////////////////////////////////////////////////////
192// Local variables used in sort and merge
193lbm_value symbol_x = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
194lbm_value symbol_y = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
195#ifdef CLEAN_UP_CLOSURES
196static lbm_value clean_cl_env_symbol = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
197#endif
198
199// ////////////////////////////////////////////////////////////
200// Error strings
201const char* lbm_error_str_parse_eof = "End of parse stream.";
202const char* lbm_error_str_parse_dot = "Incorrect usage of '.'.";
203const char* lbm_error_str_parse_close = "Expected closing parenthesis.";
204const char* lbm_error_str_num_args = "Incorrect number of arguments.";
205const char* lbm_error_str_forbidden_in_atomic = "Operation is forbidden in an atomic block.";
206const char* lbm_error_str_no_number = "Argument(s) must be a number.";
207const char* lbm_error_str_not_a_boolean = "Argument must be t or nil (true or false).";
208const char* lbm_error_str_incorrect_arg = "Incorrect argument.";
209const char* lbm_error_str_var_outside_progn = "Usage of var outside of progn.";
210const char* lbm_error_str_flash_not_possible = "Value cannot be written to flash.";
211const char* lbm_error_str_flash_error = "Error writing to flash.";
212const char* lbm_error_str_flash_full = "Flash memory is full.";
213const char* lbm_error_str_variable_not_bound = "Variable not bound.";
214const char* lbm_error_str_read_no_mem = "Out of memory while reading.";
215const char* lbm_error_str_qq_expand = "Quasiquotation expansion error.";
216const char* lbm_error_str_not_applicable = "Value is not applicable.";
217const char* lbm_error_str_built_in = "Cannot redefine built-in.";
218
219static lbm_value lbm_error_suspect;
220static bool_Bool lbm_error_has_suspect = false0;
221
222
223// ////////////////////////////////////////////////////////////
224// Prototypes for locally used functions (static)
225static uint32_t lbm_mailbox_free_space_for_cid(lbm_cid cid);
226static void apply_apply(lbm_value *args, lbm_uint nargs, eval_context_t *ctx);
227static int gc(void);
228#ifdef LBM_USE_ERROR_LINENO
229static noreturn__attribute__ ((__noreturn__)) void error_ctx(lbm_value, int line_no);
230static noreturn__attribute__ ((__noreturn__)) void error_at_ctx(lbm_value err_val, lbm_value at, int line_no);
231#else
232static noreturn__attribute__ ((__noreturn__)) void error_ctx(lbm_value);
233static noreturn__attribute__ ((__noreturn__)) void error_at_ctx(lbm_value err_val, lbm_value at);
234#endif
235static void mailbox_add_mail(eval_context_t *ctx, lbm_value mail);
236
237// TODO: Optimize, In a large number of cases
238// where WITH_GC is used, it is not really required to check is_symbol_merror.
239// Just checking is_symbol should be enough.
240// Given the number of calls to WITH_GC this could save some code
241// space and potentially also be a slight speedup.
242// TODO: profile.
243#ifdef LBM_ALWAYS_GC
244#define WITH_GC(y, x)(y) = (x); if (lbm_is_symbol_merror((y))) { gc(); (y) = (x); if
(lbm_is_symbol_merror((y))) { error_ctx((((0x23) << 4)
| 0x00000000u)); } }
\
245 gc(); \
246 (y) = (x); \
247 if (lbm_is_symbol_merror((y))) { \
248 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u)); \
249 }
250
251#define WITH_GC_RMBR_1(y, x, r)(y) = (x); if (lbm_is_symbol_merror((y))) { lbm_gc_mark_phase
(r); gc(); (y) = (x); if (lbm_is_symbol_merror((y))) { error_ctx
((((0x23) << 4) | 0x00000000u)); } }
\
252 lbm_gc_mark_phase(r); \
253 gc(); \
254 (y) = (x); \
255 if (lbm_is_symbol_merror((y))) { \
256 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u)); \
257 }
258
259#else
260
261#define WITH_GC(y, x)(y) = (x); if (lbm_is_symbol_merror((y))) { gc(); (y) = (x); if
(lbm_is_symbol_merror((y))) { error_ctx((((0x23) << 4)
| 0x00000000u)); } }
\
262 (y) = (x); \
263 if (lbm_is_symbol_merror((y))) { \
264 gc(); \
265 (y) = (x); \
266 if (lbm_is_symbol_merror((y))) { \
267 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u)); \
268 } \
269 /* continue executing statements below */ \
270 }
271#define WITH_GC_RMBR_1(y, x, r)(y) = (x); if (lbm_is_symbol_merror((y))) { lbm_gc_mark_phase
(r); gc(); (y) = (x); if (lbm_is_symbol_merror((y))) { error_ctx
((((0x23) << 4) | 0x00000000u)); } }
\
272 (y) = (x); \
273 if (lbm_is_symbol_merror((y))) { \
274 lbm_gc_mark_phase(r); \
275 gc(); \
276 (y) = (x); \
277 if (lbm_is_symbol_merror((y))) { \
278 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u)); \
279 } \
280 /* continue executing statements below */ \
281 }
282#endif
283
284#define DROP(c)do { if (lbm_is_ptr(c)) { lbm_cons_t *_cell = lbm_ref_cell(c)
; c = _cell->cdr; } } while (0)
\
285 do { \
286 if (lbm_is_ptr(c)) { \
287 lbm_cons_t *_cell = lbm_ref_cell(c); \
288 c = _cell->cdr; \
289 } \
290 } while (0)
291
292#define EXTRACT(c, a)do { if (lbm_is_ptr(c)) { lbm_cons_t *_cell = lbm_ref_cell(c)
; a = _cell->car; c = _cell->cdr; } else { a = (((0x0) <<
4) | 0x00000000u); } } while (0)
\
293 do { \
294 if (lbm_is_ptr(c)) { \
295 lbm_cons_t *_cell = lbm_ref_cell(c); \
296 a = _cell->car; \
297 c = _cell->cdr; \
298 } else { \
299 a = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); \
300 } \
301 } while (0)
302
303#define EXTRACT_NO_ADVANCE(c, a)do { if (lbm_is_ptr(c)) { lbm_cons_t *_cell = lbm_ref_cell(c)
; a = _cell->car; } else { a = (((0x0) << 4) | 0x00000000u
); } } while (0)
\
304 do { \
305 if (lbm_is_ptr(c)) { \
306 lbm_cons_t *_cell = lbm_ref_cell(c); \
307 a = _cell->car; \
308 } else { \
309 a = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); \
310 } \
311 } while (0)
312
313// ////////////////////////////////////////////////////////////
314// Context queues
315typedef struct {
316 eval_context_t *first;
317 eval_context_t *last;
318} eval_context_queue_t;
319
320static eval_context_queue_t blocked = {NULL((void*)0), NULL((void*)0)};
321static eval_context_queue_t queue = {NULL((void*)0), NULL((void*)0)};
322
323lbm_mutex_t qmutex;
324bool_Bool qmutex_initialized = false0;
325
326static void enqueue_ctx(eval_context_queue_t *q, eval_context_t *ctx);
327
328// The currently executing context.
329eval_context_t *ctx_running = NULL((void*)0);
330volatile bool_Bool lbm_system_sleeping = false0;
331
332static volatile bool_Bool gc_requested = false0;
333void lbm_request_gc(void) {
334 gc_requested = true1;
335}
336
337/*
338 On ChibiOs the CH_CFG_ST_FREQUENCY setting in chconf.h sets the
339 resolution of the timer used for sleep operations. If this is set
340 to 10KHz the resolution is 100us.
341
342 The CH_CFG_ST_TIMEDELTA specifies the minimum number of ticks that
343 can be safely specified in a timeout directive (wonder if that
344 means sleep-period). The timedelta is set to 2.
345
346 If I have understood these correctly it means that the minimum
347 sleep duration possible is 2 * 100us = 200us.
348*/
349
350#define EVAL_CPS_DEFAULT_STACK_SIZE256 256
351// The intended unit on the QUOTA is us (microseconds) and this should
352// be ensured by the platform support libraries for a given platform.
353#define EVAL_TIME_QUOTA400 400
354#define EVAL_CPS_MIN_SLEEP200 200
355#define EVAL_STEPS_QUOTA10 10
356
357#ifdef LBM_USE_TIME_QUOTA
358static volatile uint32_t eval_time_refill = EVAL_TIME_QUOTA400;
359static uint32_t eval_time_quota = EVAL_TIME_QUOTA400;
360static uint32_t eval_current_quota = 0;
361void lbm_set_eval_time_quota(uint32_t quota) {
362 eval_time_refill = quota;
363}
364#else
365static volatile uint32_t eval_steps_refill = EVAL_STEPS_QUOTA10;
366static uint32_t eval_steps_quota = EVAL_STEPS_QUOTA10;
367void lbm_set_eval_step_quota(uint32_t quota) {
368 eval_steps_refill = quota;
369}
370#endif
371
372static volatile uint32_t eval_cps_run_state = EVAL_CPS_STATE_DEAD8;
373static volatile uint32_t eval_cps_next_state = EVAL_CPS_STATE_NONE0;
374static volatile uint32_t eval_cps_next_state_arg = 0;
375static volatile bool_Bool eval_cps_state_changed = false0;
376
377sizeopt__attribute__((cold, noinline)) static void usleep_nonsense(uint32_t us) {
378 (void) us;
379}
380
381sizeopt__attribute__((cold, noinline)) static bool_Bool dynamic_load_nonsense(const char *sym, const char **code) {
382 (void) sym;
383 (void) code;
384 return false0;
385}
386
387sizeopt__attribute__((cold, noinline)) static int printf_nonsense(const char *fmt, ...) {
388 (void) fmt;
389 return 0;
390}
391
392sizeopt__attribute__((cold, noinline)) static void ctx_done_nonsense(eval_context_t *ctx) {
393 (void) ctx;
394}
395
396static void (*usleep_callback)(uint32_t) = usleep_nonsense;
397static void (*ctx_done_callback)(eval_context_t *) = ctx_done_nonsense;
398int (*lbm_printf_callback)(const char *, ...) = printf_nonsense;
399static bool_Bool (*dynamic_load_callback)(const char *, const char **) = dynamic_load_nonsense;
400
401sizeopt__attribute__((cold, noinline)) void lbm_set_usleep_callback(void (*fptr)(uint32_t)) {
402 if (fptr == NULL((void*)0)) usleep_callback = usleep_nonsense;
403 else usleep_callback = fptr;
404}
405
406sizeopt__attribute__((cold, noinline)) void lbm_set_ctx_done_callback(void (*fptr)(eval_context_t *)) {
407 if (fptr == NULL((void*)0)) ctx_done_callback = ctx_done_nonsense;
408 else ctx_done_callback = fptr;
409}
410
411sizeopt__attribute__((cold, noinline)) void lbm_set_printf_callback(int (*fptr)(const char*, ...)){
412 if (fptr == NULL((void*)0)) lbm_printf_callback = printf_nonsense;
413 else lbm_printf_callback = fptr;
414}
415
416sizeopt__attribute__((cold, noinline)) void lbm_set_dynamic_load_callback(bool_Bool (*fptr)(const char *, const char **)) {
417 if (fptr == NULL((void*)0)) dynamic_load_callback = dynamic_load_nonsense;
418 else dynamic_load_callback = fptr;
419}
420
421static volatile lbm_event_t *lbm_events = NULL((void*)0);
422static unsigned int lbm_events_head = 0;
423static unsigned int lbm_events_tail = 0;
424static unsigned int lbm_events_max = 0;
425static bool_Bool lbm_events_full = false0;
426static lbm_mutex_t lbm_events_mutex;
427static bool_Bool lbm_events_mutex_initialized = false0;
428static volatile lbm_cid lbm_event_handler_pid = -1;
429
430static unsigned int lbm_event_queue_item_count(void) {
431 unsigned int res = lbm_events_max;
432 if (!lbm_events_full) {
433 if (lbm_events_head >= lbm_events_tail) {
434 res = lbm_events_head - lbm_events_tail;
435 } else {
436 res = lbm_events_max - lbm_events_tail + lbm_events_head;
437 }
438 }
439 return res;
440}
441
442lbm_cid lbm_get_event_handler_pid(void) {
443 return lbm_event_handler_pid;
444}
445
446void lbm_set_event_handler_pid(lbm_cid pid) {
447 lbm_event_handler_pid = pid;
448}
449
450bool_Bool lbm_event_handler_exists(void) {
451 return(lbm_event_handler_pid > 0);
452}
453
454static bool_Bool event_internal(lbm_event_type_t event_type, lbm_uint parameter, lbm_uint buf_ptr, lbm_uint buf_len) {
455 bool_Bool r = false0;
456 if (lbm_events) {
457 lbm_mutex_lock(&lbm_events_mutex);
458 if (!lbm_events_full) {
459 lbm_event_t event;
460 event.type = event_type;
461 event.parameter = parameter;
462 event.buf_ptr = buf_ptr;
463 event.buf_len = buf_len;
464 lbm_events[lbm_events_head] = event;
465 lbm_events_head = (lbm_events_head + 1) % lbm_events_max;
466 lbm_events_full = lbm_events_head == lbm_events_tail;
467 r = true1;
468 }
469 lbm_mutex_unlock(&lbm_events_mutex);
470 }
471 return r;
472}
473
474bool_Bool lbm_event_define(lbm_value key, lbm_flat_value_t *fv) {
475 return event_internal(LBM_EVENT_DEFINE, key, (lbm_uint)fv->buf, fv->buf_size);
476}
477
478bool_Bool lbm_event_unboxed(lbm_value unboxed) {
479 lbm_uint t = lbm_type_of(unboxed);
480 if (t == LBM_TYPE_SYMBOL0x00000000u ||
481 t == LBM_TYPE_I0x00000008u ||
482 t == LBM_TYPE_U0x0000000Cu ||
483 t == LBM_TYPE_CHAR0x00000004u) {
484 if (lbm_event_handler_pid > 0) {
485 if (lbm_mailbox_free_space_for_cid(lbm_event_handler_pid) > lbm_event_queue_item_count()) {
486 return event_internal(LBM_EVENT_FOR_HANDLER, 0, (lbm_uint)unboxed, 0);
487 }
488 }
489 }
490 return false0;
491}
492
493bool_Bool lbm_event(lbm_flat_value_t *fv) {
494 if (lbm_event_handler_pid > 0) {
495 if (lbm_mailbox_free_space_for_cid(lbm_event_handler_pid) > lbm_event_queue_item_count()) {
496 return event_internal(LBM_EVENT_FOR_HANDLER, 0, (lbm_uint)fv->buf, fv->buf_size);
497 }
498 }
499 return false0;
500}
501
502static bool_Bool lbm_event_pop(lbm_event_t *event) {
503 lbm_mutex_lock(&lbm_events_mutex);
504 bool_Bool r = false0;
505 if (lbm_events_head != lbm_events_tail || lbm_events_full) {
506 *event = lbm_events[lbm_events_tail];
507 lbm_events_tail = (lbm_events_tail + 1) % lbm_events_max;
508 lbm_events_full = false0;
509 r = true1;
510 }
511 lbm_mutex_unlock(&lbm_events_mutex);
512 return r;
513}
514
515bool_Bool lbm_event_queue_is_empty(void) {
516 lbm_mutex_lock(&lbm_events_mutex);
517 bool_Bool empty = false0;
518 if (lbm_events_head == lbm_events_tail && !lbm_events_full) {
519 empty = true1;
520 }
521 lbm_mutex_unlock(&lbm_events_mutex);
522 return empty;
523}
524
525static bool_Bool eval_running = false0;
526static volatile bool_Bool blocking_extension = false0;
527static lbm_mutex_t blocking_extension_mutex;
528static bool_Bool blocking_extension_mutex_initialized = false0;
529static lbm_uint blocking_extension_timeout_us = 0;
530static bool_Bool blocking_extension_timeout = false0;
531
532static bool_Bool is_atomic = false0;
533
534// MODES
535static volatile bool_Bool lbm_verbose = false0;
536static volatile bool_Bool lbm_hide_trapped_error = false0;
537
538void lbm_toggle_verbose(void) {
539 lbm_verbose = !lbm_verbose;
540}
541
542void lbm_set_verbose(bool_Bool verbose) {
543 lbm_verbose = verbose;
544}
545
546void lbm_set_hide_trapped_error(bool_Bool hide) {
547 lbm_hide_trapped_error = hide;
548}
549
550lbm_cid lbm_get_current_cid(void) {
551 lbm_cid cid = -1;
552 if (ctx_running)
553 cid = ctx_running->id;
554 return cid;
555}
556
557eval_context_t *lbm_get_current_context(void) {
558 return ctx_running;
559}
560
561#ifdef LBM_USE_TIME_QUOTA
562void lbm_surrender_quota(void) {
563 // dummy;
564}
565#else
566void lbm_surrender_quota(void) {
567 eval_steps_quota = 0;
568}
569#endif
570
571/****************************************************/
572/* Utilities used locally in this file */
573
574static inline lbm_array_header_t *assume_array(lbm_value a){
575 return (lbm_array_header_t*)lbm_ref_cell(a)->car;
576}
577
578static lbm_value cons_with_gc(lbm_value head, lbm_value tail, lbm_value remember) {
579 lbm_value res;
580#ifdef LBM_ALWAYS_GC
581 lbm_value always_gc_roots[3] = {head, tail, remember};
582 lbm_gc_mark_roots(always_gc_roots,3);
583 gc();
584#endif
585 if (!lbm_heap_num_free()) {
586 lbm_value roots[3] = {head, tail, remember};
587 lbm_gc_mark_roots(roots,3);
588 gc();
589 if (!lbm_heap_num_free()) {
590 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
591 }
592 }
593
594 res = lbm_heap_state.freelist;
595 lbm_uint heap_ix = lbm_dec_ptr(res);
596 lbm_heap_state.freelist = lbm_heap_state.heap[heap_ix].cdr;
597 lbm_heap_state.num_free--;
598 lbm_heap_state.heap[heap_ix].car = head;
599 lbm_heap_state.heap[heap_ix].cdr = tail;
600 res = lbm_set_ptr_type(res, LBM_TYPE_CONS0x10000000u);
601 return res;
602}
603
604// ////////////////////////////////////////////////////////////
605// Stack and CPS
606
607// The CPS system is dependent on a diciplined use of a continuation
608// stack! Continuations are pushed and popped from this stack and
609// between the point in time when a continuation is pushed and when it is popped
610// significant stack "traffic" may have occurred.
611//
612// In the evaluator, functions called things line "eval_X" usually sets up
613// a stack-frame for a future exection of a "cont_X" continuation.
614// Some kind of proof is needed that Things that pushed in a continuation setup-phase
615// are all popped (no more, no less) in a continuation execution phase.
616// continuations "cont_X" also may set up more continuations and in that
617// case they may modify the stack in place or reuse in part or full the
618// stack-frame associated with "cont_X"
619//
620// TODO: for each "eval_X" and "cont_X" pair write an argument or some kind
621// of test that illustrates correct usage of the stack discipline.
622//
623// For now the argument of stack discipline being honored is that all tests
624// pass and no tests end up in stack underflow.
625//
626// Stack overflow is easy to end up in, just write a non-tail-recursive but recursive funtions
627// and run it for a suitably large input.
628//
629// * Potentially tricky situation is "trap" used on a call to a non-tail-recursive function that
630// ends out exhausting stack.
631// # Trap rewinds the stack to the point of trap so it should be perfectly safe to trap even in this situation.
632
633// get_stack_ptr and pop_stack_ptr does in no tests reach
634// the error condition. The check n <= sp is not really needed.
635static inline lbm_uint *get_stack_ptr(eval_context_t *ctx, unsigned int n) {
636 lbm_uint index = ctx->K.sp - n;
637 return &ctx->K.data[index];
638}
639
640// pop_stack_ptr is safe when no GC is performed and
641// the values of the stack will be dropped.
642static inline lbm_uint *pop_stack_ptr(eval_context_t *ctx, unsigned int n) {
643 ctx->K.sp -= n;
644 return &ctx->K.data[ctx->K.sp];
645}
646
647// stack_drop is assuming eval_cps uses a rigoursly tested and principled
648// approach to stack management. If the stack is being abused by the runtime
649// system this is usually very quickly discovered using the test suite as
650// the behavior of the RTS becomes completely wacko.
651static inline void stack_drop(eval_context_t *ctx, unsigned int n) {
652 ctx->K.sp -= n;
653}
654
655static inline lbm_uint *stack_reserve(eval_context_t *ctx, unsigned int n) {
656 if (ctx->K.sp + n < ctx->K.size) {
657 lbm_uint *ptr = &ctx->K.data[ctx->K.sp];
658 ctx->K.sp += n;
659 return ptr;
660 }
661 ERROR_CTX(ENC_SYM_STACK_ERROR)error_ctx((((0x27) << 4) | 0x00000000u));
662}
663
664static void handle_flash_status(lbm_flash_status s) {
665 if ( s == LBM_FLASH_FULL) {
666 lbm_set_error_reason((char*)lbm_error_str_flash_full);
667 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
668 }
669 if (s == LBM_FLASH_WRITE_ERROR) {
670 lbm_set_error_reason((char*)lbm_error_str_flash_error);
671 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
672 }
673}
674
675static void lift_array_flash(lbm_value flash_cell, bool_Bool bytearray, char *data, lbm_uint num_elt) {
676
677 lbm_array_header_t flash_array_header;
678 flash_array_header.size = num_elt;
679 flash_array_header.data = (lbm_uint*)data;
680 lbm_uint flash_array_header_ptr = 0;
681 handle_flash_status(lbm_write_const_raw((lbm_uint*)&flash_array_header,
682 sizeof(lbm_array_header_t) / sizeof(lbm_uint),
683 &flash_array_header_ptr));
684 handle_flash_status(write_const_car(flash_cell, flash_array_header_ptr));
685 lbm_uint t = bytearray ? ENC_SYM_ARRAY_TYPE(((0x30) << 4) | 0x00000000u) : ENC_SYM_LISPARRAY_TYPE(((0x39) << 4) | 0x00000000u);
686 handle_flash_status(write_const_cdr(flash_cell, t));
687}
688
689// ////////////////////////////////////////////////////////////
690// get_car and lbm_car
691
692// lbm_car is a lower level operation that extracts a car field from a cons cell
693// without any consideration of any additional type-tags associated with the cell.
694// get_car is for list cons-cells only.
695
696static inline void get_car_and_cdr(lbm_value a, lbm_value *a_car, lbm_value *a_cdr) {
697 if (lbm_is_cons(a)) {
698 lbm_cons_t *cell = lbm_ref_cell(a);
699 *a_car = cell->car;
700 *a_cdr = cell->cdr;
701 } else if (lbm_is_symbol_nil(a)) {
702 *a_car = *a_cdr = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
703 } else {
704 ERROR_CTX(ENC_SYM_TERROR)error_ctx((((0x21) << 4) | 0x00000000u));
705 }
706}
707
708/* car cdr caar cadr replacements that are evaluator safe. */
709static inline lbm_value get_car(lbm_value a) {
710 if (lbm_is_cons(a)) {
711 lbm_cons_t *cell = lbm_ref_cell(a);
712 return cell->car;
713 } else if (lbm_is_symbol_nil(a)) {
714 return a;
715 }
716 ERROR_CTX(ENC_SYM_TERROR)error_ctx((((0x21) << 4) | 0x00000000u));
717}
718
719static inline lbm_value get_cdr(lbm_value a) {
720 if (lbm_is_cons(a)) {
721 lbm_cons_t *cell = lbm_ref_cell(a);
722 return cell->cdr;
723 } else if (lbm_is_symbol_nil(a)) {
724 return a;
725 }
726 ERROR_CTX(ENC_SYM_TERROR)error_ctx((((0x21) << 4) | 0x00000000u));
727}
728
729static inline lbm_value get_cadr(lbm_value a) {
730 if (lbm_is_cons(a)) {
731 lbm_cons_t *cell = lbm_ref_cell(a);
732 lbm_value tmp = cell->cdr;
733 if (lbm_is_cons(tmp)) {
734 return lbm_ref_cell(tmp)->car;
735 } else if (lbm_is_symbol_nil(tmp)) {
736 return tmp;
737 }
738 } else if (lbm_is_symbol_nil(a)) {
739 return a;
740 }
741 ERROR_CTX(ENC_SYM_TERROR)error_ctx((((0x21) << 4) | 0x00000000u));
742}
743
744// Allocate a binding and attach it to a list (if so desired)
745static lbm_value allocate_binding(lbm_value key, lbm_value val, lbm_value the_cdr) {
746#ifdef LBM_ALWAYS_GC
747 lbm_gc_mark_phase(key);
748 lbm_gc_mark_phase(val);
749 lbm_gc_mark_phase(the_cdr);
750 gc();
751 if (lbm_heap_num_free() < 2) {
752 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
753 }
754#else
755 if (lbm_heap_num_free() < 2) {
756 lbm_gc_mark_phase(key);
757 lbm_gc_mark_phase(val);
758 lbm_gc_mark_phase(the_cdr);
759 gc();
760 if (lbm_heap_num_free() < 2) {
761 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
762 }
763 }
764#endif
765 // If num_free is calculated correctly, freelist is definitely a cons-cell.
766 lbm_cons_t* heap = lbm_heap_state.heap;
767 lbm_value binding_cell = lbm_heap_state.freelist;
768 lbm_uint binding_cell_ix = lbm_dec_ptr(binding_cell);
769 lbm_value list_cell = heap[binding_cell_ix].cdr;
770 lbm_uint list_cell_ix = lbm_dec_ptr(list_cell);
771 lbm_heap_state.freelist = heap[list_cell_ix].cdr;
772 lbm_heap_state.num_free -= 2;
773 heap[binding_cell_ix].car = key;
774 heap[binding_cell_ix].cdr = val;
775 heap[list_cell_ix].car = binding_cell;
776 heap[list_cell_ix].cdr = the_cdr;
777 return list_cell;
778}
779
780#define CLO_PARAMS0 0
781#define CLO_BODY1 1
782#define CLO_ENV2 2
783#define LOOP_BINDS0 0
784#define LOOP_COND1 1
785#define LOOP_BODY2 2
786
787static void atomic_error(void) {
788 lbm_set_error_reason((char*)lbm_error_str_forbidden_in_atomic);
789 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
790}
791
792// block_current_ctx blocks a context until it is
793// woken up externally or a timeout period of time passes.
794// Blocking while in an atomic block would have bad consequences.
795static void block_current_ctx(uint32_t state, lbm_uint sleep_us, bool_Bool do_cont) {
796 if (is_atomic) atomic_error();
797 ctx_running->timestamp = lbm_timestamp();
798 ctx_running->sleep_us = sleep_us;
799 ctx_running->state = state;
800 ctx_running->app_cont = do_cont;
801 enqueue_ctx(&blocked, ctx_running);
802 ctx_running = NULL((void*)0);
803}
804
805// reblock an essentially already blocked context.
806// Same as block but sets no new timestamp or sleep_us.
807static void reblock_current_ctx(uint32_t state, bool_Bool do_cont) {
808 if (is_atomic) atomic_error();
809 ctx_running->state = state;
810 ctx_running->app_cont = do_cont;
811 enqueue_ctx(&blocked, ctx_running);
812 ctx_running = NULL((void*)0);
813}
814
815
816lbm_flash_status lbm_write_const_array_padded(uint8_t *data, lbm_uint n, lbm_uint *res) {
817 lbm_uint full_words = n / sizeof(lbm_uint);
818 lbm_uint n_mod = n % sizeof(lbm_uint);
819
820 if (n_mod == 0) { // perfect fit.
821 return lbm_write_const_raw((lbm_uint*)data, full_words, res);
822 } else {
823 lbm_uint last_word = 0;
824 memcpy(&last_word, &data[full_words * sizeof(lbm_uint)], n_mod);
825 if (full_words >= 1) {
826 lbm_flash_status s = lbm_write_const_raw((lbm_uint*)data, full_words, res);
827 if ( s == LBM_FLASH_WRITE_OK) {
828 lbm_uint dummy;
829 s = lbm_write_const_raw(&last_word, 1, &dummy);
830 }
831 return s;
832 } else {
833 return lbm_write_const_raw(&last_word, 1, res);
834 }
835 }
836}
837
838/****************************************************/
839/* Error message creation */
840
841#define ERROR_MESSAGE_BUFFER_SIZE_BYTES256 256
842
843sizeopt__attribute__((cold, noinline)) void print_env_ll(lbm_value e, char *buf, unsigned int size) {
844 lbm_value curr_l = e;
845 while (lbm_type_of(curr_l) == LBM_TYPE_CONS0x10000000u) {
846 lbm_print_value(buf, (size/2) - 1, lbm_caar(curr_l));
847 lbm_print_value(buf + (size/2),size/2, lbm_cdr(lbm_car(curr_l)));
848 lbm_printf_callback("\t%s = %s\n", buf, buf+(size/2));
849 curr_l = lbm_cdr(curr_l);
850 }
851}
852
853sizeopt__attribute__((cold, noinline)) void print_environments(char *buf, unsigned int size) {
854
855 lbm_printf_callback("\tCurrent local environment:\n");
856 print_env_ll(ctx_running->curr_env, buf, size);
857 lbm_printf_callback("\n\n\tCurrent global environment:\n");
858 lbm_value *glob_env = lbm_get_global_env();
859 for (int i = 0; i < GLOBAL_ENV_ROOTS32; i ++) {
860 print_env_ll(glob_env[i], buf, size);
861 }
862}
863
864sizeopt__attribute__((cold, noinline)) void print_error_value(char *buf, uint32_t bufsize, char *pre, lbm_value v, bool_Bool lookup) {
865
866 lbm_print_value(buf, bufsize, v);
867 lbm_printf_callback("%s %s\n",pre, buf);
868 if (lookup) {
869 if (lbm_is_symbol(v)) {
870 if (lbm_dec_sym(v) >= RUNTIME_SYMBOLS_START0x40000) {
871 lbm_value res = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
872 if (lbm_env_lookup_b(&res, v, ctx_running->curr_env) ||
873 lbm_global_env_lookup(&res, v)) {
874 lbm_print_value(buf, bufsize, res);
875 lbm_printf_callback(" bound to: %s\n", buf);
876 } else {
877 lbm_printf_callback(" UNDEFINED\n");
878 }
879 }
880 }
881 }
882}
883
884sizeopt__attribute__((cold, noinline)) static void print_error_message(lbm_value error,
885 bool_Bool has_at,
886 lbm_value at,
887 unsigned int row,
888 unsigned int col,
889 lbm_int row0,
890 lbm_int row1,
891 lbm_int cid,
892 char *name,
893 bool_Bool trapped) {
894 /* try to allocate a lbm_print_value buffer on the lbm_memory */
895 char *buf = lbm_malloc_reserve(ERROR_MESSAGE_BUFFER_SIZE_BYTES256);
896 if (!buf) {
897 lbm_printf_callback("Error: Not enough memory to show a human readable error message\n");
898 return;
899 }
900 if (trapped) {
901 print_error_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256," Error (trapped):", error, false0);
902 } else {
903 print_error_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256," Error:", error, false0);
904 }
905 if (lbm_is_symbol_merror(error)) {
906 lbm_printf_callback("\n Heap cells free: %d\n", lbm_heap_state.num_free);
907 lbm_printf_callback(" Mem longest free: %d\n\n", lbm_memory_longest_free());
908 }
909 if (name) {
910 lbm_printf_callback( " CTX: %d \"%s\"\n", cid, name);
911 } else {
912 lbm_printf_callback( " CTX: %d\n", cid);
913 }
914 print_error_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256," Current:", ctx_running->curr_exp, true1);
915 // An error can have both a set suspect that can be more detailed than the "at"
916 // show both if present!
917 if (lbm_error_has_suspect) {
918 print_error_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256," At:", lbm_error_suspect, true1);
919 lbm_error_has_suspect = false0;
920 }
921 // TODO: Should perhaps be called has_in and be meant to capture a bit
922 // of the surrounding of where the error happened.
923 if (has_at) {
924 print_error_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256," In:", at, true1);
925 }
926
927 lbm_printf_callback("\n");
928
929 if (lbm_is_symbol(error) &&
930 error == ENC_SYM_RERROR(((0x20) << 4) | 0x00000000u)) {
931 lbm_printf_callback(" Line: %u\n", row);
932 lbm_printf_callback(" Column: %u\n", col);
933 } else if (row0 >= 0) {
934 if (row1 < 0) lbm_printf_callback(" Starting at row: %d\n", row0);
935 else lbm_printf_callback(" Between row %d and %d\n", row0, row1);
936 }
937
938 lbm_printf_callback("\n");
939
940 if (ctx_running->error_reason) {
941 lbm_printf_callback(" Reason: %s\n\n", ctx_running->error_reason);
942 }
943 if (lbm_verbose) {
944 lbm_print_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256, ctx_running->r);
945 lbm_printf_callback(" Current intermediate result: %s\n\n", buf);
946
947 print_environments(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256);
948
949 lbm_printf_callback("\n Mailbox:\n");
950 for (unsigned int i = 0; i < ctx_running->num_mail; i ++) {
951 lbm_print_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256, ctx_running->mailbox[i]);
952 lbm_printf_callback(" %s\n", buf);
953 }
954 lbm_printf_callback("\n Stack:\n");
955 for (unsigned int i = 0; i < ctx_running->K.sp; i ++) {
956 lbm_print_value(buf, ERROR_MESSAGE_BUFFER_SIZE_BYTES256, ctx_running->K.data[i]);
957 lbm_printf_callback(" %s\n", buf);
958 }
959 }
960 lbm_free(buf);
961}
962
963/****************************************************/
964/* Tokenizing and parsing */
965
966static bool_Bool create_string_channel(char *str, lbm_value *res, lbm_value dep) {
967
968 lbm_char_channel_t *chan = NULL((void*)0);
969 lbm_string_channel_state_t *st = NULL((void*)0);
970
971 st = (lbm_string_channel_state_t*)lbm_malloc(sizeof(lbm_string_channel_state_t));
972 if (st == NULL((void*)0)) {
973 return false0;
974 }
975 chan = (lbm_char_channel_t*)lbm_malloc(sizeof(lbm_char_channel_t));
976 if (chan == NULL((void*)0)) {
977 lbm_free(st);
978 return false0;
979 }
980
981 lbm_create_string_char_channel(st, chan, str);
982 lbm_value cell = lbm_heap_allocate_cell(LBM_TYPE_CHANNEL0x90000000u, (lbm_uint) chan, ENC_SYM_CHANNEL_TYPE(((0x37) << 4) | 0x00000000u));
983 if (cell == ENC_SYM_MERROR(((0x23) << 4) | 0x00000000u)) {
984 lbm_free(st);
985 lbm_free(chan);
986 return false0;
987 }
988
989 lbm_char_channel_set_dependency(chan, dep);
990
991 *res = cell;
992 return true1;
993}
994
995/****************************************************/
996/* Queue functions */
997
998static void queue_iterator_nm(eval_context_queue_t *q, ctx_fun f, void *arg1, void *arg2) {
999 eval_context_t *curr;
1000 curr = q->first;
1001
1002 while (curr != NULL((void*)0)) {
1003 f(curr, arg1, arg2);
1004 curr = curr->next;
1005 }
1006}
1007
1008void lbm_all_ctxs_iterator(ctx_fun f, void *arg1, void *arg2) {
1009 lbm_mutex_lock(&qmutex);
1010 queue_iterator_nm(&blocked, f, arg1, arg2);
1011 queue_iterator_nm(&queue, f, arg1, arg2);
1012 if (ctx_running) f(ctx_running, arg1, arg2);
1013 lbm_mutex_unlock(&qmutex);
1014}
1015
1016void lbm_running_iterator(ctx_fun f, void *arg1, void *arg2){
1017 lbm_mutex_lock(&qmutex);
1018 queue_iterator_nm(&queue, f, arg1, arg2);
1019 lbm_mutex_unlock(&qmutex);
1020}
1021
1022void lbm_blocked_iterator(ctx_fun f, void *arg1, void *arg2){
1023 lbm_mutex_lock(&qmutex);
1024 queue_iterator_nm(&blocked, f, arg1, arg2);
1025 lbm_mutex_unlock(&qmutex);
1026}
1027
1028static void enqueue_ctx_nm(eval_context_queue_t *q, eval_context_t *ctx) {
1029 if (q->last == NULL((void*)0)) {
1030 ctx->prev = NULL((void*)0);
1031 ctx->next = NULL((void*)0);
1032 q->first = ctx;
1033 q->last = ctx;
1034 } else {
1035 ctx->prev = q->last;
1036 ctx->next = NULL((void*)0);
1037 q->last->next = ctx;
1038 q->last = ctx;
1039 }
1040}
1041
1042static void enqueue_ctx(eval_context_queue_t *q, eval_context_t *ctx) {
1043 lbm_mutex_lock(&qmutex);
1044 enqueue_ctx_nm(q,ctx);
1045 lbm_mutex_unlock(&qmutex);
1046}
1047
1048// //////////////////////////////////////////////////
1049// If CID was a type that is impossible to create
1050// other than by "spawning a thread", we could
1051// make direct use of the fact that it is an index into
1052// lbm_memory that identifies a context.
1053// We would still need to ensure by inspection
1054// that the value stored is a context.
1055//
1056// Currently any access to a context via its CID is
1057// done by searching all queues for the context and then modifying it.
1058// This is a SAFE way of accessing the context as it enables
1059// detection of state CID.
1060//
1061// Alternative: A CID should be a heap cell (context_address . symbol)
1062// where no program can generate symbol and the type of (context_address . symbol)
1063// is LBM_TYPE_CID.
1064// This would cost one heap cell per context but, it would
1065// give O(1) lookup of context structure which
1066// is useful in for example message delivery.
1067
1068static eval_context_t *lookup_ctx_nm(eval_context_queue_t *q, lbm_cid cid) {
1069 eval_context_t *curr;
1070 curr = q->first;
1071 while (curr != NULL((void*)0)) {
1072 if (curr->id == cid) {
1073 return curr;
1074 }
1075 curr = curr->next;
1076 }
1077 return NULL((void*)0);
1078}
1079
1080static eval_context_t *lookup_ctx_name_nm(eval_context_queue_t *q, char *name, lbm_uint name_len) {
1081 eval_context_t *curr;
1082 curr = q->first;
1083 while (curr != NULL((void*)0)) {
1084 if (curr->name && strncmp(curr->name, name, name_len) == 0) {
1085 return curr;
1086 }
1087 curr = curr->next;
1088 }
1089 return NULL((void*)0);
1090}
1091
1092
1093// Unlinks a context from a queue (doubly linked list).
1094// Unlinking must be preceded by a lookup, both within the same
1095// lock of a mutex.
1096static void unlink_ctx_nm(eval_context_queue_t *q, eval_context_t *ctx) {
1097
1098 if (ctx->prev == NULL((void*)0)) { // ctx is first in queue
1099 q->first = ctx->next;
1100 } else {
1101 ctx->prev->next = ctx->next;
1102 }
1103
1104 if (ctx->next == NULL((void*)0)) { // ctx is last in queue
1105 q->last = ctx->prev;
1106 } else {
1107 ctx->next->prev = ctx->prev;
1108 }
1109 ctx->next = NULL((void*)0);
1110 ctx->prev = NULL((void*)0);
1111}
1112
1113/* End execution of the running context. */
1114static void finish_ctx(void) {
1115
1116 // Reset atomic status if this finish_ctx is part of an
1117 // untrapper error or a self-kill within an atomic block.
1118 is_atomic = false0;
1119 if (!ctx_running) {
1120 return;
1121 }
1122 if (ctx_running->id == lbm_event_handler_pid) {
1123 lbm_event_handler_pid = -1;
1124 }
1125 /* Drop the continuation stack immediately to free up lbm_memory */
1126 lbm_stack_free(&ctx_running->K);
1127 ctx_done_callback(ctx_running);
1128
1129 lbm_free(ctx_running->name); //free name if in LBM_MEM
1130
1131 lbm_memory_free((lbm_uint*)ctx_running->error_reason); //free error_reason if in LBM_MEM
1132
1133 lbm_memory_free((lbm_uint*)ctx_running->mailbox);
1134 lbm_memory_free((lbm_uint*)ctx_running);
1135 ctx_running = NULL((void*)0);
1136}
1137
1138static void context_exists(eval_context_t *ctx, void *cid, void *b) {
1139 if (ctx->id == *(lbm_cid*)cid) {
1140 *(bool_Bool*)b = true1;
1141 }
1142}
1143
1144sizeopt__attribute__((cold, noinline)) void lbm_set_error_suspect(lbm_value suspect) {
1145 lbm_error_suspect = suspect;
1146 lbm_error_has_suspect = true1;
1147}
1148
1149sizeopt__attribute__((cold, noinline)) void lbm_set_error_reason(const char *error_str) {
1150 if (ctx_running != NULL((void*)0)) {
1151 ctx_running->error_reason = error_str;
1152 }
1153}
1154
1155// Not possible to CONS_WITH_GC in error_ctx_base (potential loop)
1156#ifdef LBM_USE_ERROR_LINENO
1157sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void error_ctx_base(lbm_value err_val, bool_Bool has_at, lbm_value at, unsigned int row, unsigned int column, int line_no) {
1158#else
1159sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void error_ctx_base(lbm_value err_val, bool_Bool has_at, lbm_value at, unsigned int row, unsigned int column) {
1160#endif
1161 bool_Bool print_trapped = !lbm_hide_trapped_error && (ctx_running->flags & EVAL_CPS_CONTEXT_FLAG_TRAP_UNROLL_RETURN(uint32_t)0x10);
1162 // An error always exists atomic status.
1163 is_atomic = false0;
1164
1165 if (!(lbm_hide_trapped_error &&
1166 (ctx_running->flags & EVAL_CPS_CONTEXT_FLAG_TRAP_UNROLL_RETURN(uint32_t)0x10))) {
1167 print_error_message(err_val,
1168 has_at,
1169 at,
1170 row,
1171 column,
1172 ctx_running->row0,
1173 ctx_running->row1,
1174 ctx_running->id,
1175 ctx_running->name,
1176 print_trapped
1177 );
1178 }
1179#ifdef LBM_USE_ERROR_LINENO
1180 if (!lbm_hide_trapped_error) {
1181 lbm_printf_callback("eval_cps.c line number: %d\n", line_no);
1182 }
1183#endif
1184 if (ctx_running->flags & EVAL_CPS_CONTEXT_FLAG_TRAP(uint32_t)0x01) {
1185 if (lbm_heap_num_free() < 3) {
1186 gc();
1187 }
1188
1189 if (lbm_heap_num_free() >= 3) {
1190 lbm_value msg = lbm_cons(err_val, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
1191 msg = lbm_cons(lbm_enc_i(ctx_running->id), msg);
1192 msg = lbm_cons(ENC_SYM_EXIT_ERROR(((0x3000C) << 4) | 0x00000000u), msg);
1193 if (!lbm_is_symbol_merror(msg)) {
1194 lbm_find_receiver_and_send(ctx_running->parent, msg);
1195 }
1196 }
1197 // context dies.
1198 } else if ((ctx_running->flags & EVAL_CPS_CONTEXT_FLAG_TRAP_UNROLL_RETURN(uint32_t)0x10) &&
1199 (err_val != ENC_SYM_FATAL_ERROR(((0x26) << 4) | 0x00000000u))) {
1200 while (ctx_running->K.sp > 0) {
1201 lbm_uint v = ctx_running->K.data[--ctx_running->K.sp];
1202 if (v == EXCEPTION_HANDLER(((45) << 2) | 0xF8000001u)) { // context continues executing.
1203 lbm_value *sptr = get_stack_ptr(ctx_running, 2);
1204 lbm_set_car(sptr[0], ENC_SYM_EXIT_ERROR(((0x3000C) << 4) | 0x00000000u));
1205 stack_reserve(ctx_running, 1)[0] = EXCEPTION_HANDLER(((45) << 2) | 0xF8000001u);
1206 ctx_running->app_cont = true1;
1207 ctx_running->r = err_val;
1208 longjmp(error_jmp_buf, 1);
1209 }
1210 }
1211 err_val = ENC_SYM_FATAL_ERROR(((0x26) << 4) | 0x00000000u);
1212 }
1213 ctx_running->r = err_val;
1214 finish_ctx();
1215 longjmp(error_jmp_buf, 1);
1216}
1217
1218#ifdef LBM_USE_ERROR_LINENO
1219sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void error_at_ctx(lbm_value err_val, lbm_value at, int line_no) {
1220 error_ctx_base(err_val, true1, at, 0, 0, line_no);
1221}
1222
1223sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void error_ctx(lbm_value err_val, int line_no) {
1224 error_ctx_base(err_val, false0, 0, 0, 0, line_no);
1225}
1226
1227sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void read_error_ctx(unsigned int row, unsigned int column, int line_no) {
1228 error_ctx_base(ENC_SYM_RERROR(((0x20) << 4) | 0x00000000u), false0, 0, row, column, line_no);
1229}
1230#else
1231sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void error_at_ctx(lbm_value err_val, lbm_value at) {
1232 error_ctx_base(err_val, true1, at, 0, 0);
1233}
1234
1235sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void error_ctx(lbm_value err_val) {
1236 error_ctx_base(err_val, false0, 0, 0, 0);
1237}
1238
1239sizeopt__attribute__((cold, noinline)) static noreturn__attribute__ ((__noreturn__)) void read_error_ctx(unsigned int row, unsigned int column) {
1240 error_ctx_base(ENC_SYM_RERROR(((0x20) << 4) | 0x00000000u), false0, 0, row, column);
1241}
1242#endif
1243
1244// successfully finish a context
1245static void ok_ctx(void) {
1246 if (ctx_running->flags & EVAL_CPS_CONTEXT_FLAG_TRAP(uint32_t)0x01) {
1247 lbm_value msg;
1248 WITH_GC(msg, lbm_heap_allocate_list_init(3,(msg) = (lbm_heap_allocate_list_init(3, (((0x3000B) << 4
) | 0x00000000u), lbm_enc_i(ctx_running->id), ctx_running->
r)); if (lbm_is_symbol_merror((msg))) { gc(); (msg) = (lbm_heap_allocate_list_init
(3, (((0x3000B) << 4) | 0x00000000u), lbm_enc_i(ctx_running
->id), ctx_running->r)); if (lbm_is_symbol_merror((msg)
)) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
1249 ENC_SYM_EXIT_OK,(msg) = (lbm_heap_allocate_list_init(3, (((0x3000B) << 4
) | 0x00000000u), lbm_enc_i(ctx_running->id), ctx_running->
r)); if (lbm_is_symbol_merror((msg))) { gc(); (msg) = (lbm_heap_allocate_list_init
(3, (((0x3000B) << 4) | 0x00000000u), lbm_enc_i(ctx_running
->id), ctx_running->r)); if (lbm_is_symbol_merror((msg)
)) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
1250 lbm_enc_i(ctx_running->id),(msg) = (lbm_heap_allocate_list_init(3, (((0x3000B) << 4
) | 0x00000000u), lbm_enc_i(ctx_running->id), ctx_running->
r)); if (lbm_is_symbol_merror((msg))) { gc(); (msg) = (lbm_heap_allocate_list_init
(3, (((0x3000B) << 4) | 0x00000000u), lbm_enc_i(ctx_running
->id), ctx_running->r)); if (lbm_is_symbol_merror((msg)
)) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
1251 ctx_running->r))(msg) = (lbm_heap_allocate_list_init(3, (((0x3000B) << 4
) | 0x00000000u), lbm_enc_i(ctx_running->id), ctx_running->
r)); if (lbm_is_symbol_merror((msg))) { gc(); (msg) = (lbm_heap_allocate_list_init
(3, (((0x3000B) << 4) | 0x00000000u), lbm_enc_i(ctx_running
->id), ctx_running->r)); if (lbm_is_symbol_merror((msg)
)) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
1252 lbm_find_receiver_and_send(ctx_running->parent, msg);
1253 }
1254 finish_ctx();
1255}
1256
1257static eval_context_t *dequeue_ctx_nm(eval_context_queue_t *q) {
1258 if (q->last == NULL((void*)0)) {
1259 return NULL((void*)0);
1260 }
1261 // q->first should only be NULL if q->last is.
1262 eval_context_t *res = q->first;
1263
1264 if (q->first == q->last) { // One thing in queue
1265 q->first = NULL((void*)0);
1266 q->last = NULL((void*)0);
1267 } else {
1268 q->first = q->first->next;
1269 q->first->prev = NULL((void*)0);
1270 }
1271 res->prev = NULL((void*)0);
1272 res->next = NULL((void*)0);
1273 return res;
1274}
1275
1276static void wake_up_ctxs_nm(void) {
1277 lbm_uint t_now;
1278 t_now = lbm_timestamp();
1279 eval_context_queue_t *q = &blocked;
1280 eval_context_t *curr = q->first;
1281
1282 while (curr != NULL((void*)0)) {
1283 lbm_uint t_diff;
1284 eval_context_t *next = curr->next;
1285 if (LBM_IS_STATE_WAKE_UP_WAKABLE(curr->state)(curr->state & ((uint32_t)4u | (curr->state & (
(uint32_t)2u | (uint32_t)16u))))
) {
1286 if ( curr->timestamp > t_now) {
1287 /* There was an overflow on the counter */
1288#ifndef LBM64
1289 t_diff = (0xFFFFFFFF - curr->timestamp) + t_now;
1290#else
1291 t_diff = (0xFFFFFFFFFFFFFFFF - curr->timestamp) + t_now;
1292#endif
1293 } else {
1294 t_diff = t_now - curr->timestamp;
1295 }
1296
1297 if (t_diff >= curr->sleep_us) {
1298 eval_context_t *wake_ctx = curr;
1299 if (curr == q->last) {
1300 if (curr->prev) {
1301 q->last = curr->prev;
1302 q->last->next = NULL((void*)0);
1303 } else {
1304 q->first = NULL((void*)0);
1305 q->last = NULL((void*)0);
1306 }
1307 } else if (curr->prev == NULL((void*)0)) {
1308 q->first = curr->next;
1309 q->first->prev = NULL((void*)0);
1310 } else {
1311 curr->prev->next = curr->next;
1312 if (curr->next) {
1313 curr->next->prev = curr->prev;
1314 }
1315 }
1316 wake_ctx->next = NULL((void*)0);
1317 wake_ctx->prev = NULL((void*)0);
1318 if (LBM_IS_STATE_TIMEOUT(curr->state)(curr->state & ((uint32_t)2u | (uint32_t)16u))) {
1319 mailbox_add_mail(wake_ctx, ENC_SYM_TIMEOUT(((0xA) << 4) | 0x00000000u));
1320 wake_ctx->r = ENC_SYM_TIMEOUT(((0xA) << 4) | 0x00000000u);
1321 }
1322 wake_ctx->state = LBM_THREAD_STATE_READY(uint32_t)0u;
1323 enqueue_ctx_nm(&queue, wake_ctx);
1324 }
1325 }
1326 curr = next;
1327 }
1328}
1329
1330static void yield_ctx(lbm_uint sleep_us) {
1331 if (is_atomic) atomic_error();
1332 ctx_running->timestamp = lbm_timestamp();
1333 ctx_running->sleep_us = sleep_us;
1334 ctx_running->state = LBM_THREAD_STATE_SLEEPING(uint32_t)4u;
1335 ctx_running->r = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
1336 ctx_running->app_cont = true1;
1337 enqueue_ctx(&blocked,ctx_running);
1338 ctx_running = NULL((void*)0);
1339}
1340
1341static lbm_cid lbm_create_ctx_parent(lbm_value program, lbm_value env, lbm_uint stack_size, lbm_cid parent, uint32_t context_flags, char *name) {
1342
1343 if (!lbm_is_cons(program)) return -1;
1344
1345 eval_context_t *ctx = NULL((void*)0);
1346#ifdef LBM_ALWAYS_GC
1347 {
1348 lbm_uint roots[2] = {program, env};
1349 lbm_gc_mark_roots(roots, 2);
1350 gc();
1351 }
1352#endif
1353 ctx = (eval_context_t*)lbm_malloc(sizeof(eval_context_t));
1354 if (ctx == NULL((void*)0)) {
1355 lbm_uint roots[2] = {program, env};
1356 lbm_gc_mark_roots(roots, 2);
1357 gc();
1358 ctx = (eval_context_t*)lbm_malloc(sizeof(eval_context_t));
1359 }
1360 if (ctx == NULL((void*)0)) return -1;
1361#ifdef LBM_ALWAYS_GC
1362 {
1363 lbm_uint roots[2] = {program, env};
1364 lbm_gc_mark_roots(roots, 2);
1365 gc();
1366 }
1367#endif
1368 if (!lbm_stack_allocate(&ctx->K, stack_size)) {
1369 lbm_uint roots[2] = {program, env};
1370 lbm_gc_mark_roots(roots, 2);
1371 gc();
1372 if (!lbm_stack_allocate(&ctx->K, stack_size)) {
1373 lbm_memory_free((lbm_uint*)ctx);
1374 return -1;
1375 }
1376 }
1377
1378 lbm_value *mailbox = NULL((void*)0);
1379#ifdef LBM_ALWAYS_GC
1380 {
1381 lbm_uint roots[2] = {program, env};
1382 lbm_gc_mark_roots(roots, 2);
1383 gc();
1384 }
1385#endif
1386 mailbox = (lbm_value*)lbm_memory_allocate(EVAL_CPS_DEFAULT_MAILBOX_SIZE10);
1387 if (mailbox == NULL((void*)0)) {
1388 lbm_value roots[2] = {program, env};
1389 lbm_gc_mark_roots(roots,2);
1390 gc();
1391 mailbox = (lbm_value *)lbm_memory_allocate(EVAL_CPS_DEFAULT_MAILBOX_SIZE10);
1392 }
1393 if (mailbox == NULL((void*)0)) {
1394 lbm_stack_free(&ctx->K);
1395 lbm_memory_free((lbm_uint*)ctx);
1396 return -1;
1397 }
1398
1399 // TODO: Limit names to 19 chars + 1 char for 0? (or something similar).
1400 if (name) {
1401 lbm_uint name_len = strlen(name) + 1;
1402#ifdef LBM_ALWAYS_GC
1403 {
1404 lbm_uint roots[2] = {program, env};
1405 lbm_gc_mark_roots(roots, 2);
1406 gc();
1407 }
1408#endif
1409 ctx->name = lbm_malloc(name_len);
1410 if (ctx->name == NULL((void*)0)) {
1411 lbm_value roots[2] = {program, env};
1412 lbm_gc_mark_roots(roots, 2);
1413 gc();
1414 ctx->name = lbm_malloc(name_len);
1415 }
1416 if (ctx->name == NULL((void*)0)) {
1417 lbm_stack_free(&ctx->K);
1418 lbm_memory_free((lbm_uint*)mailbox);
1419 lbm_memory_free((lbm_uint*)ctx);
1420 return -1;
1421 }
1422 memcpy(ctx->name, name, name_len);
1423 } else {
1424 ctx->name = NULL((void*)0);
1425 }
1426
1427 lbm_int cid = lbm_memory_address_to_ix((lbm_uint*)ctx);
1428
1429 ctx->program = lbm_cdr(program);
1430 ctx->curr_exp = lbm_car(program);
1431 ctx->curr_env = env;
1432 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
1433 ctx->error_reason = NULL((void*)0);
1434 ctx->mailbox = mailbox;
1435 ctx->mailbox_size = EVAL_CPS_DEFAULT_MAILBOX_SIZE10;
1436 ctx->flags = context_flags;
1437 ctx->num_mail = 0;
1438 ctx->app_cont = false0;
1439 ctx->timestamp = 0;
1440 ctx->sleep_us = 0;
1441 ctx->state = LBM_THREAD_STATE_READY(uint32_t)0u;
1442 ctx->prev = NULL((void*)0);
1443 ctx->next = NULL((void*)0);
1444
1445 ctx->row0 = -1;
1446 ctx->row1 = -1;
1447 ctx->reader_stream = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
1448
1449 ctx->id = cid;
1450 ctx->parent = parent;
1451
1452 if (!lbm_push(&ctx->K, DONE(((0) << 2) | 0xF8000001u))) {
1453 lbm_memory_free((lbm_uint*)ctx->mailbox);
1454 lbm_stack_free(&ctx->K);
1455 lbm_memory_free((lbm_uint*)ctx);
1456 return -1;
1457 }
1458
1459 enqueue_ctx(&queue,ctx);
1460
1461 return ctx->id;
1462}
1463
1464lbm_cid lbm_create_ctx(lbm_value program, lbm_value env, lbm_uint stack_size, char *name) {
1465 // Creates a parentless context.
1466 return lbm_create_ctx_parent(program,
1467 env,
1468 stack_size,
1469 -1,
1470 EVAL_CPS_CONTEXT_FLAG_NOTHING(uint32_t)0x00,
1471 name);
1472}
1473
1474bool_Bool lbm_mailbox_change_size(eval_context_t *ctx, lbm_uint new_size) {
1475
1476 lbm_value *mailbox = NULL((void*)0);
1477#ifdef LBM_ALWAYS_GC
1478 gc();
1479#endif
1480 mailbox = (lbm_value*)lbm_memory_allocate(new_size);
1481 if (mailbox == NULL((void*)0)) {
1482 gc();
1483 mailbox = (lbm_value *)lbm_memory_allocate(new_size);
1484 }
1485 if (mailbox == NULL((void*)0)) {
1486 return false0;
1487 }
1488
1489 for (lbm_uint i = 0; i < ctx->num_mail; i ++ ) {
1490 mailbox[i] = ctx->mailbox[i];
1491 }
1492 lbm_memory_free(ctx->mailbox);
1493 ctx->mailbox = mailbox;
1494 ctx->mailbox_size = (uint32_t)new_size;
1495 return true1;
1496}
1497
1498static void mailbox_remove_mail(eval_context_t *ctx, lbm_uint ix) {
1499
1500 for (lbm_uint i = ix; i < ctx->num_mail-1; i ++) {
1501 ctx->mailbox[i] = ctx->mailbox[i+1];
1502 }
1503 ctx->num_mail --;
1504}
1505
1506static void mailbox_add_mail(eval_context_t *ctx, lbm_value mail) {
1507
1508 if (ctx->num_mail >= ctx->mailbox_size) {
1509 mailbox_remove_mail(ctx, 0);
1510 }
1511
1512 ctx->mailbox[ctx->num_mail] = mail;
1513 ctx->num_mail ++;
1514}
1515
1516/**************************************************************
1517 * Advance execution to the next expression in the program.
1518 * Assumes programs are not malformed. Apply_eval_program
1519 * ensures programs are lists ending in nil. The reader
1520 * ensures this likewise.
1521 *************************************************************/
1522static void advance_ctx(eval_context_t *ctx) {
1523 if (ctx->program) { // fast not-nil check, assume cons if not nil.
1524 stack_reserve(ctx, 1)[0] = DONE(((0) << 2) | 0xF8000001u);
1525 lbm_cons_t *cell = lbm_ref_cell(ctx->program);
1526 ctx->curr_exp = cell->car;
1527 ctx->program = cell->cdr;
1528 ctx->curr_env = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
1529 } else {
1530 if (ctx_running == ctx) { // This should always be the case because of odd historical reasons.
1531 ok_ctx();
1532 }
1533 }
1534}
1535
1536bool_Bool lbm_unblock_ctx(lbm_cid cid, lbm_flat_value_t *fv) {
1537 return event_internal(LBM_EVENT_UNBLOCK_CTX, (lbm_uint)cid, (lbm_uint)fv->buf, fv->buf_size);
1538}
1539
1540bool_Bool lbm_unblock_ctx_r(lbm_cid cid) {
1541 lbm_mutex_lock(&blocking_extension_mutex);
1542 bool_Bool r = false0;
1543 eval_context_t *found = NULL((void*)0);
1544 lbm_mutex_lock(&qmutex);
1545 found = lookup_ctx_nm(&blocked, cid);
1546 if (found && (LBM_IS_STATE_UNBLOCKABLE(found->state)(found->state & ((uint32_t)1u | (uint32_t)2u)))) {
1547 unlink_ctx_nm(&blocked,found);
1548 found->state = LBM_THREAD_STATE_READY(uint32_t)0u;
1549 enqueue_ctx_nm(&queue,found);
1550 r = true1;
1551 }
1552 lbm_mutex_unlock(&qmutex);
1553 lbm_mutex_unlock(&blocking_extension_mutex);
1554 return r;
1555}
1556
1557// unblock unboxed is also safe for rmbr:ed things.
1558// TODO: What happens if we unblock and the value is "merror"
1559bool_Bool lbm_unblock_ctx_unboxed(lbm_cid cid, lbm_value unboxed) {
1560 lbm_mutex_lock(&blocking_extension_mutex);
1561 bool_Bool r = false0;
1562 eval_context_t *found = NULL((void*)0);
1563 lbm_mutex_lock(&qmutex);
1564 found = lookup_ctx_nm(&blocked, cid);
1565 if (found && (LBM_IS_STATE_UNBLOCKABLE(found->state)(found->state & ((uint32_t)1u | (uint32_t)2u)))) {
1566 unlink_ctx_nm(&blocked,found);
1567 found->r = unboxed;
1568 if (lbm_is_error(unboxed)) {
1569 get_stack_ptr(found, 1)[0] = TERMINATE(((25) << 2) | 0xF8000001u); // replace TOS
1570 found->app_cont = true1;
1571 }
1572 found->state = LBM_THREAD_STATE_READY(uint32_t)0u;
1573 enqueue_ctx_nm(&queue,found);
1574 r = true1;
1575 }
1576 lbm_mutex_unlock(&qmutex);
1577 lbm_mutex_unlock(&blocking_extension_mutex);
1578 return r;
1579}
1580
1581static bool_Bool lbm_block_ctx_base(bool_Bool timeout, float t_s) {
1582 lbm_mutex_lock(&blocking_extension_mutex);
1583 blocking_extension = true1;
1584 if (timeout) {
1585 blocking_extension_timeout_us = S_TO_US(t_s)(lbm_uint)((t_s) * 1000000);
1586 blocking_extension_timeout = true1;
1587 } else {
1588 blocking_extension_timeout = false0;
1589 }
1590 return true1;
1591}
1592
1593void lbm_block_ctx_from_extension_timeout(float s) {
1594 lbm_block_ctx_base(true1, s);
1595}
1596
1597void lbm_block_ctx_from_extension(void) {
1598 lbm_block_ctx_base(false0, 0);
1599}
1600
1601// todo: May need to pop rmbrs from stack, if present.
1602// Suspect that the letting the discard cont run is really not a problem.
1603// Either way will be quite confusing what happens to allocated things when undoing block.
1604void lbm_undo_block_ctx_from_extension(void) {
1605 blocking_extension = false0;
1606 blocking_extension_timeout_us = 0;
1607 blocking_extension_timeout = false0;
1608 lbm_mutex_unlock(&blocking_extension_mutex);
1609}
1610
1611// TODO: very similar iteration patterns.
1612// Try to break out common part from free_space and from find_and_send
1613/** mailbox_free_space_for_cid is used to get the available
1614 * space in a given context's mailbox.
1615 */
1616static uint32_t lbm_mailbox_free_space_for_cid(lbm_cid cid) {
1617 eval_context_t *found = NULL((void*)0);
1618 uint32_t res = 0;
1619
1620 lbm_mutex_lock(&qmutex);
1621
1622 found = lookup_ctx_nm(&blocked, cid);
1623 if (!found) {
1624 found = lookup_ctx_nm(&queue, cid);
1625 }
1626 if (!found && ctx_running && ctx_running->id == cid) {
1627 found = ctx_running;
1628 }
1629
1630 if (found) {
1631 res = found->mailbox_size - found->num_mail;
1632 }
1633
1634 lbm_mutex_unlock(&qmutex);
1635
1636 return res;
1637}
1638
1639typedef struct {
1640 bool_Bool by_name;
1641 lbm_uint name_len;
1642 union {
1643 char *name;
1644 lbm_cid cid;
1645 } u;
1646} find_receiver_t;
1647
1648bool_Bool find_receiver_and_send(find_receiver_t c, lbm_value msg) {
1649 lbm_mutex_lock(&qmutex);
1650 eval_context_t *found = NULL((void*)0);
1651 int res = true1;
1652
1653 if (c.by_name) {
1654 found = lookup_ctx_name_nm(&blocked, c.u.name, c.name_len);
1655 } else {
1656 found = lookup_ctx_nm(&blocked, c.u.cid);
1657 }
1658 if (found) {
1659 if (LBM_IS_STATE_RECV(found->state)(found->state & ((uint32_t)8u | (uint32_t)16u))) { // only if unblock receivers here.
1660 unlink_ctx_nm(&blocked,found);
1661 found->state = LBM_THREAD_STATE_READY(uint32_t)0u;
1662 enqueue_ctx_nm(&queue,found);
1663 }
1664 mailbox_add_mail(found, msg);
1665 goto find_receiver_end;
1666 }
1667
1668 if (c.by_name) {
1669 found = lookup_ctx_name_nm(&queue, c.u.name, c.name_len);
1670 } else {
1671 found = lookup_ctx_nm(&queue, c.u.cid);
1672 }
1673 if (found) {
1674 mailbox_add_mail(found, msg);
1675 goto find_receiver_end;
1676 }
1677
1678 /* check the current context */
1679 if (c.by_name) {
1680 if (ctx_running && ctx_running->name && strncmp(ctx_running->name, c.u.name, c.name_len) == 0) {
1681 mailbox_add_mail(ctx_running, msg);
1682 goto find_receiver_end;
1683 }
1684 } else {
1685 if (ctx_running && ctx_running->id == c.u.cid) {
1686 mailbox_add_mail(ctx_running, msg);
1687 goto find_receiver_end;
1688 }
1689 }
1690 res = false0;
1691 find_receiver_end:
1692 lbm_mutex_unlock(&qmutex);
1693 return res;
1694}
1695/** find_receiver_and_send is used for message passing where
1696 * the semantics is that the oldest message is dropped if the
1697 * receiver mailbox is full.
1698 */
1699bool_Bool lbm_find_receiver_and_send(lbm_cid cid, lbm_value msg) {
1700 find_receiver_t c;
1701 c.u.cid = cid;
1702 c.by_name = false0;
1703 return find_receiver_and_send(c, msg);
1704}
1705// a match binder looks like (? x) or (? _) for example.
1706// It is a list of two elements where the first is a ? and the second is a symbol.
1707static inline lbm_value get_match_binder_variable(lbm_value exp) {
1708 lbm_value var = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // 0 false
1709 if (lbm_is_cons(exp)) {
1710 lbm_cons_t *e_cell = lbm_ref_cell(exp);
1711 lbm_value bt = e_cell->car;
1712 if (bt == ENC_SYM_MATCH_ANY(((0x41) << 4) | 0x00000000u) && lbm_is_cons(e_cell->cdr)) {
1713 var = lbm_ref_cell(e_cell->cdr)->car;
1714 }
1715 }
1716 return var;
1717}
1718
1719/* Pattern matching is currently implemented as a recursive
1720 function and make use of stack relative to the size of
1721 expressions that are being matched. */
1722static bool_Bool match(lbm_value p, lbm_value e, lbm_value *env, int rlevel) {
1723 if (rlevel >= LBM_MAX_C_RECURSION200) return false0;
1724 bool_Bool r;
1725 match_quickpath:
1726 r = false0;
Value stored to 'r' is never read
1727 lbm_value var = get_match_binder_variable(p);
1728 if (var) {
1729#ifdef LBM_ALWAYS_GC
1730 lbm_gc_mark_phase(*env);
1731 gc();
1732#endif
1733 lbm_value ls = lbm_heap_allocate_list_init(2, var, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
1734 if (!lbm_is_ptr(ls)) {
1735 lbm_gc_mark_phase(*env);
1736 gc();
1737 ls = lbm_heap_allocate_list_init(2, var, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
1738 if (!lbm_is_ptr(ls)) {
1739 ERROR_CTX(ls)error_ctx(ls);
1740 }
1741 }
1742 lbm_value c1 = ls;
1743 lbm_value c2 = lbm_cdr(ls);
1744 lbm_set_cdr(c1, e);
1745 lbm_set_car_and_cdr(c2, c1, *env);
1746 *env = c2;
1747 r = true1;
1748 } else if (lbm_is_symbol(p)) {
1749 if (p == ENC_SYM_DONTCARE(((0x9) << 4) | 0x00000000u)) r = true1;
1750 else r = (p == e);
1751 } else if (lbm_is_cons(p) && lbm_is_cons(e) ) {
1752 lbm_cons_t *p_cell = lbm_ref_cell(p);
1753 lbm_cons_t *e_cell = lbm_ref_cell(e);
1754 lbm_value headp = p_cell->car;
1755 lbm_value tailp = p_cell->cdr;
1756 lbm_value heade = e_cell->car;
1757 lbm_value taile = e_cell->cdr;
1758 if (match(headp, heade, env, rlevel+1)) {
1759 p = tailp;
1760 e = taile;
1761 goto match_quickpath;
1762 }
1763 r = false0;
1764 } else {
1765 // TODO: Think about this.
1766 // may be better to pass rlevel here.
1767 r = struct_eq(p, e, 0);
1768 }
1769 return r;
1770}
1771
1772// Find match is not very picky about syntax.
1773// A completely malformed recv form is most likely to
1774// just return no_match.
1775static int find_match(lbm_value plist, lbm_value *earr, lbm_uint num, lbm_value *e, lbm_value *env) {
1776 // A pattern list is a list of pattern, expression lists.
1777 // ( (p1 e1) (p2 e2) ... (pn en))
1778 lbm_value curr_p = plist;
1779 int n = 0;
1780 for (int i = 0; i < (int)num; i ++ ) {
1781 lbm_value curr_e = earr[i];
1782 while (lbm_is_cons(curr_p)) {
1783
1784 lbm_value curr = lbm_ref_cell(curr_p)->car;
1785 lbm_value p0, p1, p2;
1786 EXTRACT(curr, p0)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p0 = _cell->car; curr = _cell->cdr; } else { p0
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
1787 EXTRACT(curr, p1)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p1 = _cell->car; curr = _cell->cdr; } else { p1
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
1788 EXTRACT_NO_ADVANCE(curr, p2)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p2 = _cell->car; } else { p2 = (((0x0) << 4)
| 0x00000000u); } } while (0)
;
1789 if (!lbm_is_symbol_nil(p2)) { // A rare syntax check. maybe drop?
1790 lbm_set_error_reason("Incorrect pattern format for recv");
1791 ERROR_AT_CTX(ENC_SYM_EERROR,curr)error_at_ctx((((0x22) << 4) | 0x00000000u), curr);
1792 }
1793 if (match(p0, curr_e, env, 0)) {
1794 *e = p1;
1795 return n;
1796 }
1797 curr_p = lbm_ref_cell(curr_p)->cdr;
1798 }
1799 curr_p = plist; /* search all patterns against next exp */
1800 n ++;
1801 }
1802 return FM_NO_MATCH-2;
1803}
1804
1805/****************************************************/
1806/* Garbage collection */
1807
1808static void mark_context(eval_context_t *ctx, void *arg1, void *arg2) {
1809 (void) arg1;
1810 (void) arg2;
1811 lbm_value roots[4] = {ctx->curr_exp, ctx->program, ctx->r, ctx->reader_stream};
1812 lbm_gc_mark_env(ctx->curr_env);
1813 lbm_gc_mark_roots(roots, 4);
1814 lbm_gc_mark_roots(ctx->mailbox, ctx->num_mail);
1815 lbm_gc_mark_continuation_stack(ctx->K.data, ctx->K.sp);
1816}
1817
1818static int gc(void) {
1819 if (ctx_running) {
1820 ctx_running->state = ctx_running->state | LBM_THREAD_STATE_GC_BIT(uint32_t)(1u << 31);
1821 }
1822
1823 gc_requested = false0;
1824 lbm_gc_state_inc();
1825
1826 // The freelist should generally be NIL when GC runs.
1827 lbm_nil_freelist();
1828 lbm_value *env = lbm_get_global_env();
1829 for (int i = 0; i < GLOBAL_ENV_ROOTS32; i ++) {
1830 lbm_gc_mark_env(env[i]);
1831 }
1832
1833 lbm_mutex_lock(&qmutex); // Lock the queues.
1834 // Any concurrent messing with the queues
1835 // while doing GC cannot possibly be good.
1836 queue_iterator_nm(&queue, mark_context, NULL((void*)0), NULL((void*)0));
1837 queue_iterator_nm(&blocked, mark_context, NULL((void*)0), NULL((void*)0));
1838
1839 if (ctx_running) {
1840 mark_context(ctx_running, NULL((void*)0), NULL((void*)0));
1841 }
1842 lbm_mutex_unlock(&qmutex);
1843
1844 int r = lbm_gc_sweep_phase();
1845 lbm_heap_new_freelist_length();
1846 lbm_memory_update_min_free();
1847
1848 if (ctx_running) {
1849 ctx_running->state = ctx_running->state & ~LBM_THREAD_STATE_GC_BIT(uint32_t)(1u << 31);
1850 }
1851 return r;
1852}
1853
1854int lbm_perform_gc(void) {
1855 return gc();
1856}
1857
1858/****************************************************/
1859/* Evaluation functions */
1860
1861
1862/* eval_symbol
1863 * There are multiple possible ways a symbol could be "bound".
1864 * 1. there is a mapping symbol -> value in the global env.
1865 * 2. there is a mapping symbol -> value in the local env (ctx->curr_env).
1866 * 3. there is a dynamically loadable value associated with the symbol.
1867 * 4. The symbol is special or associated with an extension,
1868 * in which case it evaluates to itself.
1869 *
1870 * Syntax: any-symbol
1871 *
1872 * Expects: T(ctx->curr_exp) == symbol
1873 *
1874 * cases: 1,2,4
1875 * Produces:
1876 * ctx->r = value bound to symbol
1877 * ctx->app_cont = true
1878 *
1879 * cases: 3
1880 * Produces:
1881 * sp = sp+3
1882 * s[sp-3] = ctx->curr_exp (the symbol to evaluate)
1883 * s[sp-2] = ctx->curr_env
1884 * s[sp-1] = RESUME
1885 * ctx->curr_exp <- read_and_evaluate(dynamic value)
1886 * ctx->curr_env <- NIL
1887 */
1888static void eval_symbol(eval_context_t *ctx) {
1889 lbm_uint s = lbm_dec_sym(ctx->curr_exp);
1890 if (s >= RUNTIME_SYMBOLS_START0x40000) {
1891 lbm_value res = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
1892 if (lbm_env_lookup_b(&res, ctx->curr_exp, ctx->curr_env) ||
1893 lbm_global_env_lookup(&res, ctx->curr_exp)) {
1894 ctx->r = res;
1895 ctx->app_cont = true1;
1896 return;
1897 }
1898 // Dynamic load attempt
1899 // Only symbols of kind RUNTIME can be dynamically loaded.
1900 const char *sym_str = lbm_get_name_by_symbol(s);
1901 const char *code_str = NULL((void*)0);
1902 if (!dynamic_load_callback(sym_str, &code_str)) {
1903 ERROR_AT_CTX(ENC_SYM_NOT_FOUND, ctx->curr_exp)error_at_ctx((((0x24) << 4) | 0x00000000u), ctx->curr_exp
)
;
1904 }
1905 lbm_value *sptr = stack_reserve(ctx, 3);
1906 sptr[0] = ctx->curr_exp;
1907 sptr[1] = ctx->curr_env;
1908 sptr[2] = RESUME(((12) << 2) | 0xF8000001u);
1909
1910 lbm_value chan = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
1911#ifdef LBM_ALWAYS_GC
1912 gc();
1913#endif
1914 if (!create_string_channel((char *)code_str, &chan, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u))) {
1915 gc();
1916 if (!create_string_channel((char *)code_str, &chan, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u))) {
1917 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
1918 }
1919 }
1920
1921 // Here, chan has either been assigned or execution has terminated.
1922
1923 lbm_value loader;
1924 WITH_GC_RMBR_1(loader, lbm_heap_allocate_list_init(2,(loader) = (lbm_heap_allocate_list_init(2, (((0x30001) <<
4) | 0x00000000u), chan)); if (lbm_is_symbol_merror((loader)
)) { lbm_gc_mark_phase(chan); gc(); (loader) = (lbm_heap_allocate_list_init
(2, (((0x30001) << 4) | 0x00000000u), chan)); if (lbm_is_symbol_merror
((loader))) { error_ctx((((0x23) << 4) | 0x00000000u));
} }
1925 ENC_SYM_READ,(loader) = (lbm_heap_allocate_list_init(2, (((0x30001) <<
4) | 0x00000000u), chan)); if (lbm_is_symbol_merror((loader)
)) { lbm_gc_mark_phase(chan); gc(); (loader) = (lbm_heap_allocate_list_init
(2, (((0x30001) << 4) | 0x00000000u), chan)); if (lbm_is_symbol_merror
((loader))) { error_ctx((((0x23) << 4) | 0x00000000u));
} }
1926 chan), chan)(loader) = (lbm_heap_allocate_list_init(2, (((0x30001) <<
4) | 0x00000000u), chan)); if (lbm_is_symbol_merror((loader)
)) { lbm_gc_mark_phase(chan); gc(); (loader) = (lbm_heap_allocate_list_init
(2, (((0x30001) << 4) | 0x00000000u), chan)); if (lbm_is_symbol_merror
((loader))) { error_ctx((((0x23) << 4) | 0x00000000u));
} }
;
1927 lbm_value evaluator;
1928 WITH_GC_RMBR_1(evaluator, lbm_heap_allocate_list_init(2,(evaluator) = (lbm_heap_allocate_list_init(2, (((0x30008) <<
4) | 0x00000000u), loader)); if (lbm_is_symbol_merror((evaluator
))) { lbm_gc_mark_phase(loader); gc(); (evaluator) = (lbm_heap_allocate_list_init
(2, (((0x30008) << 4) | 0x00000000u), loader)); if (lbm_is_symbol_merror
((evaluator))) { error_ctx((((0x23) << 4) | 0x00000000u
)); } }
1929 ENC_SYM_EVAL,(evaluator) = (lbm_heap_allocate_list_init(2, (((0x30008) <<
4) | 0x00000000u), loader)); if (lbm_is_symbol_merror((evaluator
))) { lbm_gc_mark_phase(loader); gc(); (evaluator) = (lbm_heap_allocate_list_init
(2, (((0x30008) << 4) | 0x00000000u), loader)); if (lbm_is_symbol_merror
((evaluator))) { error_ctx((((0x23) << 4) | 0x00000000u
)); } }
1930 loader), loader)(evaluator) = (lbm_heap_allocate_list_init(2, (((0x30008) <<
4) | 0x00000000u), loader)); if (lbm_is_symbol_merror((evaluator
))) { lbm_gc_mark_phase(loader); gc(); (evaluator) = (lbm_heap_allocate_list_init
(2, (((0x30008) << 4) | 0x00000000u), loader)); if (lbm_is_symbol_merror
((evaluator))) { error_ctx((((0x23) << 4) | 0x00000000u
)); } }
;
1931 ctx->curr_exp = evaluator;
1932 ctx->curr_env = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // dynamics should be evaluable in empty local env
1933 } else {
1934 //special symbols and extensions can be handled the same way.
1935 ctx->r = ctx->curr_exp;
1936 ctx->app_cont = true1;
1937 }
1938}
1939
1940// (quote e) => e
1941static void eval_quote(eval_context_t *ctx) {
1942 ctx->r = get_cadr(ctx->curr_exp);
1943 ctx->app_cont = true1;
1944}
1945
1946// a => a
1947static void eval_selfevaluating(eval_context_t *ctx) {
1948 ctx->r = ctx->curr_exp;
1949 ctx->app_cont = true1;
1950}
1951
1952// (progn e1 ... en)
1953static void eval_progn(eval_context_t *ctx) {
1954 lbm_value exps = get_cdr(ctx->curr_exp);
1955
1956 if (lbm_is_cons(exps)) {
1957 lbm_cons_t *cell = lbm_ref_cell(exps); // already checked that it's cons.
1958 ctx->curr_exp = cell->car;
1959 if (lbm_is_cons(cell->cdr)) { // malformed progn not ending in nil is tolerated
1960 lbm_uint *sptr = stack_reserve(ctx, 4);
1961 sptr[0] = ctx->curr_env; // env to restore between expressions in progn
1962 sptr[1] = lbm_enc_u(0); // Has env been copied (needed for progn local bindings)
1963 sptr[2] = cell->cdr; // Requirement: sptr[2] is a cons.
1964 sptr[3] = PROGN_REST(((4) << 2) | 0xF8000001u);
1965 }
1966 } else if (lbm_is_symbol_nil(exps)) { // Empty progn is nil
1967 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
1968 ctx->app_cont = true1;
1969 } else {
1970 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
1971 }
1972}
1973
1974// (atomic e1 ... en)
1975static void eval_atomic(eval_context_t *ctx) {
1976 if (is_atomic) atomic_error();
1977 stack_reserve(ctx, 1)[0] = EXIT_ATOMIC(((14) << 2) | 0xF8000001u);
1978 is_atomic = true1;
1979 eval_progn(ctx);
1980}
1981
1982// (call-cc (lambda (k) .... ))
1983static void eval_callcc(eval_context_t *ctx) {
1984 lbm_value cont_array;
1985 lbm_uint *sptr0 = stack_reserve(ctx, 1);
1986 sptr0[0] = is_atomic ? ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u) : ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
1987#ifdef LBM_ALWAYS_GC
1988 gc();
1989#endif
1990 if (!lbm_heap_allocate_lisp_array(&cont_array, ctx->K.sp)) {
1991 gc();
1992 lbm_heap_allocate_lisp_array(&cont_array, ctx->K.sp);
1993 }
1994 if (lbm_is_ptr(cont_array)) {
1995 lbm_array_header_t *arr = assume_array(cont_array);
1996 // sp is small and sp*sizeof(lbm_uint) will now overflow.
1997 memcpy(arr->data, ctx->K.data, ctx->K.sp * sizeof(lbm_uint));
1998 // The stored stack contains the is_atomic flag.
1999 // This flag is overwritten in the following execution path.
2000
2001 lbm_value acont = cons_with_gc(ENC_SYM_CONT(((0x10E) << 4) | 0x00000000u), cont_array, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2002 lbm_value arg_list = cons_with_gc(acont, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2003 // Go directly into application evaluation without passing go
2004 lbm_uint *sptr = stack_reserve(ctx, 2);
2005 sptr0[0] = ctx->curr_env; // overwrites is_atomic in this execution path
2006 sptr[0] = arg_list;
2007 sptr[1] = APPLICATION_START(((10) << 2) | 0xF8000001u);
2008 ctx->curr_exp = get_cadr(ctx->curr_exp);
2009 } else {
2010 // failed to create continuation array.
2011 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
2012 }
2013}
2014
2015// (call-cc-unsafe (lambda (k) ... ))
2016// cc-unsafe: continuation should not be bound to any global directly or indirectly.
2017// invoking the continuation must check that target SP holds a continuation that
2018// can be applied using app_cont, otherwise error. The continuation need not be correct
2019// in case user globally bound the continuation, but it may rule out disastrous failure.
2020static void eval_call_cc_unsafe(eval_context_t *ctx) {
2021 lbm_uint sp = ctx->K.sp;
2022 // The stored stack contains the is_atomic flag.
2023 // This flag is overwritten in the following execution path.
2024 lbm_value acont;
2025 WITH_GC(acont, lbm_heap_allocate_list_init(3,(acont) = (lbm_heap_allocate_list_init(3, (((0x118) << 4
) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic ? (((0x2)
<< 4) | 0x00000000u) : (((0x0) << 4) | 0x00000000u
), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { gc(); (acont) = (lbm_heap_allocate_list_init(3, (
((0x118) << 4) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic
? (((0x2) << 4) | 0x00000000u) : (((0x0) << 4) |
0x00000000u), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { error_ctx((((0x23) << 4) | 0x00000000u)); }
}
2026 ENC_SYM_CONT_SP,(acont) = (lbm_heap_allocate_list_init(3, (((0x118) << 4
) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic ? (((0x2)
<< 4) | 0x00000000u) : (((0x0) << 4) | 0x00000000u
), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { gc(); (acont) = (lbm_heap_allocate_list_init(3, (
((0x118) << 4) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic
? (((0x2) << 4) | 0x00000000u) : (((0x0) << 4) |
0x00000000u), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { error_ctx((((0x23) << 4) | 0x00000000u)); }
}
2027 lbm_enc_i((int32_t)sp),(acont) = (lbm_heap_allocate_list_init(3, (((0x118) << 4
) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic ? (((0x2)
<< 4) | 0x00000000u) : (((0x0) << 4) | 0x00000000u
), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { gc(); (acont) = (lbm_heap_allocate_list_init(3, (
((0x118) << 4) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic
? (((0x2) << 4) | 0x00000000u) : (((0x0) << 4) |
0x00000000u), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { error_ctx((((0x23) << 4) | 0x00000000u)); }
}
2028 is_atomic ? ENC_SYM_TRUE : ENC_SYM_NIL, ENC_SYM_NIL))(acont) = (lbm_heap_allocate_list_init(3, (((0x118) << 4
) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic ? (((0x2)
<< 4) | 0x00000000u) : (((0x0) << 4) | 0x00000000u
), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { gc(); (acont) = (lbm_heap_allocate_list_init(3, (
((0x118) << 4) | 0x00000000u), lbm_enc_i((int32_t)sp), is_atomic
? (((0x2) << 4) | 0x00000000u) : (((0x0) << 4) |
0x00000000u), (((0x0) << 4) | 0x00000000u))); if (lbm_is_symbol_merror
((acont))) { error_ctx((((0x23) << 4) | 0x00000000u)); }
}
;
2029 lbm_value arg_list = cons_with_gc(acont, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2030 // Go directly into application evaluation without passing go
2031 lbm_uint *sptr = stack_reserve(ctx, 3);
2032 sptr[0] = ctx->curr_env;
2033 sptr[1] = arg_list;
2034 sptr[2] = APPLICATION_START(((10) << 2) | 0xF8000001u);
2035 ctx->curr_exp = get_cadr(ctx->curr_exp);
2036}
2037
2038// (define sym exp)
2039static void eval_define(eval_context_t *ctx) {
2040 lbm_value pKEY, pVAL;
2041 lbm_value curr = ctx->curr_exp;
2042 DROP(curr)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); curr = _cell->cdr; } } while (0)
;
2043 EXTRACT(curr, pKEY)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); pKEY = _cell->car; curr = _cell->cdr; } else { pKEY
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
2044 EXTRACT(curr, pVAL)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); pVAL = _cell->car; curr = _cell->cdr; } else { pVAL
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
2045 lbm_value rest = curr;
2046 lbm_uint *sptr = stack_reserve(ctx, 2);
2047 if (lbm_is_symbol(pKEY) && lbm_is_symbol_nil(rest)) {
2048 lbm_uint sym_val = lbm_dec_sym(pKEY);
2049 sptr[0] = pKEY;
2050 if (sym_val >= RUNTIME_SYMBOLS_START0x40000) {
2051 sptr[1] = SET_GLOBAL_ENV(((1) << 2) | 0xF8000001u);
2052 if (ctx->flags & EVAL_CPS_CONTEXT_FLAG_CONST(uint32_t)0x02) {
2053 stack_reserve(ctx, 1)[0] = MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u);
2054 }
2055 ctx->curr_exp = pVAL;
2056 return;
2057 } else {
2058 lbm_set_error_reason((char*)lbm_error_str_built_in);
2059 }
2060 }
2061 ERROR_AT_CTX(ENC_SYM_EERROR, ctx->curr_exp)error_at_ctx((((0x22) << 4) | 0x00000000u), ctx->curr_exp
)
;
2062}
2063
2064/* Eval lambda is cheating, a lot! It does this
2065 for performance reasons. The cheats are that
2066 1. When closure is created, a reference to the local env
2067 in which the lambda was evaluated is added to the closure.
2068 Ideally it should have created a list of free variables in the function
2069 and then looked up the values of these creating a new environment.
2070 2. The global env is considered global constant. As there is no copying
2071 of environment bindings into the closure, undefine may break closures.
2072
2073 some obscure programs such as test_setq_local_closure.lisp does not
2074 work properly due to this cheating.
2075 */
2076// (lambda param-list body-exp) -> (closure param-list body-exp env)
2077static void eval_lambda(eval_context_t *ctx) {
2078#ifdef LBM_ALWAYS_GC
2079 gc();
2080#endif
2081 for (int retry = 0; retry < 2; retry ++) {
2082 if (lbm_heap_num_free() >= 4) {
2083 lbm_value clo = lbm_heap_state.freelist;
2084 lbm_value lam = get_cdr(ctx->curr_exp);
2085 lbm_uint ix = lbm_dec_ptr(clo);
2086 lbm_cons_t *heap = lbm_heap_state.heap;
2087 heap[ix].car = ENC_SYM_CLOSURE(((0x10F) << 4) | 0x00000000u);
2088 ix = lbm_dec_ptr(heap[ix].cdr);
2089 get_car_and_cdr(lam, &heap[ix].car, &lam); // params
2090 ix = lbm_dec_ptr(heap[ix].cdr);
2091 get_car_and_cdr(lam, &heap[ix].car, &lam); // body
2092 ix = lbm_dec_ptr(heap[ix].cdr);
2093 heap[ix].car = ctx->curr_env;
2094 lbm_heap_state.freelist = heap[ix].cdr;
2095 heap[ix].cdr = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2096 lbm_heap_state.num_free-=4;
2097 ctx->r = clo;
2098#ifdef CLEAN_UP_CLOSURES
2099 lbm_uint sym_id = 0;
2100 if (clean_cl_env_symbol) {
2101 lbm_value tail = cons_with_gc(ctx->r, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2102 lbm_value app = cons_with_gc(clean_cl_env_symbol, tail, tail);
2103 ctx->curr_exp = app;
2104 } else if (lbm_get_symbol_by_name("clean-cl-env", &sym_id)) {
2105 clean_cl_env_symbol = lbm_enc_sym(sym_id);
2106 lbm_value tail = cons_with_gc(ctx->r, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2107 lbm_value app = cons_with_gc(clean_cl_env_symbol, tail, tail);
2108 ctx->curr_exp = app;
2109 } else {
2110 ctx->app_cont = true1;
2111 }
2112#else
2113 ctx->app_cont = true1;
2114#endif
2115 return;
2116 } else {
2117 gc();
2118 }
2119 }
2120 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
2121}
2122
2123// (if cond-expr then-expr else-expr)
2124static void eval_if(eval_context_t *ctx) {
2125 lbm_value cdr = get_cdr(ctx->curr_exp);
2126 lbm_value *sptr = stack_reserve(ctx, 3);
2127 get_car_and_cdr(cdr, &ctx->curr_exp, &sptr[0]);
2128 sptr[1] = ctx->curr_env;
2129 sptr[2] = IF(((3) << 2) | 0xF8000001u);
2130}
2131
2132// (cond (cond-expr-1 expr-1)
2133// ...
2134// (cond-expr-N expr-N))
2135static void eval_cond(eval_context_t *ctx) {
2136 lbm_value curr = ctx->curr_exp;
2137 lbm_value c1;
2138 DROP(curr)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); curr = _cell->cdr; } } while (0)
;
2139 EXTRACT(curr, c1)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); c1 = _cell->car; curr = _cell->cdr; } else { c1
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
2140 lbm_value rest_conds = curr;
2141
2142 // end recursion at (cond )
2143 if (lbm_is_symbol_nil(c1)) {
2144 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2145 ctx->app_cont = true1;
2146 } else {
2147 // Cond is one of the few places where a bit of syntax checking takes place at runtime..
2148 // Maybe dont bother?
2149 lbm_uint len = lbm_list_length(c1);
2150 if (len != 2) {
2151 lbm_set_error_reason("Incorrect syntax in cond");
2152 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2153 }
2154 lbm_value cond = c1;
2155 lbm_value ce0, ce1;
2156 EXTRACT(cond, ce0)do { if (lbm_is_ptr(cond)) { lbm_cons_t *_cell = lbm_ref_cell
(cond); ce0 = _cell->car; cond = _cell->cdr; } else { ce0
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
2157 EXTRACT_NO_ADVANCE(cond, ce1)do { if (lbm_is_ptr(cond)) { lbm_cons_t *_cell = lbm_ref_cell
(cond); ce1 = _cell->car; } else { ce1 = (((0x0) << 4
) | 0x00000000u); } } while (0)
;
2158 lbm_value rest;
2159 WITH_GC(rest, lbm_heap_allocate_list_init(2,(rest) = (lbm_heap_allocate_list_init(2, ce1, cons_with_gc(((
(0x110) << 4) | 0x00000000u), rest_conds , (((0x0) <<
4) | 0x00000000u)))); if (lbm_is_symbol_merror((rest))) { gc
(); (rest) = (lbm_heap_allocate_list_init(2, ce1, cons_with_gc
((((0x110) << 4) | 0x00000000u), rest_conds , (((0x0) <<
4) | 0x00000000u)))); if (lbm_is_symbol_merror((rest))) { error_ctx
((((0x23) << 4) | 0x00000000u)); } }
2160 ce1, // Then branch(rest) = (lbm_heap_allocate_list_init(2, ce1, cons_with_gc(((
(0x110) << 4) | 0x00000000u), rest_conds , (((0x0) <<
4) | 0x00000000u)))); if (lbm_is_symbol_merror((rest))) { gc
(); (rest) = (lbm_heap_allocate_list_init(2, ce1, cons_with_gc
((((0x110) << 4) | 0x00000000u), rest_conds , (((0x0) <<
4) | 0x00000000u)))); if (lbm_is_symbol_merror((rest))) { error_ctx
((((0x23) << 4) | 0x00000000u)); } }
2161 cons_with_gc(ENC_SYM_COND, rest_conds , ENC_SYM_NIL)))(rest) = (lbm_heap_allocate_list_init(2, ce1, cons_with_gc(((
(0x110) << 4) | 0x00000000u), rest_conds , (((0x0) <<
4) | 0x00000000u)))); if (lbm_is_symbol_merror((rest))) { gc
(); (rest) = (lbm_heap_allocate_list_init(2, ce1, cons_with_gc
((((0x110) << 4) | 0x00000000u), rest_conds , (((0x0) <<
4) | 0x00000000u)))); if (lbm_is_symbol_merror((rest))) { error_ctx
((((0x23) << 4) | 0x00000000u)); } }
;
2162 lbm_value *sptr = stack_reserve(ctx, 3);
2163 sptr[0] = rest;
2164 sptr[1] = ctx->curr_env;
2165 sptr[2] = IF(((3) << 2) | 0xF8000001u);
2166 ctx->curr_exp = ce0; //condition;
2167 }
2168}
2169
2170static void eval_app_cont(eval_context_t *ctx) {
2171 stack_drop(ctx, 1);
2172 ctx->app_cont = true1;
2173}
2174
2175// Create a named location in an environment to later receive a value.
2176// Protects env from GC, other data is the obligation of the caller.
2177static void create_binding_location(lbm_value key, lbm_value *env) {
2178 if (lbm_is_symbol(key)) { // default case
2179 if (key == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u) || key == ENC_SYM_DONTCARE(((0x9) << 4) | 0x00000000u)) return;
2180#ifdef LBM_ALWAYS_GC
2181 lbm_gc_mark_phase(*env);
2182 gc();
2183#endif
2184 lbm_value ls = lbm_heap_allocate_list_init(2,
2185 key,
2186 ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2187 if (!lbm_is_ptr(ls)) {
2188 lbm_gc_mark_phase(*env);
2189 gc();
2190 ls = lbm_heap_allocate_list_init(2,
2191 key,
2192 ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2193 if (!lbm_is_ptr(ls)) ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
2194 }
2195 lbm_value binding = ls;
2196 lbm_cons_t *ls_ref = lbm_ref_cell(ls);
2197 lbm_value new_env = ls_ref->cdr;
2198 ls_ref->cdr = ENC_SYM_PLACEHOLDER(((0x2A) << 4) | 0x00000000u); // known cons
2199 //lbm_set_cdr(binding, ENC_SYM_PLACEHOLDER);
2200 lbm_cons_t *new_env_ref = lbm_ref_cell(new_env); //known cons
2201 new_env_ref->car = binding;
2202 new_env_ref->cdr = *env;
2203 //lbm_set_car_and_cdr(new_env,binding, *env);
2204 *env = new_env;
2205 } else if (lbm_is_cons(key)) { // deconstruct case
2206 create_binding_location(lbm_ref_cell(key)->car, env);
2207 create_binding_location(lbm_ref_cell(key)->cdr, env);
2208 } else {
2209 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2210 }
2211}
2212
2213static void let_bind_values_eval(lbm_value binds, lbm_value exp, lbm_value env, eval_context_t *ctx) {
2214 if (lbm_is_cons(binds)) {
2215 // Preallocate binding locations.
2216 lbm_value curr = binds;
2217 while (lbm_is_cons(curr)) {
2218 lbm_value new_env_tmp = env;
2219 lbm_cons_t *cell = lbm_ref_cell(curr); // already checked that cons.
2220 lbm_value car_curr = cell->car;
2221 lbm_value cdr_curr = cell->cdr;
2222 lbm_value key = get_car(car_curr);
2223 create_binding_location(key, &new_env_tmp);
2224 env = new_env_tmp;
2225 curr = cdr_curr;
2226 }
2227
2228 lbm_cons_t *cell = lbm_ref_cell(binds); // already checked that cons.
2229 lbm_value car_binds = cell->car;
2230 lbm_value cdr_binds = cell->cdr;
2231 lbm_value kv0, kv1;
2232 lbm_value kv = car_binds;
2233 EXTRACT(kv, kv0)do { if (lbm_is_ptr(kv)) { lbm_cons_t *_cell = lbm_ref_cell(kv
); kv0 = _cell->car; kv = _cell->cdr; } else { kv0 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
;
2234 EXTRACT_NO_ADVANCE(kv, kv1)do { if (lbm_is_ptr(kv)) { lbm_cons_t *_cell = lbm_ref_cell(kv
); kv1 = _cell->car; } else { kv1 = (((0x0) << 4) | 0x00000000u
); } } while (0)
;
2235
2236 lbm_uint *sptr = stack_reserve(ctx, 5);
2237 sptr[0] = exp;
2238 sptr[1] = cdr_binds;
2239 sptr[2] = env;
2240 sptr[3] = kv0;
2241 sptr[4] = BIND_TO_KEY_REST(((2) << 2) | 0xF8000001u);
2242 ctx->curr_exp = kv1;
2243 ctx->curr_env = env;
2244 } else {
2245 ctx->curr_exp = exp;
2246 }
2247}
2248
2249// (var x (...)) - local binding inside of an progn
2250// var has to take, place root-level nesting within progn.
2251// (progn ... (var a 10) ...) OK!
2252// (progn ... (something (var a 10)) ... ) NOT OK!
2253/* progn stack
2254 sp-4 : env
2255 sp-3 : 0
2256 sp-2 : rest
2257 sp-1 : PROGN_REST
2258*/
2259static void eval_var(eval_context_t *ctx) {
2260 if (ctx->K.sp >= 4) { // Possibly in progn
2261 lbm_value sv = ctx->K.data[ctx->K.sp - 1];
2262 if (IS_CONTINUATION(sv)(((sv) & 0xF8000001u) == 0xF8000001u) && (sv == PROGN_REST(((4) << 2) | 0xF8000001u))) {
2263 lbm_uint sp = ctx->K.sp;
2264 lbm_uint is_copied = lbm_dec_u(ctx->K.data[sp-3]);
2265 if (is_copied == 0) {
2266 lbm_value env;
2267 WITH_GC(env, lbm_env_copy_spine(ctx->K.data[sp-4]))(env) = (lbm_env_copy_spine(ctx->K.data[sp-4])); if (lbm_is_symbol_merror
((env))) { gc(); (env) = (lbm_env_copy_spine(ctx->K.data[sp
-4])); if (lbm_is_symbol_merror((env))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
2268 ctx->K.data[sp-3] = lbm_enc_u(1);
2269 ctx->K.data[sp-4] = env;
2270 }
2271 lbm_value new_env = ctx->K.data[sp-4];
2272 lbm_value args = get_cdr(ctx->curr_exp);
2273 lbm_value key = get_car(args);
2274 create_binding_location(key, &new_env);
2275
2276 ctx->K.data[sp-4] = new_env;
2277
2278 lbm_value v_exp = get_cadr(args);
2279 lbm_value *sptr = stack_reserve(ctx, 3);
2280 sptr[0] = new_env;
2281 sptr[1] = key;
2282 sptr[2] = PROGN_VAR(((26) << 2) | 0xF8000001u);
2283 // Activating the new environment before the evaluation of the value to be bound.
2284 // This would normally shadow the existing value, but create_binding_location sets
2285 // the binding to be $placeholder, which is ignored when looking up the value.
2286 // The way closures work, the var-variable needs to be in scope during val
2287 // evaluation for a recursive closure to be possible.
2288 ctx->curr_env = new_env;
2289 ctx->curr_exp = v_exp;
2290 return;
2291 }
2292 }
2293 lbm_set_error_reason((char*)lbm_error_str_var_outside_progn);
2294 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2295}
2296
2297// (setq x (...)) - same as (set 'x (...)) or (setvar 'x (...))
2298// does not error when given incorrect number of arguments.
2299static void eval_setq(eval_context_t *ctx) {
2300 lbm_value p1, p2;
2301 lbm_value curr = ctx->curr_exp;
2302 DROP(curr)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); curr = _cell->cdr; } } while (0)
;
2303 EXTRACT(curr, p1)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p1 = _cell->car; curr = _cell->cdr; } else { p1
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
2304 EXTRACT_NO_ADVANCE(curr, p2)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p2 = _cell->car; } else { p2 = (((0x0) << 4)
| 0x00000000u); } } while (0)
;
2305 lbm_value *sptr = stack_reserve(ctx, 3);
2306 sptr[0] = ctx->curr_env;
2307 sptr[1] = p1;
2308 sptr[2] = SETQ(((27) << 2) | 0xF8000001u);
2309 ctx->curr_exp = p2;
2310}
2311
2312static void eval_move_to_flash(eval_context_t *ctx) {
2313 lbm_value args = get_cdr(ctx->curr_exp);
2314 lbm_value *sptr = stack_reserve(ctx,2);
2315 sptr[0] = args;
2316 sptr[1] = MOVE_TO_FLASH(((28) << 2) | 0xF8000001u);
2317 ctx->app_cont = true1;
2318}
2319
2320// (loop list-of-local-bindings
2321// condition-exp
2322// body-exp)
2323static void eval_loop(eval_context_t *ctx) {
2324 lbm_value env = ctx->curr_env;
2325 lbm_value p0, p1, p2;
2326 lbm_value curr = ctx->curr_exp;
2327 DROP(curr)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); curr = _cell->cdr; } } while (0)
;
2328 EXTRACT(curr,p0)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p0 = _cell->car; curr = _cell->cdr; } else { p0
= (((0x0) << 4) | 0x00000000u); } } while (0)
; // LOOP BINDS
2329 EXTRACT(curr,p1)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p1 = _cell->car; curr = _cell->cdr; } else { p1
= (((0x0) << 4) | 0x00000000u); } } while (0)
; // LOOP COND
2330 EXTRACT_NO_ADVANCE(curr,p2)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p2 = _cell->car; } else { p2 = (((0x0) << 4)
| 0x00000000u); } } while (0)
; // LOOP BODY
2331 lbm_value *sptr = stack_reserve(ctx, 4);
2332 sptr[0] = p2;
2333 sptr[1] = p1;
2334 sptr[2] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2335 sptr[3] = LOOP_ENV_PREP(((51) << 2) | 0xF8000001u);
2336 let_bind_values_eval(p0, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), env, ctx);
2337}
2338
2339/* (trap expression)
2340 *
2341 * suggested use:
2342 * (match (trap expression)
2343 * ((exit-error (? err)) (error-handler err))
2344 * ((exit-ok (? v)) (value-handler v)))
2345 */
2346static void eval_trap(eval_context_t *ctx) {
2347
2348 lbm_value expr = get_cadr(ctx->curr_exp);
2349 lbm_value retval;
2350 WITH_GC(retval, lbm_heap_allocate_list(2))(retval) = (lbm_heap_allocate_list(2)); if (lbm_is_symbol_merror
((retval))) { gc(); (retval) = (lbm_heap_allocate_list(2)); if
(lbm_is_symbol_merror((retval))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
2351 lbm_ref_cell(retval)->car = ENC_SYM_EXIT_OK(((0x3000B) << 4) | 0x00000000u);
2352 // lbm_set_car(retval, ENC_SYM_EXIT_OK); // Assume things will go well.
2353 lbm_uint *sptr = stack_reserve(ctx,3);
2354 sptr[0] = retval;
2355 sptr[1] = ctx->flags;
2356 sptr[2] = EXCEPTION_HANDLER(((45) << 2) | 0xF8000001u);
2357 ctx->flags |= EVAL_CPS_CONTEXT_FLAG_TRAP_UNROLL_RETURN(uint32_t)0x10;
2358 ctx->curr_exp = expr;
2359}
2360
2361// (let list-of-binding s
2362// body-exp)
2363static void eval_let(eval_context_t *ctx) {
2364 lbm_value env = ctx->curr_env;
2365 lbm_value p1, p2;
2366 lbm_value curr = ctx->curr_exp;
2367 DROP(curr)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); curr = _cell->cdr; } } while (0)
;
2368 EXTRACT(curr, p1)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p1 = _cell->car; curr = _cell->cdr; } else { p1
= (((0x0) << 4) | 0x00000000u); } } while (0)
;
2369 EXTRACT_NO_ADVANCE(curr, p2)do { if (lbm_is_ptr(curr)) { lbm_cons_t *_cell = lbm_ref_cell
(curr); p2 = _cell->car; } else { p2 = (((0x0) << 4)
| 0x00000000u); } } while (0)
;
2370 let_bind_values_eval(p1, p2, env, ctx);
2371}
2372
2373// (and exp0 ... expN)
2374static void eval_and(eval_context_t *ctx) {
2375 lbm_value rest = get_cdr(ctx->curr_exp);
2376 if (lbm_is_symbol_nil(rest)) {
2377 ctx->app_cont = true1;
2378 ctx->r = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
2379 } else {
2380 lbm_value *sptr = stack_reserve(ctx, 3);
2381 get_car_and_cdr(rest, &ctx->curr_exp, &sptr[1]);
2382 sptr[0] = ctx->curr_env;
2383 sptr[2] = AND(((6) << 2) | 0xF8000001u);
2384 }
2385}
2386
2387// (or exp0 ... expN)
2388static void eval_or(eval_context_t *ctx) {
2389 lbm_value rest = get_cdr(ctx->curr_exp);
2390 if (lbm_is_symbol_nil(rest)) {
2391 ctx->app_cont = true1;
2392 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2393 } else {
2394 lbm_value *sptr = stack_reserve(ctx, 3);
2395 get_car_and_cdr(rest, &ctx->curr_exp, &sptr[1]);
2396 sptr[0] = ctx->curr_env;
2397 sptr[2] = OR(((7) << 2) | 0xF8000001u);
2398 }
2399}
2400
2401// Pattern matching
2402// format:
2403// (match e (pattern body)
2404// (pattern body)
2405// ... )
2406//
2407// There can be an optional pattern guard:
2408// (match e (pattern guard body)
2409// ... )
2410// a guard is a boolean expression.
2411// Guards make match, pattern matching more complicated
2412// than the recv pattern matching and requires staged execution
2413// via the continuation system rather than a while loop over a list.
2414static void eval_match(eval_context_t *ctx) {
2415
2416 lbm_value rest = get_cdr(ctx->curr_exp);
2417 if (lbm_is_cons(rest)) {
2418 lbm_cons_t *cell = lbm_ref_cell(rest);
2419 lbm_value cdr_rest = cell->cdr;
2420 ctx->curr_exp = cell->car;
2421 lbm_value *sptr = stack_reserve(ctx, 3);
2422 sptr[0] = cdr_rest;
2423 sptr[1] = ctx->curr_env;
2424 sptr[2] = MATCH(((9) << 2) | 0xF8000001u);
2425 } else {
2426 // someone wrote the program (match)
2427 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2428 }
2429}
2430
2431// Receive-timeout
2432// (recv-to timeout (pattern expr)
2433// (pattern expr))
2434static void eval_receive_timeout(eval_context_t *ctx) {
2435 if (is_atomic) atomic_error();
2436 lbm_value timeout_val = get_cadr(ctx->curr_exp);
2437 lbm_value pats = get_cdr(get_cdr(ctx->curr_exp));
2438 if (lbm_is_symbol_nil(pats)) {
2439 lbm_set_error_reason((char*)lbm_error_str_num_args);
2440 ERROR_AT_CTX(ENC_SYM_EERROR, ctx->curr_exp)error_at_ctx((((0x22) << 4) | 0x00000000u), ctx->curr_exp
)
;
2441 } else {
2442 lbm_value *sptr = stack_reserve(ctx, 2);
2443 sptr[0] = pats;
2444 sptr[1] = RECV_TO(((46) << 2) | 0xF8000001u);
2445 ctx->curr_exp = timeout_val;
2446 }
2447}
2448
2449// Receive
2450// (recv (pattern expr)
2451// (pattern expr))
2452static void eval_receive(eval_context_t *ctx) {
2453 if (is_atomic) atomic_error();
2454 lbm_value pats = get_cdr(ctx->curr_exp);
2455 if (pats) { // non-nil check
2456 if (ctx->num_mail == 0) {
2457 block_current_ctx(LBM_THREAD_STATE_RECV_BL(uint32_t)8u,0,false0);
2458 } else {
2459 lbm_value *msgs = ctx->mailbox;
2460 lbm_uint num = ctx->num_mail;
2461
2462 lbm_value e;
2463 lbm_value new_env = ctx->curr_env;
2464 int n = find_match(pats, msgs, num, &e, &new_env);
2465 if (n >= 0 ) { /* Match */
2466 mailbox_remove_mail(ctx, (lbm_uint)n);
2467 ctx->curr_env = new_env;
2468 ctx->curr_exp = e;
2469 } else { /* No match go back to sleep */
2470 ctx->r = ENC_SYM_NO_MATCH(((0x40) << 4) | 0x00000000u);
2471 block_current_ctx(LBM_THREAD_STATE_RECV_BL(uint32_t)8u, 0,false0);
2472 }
2473 }
2474 } else {
2475 lbm_set_error_reason((char*)lbm_error_str_num_args);
2476 ERROR_AT_CTX(ENC_SYM_EERROR,ctx->curr_exp)error_at_ctx((((0x22) << 4) | 0x00000000u), ctx->curr_exp
)
;
2477 }
2478}
2479
2480/*********************************************************/
2481/* Continuation functions */
2482
2483// cont_set_global_env:
2484//
2485// s[sp-1] = Key-symbol
2486//
2487// ctx->r = Value
2488static void cont_set_global_env(eval_context_t *ctx){
2489
2490 lbm_value val = ctx->r;
2491
2492 lbm_value key = ctx->K.data[--ctx->K.sp];
2493 lbm_uint dec_key = lbm_dec_sym(key);
2494 lbm_uint ix_key = dec_key & GLOBAL_ENV_MASK0x1F;
2495 lbm_value *global_env = lbm_get_global_env();
2496 lbm_uint orig_env = global_env[ix_key];
2497 lbm_value new_env;
2498 // A key is a symbol and should not need to be remembered.
2499 WITH_GC(new_env, lbm_env_set(orig_env,key,val))(new_env) = (lbm_env_set(orig_env,key,val)); if (lbm_is_symbol_merror
((new_env))) { gc(); (new_env) = (lbm_env_set(orig_env,key,val
)); if (lbm_is_symbol_merror((new_env))) { error_ctx((((0x23)
<< 4) | 0x00000000u)); } }
;
2500
2501 global_env[ix_key] = new_env;
2502 ctx->r = val;
2503
2504 ctx->app_cont = true1;
2505}
2506
2507// cont_resume:
2508//
2509// s[sp-2] = Expression
2510// s[sp-1] = Environment
2511//
2512// ctx->r = Irrelevant.
2513static void cont_resume(eval_context_t *ctx) {
2514 ctx->curr_env = ctx->K.data[--ctx->K.sp];
2515 ctx->curr_exp = ctx->K.data[--ctx->K.sp];
2516}
2517
2518// cont_progn_rest:
2519//
2520// s[sp-3] = Environment to evaluate each expression in.
2521// s[sp-2] = Flag indicating if env has been copied.
2522// s[sp-1] = list of expressions to evaluate.
2523//
2524// ctx->r = Result of last evaluated expression.
2525static void cont_progn_rest(eval_context_t *ctx) {
2526 lbm_value *sptr = get_stack_ptr(ctx, 3);
2527
2528 lbm_value env = sptr[0];
2529 // eval_progn and cont_progn_rest both ensure that sptr[2] is a list
2530 // whenever cont_progn_rest is called.
2531
2532 lbm_cons_t *rest_cell = lbm_ref_cell(sptr[2]);
2533 lbm_value rest_cdr = rest_cell->cdr;
2534 ctx->curr_exp = rest_cell->car;;
2535 ctx->curr_env = env;
2536 if (lbm_is_cons(rest_cdr)) {
2537 sptr[2] = rest_cdr; // Requirement: rest_cdr is a cons
2538 stack_reserve(ctx, 1)[0] = PROGN_REST(((4) << 2) | 0xF8000001u);
2539 } else {
2540 // Nothing is pushed to stack for final element in progn. (tail-call req)
2541 stack_drop(ctx, 3);
2542 }
2543}
2544
2545// cont_wait
2546//
2547// s[sp-1] = cid
2548static void cont_wait(eval_context_t *ctx) {
2549
2550 lbm_value cid_val = ctx->K.data[--ctx->K.sp];
2551 lbm_cid cid = (lbm_cid)lbm_dec_i(cid_val);
2552
2553 bool_Bool exists = false0;
2554
2555 lbm_blocked_iterator(context_exists, &cid, &exists);
2556 lbm_running_iterator(context_exists, &cid, &exists);
2557
2558 if (ctx_running->id == cid) {
2559 exists = true1;
2560 }
2561
2562 if (exists) {
2563 lbm_value *sptr = stack_reserve(ctx, 2);
2564 sptr[0] = lbm_enc_i(cid);
2565 sptr[1] = WAIT(((8) << 2) | 0xF8000001u);
2566 ctx->r = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
2567 ctx->app_cont = true1;
2568 yield_ctx(50000);
2569 } else {
2570 ctx->r = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
2571 ctx->app_cont = true1;
2572 }
2573}
2574
2575/***************************************************/
2576/* Application helper functions. */
2577
2578
2579/**
2580 * @brief Setup application of cont object (created by call-cc)
2581 *
2582 * The "function" form, e.g. `(SYM_CONT . cont-array)`, is expected to be stored
2583 * in `ctx->r`.
2584 *
2585 * @param args List of the arguments to apply with.
2586 * @return lbm_value The resulting argument value which should either be
2587 * evaluated or passed on directly depending on how you use this.
2588 */
2589static lbm_value setup_cont(eval_context_t *ctx, lbm_value args) {
2590 /* Continuation created using call-cc.
2591 * ((SYM_CONT . cont-array) arg0 )
2592 */
2593 lbm_value c = get_cdr(ctx->r); /* should be the continuation array*/
2594
2595 if (!lbm_is_lisp_array_r(c)) {
2596 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
2597 }
2598
2599 lbm_value arg;
2600 lbm_uint arg_count = lbm_list_length(args);
2601 switch (arg_count) {
2602 case 0:
2603 arg = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2604 break;
2605 case 1:
2606 arg = get_car(args);
2607 break;
2608 default:
2609 lbm_set_error_reason(lbm_error_str_num_args);
2610 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2611 }
2612
2613 lbm_stack_clear(&ctx->K);
2614
2615 lbm_array_header_t *arr = assume_array(c);
2616 ctx->K.sp = arr->size / sizeof(lbm_uint);
2617 memcpy(ctx->K.data, arr->data, arr->size);
2618
2619 lbm_value atomic = ctx->K.data[--ctx->K.sp];
2620 is_atomic = atomic ? 1 : 0;
2621
2622 return arg;
2623}
2624
2625/**
2626 * @brief Setup application of cont sp object (created by call-cc-unsafe)
2627 *
2628 * The "function" form, e.g. `(SYM_CONT_SP . stack_ptr)` is expected to be
2629 * stored in `ctx->r`.
2630 *
2631 * @param args List of the arguments to apply with.
2632 * @return lbm_value The resulting argument value which should either be
2633 * evaluated or passed on directly depending on how you use this.
2634 */
2635static lbm_value setup_cont_sp(eval_context_t *ctx, lbm_value args) {
2636 // continuation created using call-cc-unsafe
2637 // ((SYM_CONT_SP . stack_ptr) arg0 )
2638 lbm_value c = get_cadr(ctx->r); /* should be the stack_ptr*/
2639 lbm_value atomic = get_cadr(get_cdr(ctx->r));
2640
2641 if (!lbm_is_number(c)) {
2642 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
2643 }
2644
2645 lbm_uint sp = (lbm_uint)lbm_dec_i(c);
2646
2647 lbm_value arg;
2648 lbm_uint arg_count = lbm_list_length(args);
2649 switch (arg_count) {
2650 case 0:
2651 arg = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2652 break;
2653 case 1:
2654 arg = get_car(args);
2655 break;
2656 default:
2657 lbm_set_error_reason(lbm_error_str_num_args);
2658 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2659 }
2660
2661 if (sp > 0 && sp <= ctx->K.sp && IS_CONTINUATION(ctx->K.data[sp-1])(((ctx->K.data[sp-1]) & 0xF8000001u) == 0xF8000001u)) {
2662 is_atomic = atomic ? 1 : 0; // works fine with nil/true
2663 ctx->K.sp = sp;
2664 return arg;
2665 } else {
2666 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
2667 }
2668}
2669
2670/**
2671 * @brief Setup application of macro
2672 *
2673 * The macro form, e.g. `(macro (...) ...)`, is expected to be stored in
2674 * `ctx->r`.
2675 *
2676 * @param args List of the arguments to apply the macro with.
2677 * @param curr_env The environment to re-evaluate the result of the macro
2678 * experssion in.
2679 */
2680static inline __attribute__ ((always_inline)) void setup_macro(eval_context_t *ctx, lbm_value args, lbm_value curr_env) {
2681 /*
2682 * Perform macro expansion.
2683 * Macro expansion is really just evaluation in an
2684 * environment augmented with the unevaluated expressions passed
2685 * as arguments.
2686 */
2687
2688 lbm_uint *sptr = stack_reserve(ctx, 2);
2689 // For EVAL_R, placed here already to protect from GC
2690 sptr[0] = curr_env;
2691 // Placed here only to protect from GC, will be overriden.
2692 sptr[1] = args;
2693
2694 lbm_value curr_param = get_cadr(ctx->r);
2695 lbm_value curr_arg = args;
2696 lbm_value expand_env = curr_env;
2697 while (lbm_is_cons(curr_param) &&
2698 lbm_is_cons(curr_arg)) {
2699 lbm_cons_t *param_cell = lbm_ref_cell(curr_param); // already checked that cons.
2700 lbm_cons_t *arg_cell = lbm_ref_cell(curr_arg);
2701 lbm_value car_curr_param = param_cell->car;
2702 lbm_value cdr_curr_param = param_cell->cdr;
2703 lbm_value car_curr_arg = arg_cell->car;
2704 lbm_value cdr_curr_arg = arg_cell->cdr;
2705
2706 lbm_value entry = cons_with_gc(car_curr_param, car_curr_arg, expand_env);
2707 lbm_value aug_env = cons_with_gc(entry, expand_env,ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2708 expand_env = aug_env;
2709
2710 curr_param = cdr_curr_param;
2711 curr_arg = cdr_curr_arg;
2712 }
2713#ifdef LBM_USE_MACRO_REST_ARGS
2714 if (lbm_is_cons(curr_arg)) {
2715 expand_env = allocate_binding(ENC_SYM_REST_ARGS(((0x30015) << 4) | 0x00000000u), curr_arg, expand_env);
2716 }
2717#endif
2718
2719 /* Two rounds of evaluation is performed.
2720 * First to instantiate the arguments into the macro body.
2721 * Second to evaluate the resulting program.
2722 */
2723
2724 sptr[1] = EVAL_R(((11) << 2) | 0xF8000001u);
2725 lbm_value exp = get_cadr(get_cdr(ctx->r));
2726 ctx->curr_exp = exp;
2727 ctx->curr_env = expand_env;
2728}
2729
2730static lbm_value perform_setvar(lbm_value key, lbm_value val, lbm_value env) {
2731
2732 lbm_uint s = lbm_dec_sym(key);
2733 if (s >= RUNTIME_SYMBOLS_START0x40000) {
2734 lbm_value new_env = lbm_env_modify_binding(env, key, val);
2735 if (lbm_is_symbol(new_env) && new_env == ENC_SYM_NOT_FOUND(((0x24) << 4) | 0x00000000u)) {
2736 lbm_uint ix_key = lbm_dec_sym(key) & GLOBAL_ENV_MASK0x1F;
2737 lbm_value *glob_env = lbm_get_global_env();
2738 new_env = lbm_env_modify_binding(glob_env[ix_key], key, val);
2739 if (new_env != ENC_SYM_NOT_FOUND(((0x24) << 4) | 0x00000000u)) {
2740 glob_env[ix_key] = new_env;
2741 }
2742 }
2743 if (lbm_is_symbol(new_env) && new_env == ENC_SYM_NOT_FOUND(((0x24) << 4) | 0x00000000u)) {
2744 lbm_set_error_reason((char*)lbm_error_str_variable_not_bound);
2745 ERROR_AT_CTX(ENC_SYM_NOT_FOUND, key)error_at_ctx((((0x24) << 4) | 0x00000000u), key);
2746 }
2747 return val;
2748 }
2749 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_SETVAR)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x30000)
<< 4) | 0x00000000u))
;
2750 return ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // unreachable
2751}
2752
2753static void apply_setvar(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2754 if (nargs == 2 && lbm_is_symbol(args[0])) {
2755 lbm_value res;
2756 WITH_GC(res, perform_setvar(args[0], args[1], ctx->curr_env))(res) = (perform_setvar(args[0], args[1], ctx->curr_env));
if (lbm_is_symbol_merror((res))) { gc(); (res) = (perform_setvar
(args[0], args[1], ctx->curr_env)); if (lbm_is_symbol_merror
((res))) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
2757 ctx->r = args[1];
2758 stack_drop(ctx, (unsigned int)nargs+1);
2759 ctx->app_cont = true1;
2760 } else {
2761 if (nargs == 2) lbm_set_error_reason((char*)lbm_error_str_incorrect_arg);
2762 else lbm_set_error_reason((char*)lbm_error_str_num_args);
2763 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_SETVAR)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x30000)
<< 4) | 0x00000000u))
;
2764 }
2765}
2766
2767
2768#define READING_EXPRESSION((0 << 4) | 0x0000000Cu) ((0 << LBM_VAL_SHIFT4) | LBM_TYPE_U0x0000000Cu)
2769#define READING_PROGRAM((1 << 4) | 0x0000000Cu) ((1 << LBM_VAL_SHIFT4) | LBM_TYPE_U0x0000000Cu)
2770#define READING_PROGRAM_INCREMENTALLY((2 << 4) | 0x0000000Cu) ((2 << LBM_VAL_SHIFT4) | LBM_TYPE_U0x0000000Cu)
2771
2772// apply_read_base
2773// called from apply functions, so the stack holds N arguments.
2774// Only 1 argument is allowed and that argument must be either a string or a stream.
2775static void apply_read_base(lbm_value *args, lbm_uint nargs, eval_context_t *ctx, bool_Bool program, bool_Bool incremental) {
2776 if (nargs == 1) {
2777 lbm_value chan = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2778 if (lbm_type_of_functional(args[0]) == LBM_TYPE_ARRAY0x80000000u) {
2779 char *str = lbm_dec_str(args[0]);
2780 if (str) {
2781#ifdef LBM_ALWAYS_GC
2782 gc();
2783#endif
2784 if (!create_string_channel(str, &chan, args[0])) {
2785 gc();
2786 if (!create_string_channel(str, &chan, args[0])) {
2787 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
2788 }
2789 }
2790 } else {
2791 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2792 }
2793 } else if (lbm_type_of(args[0]) == LBM_TYPE_CHANNEL0x90000000u) {
2794 chan = args[0];
2795 // Streaming transfers can freeze the evaluator if the stream is cut while
2796 // the reader is reading inside of an atomic block.
2797 // It is generally not advisable to read in an atomic block but now it is also
2798 // enforced in the case where it can cause problems.
2799 if (lbm_channel_may_block(lbm_dec_channel(chan)) && is_atomic) {
2800 lbm_set_error_reason((char*)lbm_error_str_forbidden_in_atomic);
2801 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2802 }
2803 } else {
2804 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2805 }
2806 // Readers can nest if they are incremental. Nesting can occur
2807 // if the context evaluates code that starts reads additional code.
2808 // Evaluation happens directly after the "read_eval_continue" continuation
2809 // and such a reader will complete its task entirely before we are going back
2810 // to reading in the enclosing reader.
2811 // A program that uses read-eval-program possibly nests incremental readers
2812 // within incremental readers (as deeply as the evaluation stack allows).
2813 // But, inner readers finishes completely before returning back to enclosing readers.
2814
2815 // cont_read_eval_continue pushes the flags and the stream and
2816 // adds a continuation that pops these values after the evaluation steps have taken place.
2817
2818 ctx->reader_stream = chan;
2819 lbm_value *sptr = get_stack_ptr(ctx, 2); // Overwrite the args.
2820
2821 // if reading a single expression, incremental
2822 // or not have no meaning.
2823 sptr[0] = READING_EXPRESSION((0 << 4) | 0x0000000Cu);
2824 if (program) {
2825 if (incremental) {
2826 sptr[0] = READING_PROGRAM_INCREMENTALLY((2 << 4) | 0x0000000Cu);
2827 } else {
2828 sptr[0] = READING_PROGRAM((1 << 4) | 0x0000000Cu);
2829 }
2830 }
2831 sptr[1] = READ_DONE(((20) << 2) | 0xF8000001u);
2832
2833 // Each reader starts in a fresh situation
2834 ctx->flags &= ~EVAL_CPS_CONTEXT_READER_FLAGS_MASK((uint32_t)0x02 | (uint32_t)0x04 | (uint32_t)0x08);
2835 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // set r to a known state.
2836
2837 if (program) {
2838 if (incremental) {
2839 ctx->flags |= EVAL_CPS_CONTEXT_FLAG_INCREMENTAL_READ(uint32_t)0x08;
2840 lbm_value *rptr1 = stack_reserve(ctx,2);
2841 // Evaluating the program in the curr_env can lead to
2842 // values on curr_env to be captured in closures created in
2843 // the program.
2844 rptr1[0] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // ctx->curr_env;
2845 rptr1[1] = READ_EVAL_CONTINUE(((17) << 2) | 0xF8000001u);
2846 } else {
2847 ctx->flags &= ~EVAL_CPS_CONTEXT_FLAG_INCREMENTAL_READ(uint32_t)0x08;
2848 lbm_value *rptr1 = stack_reserve(ctx,3);
2849 rptr1[0] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2850 rptr1[1] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
2851 rptr1[2] = READ_APPEND_CONTINUE(((16) << 2) | 0xF8000001u);
2852 }
2853 }
2854
2855 // S | reading expression | reading program | reading program incrementally
2856 // ---------------------------------------------------------------------------------
2857 // -5| | READING_PROGRAM |
2858 // -4| | READ_DONE | READING_PROGRAM_INCREMENTALLY
2859 // -3| | NIL | READ_DONE
2860 // -2| READING_EXPRESSION | NIL | curr_env
2861 // -1| READ_DONE | READ_APPEND_CONTINUE | READ_EVAL_CONTINUE
2862
2863 stack_reserve(ctx,1)[0] = READ_NEXT_TOKEN_GRAB_ROW(((52) << 2) | 0xF8000001u);
2864 ctx->app_cont = true1;
2865 } else {
2866 lbm_set_error_reason((char*)lbm_error_str_num_args);
2867 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
2868 }
2869}
2870
2871static void apply_read_program(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2872 apply_read_base(args,nargs,ctx,true1,false0);
2873}
2874
2875static void apply_read_eval_program(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2876 apply_read_base(args,nargs,ctx,true1,true1);
2877}
2878
2879static void apply_read(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2880 apply_read_base(args,nargs,ctx,false0,false0);
2881}
2882
2883static void apply_spawn_base(lbm_value *args, lbm_uint nargs, eval_context_t *ctx, uint32_t context_flags) {
2884
2885 lbm_uint stack_size = EVAL_CPS_DEFAULT_STACK_SIZE256;
2886 lbm_uint closure_pos = 0;
2887 char *name = NULL((void*)0);
2888 // allowed arguments:
2889 // (spawn opt-name opt-stack-size closure arg1 ... argN)
2890
2891 if (nargs >= 1 &&
2892 lbm_is_closure(args[0])) {
2893 closure_pos = 0;
2894 } else if (nargs >= 2 &&
2895 lbm_is_number(args[0]) &&
2896 lbm_is_closure(args[1])) {
2897 stack_size = lbm_dec_as_u32(args[0]);
2898 closure_pos = 1;
2899 } else if (nargs >= 2 &&
2900 lbm_is_array_r(args[0]) &&
2901 lbm_is_closure(args[1])) {
2902 name = lbm_dec_str(args[0]);
2903 closure_pos = 1;
2904 } else if (nargs >= 3 &&
2905 lbm_is_array_r(args[0]) &&
2906 lbm_is_number(args[1]) &&
2907 lbm_is_closure(args[2])) {
2908 stack_size = lbm_dec_as_u32(args[1]);
2909 closure_pos = 2;
2910 name = lbm_dec_str(args[0]);
2911 } else {
2912 if (context_flags & EVAL_CPS_CONTEXT_FLAG_TRAP(uint32_t)0x01)
2913 ERROR_AT_CTX(ENC_SYM_TERROR,ENC_SYM_SPAWN_TRAP)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30005)
<< 4) | 0x00000000u))
;
2914 else
2915 ERROR_AT_CTX(ENC_SYM_TERROR,ENC_SYM_SPAWN)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30004)
<< 4) | 0x00000000u))
;
2916 }
2917
2918 lbm_value cl0, cl1, cl2;
2919 lbm_value cl = get_cdr(args[closure_pos]);
2920 EXTRACT(cl, cl0)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl0 = _cell->car; cl = _cell->cdr; } else { cl0 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_PARAMS
2921 EXTRACT(cl, cl1)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl1 = _cell->car; cl = _cell->cdr; } else { cl1 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_BODY
2922 EXTRACT_NO_ADVANCE(cl, cl2)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl2 = _cell->car; } else { cl2 = (((0x0) << 4) | 0x00000000u
); } } while (0)
; // CLO_ENV
2923 lbm_value curr_param = cl0;
2924 lbm_value clo_env = cl2;
2925 lbm_uint i = closure_pos + 1;
2926 while (lbm_is_cons(curr_param) && i <= nargs) {
2927 lbm_value entry = cons_with_gc(lbm_ref_cell(curr_param)->car, args[i], clo_env);
2928 lbm_value aug_env = cons_with_gc(entry, clo_env,ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
2929 clo_env = aug_env;
2930 curr_param = lbm_ref_cell(curr_param)->cdr;
2931 i ++;
2932 }
2933
2934 stack_drop(ctx, (unsigned int)nargs+1);
2935
2936 lbm_value program = cons_with_gc(cl1, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), clo_env);
2937
2938 lbm_cid cid = lbm_create_ctx_parent(program,
2939 clo_env,
2940 stack_size,
2941 lbm_get_current_cid(),
2942 context_flags,
2943 name);
2944 // setting these values is a good idea
2945 // even if creating a context failed.
2946 // The info in r may be useful for user.
2947 ctx->r = lbm_enc_i(cid);
2948 ctx->app_cont = true1;
2949 if (cid == -1) ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u)); // Kill parent and signal out of memory.
2950}
2951
2952static void apply_spawn(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2953 apply_spawn_base(args,nargs,ctx, EVAL_CPS_CONTEXT_FLAG_NOTHING(uint32_t)0x00);
2954}
2955
2956static void apply_spawn_trap(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2957 apply_spawn_base(args,nargs,ctx, EVAL_CPS_CONTEXT_FLAG_TRAP(uint32_t)0x01);
2958}
2959
2960static void apply_yield(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2961 if (nargs == 1 && lbm_is_number(args[0])) {
2962 lbm_uint ts = lbm_dec_as_u32(args[0]);
2963 stack_drop(ctx, (unsigned int)nargs+1);
2964 yield_ctx(ts);
2965 } else {
2966 lbm_set_error_reason((char*)lbm_error_str_no_number);
2967 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_YIELD)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30006)
<< 4) | 0x00000000u))
;
2968 }
2969}
2970
2971static void apply_sleep(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2972 if (nargs == 1 && lbm_is_number(args[0])) {
2973 lbm_uint ts = (lbm_uint)(1000000.0f * lbm_dec_as_float(args[0]));
2974 stack_drop(ctx, (unsigned int)nargs+1);
2975 yield_ctx(ts);
2976 } else {
2977 lbm_set_error_reason((char*)lbm_error_str_no_number);
2978 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_SLEEP)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30012)
<< 4) | 0x00000000u))
;
2979 }
2980}
2981
2982static void apply_wait(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2983 if (nargs == 1 && lbm_type_of(args[0]) == LBM_TYPE_I0x00000008u) {
2984 lbm_cid cid = (lbm_cid)lbm_dec_i(args[0]);
2985 lbm_value *sptr = get_stack_ptr(ctx, 2);
2986 sptr[0] = lbm_enc_i(cid);
2987 sptr[1] = WAIT(((8) << 2) | 0xF8000001u);
2988 ctx->r = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
2989 ctx->app_cont = true1;
2990 yield_ctx(50000);
2991 } else {
2992 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_WAIT)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30007)
<< 4) | 0x00000000u))
;
2993 }
2994}
2995
2996/* (eval expr)
2997 (eval env expr) */
2998static void apply_eval(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
2999 if ( nargs == 1) {
3000 ctx->curr_exp = args[0];
3001 } else if (nargs == 2) {
3002 ctx->curr_exp = args[1];
3003 ctx->curr_env = args[0];
3004 } else {
3005 lbm_set_error_reason((char*)lbm_error_str_num_args);
3006 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_EVAL)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x30008)
<< 4) | 0x00000000u))
;
3007 }
3008 stack_drop(ctx, (unsigned int)nargs+1);
3009}
3010
3011static void apply_eval_program(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3012 if (nargs == 1) {
3013 // here ctx->r = args[0];
3014 lbm_value prg = args[0]; // No check that this is a program.
3015 lbm_value app_cont;
3016 lbm_value app_cont_prg;
3017 lbm_value new_prg;
3018 lbm_value prg_copy;
3019
3020 int len = -1;
3021 WITH_GC(prg_copy, lbm_list_copy(&len, prg, ENC_SYM_NIL))(prg_copy) = (lbm_list_copy(&len, prg, (((0x0) << 4
) | 0x00000000u))); if (lbm_is_symbol_merror((prg_copy))) { gc
(); (prg_copy) = (lbm_list_copy(&len, prg, (((0x0) <<
4) | 0x00000000u))); if (lbm_is_symbol_merror((prg_copy))) {
error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
3022 stack_drop(ctx, (unsigned int)nargs+1);
3023 // There is always a continuation (DONE).
3024 // If ctx->program is nil, the stack should contain DONE.
3025 // after adding an intermediate done for prg, stack becomes DONE, DONE.
3026 app_cont = cons_with_gc(ENC_SYM_APP_CONT(((0x111) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), prg_copy);
3027 app_cont_prg = cons_with_gc(app_cont, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), prg_copy);
3028 new_prg = lbm_list_append(app_cont_prg, ctx->program);
3029 new_prg = lbm_list_append(prg_copy, new_prg);
3030 // new_prg is guaranteed to be a cons cell or nil
3031 // even if the eval-program application is syntactically broken.
3032 stack_reserve(ctx, 1)[0] = DONE(((0) << 2) | 0xF8000001u);
3033 ctx->program = get_cdr(new_prg);
3034 ctx->curr_exp = get_car(new_prg);
3035 } else {
3036 lbm_set_error_reason((char*)lbm_error_str_num_args);
3037 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_EVAL_PROGRAM)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x30009)
<< 4) | 0x00000000u))
;
3038 }
3039}
3040
3041static void apply_send(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3042 if (nargs == 2) {
3043 lbm_value msg = args[1];
3044 if (lbm_type_of(args[0]) == LBM_TYPE_I0x00000008u) {
3045 lbm_cid cid = (lbm_cid)lbm_dec_i(args[0]);
3046 bool_Bool r = lbm_find_receiver_and_send(cid, msg);
3047 /* return the status */
3048 stack_drop(ctx, (unsigned int)nargs+1);
3049 ctx->r = r ? ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u) : ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3050 ctx->app_cont = true1;
3051 } else if (lbm_type_of_functional(args[0]) == LBM_TYPE_ARRAY0x80000000u) {
3052 char *name;
3053 size_t name_len;
3054 if (lbm_value_is_printable_string(args[0], &name) &&
3055 lbm_dec_str_size(args[0], &name, &name_len)) {
3056 find_receiver_t c;
3057 c.u.name = name;
3058 c.name_len = (lbm_uint)name_len;
3059 c.by_name = true1;
3060 bool_Bool r = find_receiver_and_send(c, msg);
3061 stack_drop(ctx, (unsigned int)nargs + 1);
3062 ctx->r = r ? ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u) : ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3063 ctx->app_cont = true1;
3064 } else {
3065 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_SEND)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x3000A)
<< 4) | 0x00000000u))
;
3066 }
3067 } else {
3068 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_SEND)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x3000A)
<< 4) | 0x00000000u))
;
3069 }
3070 } else {
3071 lbm_set_error_reason((char*)lbm_error_str_num_args);
3072 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_SEND)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x3000A)
<< 4) | 0x00000000u))
;
3073 }
3074}
3075
3076static void apply_ok(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3077 lbm_value ok_val = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
3078 if (nargs >= 1) {
3079 ok_val = args[0];
3080 }
3081 ctx->r = ok_val;
3082 ok_ctx();
3083}
3084
3085static void apply_error(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3086 (void) ctx;
3087 lbm_value err_val = ENC_SYM_EERROR(((0x22) << 4) | 0x00000000u);
3088 if (nargs >= 1) {
3089 err_val = args[0];
3090 }
3091 ERROR_AT_CTX(err_val, ENC_SYM_EXIT_ERROR)error_at_ctx(err_val, (((0x3000C) << 4) | 0x00000000u));
3092}
3093
3094// ////////////////////////////////////////////////////////////
3095// Map takes a function f and a list ls as arguments.
3096// The function f is applied to each element of ls.
3097//
3098// Normally when applying a function to an argument this happens:
3099// 1. the function is evaluated
3100// 2. the argument is evaluated
3101// 3. the result of evaluating the function is applied to the result of evaluating
3102// the argument.
3103//
3104// When doing (map f arg-list) I assume one means to apply f to each element of arg-list
3105// exactly as those elements are. That is, no evaluation of the argument.
3106// The implementation of map below makes sure that the elements of the arg-list are not
3107// evaluated by wrapping them each in a `quote`.
3108//
3109// Map creates a structure in memory that looks like this (f (quote dummy . nil) . nil).
3110// Then, for each element from arg-list (example a1 ... aN) the object
3111// (f (quote aM . nil) . nil) is created by substituting dummy for an element of the list.
3112// after this substitution the evaluator is fired up to evaluate the entire (f (quote aM . nil) . nil)
3113// structure resulting in an element for the result list.
3114//
3115// Here comes the fun part, if you (map quote arg-list), then the object
3116// (quote (quote aM . nil) . nil) is created and evaluated. Now note that quote just gives back
3117// exactly what you give to it when evaluated.
3118// So (quote (quote aM . nil) . nil) gives you as result (quote aM . nil) and now also note that
3119// this is a list, and a list is really just an address on the heap!
3120// This leads to the very fun behavior that:
3121//
3122// # (map quote '(1 2 3 4))
3123// > ((quote 4) (quote 4) (quote 4) (quote 4))
3124//
3125// A potential fix is to instead of creating the object (f (quote aM . nil) . nil)
3126// we create the object (f var) for some unique var and then extend the environment
3127// for each round of evaluation with a binding var => aM.
3128
3129// (map f arg-list)
3130static void apply_map(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3131 if (nargs == 2 && lbm_is_cons(args[1])) {
3132 lbm_value *sptr = get_stack_ptr(ctx, 3);
3133
3134 lbm_value f = args[0];
3135 lbm_cons_t *args1_cell = lbm_ref_cell(args[1]);
3136 lbm_value h = args1_cell->car;
3137 lbm_value t = args1_cell->cdr;
3138
3139 lbm_value appli_1;
3140 lbm_value appli;
3141 WITH_GC(appli_1, lbm_heap_allocate_list(2))(appli_1) = (lbm_heap_allocate_list(2)); if (lbm_is_symbol_merror
((appli_1))) { gc(); (appli_1) = (lbm_heap_allocate_list(2));
if (lbm_is_symbol_merror((appli_1))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
3142 WITH_GC_RMBR_1(appli, lbm_heap_allocate_list(2), appli_1)(appli) = (lbm_heap_allocate_list(2)); if (lbm_is_symbol_merror
((appli))) { lbm_gc_mark_phase(appli_1); gc(); (appli) = (lbm_heap_allocate_list
(2)); if (lbm_is_symbol_merror((appli))) { error_ctx((((0x23)
<< 4) | 0x00000000u)); } }
;
3143
3144 // appli_1 is a list of length 2 here.
3145 lbm_value appli_0 = lbm_ref_cell(appli_1)->cdr;
3146
3147 // appli is a list of length 2 here, so a cons
3148 lbm_cons_t *cell = lbm_ref_cell(appli_0);
3149 cell->car = h;
3150 cell->cdr = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3151
3152 cell = lbm_ref_cell(appli_1);
3153 cell->car = ENC_SYM_QUOTE(((0x100) << 4) | 0x00000000u);
3154
3155 lbm_cons_t *appli_cell = lbm_ref_cell(appli);
3156 cell = lbm_ref_cell(appli_cell->cdr);
3157 cell->car = appli_1;
3158 cell->cdr = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3159
3160 appli_cell->car = f;
3161
3162
3163 lbm_value elt = cons_with_gc(ctx->r, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), appli);
3164 sptr[0] = t; // reuse stack space
3165 sptr[1] = ctx->curr_env;
3166 sptr[2] = elt;
3167 lbm_value *rptr = stack_reserve(ctx,4);
3168 rptr[0] = elt;
3169 rptr[1] = appli;
3170 rptr[2] = appli_0;
3171 rptr[3] = MAP(((23) << 2) | 0xF8000001u);
3172 ctx->curr_exp = appli;
3173 } else if (nargs == 2 && lbm_is_symbol_nil(args[1])) {
3174 stack_drop(ctx, 3);
3175 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3176 ctx->app_cont = true1;
3177 } else {
3178 lbm_set_error_reason((char*)lbm_error_str_num_args);
3179 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_MAP)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x3000D)
<< 4) | 0x00000000u))
;
3180 }
3181}
3182
3183static void apply_reverse(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3184 if (nargs == 1 && lbm_is_list(args[0])) {
3185 lbm_value curr = args[0];
3186
3187 lbm_value new_list = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3188 while (lbm_is_cons(curr)) {
3189 lbm_cons_t *curr_cell = lbm_ref_cell(curr); // known cons.
3190 lbm_value tmp = cons_with_gc(curr_cell->car, new_list, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
3191 new_list = tmp;
3192 curr = curr_cell->cdr;
3193 }
3194 stack_drop(ctx, 2);
3195 ctx->r = new_list;
3196 ctx->app_cont = true1;
3197 } else {
3198 lbm_set_error_reason("Reverse requires a list argument");
3199 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_REVERSE)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x3000E)
<< 4) | 0x00000000u))
;
3200 }
3201}
3202
3203static void apply_flatten(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3204 if (nargs == 1) {
3205#ifdef LBM_ALWAYS_GC
3206 gc();
3207#endif
3208 lbm_value v = flatten_value(args[0]);
3209 if ( v == ENC_SYM_MERROR(((0x23) << 4) | 0x00000000u)) {
3210 gc();
3211 v = flatten_value(args[0]);
3212 }
3213
3214 if (lbm_is_symbol(v)) {
3215 ERROR_AT_CTX(v, ENC_SYM_FLATTEN)error_at_ctx(v, (((0x3000F) << 4) | 0x00000000u));
3216 } else {
3217 stack_drop(ctx, 2);
3218 ctx->r = v;
3219 ctx->app_cont = true1;
3220 }
3221 return;
3222 }
3223 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_FLATTEN)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x3000F)
<< 4) | 0x00000000u))
;
3224}
3225
3226static void apply_unflatten(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3227 lbm_array_header_t *array;
3228 if(nargs == 1 && (array = lbm_dec_array_r(args[0]))) {
3229 lbm_flat_value_t fv;
3230 fv.buf = (uint8_t*)array->data;
3231 fv.buf_size = array->size;
3232 fv.buf_pos = 0;
3233
3234 lbm_value res;
3235
3236 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3237 if (lbm_unflatten_value(&fv, &res)) {
3238 ctx->r = res;
3239 }
3240 stack_drop(ctx, 2);
3241 ctx->app_cont = true1;
3242 return;
3243 }
3244 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_UNFLATTEN)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30010)
<< 4) | 0x00000000u))
;
3245}
3246
3247static void apply_kill(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3248 if (nargs == 2 && lbm_is_number(args[0])) {
3249 lbm_cid cid = lbm_dec_as_i32(args[0]);
3250
3251 if (ctx->id == cid) {
3252 ctx->r = args[1];
3253 finish_ctx();
3254 return;
3255 }
3256 lbm_mutex_lock(&qmutex);
3257 eval_context_t *found = NULL((void*)0);
3258 if ((found = lookup_ctx_nm(&blocked, cid))) {
3259 unlink_ctx_nm(&blocked, found);
3260 } else if ((found = lookup_ctx_nm(&queue, cid))) {
3261 unlink_ctx_nm(&queue, found);
3262 }
3263
3264 if (found) {
3265 found->K.data[found->K.sp - 1] = KILL(((37) << 2) | 0xF8000001u);
3266 found->r = args[1];
3267 found->app_cont = true1;
3268 found->state = LBM_THREAD_STATE_READY(uint32_t)0u;
3269 enqueue_ctx_nm(&queue,found);
3270 ctx->r = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
3271 } else {
3272 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3273 }
3274 stack_drop(ctx, 3);
3275 ctx->app_cont = true1;
3276 lbm_mutex_unlock(&qmutex);
3277 return;
3278 }
3279 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_KILL)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30011)
<< 4) | 0x00000000u))
;
3280}
3281
3282static lbm_value cmp_to_clo(lbm_value cmp) {
3283 lbm_value closure;
3284 WITH_GC(closure, lbm_heap_allocate_list(4))(closure) = (lbm_heap_allocate_list(4)); if (lbm_is_symbol_merror
((closure))) { gc(); (closure) = (lbm_heap_allocate_list(4));
if (lbm_is_symbol_merror((closure))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
3285 lbm_set_car(closure, ENC_SYM_CLOSURE(((0x10F) << 4) | 0x00000000u));
3286 lbm_value cl1 = lbm_cdr(closure);
3287 lbm_value par;
3288 WITH_GC_RMBR_1(par, lbm_heap_allocate_list_init(2, symbol_x, symbol_y), closure)(par) = (lbm_heap_allocate_list_init(2, symbol_x, symbol_y));
if (lbm_is_symbol_merror((par))) { lbm_gc_mark_phase(closure
); gc(); (par) = (lbm_heap_allocate_list_init(2, symbol_x, symbol_y
)); if (lbm_is_symbol_merror((par))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
3289 lbm_set_car(cl1, par);
3290 lbm_value cl2 = lbm_cdr(cl1);
3291 lbm_value body;
3292 WITH_GC_RMBR_1(body, lbm_heap_allocate_list_init(3, cmp, symbol_x, symbol_y), closure)(body) = (lbm_heap_allocate_list_init(3, cmp, symbol_x, symbol_y
)); if (lbm_is_symbol_merror((body))) { lbm_gc_mark_phase(closure
); gc(); (body) = (lbm_heap_allocate_list_init(3, cmp, symbol_x
, symbol_y)); if (lbm_is_symbol_merror((body))) { error_ctx((
((0x23) << 4) | 0x00000000u)); } }
;
3293 lbm_set_car(cl2, body);
3294 lbm_value cl3 = lbm_cdr(cl2);
3295 lbm_set_car(cl3, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
3296 return closure;
3297}
3298
3299// (merge comparator list1 list2)
3300static void apply_merge(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3301 if (nargs == 3 && lbm_is_list(args[1]) && lbm_is_list(args[2])) {
3302
3303 if (!lbm_is_closure(args[0])) {
3304 args[0] = cmp_to_clo(args[0]);
3305 }
3306
3307 // Copy input lists for functional behaviour at top-level
3308 // merge itself is in-place in the copied lists.
3309 lbm_value a;
3310 lbm_value b;
3311 int len_a = -1;
3312 int len_b = -1;
3313 WITH_GC(a, lbm_list_copy(&len_a, args[1], ENC_SYM_NIL))(a) = (lbm_list_copy(&len_a, args[1], (((0x0) << 4)
| 0x00000000u))); if (lbm_is_symbol_merror((a))) { gc(); (a)
= (lbm_list_copy(&len_a, args[1], (((0x0) << 4) | 0x00000000u
))); if (lbm_is_symbol_merror((a))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
3314 WITH_GC_RMBR_1(b, lbm_list_copy(&len_b, args[2], ENC_SYM_NIL), a)(b) = (lbm_list_copy(&len_b, args[2], (((0x0) << 4)
| 0x00000000u))); if (lbm_is_symbol_merror((b))) { lbm_gc_mark_phase
(a); gc(); (b) = (lbm_list_copy(&len_b, args[2], (((0x0) <<
4) | 0x00000000u))); if (lbm_is_symbol_merror((b))) { error_ctx
((((0x23) << 4) | 0x00000000u)); } }
;
3315
3316 if (len_a == 0) {
3317 ctx->r = b;
3318 stack_drop(ctx, 4);
3319 ctx->app_cont = true1;
3320 return;
3321 }
3322 if (len_b == 0) {
3323 ctx->r = a;
3324 stack_drop(ctx, 4);
3325 ctx->app_cont = true1;
3326 return;
3327 }
3328
3329 args[1] = a; // keep safe by replacing the original on stack.
3330 args[2] = b;
3331
3332 lbm_value cl = lbm_cdr(args[0]);
3333 lbm_value cl0, cl1, cl2;
3334 EXTRACT(cl, cl0)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl0 = _cell->car; cl = _cell->cdr; } else { cl0 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_PARAMS
3335 EXTRACT(cl, cl1)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl1 = _cell->car; cl = _cell->cdr; } else { cl1 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_BODY
3336 EXTRACT_NO_ADVANCE(cl, cl2)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl2 = _cell->car; } else { cl2 = (((0x0) << 4) | 0x00000000u
); } } while (0)
; // CLO_ENV
3337
3338 lbm_value cmp_env = cl2;
3339 lbm_uint len = lbm_list_length(cl0);
3340 if (len == 2) {
3341 lbm_value a_1 = a;
3342 lbm_value b_1 = b;
3343 lbm_value a_rest = lbm_cdr(a);
3344 lbm_value b_rest = lbm_cdr(b);
3345 lbm_value par1 = get_car(cl0);
3346 lbm_value par2 = get_cadr(cl0);
3347 lbm_value new_env0;
3348 lbm_value new_env;
3349 WITH_GC(new_env0, lbm_env_set(cmp_env, par1, lbm_car(a_1)))(new_env0) = (lbm_env_set(cmp_env, par1, lbm_car(a_1))); if (
lbm_is_symbol_merror((new_env0))) { gc(); (new_env0) = (lbm_env_set
(cmp_env, par1, lbm_car(a_1))); if (lbm_is_symbol_merror((new_env0
))) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
3350 WITH_GC_RMBR_1(new_env, lbm_env_set(new_env0, par2, lbm_car(b_1)),new_env0)(new_env) = (lbm_env_set(new_env0, par2, lbm_car(b_1))); if (
lbm_is_symbol_merror((new_env))) { lbm_gc_mark_phase(new_env0
); gc(); (new_env) = (lbm_env_set(new_env0, par2, lbm_car(b_1
))); if (lbm_is_symbol_merror((new_env))) { error_ctx((((0x23
) << 4) | 0x00000000u)); } }
;
3351 cmp_env = new_env;
3352 lbm_set_cdr(a_1, b_1);
3353 lbm_set_cdr(b_1, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
3354 lbm_value cmp = cl1;
3355
3356 stack_drop(ctx, 4); // TODO: Optimize drop 4 alloc 10 into alloc 6
3357 lbm_uint *sptr = stack_reserve(ctx, 10);
3358 sptr[0] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // head of merged list
3359 sptr[1] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // last of merged list
3360 sptr[2] = a_1;
3361 sptr[3] = a_rest;
3362 sptr[4] = b_rest;
3363 sptr[5] = cmp;
3364 sptr[6] = cmp_env;
3365 sptr[7] = par1;
3366 sptr[8] = par2;
3367 sptr[9] = MERGE_REST(((40) << 2) | 0xF8000001u);
3368 ctx->curr_exp = cl1;
3369 ctx->curr_env = cmp_env;
3370 return;
3371 }
3372 }
3373 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_MERGE)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30013)
<< 4) | 0x00000000u))
;
3374}
3375
3376// (sort comparator list)
3377static void apply_sort(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3378 if (nargs == 2 && lbm_is_list(args[1])) {
3379
3380 if (!lbm_is_closure(args[0])) {
3381 args[0] = cmp_to_clo(args[0]);
3382 }
3383
3384 int len = -1;
3385 lbm_value list_copy;
3386 WITH_GC(list_copy, lbm_list_copy(&len, args[1], ENC_SYM_NIL))(list_copy) = (lbm_list_copy(&len, args[1], (((0x0) <<
4) | 0x00000000u))); if (lbm_is_symbol_merror((list_copy))) {
gc(); (list_copy) = (lbm_list_copy(&len, args[1], (((0x0
) << 4) | 0x00000000u))); if (lbm_is_symbol_merror((list_copy
))) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
3387 if (len <= 1) {
3388 stack_drop(ctx, 3);
3389 ctx->r = list_copy;
3390 ctx->app_cont = true1;
3391 return;
3392 }
3393
3394 args[1] = list_copy; // Keep safe, original replaced on stack.
3395
3396 // Take the headmost 2, 1-element sublists.
3397 lbm_value a = list_copy;
3398 lbm_value b = lbm_cdr(a);
3399 lbm_value rest = lbm_cdr(b);
3400 // Do not terminate b. keep rest of list safe from GC in the following
3401 // closure extraction.
3402 //lbm_set_cdr(a, b); // This is void
3403
3404 lbm_value cl = lbm_cdr(args[0]);
3405 lbm_value cl0, cl1, cl2;
3406 EXTRACT(cl, cl0)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl0 = _cell->car; cl = _cell->cdr; } else { cl0 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_PARAMS
3407 EXTRACT(cl, cl1)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl1 = _cell->car; cl = _cell->cdr; } else { cl1 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_BODY
3408 EXTRACT_NO_ADVANCE(cl, cl2)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl2 = _cell->car; } else { cl2 = (((0x0) << 4) | 0x00000000u
); } } while (0)
; // CLO_ENV
3409 lbm_value cmp_env = cl2;
3410
3411 lbm_uint cl_len = lbm_list_length(cl0);
3412 if (cl_len == 2) {
3413 lbm_value par1 = get_car(cl0);
3414 lbm_value par2 = get_cadr(cl0);
3415 lbm_value new_env0;
3416 lbm_value new_env;
3417 WITH_GC(new_env0, lbm_env_set(cmp_env, par1, lbm_car(a)))(new_env0) = (lbm_env_set(cmp_env, par1, lbm_car(a))); if (lbm_is_symbol_merror
((new_env0))) { gc(); (new_env0) = (lbm_env_set(cmp_env, par1
, lbm_car(a))); if (lbm_is_symbol_merror((new_env0))) { error_ctx
((((0x23) << 4) | 0x00000000u)); } }
;
3418 WITH_GC_RMBR_1(new_env, lbm_env_set(new_env0, par2, lbm_car(b)), new_env0)(new_env) = (lbm_env_set(new_env0, par2, lbm_car(b))); if (lbm_is_symbol_merror
((new_env))) { lbm_gc_mark_phase(new_env0); gc(); (new_env) =
(lbm_env_set(new_env0, par2, lbm_car(b))); if (lbm_is_symbol_merror
((new_env))) { error_ctx((((0x23) << 4) | 0x00000000u))
; } }
;
3419 cmp_env = new_env;
3420
3421 lbm_value cmp = cl1;
3422
3423 // Terminate the comparator argument list.
3424 lbm_set_cdr(b, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
3425
3426 stack_drop(ctx, 3); //TODO: optimize drop 3, alloc 20 into alloc 17
3427 lbm_uint *sptr = stack_reserve(ctx, 20);
3428 sptr[0] = cmp;
3429 sptr[1] = cmp_env;
3430 sptr[2] = par1;
3431 sptr[3] = par2;
3432 sptr[4] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // head of merged accumulation of sublists
3433 sptr[5] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // last of merged accumulation of sublists
3434 sptr[6] = rest;
3435 sptr[7] = lbm_enc_i(1);
3436 sptr[8] = lbm_enc_i(len); //TODO: 28 bit i vs 32 bit i
3437 sptr[9] = MERGE_LAYER(((41) << 2) | 0xF8000001u);
3438 sptr[10] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // head of merged sublist
3439 sptr[11] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // last of merged sublist
3440 sptr[12] = a;
3441 sptr[13] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // no a_rest, 1 element lists in layer 1.
3442 sptr[14] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // no b_rest, 1 element lists in layer 1.
3443 sptr[15] = cmp;
3444 sptr[16] = cmp_env;
3445 sptr[17] = par1;
3446 sptr[18] = par2;
3447 sptr[19] = MERGE_REST(((40) << 2) | 0xF8000001u);
3448 ctx->curr_exp = cmp;
3449 ctx->curr_env = cmp_env;
3450 return;
3451 }
3452 }
3453 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_SORT)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x30014)
<< 4) | 0x00000000u))
;
3454}
3455
3456static void apply_rest_args(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3457 lbm_value res = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); //TODO: lbm_env_lookup does not set res in all cases.
3458 if (lbm_env_lookup_b(&res, ENC_SYM_REST_ARGS(((0x30015) << 4) | 0x00000000u), ctx->curr_env)) {
3459 if (nargs == 1 && lbm_is_number(args[0])) {
3460 int32_t ix = lbm_dec_as_i32(args[0]);
3461 res = lbm_index_list(res, ix);
3462 }
3463 ctx->r = res;
3464 } else {
3465 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3466 }
3467 stack_drop(ctx, (unsigned int)nargs+1);
3468 ctx->app_cont = true1;
3469}
3470
3471/* (rotate list-expr dist/dir-expr) */
3472static void apply_rotate(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
3473 if (nargs == 2 && lbm_is_list(args[0]) && lbm_is_number(args[1])) {
3474 int len = -1;
3475 lbm_value ls;
3476 WITH_GC(ls, lbm_list_copy(&len, args[0], ENC_SYM_NIL))(ls) = (lbm_list_copy(&len, args[0], (((0x0) << 4) |
0x00000000u))); if (lbm_is_symbol_merror((ls))) { gc(); (ls)
= (lbm_list_copy(&len, args[0], (((0x0) << 4) | 0x00000000u
))); if (lbm_is_symbol_merror((ls))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
3477 int dist = lbm_dec_as_i32(args[1]);
3478 if (len > 0 && dist != 0) {
3479 int d = dist;
3480 if (dist > 0) {
3481 ls = lbm_list_destructive_reverse(ls);
3482 } else {
3483 d = -dist;
3484 }
3485
3486 lbm_value start = ls;
3487 lbm_value end = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3488 lbm_value curr = start;
3489 while (lbm_is_cons(curr)) {
3490 end = curr;
3491 curr = lbm_ref_cell(curr)->cdr;
3492 }
3493
3494 for (int i = 0; i < d; i ++) {
3495 lbm_value a = start;
3496 start = lbm_cdr(start);
3497 lbm_set_cdr(a, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
3498 lbm_set_cdr(end, a);
3499 end = a;
3500 }
3501 ls = start;
3502 if (dist > 0) {
3503 ls = lbm_list_destructive_reverse(ls);
3504 }
3505 }
3506 stack_drop(ctx, (unsigned int)nargs+1);
3507 ctx->app_cont = true1;
3508 ctx->r = ls;
3509 return;
3510 }
3511 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
3512}
3513
3514/***************************************************/
3515/* Application lookup table */
3516
3517typedef void (*apply_fun)(lbm_value *, lbm_uint, eval_context_t *);
3518static const apply_fun fun_table[] =
3519 {
3520 apply_setvar,
3521 apply_read,
3522 apply_read_program,
3523 apply_read_eval_program,
3524 apply_spawn,
3525 apply_spawn_trap,
3526 apply_yield,
3527 apply_wait,
3528 apply_eval,
3529 apply_eval_program,
3530 apply_send,
3531 apply_ok,
3532 apply_error,
3533 apply_map,
3534 apply_reverse,
3535 apply_flatten,
3536 apply_unflatten,
3537 apply_kill,
3538 apply_sleep,
3539 apply_merge,
3540 apply_sort,
3541 apply_rest_args,
3542 apply_rotate,
3543 apply_apply,
3544 };
3545
3546
3547/***************************************************/
3548/* fptr call with retry on GC */
3549static void call_fptr(lbm_value (*fptr)(lbm_value *, lbm_uint), lbm_value *args, lbm_uint arg_count, eval_context_t *ctx) {
3550 lbm_value res;
3551#ifdef LBM_ALWAYS_GC
3552 gc();
3553#endif
3554 res = fptr(&args[1], arg_count);
3555 if (lbm_is_error(res)) {
3556 if (lbm_is_symbol_merror(res)) {
3557 gc();
3558 res = fptr(&args[1], arg_count);
3559 }
3560 if (lbm_is_error(res)) {
3561 ERROR_AT_CTX(res, args[0])error_at_ctx(res, args[0]);
3562 }
3563 }
3564 stack_drop(ctx, (unsigned int)arg_count+1);
3565 ctx->app_cont = true1;
3566 ctx->r = res;
3567}
3568
3569/***************************************************/
3570/* Application of function that takes arguments */
3571/* passed over the stack. */
3572
3573static void application(eval_context_t *ctx, lbm_value *fun_args, lbm_uint arg_count) {
3574 /* If arriving here, we know that the fun is a symbol.
3575 * and can be a built in operation or an extension.
3576 */
3577 lbm_value fun = fun_args[0];
3578
3579 lbm_uint fun_val = lbm_dec_sym(fun);
3580 lbm_uint fun_kind = SYMBOL_KIND(fun_val)((fun_val) >> 16);
3581
3582 switch (fun_kind) {
3583 case SYMBOL_KIND_EXTENSION1:
3584 call_fptr(extension_table[SYMBOL_IX(fun_val)((fun_val) & 0xFFFF)].fptr, fun_args, arg_count, ctx);
3585 if (blocking_extension) {
3586 blocking_extension = false0;
3587 if (is_atomic) {
3588 // Check atomic_error explicitly so that the mutex
3589 // can be released if there is an error.
3590 lbm_mutex_unlock(&blocking_extension_mutex);
3591 atomic_error();
3592 }
3593 if (blocking_extension_timeout) {
3594 blocking_extension_timeout = false0;
3595 block_current_ctx(LBM_THREAD_STATE_TIMEOUT(uint32_t)2u, blocking_extension_timeout_us,true1);
3596 } else {
3597 block_current_ctx(LBM_THREAD_STATE_BLOCKED(uint32_t)1u, 0,true1);
3598 }
3599 lbm_mutex_unlock(&blocking_extension_mutex);
3600 }
3601 break;
3602 case SYMBOL_KIND_FUNDAMENTAL2:
3603 call_fptr(fundamental_table[SYMBOL_IX(fun_val)((fun_val) & 0xFFFF)], fun_args, arg_count, ctx);
3604 break;
3605 case SYMBOL_KIND_APPFUN3:
3606 fun_table[SYMBOL_IX(fun_val)((fun_val) & 0xFFFF)](&fun_args[1], arg_count, ctx);
3607 break;
3608 default:
3609 // Symbols that are "special" but not in the way caught above
3610 // ends up here.
3611 lbm_set_error_reason("Symbol does not represent a function");
3612 ERROR_AT_CTX(ENC_SYM_EERROR,fun_args[0])error_at_ctx((((0x22) << 4) | 0x00000000u), fun_args[0]
)
;
3613 break;
3614 }
3615}
3616
3617// cont_cloure_application_args
3618//
3619// s[sp-5] = environment to evaluate the args in.
3620// s[sp-4] = body
3621// s[sp-3] = closure environment
3622// s[sp-2] = parameter list (Guaranteed cons cell)
3623// s[sp-1] = args list (Possibly NIL)
3624//
3625// ctx->r = evaluated argument.
3626static void cont_closure_application_args(eval_context_t *ctx) {
3627 lbm_uint* sptr = get_stack_ptr(ctx, 5);
3628
3629 // Not naming these (arg_env, exp, clo_env) may seem like
3630 // poor programming practice, but has a measureable effect on performance on STM32F4.
3631 // Possible reasons:
3632 // - Minute difference in register pressure.
3633 // - Difficulty optimizing across function calls with unknown behavior (unless the compiler
3634 // would analyze it) in relation to the context stack.
3635
3636 //lbm_value arg_env = (lbm_value)sptr[0];
3637 //lbm_value exp = (lbm_value)sptr[1];
3638 //lbm_value clo_env = (lbm_value)sptr[2];
3639 lbm_value params = (lbm_value)sptr[3];
3640 lbm_value args = (lbm_value)sptr[4];
3641
3642 lbm_cons_t *params_cell = lbm_ref_cell(params);
3643
3644 lbm_value binder = allocate_binding(params_cell->car, ctx->r, sptr[2]);
3645
3646 if (lbm_is_cons(args)) { // There are args
3647 lbm_cons_t *args_cell = lbm_ref_cell(args);
3648
3649 // params_cell->cdr is programmer entered syntax, we need to check if a cons
3650 if (lbm_is_cons(params_cell->cdr)) {
3651 sptr[2] = binder;
3652 sptr[3] = params_cell->cdr; // Guaranteed cons cell here
3653 sptr[4] = args_cell->cdr; // Possibly NIL
3654 stack_reserve(ctx,1)[0] = CLOSURE_ARGS(((13) << 2) | 0xF8000001u);
3655 } else { // Args but no params => REST_ARGS
3656 lbm_value rest_binder = allocate_binding(ENC_SYM_REST_ARGS(((0x30015) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), binder);
3657 sptr[2] = rest_binder;
3658 sptr[3] = args_cell->cdr;
3659 sptr[4] = get_car(rest_binder); // last element of rest_args so far
3660 stack_reserve(ctx,1)[0] = CLOSURE_ARGS_REST(((42) << 2) | 0xF8000001u);
3661 }
3662 ctx->curr_exp = args_cell->car;
3663 ctx->curr_env = sptr[0]; //arg_env;
3664 } else { // No args
3665 if (lbm_is_symbol_nil(params_cell->cdr)) { // No Parameters
3666 stack_drop(ctx, 5);
3667 ctx->curr_env = binder;
3668 ctx->curr_exp = sptr[1]; //exp;
3669 } else { // Not enough arguments
3670 lbm_set_error_reason((char*)lbm_error_str_num_args);
3671 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
3672 }
3673 }
3674}
3675
3676// cont_closure_args_rest
3677//
3678// s[sp-5] = environment to evaluate args in
3679// s[sp-4] = body
3680// s[sp-3] = closure environment
3681// s[sp-2] = argument list
3682// s[sp-1] = last cell in rest-args list so far.
3683static void cont_closure_args_rest(eval_context_t *ctx) {
3684 lbm_uint* sptr = get_stack_ptr(ctx, 5);
3685 lbm_value arg_env = (lbm_value)sptr[0];
3686 lbm_value exp = (lbm_value)sptr[1];
3687 lbm_value clo_env = (lbm_value)sptr[2];
3688 lbm_value args = (lbm_value)sptr[3];
3689 lbm_value last = (lbm_value)sptr[4];
3690 lbm_cons_t* heap = lbm_heap_state.heap;
3691#ifdef LBM_ALWAYS_GC
3692 gc();
3693#endif
3694 lbm_value binding = lbm_heap_state.freelist;
3695 if (binding == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
3696 gc();
3697 binding = lbm_heap_state.freelist;
3698 if (binding == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
3699 }
3700 lbm_uint binding_ix = lbm_dec_ptr(binding);
3701 lbm_heap_state.freelist = heap[binding_ix].cdr;
3702 lbm_heap_state.num_free -= 1;
3703 heap[binding_ix].car = ctx->r;
3704 heap[binding_ix].cdr = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
3705
3706 lbm_set_cdr(last, binding);
3707 sptr[4] = binding;
3708
3709 if (args == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
3710 stack_drop(ctx, 5);
3711 ctx->curr_env = clo_env;
3712 ctx->curr_exp = exp;
3713 } else {
3714 stack_reserve(ctx,1)[0] = CLOSURE_ARGS_REST(((42) << 2) | 0xF8000001u);
3715 sptr[3] = get_cdr(args);
3716 ctx->curr_exp = get_car(args);
3717 ctx->curr_env = arg_env;
3718 }
3719}
3720
3721
3722// cont_application_args
3723// Functions that take arguments passed on the stack, fundamental and apply_f.
3724//
3725// s[sp-3] = environment to evaluate arguments in.
3726// s[sp-2] = argument list (user input syntax)
3727// s[sp-1] = count
3728//
3729// ctx->r = function
3730static void cont_application_args(eval_context_t *ctx) {
3731 lbm_uint *sptr = get_stack_ptr(ctx, 3);
3732
3733 lbm_value env = sptr[0];
3734 lbm_value rest = sptr[1];
3735 lbm_value count = sptr[2];
3736
3737 ctx->curr_env = env;
3738 sptr[0] = ctx->r; // Function 1st then Arguments
3739 if (lbm_is_cons(rest)) { // rest is user input syntax, expensive check needed
3740 lbm_cons_t *cell = lbm_ref_cell(rest);
3741 sptr[1] = env;
3742 sptr[2] = cell->cdr;
3743 lbm_value *rptr = stack_reserve(ctx,2);
3744 rptr[0] = count + (1 << LBM_VAL_SHIFT4); // arithmetic on encoded value
3745 rptr[1] = APPLICATION_ARGS(((5) << 2) | 0xF8000001u);
3746 ctx->curr_exp = cell->car;
3747 } else { // tollerant for incorrect list termination.
3748 // No more arguments
3749 stack_drop(ctx, 2);
3750 lbm_uint nargs = lbm_dec_u(count);
3751 lbm_value *args = get_stack_ptr(ctx, (uint32_t)(nargs + 1));
3752 application(ctx,args, nargs);
3753 }
3754}
3755
3756// cont_and
3757//
3758// s[sp-2] = environment to evaluate args in.
3759// s[sp-1] = rest of argument list (user input syntax)
3760static void cont_and(eval_context_t *ctx) {
3761 lbm_value rest = ctx->K.data[--ctx->K.sp];
3762 lbm_value env = ctx->K.data[--ctx->K.sp];
3763 if (lbm_is_symbol_nil(ctx->r)) {
3764 ctx->app_cont = true1;
3765 } else if (lbm_is_cons(rest)) {
3766 lbm_cons_t *r_cell = lbm_ref_cell(rest);
3767 lbm_value *sptr = stack_reserve(ctx, 3);
3768 sptr[0] = env;
3769 sptr[1] = r_cell->cdr;
3770 sptr[2] = AND(((6) << 2) | 0xF8000001u);
3771 ctx->curr_env = env;
3772 ctx->curr_exp = r_cell->car;
3773 } else {
3774 ctx->app_cont = true1;
3775 }
3776}
3777
3778// cont_or
3779//
3780// s[sp-2] = environment to evaluate args in.
3781// s[sp-1] = rest of argument list (user input syntax)
3782static void cont_or(eval_context_t *ctx) {
3783 lbm_value rest = ctx->K.data[--ctx->K.sp];
3784 lbm_value env = ctx->K.data[--ctx->K.sp];
3785 if (!lbm_is_symbol_nil(ctx->r)) {
3786 ctx->app_cont = true1;
3787 } else if (lbm_is_cons(rest)) {
3788 lbm_value *sptr = stack_reserve(ctx, 3);
3789 lbm_cons_t *r_cell = lbm_ref_cell(rest);
3790 sptr[0] = env;
3791 sptr[1] = r_cell->cdr;
3792 sptr[2] = OR(((7) << 2) | 0xF8000001u);
3793 ctx->curr_exp = r_cell->car;
3794 ctx->curr_env = env;
3795 } else {
3796 // if we end up here we have traversed all arguments
3797 // and seen no non-nil. (see top case).
3798 ctx->app_cont = true1;
3799 }
3800}
3801
3802static void fill_binding_location(lbm_value key, lbm_value value, lbm_value env) {
3803 if (lbm_type_of(key) == LBM_TYPE_SYMBOL0x00000000u) {
3804 // NILs dual role makes it hard to detect the difference
3805 // between the end of a structural key or an attempt to use NIL as the key
3806 // or as part of big key.
3807 // NIL has been given the same role as dont care.
3808 if (lbm_dec_sym(key) >= RUNTIME_SYMBOLS_START0x40000) {
3809 lbm_env_modify_binding(env,key,value);
3810 } else {
3811 if (key == ENC_SYM_DONTCARE(((0x9) << 4) | 0x00000000u) || key == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) return;
3812 lbm_set_error_reason((char*)lbm_error_str_built_in);
3813 ERROR_AT_CTX(ENC_SYM_EERROR, key)error_at_ctx((((0x22) << 4) | 0x00000000u), key);
3814 }
3815 } else if (lbm_is_cons(key) &&
3816 lbm_is_cons(value)) {
3817 fill_binding_location(lbm_ref_cell(key)->car, lbm_ref_cell(value)->car, env);
3818 fill_binding_location(lbm_ref_cell(key)->cdr, lbm_ref_cell(value)->cdr, env);
3819 } else {
3820 lbm_set_error_reason("Incorrect type of key in binding");
3821 ERROR_AT_CTX(ENC_SYM_TERROR, key)error_at_ctx((((0x21) << 4) | 0x00000000u), key);
3822 }
3823}
3824
3825// cont_bind_to_key_rest
3826//
3827// s[sp-4] = expression to evaluate in final env
3828// s[sp-3] = rest of list of bindings
3829// s[sp-2] = env to evaluate values in (Modified along the way)
3830// s[sp-1] = key
3831//
3832// ctx->r = evaluated value to bind to key
3833static void cont_bind_to_key_rest(eval_context_t *ctx) {
3834
3835 lbm_value *sptr = get_stack_ptr(ctx, 4);
3836
3837 lbm_value rest = sptr[1];
3838 lbm_value env = sptr[2];
3839 lbm_value key = sptr[3];
3840
3841 fill_binding_location(key, ctx->r, env);
3842
3843 if (lbm_is_cons(rest)) {
3844 lbm_value car_rest = lbm_ref_cell(rest)->car;
3845 lbm_value cr = car_rest;
3846 lbm_value kv0, kv1;
3847 EXTRACT(cr, kv0)do { if (lbm_is_ptr(cr)) { lbm_cons_t *_cell = lbm_ref_cell(cr
); kv0 = _cell->car; cr = _cell->cdr; } else { kv0 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
;
3848 EXTRACT_NO_ADVANCE(cr, kv1)do { if (lbm_is_ptr(cr)) { lbm_cons_t *_cell = lbm_ref_cell(cr
); kv1 = _cell->car; } else { kv1 = (((0x0) << 4) | 0x00000000u
); } } while (0)
;
3849
3850 sptr[1] = lbm_ref_cell(rest)->cdr;
3851 sptr[3] = kv0;
3852 stack_reserve(ctx,1)[0] = BIND_TO_KEY_REST(((2) << 2) | 0xF8000001u);
3853 ctx->curr_exp = kv1;
3854 ctx->curr_env = env;
3855 } else {
3856 // Otherwise evaluate the expression in the populated env
3857 ctx->curr_exp = sptr[0];
3858 ctx->curr_env = env;
3859 stack_drop(ctx, 4);
3860 }
3861}
3862
3863// cont_if
3864//
3865// s[sp-2] = then/else list (user input syntax)
3866// s[sp-1] = environment
3867//
3868// ctx->r = evaluated condition
3869static void cont_if(eval_context_t *ctx) {
3870
3871 lbm_value arg = ctx->r;
3872
3873 lbm_value *sptr = pop_stack_ptr(ctx, 2);
3874
3875 ctx->curr_env = sptr[1];
3876 if (lbm_is_symbol_nil(arg)) {
3877 ctx->curr_exp = get_cadr(sptr[0]); // else branch
3878 } else {
3879 ctx->curr_exp = get_car(sptr[0]); // then branch
3880 }
3881}
3882
3883// cont_match
3884//
3885// s[sp-1] = patterns (user input syntax)
3886// s[sp-1] = orig_env
3887//
3888// ctx->r = expression to match against patterns
3889static void cont_match(eval_context_t *ctx) {
3890 lbm_value e = ctx->r;
3891
3892 lbm_uint *sptr = get_stack_ptr(ctx, 2);
3893 lbm_value patterns = (lbm_value)sptr[0];
3894 lbm_value orig_env = (lbm_value)sptr[1]; // restore enclosing environment.
3895 lbm_value new_env = orig_env;
3896
3897 if (lbm_is_symbol_nil(patterns)) {
3898 // no more patterns
3899 stack_drop(ctx, 2);
3900 ctx->r = ENC_SYM_NO_MATCH(((0x40) << 4) | 0x00000000u);
3901 ctx->app_cont = true1;
3902 } else if (lbm_is_cons(patterns)) {
3903 lbm_value match_case = lbm_ref_cell(patterns)->car;
3904 lbm_value pattern = get_car(match_case);
3905 lbm_value n1 = get_cadr(match_case);
3906 lbm_value n2 = get_cdr(get_cdr(match_case));
3907 lbm_value body;
3908 bool_Bool check_guard = false0;
3909 if (lbm_is_symbol_nil(n2)) { // TODO: Not a very robust check.
3910 body = n1;
3911 } else {
3912 body = get_car(n2);
3913 check_guard = true1;
3914 }
3915 bool_Bool is_match = match(pattern, e, &new_env, 0);
3916 if (is_match) {
3917 if (check_guard) {
3918 lbm_value *rptr = stack_reserve(ctx,5);
3919 sptr[0] = lbm_ref_cell(patterns)->cdr;
3920 sptr[1] = ctx->curr_env;
3921 rptr[0] = MATCH(((9) << 2) | 0xF8000001u);
3922 rptr[1] = new_env;
3923 rptr[2] = body;
3924 rptr[3] = e;
3925 rptr[4] = MATCH_GUARD(((24) << 2) | 0xF8000001u);
3926 ctx->curr_env = new_env;
3927 ctx->curr_exp = n1; // The guard
3928 } else {
3929 stack_drop(ctx, 2);
3930 ctx->curr_env = new_env;
3931 ctx->curr_exp = body;
3932 }
3933 } else {
3934 // set up for checking of next pattern
3935 sptr[0] = get_cdr(patterns);
3936 sptr[1] = orig_env;
3937 stack_reserve(ctx,1)[0] = MATCH(((9) << 2) | 0xF8000001u);
3938 // leave r unaltered
3939 ctx->app_cont = true1;
3940 }
3941 } else {
3942 ERROR_AT_CTX(ENC_SYM_TERROR, ENC_SYM_MATCH)error_at_ctx((((0x21) << 4) | 0x00000000u), (((0x108) <<
4) | 0x00000000u))
;
3943 }
3944}
3945
3946static void cont_exit_atomic(eval_context_t *ctx) {
3947 is_atomic = false0; // atomic blocks cannot nest!
3948 ctx->app_cont = true1;
3949}
3950
3951// cont_map:
3952//
3953// sptr[0]: s[sp-6] = Rest of the input list.
3954// sptr[1]: s[sp-5] = Environment to restore for the eval of each application.
3955// sptr[2]: s[sp-4] = Result list.
3956// sptr[3]: s[sp-3] = Cell that goes into result list after being populated with application result.
3957// sptr[4]: s[sp-2] = Ref to application.
3958// sptr[5]: s[sp-1] = Ref to application argument.
3959//
3960// ctx->r = eval result of previous application.
3961static void cont_map(eval_context_t *ctx) {
3962 lbm_value *sptr = get_stack_ptr(ctx, 6);
3963 lbm_value ls = sptr[0];
3964 lbm_value env = sptr[1];
3965 lbm_value t = sptr[3]; // known cons!
3966 lbm_ref_cell(t)->car = ctx->r;
3967 //lbm_set_car(t, ctx->r); // update car field tailmost position.
3968 if (lbm_is_cons(ls)) {
3969 lbm_cons_t *cell = lbm_ref_cell(ls); // already checked that cons.
3970 lbm_value next = cell->car;
3971 lbm_value rest = cell->cdr;
3972 sptr[0] = rest;
3973 stack_reserve(ctx,1)[0] = MAP(((23) << 2) | 0xF8000001u);
3974 lbm_ref_cell(sptr[5])->car = next; // update known cons
3975 //lbm_set_car(sptr[5], next); // new arguments
3976
3977 lbm_value elt = cons_with_gc(ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
3978 lbm_ref_cell(t)->cdr = elt;
3979 //lbm_set_cdr(t, elt);
3980 sptr[3] = elt; // (r1 ... rN . (nil . nil))
3981 ctx->curr_exp = sptr[4];
3982 ctx->curr_env = env;
3983 } else {
3984 ctx->r = sptr[2]; //head of result list
3985 ctx->curr_env = env;
3986 stack_drop(ctx, 6);
3987 ctx->app_cont = true1;
3988 }
3989}
3990
3991static void cont_match_guard(eval_context_t *ctx) {
3992 if (lbm_is_symbol_nil(ctx->r)) {
3993 lbm_value e = ctx->K.data[--ctx->K.sp];
3994 stack_drop(ctx, 2);
3995 ctx->r = e;
3996 ctx->app_cont = true1;
3997 } else {
3998 stack_drop(ctx, 1);
3999 lbm_value body = ctx->K.data[--ctx->K.sp];
4000 lbm_value env = ctx->K.data[--ctx->K.sp];
4001 stack_drop(ctx, 3);
4002 ctx->curr_env = env;
4003 ctx->curr_exp = body;
4004 }
4005}
4006
4007static void cont_terminate(eval_context_t *ctx) {
4008 ERROR_CTX(ctx->r)error_ctx(ctx->r);
4009}
4010
4011static void cont_loop(eval_context_t *ctx) {
4012 lbm_value *sptr = get_stack_ptr(ctx, 3);
4013 stack_reserve(ctx,1)[0] = LOOP_CONDITION(((39) << 2) | 0xF8000001u);
4014 ctx->curr_env = sptr[2];
4015 ctx->curr_exp = sptr[1];
4016}
4017
4018static void cont_loop_condition(eval_context_t *ctx) {
4019 if (lbm_is_symbol_nil(ctx->r)) {
4020 stack_drop(ctx, 3);
4021 ctx->app_cont = true1; // A loop returns nil? Makes sense to me... but in general?
4022 return;
4023 }
4024 lbm_value *sptr = get_stack_ptr(ctx, 3);
4025 stack_reserve(ctx,1)[0] = LOOP(((38) << 2) | 0xF8000001u);
4026 ctx->curr_env = sptr[2];
4027 ctx->curr_exp = sptr[0];
4028}
4029
4030static void cont_loop_env_prep(eval_context_t *ctx) {
4031 lbm_value *sptr = get_stack_ptr(ctx, 3);
4032 sptr[2] = ctx->curr_env;
4033 stack_reserve(ctx,1)[0] = LOOP_CONDITION(((39) << 2) | 0xF8000001u);
4034 ctx->curr_exp = sptr[1];
4035}
4036
4037static void cont_merge_rest(eval_context_t *ctx) {
4038 lbm_uint *sptr = get_stack_ptr(ctx, 9);
4039
4040 // If comparator returns true (result is in ctx->r):
4041 // "a" should be moved to the last element position in merged list.
4042 // A new element from "a_rest" should be moved into comparator argument 1 pos.
4043 // else
4044 // "b" should be moved to last element position in merged list.
4045 // A new element from "b_rest" should be moved into comparator argument 2 pos.
4046 //
4047 // If a_rest or b_rest is NIL:
4048 // we are done, the remaining elements of
4049 // non_nil list should be appended to merged list.
4050 // else
4051 // Set up for a new comparator evaluation and recurse.
4052 lbm_value a = sptr[2];
4053 lbm_value b = lbm_cdr(a);
4054 lbm_set_cdr(a, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)); // terminate 1 element list
4055
4056 if (ctx->r == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) { // Comparison false
4057
4058 if (sptr[0] == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4059 sptr[0] = b;
4060 sptr[1] = b;
4061 } else {
4062 lbm_set_cdr(sptr[1], b);
4063 sptr[1] = b;
4064 }
4065 if (sptr[4] == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4066 lbm_set_cdr(a, sptr[3]);
4067 lbm_set_cdr(sptr[1], a);
4068 ctx->r = sptr[0];
4069 stack_drop(ctx, 9);
4070 ctx->app_cont = true1;
4071 return;
4072 } else {
4073 b = sptr[4];
4074 sptr[4] = lbm_cdr(sptr[4]);
4075 lbm_set_cdr(b, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
4076 }
4077 } else {
4078 if (sptr[0] == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4079 sptr[0] = a;
4080 sptr[1] = a;
4081 } else {
4082 lbm_set_cdr(sptr[1], a);
4083 sptr[1] = a;
4084 }
4085
4086 if (sptr[3] == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4087 lbm_set_cdr(b, sptr[4]);
4088 lbm_set_cdr(sptr[1], b);
4089 ctx->r = sptr[0];
4090 stack_drop(ctx, 9);
4091 ctx->app_cont = true1;
4092 return;
4093 } else {
4094 a = sptr[3];
4095 sptr[3] = lbm_cdr(sptr[3]);
4096 lbm_set_cdr(a, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
4097 }
4098 }
4099 lbm_set_cdr(a, b);
4100 sptr[2] = a;
4101
4102 lbm_value par1 = sptr[7];
4103 lbm_value par2 = sptr[8];
4104 lbm_value cmp_body = sptr[5];
4105 lbm_value cmp_env = sptr[6];
4106 // Environment should be preallocated already at this point
4107 // and the operations below should never need GC.
4108 lbm_value new_env0 = lbm_env_set(cmp_env, par1, lbm_car(a));
4109 lbm_value new_env = lbm_env_set(new_env0, par2, lbm_car(b));
4110 if (lbm_is_symbol(new_env0) || lbm_is_symbol(new_env)) {
4111 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4112 }
4113 cmp_env = new_env;
4114
4115 stack_reserve(ctx,1)[0] = MERGE_REST(((40) << 2) | 0xF8000001u);
4116 ctx->curr_exp = cmp_body;
4117 ctx->curr_env = cmp_env;
4118}
4119
4120// merge_layer stack contents
4121// s[sp-9] = cmp
4122// s[sp-8] = cmp_env
4123// s[sp-7] = par1
4124// s[sp-6] = par2
4125// s[sp-5] = acc - first cell
4126// s[sp-4] = acc - last cell
4127// s[sp-3] = rest;
4128// s[sp-2] = layer
4129// s[sp-1] = length or original list
4130//
4131// ctx->r merged sublist
4132static void cont_merge_layer(eval_context_t *ctx) {
4133 lbm_uint *sptr = get_stack_ptr(ctx, 9);
4134 lbm_int layer = lbm_dec_i(sptr[7]);
4135 lbm_int len = lbm_dec_i(sptr[8]);
4136
4137 lbm_value r_curr = ctx->r;
4138 while (lbm_is_cons(r_curr)) {
4139 lbm_value next = lbm_ref_cell(r_curr)->cdr;
4140 if (next == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4141 break;
4142 }
4143 r_curr = next;
4144 }
4145
4146 if (sptr[4] == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4147 sptr[4] = ctx->r;
4148 sptr[5] = r_curr;
4149 } else {
4150 lbm_set_cdr(sptr[5], ctx->r); // accumulate merged sublists.
4151 sptr[5] = r_curr;
4152 }
4153
4154 lbm_value layer_rest = sptr[6];
4155 // switch layer or done ?
4156 if (layer_rest == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4157 if (layer * 2 >= len) {
4158 ctx->r = sptr[4];
4159 ctx->app_cont = true1;
4160 stack_drop(ctx, 9);
4161 return;
4162 } else {
4163 // Setup for merges of the next layer
4164 layer = layer * 2;
4165 sptr[7] = lbm_enc_i(layer);
4166 layer_rest = sptr[4]; // continue on the accumulation of all sublists.
4167 sptr[5] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4168 sptr[4] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4169 }
4170 }
4171 // merge another sublist based on current layer.
4172 lbm_value a_list = layer_rest;
4173 // build sublist a
4174 lbm_value curr = layer_rest;
4175 for (int i = 0; i < layer-1; i ++) {
4176 if (lbm_is_cons(curr)) {
4177 curr = lbm_ref_cell(curr)->cdr;
4178 } else {
4179 break;
4180 }
4181 }
4182 layer_rest = lbm_cdr(curr);
4183 lbm_set_cdr(curr, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)); //terminate sublist.
4184
4185 lbm_value b_list = layer_rest;
4186 // build sublist b
4187 curr = layer_rest;
4188 for (int i = 0; i < layer-1; i ++) {
4189 if (lbm_is_cons(curr)) {
4190 curr = lbm_ref_cell(curr)->cdr;
4191 } else {
4192 break;
4193 }
4194 }
4195 layer_rest = lbm_cdr(curr);
4196 lbm_set_cdr(curr, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)); //terminate sublist.
4197
4198 sptr[6] = layer_rest;
4199
4200 if (b_list == ENC_SYM_NIL(((0x0) << 4) | 0x00000000u)) {
4201 stack_reserve(ctx,1)[0] = MERGE_LAYER(((41) << 2) | 0xF8000001u);
4202 ctx->r = a_list;
4203 ctx->app_cont = true1;
4204 return;
4205 }
4206 // Set up for a merge of sublists.
4207
4208 lbm_value a_rest = lbm_cdr(a_list);
4209 lbm_value b_rest = lbm_cdr(b_list);
4210 lbm_value a = a_list;
4211 lbm_value b = b_list;
4212 lbm_set_cdr(a, b);
4213 // Terminating the b list would be incorrect here
4214 // if there was any chance that the environment update below
4215 // performs GC.
4216 lbm_set_cdr(b, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
4217
4218 lbm_value cmp_body = sptr[0];
4219 lbm_value cmp_env = sptr[1];
4220 lbm_value par1 = sptr[2];
4221 lbm_value par2 = sptr[3];
4222 // Environment should be preallocated already at this point
4223 // and the operations below should never need GC.
4224 lbm_value new_env0 = lbm_env_set(cmp_env, par1, lbm_car(a));
4225 lbm_value new_env = lbm_env_set(cmp_env, par2, lbm_car(b));
4226 if (lbm_is_symbol(new_env0) || lbm_is_symbol(new_env)) {
4227 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4228 }
4229 cmp_env = new_env;
4230
4231 lbm_uint *merge_cont = stack_reserve(ctx, 11);
4232 merge_cont[0] = MERGE_LAYER(((41) << 2) | 0xF8000001u);
4233 merge_cont[1] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4234 merge_cont[2] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4235 merge_cont[3] = a;
4236 merge_cont[4] = a_rest;
4237 merge_cont[5] = b_rest;
4238 merge_cont[6] = cmp_body;
4239 merge_cont[7] = cmp_env;
4240 merge_cont[8] = par1;
4241 merge_cont[9] = par2;
4242 merge_cont[10] = MERGE_REST(((40) << 2) | 0xF8000001u);
4243 ctx->curr_exp = cmp_body;
4244 ctx->curr_env = cmp_env;
4245 return;
4246}
4247
4248/****************************************************/
4249/* READER */
4250
4251static void error_on_invalid_read_result(lbm_char_channel_t *str, eval_context_t *ctx) {
4252 if (lbm_is_symbol(ctx->r)) {
4253 lbm_uint sym_val = lbm_dec_sym(ctx->r);
4254 if (sym_val >= TOKENIZER_SYMBOLS_START0x70 &&
4255 sym_val <= TOKENIZER_SYMBOLS_END0x87) {
4256 READ_ERROR_CTX(lbm_channel_row(str), lbm_channel_column(str))read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4257 }
4258 }
4259}
4260
4261static void read_finish(lbm_char_channel_t *str, eval_context_t *ctx) {
4262
4263 /* Tokenizer reached "end of file"
4264 The parser could be in a state where it needs
4265 more tokens to correctly finish an expression.
4266
4267 Four cases
4268 1. The program / expression is malformed and the context should die.
4269 2. We are finished reading a program and should close off the
4270 internal representation with a closing parenthesis. Then
4271 apply continuation.
4272 3. We are finished reading an expression and should
4273 apply the continuation
4274 4. We are finished read-and-evaluating
4275
4276 In case 2, we should find the READ_DONE at sp - 4.
4277 In case 3, we should find the READ_DONE at sp - 1.
4278 In case 4, we should find the READ_DONE at sp - 3.
4279
4280 case 3 should not end up here, but rather end up in
4281 cont_read_done.
4282 */
4283
4284 error_on_invalid_read_result(str, ctx);
4285
4286 if (ctx->K.sp > 4 && (ctx->K.data[ctx->K.sp - 3] == READ_DONE(((20) << 2) | 0xF8000001u)) &&
4287 (ctx->K.data[ctx->K.sp - 4] == READING_PROGRAM_INCREMENTALLY((2 << 4) | 0x0000000Cu))) {
4288 /* read and evaluate is done */
4289 --ctx->K.sp; // Pop READ_EVAL_CONTINUE
4290 lbm_value env = ctx->K.data[--ctx->K.sp];
4291 ctx->curr_env = env;
4292 ctx->app_cont = true1; // Program evaluated and result is in ctx->r.
4293 } else if (ctx->K.sp > 5 && (ctx->K.data[ctx->K.sp - 4] == READ_DONE(((20) << 2) | 0xF8000001u)) &&
4294 (ctx->K.data[ctx->K.sp - 5] == READING_PROGRAM((1 << 4) | 0x0000000Cu))) {
4295 /* successfully finished reading a program (CASE 2) */
4296 ctx->r = ENC_SYM_CLOSEPAR(((0x71) << 4) | 0x00000000u);
4297 ctx->app_cont = true1; // Perform the final READ_APPEND_CONTINUE
4298 } else {
4299 if (lbm_channel_row(str) == 1 && lbm_channel_column(str) == 1) {
4300 // (read "") evaluates to nil.
4301 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4302 ctx->app_cont = true1;
4303 } else {
4304 lbm_channel_reader_close(str);
4305 lbm_set_error_reason((char*)lbm_error_str_parse_eof);
4306 READ_ERROR_CTX(lbm_channel_row(str), lbm_channel_column(str))read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4307 }
4308 }
4309}
4310
4311/* cont_read_next_token
4312 uses ctx->reader_stream
4313 ctx->r : Input value ignored.
4314*/
4315static void cont_read_next_token(eval_context_t *ctx) {
4316
4317 lbm_char_channel_t *chan = lbm_dec_channel(ctx->reader_stream);
4318
4319 if (chan == NULL((void*)0) || chan->state == NULL((void*)0)) {
4320 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4321 }
4322
4323 if (!lbm_channel_more(chan) && lbm_channel_is_empty(chan)) {
4324 read_finish(chan, ctx);
4325 return;
4326 }
4327 /* Eat whitespace and comments */
4328 if (!tok_clean_whitespace(chan)) {
4329 stack_reserve(ctx,1)[0] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4330 yield_ctx(EVAL_CPS_MIN_SLEEP200);
4331 return;
4332 }
4333 /* After eating whitespace we may be at end of file/stream */
4334 if (!lbm_channel_more(chan) && lbm_channel_is_empty(chan)) {
4335 read_finish(chan, ctx);
4336 return;
4337 }
4338
4339 /* Attempt to extract tokens from the character stream */
4340 int n = 0;
4341 lbm_value res = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4342 unsigned int string_len = 0;
4343
4344 /*
4345 * SYNTAX
4346 */
4347 uint32_t tok_match;
4348 n = tok_syntax(chan, &tok_match);
4349 if (n > 0) {
4350 if (!lbm_channel_drop(chan, (unsigned int)n)) {
4351 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4352 }
4353 lbm_value compound_read_start = READ_START_BYTEARRAY(((21) << 2) | 0xF8000001u);
4354 lbm_value compound_value_closer = ENC_SYM_CLOSEBRACK(((0x81) << 4) | 0x00000000u);
4355 lbm_value compound_value_opener = ENC_SYM_OPENBRACK(((0x80) << 4) | 0x00000000u);
4356 switch(tok_match) {
4357 case TOKOPENPAR1u: {
4358 lbm_value *rptr = stack_reserve(ctx,3);
4359 rptr[0] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4360 rptr[1] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4361 rptr[2] = READ_APPEND_CONTINUE(((16) << 2) | 0xF8000001u);
4362 ctx->r = ENC_SYM_OPENPAR(((0x70) << 4) | 0x00000000u); // This return value is used in case the stream is ended here.
4363 // The stream having no more data after an OPENPAR is an error
4364 // and read_finish will make use of this info to issue an error.
4365 } break;
4366 case TOKCLOSEPAR2u: {
4367 ctx->r = ENC_SYM_CLOSEPAR(((0x71) << 4) | 0x00000000u);
4368 ctx->app_cont = true1;
4369 } return;
4370 case TOKOPENARRAY16u:
4371 // Switch to array reader
4372 compound_read_start = READ_START_ARRAY(((49) << 2) | 0xF8000001u);
4373 compound_value_opener = ENC_SYM_OPENARRAY(((0x86) << 4) | 0x00000000u); /* fall through */
4374 case TOKOPENBRACK3u: {
4375 lbm_value *rptr = stack_reserve(ctx, 1);
4376 rptr[0] = compound_read_start;
4377 ctx->r = compound_value_opener;
4378 } break;
4379 case TOKCLOSEARRAY17u:
4380 compound_value_closer = ENC_SYM_CLOSEARRAY(((0x87) << 4) | 0x00000000u); /* fall through */
4381 case TOKCLOSEBRACK4u:
4382 ctx->r = compound_value_closer;
4383 ctx->app_cont = true1;
4384 return;
4385 case TOKDOT5u:
4386 ctx->r = ENC_SYM_DOT(((0x76) << 4) | 0x00000000u);
4387 ctx->app_cont = true1;
4388 return;
4389 case TOKDONTCARE6u:
4390 ctx->r = ENC_SYM_DONTCARE(((0x9) << 4) | 0x00000000u);
4391 ctx->app_cont = true1;
4392 return;
4393 case TOKQUOTE7u: {
4394 lbm_value *rptr = stack_reserve(ctx, 2);
4395 rptr[0] = ENC_SYM_QUOTE(((0x100) << 4) | 0x00000000u);
4396 rptr[1] = WRAP_RESULT(((47) << 2) | 0xF8000001u);
4397 }break;
4398 case TOKBACKQUOTE8u:
4399 stack_reserve(ctx, 1)[0] = QQ_EXPAND_START(((32) << 2) | 0xF8000001u);
4400 break;
4401 case TOKCOMMAAT9u: {
4402 lbm_value *rptr = stack_reserve(ctx, 2);
4403 rptr[0] = ENC_SYM_COMMAAT(((0x74) << 4) | 0x00000000u);
4404 rptr[1] = WRAP_RESULT(((47) << 2) | 0xF8000001u);
4405 } break;
4406 case TOKCOMMA10u: {
4407 lbm_value *rptr = stack_reserve(ctx, 2);
4408 rptr[0] = ENC_SYM_COMMA(((0x73) << 4) | 0x00000000u);
4409 rptr[1] = WRAP_RESULT(((47) << 2) | 0xF8000001u);
4410 } break;
4411 case TOKMATCHANY11u:
4412 ctx->r = ENC_SYM_MATCH_ANY(((0x41) << 4) | 0x00000000u);
4413 ctx->app_cont = true1;
4414 return;
4415 case TOKOPENCURL12u: {
4416 lbm_value *rptr = stack_reserve(ctx,3);
4417 rptr[0] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4418 rptr[1] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4419 rptr[2] = READ_APPEND_CONTINUE(((16) << 2) | 0xF8000001u);
4420 ctx->r = ENC_SYM_PROGN(((0x102) << 4) | 0x00000000u);
4421 ctx->app_cont = true1;
4422 } return;
4423 case TOKCLOSECURL13u:
4424 ctx->r = ENC_SYM_CLOSEPAR(((0x71) << 4) | 0x00000000u);
4425 ctx->app_cont = true1;
4426 return;
4427 case TOKCONSTSTART14u: /* fall through */
4428 case TOKCONSTEND15u: {
4429 if (tok_match == TOKCONSTSTART14u) ctx->flags |= EVAL_CPS_CONTEXT_FLAG_CONST(uint32_t)0x02;
4430 if (tok_match == TOKCONSTEND15u) ctx->flags &= ~EVAL_CPS_CONTEXT_FLAG_CONST(uint32_t)0x02;
4431 stack_reserve(ctx,1)[0] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4432 ctx->app_cont = true1;
4433 } return;
4434 default:
4435 READ_ERROR_CTX(lbm_channel_row(chan), lbm_channel_column(chan))read_error_ctx(lbm_channel_row(chan), lbm_channel_column(chan
))
;
4436 }
4437 // read next token
4438 stack_reserve(ctx, 1)[0] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4439 ctx->app_cont = true1;
4440 return;
4441 } else if (n < 0) goto retry_token;
4442
4443 /*
4444 * STRING
4445 */
4446 n = tok_string(chan, &string_len);
4447 if (n >= 2) {
4448 lbm_channel_drop(chan, (unsigned int)n);
4449#ifdef LBM_ALWAYS_GC
4450 gc();
4451#endif
4452 if (!lbm_heap_allocate_array(&res, (unsigned int)(string_len+1))) {
4453 gc();
4454 lbm_heap_allocate_array(&res, (unsigned int)(string_len+1));
4455 }
4456 if (lbm_is_ptr(res)) {
4457 lbm_array_header_t *arr = assume_array(res);
4458 char *data = (char*)arr->data;
4459 memset(data,0, string_len + 1);
4460 memcpy(data, tokpar_sym_str, string_len);
4461 ctx->r = res;
4462 ctx->app_cont = true1;
4463 return;
4464 } else {
4465 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
4466 }
4467 } else if (n < 0) goto retry_token;
4468
4469 /*
4470 * FLOAT
4471 */
4472 token_float f_val;
4473 n = tok_double(chan, &f_val);
4474 if (n > 0) {
4475 lbm_channel_drop(chan, (unsigned int) n);
4476 switch(f_val.type) {
4477 case TOKTYPEF32107u:
4478 WITH_GC(res, lbm_enc_float((float)f_val.value))(res) = (lbm_enc_float((float)f_val.value)); if (lbm_is_symbol_merror
((res))) { gc(); (res) = (lbm_enc_float((float)f_val.value));
if (lbm_is_symbol_merror((res))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
4479 break;
4480 case TOKTYPEF64108u:
4481 res = lbm_enc_double(f_val.value);
4482 break;
4483 default:
4484 READ_ERROR_CTX(lbm_channel_row(chan), lbm_channel_column(chan))read_error_ctx(lbm_channel_row(chan), lbm_channel_column(chan
))
;
4485 }
4486 ctx->r = res;
4487 ctx->app_cont = true1;
4488 return;
4489 } else if (n < 0) goto retry_token;
4490
4491 /*
4492 * INTEGER
4493 */
4494 token_int int_result;
4495 n = tok_integer(chan, &int_result);
4496 if (n > 0) {
4497 lbm_channel_drop(chan, (unsigned int)n);
4498 switch(int_result.type) {
4499 case TOKTYPEBYTE100u:
4500 res = lbm_enc_char((uint8_t)(int_result.negative ? -int_result.value : int_result.value));
4501 break;
4502 case TOKTYPEI101u:
4503 res = lbm_enc_i((lbm_int)(int_result.negative ? -int_result.value : int_result.value));
4504 break;
4505 case TOKTYPEU102u:
4506 res = lbm_enc_u((lbm_uint)(int_result.negative ? -int_result.value : int_result.value));
4507 break;
4508 case TOKTYPEI32103u:
4509 WITH_GC(res, lbm_enc_i32((int32_t)(int_result.negative ? -int_result.value : int_result.value)))(res) = (lbm_enc_i32((int32_t)(int_result.negative ? -int_result
.value : int_result.value))); if (lbm_is_symbol_merror((res))
) { gc(); (res) = (lbm_enc_i32((int32_t)(int_result.negative ?
-int_result.value : int_result.value))); if (lbm_is_symbol_merror
((res))) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
4510 break;
4511 case TOKTYPEU32104u:
4512 WITH_GC(res,lbm_enc_u32((uint32_t)(int_result.negative ? -int_result.value : int_result.value)))(res) = (lbm_enc_u32((uint32_t)(int_result.negative ? -int_result
.value : int_result.value))); if (lbm_is_symbol_merror((res))
) { gc(); (res) = (lbm_enc_u32((uint32_t)(int_result.negative
? -int_result.value : int_result.value))); if (lbm_is_symbol_merror
((res))) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
4513 break;
4514 case TOKTYPEI64105u:
4515 WITH_GC(res,lbm_enc_i64((int64_t)(int_result.negative ? -int_result.value : int_result.value)))(res) = (lbm_enc_i64((int64_t)(int_result.negative ? -int_result
.value : int_result.value))); if (lbm_is_symbol_merror((res))
) { gc(); (res) = (lbm_enc_i64((int64_t)(int_result.negative ?
-int_result.value : int_result.value))); if (lbm_is_symbol_merror
((res))) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
4516 break;
4517 case TOKTYPEU64106u:
4518 WITH_GC(res,lbm_enc_u64((uint64_t)(int_result.negative ? -int_result.value : int_result.value)))(res) = (lbm_enc_u64((uint64_t)(int_result.negative ? -int_result
.value : int_result.value))); if (lbm_is_symbol_merror((res))
) { gc(); (res) = (lbm_enc_u64((uint64_t)(int_result.negative
? -int_result.value : int_result.value))); if (lbm_is_symbol_merror
((res))) { error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
4519 break;
4520 default:
4521 READ_ERROR_CTX(lbm_channel_row(chan), lbm_channel_column(chan))read_error_ctx(lbm_channel_row(chan), lbm_channel_column(chan
))
;
4522 }
4523 ctx->r = res;
4524 ctx->app_cont = true1;
4525 return;
4526 } else if (n < 0) goto retry_token;
4527
4528 /*
4529 * SYMBOL
4530 */
4531 n = tok_symbol(chan);
4532 if (n > 0) {
4533 lbm_channel_drop(chan, (unsigned int) n);
4534 lbm_uint symbol_id;
4535 if (!lbm_get_symbol_by_name(tokpar_sym_str, &symbol_id)) {
4536 int r = 0;
4537
4538 // Checked for every symbol read.
4539 if (n > 4 &&
4540 (memcmp(tokpar_sym_str, "ext-", 4) == 0)) {
4541
4542 // "ext-" symbols shouldnt have a regular symbol-id.
4543 // These symbols take a slot in the extension table
4544 // and follow a specialised lookup procedure.
4545 lbm_uint id;
4546 if (!lbm_lookup_extension_id(tokpar_sym_str, &id)) {
4547 lbm_uint ext_name_len = (lbm_uint)n + 1;
4548#ifdef LBM_ALWAYS_GC
4549 gc();
4550#endif
4551 char *ext_name = lbm_malloc(ext_name_len);
4552 if (!ext_name) {
4553 gc();
4554 ext_name = lbm_malloc(ext_name_len);
4555 }
4556 if (ext_name) {
4557 memcpy(ext_name, tokpar_sym_str, ext_name_len);
4558 lbm_add_extension(ext_name, lbm_extensions_default);
4559 } else {
4560 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
4561 }
4562 }
4563 // TODO: Change API so that an extra O(N) not needed?
4564 if (!lbm_lookup_extension_id(tokpar_sym_str, &id)) {
4565 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4566 }
4567 symbol_id = id;
4568 r = 1;
4569 } else {
4570 r = lbm_add_symbol_base(tokpar_sym_str, &symbol_id);
4571 }
4572 if (!r) {
4573 READ_ERROR_CTX(lbm_channel_row(chan), lbm_channel_column(chan))read_error_ctx(lbm_channel_row(chan), lbm_channel_column(chan
))
;
4574 }
4575 }
4576 ctx->r = lbm_enc_sym(symbol_id);
4577 ctx->app_cont = true1;
4578 return;
4579 } else if (n == TOKENIZER_NEED_MORE-1) {
4580 goto retry_token;
4581 } else if (n <= TOKENIZER_STRING_ERROR-2) {
4582 READ_ERROR_CTX(lbm_channel_row(chan), lbm_channel_column(chan))read_error_ctx(lbm_channel_row(chan), lbm_channel_column(chan
))
;
4583 }
4584
4585 /*
4586 * CHAR
4587 */
4588 char c_val;
4589 n = tok_char(chan, &c_val);
4590 if(n > 0) {
4591 lbm_channel_drop(chan,(unsigned int) n);
4592 ctx->r = lbm_enc_char((uint8_t)c_val);
4593 ctx->app_cont = true1;
4594 return;
4595 }else if (n < 0) goto retry_token;
4596
4597 READ_ERROR_CTX(lbm_channel_row(chan), lbm_channel_column(chan))read_error_ctx(lbm_channel_row(chan), lbm_channel_column(chan
))
;
4598
4599 retry_token:
4600 if (n == TOKENIZER_NEED_MORE-1) {
4601 stack_reserve(ctx,1)[0] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4602 yield_ctx(EVAL_CPS_MIN_SLEEP200);
4603 return;
4604 }
4605 READ_ERROR_CTX(lbm_channel_row(chan), lbm_channel_column(chan))read_error_ctx(lbm_channel_row(chan), lbm_channel_column(chan
))
;
4606}
4607
4608static void cont_read_start_bytearray(eval_context_t *ctx) {
4609 lbm_char_channel_t *str = lbm_dec_channel(ctx->reader_stream);
4610 if (str == NULL((void*)0) || str->state == NULL((void*)0)) {
4611 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4612 return; // INFER does not understand that error_ctx longjmps out
4613 // of this function here.
4614 }
4615 if (ctx->r == ENC_SYM_CLOSEBRACK(((0x81) << 4) | 0x00000000u)) {
4616 lbm_value array;
4617
4618 if (!lbm_heap_allocate_array(&array, 0)) {
4619 gc();
4620 if (!lbm_heap_allocate_array(&array, 0)) {
4621 lbm_set_error_reason((char*)lbm_error_str_read_no_mem);
4622 lbm_channel_reader_close(str);
4623 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u)); // Terminates ctx
4624 }
4625 }
4626 ctx->r = array;
4627 ctx->app_cont = true1;
4628 } else if (lbm_is_number(ctx->r)) {
4629#ifdef LBM_ALWAYS_GC
4630 gc();
4631#endif
4632 lbm_uint num_free = lbm_memory_longest_free();
4633 lbm_uint initial_size = (lbm_uint)((float)num_free * 0.9);
4634 if (initial_size == 0) {
4635 gc();
4636 num_free = lbm_memory_longest_free();
4637 initial_size = (lbm_uint)((float)num_free * 0.9);
4638 if (initial_size == 0) {
4639 lbm_channel_reader_close(str);
4640 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
4641 }
4642 }
4643 lbm_value array;
4644 // lbm_memory should not be large enough
4645 // for this to overflow a 32bit number.
4646 initial_size = sizeof(lbm_uint) * initial_size;
4647
4648 // Keep in mind that this allocation can fail for both
4649 // lbm_memory and heap reasons.
4650 if (!lbm_heap_allocate_array(&array, initial_size)) {
4651 gc();
4652 if (!lbm_heap_allocate_array(&array, initial_size)) {
4653 lbm_set_error_reason((char*)lbm_error_str_read_no_mem);
4654 lbm_channel_reader_close(str);
4655 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4656 // NOTE: If array is not created evaluation ends here.
4657 // Static analysis seems unaware.
4658 }
4659 }
4660
4661
4662 lbm_value *rptr = stack_reserve(ctx, 4);
4663 rptr[0] = array;
4664 rptr[1] = lbm_enc_u(initial_size);
4665 rptr[2] = lbm_enc_u(0);
4666 rptr[3] = READ_APPEND_BYTEARRAY(((22) << 2) | 0xF8000001u);
4667 ctx->app_cont = true1;
4668 } else {
4669 lbm_channel_reader_close(str);
4670 READ_ERROR_CTX(lbm_channel_row(str), lbm_channel_column(str))read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4671 }
4672}
4673
4674static void cont_read_append_bytearray(eval_context_t *ctx) {
4675 lbm_uint *sptr = get_stack_ptr(ctx, 3);
4676
4677 lbm_value array = sptr[0];
4678 lbm_value size = lbm_dec_u(sptr[1]);
4679 lbm_value ix = lbm_dec_u(sptr[2]);
4680
4681 // This is an MERROR because if this comparison
4682 // is true, there is a literal byte array in the code
4683 // and it did not fit into the array we are reading into,
4684 // which is 90% of free memory.
4685 if (ix >= size) {
4686 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
4687 }
4688
4689 // if sptr[0] is not an array something is very very wrong.
4690 // Not robust against a garbage on stack. But how would garbage get onto stack?
4691 lbm_array_header_t *arr = assume_array(array);
4692 if (lbm_is_number(ctx->r)) {
4693 ((uint8_t*)arr->data)[ix] = (uint8_t)lbm_dec_as_u32(ctx->r);
4694
4695 sptr[2] = lbm_enc_u(ix + 1);
4696 lbm_value *rptr = stack_reserve(ctx, 2);
4697 rptr[0] = READ_APPEND_BYTEARRAY(((22) << 2) | 0xF8000001u);
4698 rptr[1] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4699 ctx->app_cont = true1;
4700 } else if (lbm_is_symbol(ctx->r) && ctx->r == ENC_SYM_CLOSEBRACK(((0x81) << 4) | 0x00000000u)) {
4701 lbm_uint array_size = ix / sizeof(lbm_uint);
4702
4703 if (ix % sizeof(lbm_uint) != 0) {
4704 array_size = array_size + 1;
4705 }
4706 lbm_memory_shrink((lbm_uint*)arr->data, array_size);
4707 arr->size = ix;
4708 stack_drop(ctx, 3);
4709 ctx->r = array;
4710 ctx->app_cont = true1;
4711 } else {
4712 ERROR_CTX(ENC_SYM_TERROR)error_ctx((((0x21) << 4) | 0x00000000u));
4713 }
4714}
4715
4716// Lisp array syntax reading ////////////////////////////////////////
4717
4718static void cont_read_start_array(eval_context_t *ctx) {
4719 lbm_char_channel_t *str = lbm_dec_channel(ctx->reader_stream);
4720 if (str == NULL((void*)0) || str->state == NULL((void*)0)) {
4721 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4722 return; // INFER does not understand that error_ctx longjmps out
4723 // of this function here.
4724 }
4725 if (ctx->r == ENC_SYM_CLOSEARRAY(((0x87) << 4) | 0x00000000u)) {
4726 lbm_value array;
4727
4728 if (!lbm_heap_allocate_lisp_array(&array, 0)) {
4729 gc();
4730 if (!lbm_heap_allocate_lisp_array(&array, 0)) {
4731 lbm_set_error_reason((char*)lbm_error_str_read_no_mem);
4732 lbm_channel_reader_close(str);
4733 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u)); // Terminates ctx
4734 }
4735 }
4736 ctx->r = array;
4737 ctx->app_cont = true1;
4738 } else {
4739#ifdef LBM_ALWAYS_GC
4740 gc();
4741#endif
4742 lbm_uint num = ((lbm_uint)((float)lbm_memory_longest_free() * 0.9) / sizeof(lbm_uint)) ;
4743 lbm_uint initial_size = (lbm_uint)num;
4744 if (initial_size == 0) {
4745 gc();
4746 num = ((lbm_uint)((float)lbm_memory_longest_free() * 0.9) / sizeof(lbm_uint)) ;
4747 initial_size = (lbm_uint)num;
4748 if (initial_size == 0) {
4749 lbm_channel_reader_close(str);
4750 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
4751 }
4752 }
4753 lbm_value array;
4754 // lbm_memory should not be large enough
4755 // for this to overflow a 32bit number.
4756 initial_size = sizeof(lbm_uint) * initial_size;
4757
4758 if (!lbm_heap_allocate_lisp_array(&array, initial_size)) {
4759 gc();
4760 if (!lbm_heap_allocate_lisp_array(&array, initial_size)) {
4761 lbm_set_error_reason((char*)lbm_error_str_read_no_mem);
4762 lbm_channel_reader_close(str);
4763 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4764 }
4765 }
4766
4767 lbm_value *rptr = stack_reserve(ctx, 4);
4768 rptr[0] = array;
4769 rptr[1] = lbm_enc_u(initial_size);
4770 rptr[2] = lbm_enc_u(0);
4771 rptr[3] = READ_APPEND_ARRAY(((50) << 2) | 0xF8000001u);
4772 ctx->app_cont = true1;
4773 }
4774}
4775
4776static void cont_read_append_array(eval_context_t *ctx) {
4777 lbm_uint *sptr = get_stack_ptr(ctx, 3);
4778
4779 lbm_value array = sptr[0];
4780 lbm_value size = lbm_dec_as_u32(sptr[1]);
4781 lbm_value ix = lbm_dec_as_u32(sptr[2]);
4782
4783 // This is a MERROR because if this comparison is true
4784 // it means that a literal lisp aray is requireing more that
4785 // 90% of currently free memory. The programmer should
4786 // be informed that her program uses too much memory.
4787 if (ix >= (size / sizeof(lbm_uint))) {
4788 ERROR_CTX(ENC_SYM_MERROR)error_ctx((((0x23) << 4) | 0x00000000u));
4789 }
4790
4791 // if sptr[0] is not an array something is very very wrong.
4792 // Not robust against a garbage on stack. But how would garbage get onto stack?
4793 lbm_array_header_t *arr = assume_array(array);
4794 if (lbm_is_symbol(ctx->r) && ctx->r == ENC_SYM_CLOSEARRAY(((0x87) << 4) | 0x00000000u)) {
4795 lbm_uint array_size = ix;
4796
4797 if (ix % sizeof(lbm_uint) != 0) {
4798 array_size = array_size + 1;
4799 }
4800 lbm_memory_shrink((lbm_uint*)arr->data, array_size);
4801 // Ix is small and ix * sizeof(lbm_uint) will not overflow.
4802 arr->size = ix * sizeof(lbm_uint);
4803 stack_drop(ctx, 3);
4804 ctx->r = array;
4805 ctx->app_cont = true1;
4806 } else {
4807 ((lbm_uint*)arr->data)[ix] = ctx->r;
4808
4809 sptr[2] = lbm_enc_u(ix + 1);
4810 lbm_value *rptr = stack_reserve(ctx, 2);
4811 rptr[0] = READ_APPEND_ARRAY(((50) << 2) | 0xF8000001u);
4812 rptr[1] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4813 ctx->app_cont = true1;
4814 }
4815}
4816
4817// read_grab_row leads into an implicit read_next_token.
4818static void cont_read_next_token_grab_row(eval_context_t *ctx) {
4819 lbm_char_channel_t *chan = lbm_dec_channel(ctx->reader_stream);
4820 if (chan == NULL((void*)0) || chan->state == NULL((void*)0)) {
4821 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4822 }
4823 ctx->row0 = (int32_t)lbm_channel_row(chan);
4824 ctx->row1 = -1; // a new start, end is unknown
4825 cont_read_next_token(ctx);
4826}
4827
4828// Lisp list syntax reading ////////////////////////////////////////
4829
4830static void cont_read_append_continue(eval_context_t *ctx) {
4831 lbm_value *sptr = get_stack_ptr(ctx, 2);
4832
4833 lbm_value first_cell = sptr[0];
4834 lbm_value last_cell = sptr[1];
4835
4836 lbm_char_channel_t *str = lbm_dec_channel(ctx->reader_stream);
4837 if (str == NULL((void*)0) || str->state == NULL((void*)0)) {
4838 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4839 }
4840
4841 if (lbm_is_symbol(ctx->r)) {
4842 switch(ctx->r) {
4843 case ENC_SYM_CLOSEPAR(((0x71) << 4) | 0x00000000u):
4844 // last_cell is either nil or a rw cons cell.
4845 if (lbm_is_symbol_nil(last_cell)) {
4846 ctx->r = last_cell;
4847 } else {
4848 // Here we know, by the principled use of the stack, that last_cell is a rw cons cell.
4849 lbm_ref_cell(last_cell)->cdr = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4850 // Could even rewrite as: lbm_heap_state.heap[lbm_dec_ptr(last_cell)].cdr = ENC_SYM_NIL;
4851 ctx->r = first_cell;
4852 }
4853 stack_drop(ctx, 2);
4854 // Skip reading another token and apply the continuation.
4855 ctx->app_cont = true1;
4856 return;
4857 case ENC_SYM_DOT(((0x76) << 4) | 0x00000000u): {
4858 lbm_value *rptr = stack_reserve(ctx, 2);
4859 rptr[0] = READ_DOT_TERMINATE(((19) << 2) | 0xF8000001u);
4860 rptr[1] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4861 ctx->app_cont = true1;
4862 } return;
4863 }
4864 }
4865 lbm_value new_cell = cons_with_gc(ctx->r, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
4866 // Does not return if merror. So we cannot get a read-error here
4867 // unless we write the a version of cons_with_gc here.
4868 //if (lbm_is_symbol_merror(new_cell)) {
4869 // lbm_channel_reader_close(str);
4870 // read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4871 // return;
4872 //}
4873 if (lbm_is_symbol_nil(last_cell)) {
4874 first_cell = last_cell = new_cell;
4875 } else {
4876 lbm_ref_cell(last_cell)->cdr = new_cell;
4877 last_cell = new_cell;
4878 }
4879
4880 sptr[0] = first_cell;
4881 sptr[1] = last_cell;
4882 lbm_value *rptr = stack_reserve(ctx, 2);
4883 rptr[0] = READ_APPEND_CONTINUE(((16) << 2) | 0xF8000001u);
4884 rptr[1] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4885 ctx->app_cont = true1;
4886}
4887
4888static void cont_read_eval_continue(eval_context_t *ctx) {
4889 lbm_value env;
4890 lbm_value *sptr = get_stack_ptr(ctx, 1);
4891 env = sptr[0];
4892 lbm_char_channel_t *str = lbm_dec_channel(ctx->reader_stream);
4893 if (str && str->state) {
4894 ctx->row1 = (lbm_int)str->row(str);
4895 if (lbm_type_of(ctx->r) == LBM_TYPE_SYMBOL0x00000000u) {
4896 switch(ctx->r) {
4897 case ENC_SYM_CLOSEPAR(((0x71) << 4) | 0x00000000u):
4898 stack_drop(ctx, 1);
4899 ctx->app_cont = true1;
4900 return;
4901 case ENC_SYM_DOT(((0x76) << 4) | 0x00000000u):
4902 // A dot here is a syntax error.
4903 lbm_set_error_reason((char*)lbm_error_str_parse_dot);
4904 READ_ERROR_CTX(lbm_channel_row(str),lbm_channel_column(str))read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4905 return;
4906 }
4907 }
4908 lbm_value *rptr = stack_reserve(ctx, 5);
4909 rptr[0] = READ_EVAL_CONTINUE(((17) << 2) | 0xF8000001u);
4910 rptr[1] = READ_NEXT_TOKEN_GRAB_ROW(((52) << 2) | 0xF8000001u);
4911 rptr[2] = ctx->reader_stream;
4912 rptr[3] = lbm_enc_u(ctx->flags);
4913 rptr[4] = POP_READER_FLAGS(((44) << 2) | 0xF8000001u);
4914
4915 // Evaluate result of reading (in r) and then continue with
4916 // reading reading the rest of the program.
4917 ctx->curr_env = env;
4918 ctx->curr_exp = ctx->r;
4919 } else {
4920 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4921 }
4922}
4923
4924static void cont_read_expect_closepar(eval_context_t *ctx) {
4925 lbm_value res = ctx->K.data[--ctx->K.sp];
4926
4927 lbm_char_channel_t *str = lbm_dec_channel(ctx->reader_stream);
4928 if (str == NULL((void*)0) || str->state == NULL((void*)0)) { // TODO: De Morgan these conditions.
4929 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4930 } else {
4931 if (lbm_type_of(ctx->r) == LBM_TYPE_SYMBOL0x00000000u &&
4932 ctx->r == ENC_SYM_CLOSEPAR(((0x71) << 4) | 0x00000000u)) {
4933 ctx->r = res;
4934 ctx->app_cont = true1;
4935 } else {
4936 lbm_channel_reader_close(str);
4937 lbm_set_error_reason((char*)lbm_error_str_parse_close);
4938 READ_ERROR_CTX(lbm_channel_row(str), lbm_channel_column(str))read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4939 }
4940 }
4941}
4942
4943static void cont_read_dot_terminate(eval_context_t *ctx) {
4944 lbm_value *sptr = get_stack_ptr(ctx, 2);
4945
4946 lbm_value last_cell = sptr[1];
4947
4948 lbm_char_channel_t *str = lbm_dec_channel(ctx->reader_stream);
4949 if (str == NULL((void*)0) || str->state == NULL((void*)0)) {
4950 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4951 } else if (lbm_type_of(ctx->r) == LBM_TYPE_SYMBOL0x00000000u &&
4952 (ctx->r == ENC_SYM_CLOSEPAR(((0x71) << 4) | 0x00000000u) ||
4953 ctx->r == ENC_SYM_DOT(((0x76) << 4) | 0x00000000u))) {
4954 lbm_channel_reader_close(str);
4955 lbm_set_error_reason((char*)lbm_error_str_parse_dot);
4956 READ_ERROR_CTX(lbm_channel_row(str), lbm_channel_column(str))read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4957 } else if (lbm_is_cons(last_cell)) {
4958 lbm_ref_cell(last_cell)->cdr = ctx->r;
4959 //lbm_set_cdr(last_cell, ctx->r);
4960 ctx->r = sptr[0]; // first cell
4961 lbm_value *rptr = stack_reserve(ctx, 1);
4962 sptr[0] = ctx->r;
4963 sptr[1] = READ_EXPECT_CLOSEPAR(((18) << 2) | 0xF8000001u);
4964 rptr[0] = READ_NEXT_TOKEN(((15) << 2) | 0xF8000001u);
4965 ctx->app_cont = true1;
4966 } else {
4967 lbm_channel_reader_close(str);
4968 lbm_set_error_reason((char*)lbm_error_str_parse_dot);
4969 READ_ERROR_CTX(lbm_channel_row(str), lbm_channel_column(str))read_error_ctx(lbm_channel_row(str), lbm_channel_column(str));
4970 }
4971}
4972
4973static void cont_read_done(eval_context_t *ctx) {
4974 --ctx->K.sp; // Ignore reader mode.
4975
4976 lbm_char_channel_t *str = lbm_dec_channel(ctx->reader_stream);
4977 if (str == NULL((void*)0) || str->state == NULL((void*)0)) {
4978 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
4979 }
4980
4981 lbm_channel_reader_close(str);
4982
4983 // Reading row/col from closed channel is OK!
4984 error_on_invalid_read_result(str, ctx);
4985
4986 ctx->row0 = -1;
4987 ctx->row1 = -1;
4988 ctx->reader_stream = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
4989 ctx->app_cont = true1;
4990}
4991
4992static void cont_wrap_result(eval_context_t *ctx) {
4993 lbm_value cell;
4994 lbm_value wrapper = ctx->K.data[--ctx->K.sp];
4995 WITH_GC(cell, lbm_heap_allocate_list_init(2,(cell) = (lbm_heap_allocate_list_init(2, wrapper, ctx->r))
; if (lbm_is_symbol_merror((cell))) { gc(); (cell) = (lbm_heap_allocate_list_init
(2, wrapper, ctx->r)); if (lbm_is_symbol_merror((cell))) {
error_ctx((((0x23) << 4) | 0x00000000u)); } }
4996 wrapper,(cell) = (lbm_heap_allocate_list_init(2, wrapper, ctx->r))
; if (lbm_is_symbol_merror((cell))) { gc(); (cell) = (lbm_heap_allocate_list_init
(2, wrapper, ctx->r)); if (lbm_is_symbol_merror((cell))) {
error_ctx((((0x23) << 4) | 0x00000000u)); } }
4997 ctx->r))(cell) = (lbm_heap_allocate_list_init(2, wrapper, ctx->r))
; if (lbm_is_symbol_merror((cell))) { gc(); (cell) = (lbm_heap_allocate_list_init
(2, wrapper, ctx->r)); if (lbm_is_symbol_merror((cell))) {
error_ctx((((0x23) << 4) | 0x00000000u)); } }
;
4998 ctx->r = cell;
4999 ctx->app_cont = true1;
5000}
5001
5002// cont_application_start
5003//
5004// sptr[0] = env
5005// sptr[1] = args
5006//
5007// ctx->r = function
5008static void cont_application_start(eval_context_t *ctx) {
5009 if (lbm_is_symbol(ctx->r)) {
5010 stack_reserve(ctx,1)[0] = lbm_enc_u(0);
5011 cont_application_args(ctx);
5012 } else if (lbm_is_cons(ctx->r)) {
5013 lbm_uint *sptr = get_stack_ptr(ctx, 2);
5014 lbm_value args = (lbm_value)sptr[1];
5015 switch (lbm_ref_cell(ctx->r)->car) { // Already checked that is_cons
5016 case ENC_SYM_CLOSURE(((0x10F) << 4) | 0x00000000u): {
5017 lbm_value cl = lbm_ref_cell(ctx->r)->cdr; // Already checked that is_cons
5018 lbm_value cl0, cl1, cl2;
5019 EXTRACT(cl, cl0)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl0 = _cell->car; cl = _cell->cdr; } else { cl0 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_PARAMS
5020 EXTRACT(cl, cl1)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl1 = _cell->car; cl = _cell->cdr; } else { cl1 = ((
(0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_BODY
5021 EXTRACT_NO_ADVANCE(cl, cl2)do { if (lbm_is_ptr(cl)) { lbm_cons_t *_cell = lbm_ref_cell(cl
); cl2 = _cell->car; } else { cl2 = (((0x0) << 4) | 0x00000000u
); } } while (0)
; // CLO_ENV
5022 lbm_value arg_env = (lbm_value)sptr[0];
5023
5024 if (lbm_is_cons(args)) { // There are args
5025 lbm_cons_t *args_cell = lbm_ref_cell(args);
5026 sptr[1] = cl1; // WARNING overwrites args on stack. args are unprotected.
5027 if (lbm_is_cons(cl0)) { // There are params
5028 lbm_value *reserved = stack_reserve(ctx, 4);
5029 reserved[0] = cl2;
5030 reserved[1] = cl0; // Guaranteed cons cell here
5031 reserved[2] = args_cell->cdr; // Possibly NIL
5032 reserved[3] = CLOSURE_ARGS(((13) << 2) | 0xF8000001u);
5033 ctx->curr_exp = args_cell->car;
5034 ctx->curr_env = arg_env;
5035 } else { // args but no params => REST_ARGS
5036 lbm_value *reserved0 = stack_reserve(ctx, 2);
5037 reserved0[0] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);;
5038 reserved0[1] = args_cell->cdr;
5039 ctx->curr_exp = args_cell->car; // protect car(args) from allocate binding
5040 ctx->curr_env = arg_env;
5041 lbm_value rest_binder = allocate_binding(ENC_SYM_REST_ARGS(((0x30015) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), cl2);
5042 lbm_value *reserved1 = stack_reserve(ctx, 2);
5043 reserved0[0] = rest_binder;
5044 reserved1[0] = get_car(rest_binder);
5045 reserved1[1] = CLOSURE_ARGS_REST(((42) << 2) | 0xF8000001u);
5046 }
5047 } else { // No args
5048 if (lbm_is_symbol_nil(cl0)) { // No parameters
5049 stack_drop(ctx, 2);
5050 ctx->curr_exp = cl1;
5051 ctx->curr_env = cl2;
5052 } else { // Not enough arguments
5053 lbm_set_error_reason((char*)lbm_error_str_num_args);
5054 ERROR_AT_CTX(ENC_SYM_EERROR, ctx->r)error_at_ctx((((0x22) << 4) | 0x00000000u), ctx->r);
5055 }
5056 }
5057 } break;
5058 case ENC_SYM_CONT(((0x10E) << 4) | 0x00000000u):{
5059 ctx->curr_exp = setup_cont(ctx, args);
5060 } break;
5061 case ENC_SYM_CONT_SP(((0x118) << 4) | 0x00000000u): {
5062 ctx->curr_exp = setup_cont_sp(ctx, args);
5063 return;
5064 } break;
5065 case ENC_SYM_MACRO(((0x10D) << 4) | 0x00000000u):{
5066 lbm_value env = (lbm_value)sptr[0];
5067 pop_stack_ptr(ctx, 2);
5068 setup_macro(ctx, args, env);
5069 } break;
5070 default:
5071 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
5072 }
5073 } else {
5074 lbm_set_error_reason(lbm_error_str_not_applicable);
5075 ERROR_AT_CTX(ENC_SYM_EERROR, ctx->r)error_at_ctx((((0x22) << 4) | 0x00000000u), ctx->r);
5076 }
5077}
5078
5079static void cont_eval_r(eval_context_t* ctx) {
5080 lbm_value env = ctx->K.data[--ctx->K.sp];
5081 ctx->curr_exp = ctx->r;
5082 ctx->curr_env = env;
5083}
5084
5085static void cont_progn_var(eval_context_t* ctx) {
5086
5087 lbm_value key = ctx->K.data[--ctx->K.sp];
5088 lbm_value env = ctx->K.data[--ctx->K.sp];
5089 fill_binding_location(key, ctx->r, env);
5090
5091 ctx->curr_env = env; // evaluating value may build upon local env.
5092 ctx->app_cont = true1;
5093}
5094
5095static void cont_setq(eval_context_t *ctx) {
5096 lbm_value sym = ctx->K.data[--ctx->K.sp];
5097 lbm_value env = ctx->K.data[--ctx->K.sp];
5098 lbm_value res;
5099 WITH_GC(res, perform_setvar(sym, ctx->r, env))(res) = (perform_setvar(sym, ctx->r, env)); if (lbm_is_symbol_merror
((res))) { gc(); (res) = (perform_setvar(sym, ctx->r, env)
); if (lbm_is_symbol_merror((res))) { error_ctx((((0x23) <<
4) | 0x00000000u)); } }
;
5100 ctx->r = res;
5101 ctx->app_cont = true1;
5102}
5103
5104lbm_flash_status request_flash_storage_cell(lbm_value val, lbm_value *res) {
5105
5106 lbm_value flash_cell;
5107 lbm_flash_status s = lbm_allocate_const_cell(&flash_cell);
5108 if (s != LBM_FLASH_WRITE_OK)
5109 return s;
5110 lbm_value new_val = val;
5111 new_val &= ~LBM_PTR_VAL_MASK0x03FFFFFCu; // clear the value part of the ptr
5112 new_val |= (flash_cell & LBM_PTR_VAL_MASK0x03FFFFFCu);
5113 new_val |= LBM_PTR_TO_CONSTANT_BIT0x04000000u;
5114 *res = new_val;
5115 return s;
5116}
5117
5118static void cont_move_to_flash(eval_context_t *ctx) {
5119
5120 lbm_value args = ctx->K.data[--ctx->K.sp];
5121
5122 if (lbm_is_symbol_nil(args)) {
5123 // Done looping over arguments. return true.
5124 ctx->r = ENC_SYM_TRUE(((0x2) << 4) | 0x00000000u);
5125 ctx->app_cont = true1;
5126 return;
5127 }
5128
5129 lbm_value first_arg, rest;
5130 get_car_and_cdr(args, &first_arg, &rest);
5131
5132 lbm_value val;
5133 if (lbm_is_symbol(first_arg) && lbm_global_env_lookup(&val, first_arg)) {
5134 // Prepare to copy the rest of the arguments when done with first.
5135 lbm_value *rptr = stack_reserve(ctx, 2);
5136 rptr[0] = rest;
5137 rptr[1] = MOVE_TO_FLASH(((28) << 2) | 0xF8000001u);
5138 if (lbm_is_ptr(val) &&
5139 (!(val & LBM_PTR_TO_CONSTANT_BIT0x04000000u))) {
5140 lbm_value * rptr1 = stack_reserve(ctx, 3);
5141 rptr1[0] = first_arg;
5142 rptr1[1] = SET_GLOBAL_ENV(((1) << 2) | 0xF8000001u);
5143 rptr1[2] = MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u);
5144 ctx->r = val;
5145 }
5146 ctx->app_cont = true1;
5147 return;
5148 }
5149 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
5150}
5151
5152static void cont_move_val_to_flash_dispatch(eval_context_t *ctx) {
5153
5154 lbm_value val = ctx->r;
5155
5156 if (lbm_is_cons(val)) { // non-constant cons-cell
5157 lbm_value *rptr = stack_reserve(ctx, 5);
5158 rptr[0] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // fst cell of list
5159 rptr[1] = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u); // last cell of list
5160 rptr[2] = get_cdr(val);
5161 rptr[3] = MOVE_LIST_TO_FLASH(((30) << 2) | 0xF8000001u);
5162 rptr[4] = MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u);
5163 ctx->r = lbm_ref_cell(val)->car; // already checked is_cons
5164 ctx->app_cont = true1;
5165 return;
5166 }
5167
5168 if (lbm_is_ptr(val) && (val & LBM_PTR_TO_CONSTANT_BIT0x04000000u)) { // constant pointer cons or not.
5169 //ctx->r unchanged
5170 ctx->app_cont = true1;
5171 return;
5172 }
5173
5174 if (lbm_is_ptr(val)) { // something that is not a cons but still a ptr type.
5175 lbm_cons_t *ref = lbm_ref_cell(val);
5176 if (lbm_type_of(ref->cdr) == LBM_TYPE_SYMBOL0x00000000u) {
5177 switch (ref->cdr) {
5178 case ENC_SYM_RAW_I_TYPE(((0x31) << 4) | 0x00000000u): /* fall through */
5179 case ENC_SYM_RAW_U_TYPE(((0x32) << 4) | 0x00000000u):
5180 case ENC_SYM_RAW_F_TYPE(((0x33) << 4) | 0x00000000u): {
5181 lbm_value flash_cell = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5182 handle_flash_status(request_flash_storage_cell(val, &flash_cell));
5183 handle_flash_status(write_const_car(flash_cell, ref->car));
5184 handle_flash_status(write_const_cdr(flash_cell, ref->cdr));
5185 ctx->r = flash_cell;
5186 } break;
5187 case ENC_SYM_IND_I_TYPE(((0x34) << 4) | 0x00000000u): /* fall through */
5188 case ENC_SYM_IND_U_TYPE(((0x35) << 4) | 0x00000000u):
5189 case ENC_SYM_IND_F_TYPE(((0x36) << 4) | 0x00000000u): {
5190#ifndef LBM64
5191 /* 64 bit values are in lbm mem on 32bit platforms. */
5192 lbm_uint *lbm_mem_ptr = (lbm_uint*)ref->car;
5193 lbm_uint flash_ptr;
5194
5195 handle_flash_status(lbm_write_const_raw(lbm_mem_ptr, 2, &flash_ptr));
5196 lbm_value flash_cell = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5197 handle_flash_status(request_flash_storage_cell(val, &flash_cell));
5198 handle_flash_status(write_const_car(flash_cell, flash_ptr));
5199 handle_flash_status(write_const_cdr(flash_cell, ref->cdr));
5200 ctx->r = flash_cell;
5201#else
5202 // There are no indirect types in LBM64
5203 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
5204#endif
5205 } break;
5206 case ENC_SYM_LISPARRAY_TYPE(((0x39) << 4) | 0x00000000u): {
5207 lbm_array_header_t *arr = (lbm_array_header_t*)ref->car;
5208 lbm_uint size = arr->size / sizeof(lbm_uint);
5209 lbm_uint flash_addr = 0;
5210 lbm_value *arrdata = (lbm_value *)arr->data;
5211 lbm_value flash_cell = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5212 handle_flash_status(request_flash_storage_cell(val, &flash_cell));
5213 handle_flash_status(lbm_allocate_const_raw(size, &flash_addr));
5214 lift_array_flash(flash_cell,
5215 false0,
5216 (char *)flash_addr,
5217 arr->size);
5218 // Move array contents to flash recursively
5219 lbm_value *rptr = stack_reserve(ctx, 5);
5220 rptr[0] = flash_cell;
5221 rptr[1] = lbm_enc_u(0);
5222 rptr[2] = val;
5223 rptr[3] = MOVE_ARRAY_ELTS_TO_FLASH(((43) << 2) | 0xF8000001u);
5224 rptr[4] = MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u);
5225 ctx->r = arrdata[0];
5226 ctx->app_cont = true1;
5227 return;
5228 }
5229 case ENC_SYM_ARRAY_TYPE(((0x30) << 4) | 0x00000000u): {
5230 lbm_array_header_t *arr = (lbm_array_header_t*)ref->car;
5231 // arbitrary address: flash_arr.
5232 lbm_uint flash_arr = 0;
5233 handle_flash_status(lbm_write_const_array_padded((uint8_t*)arr->data, arr->size, &flash_arr));
5234 lbm_value flash_cell = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5235 handle_flash_status(request_flash_storage_cell(val, &flash_cell));
5236 lift_array_flash(flash_cell,
5237 true1,
5238 (char *)flash_arr,
5239 arr->size);
5240 ctx->r = flash_cell;
5241 } break;
5242 case ENC_SYM_CHANNEL_TYPE(((0x37) << 4) | 0x00000000u): /* fall through */
5243 case ENC_SYM_CUSTOM_TYPE(((0x38) << 4) | 0x00000000u):
5244 lbm_set_error_reason((char *)lbm_error_str_flash_not_possible);
5245 ERROR_CTX(ENC_SYM_EERROR)error_ctx((((0x22) << 4) | 0x00000000u));
5246 }
5247 } else {
5248 ERROR_CTX(ENC_SYM_FATAL_ERROR)error_ctx((((0x26) << 4) | 0x00000000u));
5249 }
5250 ctx->app_cont = true1;
5251 return;
5252 }
5253
5254 // if no condition matches, nothing happens (id).
5255 ctx->r = val;
5256 ctx->app_cont = true1;
5257}
5258
5259static void cont_move_list_to_flash(eval_context_t *ctx) {
5260
5261 // ctx->r holds the value that should go in car
5262
5263 lbm_value *sptr = get_stack_ptr(ctx, 3);
5264
5265 lbm_value fst = sptr[0];
5266 lbm_value lst = sptr[1];
5267 lbm_value val = sptr[2];
5268
5269
5270 lbm_value new_lst = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5271 // Allocate element ptr storage after storing the element to flash.
5272 handle_flash_status(request_flash_storage_cell(lbm_enc_cons_ptr(LBM_PTR_NULL(0x03FFFFFCu >> 2)), &new_lst));
5273
5274 if (lbm_is_symbol_nil(fst)) {
5275 lst = new_lst;
5276 fst = new_lst;
5277 handle_flash_status(write_const_car(lst, ctx->r));
5278 } else {
5279 handle_flash_status(write_const_cdr(lst, new_lst)); // low before high
5280 handle_flash_status(write_const_car(new_lst, ctx->r));
5281 lst = new_lst;
5282 }
5283
5284 if (lbm_is_cons(val)) {
5285 sptr[0] = fst;
5286 sptr[1] = lst;//rest_cell;
5287 sptr[2] = lbm_ref_cell(val)->cdr;
5288 lbm_value *rptr = stack_reserve(ctx, 2);
5289 rptr[0] = MOVE_LIST_TO_FLASH(((30) << 2) | 0xF8000001u);
5290 rptr[1] = MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u);
5291 ctx->r = lbm_ref_cell(val)->car; // already checked is_cons
5292 } else {
5293 sptr[0] = fst;
5294 sptr[1] = lst;
5295 sptr[2] = CLOSE_LIST_IN_FLASH(((31) << 2) | 0xF8000001u);
5296 stack_reserve(ctx, 1)[0] = MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u);
5297 ctx->r = val;
5298 }
5299 ctx->app_cont = true1;
5300}
5301
5302static void cont_close_list_in_flash(eval_context_t *ctx) {
5303 lbm_value lst = ctx->K.data[--ctx->K.sp];
5304 lbm_value fst = ctx->K.data[--ctx->K.sp];
5305 lbm_value val = ctx->r;
5306 handle_flash_status(write_const_cdr(lst, val));
5307 ctx->r = fst;
5308 ctx->app_cont = true1;
5309}
5310
5311static void cont_move_array_elts_to_flash(eval_context_t *ctx) {
5312 lbm_value *sptr = get_stack_ptr(ctx, 3);
5313 // sptr[2] = source array in RAM
5314 // sptr[1] = current index
5315 // sptr[0] = target array in flash
5316 lbm_array_header_t *src_arr = assume_array(sptr[2]);
5317 lbm_uint size = src_arr->size / sizeof(lbm_uint);
5318 lbm_value *srcdata = (lbm_value *)src_arr->data;
5319
5320 lbm_array_header_t *tgt_arr = assume_array(sptr[0]);
5321 lbm_uint *tgtdata = (lbm_value *)tgt_arr->data;
5322 lbm_uint ix = lbm_dec_as_u32(sptr[1]);
5323 handle_flash_status(lbm_const_write(&tgtdata[ix], ctx->r));
5324 if (ix >= size-1) {
5325 ctx->r = sptr[0];
5326 stack_drop(ctx, 3);
5327 ctx->app_cont = true1;
5328 return;
5329 }
5330 sptr[1] = lbm_enc_u(ix + 1);
5331 lbm_value *rptr = stack_reserve(ctx, 2);
5332 rptr[0] = MOVE_ARRAY_ELTS_TO_FLASH(((43) << 2) | 0xF8000001u);
5333 rptr[1] = MOVE_VAL_TO_FLASH_DISPATCH(((29) << 2) | 0xF8000001u);
5334 ctx->r = srcdata[ix+1];
5335 ctx->app_cont = true1;
5336 return;
5337}
5338
5339static void cont_qq_expand_start(eval_context_t *ctx) {
5340 lbm_value *rptr = stack_reserve(ctx, 2);
5341 rptr[0] = ctx->r;
5342 rptr[1] = QQ_EXPAND(((33) << 2) | 0xF8000001u);
5343 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5344 ctx->app_cont = true1;
5345}
5346
5347static lbm_value quote_it(lbm_value qquoted) {
5348 if (lbm_is_symbol(qquoted) &&
5349 lbm_is_special(qquoted)) return qquoted;
5350
5351 lbm_value val = cons_with_gc(qquoted, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5352 return cons_with_gc(ENC_SYM_QUOTE(((0x100) << 4) | 0x00000000u), val, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5353}
5354
5355static bool_Bool is_append(lbm_value a) {
5356 return (lbm_is_cons(a) &&
5357 lbm_is_symbol(lbm_ref_cell(a)->car) &&
5358 (lbm_ref_cell(a)->car == ENC_SYM_APPEND(((0x20015) << 4) | 0x00000000u)));
5359}
5360
5361static lbm_value append(lbm_value front, lbm_value back) {
5362 if (lbm_is_symbol_nil(front)) return back;
5363 if (lbm_is_symbol_nil(back)) return front;
5364
5365 if (lbm_is_quoted_list(front) &&
5366 lbm_is_quoted_list(back)) {
5367 lbm_value f = get_cadr(front);
5368 lbm_value b = get_cadr(back);
5369 return quote_it(lbm_list_append(f, b));
5370 }
5371
5372 if (is_append(back) &&
5373 lbm_is_quoted_list(get_cadr(back)) &&
5374 lbm_is_quoted_list(front)) {
5375 lbm_value ql = get_cadr(back);
5376 lbm_value f = get_cadr(front);
5377 lbm_value b = get_cadr(ql);
5378
5379 lbm_value v = lbm_list_append(f, b);
5380 lbm_set_car(get_cdr(ql), v);
5381 return back;
5382 }
5383
5384 if (is_append(back)) {
5385 back = get_cdr(back);
5386 lbm_value new = cons_with_gc(front, back, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5387 return cons_with_gc(ENC_SYM_APPEND(((0x20015) << 4) | 0x00000000u), new, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5388 }
5389
5390 lbm_value t0, t1;
5391
5392 t0 = cons_with_gc(back, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), front);
5393 t1 = cons_with_gc(front, t0, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5394 return cons_with_gc(ENC_SYM_APPEND(((0x20015) << 4) | 0x00000000u), t1, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5395}
5396
5397// ////////////////////////////////////////////////////////////
5398// Quasiquotation expansion that takes place at read time
5399// and is based on the paper by Bawden "Quasiquotation in lisp".
5400// Bawden, Alan. "Quasiquotation in Lisp." PEPM. 1999.
5401//
5402// cont_qq_expand and cont_qq_expand_list corresponds (mostly) to
5403// qq-expand and qq-expand-list in the paper.
5404// One difference is that the case where a backquote is nested
5405// inside of a backqoute is handled via the recursion through the
5406// reader.
5407
5408/* Bawden's qq-expand implementation
5409(define (qq-expand x)
5410 (cond ((tag-comma? x)
5411 (tag-data x))
5412 ((tag-comma-atsign? x)
5413 (error "Illegal"))
5414 ((tag-backquote? x)
5415 (qq-expand
5416 (qq-expand (tag-data x))))
5417 ((pair? x)
5418 `(append
5419 ,(qq-expand-list (car x))
5420 ,(qq-expand (cdr x))))
5421 (else `',x)))
5422 */
5423static void cont_qq_expand(eval_context_t *ctx) {
5424 lbm_value qquoted = ctx->K.data[--ctx->K.sp];
5425
5426 switch(lbm_type_of(qquoted)) {
5427 case LBM_TYPE_CONS0x10000000u: {
5428 lbm_value car_val;
5429 lbm_value cdr_val;
5430 get_car_and_cdr(qquoted, &car_val, &cdr_val);
5431
5432 if (lbm_type_of(car_val) == LBM_TYPE_SYMBOL0x00000000u &&
5433 car_val == ENC_SYM_COMMA(((0x73) << 4) | 0x00000000u)) {
5434 ctx->r = append(ctx->r, get_car(cdr_val));
5435 ctx->app_cont = true1;
5436 } else if (lbm_type_of(car_val) == LBM_TYPE_SYMBOL0x00000000u &&
5437 car_val == ENC_SYM_COMMAAT(((0x74) << 4) | 0x00000000u)) {
5438 lbm_set_error_reason((char*)lbm_error_str_qq_expand);
5439 ERROR_AT_CTX(ENC_SYM_RERROR, qquoted)error_at_ctx((((0x20) << 4) | 0x00000000u), qquoted);
5440 } else {
5441 lbm_value *rptr = stack_reserve(ctx, 6);
5442 rptr[0] = ctx->r;
5443 rptr[1] = QQ_APPEND(((34) << 2) | 0xF8000001u);
5444 rptr[2] = cdr_val;
5445 rptr[3] = QQ_EXPAND(((33) << 2) | 0xF8000001u);
5446 rptr[4] = car_val;
5447 rptr[5] = QQ_EXPAND_LIST(((35) << 2) | 0xF8000001u);
5448 ctx->app_cont = true1;
5449 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5450 }
5451
5452 } break;
5453 default: {
5454 lbm_value res = quote_it(qquoted);
5455 ctx->r = append(ctx->r, res);
5456 ctx->app_cont = true1;
5457 }
5458 }
5459}
5460
5461static void cont_qq_append(eval_context_t *ctx) {
5462 lbm_value head = ctx->K.data[--ctx->K.sp];
5463 ctx->r = append(head, ctx->r);
5464 ctx->app_cont = true1;
5465}
5466
5467/* Bawden's qq-expand-list implementation
5468(define (qq-expand-list x)
5469 (cond ((tag-comma? x)
5470 `(list ,(tag-data x)))
5471 ((tag-comma-atsign? x)
5472 (tag-data x))
5473 ((tag-backquote? x)
5474 (qq-expand-list
5475 (qq-expand (tag-data x))))
5476 ((pair? x)
5477 `(list
5478 (append
5479 ,(qq-expand-list (car x))
5480 ,(qq-expand (cdr x)))))
5481 (else `'(,x))))
5482*/
5483
5484static void cont_qq_expand_list(eval_context_t* ctx) {
5485 lbm_value l = ctx->K.data[--ctx->K.sp];
5486
5487 ctx->app_cont = true1;
5488 switch(lbm_type_of(l)) {
5489 case LBM_TYPE_CONS0x10000000u: {
5490 lbm_value car_val;
5491 lbm_value cdr_val;
5492 get_car_and_cdr(l, &car_val, &cdr_val);
5493
5494 if (lbm_type_of(car_val) == LBM_TYPE_SYMBOL0x00000000u &&
5495 car_val == ENC_SYM_COMMA(((0x73) << 4) | 0x00000000u)) {
5496 lbm_value tl = cons_with_gc(get_car(cdr_val), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5497 lbm_value tmp = cons_with_gc(ENC_SYM_LIST(((0x20014) << 4) | 0x00000000u), tl, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5498 ctx->r = append(ctx->r, tmp);
5499 return;
5500 } else if (lbm_type_of(car_val) == LBM_TYPE_SYMBOL0x00000000u &&
5501 car_val == ENC_SYM_COMMAAT(((0x74) << 4) | 0x00000000u)) {
5502 lbm_value cadr_val = get_car(cdr_val);
5503 ctx->r = cadr_val;
5504 return;
5505 } else {
5506 lbm_value *rptr = stack_reserve(ctx, 7);
5507 rptr[0] = QQ_LIST(((36) << 2) | 0xF8000001u);
5508 rptr[1] = ctx->r;
5509 rptr[2] = QQ_APPEND(((34) << 2) | 0xF8000001u);
5510 rptr[3] = cdr_val;
5511 rptr[4] = QQ_EXPAND(((33) << 2) | 0xF8000001u);
5512 rptr[5] = car_val;
5513 rptr[6] = QQ_EXPAND_LIST(((35) << 2) | 0xF8000001u);
5514 ctx->r = ENC_SYM_NIL(((0x0) << 4) | 0x00000000u);
5515 }
5516
5517 } break;
5518 default: {
5519 lbm_value a_list = cons_with_gc(l, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5520 lbm_value tl = cons_with_gc(a_list, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5521 lbm_value tmp = cons_with_gc(ENC_SYM_QUOTE(((0x100) << 4) | 0x00000000u), tl, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5522 ctx->r = append(ctx->r, tmp);
5523 }
5524 }
5525}
5526
5527static void cont_qq_list(eval_context_t *ctx) {
5528 lbm_value val = ctx->r;
5529 lbm_value apnd_app = cons_with_gc(val, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u), ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5530 lbm_value tmp = cons_with_gc(ENC_SYM_LIST(((0x20014) << 4) | 0x00000000u), apnd_app, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5531 ctx->r = tmp;
5532 ctx->app_cont = true1;
5533}
5534
5535static void cont_kill(eval_context_t *ctx) {
5536 (void) ctx;
5537 ok_ctx();
5538}
5539
5540// cont_pop_reader_flags
5541// s[sp-1] flags
5542// Preserves r
5543static void cont_pop_reader_flags(eval_context_t *ctx) {
5544 lbm_value flags = ctx->K.data[--ctx->K.sp];
5545 lbm_value stream = ctx->K.data[--ctx->K.sp];
5546 ctx->reader_stream = stream;
5547 ctx->flags = ctx->flags & ~EVAL_CPS_CONTEXT_READER_FLAGS_MASK((uint32_t)0x02 | (uint32_t)0x04 | (uint32_t)0x08);
5548 ctx->flags |= (lbm_dec_as_u32(flags) & EVAL_CPS_CONTEXT_READER_FLAGS_MASK((uint32_t)0x02 | (uint32_t)0x04 | (uint32_t)0x08));
5549 ctx->app_cont = true1;
5550}
5551
5552// cont_exception_handler
5553//
5554// s[sp-2] retval - a list of 2 elements created by eval_trap
5555// s[sp-1] flags - context flags stored by eval_trap
5556//
5557static void cont_exception_handler(eval_context_t *ctx) {
5558 lbm_value *sptr = pop_stack_ptr(ctx, 2);
5559 lbm_value retval = sptr[0];
5560 lbm_value flags = sptr[1];
5561 lbm_set_car(get_cdr(retval), ctx->r);
5562 ctx->flags = (uint32_t)flags;
5563 ctx->r = retval;
5564 ctx->app_cont = true1;
5565}
5566
5567// cont_recv_to:
5568//
5569// s[sp-1] = patterns
5570//
5571// ctx->r = timeout value
5572static void cont_recv_to(eval_context_t *ctx) {
5573 if (lbm_is_number(ctx->r)) {
5574 lbm_value *sptr = get_stack_ptr(ctx, 1); // patterns at sptr[0]
5575 float timeout_time = lbm_dec_as_float(ctx->r);
5576 if (timeout_time < 0.0) timeout_time = 0.0; // clamp.
5577 if (ctx->num_mail > 0) {
5578 lbm_value e;
5579 lbm_value new_env = ctx->curr_env;
5580 int n = find_match(sptr[0], ctx->mailbox, ctx->num_mail, &e, &new_env);
5581 if (n >= 0) { // match
5582 mailbox_remove_mail(ctx, (lbm_uint)n);
5583 ctx->curr_env = new_env;
5584 ctx->curr_exp = e;
5585 stack_drop(ctx, 1);
5586 return;
5587 }
5588 }
5589 // If no mail or no match, go to sleep
5590 lbm_uint *rptr = stack_reserve(ctx,2);
5591 rptr[0] = ctx->r;
5592 rptr[1] = RECV_TO_RETRY(((48) << 2) | 0xF8000001u);
5593 block_current_ctx(LBM_THREAD_STATE_RECV_TO(uint32_t)16u,S_TO_US(timeout_time)(lbm_uint)((timeout_time) * 1000000),true1);
5594 } else {
5595 ERROR_CTX(ENC_SYM_TERROR)error_ctx((((0x21) << 4) | 0x00000000u));
5596 }
5597}
5598
5599// cont_recv_to_retry
5600//
5601// s[sp-2] = patterns
5602// s[sp-1] = timeout value
5603//
5604// ctx->r = nonsense | timeout symbol
5605static void cont_recv_to_retry(eval_context_t *ctx) {
5606 lbm_value *sptr = get_stack_ptr(ctx, 2); //sptr[0] = patterns, sptr[1] = timeout
5607
5608 if (ctx->num_mail > 0) {
5609 lbm_value e;
5610 lbm_value new_env = ctx->curr_env;
5611 int n = find_match(sptr[0], ctx->mailbox, ctx->num_mail, &e, &new_env);
5612 if (n >= 0) { // match
5613 mailbox_remove_mail(ctx, (lbm_uint)n);
5614 ctx->curr_env = new_env;
5615 ctx->curr_exp = e;
5616 stack_drop(ctx, 2);
5617 return;
5618 }
5619 }
5620
5621 // No message matched but the timeout was reached.
5622 // This is like having a recv-to with no case that matches
5623 // the timeout symbol.
5624 if (ctx->r == ENC_SYM_TIMEOUT(((0xA) << 4) | 0x00000000u)) {
5625 stack_drop(ctx, 2);
5626 ctx->app_cont = true1;
5627 return;
5628 }
5629
5630 stack_reserve(ctx,1)[0] = RECV_TO_RETRY(((48) << 2) | 0xF8000001u);
5631 reblock_current_ctx(LBM_THREAD_STATE_RECV_TO(uint32_t)16u,true1);
5632}
5633
5634
5635/*********************************************************/
5636/* Continuations table */
5637typedef void (*cont_fun)(eval_context_t *);
5638
5639static const cont_fun continuations[NUM_CONTINUATIONS53] =
5640 { advance_ctx, // CONT_DONE
5641 cont_set_global_env,
5642 cont_bind_to_key_rest,
5643 cont_if,
5644 cont_progn_rest,
5645 cont_application_args,
5646 cont_and,
5647 cont_or,
5648 cont_wait,
5649 cont_match,
5650 cont_application_start,
5651 cont_eval_r,
5652 cont_resume,
5653 cont_closure_application_args,
5654 cont_exit_atomic,
5655 cont_read_next_token,
5656 cont_read_append_continue,
5657 cont_read_eval_continue,
5658 cont_read_expect_closepar,
5659 cont_read_dot_terminate,
5660 cont_read_done,
5661 cont_read_start_bytearray,
5662 cont_read_append_bytearray,
5663 cont_map,
5664 cont_match_guard,
5665 cont_terminate,
5666 cont_progn_var,
5667 cont_setq,
5668 cont_move_to_flash,
5669 cont_move_val_to_flash_dispatch,
5670 cont_move_list_to_flash,
5671 cont_close_list_in_flash,
5672 cont_qq_expand_start,
5673 cont_qq_expand,
5674 cont_qq_append,
5675 cont_qq_expand_list,
5676 cont_qq_list,
5677 cont_kill,
5678 cont_loop,
5679 cont_loop_condition,
5680 cont_merge_rest,
5681 cont_merge_layer,
5682 cont_closure_args_rest,
5683 cont_move_array_elts_to_flash,
5684 cont_pop_reader_flags,
5685 cont_exception_handler,
5686 cont_recv_to,
5687 cont_wrap_result,
5688 cont_recv_to_retry,
5689 cont_read_start_array,
5690 cont_read_append_array,
5691 cont_loop_env_prep,
5692 cont_read_next_token_grab_row,
5693 };
5694
5695/*********************************************************/
5696/* Evaluators lookup table (special forms) */
5697typedef void (*evaluator_fun)(eval_context_t *);
5698
5699static const evaluator_fun evaluators[] =
5700 {
5701 eval_quote,
5702 eval_define,
5703 eval_progn,
5704 eval_lambda,
5705 eval_if,
5706 eval_let,
5707 eval_and,
5708 eval_or,
5709 eval_match,
5710 eval_receive,
5711 eval_receive_timeout,
5712 eval_callcc,
5713 eval_atomic,
5714 eval_selfevaluating, // macro
5715 eval_selfevaluating, // cont
5716 eval_selfevaluating, // closure
5717 eval_cond,
5718 eval_app_cont,
5719 eval_var,
5720 eval_setq,
5721 eval_move_to_flash,
5722 eval_loop,
5723 eval_trap,
5724 eval_call_cc_unsafe,
5725 eval_selfevaluating, // cont_sp
5726 };
5727
5728
5729/*********************************************************/
5730/* Evaluator step function */
5731
5732static void evaluation_step(void){
5733 eval_context_t *ctx = ctx_running;
5734
5735 if (ctx->app_cont) {
5736 lbm_value k = ctx->K.data[--ctx->K.sp];
5737 ctx->app_cont = false0;
5738
5739 // If app_cont is true, then top of stack must be a valid continuation!
5740 // If top of stack is not a valid continuation CRASH!
5741
5742 lbm_uint decoded_k = DEC_CONTINUATION(k)(((k) & ~0xF8000001u) >> 2);
5743 continuations[decoded_k](ctx);
5744 return;
5745 }
5746
5747 if (lbm_is_symbol(ctx->curr_exp)) {
5748 eval_symbol(ctx);
5749 return;
5750 }
5751 if (lbm_is_cons(ctx->curr_exp)) {
5752 lbm_cons_t *cell = lbm_ref_cell(ctx->curr_exp);
5753 lbm_value h = cell->car;
5754 if (lbm_is_symbol(h) && ((h & ENC_SPECIAL_FORMS_MASK0xFFFFF000) == ENC_SPECIAL_FORMS_BIT0x00001000)) {
5755 lbm_uint eval_index = lbm_dec_sym(h) & SPECIAL_FORMS_INDEX_MASK0x000000FF;
5756 evaluators[eval_index](ctx);
5757 return;
5758 }
5759 /*
5760 * At this point head can be anything. It should evaluate
5761 * into a form that can be applied (closure, symbol, ...) though.
5762 */
5763 lbm_value *reserved = stack_reserve(ctx, 3);
5764 reserved[0] = ctx->curr_env; // INFER: stack_reserve aborts context if error.
5765 reserved[1] = cell->cdr;
5766 reserved[2] = APPLICATION_START(((10) << 2) | 0xF8000001u);
5767 ctx->curr_exp = h; // evaluate the function
5768 return;
5769 }
5770
5771 eval_selfevaluating(ctx);
5772 return;
5773}
5774
5775// Placed down here since it depends on a lot of things.
5776// (apply fun arg-list)
5777static void apply_apply(lbm_value *args, lbm_uint nargs, eval_context_t *ctx) {
5778 if (nargs == 2 && lbm_is_list(args[1])) {
5779 lbm_value fun = args[0];
5780 lbm_value arg_list = args[1];
5781
5782 stack_drop(ctx, (unsigned int)nargs+1);
5783
5784 if (lbm_is_symbol(fun)) {
5785 if ((fun & ENC_SPECIAL_FORMS_MASK0xFFFFF000) == ENC_SPECIAL_FORMS_BIT0x00001000) {
5786 // Since the special form evaluators are responsible for conditionally
5787 // evaluating their arguments there is no easy way to prevent them
5788 // evaluating their arguments. Therefore we compromise and allow them to do
5789 // so, even if this isn't always how you would expect apply to work.
5790 // For instance, `(apply and '(a))` would try evaluating the symbol `a`,
5791 // instead of just returning the symbol `a` outright.
5792
5793 // Evaluator functions expect the current expression to equal the special
5794 // form, i.e. including the function symbol.
5795 lbm_value fun_and_args = cons_with_gc(fun, arg_list, ENC_SYM_NIL(((0x0) << 4) | 0x00000000u));
5796 ctx->curr_exp = fun_and_args;
5797 lbm_uint eval_index = lbm_dec_sym(fun) & SPECIAL_FORMS_INDEX_MASK0x000000FF;
5798 evaluators[eval_index](ctx);
5799 return;
5800 } else { // lbm_is_symbol(fun)
5801 stack_reserve(ctx, 1)[0] = fun;
5802 unsigned int arg_count = 0;
5803 for (lbm_value current = arg_list; lbm_is_cons(current);) {
5804 lbm_cons_t *cell = lbm_ref_cell(current);
5805 stack_reserve(ctx, 1)[0] = cell->car;
5806 arg_count++;
5807 current = cell->cdr;
5808 }
5809 lbm_value *fun_and_args = get_stack_ptr(ctx, arg_count + 1);
5810 application(ctx, fun_and_args, arg_count);
5811 return;
5812 }
5813 } else if (lbm_is_cons(fun)) {
5814 lbm_cons_t *fun_cell = lbm_ref_cell(fun);
5815 switch (fun_cell->car) {
5816 case ENC_SYM_CLOSURE(((0x10F) << 4) | 0x00000000u): {
5817 lbm_value closure = fun_cell->cdr;
5818 lbm_value cl0, cl1, cl2;
5819 EXTRACT(closure, cl0)do { if (lbm_is_ptr(closure)) { lbm_cons_t *_cell = lbm_ref_cell
(closure); cl0 = _cell->car; closure = _cell->cdr; } else
{ cl0 = (((0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_PARAMS
5820 EXTRACT(closure, cl1)do { if (lbm_is_ptr(closure)) { lbm_cons_t *_cell = lbm_ref_cell
(closure); cl1 = _cell->car; closure = _cell->cdr; } else
{ cl1 = (((0x0) << 4) | 0x00000000u); } } while (0)
; // CLO_BODY
5821 EXTRACT_NO_ADVANCE(closure, cl2)do { if (lbm_is_ptr(closure)) { lbm_cons_t *_cell = lbm_ref_cell
(closure); cl2 = _cell->car; } else { cl2 = (((0x0) <<
4) | 0x00000000u); } } while (0)
; // CLO_ENV
5822
5823 // Only placed here to protect from GC. Will be overriden later.
5824 // ctx->r = arg_list; // Should already be placed there.
5825 ctx->curr_exp = fun;
5826
5827 lbm_value env = cl2;
5828
5829 lbm_value current_params = cl0;
5830 lbm_value current_args = arg_list;
5831 while (lbm_is_cons(current_params) && lbm_is_cons(current_args)) {
5832 lbm_cons_t *p_cell = lbm_ref_cell(current_params);
5833 lbm_cons_t *a_cell = lbm_ref_cell(current_args);
5834 env = allocate_binding(p_cell->car, a_cell->car, env);
5835 current_params = p_cell->cdr;
5836 current_args = a_cell->cdr;
5837 }
5838 if (lbm_is_cons(current_args)) {
5839 env = allocate_binding(ENC_SYM_REST_ARGS(((0x30015) << 4) | 0x00000000u), current_args, env);
5840 } else if (lbm_is_cons(current_params)) {
5841 lbm_set_error_reason(lbm_error_str_num_args);
5842 ERROR_AT_CTX(ENC_SYM_EERROR, fun)error_at_ctx((((0x22) << 4) | 0x00000000u), fun);
5843 }
5844
5845 ctx->curr_env = env;
5846 ctx->curr_exp = cl1;
5847 return;
5848 }
5849 case ENC_SYM_CONT(((0x10E) << 4) | 0x00000000u):
5850 ctx->r = fun;
5851 ctx->r = setup_cont(ctx, arg_list);
5852 ctx->app_cont = true1;
5853 return;
5854 case ENC_SYM_CONT_SP(((0x118) << 4) | 0x00000000u):
5855 ctx->r = fun;
5856 ctx->r = setup_cont_sp(ctx, arg_list);
5857 ctx->app_cont = true1;
5858 return;
5859 case ENC_SYM_MACRO(((0x10D) << 4) | 0x00000000u):
5860 ctx->r = fun;
5861 setup_macro(ctx, arg_list, ctx->curr_env);
5862 return;
5863 default:
5864 lbm_set_error_reason(lbm_error_str_not_applicable);
5865 ERROR_AT_CTX(ENC_SYM_EERROR, fun)error_at_ctx((((0x22) << 4) | 0x00000000u), fun);
5866 }
5867 } else {
5868 lbm_set_error_reason(lbm_error_str_not_applicable);
5869 ERROR_AT_CTX(ENC_SYM_EERROR, fun)error_at_ctx((((0x22) << 4) | 0x00000000u), fun);
5870 }
5871 } else {
5872 lbm_set_error_reason(lbm_error_str_incorrect_arg);
5873 ERROR_AT_CTX(ENC_SYM_EERROR, ENC_SYM_APPLY)error_at_ctx((((0x22) << 4) | 0x00000000u), (((0x30017)
<< 4) | 0x00000000u))
;
5874 }
5875}
5876
5877// Reset has a built in pause.
5878// so after reset, continue.
5879void lbm_reset_eval(void) {
5880 eval_cps_next_state_arg = 0;
5881 eval_cps_next_state = EVAL_CPS_STATE_RESET16;
5882 if (eval_cps_next_state != eval_cps_run_state) eval_cps_state_changed = true1;
5883}
5884
5885void lbm_pause_eval(void ) {
5886 eval_cps_next_state_arg = 0;
5887 eval_cps_next_state = EVAL_CPS_STATE_PAUSED1;
5888 if (eval_cps_next_state != eval_cps_run_state) eval_cps_state_changed = true1;
5889}
5890
5891void lbm_pause_eval_with_gc(uint32_t num_free) {
5892 eval_cps_next_state_arg = num_free;
5893 eval_cps_next_state = EVAL_CPS_STATE_PAUSED1;
5894 if (eval_cps_next_state != eval_cps_run_state) eval_cps_state_changed = true1;
5895}
5896
5897void lbm_continue_eval(void) {
5898 eval_cps_next_state = EVAL_CPS_STATE_RUNNING2;
5899 if (eval_cps_next_state != eval_cps_run_state) eval_cps_state_changed = true1;
5900}
5901
5902void lbm_kill_eval(void) {
5903 eval_cps_next_state = EVAL_CPS_STATE_KILL4;
5904 if (eval_cps_next_state != eval_cps_run_state) eval_cps_state_changed = true1;
5905}
5906
5907uint32_t lbm_get_eval_state(void) {
5908 return eval_cps_run_state;
5909}
5910
5911// Only unblocks threads that are unblockable.
5912// A sleeping thread is not unblockable.
5913static void handle_event_unblock_ctx(lbm_cid cid, lbm_value v) {
5914 eval_context_t *found = NULL((void*)0);
5915 lbm_mutex_lock(&qmutex);
5916
5917 found = lookup_ctx_nm(&blocked, cid);
5918 if (found && LBM_IS_STATE_UNBLOCKABLE(found->state)(found->state & ((uint32_t)1u | (uint32_t)2u))){
5919 unlink_ctx_nm(&blocked,found);
5920 if (lbm_is_error(v)) {
5921 get_stack_ptr(found, 1)[0] = TERMINATE(((25) << 2) | 0xF8000001u); // replace TOS
5922 found->app_cont = true1;
5923 }
5924 found->r = v;
5925 found->state = LBM_THREAD_STATE_READY(uint32_t)0u;
5926 enqueue_ctx_nm(&queue,found);
5927 }
5928 lbm_mutex_unlock(&qmutex);
5929}
5930
5931static void handle_event_define(lbm_value key, lbm_value val) {
5932 lbm_uint dec_key = lbm_dec_sym(key);
5933 lbm_uint ix_key = dec_key & GLOBAL_ENV_MASK0x1F;
5934 lbm_value *global_env = lbm_get_global_env();
5935 lbm_uint orig_env = global_env[ix_key];
5936 lbm_value new_env;
5937 // A key is a symbol and should not need to be remembered.
5938 WITH_GC(new_env, lbm_env_set(orig_env,key,val))(new_env) = (lbm_env_set(orig_env,key,val)); if (lbm_is_symbol_merror
((new_env))) { gc(); (new_env) = (lbm_env_set(orig_env,key,val
)); if (lbm_is_symbol_merror((new_env))) { error_ctx((((0x23)
<< 4) | 0x00000000u)); } }
;
5939
5940 global_env[ix_key] = new_env;
5941}
5942
5943static lbm_value get_event_value(lbm_event_t *e) {
5944 lbm_value v;
5945 if (e->buf_len > 0) {
5946 lbm_flat_value_t fv;
5947 fv.buf = (uint8_t*)e->buf_ptr;
5948 fv.buf_size = e->buf_len;
5949 fv.buf_pos = 0;
5950 lbm_unflatten_value(&fv, &v);
5951 // Free the flat value buffer. GC is unaware of its existence.
5952 lbm_free(fv.buf);
5953 } else {
5954 v = (lbm_value)e->buf_ptr;
5955 }
5956 return v;
5957}
5958
5959// In a scenario where C is enqueuing events and other LBM threads
5960// are sendind mail to event handler concurrently, old events will
5961// be dropped as the backpressure mechanism wont detect this scenario.
5962// TODO: Low prio pondering on robust solutions.
5963static void process_events(void) {
5964
5965 if (!lbm_events) {
5966 return;
5967 }
5968
5969 lbm_event_t e;
5970 while (lbm_event_pop(&e)) {
5971 lbm_value event_val = get_event_value(&e);
5972 switch(e.type) {
5973 case LBM_EVENT_UNBLOCK_CTX:
5974 handle_event_unblock_ctx((lbm_cid)e.parameter, event_val);
5975 break;
5976 case LBM_EVENT_DEFINE:
5977 handle_event_define((lbm_value)e.parameter, event_val);
5978 break;
5979 case LBM_EVENT_FOR_HANDLER:
5980 if (lbm_event_handler_pid >= 0) {
5981 //If multiple events for handler, this is wasteful!
5982 // TODO: Find the event_handler once and send all mails.
5983 // However, do it with as little new code as possible.
5984 lbm_find_receiver_and_send(lbm_event_handler_pid, event_val);
5985 }
5986 break;
5987 }
5988 }
5989}
5990
5991void lbm_add_eval_symbols(void) {
5992 lbm_uint x = 0;
5993 lbm_uint y = 0;
5994 lbm_add_symbol("x", &x);
5995 lbm_add_symbol("y", &y);
5996 symbol_x = lbm_enc_sym(x);
5997 symbol_y = lbm_enc_sym(y);
5998}
5999
6000
6001
6002#ifdef LBM_SINGLE_THREADED
6003bool_Bool lbm_eval_step(int n) {
6004 if (setjmp(error_jmp_buf)_setjmp (error_jmp_buf) > 0) { return false0; }
6005
6006 bool_Bool busy = false0;
6007
6008 if (ctx_running) {
6009 busy = true1;
6010 while (n > 0 && ctx_running) {
6011 evaluation_step();
6012 n--;
6013 }
6014 if (ctx_running) {
6015 enqueue_ctx_nm(&queue, ctx_running);
6016 ctx_running = NULL((void*)0);
6017 }
6018 } else {
6019 if (gc_requested) gc();
6020 process_events();
6021 lbm_mutex_lock(&qmutex);
6022 wake_up_ctxs_nm();
6023 ctx_running = dequeue_ctx_nm(&queue);
6024 lbm_mutex_unlock(&qmutex);
6025 }
6026 return busy;
6027}
6028
6029bool_Bool lbm_eval_init(void) {
6030 blocked.first = NULL((void*)0);
6031 blocked.last = NULL((void*)0);
6032 queue.first = NULL((void*)0);
6033 queue.last = NULL((void*)0);
6034 ctx_running = NULL((void*)0);
6035
6036 if (!lbm_init_env()) return false0;
6037
6038 return true1;
6039}
6040
6041#else
6042
6043/* eval_cps_run can be paused
6044 I think it would be better use a mailbox for
6045 communication between other threads and the run_eval
6046 but for now a set of variables will be used. */
6047void lbm_run_eval(void){
6048 setjmp(error_jmp_buf)_setjmp (error_jmp_buf);
6049
6050 while (eval_running) {
6051 if (eval_cps_state_changed || eval_cps_run_state == EVAL_CPS_STATE_PAUSED1) {
6052 eval_cps_state_changed = false0;
6053 switch (eval_cps_next_state) {
6054 case EVAL_CPS_STATE_RESET16:
6055 if (eval_cps_run_state != EVAL_CPS_STATE_RESET16) {
6056 is_atomic = false0;
6057 blocked.first = NULL((void*)0);
6058 blocked.last = NULL((void*)0);
6059 queue.first = NULL((void*)0);
6060 queue.last = NULL((void*)0);
6061 ctx_running = NULL((void*)0);
6062#ifdef LBM_USE_TIME_QUOTA
6063 eval_time_quota = 0; // maybe timestamp here ?
6064#else
6065 eval_steps_quota = eval_steps_refill;
6066#endif
6067 eval_cps_run_state = EVAL_CPS_STATE_RESET16;
6068 if (blocking_extension) {
6069 blocking_extension = false0;
6070 lbm_mutex_unlock(&blocking_extension_mutex);
6071 }
6072 }
6073 usleep_callback(EVAL_CPS_MIN_SLEEP200);
6074 continue;
6075 case EVAL_CPS_STATE_PAUSED1:
6076 if (eval_cps_run_state != EVAL_CPS_STATE_PAUSED1) {
6077 if (lbm_heap_num_free() < eval_cps_next_state_arg) {
6078 gc();
6079 }
6080 eval_cps_next_state_arg = 0;
6081 eval_cps_run_state = EVAL_CPS_STATE_PAUSED1;
6082 }
6083 usleep_callback(EVAL_CPS_MIN_SLEEP200);
6084 continue;
6085 case EVAL_CPS_STATE_KILL4:
6086 eval_cps_run_state = EVAL_CPS_STATE_DEAD8;
6087 eval_running = false0;
6088 continue;
6089 default: // running state
6090 eval_cps_run_state = eval_cps_next_state;
6091 break;
6092 }
6093 }
6094 while (true1) {
6095#ifdef LBM_USE_TIME_QUOTA
6096 // Is "negative" (closer to max value) when the quota timestamp is "ahead
6097 // of" the current timestamp. It handles the quota being very large while
6098 // the current timestamp has overflowed back to being small, giving a
6099 // "positive" (closer to min value) result, meaning the context will be
6100 // switched.
6101 uint32_t unsigned_difference = lbm_timestamp() - eval_current_quota;
6102 bool_Bool is_negative = unsigned_difference & (1u << 31);
6103 if (is_negative && ctx_running) {
6104 evaluation_step();
6105 } else {
6106 if (eval_cps_state_changed) break;
6107 if (!is_atomic) {
6108 if (gc_requested) {
6109 gc();
6110 }
6111 process_events();
6112 lbm_mutex_lock(&qmutex);
6113 if (ctx_running) {
6114 enqueue_ctx_nm(&queue, ctx_running);
6115 ctx_running = NULL((void*)0);
6116 }
6117 wake_up_ctxs_nm();
6118 ctx_running = dequeue_ctx_nm(&queue);
6119 lbm_mutex_unlock(&qmutex);
6120 if (!ctx_running) {
6121 lbm_system_sleeping = true1;
6122 //Fixed sleep interval to poll events regularly.
6123 usleep_callback(EVAL_CPS_MIN_SLEEP200);
6124 lbm_system_sleeping = false0;
6125 }
6126 }
6127 // Assign a new quota last.
6128 // This means that the time it takes in finding a context to dequeue
6129 // and the other work above is not included in the woken up contexts quota.
6130 //
6131 // Earlier the new quota was assigned at the top of this branch,
6132 // If that happened such that timestamp + eval_time_refil ends
6133 // up to be just shy of an overflow, going through all the rest of
6134 // logic could potentially overflow the timestamp and create a situation
6135 // where the scheduled task has a humongous quota!
6136 eval_current_quota = lbm_timestamp() + eval_time_refill;
6137 }
6138#else
6139 if (eval_steps_quota && ctx_running) {
6140 eval_steps_quota--;
6141 evaluation_step();
6142 } else {
6143 if (eval_cps_state_changed) break;
6144 eval_steps_quota = eval_steps_refill;
6145 if (!is_atomic) {
6146 if (gc_requested) {
6147 gc();
6148 }
6149 process_events();
6150 lbm_mutex_lock(&qmutex);
6151 if (ctx_running) {
6152 enqueue_ctx_nm(&queue, ctx_running);
6153 ctx_running = NULL((void*)0);
6154 }
6155 wake_up_ctxs_nm();
6156 ctx_running = dequeue_ctx_nm(&queue);
6157 lbm_mutex_unlock(&qmutex);
6158 if (!ctx_running) {
6159 lbm_system_sleeping = true1;
6160 //Fixed sleep interval to poll events regularly.
6161 usleep_callback(EVAL_CPS_MIN_SLEEP200);
6162 lbm_system_sleeping = false0;
6163 }
6164 }
6165 }
6166#endif
6167 }
6168 }
6169}
6170
6171bool_Bool lbm_eval_init(void) {
6172 if (!qmutex_initialized) {
6173 lbm_mutex_init(&qmutex);
6174 qmutex_initialized = true1;
6175 }
6176 if (!lbm_events_mutex_initialized) {
6177 lbm_mutex_init(&lbm_events_mutex);
6178 lbm_events_mutex_initialized = true1;
6179 }
6180 if (!blocking_extension_mutex_initialized) {
6181 lbm_mutex_init(&blocking_extension_mutex);
6182 blocking_extension_mutex_initialized = true1;
6183 }
6184
6185 lbm_mutex_lock(&qmutex);
6186 lbm_mutex_lock(&lbm_events_mutex);
6187
6188 is_atomic = false0;
6189 blocked.first = NULL((void*)0);
6190 blocked.last = NULL((void*)0);
6191 queue.first = NULL((void*)0);
6192 queue.last = NULL((void*)0);
6193 ctx_running = NULL((void*)0);
6194
6195 eval_cps_run_state = EVAL_CPS_STATE_RUNNING2;
6196
6197 lbm_mutex_unlock(&lbm_events_mutex);
6198 lbm_mutex_unlock(&qmutex);
6199
6200 if (!lbm_init_env()) return false0;
6201 eval_running = true1;
6202 return true1;
6203}
6204
6205#endif
6206
6207bool_Bool lbm_eval_init_events(unsigned int num_events) {
6208
6209 lbm_mutex_lock(&lbm_events_mutex);
6210 lbm_events = (lbm_event_t*)lbm_malloc(num_events * sizeof(lbm_event_t));
6211 bool_Bool r = false0;
6212 if (lbm_events) {
6213 lbm_events_max = num_events;
6214 lbm_events_head = 0;
6215 lbm_events_tail = 0;
6216 lbm_events_full = false0;
6217 lbm_event_handler_pid = -1;
6218 r = true1;
6219 }
6220 lbm_mutex_unlock(&lbm_events_mutex);
6221 return r;
6222}