JsonNode.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const JsonNode &node);
  15. struct Bonus;
  16. class ResourceID;
  17. class DLL_LINKAGE JsonNode
  18. {
  19. public:
  20. enum JsonType
  21. {
  22. DATA_NULL,
  23. DATA_BOOL,
  24. DATA_FLOAT,
  25. DATA_STRING,
  26. DATA_VECTOR,
  27. DATA_STRUCT
  28. };
  29. private:
  30. union JsonData
  31. {
  32. bool Bool;
  33. double Float;
  34. std::string* String;
  35. JsonVector* Vector;
  36. JsonMap* Struct;
  37. };
  38. JsonType type;
  39. JsonData data;
  40. public:
  41. /// free to use metadata field
  42. std::string meta;
  43. //Create empty node
  44. JsonNode(JsonType Type = DATA_NULL);
  45. //Create tree from Json-formatted input
  46. explicit JsonNode(const char * data, size_t datasize);
  47. //Create tree from JSON file
  48. explicit JsonNode(ResourceID && fileURI);
  49. //Copy c-tor
  50. JsonNode(const JsonNode &copy);
  51. ~JsonNode();
  52. void swap(JsonNode &b);
  53. JsonNode& operator =(JsonNode node);
  54. bool operator == (const JsonNode &other) const;
  55. bool operator != (const JsonNode &other) const;
  56. void setMeta(std::string metadata, bool recursive = true);
  57. /// Convert node to another type. Converting to nullptr will clear all data
  58. void setType(JsonType Type);
  59. JsonType getType() const;
  60. bool isNull() const;
  61. /// removes all data from node and sets type to null
  62. void clear();
  63. /// non-const accessors, node will change type on type mismatch
  64. bool & Bool();
  65. double & Float();
  66. std::string & String();
  67. JsonVector & Vector();
  68. JsonMap & Struct();
  69. /// const accessors, will cause assertion failure on type mismatch
  70. const bool & Bool() const;
  71. const double & Float() const;
  72. const std::string & String() const;
  73. const JsonVector & Vector() const;
  74. const JsonMap & Struct() const;
  75. /// returns resolved "json pointer" (string in format "/path/to/node")
  76. const JsonNode & resolvePointer(const std::string & jsonPointer) const;
  77. JsonNode & resolvePointer(const std::string & jsonPointer);
  78. /// convert json tree into specified type. Json tree must have same type as Type
  79. /// Valid types: bool, string, any numeric, map and vector
  80. /// example: convertTo< std::map< std::vector<int> > >();
  81. template<typename Type>
  82. Type convertTo() const;
  83. //operator [], for structs only - get child node by name
  84. JsonNode & operator[](std::string child);
  85. const JsonNode & operator[](std::string child) const;
  86. template <typename Handler> void serialize(Handler &h, const int version)
  87. {
  88. h & meta;
  89. // simple saving - save json in its string interpretation
  90. if (h.saving)
  91. {
  92. std::ostringstream stream;
  93. stream << *this;
  94. std::string str = stream.str();
  95. h & str;
  96. }
  97. else
  98. {
  99. std::string str;
  100. h & str;
  101. JsonNode(str.c_str(), str.size()).swap(*this);
  102. }
  103. }
  104. };
  105. namespace JsonUtils
  106. {
  107. /**
  108. * @brief parse short bonus format, excluding type
  109. * @note sets duration to Permament
  110. */
  111. DLL_LINKAGE void parseTypedBonusShort(const JsonVector &source, Bonus *dest);
  112. ///
  113. DLL_LINKAGE Bonus * parseBonus (const JsonVector &ability_vec);
  114. DLL_LINKAGE Bonus * parseBonus (const JsonNode &bonus);
  115. DLL_LINKAGE void unparseBonus (JsonNode &node, const Bonus * bonus);
  116. DLL_LINKAGE void resolveIdentifier (si32 &var, const JsonNode &node, std::string name);
  117. DLL_LINKAGE void resolveIdentifier (const JsonNode &node, si32 &var);
  118. /**
  119. * @brief recursivly merges source into dest, replacing identical fields
  120. * struct : recursively calls this function
  121. * arrays : each entry will be merged recursively
  122. * values : value in source will replace value in dest
  123. * null : if value in source is present but set to null it will delete entry in dest
  124. * @note this function will destroy data in source
  125. */
  126. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  127. /**
  128. * @brief recursivly merges source into dest, replacing identical fields
  129. * struct : recursively calls this function
  130. * arrays : each entry will be merged recursively
  131. * values : value in source will replace value in dest
  132. * null : if value in source is present but set to null it will delete entry in dest
  133. * @note this function will preserve data stored in source by creating copy
  134. */
  135. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  136. /**
  137. * @brief generate one Json structure from multiple files
  138. * @param files - list of filenames with parts of json structure
  139. */
  140. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  141. /// This version loads all files with same name (overriden by mods)
  142. DLL_LINKAGE JsonNode assembleFromFiles(std::string filename);
  143. /**
  144. * @brief removes all nodes that are identical to default entry in schema
  145. * @param node - JsonNode to minimize
  146. * @param schemaName - name of schema to use
  147. * @note for minimizing data must be valid against given schema
  148. */
  149. DLL_LINKAGE void minimize(JsonNode & node, std::string schemaName);
  150. /// opposed to minimize, adds all missing, required entries that have default value
  151. DLL_LINKAGE void maximize(JsonNode & node, std::string schemaName);
  152. /**
  153. * @brief validate node against specified schema
  154. * @param node - JsonNode to check
  155. * @param schemaName - name of schema to use
  156. * @param dataName - some way to identify data (printed in console in case of errors)
  157. * @returns true if data in node fully compilant with schema
  158. */
  159. DLL_LINKAGE bool validate(const JsonNode & node, std::string schemaName, std::string dataName);
  160. /// get schema by json URI: vcmi:<name of file in schemas directory>#<entry in file, optional>
  161. /// example: schema "vcmi:settings" is used to check user settings
  162. DLL_LINKAGE const JsonNode & getSchema(std::string URI);
  163. }
  164. //////////////////////////////////////////////////////////////////////////////////////////////////////
  165. // End of public section of the file. Anything below should be only used internally in JsonNode.cpp //
  166. //////////////////////////////////////////////////////////////////////////////////////////////////////
  167. namespace JsonDetail
  168. {
  169. // convertion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  170. template <typename T, int arithm>
  171. struct JsonConvImpl;
  172. template <typename T>
  173. struct JsonConvImpl<T, 1>
  174. {
  175. static T convertImpl(const JsonNode & node)
  176. {
  177. return T((int)node.Float());
  178. }
  179. };
  180. template <typename T>
  181. struct JsonConvImpl<T, 0>
  182. {
  183. static T convertImpl(const JsonNode & node)
  184. {
  185. return node.Float();
  186. }
  187. };
  188. template<typename Type>
  189. struct JsonConverter
  190. {
  191. static Type convert(const JsonNode & node)
  192. {
  193. ///this should be triggered only for numeric types and enums
  194. static_assert(boost::mpl::or_<std::is_arithmetic<Type>, std::is_enum<Type>, boost::is_class<Type> >::value, "Unsupported type for JsonNode::convertTo()!");
  195. return JsonConvImpl<Type, boost::mpl::or_<std::is_enum<Type>, boost::is_class<Type> >::value >::convertImpl(node);
  196. }
  197. };
  198. template<typename Type>
  199. struct JsonConverter<std::map<std::string, Type> >
  200. {
  201. static std::map<std::string, Type> convert(const JsonNode & node)
  202. {
  203. std::map<std::string, Type> ret;
  204. BOOST_FOREACH(auto entry, node.Struct())
  205. {
  206. ret.insert(entry.first, entry.second.convertTo<Type>());
  207. }
  208. return ret;
  209. }
  210. };
  211. template<typename Type>
  212. struct JsonConverter<std::set<Type> >
  213. {
  214. static std::set<Type> convert(const JsonNode & node)
  215. {
  216. std::set<Type> ret;
  217. BOOST_FOREACH(auto entry, node.Vector())
  218. {
  219. ret.insert(entry.convertTo<Type>());
  220. }
  221. return ret;
  222. }
  223. };
  224. template<typename Type>
  225. struct JsonConverter<std::vector<Type> >
  226. {
  227. static std::vector<Type> convert(const JsonNode & node)
  228. {
  229. std::vector<Type> ret;
  230. BOOST_FOREACH(auto entry, node.Vector())
  231. {
  232. ret.push_back(entry.convertTo<Type>());
  233. }
  234. return ret;
  235. }
  236. };
  237. template<>
  238. struct JsonConverter<std::string>
  239. {
  240. static std::string convert(const JsonNode & node)
  241. {
  242. return node.String();
  243. }
  244. };
  245. template<>
  246. struct JsonConverter<bool>
  247. {
  248. static bool convert(const JsonNode & node)
  249. {
  250. return node.Bool();
  251. }
  252. };
  253. class JsonWriter
  254. {
  255. //prefix for each line (tabulation)
  256. std::string prefix;
  257. std::ostream &out;
  258. public:
  259. template<typename Iterator>
  260. void writeContainer(Iterator begin, Iterator end);
  261. void writeEntry(JsonMap::const_iterator entry);
  262. void writeEntry(JsonVector::const_iterator entry);
  263. void writeString(const std::string &string);
  264. void writeNode(const JsonNode &node);
  265. JsonWriter(std::ostream &output, const JsonNode &node);
  266. };
  267. //Tiny string class that uses const char* as data for speed, members are private
  268. //for ease of debugging and some compatibility with std::string
  269. class constString
  270. {
  271. const char *data;
  272. const size_t datasize;
  273. public:
  274. constString(const char * inputString, size_t stringSize):
  275. data(inputString),
  276. datasize(stringSize)
  277. {
  278. }
  279. inline size_t size() const
  280. {
  281. return datasize;
  282. };
  283. inline const char& operator[] (size_t position)
  284. {
  285. assert (position < datasize);
  286. return data[position];
  287. }
  288. };
  289. //Internal class for string -> JsonNode conversion
  290. class JsonParser
  291. {
  292. std::string errors; // Contains description of all encountered errors
  293. constString input; // Input data
  294. ui32 lineCount; // Currently parsed line, starting from 1
  295. size_t lineStart; // Position of current line start
  296. size_t pos; // Current position of parser
  297. //Helpers
  298. bool extractEscaping(std::string &str);
  299. bool extractLiteral(const std::string &literal);
  300. bool extractString(std::string &string);
  301. bool extractWhitespace(bool verbose = true);
  302. bool extractSeparator();
  303. bool extractElement(JsonNode &node, char terminator);
  304. //Methods for extracting JSON data
  305. bool extractArray(JsonNode &node);
  306. bool extractFalse(JsonNode &node);
  307. bool extractFloat(JsonNode &node);
  308. bool extractNull(JsonNode &node);
  309. bool extractString(JsonNode &node);
  310. bool extractStruct(JsonNode &node);
  311. bool extractTrue(JsonNode &node);
  312. bool extractValue(JsonNode &node);
  313. //Add error\warning message to list
  314. bool error(const std::string &message, bool warning=false);
  315. public:
  316. JsonParser(const char * inputString, size_t stringSize);
  317. /// do actual parsing. filename is name of file that will printed to console if any errors were found
  318. JsonNode parse(std::string fileName);
  319. };
  320. //Internal class for Json validation. Mostly compilant with json-schema v4 draft
  321. class JsonValidator
  322. {
  323. // path from root node to current one.
  324. // JsonNode is used as variant - either string (name of node) or as float (index in list)
  325. std::vector<JsonNode> currentPath;
  326. // Stack of used schemas. Last schema is the one used currently.
  327. // May contain multiple items in case if remote references were found
  328. std::vector<std::string> usedSchemas;
  329. /// helpers for other validation methods
  330. std::string validateVectorItem(const JsonVector items, const JsonNode & schema, const JsonNode & additional, size_t index);
  331. std::string validateStructItem(const JsonNode &node, const JsonNode &schema, const JsonNode & additional, std::string nodeName);
  332. std::string validateEnum(const JsonNode &node, const JsonVector &enumeration);
  333. std::string validateNodeType(const JsonNode &node, const JsonNode &schema);
  334. std::string validatesSchemaList(const JsonNode &node, const JsonNode &schemas, std::string errorMsg, std::function<bool(size_t)> isValid);
  335. /// contains all type-independent checks
  336. std::string validateNode(const JsonNode &node, const JsonNode &schema);
  337. /// type-specific checks
  338. std::string validateVector(const JsonNode &node, const JsonNode &schema);
  339. std::string validateStruct(const JsonNode &node, const JsonNode &schema);
  340. std::string validateString(const JsonNode &node, const JsonNode &schema);
  341. std::string validateNumber(const JsonNode &node, const JsonNode &schema);
  342. /// validation of root node of both schema and input data
  343. std::string validateRoot(const JsonNode &node, std::string schemaName);
  344. /// add error message to list and return false
  345. std::string fail(const std::string &message);
  346. public:
  347. /// returns true if parsed data is fully compilant with schema
  348. bool validate(const JsonNode &root, std::string schemaName, std::string name);
  349. };
  350. } // namespace JsonDetail
  351. template<typename Type>
  352. Type JsonNode::convertTo() const
  353. {
  354. return JsonDetail::JsonConverter<Type>::convert(*this);
  355. }