JsonNode.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. 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(const JsonPath & fileURI);
  57. explicit JsonNode(const std::string & modName, const JsonPath & fileURI);
  58. explicit JsonNode(const JsonPath & 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(const 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. bool isString() const;
  73. bool isVector() const;
  74. bool isStruct() const;
  75. /// true if node contains not-null data that cannot be extended via merging
  76. /// used for generating common base node from multiple nodes (e.g. bonuses)
  77. bool containsBaseData() const;
  78. bool isCompact() const;
  79. /// removes all data from node and sets type to null
  80. void clear();
  81. /// returns bool or bool equivalent of string value if 'success' is true, or false otherwise
  82. bool TryBoolFromString(bool & success) const;
  83. /// non-const accessors, node will change type on type mismatch
  84. bool & Bool();
  85. double & Float();
  86. si64 & Integer();
  87. std::string & String();
  88. JsonVector & Vector();
  89. JsonMap & Struct();
  90. /// const accessors, will cause assertion failure on type mismatch
  91. bool Bool() const;
  92. ///float and integer allowed
  93. double Float() const;
  94. ///only integer allowed
  95. si64 Integer() const;
  96. const std::string & String() const;
  97. const JsonVector & Vector() const;
  98. const JsonMap & Struct() const;
  99. /// returns resolved "json pointer" (string in format "/path/to/node")
  100. const JsonNode & resolvePointer(const std::string & jsonPointer) const;
  101. JsonNode & resolvePointer(const std::string & jsonPointer);
  102. /// convert json tree into specified type. Json tree must have same type as Type
  103. /// Valid types: bool, string, any numeric, map and vector
  104. /// example: convertTo< std::map< std::vector<int> > >();
  105. template<typename Type>
  106. Type convertTo() const;
  107. //operator [], for structs only - get child node by name
  108. JsonNode & operator[](const std::string & child);
  109. const JsonNode & operator[](const std::string & child) const;
  110. JsonNode & operator[](size_t child);
  111. const JsonNode & operator[](size_t child) const;
  112. std::string toJson(bool compact = false) const;
  113. template <typename Handler> void serialize(Handler &h, const int version)
  114. {
  115. h & meta;
  116. h & flags;
  117. h & type;
  118. switch(type)
  119. {
  120. case JsonType::DATA_NULL:
  121. break;
  122. case JsonType::DATA_BOOL:
  123. h & data.Bool;
  124. break;
  125. case JsonType::DATA_FLOAT:
  126. h & data.Float;
  127. break;
  128. case JsonType::DATA_STRING:
  129. h & data.String;
  130. break;
  131. case JsonType::DATA_VECTOR:
  132. h & data.Vector;
  133. break;
  134. case JsonType::DATA_STRUCT:
  135. h & data.Struct;
  136. break;
  137. case JsonType::DATA_INTEGER:
  138. h & data.Integer;
  139. break;
  140. }
  141. }
  142. };
  143. namespace JsonUtils
  144. {
  145. /**
  146. * @brief parse short bonus format, excluding type
  147. * @note sets duration to Permament
  148. */
  149. DLL_LINKAGE void parseTypedBonusShort(const JsonVector & source, const std::shared_ptr<Bonus> & dest);
  150. ///
  151. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonVector & ability_vec);
  152. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonNode & ability);
  153. DLL_LINKAGE std::shared_ptr<Bonus> parseBuildingBonus(const JsonNode & ability, const BuildingID & building, const std::string & description);
  154. DLL_LINKAGE bool parseBonus(const JsonNode & ability, Bonus * placement);
  155. DLL_LINKAGE std::shared_ptr<ILimiter> parseLimiter(const JsonNode & limiter);
  156. DLL_LINKAGE CSelector parseSelector(const JsonNode &ability);
  157. DLL_LINKAGE void resolveIdentifier(si32 & var, const JsonNode & node, const std::string & name);
  158. DLL_LINKAGE void resolveIdentifier(const JsonNode & node, si32 & var);
  159. DLL_LINKAGE void resolveAddInfo(CAddInfo & var, const JsonNode & node);
  160. /**
  161. * @brief recursively merges source into dest, replacing identical fields
  162. * struct : recursively calls this function
  163. * arrays : each entry will be merged recursively
  164. * values : value in source will replace value in dest
  165. * null : if value in source is present but set to null it will delete entry in dest
  166. * @note this function will destroy data in source
  167. */
  168. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source, bool ignoreOverride = false, bool copyMeta = false);
  169. /**
  170. * @brief recursively merges source into dest, replacing identical fields
  171. * struct : recursively calls this function
  172. * arrays : each entry will be merged recursively
  173. * values : value in source will replace value in dest
  174. * null : if value in source is present but set to null it will delete entry in dest
  175. * @note this function will preserve data stored in source by creating copy
  176. */
  177. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source, bool ignoreOverride = false, bool copyMeta = false);
  178. /** @brief recursively merges descendant into copy of base node
  179. * Result emulates inheritance semantic
  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(const std::vector<std::string> & files);
  201. DLL_LINKAGE JsonNode assembleFromFiles(const std::vector<std::string> & files, bool & isValid);
  202. /// This version loads all files with same name (overridden by mods)
  203. DLL_LINKAGE JsonNode assembleFromFiles(const 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, const std::string & schemaName);
  211. /// opposed to minimize, adds all missing, required entries that have default value
  212. DLL_LINKAGE void maximize(JsonNode & node, const 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, const std::string & schemaName, const 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(const 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(const 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. }
  322. VCMI_LIB_NAMESPACE_END