JsonNode.h 12 KB

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