JsonNode.h 10 KB

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