This repository has been archived on 2023-09-10. You can view files and clone it, but cannot push or open issues/pull-requests.
joko/lib/Value.cpp

82 lines
1.8 KiB
C++
Raw Normal View History

2023-09-09 13:09:43 +00:00
#include "Value.hpp"
#include "Type.hpp"
2023-09-09 22:03:28 +00:00
#include "Function.hpp"
#include "Code.hpp"
2023-09-09 13:09:43 +00:00
namespace jk
{
/*static*/ std::shared_ptr<Value> Value::make_nil()
{
auto value = std::make_shared<Value>();
value->m_type = std::make_shared<Type>(TYPE_NIL);
return value;
}
/*static*/ std::shared_ptr<Value> Value::make_int(int val)
{
auto value = std::make_shared<Value>();
value->m_type = std::make_shared<Type>(TYPE_INT);
value->m_int_val = val;
return value;
}
2023-09-09 22:03:28 +00:00
/*static*/ std::shared_ptr<Value>
Value::make_function(std::shared_ptr<Function> val)
{
auto value = std::make_shared<Value>();
value->m_type = std::make_shared<Type>(TYPE_FUNCTION);
value->m_function_val = val;
return value;
}
/*static*/ std::shared_ptr<Value>
Value::make_code(std::shared_ptr<Code> val)
{
auto value = std::make_shared<Value>();
value->m_type = std::make_shared<Type>(TYPE_CODE);
value->m_code_val = val;
return value;
}
/*static*/ std::shared_ptr<Value>
Value::make_ref(size_t val)
{
auto value = std::make_shared<Value>();
value->m_type = std::make_shared<Type>(TYPE_REF);
value->m_ref_val = val;
return value;
}
std::shared_ptr<Function> Value::as_function() const
{
return m_function_val;
}
std::shared_ptr<Code> Value::as_code() const
{
return m_code_val;
}
2023-09-09 13:09:43 +00:00
std::weak_ptr<Type> Value::type() const
{
return m_type;
}
2023-09-09 22:03:28 +00:00
std::string Value::string() const
{
switch (m_type->type())
{
case TYPE_NIL: return "<nil>";
case TYPE_INT: return std::to_string(*m_int_val);
2023-09-10 06:06:34 +00:00
case TYPE_REF: return "<ref:" + std::to_string(*m_ref_val) + ">";
2023-09-09 22:03:28 +00:00
default:
std::cerr << "cannot stringify value '"
<< TypeTypeStr[m_type->type()]
<< "'"
<< std::endl;
abort();
}
}
2023-09-09 13:09:43 +00:00
}