JsonNode.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 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. std::string toJson(bool compact = false) const;
  112. template <typename Handler> void serialize(Handler &h, const int version)
  113. {
  114. h & meta;
  115. h & flags;
  116. h & type;
  117. switch(type)
  118. {
  119. case JsonType::DATA_NULL:
  120. break;
  121. case JsonType::DATA_BOOL:
  122. h & data.Bool;
  123. break;
  124. case JsonType::DATA_FLOAT:
  125. h & data.Float;
  126. break;
  127. case JsonType::DATA_STRING:
  128. h & data.String;
  129. break;
  130. case JsonType::DATA_VECTOR:
  131. h & data.Vector;
  132. break;
  133. case JsonType::DATA_STRUCT:
  134. h & data.Struct;
  135. break;
  136. case JsonType::DATA_INTEGER:
  137. h & data.Integer;
  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, const 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, const BuildingID & building, const 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 CSelector parseSelector(const JsonNode &ability);
  156. DLL_LINKAGE void resolveIdentifier(si32 & var, const JsonNode & node, const std::string & name);
  157. DLL_LINKAGE void resolveIdentifier(const JsonNode & node, si32 & var);
  158. DLL_LINKAGE void resolveAddInfo(CAddInfo & var, const JsonNode & node);
  159. /**
  160. * @brief recursively merges source into dest, replacing identical fields
  161. * struct : recursively calls this function
  162. * arrays : each entry will be merged recursively
  163. * values : value in source will replace value in dest
  164. * null : if value in source is present but set to null it will delete entry in dest
  165. * @note this function will destroy data in source
  166. */
  167. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source, bool ignoreOverride = false, bool copyMeta = false);
  168. /**
  169. * @brief recursively merges source into dest, replacing identical fields
  170. * struct : recursively calls this function
  171. * arrays : each entry will be merged recursively
  172. * values : value in source will replace value in dest
  173. * null : if value in source is present but set to null it will delete entry in dest
  174. * @note this function will preserve data stored in source by creating copy
  175. */
  176. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source, bool ignoreOverride = false, bool copyMeta = false);
  177. /** @brief recursively merges descendant into copy of base node
  178. * Result emulates inheritance semantic
  179. */
  180. DLL_LINKAGE void inherit(JsonNode & descendant, const JsonNode & base);
  181. /**
  182. * @brief construct node representing the common structure of input nodes
  183. * @param pruneEmpty - omit common properties whose intersection is empty
  184. * different types: null
  185. * struct: recursive intersect on common properties
  186. * other: input if equal, null otherwise
  187. */
  188. DLL_LINKAGE JsonNode intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty = true);
  189. DLL_LINKAGE JsonNode intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty = true);
  190. /**
  191. * @brief construct node representing the difference "node - base"
  192. * merging difference with base gives node
  193. */
  194. DLL_LINKAGE JsonNode difference(const JsonNode & node, const JsonNode & base);
  195. /**
  196. * @brief generate one Json structure from multiple files
  197. * @param files - list of filenames with parts of json structure
  198. */
  199. DLL_LINKAGE JsonNode assembleFromFiles(const std::vector<std::string> & files);
  200. DLL_LINKAGE JsonNode assembleFromFiles(const std::vector<std::string> & files, bool & isValid);
  201. /// This version loads all files with same name (overridden by mods)
  202. DLL_LINKAGE JsonNode assembleFromFiles(const std::string & filename);
  203. /**
  204. * @brief removes all nodes that are identical to default entry in schema
  205. * @param node - JsonNode to minimize
  206. * @param schemaName - name of schema to use
  207. * @note for minimizing data must be valid against given schema
  208. */
  209. DLL_LINKAGE void minimize(JsonNode & node, const std::string & schemaName);
  210. /// opposed to minimize, adds all missing, required entries that have default value
  211. DLL_LINKAGE void maximize(JsonNode & node, const std::string & schemaName);
  212. /**
  213. * @brief validate node against specified schema
  214. * @param node - JsonNode to check
  215. * @param schemaName - name of schema to use
  216. * @param dataName - some way to identify data (printed in console in case of errors)
  217. * @returns true if data in node fully compilant with schema
  218. */
  219. DLL_LINKAGE bool validate(const JsonNode & node, const std::string & schemaName, const std::string & dataName);
  220. /// get schema by json URI: vcmi:<name of file in schemas directory>#<entry in file, optional>
  221. /// example: schema "vcmi:settings" is used to check user settings
  222. DLL_LINKAGE const JsonNode & getSchema(const std::string & URI);
  223. /// for easy construction of JsonNodes; helps with inserting primitives into vector node
  224. DLL_LINKAGE JsonNode boolNode(bool value);
  225. DLL_LINKAGE JsonNode floatNode(double value);
  226. DLL_LINKAGE JsonNode stringNode(const std::string & value);
  227. DLL_LINKAGE JsonNode intNode(si64 value);
  228. }
  229. namespace JsonDetail
  230. {
  231. // conversion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  232. template <typename T, int arithm>
  233. struct JsonConvImpl;
  234. template <typename T>
  235. struct JsonConvImpl<T, 1>
  236. {
  237. static T convertImpl(const JsonNode & node)
  238. {
  239. return T((int)node.Float());
  240. }
  241. };
  242. template <typename T>
  243. struct JsonConvImpl<T, 0>
  244. {
  245. static T convertImpl(const JsonNode & node)
  246. {
  247. return T(node.Float());
  248. }
  249. };
  250. template<typename Type>
  251. struct JsonConverter
  252. {
  253. static Type convert(const JsonNode & node)
  254. {
  255. ///this should be triggered only for numeric types and enums
  256. static_assert(boost::mpl::or_<std::is_arithmetic<Type>, std::is_enum<Type>, boost::is_class<Type> >::value, "Unsupported type for JsonNode::convertTo()!");
  257. return JsonConvImpl<Type, boost::mpl::or_<std::is_enum<Type>, boost::is_class<Type> >::value >::convertImpl(node);
  258. }
  259. };
  260. template<typename Type>
  261. struct JsonConverter<std::map<std::string, Type> >
  262. {
  263. static std::map<std::string, Type> convert(const JsonNode & node)
  264. {
  265. std::map<std::string, Type> ret;
  266. for (const JsonMap::value_type & entry : node.Struct())
  267. {
  268. ret.insert(entry.first, entry.second.convertTo<Type>());
  269. }
  270. return ret;
  271. }
  272. };
  273. template<typename Type>
  274. struct JsonConverter<std::set<Type> >
  275. {
  276. static std::set<Type> convert(const JsonNode & node)
  277. {
  278. std::set<Type> ret;
  279. for(const JsonVector::value_type & entry : node.Vector())
  280. {
  281. ret.insert(entry.convertTo<Type>());
  282. }
  283. return ret;
  284. }
  285. };
  286. template<typename Type>
  287. struct JsonConverter<std::vector<Type> >
  288. {
  289. static std::vector<Type> convert(const JsonNode & node)
  290. {
  291. std::vector<Type> ret;
  292. for (const JsonVector::value_type & entry: node.Vector())
  293. {
  294. ret.push_back(entry.convertTo<Type>());
  295. }
  296. return ret;
  297. }
  298. };
  299. template<>
  300. struct JsonConverter<std::string>
  301. {
  302. static std::string convert(const JsonNode & node)
  303. {
  304. return node.String();
  305. }
  306. };
  307. template<>
  308. struct JsonConverter<bool>
  309. {
  310. static bool convert(const JsonNode & node)
  311. {
  312. return node.Bool();
  313. }
  314. };
  315. }
  316. template<typename Type>
  317. Type JsonNode::convertTo() const
  318. {
  319. return JsonDetail::JsonConverter<Type>::convert(*this);
  320. }
  321. VCMI_LIB_NAMESPACE_END