Phasor 3.3.0
Stack VM based Programming Language
Loading...
Searching...
No Matches
Variables.cpp
Go to the documentation of this file.
1#ifndef CMAKE_PCH
2#include "VM.hpp"
3#endif
4
5namespace Phasor
6{
7
8size_t VM::addVariable(const Value &value)
9{
10#ifdef TRACING
11 log(std::format("VM::{}({:T})\n", __func__, value));
12 flush();
13#endif
14 variables.push_back(value);
15 return variables.size() - 1;
16}
17
18void VM::freeVariable(const size_t index)
19{
20#ifdef TRACING
21 log(std::format("VM::{}({})\n", __func__, index));
22 flush();
23#endif
24 if (index < variables.size())
25 {
26 variables[index] = Value();
27 }
28}
29
30void VM::freeVariableByName(const std::string &name)
31{
32#ifdef TRACING
33 log(std::format("VM::{}(\"{}\")\n", __func__, name));
34 flush();
35#endif
36 if (!m_bytecode)
37 throw std::runtime_error("Error in freeVariable(): No bytecode loaded");
38 auto it = m_bytecode->variables.find(name);
39 if (it == m_bytecode->variables.end())
40 throw std::runtime_error("Error in freeVariable(): Unknown variable \"" + name + "\"");
41
42 freeVariable(it->second);
43}
44
45void VM::setVariable(const size_t index, const Value &value)
46{
47#ifdef TRACING
48 log(std::format("VM::{}({}, {:T})\n", __func__, index, value));
49 flush();
50#endif
51 if (index >= variables.size())
52 {
53 throw std::runtime_error("Invalid variable index");
54 }
55 variables[index] = value;
56}
57
58Value VM::getVariable(const size_t index)
59{
60 if (index >= variables.size())
61 {
62#ifdef TRACING
63 log(std::format("VM::{}({}) -> <invalid index>\n", __func__, index));
64 flush();
65#endif
66 throw std::runtime_error("Invalid variable index");
67 }
68#ifdef TRACING
69 log(std::format("VM::{}({}) -> {:T}\n", __func__, index, variables[index]));
70 flush();
71#endif
72 return variables[index];
73}
74
76{
77#ifdef TRACING
78 log(std::format("VM::{}()\n", __func__));
79 flush();
80#endif
81 return variables.size();
82}
83
84} // namespace Phasor
std::vector< Value > variables
Variable storage indexed by variable index, or simply: the managed heap.
Definition VM.hpp:259
Value getVariable(size_t index)
Get a variable from the VM.
Definition Variables.cpp:58
void freeVariableByName(const std::string &name)
Free a variable by name in the VM.
Definition Variables.cpp:30
size_t getVariableCount()
Get the number of variables in the VM.
Definition Variables.cpp:75
void log(const Value &msg)
Log a Value to stdout.
Definition Utility.cpp:269
size_t addVariable(const Value &value)
Add a variable to the VM.
Definition Variables.cpp:8
void flush()
Flush stdout.
Definition Utility.cpp:281
void setVariable(size_t index, const Value &value)
Set a variable in the VM.
Definition Variables.cpp:45
const Bytecode * m_bytecode
Bytecode to execute.
Definition VM.hpp:262
void freeVariable(size_t index)
Free a variable in the VM.
Definition Variables.cpp:18
A value in the Phasor VM.
Definition Value.hpp:58
The Phasor Programming Language and Runtime.
Definition AST.hpp:12