2
0

JsonNode.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. //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. template <typename Handler> void serialize(Handler &h, const int version)
  101. {
  102. h & meta;
  103. h & flags;
  104. h & data;
  105. }
  106. };
  107. namespace JsonUtils
  108. {
  109. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonVector & ability_vec);
  110. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonNode & ability);
  111. DLL_LINKAGE std::shared_ptr<Bonus> parseBuildingBonus(const JsonNode & ability, const FactionID & faction, const BuildingID & building, const std::string & description);
  112. DLL_LINKAGE bool parseBonus(const JsonNode & ability, Bonus * placement);
  113. DLL_LINKAGE std::shared_ptr<ILimiter> parseLimiter(const JsonNode & limiter);
  114. DLL_LINKAGE CSelector parseSelector(const JsonNode &ability);
  115. DLL_LINKAGE void resolveAddInfo(CAddInfo & var, const JsonNode & node);
  116. /**
  117. * @brief recursively merges source into dest, replacing identical fields
  118. * struct : recursively calls this function
  119. * arrays : each entry will be merged recursively
  120. * values : value in source will replace value in dest
  121. * null : if value in source is present but set to null it will delete entry in dest
  122. * @note this function will destroy data in source
  123. */
  124. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source, bool ignoreOverride = false, bool copyMeta = false);
  125. /**
  126. * @brief recursively merges source into dest, replacing identical fields
  127. * struct : recursively calls this function
  128. * arrays : each entry will be merged recursively
  129. * values : value in source will replace value in dest
  130. * null : if value in source is present but set to null it will delete entry in dest
  131. * @note this function will preserve data stored in source by creating copy
  132. */
  133. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source, bool ignoreOverride = false, bool copyMeta = false);
  134. /** @brief recursively merges descendant into copy of base node
  135. * Result emulates inheritance semantic
  136. */
  137. DLL_LINKAGE void inherit(JsonNode & descendant, const JsonNode & base);
  138. /**
  139. * @brief construct node representing the common structure of input nodes
  140. * @param pruneEmpty - omit common properties whose intersection is empty
  141. * different types: null
  142. * struct: recursive intersect on common properties
  143. * other: input if equal, null otherwise
  144. */
  145. DLL_LINKAGE JsonNode intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty = true);
  146. DLL_LINKAGE JsonNode intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty = true);
  147. /**
  148. * @brief construct node representing the difference "node - base"
  149. * merging difference with base gives node
  150. */
  151. DLL_LINKAGE JsonNode difference(const JsonNode & node, const JsonNode & base);
  152. /**
  153. * @brief generate one Json structure from multiple files
  154. * @param files - list of filenames with parts of json structure
  155. */
  156. DLL_LINKAGE JsonNode assembleFromFiles(const std::vector<std::string> & files);
  157. DLL_LINKAGE JsonNode assembleFromFiles(const std::vector<std::string> & files, bool & isValid);
  158. /// This version loads all files with same name (overridden by mods)
  159. DLL_LINKAGE JsonNode assembleFromFiles(const std::string & filename);
  160. /**
  161. * @brief removes all nodes that are identical to default entry in schema
  162. * @param node - JsonNode to minimize
  163. * @param schemaName - name of schema to use
  164. * @note for minimizing data must be valid against given schema
  165. */
  166. DLL_LINKAGE void minimize(JsonNode & node, const std::string & schemaName);
  167. /// opposed to minimize, adds all missing, required entries that have default value
  168. DLL_LINKAGE void maximize(JsonNode & node, const std::string & schemaName);
  169. /**
  170. * @brief validate node against specified schema
  171. * @param node - JsonNode to check
  172. * @param schemaName - name of schema to use
  173. * @param dataName - some way to identify data (printed in console in case of errors)
  174. * @returns true if data in node fully compilant with schema
  175. */
  176. DLL_LINKAGE bool validate(const JsonNode & node, const std::string & schemaName, const std::string & dataName);
  177. /// get schema by json URI: vcmi:<name of file in schemas directory>#<entry in file, optional>
  178. /// example: schema "vcmi:settings" is used to check user settings
  179. DLL_LINKAGE const JsonNode & getSchema(const std::string & URI);
  180. /// for easy construction of JsonNodes; helps with inserting primitives into vector node
  181. DLL_LINKAGE JsonNode boolNode(bool value);
  182. DLL_LINKAGE JsonNode floatNode(double value);
  183. DLL_LINKAGE JsonNode stringNode(const std::string & value);
  184. DLL_LINKAGE JsonNode intNode(si64 value);
  185. }
  186. namespace JsonDetail
  187. {
  188. // conversion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  189. template <typename T, int arithm>
  190. struct JsonConvImpl;
  191. template <typename T>
  192. struct JsonConvImpl<T, 1>
  193. {
  194. static T convertImpl(const JsonNode & node)
  195. {
  196. return T((int)node.Float());
  197. }
  198. };
  199. template <typename T>
  200. struct JsonConvImpl<T, 0>
  201. {
  202. static T convertImpl(const JsonNode & node)
  203. {
  204. return T(node.Float());
  205. }
  206. };
  207. template<typename Type>
  208. struct JsonConverter
  209. {
  210. static Type convert(const JsonNode & node)
  211. {
  212. ///this should be triggered only for numeric types and enums
  213. static_assert(std::is_arithmetic_v<Type> || std::is_enum_v<Type> || std::is_class_v<Type>, "Unsupported type for JsonNode::convertTo()!");
  214. return JsonConvImpl<Type, std::is_enum_v<Type> || std::is_class_v<Type> >::convertImpl(node);
  215. }
  216. };
  217. template<typename Type>
  218. struct JsonConverter<std::map<std::string, Type> >
  219. {
  220. static std::map<std::string, Type> convert(const JsonNode & node)
  221. {
  222. std::map<std::string, Type> ret;
  223. for (const JsonMap::value_type & entry : node.Struct())
  224. {
  225. ret.insert(entry.first, entry.second.convertTo<Type>());
  226. }
  227. return ret;
  228. }
  229. };
  230. template<typename Type>
  231. struct JsonConverter<std::set<Type> >
  232. {
  233. static std::set<Type> convert(const JsonNode & node)
  234. {
  235. std::set<Type> ret;
  236. for(const JsonVector::value_type & entry : node.Vector())
  237. {
  238. ret.insert(entry.convertTo<Type>());
  239. }
  240. return ret;
  241. }
  242. };
  243. template<typename Type>
  244. struct JsonConverter<std::vector<Type> >
  245. {
  246. static std::vector<Type> convert(const JsonNode & node)
  247. {
  248. std::vector<Type> ret;
  249. for (const JsonVector::value_type & entry: node.Vector())
  250. {
  251. ret.push_back(entry.convertTo<Type>());
  252. }
  253. return ret;
  254. }
  255. };
  256. template<>
  257. struct JsonConverter<std::string>
  258. {
  259. static std::string convert(const JsonNode & node)
  260. {
  261. return node.String();
  262. }
  263. };
  264. template<>
  265. struct JsonConverter<bool>
  266. {
  267. static bool convert(const JsonNode & node)
  268. {
  269. return node.Bool();
  270. }
  271. };
  272. }
  273. template<typename Type>
  274. Type JsonNode::convertTo() const
  275. {
  276. return JsonDetail::JsonConverter<Type>::convert(*this);
  277. }
  278. VCMI_LIB_NAMESPACE_END