JsonNode.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. //non-const accessors, node will change type on type mismatch
  59. bool & Bool();
  60. double & Float();
  61. std::string & String();
  62. JsonVector & Vector();
  63. JsonMap & Struct();
  64. //const accessors, will cause assertion failure on type mismatch
  65. const bool & Bool() const;
  66. const double & Float() const;
  67. const std::string & String() const;
  68. const JsonVector & Vector() const;
  69. const JsonMap & Struct() const;
  70. /// convert json tree into specified type. Json tree must have same type as Type
  71. /// Valid types: bool, string, any numeric, map and vector
  72. /// example: convertTo< std::map< std::vector<int> > >();
  73. template<typename Type>
  74. Type convertTo() const;
  75. //operator [], for structs only - get child node by name
  76. JsonNode & operator[](std::string child);
  77. const JsonNode & operator[](std::string child) const;
  78. template <typename Handler> void serialize(Handler &h, const int version)
  79. {
  80. // simple saving - save json in its string interpretation
  81. if (h.saving)
  82. {
  83. std::ostringstream stream;
  84. stream << *this;
  85. std::string str = stream.str();
  86. h & str;
  87. }
  88. else
  89. {
  90. std::string str;
  91. h & str;
  92. JsonNode(str.c_str(), str.size()).swap(*this);
  93. }
  94. }
  95. };
  96. namespace JsonUtils
  97. {
  98. /**
  99. * @brief parse short bonus format, excluding type
  100. * @note sets duration to Permament
  101. */
  102. DLL_LINKAGE void parseTypedBonusShort(const JsonVector &source, Bonus *dest);
  103. ///
  104. DLL_LINKAGE Bonus * parseBonus (const JsonVector &ability_vec);
  105. DLL_LINKAGE Bonus * parseBonus (const JsonNode &bonus);
  106. DLL_LINKAGE void unparseBonus (JsonNode &node, const Bonus * bonus);
  107. DLL_LINKAGE void resolveIdentifier (si32 &var, const JsonNode &node, std::string name);
  108. DLL_LINKAGE void resolveIdentifier (const JsonNode &node, si32 &var);
  109. /**
  110. * @brief recursivly merges source into dest, replacing identical fields
  111. * struct : recursively calls this function
  112. * arrays : each entry will be merged recursively
  113. * values : value in source will replace value in dest
  114. * null : if value in source is present but set to null it will delete entry in dest
  115. * @note this function will destroy data in source
  116. */
  117. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  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 preserve data stored in source by creating copy
  125. */
  126. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  127. /**
  128. * @brief generate one Json structure from multiple files
  129. * @param files - list of filenames with parts of json structure
  130. */
  131. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  132. /// removes all nodes that are identical to default entry in schema
  133. DLL_LINKAGE void minimize(JsonNode & node, const JsonNode& schema);
  134. /// check schema
  135. DLL_LINKAGE void validate(JsonNode & node, const JsonNode& schema);
  136. }
  137. //////////////////////////////////////////////////////////////////////////////////////////////////////
  138. // End of public section of the file. Anything below should be only used internally in JsonNode.cpp //
  139. //////////////////////////////////////////////////////////////////////////////////////////////////////
  140. namespace JsonDetail
  141. {
  142. // convertion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  143. template <typename T, int arithm>
  144. struct JsonConvImpl;
  145. template <typename T>
  146. struct JsonConvImpl<T, 1>
  147. {
  148. static T convertImpl(const JsonNode & node)
  149. {
  150. return T((int)node.Float());
  151. }
  152. };
  153. template <typename T>
  154. struct JsonConvImpl<T, 0>
  155. {
  156. static T convertImpl(const JsonNode & node)
  157. {
  158. return node.Float();
  159. }
  160. };
  161. template<typename Type>
  162. struct JsonConverter
  163. {
  164. static Type convert(const JsonNode & node)
  165. {
  166. ///this should be triggered only for numeric types and enums
  167. static_assert(boost::mpl::or_<std::is_arithmetic<Type>, std::is_enum<Type>, boost::is_class<Type> >::value, "Unsupported type for JsonNode::convertTo()!");
  168. return JsonConvImpl<Type, boost::mpl::or_<std::is_enum<Type>, boost::is_class<Type> >::value >::convertImpl(node);
  169. }
  170. };
  171. template<typename Type>
  172. struct JsonConverter<std::map<std::string, Type> >
  173. {
  174. static std::map<std::string, Type> convert(const JsonNode & node)
  175. {
  176. std::map<std::string, Type> ret;
  177. BOOST_FOREACH(auto entry, node.Struct())
  178. {
  179. ret.insert(entry.first, entry.second.convertTo<Type>());
  180. }
  181. return ret;
  182. }
  183. };
  184. template<typename Type>
  185. struct JsonConverter<std::set<Type> >
  186. {
  187. static std::set<Type> convert(const JsonNode & node)
  188. {
  189. std::set<Type> ret;
  190. BOOST_FOREACH(auto entry, node.Vector())
  191. {
  192. ret.insert(entry.convertTo<Type>());
  193. }
  194. return ret;
  195. }
  196. };
  197. template<typename Type>
  198. struct JsonConverter<std::vector<Type> >
  199. {
  200. static std::vector<Type> convert(const JsonNode & node)
  201. {
  202. std::vector<Type> ret;
  203. BOOST_FOREACH(auto entry, node.Vector())
  204. {
  205. ret.push_back(entry.convertTo<Type>());
  206. }
  207. return ret;
  208. }
  209. };
  210. template<>
  211. struct JsonConverter<std::string>
  212. {
  213. static std::string convert(const JsonNode & node)
  214. {
  215. return node.String();
  216. }
  217. };
  218. template<>
  219. struct JsonConverter<bool>
  220. {
  221. static bool convert(const JsonNode & node)
  222. {
  223. return node.Bool();
  224. }
  225. };
  226. class JsonWriter
  227. {
  228. //prefix for each line (tabulation)
  229. std::string prefix;
  230. std::ostream &out;
  231. public:
  232. template<typename Iterator>
  233. void writeContainer(Iterator begin, Iterator end);
  234. void writeEntry(JsonMap::const_iterator entry);
  235. void writeEntry(JsonVector::const_iterator entry);
  236. void writeString(const std::string &string);
  237. void writeNode(const JsonNode &node);
  238. JsonWriter(std::ostream &output, const JsonNode &node);
  239. };
  240. //Tiny string class that uses const char* as data for speed, members are private
  241. //for ease of debugging and some compatibility with std::string
  242. class constString
  243. {
  244. const char *data;
  245. const size_t datasize;
  246. public:
  247. constString(const char * inputString, size_t stringSize):
  248. data(inputString),
  249. datasize(stringSize)
  250. {
  251. }
  252. inline size_t size() const
  253. {
  254. return datasize;
  255. };
  256. inline const char& operator[] (size_t position)
  257. {
  258. assert (position < datasize);
  259. return data[position];
  260. }
  261. };
  262. //Internal class for string -> JsonNode conversion
  263. class JsonParser
  264. {
  265. std::string errors; // Contains description of all encountered errors
  266. constString input; // Input data
  267. ui32 lineCount; // Currently parsed line, starting from 1
  268. size_t lineStart; // Position of current line start
  269. size_t pos; // Current position of parser
  270. //Helpers
  271. bool extractEscaping(std::string &str);
  272. bool extractLiteral(const std::string &literal);
  273. bool extractString(std::string &string);
  274. bool extractWhitespace(bool verbose = true);
  275. bool extractSeparator();
  276. bool extractElement(JsonNode &node, char terminator);
  277. //Methods for extracting JSON data
  278. bool extractArray(JsonNode &node);
  279. bool extractFalse(JsonNode &node);
  280. bool extractFloat(JsonNode &node);
  281. bool extractNull(JsonNode &node);
  282. bool extractString(JsonNode &node);
  283. bool extractStruct(JsonNode &node);
  284. bool extractTrue(JsonNode &node);
  285. bool extractValue(JsonNode &node);
  286. //Add error\warning message to list
  287. bool error(const std::string &message, bool warning=false);
  288. public:
  289. JsonParser(const char * inputString, size_t stringSize, JsonNode &root);
  290. };
  291. //Internal class for Json validation, used automaticaly in JsonNode constructor. Behaviour:
  292. // - "schema" entry from root node is used for validation and will be removed
  293. // - any missing entries will be replaced with default value from schema (if present)
  294. // - if entry uses different type than defined in schema it will be removed
  295. // - entries nod described in schema will be kept unchanged
  296. class JsonValidator
  297. {
  298. std::string errors; // Contains description of all encountered errors
  299. std::list<std::string> currentPath; // path from root node to current one
  300. bool minimize;
  301. bool validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type);
  302. bool validateSchema(JsonNode::JsonType &type, const JsonNode &schema);
  303. bool validateNode(JsonNode &node, const JsonNode &schema, const std::string &name);
  304. bool validateItems(JsonNode &node, const JsonNode &schema);
  305. bool validateProperties(JsonNode &node, const JsonNode &schema);
  306. bool addMessage(const std::string &message);
  307. public:
  308. // validate node with "schema" entry
  309. JsonValidator(JsonNode &root, bool minimize=false);
  310. // validate with external schema
  311. JsonValidator(JsonNode &root, const JsonNode &schema, bool minimize=false);
  312. };
  313. } // namespace JsonDetail
  314. template<typename Type>
  315. Type JsonNode::convertTo() const
  316. {
  317. return JsonDetail::JsonConverter<Type>::convert(*this);
  318. }