refactor(furvm): improve type system

Closes: #52
This commit is contained in:
2026-07-11 00:45:09 +02:00
parent abbc1714c1
commit 3c0588e8db
13 changed files with 438 additions and 426 deletions
+3 -1
View File
@@ -31,7 +31,9 @@ Checks: >
-cppcoreguidelines-non-private-member-variables-in-classes, -cppcoreguidelines-non-private-member-variables-in-classes,
-cppcoreguidelines-pro-bounds-avoid-unchecked-container-access, -cppcoreguidelines-pro-bounds-avoid-unchecked-container-access,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay, -cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-bugprone-forward-declaration-namespace -cppcoreguidelines-use-enum-class,
-bugprone-forward-declaration-namespace,
-bugprone-tagged-union-member-count
WarningsAsErrors: "*" WarningsAsErrors: "*"
+5 -1
View File
@@ -21,7 +21,8 @@ public:
/** /**
* @brief Constructs a context. * @brief Constructs a context.
*/ */
context(); context()
: m_thingAllocator(m_thingArena) {}
~context() = default; ~context() = default;
@@ -124,6 +125,8 @@ public:
* @return The thing allocator. * @return The thing allocator.
*/ */
thing_allocator<std::byte> thing_alloc() const { return m_thingAllocator; } thing_allocator<std::byte> thing_alloc() const { return m_thingAllocator; }
thing_type_store& thing_type_store() { return m_thingTypeStore; }
private: private:
handle_container<mod_h> m_modules; handle_container<mod_h> m_modules;
handle_container<thing_h> m_things; handle_container<thing_h> m_things;
@@ -131,6 +134,7 @@ private:
furlang::arena m_thingArena; furlang::arena m_thingArena;
thing_allocator<std::byte> m_thingAllocator; thing_allocator<std::byte> m_thingAllocator;
class thing_type_store m_thingTypeStore;
}; };
} // namespace furvm } // namespace furvm
+4
View File
@@ -164,6 +164,10 @@ public:
* @brief Executes next instruction. * @brief Executes next instruction.
*/ */
void step(); void step();
private:
thing_type thing_type_impl(mod_h mod, mod_type type) const;
thing_type* thing_type(const mod_h& mod, const mod_type& type) const;
private: private:
executor_flags m_flags{}; // NOLINT(bugprone-invalid-enum-default-initialization) executor_flags m_flags{}; // NOLINT(bugprone-invalid-enum-default-initialization)
context_p m_context; context_p m_context;
+2 -4
View File
@@ -37,7 +37,7 @@ struct import_function {
* @brief Function signature. * @brief Function signature.
*/ */
struct function_sig { struct function_sig {
std::vector<type_h> params; std::vector<mod_type_h> params;
bool operator==(const function_sig& rhs) const { return params == rhs.params; } bool operator==(const function_sig& rhs) const { return params == rhs.params; }
@@ -190,9 +190,7 @@ private:
namespace detail { namespace detail {
struct function_sig_hash { struct function_sig_hash {
std::size_t operator()(const function_sig& signature) const { std::size_t operator()(const function_sig& signature) const;
return furlang::utility::vector_hash<type_h, detail::handle_hash<type_h>>{}(signature.params);
}
}; };
} // namespace detail } // namespace detail
+12 -20
View File
@@ -115,6 +115,12 @@ using function_h = handle<function, refcount_header<function_id>>;
// module.hpp // module.hpp
struct mod_type;
using mod_type_id = std::uint32_t;
using mod_type_h = handle<mod_type, generic_header<mod_type_id>>;
/** /**
* @class mod * @class mod
* @brief Module. * @brief Module.
@@ -138,34 +144,20 @@ using mod_id = std::string;
*/ */
using mod_h = handle<mod, refcount_header<mod_id>>; using mod_h = handle<mod, refcount_header<mod_id>>;
// thing_allocator.hpp
template <typename T>
class thing_allocator;
// thing.hpp // thing.hpp
/**
* @enum type_t
* @brief Type of the thing's type.
*/
enum class type_t : std::uint32_t;
/**
* @struct type
* @brief Thing type.
*/
struct type;
using type_p = std::shared_ptr<type>;
using type_id = std::uint32_t;
using type_h = handle<type_p, generic_header<type_id>>;
/** /**
* @class bad_thing_access * @class bad_thing_access
* @brief Bad thing access exception. * @brief Bad thing access exception.
*/ */
class bad_thing_access; class bad_thing_access;
template <typename T> using thing_type_id = std::uint32_t;
class thing_allocator;
/** /**
* @class thing * @class thing
+121 -3
View File
@@ -5,7 +5,6 @@
#include "furvm/function.hpp" #include "furvm/function.hpp"
#include "furvm/fwd.hpp" #include "furvm/fwd.hpp"
#include "furvm/handle.hpp" #include "furvm/handle.hpp"
#include "furvm/type.hpp" // IWYU pragma: keep
#include <functional> #include <functional>
#include <istream> #include <istream>
@@ -18,6 +17,125 @@
namespace furvm { namespace furvm {
struct mod_type {
using primitive = std::uint64_t;
struct array {
mod_type_id typeId;
std::size_t size;
};
struct imprt {
mod_id modId;
mod_type_id typeId;
};
enum type {
Primitive = 0,
Array,
Import,
Count,
} type;
union value {
std::nullptr_t null = nullptr;
primitive primitive;
array array;
imprt imprt;
value() = default;
value(std::uint64_t primitive)
: primitive(primitive) {}
value(mod_type_id id, std::size_t size)
: array({}) {
array.typeId = id;
array.size = size;
}
template <typename ModIdFwd, typename = std::enable_if_t<std::is_constructible_v<mod_id, ModIdFwd>>>
value(ModIdFwd&& modId, mod_type_id typeId)
: imprt({}) {
imprt.modId = std::forward<ModIdFwd>(modId);
imprt.typeId = typeId;
}
~value() {}
value(value&& other) = delete;
value& operator=(value&& other) = delete;
value(const value& other) = delete;
value& operator=(const value& other) = delete;
} value;
mod_type(primitive primitive)
: type(Primitive), value(primitive) {}
mod_type(mod_type_id id, std::size_t size)
: type(Array), value(id, size) {}
template <typename ModIdFwd, typename = std::enable_if_t<std::is_constructible_v<mod_id, ModIdFwd>>>
mod_type(ModIdFwd&& modId, mod_type_id typeId)
: type(Import), value(std::forward<ModIdFwd>(modId), typeId) {}
~mod_type() {
switch (type) {
case Array: value.array.~array(); break;
case Import: value.imprt.~imprt(); break;
case Primitive:
case Count:
default: break;
}
}
mod_type(mod_type&& other) noexcept
: type(other.type) {
switch (type) {
case Primitive: new (&value.primitive) primitive(other.value.primitive); break;
case Array: new (&value.array) array(other.value.array); break;
case Import: new (&value.imprt) imprt(std::move(other.value.imprt)); break;
case Count: break;
}
other.type = Count;
}
mod_type& operator=(mod_type&& other) noexcept {
if (this == &other) return *this;
type = other.type;
switch (type) {
case Primitive: new (&value.primitive) primitive(other.value.primitive); break;
case Array: new (&value.array) array(other.value.array); break;
case Import: new (&value.imprt) imprt(std::move(other.value.imprt)); break;
case Count: break;
}
other.type = Count;
return *this;
}
mod_type(const mod_type& other)
: type(other.type) {
switch (type) {
case Primitive: new (&value.primitive) primitive(other.value.primitive); break;
case Array: new (&value.array) array(other.value.array); break;
case Import: new (&value.imprt) imprt(other.value.imprt); break;
case Count: break;
}
}
mod_type& operator=(const mod_type& other) {
if (this == &other) return *this;
type = other.type;
switch (type) {
case Primitive: new (&value.primitive) primitive(other.value.primitive); break;
case Array: new (&value.array) array(other.value.array); break;
case Import: new (&value.imprt) imprt(other.value.imprt); break;
case Count: break;
}
return *this;
}
};
class mod { class mod {
friend class function; friend class function;
friend class serializer; friend class serializer;
@@ -181,7 +299,7 @@ public:
*/ */
template <typename... Args> template <typename... Args>
auto emplace_type(Args&&... args) { auto emplace_type(Args&&... args) {
if constexpr (std::is_constructible_v<type_p, Args...>) { if constexpr (std::is_constructible_v<mod_type, Args...>) {
return m_types.emplace_back(std::forward<Args>(args)...); return m_types.emplace_back(std::forward<Args>(args)...);
} else { } else {
return m_types.emplace(std::forward<Args>(args)...); return m_types.emplace(std::forward<Args>(args)...);
@@ -245,7 +363,7 @@ private:
std::unordered_map<function_id, pair_type> m_functionMap; std::unordered_map<function_id, pair_type> m_functionMap;
handle_container<function_h> m_functions; handle_container<function_h> m_functions;
handle_container<type_h> m_types; handle_container<mod_type_h> m_types;
std::unordered_map<std::string, native_function> m_nativeFunctions; std::unordered_map<std::string, native_function> m_nativeFunctions;
}; };
+193 -124
View File
@@ -1,38 +1,142 @@
#ifndef FURVM_THING_HPP #ifndef FURVM_THING_HPP
#define FURVM_THING_HPP #define FURVM_THING_HPP
#include "furlang/arena.hpp"
#include "furlang/utility/hash.hpp"
#include "furvm/exceptions.hpp" #include "furvm/exceptions.hpp"
#include "furvm/fwd.hpp" #include "furvm/fwd.hpp"
#include "furvm/module.hpp" #include "furvm/thing_allocator.hpp" // IWYU pragma: keep
#include "furvm/type.hpp"
#include <algorithm> #include <algorithm>
#include <cstddef> #include <cstddef>
#include <cstring> #include <cstring>
#include <functional> #include <functional>
#include <memory> #include <limits>
#include <new> #include <new>
#include <stdexcept> #include <stdexcept>
#include <unordered_map>
#include <utility> #include <utility>
namespace furvm { namespace furvm {
struct thing_type {
using primitive = std::uint64_t;
struct array {
thing_type* type;
std::size_t size;
};
enum type { // NOLINT
Primitive = 0,
Array,
Count,
} type;
union value {
primitive primitive;
array array;
value(std::uint64_t primitive)
: primitive(primitive) {}
value(thing_type* type, std::size_t size)
: array({}) {
array.type = type;
array.size = size;
}
} value;
static constexpr thing_type_id INVALID_ID = std::numeric_limits<thing_type_id>::max();
thing_type_id id = INVALID_ID;
bool operator==(const thing_type& other) const {
if (type != other.type) return false;
switch (type) {
case Primitive: return value.primitive == other.value.primitive;
case Array: return *value.array.type == *other.value.array.type && value.array.size == other.value.array.size;
case Count: break;
}
return false;
}
bool operator!=(const thing_type& other) const { return !this->operator==(other); }
};
namespace detail {
struct thing_type_hash {
std::size_t operator()(const thing_type& type) const {
std::size_t seed = std::hash<decltype(type.type)>{}(type.type);
switch (type.type) {
case thing_type::Primitive:
seed =
furlang::utility::hash_combine(seed, std::hash<decltype(type.value.primitive)>{}(type.value.primitive));
return seed;
case thing_type::Array:
seed = furlang::utility::hash_combine(seed, thing_type_hash{}(*type.value.array.type));
seed = furlang::utility::hash_combine(seed,
std::hash<decltype(type.value.array.size)>{}(type.value.array.size));
return seed;
case thing_type::Count: break;
}
throw std::runtime_error("unreachable");
}
};
} // namespace detail
class thing_type_store {
public:
thing_type* insert(thing_type& type) {
if (auto it = m_typeMap.find(type); it != m_typeMap.end()) return m_map[type.id = it->second];
if (type.id == thing_type::INVALID_ID) type.id = m_counter++;
thing_type* ptr = m_arena.allocate<thing_type>(type);
m_map[type.id] = ptr;
m_typeMap[type] = type.id;
return ptr;
}
thing_type* at(thing_type_id id) const {
if (auto it = m_map.find(id); it != m_map.end()) return it->second;
return nullptr;
}
private:
furlang::arena m_arena;
std::unordered_map<thing_type_id, thing_type*> m_map;
std::unordered_map<thing_type, thing_type_id, detail::thing_type_hash> m_typeMap;
thing_type_id m_counter = 0;
};
template <template <typename> typename Allocator> template <template <typename> typename Allocator>
class thing final { class thing final {
friend class executor; friend class executor;
public: public:
using allocator_type = Allocator<std::byte>; /**< Allocator type. */ using allocator_type = Allocator<std::byte>; /**< Allocator type. */
public:
using s8 = std::int8_t;
using s16 = std::int16_t;
using s32 = std::int32_t;
using s64 = std::int64_t;
using mod_container = std::shared_ptr<handle_container<mod_h>>; union array {
std::byte flat[];
struct {
std::size_t size;
std::byte* data;
} dynamic;
};
public: public:
/** /**
* @brief Constructs a thing. * @brief Constructs a thing.
* *
* @param type Thing type reference. * @param type Thing type.
* @param allocator Allocator for the thing's data. * @param allocator Allocator for the thing's data.
*/ */
thing(const type_ref& type, const mod_container& modules = nullptr, const allocator_type& allocator = {}) thing(const thing_type& type, const allocator_type& allocator = {})
: m_type(type), m_size(compute_size(resolve_type(type, modules))), m_modules(modules), m_allocator(allocator) { : m_type(type), m_size(compute_size(type)), m_allocator(allocator) {
// TODO: Account for alignment // TODO: Account for alignment
m_data = m_allocator.allocate(m_size); m_data = m_allocator.allocate(m_size);
std::memset(m_data, 0, m_size); std::memset(m_data, 0, m_size);
@@ -49,14 +153,10 @@ public:
* @brief Move constructor. * @brief Move constructor.
*/ */
thing(thing&& other) noexcept thing(thing&& other) noexcept
: m_type(std::move(other.m_type)), : m_type(other.m_type), m_data(other.m_data), m_size(other.m_size), m_allocator(std::move(other.m_allocator)) {
m_data(other.m_data), other.m_type.type = thing_type::Count;
m_size(other.m_size), other.m_data = nullptr;
m_modules(std::move(other.m_modules)), other.m_size = 0;
m_allocator(std::move(other.m_allocator)) {
other.m_type = {};
other.m_data = nullptr;
other.m_size = 0;
} }
/** /**
@@ -64,20 +164,17 @@ public:
*/ */
thing& operator=(thing&& other) noexcept { thing& operator=(thing&& other) noexcept {
if (this == &other) return *this; if (this == &other) return *this;
m_type = other.m_type; m_type = other.m_type;
m_data = other.m_data; m_data = other.m_data;
m_modules = std::move(other.m_modules); m_allocator = std::move(other.m_allocator);
m_allocator = std::move(other.m_allocator); other.m_type.type = thing_type::Count;
other.m_type = {}; other.m_data = nullptr;
other.m_data = nullptr; other.m_size = 0;
other.m_size = 0;
return *this; return *this;
} }
thing(const thing&) = delete; thing(const thing&) = delete;
thing& operator=(const thing&) = delete; thing& operator=(const thing&) = delete;
public:
void assign_mod_container(const mod_container& modules) { m_modules = modules; }
public: public:
/** /**
* @brief Returns a clone of the thing. * @brief Returns a clone of the thing.
@@ -85,30 +182,17 @@ public:
* @return A clone of this thing. * @return A clone of this thing.
*/ */
thing clone() const { thing clone() const {
auto type = resolve_type(m_type, m_modules); if (m_size == 0) return reference();
if (m_size == 0) {
return reference();
}
thing res(type, m_modules, m_allocator); thing res(m_type, m_allocator);
switch (type->t) { switch (m_type.type) {
case type_t::Primitive: case thing_type::Primitive: std::memcpy(res.m_data, m_data, m_size); return std::move(res);
case type_t::Array: { case thing_type::Array: copy_list(m_type, res.get<array>(), get<array>()); return std::move(res);
copy_list(*type.type, res.get<array_t>(), get<array_t>()); case thing_type::Count: break;
} break;
case type_t::Import:
default: throw std::runtime_error("unreachable");
} }
return std::move(res); throw std::runtime_error("unreachable");
} }
public: public:
/**
* @brief Returns the thing's type reference.
*
* @return The type reference.
*/
auto type() { return m_type; }
/** /**
* @brief Returns the thing's type reference. * @brief Returns the thing's type reference.
* *
@@ -137,7 +221,7 @@ public:
*/ */
template <typename T> template <typename T>
T& get() { T& get() {
std::size_t size = m_size > 0 ? m_size : compute_size_na(resolve_type(m_type, m_modules)); std::size_t size = m_size > 0 ? m_size : compute_size_na(m_type);
if (size != sizeof(T)) throw bad_thing_access(); if (size != sizeof(T)) throw bad_thing_access();
return *std::launder(reinterpret_cast<T*>(m_data)); return *std::launder(reinterpret_cast<T*>(m_data));
} }
@@ -149,7 +233,7 @@ public:
*/ */
template <typename T> template <typename T>
const T& get() const { const T& get() const {
std::size_t size = m_size > 0 ? m_size : compute_size_na(resolve_type(m_type, m_modules)); std::size_t size = m_size > 0 ? m_size : compute_size_na(m_type);
if (size != sizeof(T)) throw bad_thing_access(); if (size != sizeof(T)) throw bad_thing_access();
return *std::launder(reinterpret_cast<const T*>(m_data)); return *std::launder(reinterpret_cast<const T*>(m_data));
} }
@@ -247,79 +331,68 @@ public:
* *
* @return The integer value. * @return The integer value.
*/ */
long_t integer() const { s64 integer() const {
if (m_type->t != type_t::Primitive) throw bad_thing_access(); if (m_type.type != thing_type::Primitive) throw bad_thing_access();
switch (m_type->primitive) { switch (m_type.value.primitive) {
case sizeof(byte_t): return get<byte_t>(); case sizeof(s8): return get<s8>();
case sizeof(short_t): return get<short_t>(); case sizeof(s16): return get<s16>();
case sizeof(int_t): return get<int_t>(); case sizeof(s32): return get<s32>();
case sizeof(long_t): return get<long_t>(); case sizeof(s64): return get<s64>();
default: throw std::runtime_error("unreachable"); default: throw std::runtime_error("unreachable");
} }
} }
thing reference() const { return { m_type, m_data, m_modules, m_allocator }; } thing reference() const { return { m_type, m_data, m_allocator }; }
constexpr bool is_reference() const { return m_size == 0; } constexpr bool is_reference() const { return m_size == 0; }
void resize(long_t newSize) { void resize(s64 newSize) {
if (m_type->t != type_t::Array) throw bad_thing_access(); if (m_type.type != thing_type::Array) throw bad_thing_access();
if (m_type->array.size > 0) throw std::runtime_error("cannot resize a static array"); if (m_type.value.array.size > 0) throw std::runtime_error("cannot resize a static array");
auto& array = get<array_t>(); auto& array = get<union array>();
if (newSize < 0 || newSize == array.dynamic.size) return; if (newSize < 0 || newSize == array.dynamic.size) return;
std::size_t innerSize = compute_size_na(*m_type->array.type); std::size_t innerSize = compute_size_na(*m_type.value.array.type);
std::byte* newData = new std::byte[innerSize * newSize]; std::byte* newData = new std::byte[innerSize * newSize];
std::memcpy(newData, array.dynamic.data, innerSize * std::min(array.dynamic.size, newSize)); std::memcpy(newData,
array.dynamic.data,
innerSize * std::min(static_cast<std::int64_t>(array.dynamic.size), newSize));
array.dynamic.size = newSize; array.dynamic.size = newSize;
delete[] array.dynamic.data; delete[] array.dynamic.data;
array.dynamic.data = newData; array.dynamic.data = newData;
} }
thing at(long_t index) const { thing at(s64 index) const {
if (m_type->t != type_t::Array) throw bad_thing_access(); if (m_type.type != thing_type::Array) throw bad_thing_access();
std::size_t elementSize = compute_size_na(*m_type->array.type); std::size_t elementSize = compute_size_na(*m_type.value.array.type);
if (m_type->array.size == 0) { if (m_type.value.array.size == 0) {
auto& array = get<array_t>(); auto& array = get<union array>();
if (index < 0 || index >= array.dynamic.size) throw std::out_of_range("index out of range"); if (index < 0 || index >= array.dynamic.size) throw std::out_of_range("index out of range");
return { { m_type.mod, m_type->array.type }, return { *m_type.value.array.type, array.dynamic.data + (index * elementSize), m_allocator };
array.dynamic.data + (index * elementSize),
m_modules,
m_allocator };
} }
std::byte* data = reinterpret_cast<array_t*>(m_data)->data; std::byte* data = reinterpret_cast<array*>(m_data)->flat;
if (index < 0 || index >= m_type->array.size) throw std::out_of_range("index out of range"); if (index < 0 || index >= m_type.value.array.size) throw std::out_of_range("index out of range");
return { { m_type.mod, m_type->array.type }, data + (index * elementSize), m_modules, m_allocator }; return { *m_type.value.array.type, data + (index * elementSize), m_allocator };
} }
std::size_t size() const { std::size_t size() const {
if (m_type->t != type_t::Array) throw std::runtime_error("not an array"); if (m_type.type != thing_type::Array) throw bad_thing_access();
if (m_type->array.size == 0) return get<array_t>().dynamic.size; return m_type.value.array.size == 0 ? get<array>().dynamic.size : m_type.value.array.size;
return m_type->array.size;
}
public:
static type_ref resolve_type(const type_ref& initType, const mod_container& modules) {
type_ref rsv = initType;
while (rsv->t == type_t::Import) {
auto mod = modules->at(initType->imp.mod);
rsv = type_ref{ mod, mod->type_at(initType->imp.type) };
}
return rsv;
} }
private: private:
static void copy_list(const type_p& arrayType, array_t& dst, const array_t& src) { static void copy_list(const thing_type& arrayType, array& dst, const array& src) {
if (arrayType == nullptr || arrayType->t != type_t::Array || *arrayType->array.type == nullptr) if (arrayType.type != thing_type::Array || arrayType.value.array.type == nullptr)
throw std::runtime_error("invalid type"); throw std::runtime_error("invalid type");
auto innerType = *arrayType->array.type; const auto& innerType = *arrayType.value.array.type;
std::size_t elementSize = compute_size_na(innerType); std::size_t elementSize = compute_size_na(innerType);
std::byte* data = nullptr; std::byte* data = nullptr;
const std::byte* srcData = nullptr; const std::byte* srcData = nullptr;
std::size_t size = 0; std::size_t size = 0;
if (arrayType->array.size == 0) { if (arrayType.value.array.size == 0) {
size = dst.dynamic.size = src.dynamic.size; size = dst.dynamic.size = src.dynamic.size;
if (dst.dynamic.size < 0) { if (dst.dynamic.size < 0) {
dst.dynamic.data = nullptr; dst.dynamic.data = nullptr;
@@ -329,60 +402,57 @@ private:
srcData = src.dynamic.data; srcData = src.dynamic.data;
data = dst.dynamic.data = new std::byte[dst.dynamic.size]; data = dst.dynamic.data = new std::byte[dst.dynamic.size];
} else { } else {
data = dst.data; data = dst.flat;
srcData = src.data; srcData = src.flat;
size = arrayType->array.size; size = arrayType.value.array.size;
} }
switch (innerType->t) { switch (innerType.type) {
case type_t::Primitive: std::memcpy(dst.data, src.data, size); break; case thing_type::Primitive: std::memcpy(dst.flat, src.flat, size); return;
case type_t::Array: case thing_type::Array:
for (std::size_t i = 0; i < size; ++i) { for (std::size_t i = 0; i < size; ++i) {
copy_list(*innerType->array.type, copy_list(*innerType.value.array.type,
*std::launder(reinterpret_cast<array_t*>(data + (i * elementSize))), *std::launder(reinterpret_cast<array*>(data + (i * elementSize))),
*std::launder(reinterpret_cast<const array_t*>(srcData + (i * elementSize)))); *std::launder(reinterpret_cast<const array*>(srcData + (i * elementSize))));
} }
break; return;
case type_t::Import: throw std::runtime_error("unresolved type"); case thing_type::Count: break;
} }
throw std::runtime_error("unreachable");
} }
private: private:
static std::size_t compute_size_na(const type_p& type) { static std::size_t compute_size_na(const thing_type& type) {
switch (type->t) { switch (type.type) {
case type_t::Primitive: return type->primitive; case thing_type::Primitive: return type.value.primitive;
case type_t::Array: { case thing_type::Array:
if (type->array.size == 0) return sizeof(array_t); return type.value.array.size == 0 ? sizeof(array)
return compute_size_na(*type->array.type) * type->array.size; : compute_size_na(*type.value.array.type) * type.value.array.size;
} case thing_type::Count: break;
case type_t::Import: throw std::runtime_error("unresolved type");
} }
throw std::runtime_error("unreachable"); throw std::runtime_error("unreachable");
} }
static std::size_t compute_size_na(const type_ref& type) { return compute_size_na(*type.type); }
// NOTE: Align to 4 bytes // NOTE: Align to 4 bytes
static std::size_t compute_size(const type_p& type) { return (compute_size_na(type) + 3) & ~3; } static std::size_t compute_size(const thing_type& type) { return (compute_size_na(type) + 3) & ~3; }
static std::size_t compute_size(const type_ref& type) { return compute_size(*type.type); }
private: private:
thing(const type_ref& type, std::byte* data, const mod_container& modules, const allocator_type& allocator = {}) thing(const thing_type& type, std::byte* data, const allocator_type& allocator = {})
: m_type(type), m_size(0), m_data(data), m_modules(modules), m_allocator(allocator) {} : m_type(type), m_size(0), m_data(data), m_allocator(allocator) {}
private: private:
template <typename Op> template <typename Op>
thing binary_op(const thing& rhs, const Op& op) const { thing binary_op(const thing& rhs, const Op& op) const {
if (m_type->t == type_t::Primitive && rhs.type()->t == type_t::Primitive) { if (m_type.type == thing_type::Primitive && rhs.m_type.type == thing_type::Primitive) {
type_ref type = m_type->primitive >= rhs.type()->primitive ? m_type : rhs.type(); thing_type resultType = m_type.value.primitive >= rhs.m_type.value.primitive ? m_type : rhs.m_type;
std::size_t size = std::max(m_type->primitive, rhs.type()->primitive); std::size_t size = std::max(m_type.value.primitive, rhs.m_type.value.primitive);
long_t result = op(integer(), rhs.integer()); s64 result = op(integer(), rhs.integer());
thing res(type, m_modules, m_allocator); thing res(resultType, m_allocator);
switch (size) { switch (size) {
case sizeof(byte_t): res.get<byte_t>() = result; break; case sizeof(s8): res.get<s8>() = result; break;
case sizeof(short_t): res.get<short_t>() = result; break; case sizeof(s16): res.get<s16>() = result; break;
case sizeof(int_t): res.get<int_t>() = result; break; case sizeof(s32): res.get<s32>() = result; break;
case sizeof(long_t): res.get<long_t>() = result; break; case sizeof(s64): res.get<s64>() = result; break;
default: throw std::runtime_error("unreachable"); default: throw std::runtime_error("unreachable");
} }
return std::move(res); return std::move(res);
@@ -391,11 +461,10 @@ private:
throw std::runtime_error("unexpected operation"); throw std::runtime_error("unexpected operation");
} }
private: private:
type_ref m_type; thing_type m_type;
std::size_t m_size; std::size_t m_size;
std::byte* m_data; std::byte* m_data;
mod_container m_modules;
allocator_type m_allocator; allocator_type m_allocator;
}; };
-181
View File
@@ -1,181 +0,0 @@
#ifndef FURVM_TYPE_HPP
#define FURVM_TYPE_HPP
#include "furvm/fwd.hpp"
#include "furvm/handle.hpp" // IWYU pragma: keep
#include <cstdint>
#include <stdexcept>
namespace furvm {
enum class type_t : std::uint32_t {
Primitive = 0,
Array,
Import,
};
using primitive_type = std::uint64_t;
/**
* @brief Array type.
*/
struct array_type {
type_h type; /**< Type of the array's elements. */
/**
* @brief Size of the array.
*
* Size of the array. If size is equal to zero, then the array becomes dynamic.
*/
std::size_t size;
bool operator==(const array_type& rhs) const { return type == rhs.type && size == rhs.size; }
bool operator!=(const array_type& rhs) const { return !this->operator==(rhs); }
};
struct import_type {
mod_id mod;
type_id type;
bool operator==(const import_type& rhs) const { return mod == rhs.mod && type == rhs.type; }
bool operator!=(const import_type& rhs) const { return !this->operator==(rhs); }
};
struct type {
type_t t;
union {
primitive_type primitive{};
array_type array;
import_type imp;
};
type(type_t type)
: t(type) {}
type(primitive_type primitive)
: t(type_t::Primitive), primitive(primitive) {}
type(const type_h& type, std::size_t size = 0)
: t(type_t::Array), array(array_type{ type, size }) {}
type(const array_type& list)
: t(type_t::Array), array(list) {}
type(const import_type& imp)
: t(type_t::Import), imp(imp) {}
~type() {
switch (t) {
case type_t::Array: array.~array_type(); break;
case type_t::Import: imp.~import_type(); break;
default: break;
}
}
type(type&& other) noexcept
: t(other.t) {
switch (t) {
case type_t::Primitive: primitive = other.primitive; break;
case type_t::Array: array = std::move(other.array); break;
case type_t::Import: imp = std::move(other.imp); break;
}
}
type& operator=(type&& other) noexcept {
if (this == &other) return *this;
t = other.t;
switch (t) {
case type_t::Primitive: primitive = other.primitive; break;
case type_t::Array: array = std::move(other.array); break;
case type_t::Import: imp = std::move(other.imp); break;
}
return *this;
}
type(const type& other)
: t(other.t) {
switch (t) {
case type_t::Primitive: primitive = other.primitive; break;
case type_t::Array: array = other.array; break;
case type_t::Import: imp = other.imp; break;
}
}
type& operator=(const type& other) {
if (this == &other) return *this;
t = other.t;
switch (t) {
case type_t::Primitive: primitive = other.primitive; break;
case type_t::Array: array = other.array; break;
case type_t::Import: imp = other.imp; break;
}
return *this;
}
bool operator==(const type& rhs) const {
if (t != rhs.t) return false;
switch (t) {
case type_t::Primitive: return primitive == rhs.primitive;
case type_t::Array: return array == rhs.array;
case type_t::Import: return imp == rhs.imp;
}
throw std::runtime_error("unreachable");
}
bool operator!=(const type& rhs) const { return !this->operator==(rhs); }
};
using byte_t = std::int8_t; /**< A 1-byte integer. */
using short_t = std::int16_t; /**< A 2-byte integer. */
using int_t = std::int32_t; /**< A 4-byte integer. */
using long_t = std::int64_t; /**< An 8-byte integer. */
/**
* @brief Array type's data layout.
*/
union array_t {
std::byte data[]; /**< Static array's elements' data. */
struct {
long_t size; /**< Size of the array (in items). */
std::byte* data; /**< Pointer to dynamic array's elements' data array. */
} dynamic; /**< Dynamic array's info. */
};
/**
* @brief A 1-byte integer thing type.
*/
inline static type byteType = { sizeof(byte_t) }; // NOLINT
/**
* @brief A 2-byte integer thing type.
*/
inline static type shortType = { sizeof(short_t) }; // NOLINT
/**
* @brief A 4-byte integer thing type.
*/
inline static type intType = { sizeof(int_t) }; // NOLINT
/**
* @brief An 8-byte integer thing type.
*/
inline static type longType = { sizeof(long_t) }; // NOLINT
/**
* @brief Reference to a type.
*/
struct type_ref {
mod_h mod;
type_h type;
class type* operator->() { return &**type; }
const class type* operator->() const { return &**type; }
};
} // namespace furvm
#endif // FURVM_TYPE_HPP
-24
View File
@@ -1,24 +0,0 @@
#include "furvm/context.hpp"
#include "furvm/thing.hpp" // IWYU pragma: keep
#include "furvm/type.hpp"
#include <cstdint>
#include <memory>
namespace furvm {
context::context()
: m_thingAllocator(m_thingArena) {
mod core;
core.emplace_type(std::make_shared<type>(byteType));
core.emplace_type(std::make_shared<type>(shortType));
core.emplace_type(std::make_shared<type>(intType));
core.emplace_type(std::make_shared<type>(longType));
static_assert(sizeof(std::uintptr_t) == 8, "Unsupported platform");
core.emplace_type(*core.type_at(3));
emplace("core", std::move(core)).dispatch();
}
} // namespace furvm
+55 -34
View File
@@ -6,14 +6,35 @@
#include "furvm/fwd.hpp" #include "furvm/fwd.hpp"
#include "furvm/instruction.hpp" #include "furvm/instruction.hpp"
#include "furvm/thing.hpp" #include "furvm/thing.hpp"
#include "furvm/type.hpp"
#include <cassert>
#include <cstdint> #include <cstdint>
#include <stdexcept> #include <stdexcept>
#include <vector> #include <vector>
namespace furvm { namespace furvm {
thing_type executor::thing_type_impl(mod_h mod, mod_type type) const {
while (type.type == mod_type::Import) {
auto imprt = std::move(type.value.imprt);
mod = m_context->at(imprt.modId);
type = *mod->type_at(imprt.typeId);
}
switch (static_cast<enum thing_type::type>(type.type)) {
case thing_type::Primitive: return { static_cast<enum thing_type::type>(type.type), type.value.primitive };
case thing_type::Array: {
return { static_cast<enum thing_type::type>(type.type),
{ thing_type(mod, *mod->type_at(type.value.array.typeId)), type.value.array.size } };
}
default: throw std::runtime_error("invalid thing type");
}
}
thing_type* executor::thing_type(const mod_h& mod, const mod_type& type) const {
struct thing_type thingType = thing_type_impl(mod, type);
return m_context->thing_type_store().insert(thingType);
}
void executor::push_frame(const mod_h& mod, function function) { void executor::push_frame(const mod_h& mod, function function) {
mod_h modInst = mod; mod_h modInst = mod;
while (function.type() == function_t::Import) { while (function.type() == function_t::Import) {
@@ -26,7 +47,7 @@ void executor::push_frame(const mod_h& mod, function function) {
args.reserve(signature.params.size()); args.reserve(signature.params.size());
for (const auto& param : signature.params) { for (const auto& param : signature.params) {
auto arg = pop_thing(); auto arg = pop_thing();
if (arg->type().type != param) throw std::runtime_error("function argument type mismatch"); if (arg->type() != *thing_type(mod, *param)) throw std::runtime_error("function argument type mismatch");
args.push_back(std::move(arg)); args.push_back(std::move(arg));
} }
@@ -87,10 +108,6 @@ thing_h executor::load_thing(variable_t variable) const {
return frame.variables[variable]; return frame.variables[variable];
} }
static type_ref get_type_ref(const mod_h& mod, type_id id) {
return { mod, mod->type_at(id) };
}
void executor::step() { void executor::step() {
if ((m_flags & executor_flags::Suspended) == executor_flags::Suspended) return; if ((m_flags & executor_flags::Suspended) == executor_flags::Suspended) return;
@@ -100,25 +117,25 @@ void executor::step() {
switch (instr) { switch (instr) {
case instruction_t::NoOperation: break; case instruction_t::NoOperation: break;
case instruction_t::PushB2I: { case instruction_t::PushB2I: {
push_thing({ get_type_ref(m_context->at("core"), 2), m_context, m_context->thing_alloc() })->get<int_t>() = push_thing({ (struct thing_type){ thing_type::Primitive, { 4 } }, m_context->thing_alloc() })->get<int>() =
frame.mod->byte(frame.position++); frame.mod->byte(frame.position++);
} break; } break;
case instruction_t::Array: { case instruction_t::Array: {
type_id typeId = static_cast<type_id>(frame.mod->byte(frame.position)) | mod_type_id typeId = static_cast<mod_type_id>(frame.mod->byte(frame.position)) |
(static_cast<type_id>(frame.mod->byte(frame.position + 1)) << 8) | (static_cast<mod_type_id>(frame.mod->byte(frame.position + 1)) << 8) |
(static_cast<type_id>(frame.mod->byte(frame.position + 2)) << 16) | (static_cast<mod_type_id>(frame.mod->byte(frame.position + 2)) << 16) |
(static_cast<type_id>(frame.mod->byte(frame.position + 3)) << 24); (static_cast<mod_type_id>(frame.mod->byte(frame.position + 3)) << 24);
frame.position += 4; frame.position += 4;
auto type = furvm::thing<>::resolve_type(get_type_ref(frame.mod, typeId), m_context); const auto& type = *thing_type(frame.mod, *frame.mod->type_at(typeId));
if (*type.type == nullptr || type->t != type_t::Array || *type->array.type == nullptr) if (type.type != thing_type::Array || type.value.array.type == nullptr || type.value.array.type == &type)
throw std::runtime_error("invalid array type"); throw std::runtime_error("invalid array type");
auto array = push_thing({ type, m_context, m_context->thing_alloc() }); auto array = push_thing({ type, m_context->thing_alloc() });
if (type->array.size == 0) { if (type.value.array.size == 0) {
auto sizeThing = pop_thing(); auto sizeThing = pop_thing();
long_t size = sizeThing->integer(); std::int64_t size = sizeThing->integer();
array->resize(size); array->resize(size);
} }
@@ -199,27 +216,31 @@ void executor::step() {
} break; } break;
case instruction_t::Pointerof: { case instruction_t::Pointerof: {
auto thing = pop_thing(); auto thing = pop_thing();
auto ptr = push_thing({ get_type_ref(m_context->at("core"), 4), m_context, m_context->thing_alloc() }); auto ptr = push_thing(
switch (furvm::thing<>::resolve_type(thing->type(), m_context)->t) { { (struct thing_type){ thing_type::Primitive, { sizeof(std::uintptr_t) } }, m_context->thing_alloc() });
case type_t::Primitive: ptr->get<std::uintptr_t>() = reinterpret_cast<std::uintptr_t>(thing->raw()); break; switch (thing->type().type) {
case type_t::Array: case thing_type::Primitive: ptr->get<std::uintptr_t>() = reinterpret_cast<std::uintptr_t>(thing->raw()); break;
ptr->get<std::uintptr_t>() = reinterpret_cast<std::uintptr_t>(thing->get<array_t>().data); case thing_type::Array:
ptr->get<std::uintptr_t>() = reinterpret_cast<std::uintptr_t>(
thing->type().value.array.size == 0 ? thing->get<furvm::thing<>::array>().dynamic.data
: thing->get<furvm::thing<>::array>().flat);
break; break;
case type_t::Import: case thing_type::Count: throw std::runtime_error("unreachable");
default: throw std::runtime_error("unreachable");
} }
} break; } break;
case instruction_t::Sizeof: { case instruction_t::Sizeof: {
auto thing = pop_thing(); auto thing = pop_thing();
auto size = push_thing({ get_type_ref(m_context->at("core"), 3), m_context, m_context->thing_alloc() }); auto size = push_thing(
auto type = furvm::thing<>::resolve_type(thing->type(), m_context); { (struct thing_type){ thing_type::Primitive, { sizeof(std::size_t) } }, m_context->thing_alloc() });
switch (type->t) { switch (thing->type().type) {
case type_t::Primitive: size->get<long_t>() = static_cast<long_t>(type->primitive); break; case thing_type::Primitive:
case type_t::Array: size->get<std::int64_t>() = static_cast<std::int64_t>(thing->type().value.primitive);
size->get<long_t>() = break;
(type->array.size == 0) ? thing->get<array_t>().dynamic.size : static_cast<long_t>(type->array.size); case thing_type::Array:
size->get<std::int64_t>() = static_cast<std::int64_t>((thing->type().value.array.size == 0)
? thing->get<furvm::thing<>::array>().dynamic.size
: thing->type().value.array.size);
break; break;
case type_t::Import:
default: throw std::runtime_error("unreachable"); default: throw std::runtime_error("unreachable");
} }
} break; } break;
@@ -247,7 +268,7 @@ void executor::step() {
case instruction_t::JumpNotZero: { case instruction_t::JumpNotZero: {
byte offset = frame.mod->byte(frame.position++); byte offset = frame.mod->byte(frame.position++);
auto cond = pop_thing(); auto cond = pop_thing();
if (cond->get<int_t>() != 0) frame.position += (std::int8_t)offset; if (cond->integer() != 0) frame.position += (std::int8_t)offset;
} break; } break;
case instruction_t::Return: { case instruction_t::Return: {
pop_frame(); pop_frame();
+8
View File
@@ -98,4 +98,12 @@ function& function::operator=(const function& other) {
return *this; return *this;
} }
namespace detail {
std::size_t function_sig_hash::operator()(const function_sig& signature) const {
return furlang::utility::vector_hash<mod_type_h, detail::handle_hash<mod_type_h>>{}(signature.params);
}
} // namespace detail
} // namespace furvm } // namespace furvm
+11 -10
View File
@@ -11,19 +11,19 @@
#include <sstream> #include <sstream>
static void print_thing(const furvm::thing<furvm::thing_allocator>& thing) { static void print_thing(const furvm::thing<furvm::thing_allocator>& thing) {
switch (thing.type()->t) { switch (thing.type().type) {
case furvm::type_t::Primitive: { case furvm::thing_type::Primitive: {
std::cout << thing.integer(); std::cout << thing.integer();
} break; } break;
case furvm::type_t::Array: { case furvm::thing_type::Array: {
std::cout << "{ "; std::cout << "{ ";
for (furvm::long_t i = 0; i < thing.size(); ++i) { for (furvm::thing<>::s64 i = 0; i < thing.size(); ++i) {
if (i > 0) std::cout << ", "; if (i > 0) std::cout << ", ";
print_thing(thing.at(i)); print_thing(thing.at(i));
} }
std::cout << " }\n"; std::cout << " }\n";
} break; } break;
default: std::cerr << "{Something went wrong}"; default: std::cerr << "{Type not recognized}";
} }
} }
@@ -47,7 +47,7 @@ int main(int argc, char** argv) {
#else #else
static const furvm::byte s_bytecode[] = { static const furvm::byte s_bytecode[] = {
static_cast<furvm::byte>(furvm::instruction_t::Array), static_cast<furvm::byte>(furvm::instruction_t::Array),
0, 1,
0, 0,
0, 0,
0, 0,
@@ -58,10 +58,11 @@ int main(int argc, char** argv) {
static_cast<furvm::byte>(furvm::instruction_t::Return), static_cast<furvm::byte>(furvm::instruction_t::Return),
}; };
furvm::mod_h mod = context->emplace("main", s_bytecode, s_bytecode + sizeof(s_bytecode)); auto mod = context->emplace("main", s_bytecode, s_bytecode + sizeof(s_bytecode));
furvm::type_h intType = mod->emplace_type(std::make_shared<furvm::type>(context->at("core")->type_at(2), 10)); auto intType = mod->emplace_type(sizeof(int));
auto mainFunc = mod->emplace_function("main", furvm::function_sig{}, 0); auto arrayType = mod->emplace_type(intType.id(), 10);
mod->emplace_function(furvm::function_sig{ { intType } }, "print").dispatch(); auto mainFunc = mod->emplace_function("main", furvm::function_sig{}, 0);
mod->emplace_function(furvm::function_sig{ { arrayType } }, "print").dispatch();
#endif #endif
mod->set_native_function("print", [](furvm::executor& executor) { print_thing(*executor.load_thing(0)); }); mod->set_native_function("print", [](furvm::executor& executor) { print_thing(*executor.load_thing(0)); });
+24 -24
View File
@@ -3,7 +3,6 @@
#include "furvm/detail/serialization.hpp" #include "furvm/detail/serialization.hpp"
#include "furvm/function.hpp" #include "furvm/function.hpp"
#include "furvm/fwd.hpp" #include "furvm/fwd.hpp"
#include "furvm/type.hpp"
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
@@ -18,25 +17,26 @@ std::ostream& mod::serialize(std::ostream& os) const {
os.write(MAGIC, sizeof(MAGIC)); os.write(MAGIC, sizeof(MAGIC));
detail::serialize(os, std::uint32_t(0)); // version detail::serialize(os, std::uint32_t(0)); // version
type_id typeCount = type_id(m_types.cend() - m_types.cbegin()); mod_type_id typeCount = mod_type_id(m_types.cend() - m_types.cbegin());
detail::serialize(os, typeCount); detail::serialize(os, typeCount);
for (type_id id = 0; id < typeCount; ++id) { for (mod_type_id id = 0; id < typeCount; ++id) {
if (!m_types.contains(id)) { if (!m_types.contains(id)) {
detail::serialize(os, std::uint8_t(0xFF)); // null type detail::serialize(os, std::uint8_t(0xFF)); // null type
continue; continue;
} }
auto type = *m_types.at(id); auto type = *m_types.at(id);
switch (type->t) { switch (type.type) {
case type_t::Primitive: detail::serialize(os, type->primitive); break; case mod_type::Primitive: detail::serialize(os, type.value.primitive); break;
case type_t::Array: { case mod_type::Array: {
detail::serialize(os, type->array.size); detail::serialize(os, type.value.array.typeId);
detail::serialize(os, type->array.type.id()); detail::serialize(os, type.value.array.size);
} break; } break;
case type_t::Import: { case mod_type::Import: {
detail::serialize(os, type->imp.mod); detail::serialize(os, type.value.imprt.modId);
detail::serialize(os, type->imp.type); detail::serialize(os, type.value.imprt.typeId);
} break; } break;
case mod_type::Count: throw std::runtime_error("unreachable");
} }
} }
@@ -93,32 +93,32 @@ mod mod::load(std::istream& is) {
mod mod; mod mod;
type_id typeCount = 0; mod_type_id typeCount = 0;
detail::load(is, typeCount); detail::load(is, typeCount);
for (type_id id = 0; id < typeCount; ++id) { for (mod_type_id id = 0; id < typeCount; ++id) {
std::uint8_t type = 0; std::uint8_t type = 0;
detail::load(is, type); detail::load(is, type);
if (type == 0xFF) continue; if (type == 0xFF) continue;
switch ((type_t)type) { switch ((enum mod_type::type)type) {
case type_t::Primitive: { case mod_type::Primitive: {
primitive_type primitive = 0; mod_type::primitive primitive = 0;
detail::load(is, primitive); detail::load(is, primitive);
mod.emplace_type(id, std::make_shared<class type>(primitive)).dispatch(); mod.emplace_type(id, primitive).dispatch();
} break; } break;
case type_t::Array: { case mod_type::Array: {
mod_type_id typeId = 0;
detail::load(is, typeId);
std::size_t size = 0; std::size_t size = 0;
detail::load(is, size); detail::load(is, size);
type_id typeId = 0; mod.emplace_type(id, typeId, size).dispatch();
detail::load(is, typeId);
mod.emplace_type(id, std::make_shared<class type>(mod.type_at(typeId), size)).dispatch();
} break; } break;
case type_t::Import: { case mod_type::Import: {
std::string modName; std::string modName;
detail::load(is, modName); detail::load(is, modName);
type_id typeId = 0; mod_type_id typeId = 0;
detail::load(is, typeId); detail::load(is, typeId);
mod.emplace_type(id, std::make_shared<class type>(import_type{ std::move(modName), typeId })).dispatch(); mod.emplace_type(id, std::move(modName), typeId).dispatch();
} break; } break;
default: throw std::runtime_error("unknown type type"); default: throw std::runtime_error("unknown type type");
} }