JsonNode.h 10 KB

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