25#include <unordered_map>
31#include "nlohmann/json.hpp"
44#define MNX_REQUIRED_PROPERTY(TYPE, NAME) \
46 if (!ref().contains(#NAME)) { \
47 throw std::runtime_error("Missing required property: " #NAME); \
49 return ref()[#NAME].get<TYPE>(); \
51 void set_##NAME(const TYPE& value) { ref()[#NAME] = value; } \
52 static_assert(true, "")
66 #define MNX_ARRAY_ELEMENT_PROPERTY(TYPE, NAME, INDEX) \
67 static_assert(std::is_integral_v<decltype(INDEX)>, "array index must be an integer type"); \
68 TYPE NAME() const { return (*this)[INDEX]; } \
69 void set_##NAME(const TYPE& value) { (*this)[INDEX] = value; } \
70 static_assert(true, "")
88 #define MNX_OPTIONAL_NAMED_PROPERTY(TYPE, NAME, KEY) \
89 std::optional<TYPE> NAME() const { \
90 return ref().contains(KEY) ? std::optional<TYPE>(ref()[KEY].get<TYPE>()) : std::nullopt; \
92 TYPE NAME##_or(const TYPE& defaultVal) const { \
93 return ref().contains(KEY) ? ref()[KEY].get<TYPE>() : defaultVal; \
95 void set_##NAME(const TYPE& value) { ref()[KEY] = value; } \
96 void clear_##NAME() { ref().erase(KEY); } \
97 static_assert(true, "")
112 #define MNX_OPTIONAL_PROPERTY(TYPE, NAME) MNX_OPTIONAL_NAMED_PROPERTY(TYPE, NAME, #NAME)
129#define MNX_OPTIONAL_PROPERTY_WITH_DEFAULT(TYPE, NAME, DEFAULT) \
130 TYPE NAME() const { \
131 return ref().contains(#NAME) ? ref()[#NAME].get<TYPE>() : DEFAULT; \
133 void set_##NAME(const TYPE& value) { ref()[#NAME] = value; } \
134 void clear_##NAME() { ref().erase(#NAME); } \
135 void set_or_clear_##NAME(const TYPE& value) { \
136 if (value == DEFAULT) clear_##NAME(); \
137 else set_##NAME(value); \
139 static_assert(true, "")
152 #define MNX_REQUIRED_CHILD(TYPE, NAME) \
153 TYPE NAME() const { return getChild<TYPE>(#NAME); } \
154 template<typename... Args> \
155 TYPE create_##NAME(Args&&... args) { \
156 return setChild(#NAME, TYPE(*this, #NAME, std::forward<Args>(args)...)); \
158 static_assert(true, "")
172 #define MNX_OPTIONAL_CHILD(TYPE, NAME) \
173 std::optional<TYPE> NAME() const { return getOptionalChild<TYPE>(#NAME); } \
174 template<typename... Args> \
175 TYPE create_##NAME(Args&&... args) { \
176 return setChild(#NAME, TYPE(*this, #NAME, std::forward<Args>(args)...)); \
178 void clear_##NAME() { ref().erase(#NAME); } \
179 static_assert(true, "")
181#define MNX_ASSERT_IF(TEST) \
196using json = nlohmann::ordered_json;
200template <
typename T>
class Array;
202namespace validation {
203class SemanticValidator;
212 virtual ~Base() =
default;
215 Base(
const Base& src) : m_root(src.m_root), m_pointer(src.m_pointer)
220 m_pointer(std::move(src.m_pointer))
227 if (m_root != src.m_root) {
228 throw std::logic_error(
"Assignment from a different JSON document is not allowed.");
230 m_pointer = src.m_pointer;
239 if (m_root != src.m_root) {
240 throw std::logic_error(
"Assignment from a different JSON document is not allowed.");
242 m_pointer = std::move(src.m_pointer);
249 std::string
dump(
int indents = -1)
251 return ref().dump(indents);
257 template <
typename T>
260 static_assert(std::is_base_of_v<Base, T>,
"Template type mush be derived from Base.");
261 return T(m_root, m_pointer.parent_pointer());
267 template <
typename T>
279 json&
ref()
const {
return resolve_pointer(); }
288 const std::shared_ptr<json>&
root()
const {
return m_root; }
305 : m_root(
parent.m_root), m_pointer(
parent.m_pointer / std::string(key))
307 (*m_root)[m_pointer] = std::move(jsonRef);
317 template <
typename T>
320 static_assert(std::is_base_of_v<Base, T>,
"template type must be derived from Base");
322 json_pointer childPointer = m_pointer / std::string(key);
323 if (!checkKeyIsValid<T>(childPointer)) {
324 throw std::runtime_error(
"Missing required child node: " + std::string(key));
327 return T(m_root, childPointer);
337 template <
typename T>
338 T
setChild(
const std::string_view& key,
const T& value)
340 static_assert(std::is_base_of_v<Base, T>,
"template type must be derived from Base");
342 json_pointer childPointer = m_pointer / std::string(key);
343 (*m_root)[childPointer] = value.ref();
344 return T(m_root, childPointer);
354 template <
typename T>
357 static_assert(std::is_base_of_v<Base, T>,
"template type must be derived from Base");
359 json_pointer childPointer = m_pointer / std::string(key);
360 if (!checkKeyIsValid<T>(childPointer)) {
364 return T(m_root, childPointer);
375 template <
typename T>
378 if (!(*m_root).contains(
pointer)) {
384 if constexpr (std::is_base_of_v<Object, T>) {
385 if (!node.is_object()) {
386 throw std::runtime_error(
"Expected an object for: " +
pointer.to_string());
388 }
else if constexpr (std::is_base_of_v<Array<typename T::value_type>, T>) {
389 if (!node.is_array()) {
390 throw std::runtime_error(
"Expected an array for: " +
pointer.to_string());
402 json& resolve_pointer()
const
404 return (*m_root).at(m_pointer);
407 const std::shared_ptr<json> m_root;
410 friend class validation::SemanticValidator;
427 if (!
ref().is_object()) {
428 throw std::invalid_argument(
"mnx::Object must wrap a JSON object.");
441template <
typename T, std::enable_if_t<!std::is_base_of_v<Base, T>,
int> = 0>
444 static_assert(std::is_arithmetic_v<T> || std::is_same_v<T, std::string>,
"This template is for simple JSON classes");
459 return ref().template get<T>();
473 return src ==
ref().template get<T>();
477class ArrayElementObject;
484 static_assert(std::is_arithmetic_v<T> || std::is_same_v<T, std::string> ||
485 std::is_base_of_v<ArrayElementObject, T>,
"Invalid MNX array element type.");
488 template<
typename ArrayType>
493 mutable size_t m_idx;
496 iter(ArrayType* ptr,
size_t idx) : m_ptr(ptr), m_idx(idx) {}
497 T operator*()
const {
return (*m_ptr)[m_idx]; }
498 iter& operator++() { ++m_idx;
return *
this; }
499 bool operator!=(
const iter& o)
const {
return m_idx != o.m_idx; }
514 if (!
ref().is_array()) {
515 throw std::invalid_argument(
"mnx::Array must wrap a JSON array.");
538 if constexpr (std::is_base_of_v<Base, T>) {
539 return getChild<T>(std::to_string(index));
541 return getChild<SimpleType<T>>(std::to_string(index));
549 if constexpr (std::is_base_of_v<Base, T>) {
550 return getChild<T>(std::to_string(index));
552 return getChild<SimpleType<T>>(std::to_string(index));
557 template <
typename U = T>
558 std::enable_if_t<!std::is_base_of_v<Base, U>,
void>
561 ref().push_back(value);
568 template <
typename U = T,
typename... Args,
569 std::enable_if_t<std::is_base_of_v<Base, U>,
int> = 0>
572 if constexpr (std::is_base_of_v<Object, U>) {
573 ref().push_back(json::object());
575 ref().push_back(json::array());
577 return U(*
this, std::to_string(
ref().
size() - 1), std::forward<Args>(args)...);
606 throw std::out_of_range(
"Index out of range");
622 return std::stoul(
pointer().back());
630 template <
typename ContainerType>
633 return parent<Array<ArrayElementObject>>().parent<ContainerType>();
645 using ArrayElementObject::ArrayElementObject;
650 template <
typename T, std::enable_if_t<std::is_base_of_v<ContentObject, T>,
int> = 0>
653 return getTypedObject<T>();
659 template <
typename T, std::enable_if_t<std::is_base_of_v<ContentObject, T>,
int> = 0>
660 T getTypedObject()
const
662 if (type() != T::ContentTypeValue) {
663 throw std::invalid_argument(
"Type mismatch: expected " + std::string(T::ContentTypeValue) +
669 friend class ContentArray;
703 using BaseArray::BaseArray;
706 template <
typename T, std::enable_if_t<std::is_base_of_v<ContentObject, T>,
int> = 0>
714 template <
typename T,
typename... Args,
715 std::enable_if_t<std::is_base_of_v<ContentObject, T>,
int> = 0>
718 auto result = BaseArray::append<T>(std::forward<Args>(args)...);
720 result.set_type(std::string(T::ContentTypeValue));
728 template <
typename T, std::enable_if_t<std::is_base_of_v<ContentObject, T>,
int> = 0>
729 T getTypedObject(
size_t index)
const
732 auto element = (*this)[index];
733 if (element.type() != T::ContentTypeValue) {
734 throw std::invalid_argument(
"Type mismatch: expected " + std::string(T::ContentTypeValue) +
735 ", got " + element.type());
737 return T(
root(),
pointer() / std::to_string(index));
745template <
typename E,
typename = std::enable_if_t<std::is_enum_v<E>>>
753 static const std::unordered_map<E, std::string> reverseMap = []() {
754 std::unordered_map<E, std::string> result;
756 result.emplace(element.second, element.first);
770 static_assert(std::is_arithmetic_v<T> || std::is_same_v<T, std::string> ||
771 std::is_base_of_v<ArrayElementObject, T>,
"Invalid MNX dictionary element type.");
774 template <
typename DictionaryType,
typename IteratorType>
777 using value_type = std::pair<const std::string, T>;
778 using difference_type = std::ptrdiff_t;
779 using iterator_category = std::forward_iterator_tag;
784 DictionaryType* m_ptr;
786 mutable std::unique_ptr<value_type> m_pair;
788 void update_pair()
const {
790 if (m_it != m_ptr->ref().end()) {
791 m_pair = std::make_unique<value_type>(m_it.key(), m_ptr->operator[](m_it.key()));
796 iter(DictionaryType* ptr, IteratorType it) : m_ptr(ptr), m_it(it)
799 reference operator*()
const {
return *m_pair.get(); }
800 pointer operator->()
const {
return m_pair.get(); }
802 iter& operator++() { ++m_it; update_pair();
return *
this; }
803 iter operator++(
int) { iter tmp = *
this; ++(*this);
return tmp; }
805 bool operator!=(
const iter& o)
const {
return m_it != o.m_it; }
806 bool operator==(
const iter& o)
const {
return m_it == o.m_it; }
842 if constexpr (std::is_base_of_v<Base, T>) {
843 return getChild<T>(key);
845 return getChild<SimpleType<T>>(key);
852 if constexpr (std::is_base_of_v<Base, T>) {
853 return getChild<T>(key);
855 return getChild<SimpleType<T>>(key);
860 template <
typename U = T>
861 std::enable_if_t<!std::is_base_of_v<Base, U>,
void>
862 emplace(
const std::string& key,
const U& value)
871 template <
typename U = T,
typename... Args,
872 std::enable_if_t<std::is_base_of_v<Base, U>,
int> = 0>
873 U
append(
const std::string& key, Args&&... args)
875 if constexpr (std::is_base_of_v<Object, U>) {
876 ref()[key] = json::object();
878 ref()[key] = json::array();
880 return U(*
this, key, std::forward<Args>(args)...);
892 auto find(
const std::string& key)
894 auto it =
ref().find(key);
901 auto find(
const std::string& key)
const
903 auto it =
ref().find(key);
922#ifndef DOXYGEN_SHOULD_IGNORE_THIS
929template<
typename EnumType>
930struct adl_serializer<EnumType, std::enable_if_t<std::is_enum_v<EnumType>>>
932 template<
typename BasicJsonType>
933 static EnumType from_json(
const BasicJsonType& j)
937 auto it = map.find(j.get<std::string>());
938 if (it != map.end()) {
945 template<
typename BasicJsonType>
946 static void to_json(BasicJsonType& j,
const EnumType& value)
949 auto it = map.find(value);
950 if (it == map.end()) {
962template<
typename BasicJsonType,
typename EnumType,
963 std::enable_if_t<std::is_enum<EnumType>::value,
int> = 0>
964inline void from_json(
const BasicJsonType& j, EnumType& value)
968 auto it = map.find(j.template get<std::string>());
969 if (it != map.end()) {
977template<
typename BasicJsonType,
typename EnumType,
978 std::enable_if_t<std::is_enum<EnumType>::value,
int> = 0>
979inline void to_json(BasicJsonType& j, EnumType value)
noexcept
982 auto it = map.find(value);
983 if (it != map.end()) {
Represents an MNX object that is included as an array element.
Definition BaseTypes.h:615
ContainerType container() const
Returns the container of the array this element belongs to wrapped as the specified template type.
Definition BaseTypes.h:631
size_t calcArrayIndex() const
Calculates the array index of the current instance within the array.
Definition BaseTypes.h:620
Represents an MNX array, encapsulating property access.
Definition BaseTypes.h:483
void checkIndex(size_t index) const
validates that an index is not out of range
Definition BaseTypes.h:602
auto begin()
Returns an iterator to the beginning of the array.
Definition BaseTypes.h:588
size_t size() const
Get the size of the array.
Definition BaseTypes.h:526
bool empty() const
Check if the array is empty.
Definition BaseTypes.h:529
iter< Array > iterator
non-const iterator type
Definition BaseTypes.h:506
iter< const Array > const_iterator
const iterator type
Definition BaseTypes.h:507
T value_type
The type for elements in this Array.
Definition BaseTypes.h:504
auto operator[](size_t index) const
const operator[]
Definition BaseTypes.h:535
auto begin() const
Returns a const iterator to the beginning of the array.
Definition BaseTypes.h:594
void erase(size_t index)
Remove an element at a given index.
Definition BaseTypes.h:581
auto end()
Returns an iterator to the end of the array.
Definition BaseTypes.h:591
void clear()
Clear all elements.
Definition BaseTypes.h:532
Array(const std::shared_ptr< json > &root, json_pointer pointer)
Wraps an Array class around an existing JSON array node.
Definition BaseTypes.h:512
std::enable_if_t<!std::is_base_of_v< Base, U >, void > push_back(const U &value)
Append a new value to the array. (Available only for primitive types)
Definition BaseTypes.h:559
U append(Args &&... args)
Create a new element at the end of the array. (Available only for Base types)
Definition BaseTypes.h:570
auto end() const
Returns a const iterator to the end of the array.
Definition BaseTypes.h:597
auto operator[](size_t index)
non-const operator[]
Definition BaseTypes.h:546
Array(Base &parent, const std::string_view &key)
Creates a new Array class as a child of a JSON node.
Definition BaseTypes.h:522
Base class wrapper for all MNX JSON nodes.
Definition BaseTypes.h:210
json & ref() const
Convert this node for retrieval.
Definition BaseTypes.h:279
std::optional< T > getEnclosingElement() const
Returns the enclosing array element for this instance.
Definition Implementations.cpp:54
std::string dump(int indents=-1)
Dumps the branch to a string. Useful in debugging.
Definition BaseTypes.h:249
T getChild(const std::string_view &key) const
Retrieves and validates a required child node.
Definition BaseTypes.h:318
json_pointer pointer() const
Returns the json_pointer for this node.
Definition BaseTypes.h:271
Base(json &&jsonRef, Base &parent, const std::string_view &key)
Construct a Base reference as a child inside a parent node.
Definition BaseTypes.h:304
Base(const std::shared_ptr< json > &root, json_pointer pointer)
Wrap a Base instance around a specific JSON reference using a json_pointer.
Definition BaseTypes.h:295
T setChild(const std::string_view &key, const T &value)
Sets a child node.
Definition BaseTypes.h:338
T parent() const
Returns the parent object for this node.
Definition BaseTypes.h:258
json & ref()
Access the JSON node for modification.
Definition BaseTypes.h:285
std::optional< T > getOptionalChild(const std::string_view &key) const
Retrieves an optional child node.
Definition BaseTypes.h:355
Base(const Base &src)
Copy constructor.
Definition BaseTypes.h:215
Base & operator=(const Base &src)
Copy assignment operator.
Definition BaseTypes.h:224
Base(Base &&src) noexcept
Move constructor.
Definition BaseTypes.h:219
Base & operator=(Base &&src)
Move assignment operator.
Definition BaseTypes.h:236
const std::shared_ptr< json > & root() const
Returns the root.
Definition BaseTypes.h:288
Class for content arrays.
Definition BaseTypes.h:700
T get(size_t index) const
Retrieve an element from the array as a specific type.
Definition BaseTypes.h:707
T append(Args &&... args)
Append an element of the specified type.
Definition BaseTypes.h:716
Base class for objects that are elements of content arrays.
Definition BaseTypes.h:640
MNX_OPTIONAL_PROPERTY_WITH_DEFAULT(std::string, type, std::string(ContentTypeValueDefault))
determines our type in the JSON
static constexpr std::string_view ContentTypeValueDefault
default type value that identifies the type within the content array
Definition BaseTypes.h:642
T get() const
Retrieve an element as a specific type.
Definition BaseTypes.h:651
Represents an MNX dictionary, where each key is a user-defined string.
Definition BaseTypes.h:769
iter< Dictionary, json::iterator > iterator
non-const iterator type
Definition BaseTypes.h:813
auto operator[](const std::string &key)
non-const operator[]
Definition BaseTypes.h:850
size_t size() const
Get the size of the array.
Definition BaseTypes.h:831
auto end() const
Returns a const iterator to the end of the dictionary.
Definition BaseTypes.h:917
auto begin() const
Returns a const iterator to the beginning of the dictionary.
Definition BaseTypes.h:914
auto find(const std::string &key) const
Finds an element by key and returns a const iterator.
Definition BaseTypes.h:901
U append(const std::string &key, Args &&... args)
Create a new element using the input key. (Available only for Base types)
Definition BaseTypes.h:873
void erase(const std::string &key)
Remove an element at a given key.
Definition BaseTypes.h:884
iter< const Dictionary, json::const_iterator > const_iterator
const iterator type
Definition BaseTypes.h:814
T operator[](const std::string &key) const
const operator[]
Definition BaseTypes.h:840
T value_type
The type for elements in this Array.
Definition BaseTypes.h:811
auto begin()
Returns an iterator to the beginning of the dictionary.
Definition BaseTypes.h:908
bool empty() const
Check if the array is empty.
Definition BaseTypes.h:834
std::enable_if_t<!std::is_base_of_v< Base, U >, void > emplace(const std::string &key, const U &value)
Add a new value to the dictonary. (Available only for primitive types)
Definition BaseTypes.h:862
Dictionary(Base &parent, const std::string_view &key)
Creates a new Dictionary class as a child of a JSON node.
Definition BaseTypes.h:827
Dictionary(const std::shared_ptr< json > &root, json_pointer pointer)
Wraps an Dictionary class around an existing JSON node.
Definition BaseTypes.h:819
auto end()
Returns an iterator to the end of the dictionary.
Definition BaseTypes.h:911
auto find(const std::string &key)
Finds an element by key and returns an iterator.
Definition BaseTypes.h:892
void clear()
Clear all elements.
Definition BaseTypes.h:837
Represents an MNX object, encapsulating property access.
Definition BaseTypes.h:420
Object(const std::shared_ptr< json > &root, json_pointer pointer)
Wraps an Object class around an existing JSON object node.
Definition BaseTypes.h:425
Object(Base &parent, const std::string_view &key)
Creates a new Object class as a child of a JSON node.
Definition BaseTypes.h:435
Allows access to a fundamental type (number, boolean, string) in a JSON node.
Definition BaseTypes.h:443
SimpleType(const std::shared_ptr< json > &root, json_pointer pointer)
Wraps a SimpleType class around an existing JSON object node.
Definition BaseTypes.h:452
bool operator==(const T &src) const
Equality comparison with value type.
Definition BaseTypes.h:471
T value_type
value type of this SimpleType
Definition BaseTypes.h:447
SimpleType & operator=(const T &src)
Allow assignment to underlying json reference.
Definition BaseTypes.h:464
object model for MNX format
std::function< void(const std::string &message, const Base &location)> ErrorHandler
Error handler type for reporting errors.
Definition BaseTypes.h:414
json::json_pointer json_pointer
JSON pointer class for MNX.
Definition BaseTypes.h:197
constexpr int MNX_VERSION
The MNX version for files generated by the DOM.
Definition BaseTypes.h:194
nlohmann::ordered_json json
JSON class for MNX.
Definition BaseTypes.h:196
Supplies enum string mappings to nlohmann json's serializer.
Definition BaseTypes.h:747
static const std::unordered_map< E, std::string > enumToString()
maps enum values to strings
Definition BaseTypes.h:751
static const std::unordered_map< std::string, E > stringToEnum()
maps strings to enum values