aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.ucl/type.ccm
blob: e7843d298130bddc57fc43abdd1ea68631664206 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// This source code is released into the public domain.
module;

#include <ucl.h>

export module nihil.ucl:type;

import nihil.std;
import nihil.util;

namespace nihil::ucl {

// Our strongly-typed version of ::ucl_type.
export enum struct object_type : std::uint8_t {
	object = UCL_OBJECT,
	array = UCL_ARRAY,
	integer = UCL_INT,
	real = UCL_FLOAT,
	string = UCL_STRING,
	boolean = UCL_BOOLEAN,
	time = UCL_TIME,
	userdata = UCL_USERDATA,
	null = UCL_NULL,
};

// Get the name of a type.
export auto str(object_type type) -> std::string_view
{
	using namespace std::literals;

	switch (type) {
	case object_type::object:
		return "object"sv;
	case object_type::array:
		return "array"sv;
	case object_type::integer:
		return "integer"sv;
	case object_type::real:
		return "real"sv;
	case object_type::string:
		return "string"sv;
	case object_type::boolean:
		return "boolean"sv;
	case object_type::time:
		return "time"sv;
	case object_type::userdata:
		return "userdata"sv;
	case object_type::null:
		return "null"sv;
	default:
		// Don't fail here, since UCL might add more types that we
		// don't know about.
		return "unknown"sv;
	}
}

// Concept of a UCL data type.
export template <typename T>
concept datatype = requires(T o) {
	{ o.get_ucl_object() } -> std::convertible_to<::ucl_object_t const *>;
	{ o.type() } -> std::same_as<object_type>;
	{ T::ucl_type } -> std::convertible_to<object_type>;
};

// Exception thrown when a type assertion fails.
export struct type_mismatch : error
{
	type_mismatch(object_type expected_type, object_type actual_type)
		: error(std::format("expected type '{}' != actual type '{}'",
	                            ucl::str(expected_type), ucl::str(actual_type)))
		, m_expected_type(expected_type)
		, m_actual_type(actual_type)
	{
	}

	// The type we expected.
	auto expected_type(this type_mismatch const &self) -> object_type
	{
		return self.m_expected_type;
	}

	// The type we got.
	auto actual_type(this type_mismatch const &self) -> object_type
	{
		return self.m_actual_type;
	}

private:
	object_type m_expected_type;
	object_type m_actual_type;
};

} // namespace nihil::ucl