JsonNode.h 11 KB

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