ArkScript
A small, lisp-inspired, functional scripting language
State.cpp
Go to the documentation of this file.
1#include <Ark/State.hpp>
2
3#include <Ark/Constants.hpp>
4#include <Ark/Utils/Files.hpp>
6
7#ifdef _MSC_VER
8# pragma warning(push)
9# pragma warning(disable : 4996)
10#endif
11
12#include <Proxy/Picosha2.hpp>
14#include <fmt/core.h>
15#include <fmt/color.h>
16
17namespace Ark
18{
19 State::State(const std::vector<std::filesystem::path>& libenv) noexcept :
20 m_debug_level(0),
21 m_features(0),
22 m_libenv(libenv),
23 m_filename(ARK_NO_NAME_FILE),
24 m_max_page_size(0)
25 {
26 // default value for builtin__sys:args is empty list
27 const Value val(ValueType::List);
28 m_bound[std::string(internal::Language::SysArgs)] = val;
29 m_bound[std::string(internal::Language::SysProgramName)] = Value("");
30 }
31
32 bool State::feed(const std::string& bytecode_filename, const bool fail_with_exception)
33 {
34 if (!Utils::fileExists(bytecode_filename))
35 return false;
36
37 return feed(Utils::readFileAsBytes(bytecode_filename), fail_with_exception);
38 }
39
40 bool State::feed(const bytecode_t& bytecode, const bool fail_with_exception)
41 {
43 bcr.feed(bytecode);
44 if (!bcr.checkMagic())
45 return false;
46
47 m_bytecode = bytecode;
48
49 try
50 {
51 configure(bcr);
52 return true;
53 }
54 catch (const std::exception& e)
55 {
56 if (fail_with_exception)
57 throw;
58
59 fmt::println("{}", e.what());
60 return false;
61 }
62 }
63
64 bool State::compile(const std::string& file, const std::string& output, std::ostream* stream)
65 {
67 if (stream != nullptr)
68 welder.redirectLogsTo(*stream);
69
70 for (const auto& key : m_bound | std::views::keys)
71 welder.registerSymbol(key);
72
73 if (!welder.computeASTFromFile(file))
74 return false;
75 if (!welder.generateBytecode())
76 return false;
77
78 const std::string destination = output.empty() ? (file.substr(0, file.find_last_of('.')) + ".arkc") : output;
79 if ((m_features & DisableCache) == 0 && !welder.saveBytecodeToFile(destination))
80 return false;
81 if (!feed(welder.bytecode()))
82 return false;
83
84 return true;
85 }
86
87 bool State::doFile(const std::string& file_path, const uint16_t features, std::ostream* stream)
88 {
89 m_features = features;
90
91 if (!Utils::fileExists(file_path))
92 {
93 fmt::print(fmt::fg(fmt::color::red), "Can not find file '{}'\n", file_path);
94 return false;
95 }
96 m_filename = file_path;
97 m_bound[std::string(internal::Language::SysProgramName)] = Value(std::filesystem::path(m_filename).filename().string());
98
99 const bytecode_t bytecode = Utils::readFileAsBytes(file_path);
100 BytecodeReader bcr;
101 bcr.feed(bytecode);
102 if (!bcr.checkMagic()) // couldn't read magic number, it's a source file
103 {
104 // check if it's in the arkscript cache
105 const std::string filename = std::filesystem::path(file_path).filename().replace_extension(".arkc").string();
106 const std::filesystem::path cache_directory = std::filesystem::path(file_path).parent_path() / ARK_CACHE_DIRNAME;
107 const std::string bytecode_path = (cache_directory / filename).string();
108
109 if (!exists(cache_directory) && (m_features & DisableCache) == 0)
110 {
111 try
112 {
113 create_directory(cache_directory);
114 }
115 catch (const std::filesystem::filesystem_error&)
116 {
118 }
119 }
120
121 if (compile(file_path, bytecode_path, stream))
122 return true;
123 }
124 else if (feed(bytecode)) // it's a bytecode file
125 return true;
126 return false;
127 }
128
129 bool State::doString(const std::string& code, const uint16_t features, std::ostream* stream)
130 {
131 m_features = features;
132
134 if (stream != nullptr)
135 welder.redirectLogsTo(*stream);
136
137 for (const auto& p : m_bound)
138 welder.registerSymbol(p.first);
139
140 if (!welder.computeASTFromString(code))
141 return false;
142 if (!welder.generateBytecode())
143 return false;
144 return feed(welder.bytecode());
145 }
146
147 void State::loadFunction(const std::string& name, Procedure::CallbackType&& function) noexcept
148 {
149 m_bound[name] = Value(std::move(function));
150 }
151
152 void State::setArgs(const std::vector<std::string>& args) noexcept
153 {
155 std::ranges::transform(args, std::back_inserter(val.list()), [](const std::string& arg) {
156 return Value(arg);
157 });
158
159 m_bound[std::string(internal::Language::SysArgs)] = val;
160 }
161
162 void State::setDebug(const unsigned level) noexcept
163 {
164 m_debug_level = level;
165 }
166
167 void State::setLibDirs(const std::vector<std::filesystem::path>& libenv) noexcept
168 {
169 m_libenv = libenv;
170 }
171
173 {
174 using namespace internal;
175
176 const auto [major, minor, patch] = bcr.version();
177 if (major != ARK_VERSION_MAJOR)
178 {
179 const std::string str_version = fmt::format("{}.{}.{}", major, minor, patch);
180 throwStateError(fmt::format("Compiler and VM versions don't match: got {} while running {}", str_version, ARK_VERSION));
181 }
182
183 const auto bytecode_hash = bcr.sha256();
184
185 std::vector<unsigned char> hash(picosha2::k_digest_size);
186 picosha2::hash256(m_bytecode.begin() + bytecode::HeaderSize + picosha2::k_digest_size, m_bytecode.end(), hash);
187 // checking integrity
188 for (std::size_t j = 0; j < picosha2::k_digest_size; ++j)
189 {
190#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
191 if (hash[j] != bytecode_hash[j])
192 throwStateError("Integrity check failed");
193#endif
194 }
195
196 const auto syms = bcr.symbols();
197 const auto vals = bcr.values(syms);
198 const auto files = bcr.filenames(vals);
199 const auto inst_locs = bcr.instLocations(files);
200 const auto [pages, _] = bcr.code(inst_locs);
201
202 m_symbols = syms.symbols;
203 m_constants = vals.values;
204 m_filenames = files.filenames;
205 m_inst_locations = inst_locs.locations;
206 m_pages = pages;
208
209 // Make m_code as a big contiguous chunk of instructions,
210 // aligned on the biggest page size.
211 // This might have a downside when we have a single big page and
212 // a bunch of smaller ones, though I couldn't measure it while testing.
213 m_code.resize(m_max_page_size * pages.size(), Instruction::NOP);
214 addPagesToContiguousBytecode(pages, /* start= */ 0);
215 }
216
217 void State::reset() noexcept
218 {
219 m_symbols.clear();
220 m_constants.clear();
221 m_filenames.clear();
222 m_inst_locations.clear();
223 m_max_page_size = 0;
224 m_code.clear();
225 m_bound.clear();
226
227 // default value for builtin__sys:args is empty list
228 const Value val(ValueType::List);
229 m_bound[std::string(internal::Language::SysArgs)] = val;
231 }
232
233 void State::addPagesToContiguousBytecode(const std::vector<bytecode_t>& pages, const std::size_t start)
234 {
235 for (std::size_t i = 0, end = pages.size(); i < end; ++i)
236 {
237 for (std::size_t j = 0, end_j = pages[i].size(); j < end_j; ++j)
238 m_code[(start + i) * m_max_page_size + j] = pages[i][j];
239 }
240 }
241
242 std::size_t State::maxPageSize(const std::vector<bytecode_t>& pages)
243 {
244 return std::ranges::max(pages, {}, &bytecode_t::size).size();
245 }
246
247 void State::extendBytecode(const std::vector<bytecode_t>& pages, const std::vector<std::string>& symbols, const std::vector<Value>& constants)
248 {
249 m_symbols = symbols;
250 m_constants = constants;
251
252 // do not modify m_pages so that we can start over
253 m_max_page_size = std::max(m_max_page_size, maxPageSize(pages));
254
255 m_code.resize(m_max_page_size * (m_pages.size() + pages.size()), internal::Instruction::NOP);
256 addPagesToContiguousBytecode(m_pages, /* start= */ 0);
257 addPagesToContiguousBytecode(pages, /* start= */ m_pages.size());
258 }
259}
260
261#ifdef _MSC_VER
262# pragma warning(pop)
263#endif
A bytecode disassembler for ArkScript.
Constants used by ArkScript.
constexpr std::string_view ARK_VERSION
Definition Constants.hpp:27
constexpr int ARK_VERSION_MAJOR
Definition Constants.hpp:18
#define ARK_NO_NAME_FILE
Definition Constants.hpp:34
#define ARK_CACHE_DIRNAME
Definition Constants.hpp:33
Lots of utilities about the filesystem.
State used by the virtual machine: it loads the bytecode, can compile it if needed,...
In charge of welding everything needed to compile code.
This class is just a helper to.
Symbols symbols() const
Filenames filenames(const Values &values) const
InstLocations instLocations(const Filenames &filenames) const
Version version() const
Code code(const InstLocations &instLocations) const
Values values(const Symbols &symbols) const
std::vector< unsigned char > sha256() const
void feed(const std::string &file)
Construct needed data before displaying information about a given file.
std::function< Value(std::vector< Value > &, VM *)> CallbackType
Definition Procedure.hpp:29
std::vector< std::filesystem::path > m_libenv
Definition State.hpp:166
void setLibDirs(const std::vector< std::filesystem::path > &libenv) noexcept
Set the std search paths.
Definition State.cpp:167
uint16_t m_features
Definition State.hpp:163
std::unordered_map< std::string, Value > m_bound
Values bound to the State, to be used by the VM.
Definition State.hpp:179
void configure(const BytecodeReader &bcr)
Called to configure the state (set the bytecode, debug level, call the compiler......
Definition State.cpp:172
bool doFile(const std::string &file_path, uint16_t features=DefaultFeatures, std::ostream *stream=nullptr)
Compile a file, and use the resulting bytecode.
Definition State.cpp:87
bytecode_t m_bytecode
Definition State.hpp:165
std::string m_filename
Definition State.hpp:167
std::vector< Value > m_constants
Definition State.hpp:171
bool compile(const std::string &file, const std::string &output, std::ostream *stream=nullptr)
Reads and compiles code of file.
Definition State.cpp:64
static void throwStateError(const std::string &message)
Definition State.hpp:157
std::vector< internal::InstLoc > m_inst_locations
Definition State.hpp:173
bool doString(const std::string &code, uint16_t features=DefaultFeatures, std::ostream *stream=nullptr)
Compile a string (representing ArkScript code) and store resulting bytecode in m_bytecode.
Definition State.cpp:129
std::vector< std::string > m_filenames
Definition State.hpp:172
static std::size_t maxPageSize(const std::vector< bytecode_t > &pages)
Compute the maximum length of the given code pages.
Definition State.cpp:242
void reset() noexcept
Reset State (all member variables related to execution)
Definition State.cpp:217
bool feed(const std::string &bytecode_filename, bool fail_with_exception=false)
Feed the state by giving it the path to an existing bytecode file.
Definition State.cpp:32
void loadFunction(const std::string &name, Procedure::CallbackType &&function) noexcept
Register a function in the virtual machine.
Definition State.cpp:147
std::vector< std::string > m_symbols
Definition State.hpp:170
void addPagesToContiguousBytecode(const std::vector< bytecode_t > &pages, std::size_t start)
Definition State.cpp:233
bytecode_t m_code
Definition State.hpp:176
std::size_t m_max_page_size
Definition State.hpp:175
void setArgs(const std::vector< std::string > &args) noexcept
Set the script arguments in sys:args.
Definition State.cpp:152
std::vector< bytecode_t > m_pages
Definition State.hpp:174
unsigned m_debug_level
Definition State.hpp:162
State(const std::vector< std::filesystem::path > &libenv={}) noexcept
Construct a new State object.
Definition State.cpp:19
void setDebug(unsigned level) noexcept
Set the debug level.
Definition State.cpp:162
void extendBytecode(const std::vector< bytecode_t > &pages, const std::vector< std::string > &symbols, const std::vector< Value > &constants)
Used by the debugger to add code to the VM at runtime.
Definition State.cpp:247
List_t & list()
Definition Value.hpp:172
The welder joins all the compiler passes.
Definition Welder.hpp:40
void registerSymbol(const std::string &name)
Register a symbol as a global in the compiler.
Definition Welder.cpp:35
bool computeASTFromString(const std::string &code)
Definition Welder.cpp:48
const bytecode_t & bytecode() const noexcept
Definition Welder.cpp:170
void redirectLogsTo(std::ostream &os)
Redirect the logs to a given stream.
Definition Welder.cpp:145
bool saveBytecodeToFile(const std::string &filename)
Save the generated bytecode to a given file.
Definition Welder.cpp:130
bool generateBytecode()
Compile the AST processed by computeASTFromFile / computeASTFromString.
Definition Welder.cpp:63
bool computeASTFromFile(const std::string &filename)
Definition Welder.cpp:40
bool fileExists(const std::string &name) noexcept
Checks if a file exists.
Definition Files.hpp:28
std::vector< uint8_t > readFileAsBytes(const std::string &name)
Helper to read the bytes of a file.
Definition Files.hpp:62
constexpr std::string_view SysArgs
Definition Common.hpp:134
constexpr std::string_view SysProgramName
Definition Common.hpp:135
constexpr std::size_t HeaderSize
Definition Common.hpp:39
constexpr uint16_t DisableCache
Definition Constants.hpp:67
std::vector< uint8_t > bytecode_t
Definition Common.hpp:22