JsonNode.h 10 KB

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