JsonParser.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * JsonParser.cpp, 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. #include "StdInc.h"
  11. #include "JsonParser.h"
  12. #include "../TextOperations.h"
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. JsonParser::JsonParser(const char * inputString, size_t stringSize):
  15. input(inputString, stringSize),
  16. lineCount(1),
  17. lineStart(0),
  18. pos(0)
  19. {
  20. }
  21. JsonNode JsonParser::parse(const std::string & fileName)
  22. {
  23. JsonNode root;
  24. if (input.size() == 0)
  25. {
  26. error("File is empty", false);
  27. }
  28. else
  29. {
  30. if (!TextOperations::isValidUnicodeString(&input[0], input.size()))
  31. error("Not a valid UTF-8 file", false);
  32. extractValue(root);
  33. extractWhitespace(false);
  34. //Warn if there are any non-whitespace symbols left
  35. if (pos < input.size())
  36. error("Not all file was parsed!", true);
  37. }
  38. if (!errors.empty())
  39. {
  40. logMod->warn("File %s is not a valid JSON file!", fileName);
  41. logMod->warn(errors);
  42. }
  43. return root;
  44. }
  45. bool JsonParser::isValid()
  46. {
  47. return errors.empty();
  48. }
  49. bool JsonParser::extractSeparator()
  50. {
  51. if (!extractWhitespace())
  52. return false;
  53. if ( input[pos] !=':')
  54. return error("Separator expected");
  55. pos++;
  56. return true;
  57. }
  58. bool JsonParser::extractValue(JsonNode &node)
  59. {
  60. if (!extractWhitespace())
  61. return false;
  62. switch (input[pos])
  63. {
  64. case '\"': return extractString(node);
  65. case 'n' : return extractNull(node);
  66. case 't' : return extractTrue(node);
  67. case 'f' : return extractFalse(node);
  68. case '{' : return extractStruct(node);
  69. case '[' : return extractArray(node);
  70. case '-' : return extractFloat(node);
  71. default:
  72. {
  73. if (input[pos] >= '0' && input[pos] <= '9')
  74. return extractFloat(node);
  75. return error("Value expected!");
  76. }
  77. }
  78. }
  79. bool JsonParser::extractWhitespace(bool verbose)
  80. {
  81. while (true)
  82. {
  83. while(pos < input.size() && static_cast<ui8>(input[pos]) <= ' ')
  84. {
  85. if (input[pos] == '\n')
  86. {
  87. lineCount++;
  88. lineStart = pos+1;
  89. }
  90. pos++;
  91. }
  92. if (pos >= input.size() || input[pos] != '/')
  93. break;
  94. pos++;
  95. if (pos == input.size())
  96. break;
  97. if (input[pos] == '/')
  98. pos++;
  99. else
  100. error("Comments must consist of two slashes!", true);
  101. while (pos < input.size() && input[pos] != '\n')
  102. pos++;
  103. }
  104. if (pos >= input.size() && verbose)
  105. return error("Unexpected end of file!");
  106. return true;
  107. }
  108. bool JsonParser::extractEscaping(std::string &str)
  109. {
  110. switch(input[pos])
  111. {
  112. break; case '\"': str += '\"';
  113. break; case '\\': str += '\\';
  114. break; case 'b': str += '\b';
  115. break; case 'f': str += '\f';
  116. break; case 'n': str += '\n';
  117. break; case 'r': str += '\r';
  118. break; case 't': str += '\t';
  119. break; case '/': str += '/';
  120. break; default: return error("Unknown escape sequence!", true);
  121. }
  122. return true;
  123. }
  124. bool JsonParser::extractString(std::string &str)
  125. {
  126. if (input[pos] != '\"')
  127. return error("String expected!");
  128. pos++;
  129. size_t first = pos;
  130. while (pos != input.size())
  131. {
  132. if (input[pos] == '\"') // Correct end of string
  133. {
  134. str.append( &input[first], pos-first);
  135. pos++;
  136. return true;
  137. }
  138. if (input[pos] == '\\') // Escaping
  139. {
  140. str.append( &input[first], pos-first);
  141. pos++;
  142. if (pos == input.size())
  143. break;
  144. extractEscaping(str);
  145. first = pos + 1;
  146. }
  147. if (input[pos] == '\n') // end-of-line
  148. {
  149. str.append( &input[first], pos-first);
  150. return error("Closing quote not found!", true);
  151. }
  152. if(static_cast<unsigned char>(input[pos]) < ' ') // control character
  153. {
  154. str.append( &input[first], pos-first);
  155. first = pos+1;
  156. error("Illegal character in the string!", true);
  157. }
  158. pos++;
  159. }
  160. return error("Unterminated string!");
  161. }
  162. bool JsonParser::extractString(JsonNode &node)
  163. {
  164. std::string str;
  165. if (!extractString(str))
  166. return false;
  167. node.setType(JsonNode::JsonType::DATA_STRING);
  168. node.String() = str;
  169. return true;
  170. }
  171. bool JsonParser::extractLiteral(const std::string &literal)
  172. {
  173. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  174. {
  175. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  176. || (input[pos]>'A' && input[pos]<'Z')))
  177. pos++;
  178. return error("Unknown literal found", true);
  179. }
  180. pos += literal.size();
  181. return true;
  182. }
  183. bool JsonParser::extractNull(JsonNode &node)
  184. {
  185. if (!extractLiteral("null"))
  186. return false;
  187. node.clear();
  188. return true;
  189. }
  190. bool JsonParser::extractTrue(JsonNode &node)
  191. {
  192. if (!extractLiteral("true"))
  193. return false;
  194. node.Bool() = true;
  195. return true;
  196. }
  197. bool JsonParser::extractFalse(JsonNode &node)
  198. {
  199. if (!extractLiteral("false"))
  200. return false;
  201. node.Bool() = false;
  202. return true;
  203. }
  204. bool JsonParser::extractStruct(JsonNode &node)
  205. {
  206. node.setType(JsonNode::JsonType::DATA_STRUCT);
  207. pos++;
  208. if (!extractWhitespace())
  209. return false;
  210. //Empty struct found
  211. if (input[pos] == '}')
  212. {
  213. pos++;
  214. return true;
  215. }
  216. while (true)
  217. {
  218. if (!extractWhitespace())
  219. return false;
  220. std::string key;
  221. if (!extractString(key))
  222. return false;
  223. // split key string into actual key and meta-flags
  224. std::vector<std::string> keyAndFlags;
  225. boost::split(keyAndFlags, key, boost::is_any_of("#"));
  226. key = keyAndFlags[0];
  227. // check for unknown flags - helps with debugging
  228. std::vector<std::string> knownFlags = { "override" };
  229. for(int i = 1; i < keyAndFlags.size(); i++)
  230. {
  231. if(!vstd::contains(knownFlags, keyAndFlags[i]))
  232. error("Encountered unknown flag #" + keyAndFlags[i], true);
  233. }
  234. if (node.Struct().find(key) != node.Struct().end())
  235. error("Duplicate element encountered!", true);
  236. if (!extractSeparator())
  237. return false;
  238. if (!extractElement(node.Struct()[key], '}'))
  239. return false;
  240. // flags from key string belong to referenced element
  241. for(int i = 1; i < keyAndFlags.size(); i++)
  242. node.Struct()[key].flags.push_back(keyAndFlags[i]);
  243. if (input[pos] == '}')
  244. {
  245. pos++;
  246. return true;
  247. }
  248. }
  249. }
  250. bool JsonParser::extractArray(JsonNode &node)
  251. {
  252. pos++;
  253. node.setType(JsonNode::JsonType::DATA_VECTOR);
  254. if (!extractWhitespace())
  255. return false;
  256. //Empty array found
  257. if (input[pos] == ']')
  258. {
  259. pos++;
  260. return true;
  261. }
  262. while (true)
  263. {
  264. //NOTE: currently 50% of time is this vector resizing.
  265. //May be useful to use list during parsing and then swap() all items to vector
  266. node.Vector().resize(node.Vector().size()+1);
  267. if (!extractElement(node.Vector().back(), ']'))
  268. return false;
  269. if (input[pos] == ']')
  270. {
  271. pos++;
  272. return true;
  273. }
  274. }
  275. }
  276. bool JsonParser::extractElement(JsonNode &node, char terminator)
  277. {
  278. if (!extractValue(node))
  279. return false;
  280. if (!extractWhitespace())
  281. return false;
  282. bool comma = (input[pos] == ',');
  283. if (comma )
  284. {
  285. pos++;
  286. if (!extractWhitespace())
  287. return false;
  288. }
  289. if (input[pos] == terminator)
  290. {
  291. //FIXME: MOD COMPATIBILITY: Too many of these right now, re-enable later
  292. //if (comma)
  293. //error("Extra comma found!", true);
  294. return true;
  295. }
  296. if (!comma)
  297. error("Comma expected!", true);
  298. return true;
  299. }
  300. bool JsonParser::extractFloat(JsonNode &node)
  301. {
  302. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  303. bool negative=false;
  304. double result=0;
  305. si64 integerPart = 0;
  306. bool isFloat = false;
  307. if (input[pos] == '-')
  308. {
  309. pos++;
  310. negative = true;
  311. }
  312. if (input[pos] < '0' || input[pos] > '9')
  313. return error("Number expected!");
  314. //Extract integer part
  315. while (input[pos] >= '0' && input[pos] <= '9')
  316. {
  317. integerPart = integerPart*10+(input[pos]-'0');
  318. pos++;
  319. }
  320. result = static_cast<double>(integerPart);
  321. if (input[pos] == '.')
  322. {
  323. //extract fractional part
  324. isFloat = true;
  325. pos++;
  326. double fractMult = 0.1;
  327. if (input[pos] < '0' || input[pos] > '9')
  328. return error("Decimal part expected!");
  329. while (input[pos] >= '0' && input[pos] <= '9')
  330. {
  331. result = result + fractMult*(input[pos]-'0');
  332. fractMult /= 10;
  333. pos++;
  334. }
  335. }
  336. if(input[pos] == 'e')
  337. {
  338. //extract exponential part
  339. pos++;
  340. isFloat = true;
  341. bool powerNegative = false;
  342. double power = 0;
  343. if(input[pos] == '-')
  344. {
  345. pos++;
  346. powerNegative = true;
  347. }
  348. else if(input[pos] == '+')
  349. {
  350. pos++;
  351. }
  352. if (input[pos] < '0' || input[pos] > '9')
  353. return error("Exponential part expected!");
  354. while (input[pos] >= '0' && input[pos] <= '9')
  355. {
  356. power = power*10 + (input[pos]-'0');
  357. pos++;
  358. }
  359. if(powerNegative)
  360. power = -power;
  361. result *= std::pow(10, power);
  362. }
  363. if(isFloat)
  364. {
  365. if(negative)
  366. result = -result;
  367. node.setType(JsonNode::JsonType::DATA_FLOAT);
  368. node.Float() = result;
  369. }
  370. else
  371. {
  372. if(negative)
  373. integerPart = -integerPart;
  374. node.setType(JsonNode::JsonType::DATA_INTEGER);
  375. node.Integer() = integerPart;
  376. }
  377. return true;
  378. }
  379. bool JsonParser::error(const std::string &message, bool warning)
  380. {
  381. std::ostringstream stream;
  382. std::string type(warning?" warning: ":" error: ");
  383. stream << "At line " << lineCount << ", position "<<pos-lineStart
  384. << type << message <<"\n";
  385. errors += stream.str();
  386. return warning;
  387. }
  388. VCMI_LIB_NAMESPACE_END