JsonNode.h 10 KB

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