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

81 lines
1.8 KiB
C++
Raw Permalink Normal View History

2023-09-08 11:13:47 +00:00
#include "Value.hpp"
#include "Type.hpp"
namespace sk
{
/*static*/ std::shared_ptr<Value>
Value::make_int(int value)
{
auto res =
std::make_shared<Value>(std::make_shared<Type>(TYPE_INT));
res->m_int_val = value;
return res;
}
/*static*/ std::shared_ptr<Value>
Value::make_float(float value)
{
auto res =
std::make_shared<Value>(std::make_shared<Type>(TYPE_FLOAT));
res->m_float_val = value;
return res;
}
/*static*/ std::shared_ptr<Value>
Value::make_bool(bool value)
{
auto res =
std::make_shared<Value>(std::make_shared<Type>(TYPE_BOOL));
res->m_bool_val = value;
return res;
}
/*static*/ std::shared_ptr<Value>
Value::make_string(std::string const& value)
{
auto res =
std::make_shared<Value>(std::make_shared<Type>(TYPE_STRING));
res->m_string_val = value;
return res;
}
/*explicit*/ Value::Value(std::shared_ptr<Type> type)
: m_type { type }
{
}
/*virtual*/ Value::~Value()
{
}
bool Value::equals(Value const& rhs) const
{
return m_int_val == rhs.m_int_val
&& m_float_val == rhs.m_float_val
&& m_bool_val == rhs.m_bool_val
&& m_string_val == rhs.m_string_val;
}
std::string Value::string() const
{
switch (m_type->type())
{
case TYPE_INT: return std::to_string(as_int());
case TYPE_FLOAT: return std::to_string(as_float());
case TYPE_BOOL: return as_bool() ? "true" : "false";
case TYPE_STRING: return as_string().substr(1, as_string().size()-2);
default:
throw std::runtime_error {std::string()
+ "cannot stringify unknown type '"
+ TypeTypeStr[m_type->type()]
+ "'"};
}
}
std::weak_ptr<Type> Value::type() const
{
return m_type;
}
}