-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBytecode_Interpreter.H
More file actions
1725 lines (1550 loc) · 65.1 KB
/
Bytecode_Interpreter.H
File metadata and controls
1725 lines (1550 loc) · 65.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file Bytecode_Interpreter.H
* @brief Simple portable VM for executing the register bytecode in `Bytecode.H`.
*
* This header closes the first end-to-end execution loop over the compiler
* platform:
*
* `HIR -> IR -> Bytecode -> Bytecode_Interpreter`
*
* The VM is intentionally conservative and explicit:
*
* - registers are addressed by the ids already emitted by `Bytecode.H`
* - locals and globals remain explicit slot arrays instead of hidden stack
* memory
* - runtime failures are reported as structured values instead of exceptions
* - host callbacks from `Interpreter_Runtime.H` can be injected into globals
* - bytecode function references are kept distinct from HIR function values
*
* The execution model is deliberately small. It is meant to be easy to read,
* validate, and extend before any future optimized backend or threaded VM.
*
* @ingroup Utilities
*/
#ifndef BYTECODE_INTERPRETER_H
#define BYTECODE_INTERPRETER_H
#include <sstream>
#include <string>
#include <utility>
#include <Bytecode.H>
#include <Interpreter_Runtime.H>
namespace Aleph
{
/** @brief Runtime categories that can live inside bytecode registers/slots.
*
* Bytecode execution needs one extra case that `Interpreter_Value` does not
* model: references to bytecode functions addressed by `function_id`.
* Those references are not interchangeable with HIR callables, so the VM
* wraps both concepts in a distinct tagged value.
*/
enum class Compiler_Bytecode_Value_Kind
{
Invalid, ///< Uninitialized register/slot or explicit invalid placeholder.
Value, ///< Regular runtime payload stored as `Interpreter_Value`.
Function_Ref ///< Reference to one bytecode function in the current module.
};
/** @brief Final status produced by one VM execution request. */
enum class Compiler_Bytecode_Completion_Kind
{
Returned, ///< Execution finished with an explicit `Return`.
Halted, ///< Execution reached `Halt` and therefore produced `Unit`.
Runtime_Error ///< Execution failed with a structured runtime error.
};
/** @brief Stable debug name for one bytecode runtime value kind. */
inline const char *
compiler_bytecode_value_kind_name(const Compiler_Bytecode_Value_Kind kind) noexcept
{
switch (kind)
{
case Compiler_Bytecode_Value_Kind::Invalid:
return "Invalid";
case Compiler_Bytecode_Value_Kind::Value:
return "Value";
case Compiler_Bytecode_Value_Kind::Function_Ref:
return "FunctionRef";
}
return "Unknown";
}
/** @brief Stable debug name for one execution completion kind. */
inline const char *
compiler_bytecode_completion_kind_name(const Compiler_Bytecode_Completion_Kind kind) noexcept
{
switch (kind)
{
case Compiler_Bytecode_Completion_Kind::Returned:
return "Returned";
case Compiler_Bytecode_Completion_Kind::Halted:
return "Halted";
case Compiler_Bytecode_Completion_Kind::Runtime_Error:
return "RuntimeError";
}
return "Unknown";
}
/** @brief One value stored in bytecode registers, locals, or globals.
*
* The VM reuses `Interpreter_Value` for ordinary runtime data such as
* integers, booleans, strings, tuples, or host functions. Bytecode function
* references remain separate so the VM never confuses bytecode callables
* with HIR function values.
*/
struct Compiler_Bytecode_Value
{
Compiler_Bytecode_Value_Kind kind = Compiler_Bytecode_Value_Kind::Invalid; ///< Active payload category.
Interpreter_Value runtime_value = Interpreter_Value::make_invalid(); ///< Wrapped scalar/tuple/host-function value.
Compiler_Bytecode_Function_Id function_id = compiler_bytecode_invalid_id(); ///< Referenced bytecode function when `kind == Function_Ref`.
/** @brief Builds an invalid placeholder value. */
static Compiler_Bytecode_Value
make_invalid()
{
return {};
}
/** @brief Wraps one regular runtime value. */
static Compiler_Bytecode_Value
make_value(const Interpreter_Value & value)
{
Compiler_Bytecode_Value result;
result.kind = Compiler_Bytecode_Value_Kind::Value;
result.runtime_value = value;
return result;
}
/** @brief Wraps one regular runtime value by move. */
static Compiler_Bytecode_Value
make_value(Interpreter_Value && value)
{
Compiler_Bytecode_Value result;
result.kind = Compiler_Bytecode_Value_Kind::Value;
result.runtime_value = std::move(value);
return result;
}
/** @brief Builds the Unit singleton. */
static Compiler_Bytecode_Value
make_unit()
{
return make_value(Interpreter_Value::make_unit());
}
/** @brief Builds a boolean runtime value. */
static Compiler_Bytecode_Value
make_bool(const bool value)
{
return make_value(Interpreter_Value::make_bool(value));
}
/** @brief Builds an integer runtime value. */
static Compiler_Bytecode_Value
make_integer(const long long value)
{
return make_value(Interpreter_Value::make_integer(value));
}
/** @brief Builds a string runtime value. */
static Compiler_Bytecode_Value
make_string(std::string text)
{
return make_value(Interpreter_Value::make_string(std::move(text)));
}
/** @brief Builds a character runtime value. */
static Compiler_Bytecode_Value
make_character(const char ch)
{
return make_value(Interpreter_Value::make_character(ch));
}
/** @brief Builds a callable value backed by host code.
*
* This is useful for embeddings that want to expose helper functions to
* bytecode by preloading globals before execution.
*/
static Compiler_Bytecode_Value
make_host_function(std::string name,
const Interpreter_Host_Function callback,
void * user_data = nullptr)
{
return make_value(Interpreter_Value::make_host_function(std::move(name),
callback,
user_data));
}
/** @brief Builds a reference to one bytecode function in the current module. */
static Compiler_Bytecode_Value
make_function_ref(const Compiler_Bytecode_Function_Id id)
{
Compiler_Bytecode_Value result;
result.kind = Compiler_Bytecode_Value_Kind::Function_Ref;
result.function_id = id;
return result;
}
/** @brief Returns whether this value is invalid. */
[[nodiscard]] bool
is_invalid() const noexcept
{
return kind == Compiler_Bytecode_Value_Kind::Invalid;
}
/** @brief Returns whether this value wraps an `Interpreter_Value`. */
[[nodiscard]] bool
is_runtime_value() const noexcept
{
return kind == Compiler_Bytecode_Value_Kind::Value;
}
/** @brief Returns whether this value is a bytecode function reference. */
[[nodiscard]] bool
is_function_ref() const noexcept
{
return kind == Compiler_Bytecode_Value_Kind::Function_Ref;
}
};
/** @brief Structured runtime error produced by the bytecode VM. */
struct Compiler_Bytecode_Runtime_Error
{
std::string code; ///< Stable runtime code such as `BCV013`.
std::string message; ///< Human-readable runtime message.
std::string function_name; ///< Function active at the failure point, when known.
Compiler_Bytecode_PC pc = compiler_bytecode_invalid_id(); ///< Program counter active at the failure point, when known.
Source_Span span; ///< Source span associated with the current instruction, when known.
/** @brief Returns whether this error object is populated. */
[[nodiscard]] bool
has_error() const noexcept
{
return not code.empty() or not message.empty();
}
};
/** @brief Result of one bytecode execution request. */
struct Compiler_Bytecode_Execution_Result
{
Compiler_Bytecode_Completion_Kind kind = Compiler_Bytecode_Completion_Kind::Halted; ///< Final completion category.
Compiler_Bytecode_Value value = Compiler_Bytecode_Value::make_unit(); ///< Produced return value or final `Unit`.
Compiler_Bytecode_Runtime_Error error; ///< Structured failure when `kind == Runtime_Error`.
size_t executed_instructions = 0; ///< Number of bytecode instructions observed by the VM.
/** @brief Returns whether execution completed without runtime errors. */
[[nodiscard]] bool
ok() const noexcept
{
return kind != Compiler_Bytecode_Completion_Kind::Runtime_Error;
}
/** @brief Builds a successful return result. */
static Compiler_Bytecode_Execution_Result
returned(const Compiler_Bytecode_Value & value,
const size_t executed_instructions)
{
Compiler_Bytecode_Execution_Result result;
result.kind = Compiler_Bytecode_Completion_Kind::Returned;
result.value = value;
result.executed_instructions = executed_instructions;
return result;
}
/** @brief Builds a successful halt result. */
static Compiler_Bytecode_Execution_Result
halted(const Compiler_Bytecode_Value & value,
const size_t executed_instructions)
{
Compiler_Bytecode_Execution_Result result;
result.kind = Compiler_Bytecode_Completion_Kind::Halted;
result.value = value;
result.executed_instructions = executed_instructions;
return result;
}
/** @brief Builds a failed runtime result. */
static Compiler_Bytecode_Execution_Result
runtime_error(const Compiler_Bytecode_Runtime_Error & error,
const size_t executed_instructions)
{
Compiler_Bytecode_Execution_Result result;
result.kind = Compiler_Bytecode_Completion_Kind::Runtime_Error;
result.error = error;
result.executed_instructions = executed_instructions;
result.value = Compiler_Bytecode_Value::make_invalid();
return result;
}
};
/** @brief Returns whether two bytecode values compare equal.
*
* Equality is structural for wrapped `Interpreter_Value` payloads and exact
* by function id for bytecode function references.
*/
inline bool
compiler_bytecode_values_equal(const Compiler_Bytecode_Value & lhs,
const Compiler_Bytecode_Value & rhs)
{
if (lhs.kind != rhs.kind)
return false;
switch (lhs.kind)
{
case Compiler_Bytecode_Value_Kind::Invalid:
return true;
case Compiler_Bytecode_Value_Kind::Value:
return interpreter_values_equal(lhs.runtime_value, rhs.runtime_value);
case Compiler_Bytecode_Value_Kind::Function_Ref:
return lhs.function_id == rhs.function_id;
}
return false;
}
/** @brief Renders one bytecode value deterministically.
*
* @param value Value to render.
* @param module Optional module used to enrich bytecode function references
* with function names.
* @return Stable human-readable rendering.
*/
inline std::string
compiler_bytecode_value_to_string(const Compiler_Bytecode_Value & value,
const Compiler_Bytecode_Module * module = nullptr)
{
switch (value.kind)
{
case Compiler_Bytecode_Value_Kind::Invalid:
return "Invalid";
case Compiler_Bytecode_Value_Kind::Value:
return interpreter_value_to_string(value.runtime_value);
case Compiler_Bytecode_Value_Kind::Function_Ref:
{
std::ostringstream out;
out << "BytecodeFunction(f" << value.function_id;
if (module != nullptr and value.function_id < module->functions.size())
out << ", " << module->functions.access(value.function_id)->name;
out << ')';
return out.str();
}
}
return "Unknown";
}
/** @brief Dumps the current global state associated with one bytecode module.
*
* @param module Bytecode module that owns the slot layout.
* @param globals Runtime values stored in each global slot.
* @return Deterministic plain-text dump.
*/
inline std::string
compiler_dump_bytecode_globals(const Compiler_Bytecode_Module * module,
const DynArray<Compiler_Bytecode_Value> & globals)
{
std::ostringstream out;
if (module == nullptr)
{
out << "<null-bytecode-globals>\n";
return out.str();
}
out << "BytecodeGlobals\n";
if (module->global_slots.is_empty())
{
out << " <none>\n";
return out.str();
}
for (size_t i = 0; i < module->global_slots.size(); ++i)
{
const auto & slot = module->global_slots.access(i);
out << " g" << slot.id << ' ' << slot.name << " = ";
if (slot.id < globals.size())
out << compiler_bytecode_value_to_string(globals.access(slot.id), module);
else
out << "<missing>";
out << '\n';
}
return out.str();
}
namespace Compiler_Bytecode_Interpreter_Detail
{
inline void
reset_values(DynArray<Compiler_Bytecode_Value> & values,
const size_t count,
const Compiler_Bytecode_Value & fill = Compiler_Bytecode_Value::make_invalid())
{
values.clear();
for (size_t i = 0; i < count; ++i)
values.append(fill);
}
inline size_t
count_parameters(const Compiler_Bytecode_Function & function) noexcept
{
size_t count = 0;
for (size_t i = 0; i < function.local_slots.size(); ++i)
if (function.local_slots.access(i).kind == Compiler_IR_Slot_Kind::Parameter)
++count;
return count;
}
inline bool
constant_to_value(const Compiler_Bytecode_Constant & constant,
Compiler_Bytecode_Value & value,
std::string & error)
{
switch (constant.kind)
{
case Compiler_Bytecode_Constant_Kind::Unit:
value = Compiler_Bytecode_Value::make_unit();
return true;
case Compiler_Bytecode_Constant_Kind::Boolean:
value = Compiler_Bytecode_Value::make_bool(constant.bool_value);
return true;
case Compiler_Bytecode_Constant_Kind::Integer:
value = Compiler_Bytecode_Value::make_integer(constant.integer_value);
return true;
case Compiler_Bytecode_Constant_Kind::String:
{
std::string decoded = constant.text;
if (decoded.size() >= 2 and decoded.front() == '"' and decoded.back() == '"')
decoded = decoded.substr(1, decoded.size() - 2);
value = Compiler_Bytecode_Value::make_string(std::move(decoded));
return true;
}
case Compiler_Bytecode_Constant_Kind::Character:
value = Compiler_Bytecode_Value::make_character(constant.char_value);
return true;
case Compiler_Bytecode_Constant_Kind::Raw_Text:
error = "unsupported raw constant payload '" + constant.text + "'";
return false;
}
error = "unknown constant kind";
return false;
}
}
/** @brief Small portable VM for executing one `Compiler_Bytecode_Module`.
*
* The VM owns mutable runtime state only:
*
* - global slot values
* - the active call stack
* - transient register/local arrays per frame
*
* The bytecode module itself remains immutable and can be shared.
*/
class Compiler_Bytecode_VM
{
struct Frame
{
const Compiler_Bytecode_Function * function = nullptr;
Compiler_Bytecode_PC pc = compiler_bytecode_invalid_id();
DynArray<Compiler_Bytecode_Value> registers;
DynArray<Compiler_Bytecode_Value> locals;
Compiler_Bytecode_PC caller_resume_pc = compiler_bytecode_invalid_id();
Compiler_Bytecode_Register_Id caller_destination = 0;
bool returns_to_caller = false;
};
const Compiler_Bytecode_Module * bytecode_module = nullptr;
DynArray<Compiler_Bytecode_Value> globals;
DynArray<Frame> call_stack;
[[nodiscard]] const Frame &
current_frame() const
{
return call_stack.get_last();
}
Frame &
current_frame()
{
return call_stack.get_last();
}
[[nodiscard]] Compiler_Bytecode_Execution_Result
make_error(const std::string & code,
const std::string & message,
const size_t executed_instructions,
const Frame * frame = nullptr,
const Compiler_Bytecode_Instruction * inst = nullptr) const
{
Compiler_Bytecode_Runtime_Error error;
error.code = code;
error.message = message;
if (frame != nullptr and frame->function != nullptr)
{
error.function_name = frame->function->name;
error.pc = frame->pc;
}
if (inst != nullptr)
error.span = inst->span;
return Compiler_Bytecode_Execution_Result::runtime_error(error,
executed_instructions);
}
[[nodiscard]] Compiler_Bytecode_Execution_Result
make_validation_error(const Compiler_Bytecode_Validation_Report & report,
const size_t executed_instructions = 0) const
{
const std::string message = report.errors.is_empty()
? "invalid bytecode module"
: report.errors.access(0);
return make_error("BCV001", message, executed_instructions);
}
[[nodiscard]] bool
module_is_valid(Compiler_Bytecode_Execution_Result & error) const
{
const auto report = validate_bytecode_module(*bytecode_module);
if (report.valid)
return true;
error = make_validation_error(report);
return false;
}
[[nodiscard]] bool
push_frame(const Compiler_Bytecode_Function & function,
const DynArray<Compiler_Bytecode_Value> & arguments,
const bool returns_to_caller,
const Compiler_Bytecode_PC caller_resume_pc,
const Compiler_Bytecode_Register_Id caller_destination,
const size_t executed_instructions,
Compiler_Bytecode_Execution_Result & error)
{
const auto expected_arity
= Compiler_Bytecode_Interpreter_Detail::count_parameters(function);
if (arguments.size() != expected_arity)
{
error = make_error("BCV004",
"function '" + function.name + "' expects "
+ std::to_string(expected_arity) + " arguments but received "
+ std::to_string(arguments.size()),
executed_instructions);
return false;
}
Frame frame;
frame.function = &function;
frame.pc = function.entry_pc;
frame.caller_resume_pc = caller_resume_pc;
frame.caller_destination = caller_destination;
frame.returns_to_caller = returns_to_caller;
Compiler_Bytecode_Interpreter_Detail::reset_values(frame.registers,
function.register_count);
Compiler_Bytecode_Interpreter_Detail::reset_values(frame.locals,
function.local_slots.size());
size_t arg_index = 0;
for (size_t i = 0; i < function.local_slots.size(); ++i)
{
const auto & slot = function.local_slots.access(i);
if (slot.kind == Compiler_IR_Slot_Kind::Parameter)
{
if (slot.id >= frame.locals.size())
{
error = make_error("BCV006",
"parameter slot id " + std::to_string(slot.id)
+ " is out of bounds in function '" + function.name + "'",
executed_instructions);
return false;
}
frame.locals.access(slot.id) = arguments.access(arg_index++);
}
}
call_stack.append(std::move(frame));
return true;
}
[[nodiscard]] bool
read_register(const Frame & frame,
const Compiler_Bytecode_Register_Id id,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
Compiler_Bytecode_Value & value,
Compiler_Bytecode_Execution_Result & error) const
{
if (id >= frame.registers.size())
{
error = make_error("BCV006",
"invalid register r" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
value = frame.registers.access(id);
if (value.is_invalid())
{
error = make_error("BCV007",
"read from uninitialized register r" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
return true;
}
[[nodiscard]] bool
write_register(Frame & frame,
const Compiler_Bytecode_Register_Id id,
const Compiler_Bytecode_Value & value,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
Compiler_Bytecode_Execution_Result & error) const
{
if (id >= frame.registers.size())
{
error = make_error("BCV006",
"invalid register r" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
frame.registers.access(id) = value;
return true;
}
[[nodiscard]] bool
read_local(const Frame & frame,
const Compiler_IR_Local_Slot_Id id,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
Compiler_Bytecode_Value & value,
Compiler_Bytecode_Execution_Result & error) const
{
if (id >= frame.locals.size())
{
error = make_error("BCV006",
"invalid local slot s" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
value = frame.locals.access(id);
if (value.is_invalid())
{
error = make_error("BCV008",
"read from uninitialized local slot s" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
return true;
}
[[nodiscard]] bool
write_local(Frame & frame,
const Compiler_IR_Local_Slot_Id id,
const Compiler_Bytecode_Value & value,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
Compiler_Bytecode_Execution_Result & error) const
{
if (id >= frame.locals.size())
{
error = make_error("BCV006",
"invalid local slot s" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
frame.locals.access(id) = value;
return true;
}
[[nodiscard]] bool
read_global(const Frame & frame,
const Compiler_IR_Global_Slot_Id id,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
Compiler_Bytecode_Value & value,
Compiler_Bytecode_Execution_Result & error) const
{
if (id >= globals.size())
{
error = make_error("BCV006",
"invalid global slot g" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
value = globals.access(id);
if (value.is_invalid())
{
error = make_error("BCV009",
"read from uninitialized global slot g" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
return true;
}
[[nodiscard]] bool
write_global(Frame & frame,
const Compiler_IR_Global_Slot_Id id,
const Compiler_Bytecode_Value & value,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
Compiler_Bytecode_Execution_Result & error)
{
if (id >= globals.size())
{
error = make_error("BCV006",
"invalid global slot g" + std::to_string(id),
executed_instructions,
&frame,
&inst);
return false;
}
globals.access(id) = value;
return true;
}
[[nodiscard]] bool
require_integer(const Compiler_Bytecode_Value & value,
const Frame & frame,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
const std::string & context,
long long & result,
Compiler_Bytecode_Execution_Result & error) const
{
if (not value.is_runtime_value()
or value.runtime_value.kind != Interpreter_Value_Kind::Integer)
{
error = make_error("BCV011",
context + " expects Integer but received "
+ compiler_bytecode_value_to_string(value, bytecode_module),
executed_instructions,
&frame,
&inst);
return false;
}
result = value.runtime_value.integer_value;
return true;
}
[[nodiscard]] bool
require_bool(const Compiler_Bytecode_Value & value,
const Frame & frame,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
const std::string & context,
bool & result,
Compiler_Bytecode_Execution_Result & error) const
{
if (not value.is_runtime_value()
or value.runtime_value.kind != Interpreter_Value_Kind::Bool)
{
error = make_error("BCV012",
context + " expects Bool but received "
+ compiler_bytecode_value_to_string(value, bytecode_module),
executed_instructions,
&frame,
&inst);
return false;
}
result = value.runtime_value.bool_value;
return true;
}
[[nodiscard]] bool
read_callee_and_arguments(const Frame & frame,
const Compiler_Bytecode_Instruction & inst,
const size_t executed_instructions,
Compiler_Bytecode_Value & callee,
DynArray<Compiler_Bytecode_Value> & arguments,
Compiler_Bytecode_Execution_Result & error) const
{
if (inst.operands.is_empty())
{
error = make_error("BCV017",
"call instruction has no callee operand",
executed_instructions,
&frame,
&inst);
return false;
}
if (not read_register(frame,
inst.operands.access(0),
inst,
executed_instructions,
callee,
error))
return false;
arguments.clear();
for (size_t i = 1; i < inst.operands.size(); ++i)
{
Compiler_Bytecode_Value argument;
if (not read_register(frame,
inst.operands.access(i),
inst,
executed_instructions,
argument,
error))
return false;
arguments.append(argument);
}
return true;
}
[[nodiscard]] bool
complete_current_frame(const Compiler_Bytecode_Value & value,
const Compiler_Bytecode_Completion_Kind kind,
const size_t executed_instructions,
Compiler_Bytecode_Execution_Result & completed,
Compiler_Bytecode_Execution_Result & error)
{
const auto finished = call_stack.pop();
if (not finished.returns_to_caller)
{
completed = kind == Compiler_Bytecode_Completion_Kind::Returned
? Compiler_Bytecode_Execution_Result::returned(value, executed_instructions)
: Compiler_Bytecode_Execution_Result::halted(value, executed_instructions);
return true;
}
auto & caller = current_frame();
if (not write_register(caller,
finished.caller_destination,
value,
caller.function->code.access(caller.pc),
executed_instructions,
error))
return true;
caller.pc = finished.caller_resume_pc;
return false;
}
[[nodiscard]] bool
execute_host_call(Frame & frame,
const Compiler_Bytecode_Instruction & inst,
const Compiler_Bytecode_Value & callee,
const DynArray<Compiler_Bytecode_Value> & arguments,
const size_t executed_instructions,
Compiler_Bytecode_Execution_Result & error)
{
DynArray<Interpreter_Value> runtime_arguments;
for (size_t i = 0; i < arguments.size(); ++i)
{
if (not arguments.access(i).is_runtime_value())
{
error = make_error("BCV019",
"host function arguments cannot contain bytecode function references",
executed_instructions,
&frame,
&inst);
return false;
}
runtime_arguments.append(arguments.access(i).runtime_value);
}
Interpreter_Value runtime_result = Interpreter_Value::make_invalid();
Interpreter_Runtime_Error host_error;
const bool ok = callee.runtime_value.host_function(callee.runtime_value.host_user_data,
runtime_arguments,
runtime_result,
host_error);
if (not ok)
{
error = make_error(host_error.code.empty() ? "BCV021" : host_error.code,
host_error.message.empty()
? "host function call failed"
: host_error.message,
executed_instructions,
&frame,
&inst);
if (host_error.has_error() and not host_error.code.empty())
error.error.span = host_error.span;
return false;
}
if (not write_register(frame,
inst.destination,
Compiler_Bytecode_Value::make_value(std::move(runtime_result)),
inst,
executed_instructions,
error))
return false;
++frame.pc;
return true;
}
[[nodiscard]] Compiler_Bytecode_Execution_Result
execute_loop(const size_t max_steps)
{
size_t executed_instructions = 0;
while (not call_stack.is_empty())
{
if (max_steps != 0 and executed_instructions >= max_steps)
return make_error("BCV020",
"bytecode step limit exceeded",
executed_instructions,
¤t_frame());
auto & frame = current_frame();
if (frame.pc >= frame.function->code.size())
return make_error("BCV005",
"program counter " + std::to_string(frame.pc)
+ " is out of bounds in function '" + frame.function->name + "'",
executed_instructions,
&frame);
const auto & inst = frame.function->code.access(frame.pc);
++executed_instructions;
switch (inst.opcode)
{
case Compiler_Bytecode_Opcode::Load_Constant:
{
if (inst.constant_id >= frame.function->constants.size())
return make_error("BCV006",
"invalid constant id k"
+ std::to_string(inst.constant_id),
executed_instructions,
&frame,
&inst);
Compiler_Bytecode_Value value;
std::string conversion_error;
if (not Compiler_Bytecode_Interpreter_Detail::constant_to_value(
frame.function->constants.access(inst.constant_id),
value,
conversion_error))
return make_error("BCV010",
conversion_error,
executed_instructions,
&frame,
&inst);
Compiler_Bytecode_Execution_Result error;
if (not write_register(frame,
inst.destination,
value,
inst,