2
0

JsonNode.h 11 KB

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