MalachScript/src/Binder/BoundType.hpp

77 lines
2.9 KiB
C++

#ifndef MALACHSCRIPT_BOUNDTYPE_HPP
#define MALACHSCRIPT_BOUNDTYPE_HPP
#include <unordered_map>
#include "BoundVariable.hpp"
namespace MalachScript::Binder {
class BoundType {
public:
BoundType(Identifier identifier, ClassAttr classAttr) : _identifier(identifier), _classAttr(classAttr) {}
BoundType(Identifier identifier, ClassAttr classAttr, size_t size)
: _identifier(identifier), _classAttr(classAttr), _size(size), _inherits(0) {}
inline void Finalise() noexcept {
if (_initialised) {
return;
}
_initialised = true;
for (auto& inherits : _inherits) {
if (!inherits->IsInitialised()) {
const_cast<BoundType*>(inherits)->Finalise();
}
_size += inherits->GetSize();
}
for (auto& field : _fields) {
if (!field->GetType()->IsInitialised()) {
const_cast<BoundType*>(field->GetType())->Finalise();
}
_size += field->GetType()->GetSize();
}
}
[[nodiscard]] inline const Identifier& GetIdentifier() const noexcept { return _identifier; }
[[nodiscard]] inline size_t GetSize() const noexcept { return _size; }
[[nodiscard]] inline bool IsInitialised() const noexcept { return _initialised; }
[[nodiscard]] inline ClassAttr GetAttributes() const noexcept { return _classAttr; }
inline void AddInheritType(const BoundType* type) { _inherits.push_back(type); }
inline void AddField(const Identifier& identifier, BoundVariable* var) {
_fields.push_back(var);
_fieldsLookup[identifier] = var;
}
inline void RegisterType(const Identifier& identifier, const BoundType* type) {
_types[identifier] = const_cast<BoundType*>(type);
}
[[nodiscard]] inline const std::unordered_map<Identifier, BoundType*>& GetTypes() const noexcept {
return _types;
}
[[nodiscard]] inline const std::unordered_map<Identifier, BoundVariable*>& GetFieldsLookup() const noexcept {
return _fieldsLookup;
}
inline std::optional<BoundType*> ResolveType(const Identifier& identifier) const noexcept {
auto find = _types.find(identifier);
if (find == _types.end()) {
return {};
}
return find->second;
}
private:
bool _initialised = false;
Identifier _identifier;
ClassAttr _classAttr;
size_t _size = 0;
std::vector<const BoundType*> _inherits;
std::vector<BoundVariable*> _fields;
std::unordered_map<Identifier, BoundVariable*> _fieldsLookup;
// TODO: functions
std::unordered_map<Identifier, BoundType*> _types;
};
}
#endif // MALACHSCRIPT_BOUNDTYPE_HPP