JsonNode.h 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*
  2. * JsonNode.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "GameConstants.h"
  12. #include "filesystem/ResourcePath.h"
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. class JsonNode;
  15. using JsonMap = std::map<std::string, JsonNode>;
  16. using JsonVector = std::vector<JsonNode>;
  17. struct Bonus;
  18. class CSelector;
  19. class CAddInfo;
  20. class ILimiter;
  21. class DLL_LINKAGE JsonNode
  22. {
  23. public:
  24. enum class JsonType
  25. {
  26. DATA_NULL,
  27. DATA_BOOL,
  28. DATA_FLOAT,
  29. DATA_STRING,
  30. DATA_VECTOR,
  31. DATA_STRUCT,
  32. DATA_INTEGER
  33. };
  34. private:
  35. using JsonData = std::variant<std::monostate, bool, double, std::string, JsonVector, JsonMap, si64>;
  36. JsonData data;
  37. public:
  38. /// free to use metadata fields
  39. std::string meta;
  40. // meta-flags like override
  41. std::vector<std::string> flags;
  42. //Create empty node
  43. JsonNode(JsonType Type = JsonType::DATA_NULL);
  44. //Create tree from Json-formatted input
  45. explicit JsonNode(const char * data, size_t datasize);
  46. explicit JsonNode(const std::byte * data, size_t datasize);
  47. //Create tree from JSON file
  48. explicit JsonNode(const JsonPath & fileURI);
  49. explicit JsonNode(const std::string & modName, const JsonPath & fileURI);
  50. explicit JsonNode(const JsonPath & fileURI, bool & isValidSyntax);
  51. bool operator == (const JsonNode &other) const;
  52. bool operator != (const JsonNode &other) const;
  53. void setMeta(const std::string & metadata, bool recursive = true);
  54. /// Convert node to another type. Converting to nullptr will clear all data
  55. void setType(JsonType Type);
  56. JsonType getType() const;
  57. bool isNull() const;
  58. bool isNumber() const;
  59. bool isString() const;
  60. bool isVector() const;
  61. bool isStruct() const;
  62. /// true if node contains not-null data that cannot be extended via merging
  63. /// used for generating common base node from multiple nodes (e.g. bonuses)
  64. bool containsBaseData() const;
  65. bool isCompact() const;
  66. /// removes all data from node and sets type to null
  67. void clear();
  68. /// returns bool or bool equivalent of string value if 'success' is true, or false otherwise
  69. bool TryBoolFromString(bool & success) const;
  70. /// non-const accessors, node will change type on type mismatch
  71. bool & Bool();
  72. double & Float();
  73. si64 & Integer();
  74. std::string & String();
  75. JsonVector & Vector();
  76. JsonMap & Struct();
  77. /// const accessors, will cause assertion failure on type mismatch
  78. bool Bool() const;
  79. ///float and integer allowed
  80. double Float() const;
  81. ///only integer allowed
  82. si64 Integer() const;
  83. const std::string & String() const;
  84. const JsonVector & Vector() const;
  85. const JsonMap & Struct() const;
  86. /// returns resolved "json pointer" (string in format "/path/to/node")
  87. const JsonNode & resolvePointer(const std::string & jsonPointer) const;
  88. JsonNode & resolvePointer(const std::string & jsonPointer);
  89. /// convert json tree into specified type. Json tree must have same type as Type
  90. /// Valid types: bool, string, any numeric, map and vector
  91. /// example: convertTo< std::map< std::vector<int> > >();
  92. template<typename Type>
  93. Type convertTo() const;
  94. //operator [], for structs only - get child node by name
  95. JsonNode & operator[](const std::string & child);
  96. const JsonNode & operator[](const std::string & child) const;
  97. JsonNode & operator[](size_t child);
  98. const JsonNode & operator[](size_t child) const;
  99. std::string toJson(bool compact = false) const;
  100. std::vector<std::byte> toBytes(bool compact = false) const;
  101. template <typename Handler> void serialize(Handler &h)
  102. {
  103. h & meta;
  104. h & flags;
  105. h & data;
  106. }
  107. };
  108. namespace JsonUtils
  109. {
  110. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonVector & ability_vec);
  111. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonNode & ability);
  112. DLL_LINKAGE std::shared_ptr<Bonus> parseBuildingBonus(const JsonNode & ability, const FactionID & faction, const BuildingID & building, const std::string & description);
  113. DLL_LINKAGE bool parseBonus(const JsonNode & ability, Bonus * placement);
  114. DLL_LINKAGE std::shared_ptr<ILimiter> parseLimiter(const JsonNode & limiter);
  115. DLL_LINKAGE CSelector parseSelector(const JsonNode &ability);
  116. DLL_LINKAGE void resolveAddInfo(CAddInfo & var, const JsonNode & node);
  117. /**
  118. * @brief recursively merges source into dest, replacing identical fields
  119. * struct : recursively calls this function
  120. * arrays : each entry will be merged recursively
  121. * values : value in source will replace value in dest
  122. * null : if value in source is present but set to null it will delete entry in dest
  123. * @note this function will destroy data in source
  124. */
  125. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source, bool ignoreOverride = false, bool copyMeta = false);
  126. /**
  127. * @brief recursively merges source into dest, replacing identical fields
  128. * struct : recursively calls this function
  129. * arrays : each entry will be merged recursively
  130. * values : value in source will replace value in dest
  131. * null : if value in source is present but set to null it will delete entry in dest
  132. * @note this function will preserve data stored in source by creating copy
  133. */
  134. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source, bool ignoreOverride = false, bool copyMeta = false);
  135. /** @brief recursively merges descendant into copy of base node
  136. * Result emulates inheritance semantic
  137. */
  138. DLL_LINKAGE void inherit(JsonNode & descendant, const JsonNode & base);
  139. /**
  140. * @brief construct node representing the common structure of input nodes
  141. * @param pruneEmpty - omit common properties whose intersection is empty
  142. * different types: null
  143. * struct: recursive intersect on common properties
  144. * other: input if equal, null otherwise
  145. */
  146. DLL_LINKAGE JsonNode intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty = true);
  147. DLL_LINKAGE JsonNode intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty = true);
  148. /**
  149. * @brief construct node representing the difference "node - base"
  150. * merging difference with base gives node
  151. */
  152. DLL_LINKAGE JsonNode difference(const JsonNode & node, const JsonNode & base);
  153. /**
  154. * @brief generate one Json structure from multiple files
  155. * @param files - list of filenames with parts of json structure
  156. */
  157. DLL_LINKAGE JsonNode assembleFromFiles(const std::vector<std::string> & files);
  158. DLL_LINKAGE JsonNode assembleFromFiles(const std::vector<std::string> & files, bool & isValid);
  159. /// This version loads all files with same name (overridden by mods)
  160. DLL_LINKAGE JsonNode assembleFromFiles(const std::string & filename);
  161. /**
  162. * @brief removes all nodes that are identical to default entry in schema
  163. * @param node - JsonNode to minimize
  164. * @param schemaName - name of schema to use
  165. * @note for minimizing data must be valid against given schema
  166. */
  167. DLL_LINKAGE void minimize(JsonNode & node, const std::string & schemaName);
  168. /// opposed to minimize, adds all missing, required entries that have default value
  169. DLL_LINKAGE void maximize(JsonNode & node, const std::string & schemaName);
  170. /**
  171. * @brief validate node against specified schema
  172. * @param node - JsonNode to check
  173. * @param schemaName - name of schema to use
  174. * @param dataName - some way to identify data (printed in console in case of errors)
  175. * @returns true if data in node fully compilant with schema
  176. */
  177. DLL_LINKAGE bool validate(const JsonNode & node, const std::string & schemaName, const std::string & dataName);
  178. /// get schema by json URI: vcmi:<name of file in schemas directory>#<entry in file, optional>
  179. /// example: schema "vcmi:settings" is used to check user settings
  180. DLL_LINKAGE const JsonNode & getSchema(const std::string & URI);
  181. /// for easy construction of JsonNodes; helps with inserting primitives into vector node
  182. DLL_LINKAGE JsonNode boolNode(bool value);
  183. DLL_LINKAGE JsonNode floatNode(double value);
  184. DLL_LINKAGE JsonNode stringNode(const std::string & value);
  185. DLL_LINKAGE JsonNode intNode(si64 value);
  186. }
  187. namespace JsonDetail
  188. {
  189. // conversion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  190. template <typename T, int arithm>
  191. struct JsonConvImpl;
  192. template <typename T>
  193. struct JsonConvImpl<T, 1>
  194. {
  195. static T convertImpl(const JsonNode & node)
  196. {
  197. return T((int)node.Float());
  198. }
  199. };
  200. template <typename T>
  201. struct JsonConvImpl<T, 0>
  202. {
  203. static T convertImpl(const JsonNode & node)
  204. {
  205. return T(node.Float());
  206. }
  207. };
  208. template<typename Type>
  209. struct JsonConverter
  210. {
  211. static Type convert(const JsonNode & node)
  212. {
  213. ///this should be triggered only for numeric types and enums
  214. static_assert(std::is_arithmetic_v<Type> || std::is_enum_v<Type> || std::is_class_v<Type>, "Unsupported type for JsonNode::convertTo()!");
  215. return JsonConvImpl<Type, std::is_enum_v<Type> || std::is_class_v<Type> >::convertImpl(node);
  216. }
  217. };
  218. template<typename Type>
  219. struct JsonConverter<std::map<std::string, Type> >
  220. {
  221. static std::map<std::string, Type> convert(const JsonNode & node)
  222. {
  223. std::map<std::string, Type> ret;
  224. for (const JsonMap::value_type & entry : node.Struct())
  225. {
  226. ret.insert(entry.first, entry.second.convertTo<Type>());
  227. }
  228. return ret;
  229. }
  230. };
  231. template<typename Type>
  232. struct JsonConverter<std::set<Type> >
  233. {
  234. static std::set<Type> convert(const JsonNode & node)
  235. {
  236. std::set<Type> ret;
  237. for(const JsonVector::value_type & entry : node.Vector())
  238. {
  239. ret.insert(entry.convertTo<Type>());
  240. }
  241. return ret;
  242. }
  243. };
  244. template<typename Type>
  245. struct JsonConverter<std::vector<Type> >
  246. {
  247. static std::vector<Type> convert(const JsonNode & node)
  248. {
  249. std::vector<Type> ret;
  250. for (const JsonVector::value_type & entry: node.Vector())
  251. {
  252. ret.push_back(entry.convertTo<Type>());
  253. }
  254. return ret;
  255. }
  256. };
  257. template<>
  258. struct JsonConverter<std::string>
  259. {
  260. static std::string convert(const JsonNode & node)
  261. {
  262. return node.String();
  263. }
  264. };
  265. template<>
  266. struct JsonConverter<bool>
  267. {
  268. static bool convert(const JsonNode & node)
  269. {
  270. return node.Bool();
  271. }
  272. };
  273. }
  274. template<typename Type>
  275. Type JsonNode::convertTo() const
  276. {
  277. return JsonDetail::JsonConverter<Type>::convert(*this);
  278. }
  279. VCMI_LIB_NAMESPACE_END