JsonParser.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. bool overrideFlag = false;
  221. std::string key;
  222. if (!extractString(key))
  223. return false;
  224. if (key.find('#') != std::string::npos)
  225. {
  226. // split key string into actual key and meta-flags
  227. std::vector<std::string> keyAndFlags;
  228. boost::split(keyAndFlags, key, boost::is_any_of("#"));
  229. key = keyAndFlags[0];
  230. for(int i = 1; i < keyAndFlags.size(); i++)
  231. {
  232. if (keyAndFlags[i] == "override")
  233. overrideFlag = true;
  234. else
  235. error("Encountered unknown flag #" + keyAndFlags[i], true);
  236. }
  237. }
  238. if (node.Struct().find(key) != node.Struct().end())
  239. error("Duplicate element encountered!", true);
  240. if (!extractSeparator())
  241. return false;
  242. if (!extractElement(node.Struct()[key], '}'))
  243. return false;
  244. node.Struct()[key].setOverrideFlag(overrideFlag);
  245. if (input[pos] == '}')
  246. {
  247. pos++;
  248. return true;
  249. }
  250. }
  251. }
  252. bool JsonParser::extractArray(JsonNode &node)
  253. {
  254. pos++;
  255. node.setType(JsonNode::JsonType::DATA_VECTOR);
  256. if (!extractWhitespace())
  257. return false;
  258. //Empty array found
  259. if (input[pos] == ']')
  260. {
  261. pos++;
  262. return true;
  263. }
  264. while (true)
  265. {
  266. //NOTE: currently 50% of time is this vector resizing.
  267. //May be useful to use list during parsing and then swap() all items to vector
  268. node.Vector().resize(node.Vector().size()+1);
  269. if (!extractElement(node.Vector().back(), ']'))
  270. return false;
  271. if (input[pos] == ']')
  272. {
  273. pos++;
  274. return true;
  275. }
  276. }
  277. }
  278. bool JsonParser::extractElement(JsonNode &node, char terminator)
  279. {
  280. if (!extractValue(node))
  281. return false;
  282. if (!extractWhitespace())
  283. return false;
  284. bool comma = (input[pos] == ',');
  285. if (comma )
  286. {
  287. pos++;
  288. if (!extractWhitespace())
  289. return false;
  290. }
  291. if (input[pos] == terminator)
  292. {
  293. //FIXME: MOD COMPATIBILITY: Too many of these right now, re-enable later
  294. //if (comma)
  295. //error("Extra comma found!", true);
  296. return true;
  297. }
  298. if (!comma)
  299. error("Comma expected!", true);
  300. return true;
  301. }
  302. bool JsonParser::extractFloat(JsonNode &node)
  303. {
  304. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  305. bool negative=false;
  306. double result=0;
  307. si64 integerPart = 0;
  308. bool isFloat = false;
  309. if (input[pos] == '-')
  310. {
  311. pos++;
  312. negative = true;
  313. }
  314. if (input[pos] < '0' || input[pos] > '9')
  315. return error("Number expected!");
  316. //Extract integer part
  317. while (input[pos] >= '0' && input[pos] <= '9')
  318. {
  319. integerPart = integerPart*10+(input[pos]-'0');
  320. pos++;
  321. }
  322. result = static_cast<double>(integerPart);
  323. if (input[pos] == '.')
  324. {
  325. //extract fractional part
  326. isFloat = true;
  327. pos++;
  328. double fractMult = 0.1;
  329. if (input[pos] < '0' || input[pos] > '9')
  330. return error("Decimal part expected!");
  331. while (input[pos] >= '0' && input[pos] <= '9')
  332. {
  333. result = result + fractMult*(input[pos]-'0');
  334. fractMult /= 10;
  335. pos++;
  336. }
  337. }
  338. if(input[pos] == 'e')
  339. {
  340. //extract exponential part
  341. pos++;
  342. isFloat = true;
  343. bool powerNegative = false;
  344. double power = 0;
  345. if(input[pos] == '-')
  346. {
  347. pos++;
  348. powerNegative = true;
  349. }
  350. else if(input[pos] == '+')
  351. {
  352. pos++;
  353. }
  354. if (input[pos] < '0' || input[pos] > '9')
  355. return error("Exponential part expected!");
  356. while (input[pos] >= '0' && input[pos] <= '9')
  357. {
  358. power = power*10 + (input[pos]-'0');
  359. pos++;
  360. }
  361. if(powerNegative)
  362. power = -power;
  363. result *= std::pow(10, power);
  364. }
  365. if(isFloat)
  366. {
  367. if(negative)
  368. result = -result;
  369. node.setType(JsonNode::JsonType::DATA_FLOAT);
  370. node.Float() = result;
  371. }
  372. else
  373. {
  374. if(negative)
  375. integerPart = -integerPart;
  376. node.setType(JsonNode::JsonType::DATA_INTEGER);
  377. node.Integer() = integerPart;
  378. }
  379. return true;
  380. }
  381. bool JsonParser::error(const std::string &message, bool warning)
  382. {
  383. std::ostringstream stream;
  384. std::string type(warning?" warning: ":" error: ");
  385. stream << "At line " << lineCount << ", position "<<pos-lineStart
  386. << type << message <<"\n";
  387. errors += stream.str();
  388. return warning;
  389. }
  390. VCMI_LIB_NAMESPACE_END