JsonNode.h 11 KB

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