JsonDetail.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. /*
  2. * JsonDetail.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 "JsonDetail.h"
  12. #include "VCMI_Lib.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "CModHandler.h"
  15. #include "filesystem/Filesystem.h"
  16. #include "ScopeGuard.h"
  17. static const JsonNode nullNode;
  18. template<typename Iterator>
  19. void JsonWriter::writeContainer(Iterator begin, Iterator end)
  20. {
  21. if (begin == end)
  22. return;
  23. prefix += '\t';
  24. writeEntry(begin++);
  25. while (begin != end)
  26. {
  27. out << (compactMode ? ", " : ",\n");
  28. writeEntry(begin++);
  29. }
  30. out << (compactMode ? "" : "\n");
  31. prefix.resize(prefix.size()-1);
  32. }
  33. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  34. {
  35. if(!compactMode)
  36. {
  37. if (!entry->second.meta.empty())
  38. out << prefix << " // " << entry->second.meta << "\n";
  39. if(!entry->second.flags.empty())
  40. out << prefix << " // flags: " << boost::algorithm::join(entry->second.flags, ", ") << "\n";
  41. out << prefix;
  42. }
  43. writeString(entry->first);
  44. out << " : ";
  45. writeNode(entry->second);
  46. }
  47. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  48. {
  49. if(!compactMode)
  50. {
  51. if (!entry->meta.empty())
  52. out << prefix << " // " << entry->meta << "\n";
  53. if(!entry->flags.empty())
  54. out << prefix << " // flags: " << boost::algorithm::join(entry->flags, ", ") << "\n";
  55. out << prefix;
  56. }
  57. writeNode(*entry);
  58. }
  59. void JsonWriter::writeString(const std::string &string)
  60. {
  61. static const std::string escaped = "\"\\\b\f\n\r\t/";
  62. static const std::array<char, 8> escaped_code = {'\"', '\\', 'b', 'f', 'n', 'r', 't', '/'};
  63. out <<'\"';
  64. size_t pos=0, start=0;
  65. for (; pos<string.size(); pos++)
  66. {
  67. //we need to check if special character was been already escaped
  68. if((string[pos] == '\\')
  69. && (pos+1 < string.size())
  70. && (std::find(escaped_code.begin(), escaped_code.end(), string[pos+1]) != escaped_code.end()) )
  71. {
  72. pos++; //write unchanged, next simbol also checked
  73. }
  74. else
  75. {
  76. size_t escapedPos = escaped.find(string[pos]);
  77. if (escapedPos != std::string::npos)
  78. {
  79. out.write(string.data()+start, pos - start);
  80. out << '\\' << escaped_code[escapedPos];
  81. start = pos+1;
  82. }
  83. }
  84. }
  85. out.write(string.data()+start, pos - start);
  86. out <<'\"';
  87. }
  88. void JsonWriter::writeNode(const JsonNode &node)
  89. {
  90. bool originalMode = compactMode;
  91. if(compact && !compactMode && node.isCompact())
  92. compactMode = true;
  93. switch(node.getType())
  94. {
  95. break; case JsonNode::JsonType::DATA_NULL:
  96. out << "null";
  97. break; case JsonNode::JsonType::DATA_BOOL:
  98. if (node.Bool())
  99. out << "true";
  100. else
  101. out << "false";
  102. break; case JsonNode::JsonType::DATA_FLOAT:
  103. out << node.Float();
  104. break; case JsonNode::JsonType::DATA_STRING:
  105. writeString(node.String());
  106. break; case JsonNode::JsonType::DATA_VECTOR:
  107. out << "[" << (compactMode ? " " : "\n");
  108. writeContainer(node.Vector().begin(), node.Vector().end());
  109. out << (compactMode ? " " : prefix) << "]";
  110. break; case JsonNode::JsonType::DATA_STRUCT:
  111. out << "{" << (compactMode ? " " : "\n");
  112. writeContainer(node.Struct().begin(), node.Struct().end());
  113. out << (compactMode ? " " : prefix) << "}";
  114. break; case JsonNode::JsonType::DATA_INTEGER:
  115. out << node.Integer();
  116. }
  117. compactMode = originalMode;
  118. }
  119. JsonWriter::JsonWriter(std::ostream & output, bool compact)
  120. : out(output), compact(compact)
  121. {
  122. }
  123. ////////////////////////////////////////////////////////////////////////////////
  124. JsonParser::JsonParser(const char * inputString, size_t stringSize):
  125. input(inputString, stringSize),
  126. lineCount(1),
  127. lineStart(0),
  128. pos(0)
  129. {
  130. }
  131. JsonNode JsonParser::parse(std::string fileName)
  132. {
  133. JsonNode root;
  134. if (input.size() == 0)
  135. {
  136. error("File is empty", false);
  137. }
  138. else
  139. {
  140. if (!Unicode::isValidString(&input[0], input.size()))
  141. error("Not a valid UTF-8 file", false);
  142. extractValue(root);
  143. extractWhitespace(false);
  144. //Warn if there are any non-whitespace symbols left
  145. if (pos < input.size())
  146. error("Not all file was parsed!", true);
  147. }
  148. if (!errors.empty())
  149. {
  150. logMod->warn("File %s is not a valid JSON file!", fileName);
  151. logMod->warn(errors);
  152. }
  153. return root;
  154. }
  155. bool JsonParser::isValid()
  156. {
  157. return errors.empty();
  158. }
  159. bool JsonParser::extractSeparator()
  160. {
  161. if (!extractWhitespace())
  162. return false;
  163. if ( input[pos] !=':')
  164. return error("Separator expected");
  165. pos++;
  166. return true;
  167. }
  168. bool JsonParser::extractValue(JsonNode &node)
  169. {
  170. if (!extractWhitespace())
  171. return false;
  172. switch (input[pos])
  173. {
  174. case '\"': return extractString(node);
  175. case 'n' : return extractNull(node);
  176. case 't' : return extractTrue(node);
  177. case 'f' : return extractFalse(node);
  178. case '{' : return extractStruct(node);
  179. case '[' : return extractArray(node);
  180. case '-' : return extractFloat(node);
  181. default:
  182. {
  183. if (input[pos] >= '0' && input[pos] <= '9')
  184. return extractFloat(node);
  185. return error("Value expected!");
  186. }
  187. }
  188. }
  189. bool JsonParser::extractWhitespace(bool verbose)
  190. {
  191. while (true)
  192. {
  193. while (pos < input.size() && (ui8)input[pos] <= ' ')
  194. {
  195. if (input[pos] == '\n')
  196. {
  197. lineCount++;
  198. lineStart = pos+1;
  199. }
  200. pos++;
  201. }
  202. if (pos >= input.size() || input[pos] != '/')
  203. break;
  204. pos++;
  205. if (pos == input.size())
  206. break;
  207. if (input[pos] == '/')
  208. pos++;
  209. else
  210. error("Comments must consist from two slashes!", true);
  211. while (pos < input.size() && input[pos] != '\n')
  212. pos++;
  213. }
  214. if (pos >= input.size() && verbose)
  215. return error("Unexpected end of file!");
  216. return true;
  217. }
  218. bool JsonParser::extractEscaping(std::string &str)
  219. {
  220. switch(input[pos])
  221. {
  222. break; case '\"': str += '\"';
  223. break; case '\\': str += '\\';
  224. break; case 'b': str += '\b';
  225. break; case 'f': str += '\f';
  226. break; case 'n': str += '\n';
  227. break; case 'r': str += '\r';
  228. break; case 't': str += '\t';
  229. break; case '/': str += '/';
  230. break; default: return error("Unknown escape sequence!", true);
  231. }
  232. return true;
  233. }
  234. bool JsonParser::extractString(std::string &str)
  235. {
  236. if (input[pos] != '\"')
  237. return error("String expected!");
  238. pos++;
  239. size_t first = pos;
  240. while (pos != input.size())
  241. {
  242. if (input[pos] == '\"') // Correct end of string
  243. {
  244. str.append( &input[first], pos-first);
  245. pos++;
  246. return true;
  247. }
  248. if (input[pos] == '\\') // Escaping
  249. {
  250. str.append( &input[first], pos-first);
  251. pos++;
  252. if (pos == input.size())
  253. break;
  254. extractEscaping(str);
  255. first = pos + 1;
  256. }
  257. if (input[pos] == '\n') // end-of-line
  258. {
  259. str.append( &input[first], pos-first);
  260. return error("Closing quote not found!", true);
  261. }
  262. if ((unsigned char)(input[pos]) < ' ') // control character
  263. {
  264. str.append( &input[first], pos-first);
  265. first = pos+1;
  266. error("Illegal character in the string!", true);
  267. }
  268. pos++;
  269. }
  270. return error("Unterminated string!");
  271. }
  272. bool JsonParser::extractString(JsonNode &node)
  273. {
  274. std::string str;
  275. if (!extractString(str))
  276. return false;
  277. node.setType(JsonNode::JsonType::DATA_STRING);
  278. node.String() = str;
  279. return true;
  280. }
  281. bool JsonParser::extractLiteral(const std::string &literal)
  282. {
  283. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  284. {
  285. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  286. || (input[pos]>'A' && input[pos]<'Z')))
  287. pos++;
  288. return error("Unknown literal found", true);
  289. }
  290. pos += literal.size();
  291. return true;
  292. }
  293. bool JsonParser::extractNull(JsonNode &node)
  294. {
  295. if (!extractLiteral("null"))
  296. return false;
  297. node.clear();
  298. return true;
  299. }
  300. bool JsonParser::extractTrue(JsonNode &node)
  301. {
  302. if (!extractLiteral("true"))
  303. return false;
  304. node.Bool() = true;
  305. return true;
  306. }
  307. bool JsonParser::extractFalse(JsonNode &node)
  308. {
  309. if (!extractLiteral("false"))
  310. return false;
  311. node.Bool() = false;
  312. return true;
  313. }
  314. bool JsonParser::extractStruct(JsonNode &node)
  315. {
  316. node.setType(JsonNode::JsonType::DATA_STRUCT);
  317. pos++;
  318. if (!extractWhitespace())
  319. return false;
  320. //Empty struct found
  321. if (input[pos] == '}')
  322. {
  323. pos++;
  324. return true;
  325. }
  326. while (true)
  327. {
  328. if (!extractWhitespace())
  329. return false;
  330. std::string key;
  331. if (!extractString(key))
  332. return false;
  333. // split key string into actual key and meta-flags
  334. std::vector<std::string> keyAndFlags;
  335. boost::split(keyAndFlags, key, boost::is_any_of("#"));
  336. key = keyAndFlags[0];
  337. // check for unknown flags - helps with debugging
  338. std::vector<std::string> knownFlags = { "override" };
  339. for(int i = 1; i < keyAndFlags.size(); i++)
  340. {
  341. if(!vstd::contains(knownFlags, keyAndFlags[i]))
  342. error("Encountered unknown flag #" + keyAndFlags[i], true);
  343. }
  344. if (node.Struct().find(key) != node.Struct().end())
  345. error("Dublicated element encountered!", true);
  346. if (!extractSeparator())
  347. return false;
  348. if (!extractElement(node.Struct()[key], '}'))
  349. return false;
  350. // flags from key string belong to referenced element
  351. for(int i = 1; i < keyAndFlags.size(); i++)
  352. node.Struct()[key].flags.push_back(keyAndFlags[i]);
  353. if (input[pos] == '}')
  354. {
  355. pos++;
  356. return true;
  357. }
  358. }
  359. }
  360. bool JsonParser::extractArray(JsonNode &node)
  361. {
  362. pos++;
  363. node.setType(JsonNode::JsonType::DATA_VECTOR);
  364. if (!extractWhitespace())
  365. return false;
  366. //Empty array found
  367. if (input[pos] == ']')
  368. {
  369. pos++;
  370. return true;
  371. }
  372. while (true)
  373. {
  374. //NOTE: currently 50% of time is this vector resizing.
  375. //May be useful to use list during parsing and then swap() all items to vector
  376. node.Vector().resize(node.Vector().size()+1);
  377. if (!extractElement(node.Vector().back(), ']'))
  378. return false;
  379. if (input[pos] == ']')
  380. {
  381. pos++;
  382. return true;
  383. }
  384. }
  385. }
  386. bool JsonParser::extractElement(JsonNode &node, char terminator)
  387. {
  388. if (!extractValue(node))
  389. return false;
  390. if (!extractWhitespace())
  391. return false;
  392. bool comma = (input[pos] == ',');
  393. if (comma )
  394. {
  395. pos++;
  396. if (!extractWhitespace())
  397. return false;
  398. }
  399. if (input[pos] == terminator)
  400. {
  401. //FIXME: MOD COMPATIBILITY: Too many of these right now, re-enable later
  402. //if (comma)
  403. //error("Extra comma found!", true);
  404. return true;
  405. }
  406. if (!comma)
  407. error("Comma expected!", true);
  408. return true;
  409. }
  410. bool JsonParser::extractFloat(JsonNode &node)
  411. {
  412. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  413. bool negative=false;
  414. double result=0;
  415. si64 integerPart = 0;
  416. bool isFloat = false;
  417. if (input[pos] == '-')
  418. {
  419. pos++;
  420. negative = true;
  421. }
  422. if (input[pos] < '0' || input[pos] > '9')
  423. return error("Number expected!");
  424. //Extract integer part
  425. while (input[pos] >= '0' && input[pos] <= '9')
  426. {
  427. integerPart = integerPart*10+(input[pos]-'0');
  428. pos++;
  429. }
  430. result = integerPart;
  431. if (input[pos] == '.')
  432. {
  433. //extract fractional part
  434. isFloat = true;
  435. pos++;
  436. double fractMult = 0.1;
  437. if (input[pos] < '0' || input[pos] > '9')
  438. return error("Decimal part expected!");
  439. while (input[pos] >= '0' && input[pos] <= '9')
  440. {
  441. result = result + fractMult*(input[pos]-'0');
  442. fractMult /= 10;
  443. pos++;
  444. }
  445. }
  446. if(input[pos] == 'e')
  447. {
  448. //extract exponential part
  449. pos++;
  450. isFloat = true;
  451. bool powerNegative = false;
  452. double power = 0;
  453. if(input[pos] == '-')
  454. {
  455. pos++;
  456. powerNegative = true;
  457. }
  458. else if(input[pos] == '+')
  459. {
  460. pos++;
  461. }
  462. if (input[pos] < '0' || input[pos] > '9')
  463. return error("Exponential part expected!");
  464. while (input[pos] >= '0' && input[pos] <= '9')
  465. {
  466. power = power*10 + (input[pos]-'0');
  467. pos++;
  468. }
  469. if(powerNegative)
  470. power = -power;
  471. result *= std::pow(10, power);
  472. }
  473. if(isFloat)
  474. {
  475. if(negative)
  476. result = -result;
  477. node.setType(JsonNode::JsonType::DATA_FLOAT);
  478. node.Float() = result;
  479. }
  480. else
  481. {
  482. if(negative)
  483. integerPart = -integerPart;
  484. node.setType(JsonNode::JsonType::DATA_INTEGER);
  485. node.Integer() = integerPart;
  486. }
  487. return true;
  488. }
  489. bool JsonParser::error(const std::string &message, bool warning)
  490. {
  491. std::ostringstream stream;
  492. std::string type(warning?" warning: ":" error: ");
  493. stream << "At line " << lineCount << ", position "<<pos-lineStart
  494. << type << message <<"\n";
  495. errors += stream.str();
  496. return warning;
  497. }
  498. ///////////////////////////////////////////////////////////////////////////////
  499. //TODO: integer support
  500. static const std::unordered_map<std::string, JsonNode::JsonType> stringToType =
  501. {
  502. {"null", JsonNode::JsonType::DATA_NULL},
  503. {"boolean", JsonNode::JsonType::DATA_BOOL},
  504. {"number", JsonNode::JsonType::DATA_FLOAT},
  505. {"string", JsonNode::JsonType::DATA_STRING},
  506. {"array", JsonNode::JsonType::DATA_VECTOR},
  507. {"object", JsonNode::JsonType::DATA_STRUCT}
  508. };
  509. namespace
  510. {
  511. namespace Common
  512. {
  513. std::string emptyCheck(Validation::ValidationData &, const JsonNode &, const JsonNode &, const JsonNode &)
  514. {
  515. // check is not needed - e.g. incorporated into another check
  516. return "";
  517. }
  518. std::string notImplementedCheck(Validation::ValidationData &, const JsonNode &, const JsonNode &, const JsonNode &)
  519. {
  520. return "Not implemented entry in schema";
  521. }
  522. std::string schemaListCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data,
  523. std::string errorMsg, std::function<bool(size_t)> isValid)
  524. {
  525. std::string errors = "<tested schemas>\n";
  526. size_t result = 0;
  527. for(auto & schemaEntry : schema.Vector())
  528. {
  529. std::string error = check(schemaEntry, data, validator);
  530. if (error.empty())
  531. {
  532. result++;
  533. }
  534. else
  535. {
  536. errors += error;
  537. errors += "<end of schema>\n";
  538. }
  539. }
  540. if (isValid(result))
  541. return "";
  542. else
  543. return validator.makeErrorMessage(errorMsg) + errors;
  544. }
  545. std::string allOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  546. {
  547. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass all schemas", [&](size_t count)
  548. {
  549. return count == schema.Vector().size();
  550. });
  551. }
  552. std::string anyOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  553. {
  554. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass any schema", [&](size_t count)
  555. {
  556. return count > 0;
  557. });
  558. }
  559. std::string oneOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  560. {
  561. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass exactly one schema", [&](size_t count)
  562. {
  563. return count == 1;
  564. });
  565. }
  566. std::string notCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  567. {
  568. if (check(schema, data, validator).empty())
  569. return validator.makeErrorMessage("Successful validation against negative check");
  570. return "";
  571. }
  572. std::string enumCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  573. {
  574. for(auto & enumEntry : schema.Vector())
  575. {
  576. if (data == enumEntry)
  577. return "";
  578. }
  579. return validator.makeErrorMessage("Key must have one of predefined values");
  580. }
  581. std::string typeCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  582. {
  583. const auto typeName = schema.String();
  584. auto it = stringToType.find(typeName);
  585. if(it == stringToType.end())
  586. {
  587. return validator.makeErrorMessage("Unknown type in schema:" + typeName);
  588. }
  589. JsonNode::JsonType type = it->second;
  590. //FIXME: hack for integer values
  591. if(data.isNumber() && type == JsonNode::JsonType::DATA_FLOAT)
  592. return "";
  593. if(type != data.getType() && data.getType() != JsonNode::JsonType::DATA_NULL)
  594. return validator.makeErrorMessage("Type mismatch! Expected " + schema.String());
  595. return "";
  596. }
  597. std::string refCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  598. {
  599. std::string URI = schema.String();
  600. //node must be validated using schema pointed by this reference and not by data here
  601. //Local reference. Turn it into more easy to handle remote ref
  602. if (boost::algorithm::starts_with(URI, "#"))
  603. URI = validator.usedSchemas.back() + URI;
  604. return check(URI, data, validator);
  605. }
  606. std::string formatCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  607. {
  608. auto formats = Validation::getKnownFormats();
  609. std::string errors;
  610. auto checker = formats.find(schema.String());
  611. if (checker != formats.end())
  612. {
  613. std::string result = checker->second(data);
  614. if (!result.empty())
  615. errors += validator.makeErrorMessage(result);
  616. }
  617. else
  618. errors += validator.makeErrorMessage("Unsupported format type: " + schema.String());
  619. return errors;
  620. }
  621. }
  622. namespace String
  623. {
  624. std::string maxLengthCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  625. {
  626. if (data.String().size() > schema.Float())
  627. return validator.makeErrorMessage((boost::format("String is longer than %d symbols") % schema.Float()).str());
  628. return "";
  629. }
  630. std::string minLengthCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  631. {
  632. if (data.String().size() < schema.Float())
  633. return validator.makeErrorMessage((boost::format("String is shorter than %d symbols") % schema.Float()).str());
  634. return "";
  635. }
  636. }
  637. namespace Number
  638. {
  639. std::string maximumCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  640. {
  641. if (baseSchema["exclusiveMaximum"].Bool())
  642. {
  643. if (data.Float() >= schema.Float())
  644. return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
  645. }
  646. else
  647. {
  648. if (data.Float() > schema.Float())
  649. return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
  650. }
  651. return "";
  652. }
  653. std::string minimumCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  654. {
  655. if (baseSchema["exclusiveMinimum"].Bool())
  656. {
  657. if (data.Float() <= schema.Float())
  658. return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
  659. }
  660. else
  661. {
  662. if (data.Float() < schema.Float())
  663. return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
  664. }
  665. return "";
  666. }
  667. std::string multipleOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  668. {
  669. double result = data.Float() / schema.Float();
  670. if (floor(result) != result)
  671. return validator.makeErrorMessage((boost::format("Value is not divisible by %d") % schema.Float()).str());
  672. return "";
  673. }
  674. }
  675. namespace Vector
  676. {
  677. std::string itemEntryCheck(Validation::ValidationData & validator, const JsonVector items, const JsonNode & schema, size_t index)
  678. {
  679. validator.currentPath.push_back(JsonNode());
  680. validator.currentPath.back().Float() = index;
  681. auto onExit = vstd::makeScopeGuard([&]()
  682. {
  683. validator.currentPath.pop_back();
  684. });
  685. if (!schema.isNull())
  686. return check(schema, items[index], validator);
  687. return "";
  688. }
  689. std::string itemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  690. {
  691. std::string errors;
  692. for (size_t i=0; i<data.Vector().size(); i++)
  693. {
  694. if (schema.getType() == JsonNode::JsonType::DATA_VECTOR)
  695. {
  696. if (schema.Vector().size() > i)
  697. errors += itemEntryCheck(validator, data.Vector(), schema.Vector()[i], i);
  698. }
  699. else
  700. {
  701. errors += itemEntryCheck(validator, data.Vector(), schema, i);
  702. }
  703. }
  704. return errors;
  705. }
  706. std::string additionalItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  707. {
  708. std::string errors;
  709. // "items" is struct or empty (defaults to empty struct) - validation always successful
  710. const JsonNode & items = baseSchema["items"];
  711. if (items.getType() != JsonNode::JsonType::DATA_VECTOR)
  712. return "";
  713. for (size_t i=items.Vector().size(); i<data.Vector().size(); i++)
  714. {
  715. if (schema.getType() == JsonNode::JsonType::DATA_STRUCT)
  716. errors += itemEntryCheck(validator, data.Vector(), schema, i);
  717. else if (!schema.isNull() && schema.Bool() == false)
  718. errors += validator.makeErrorMessage("Unknown entry found");
  719. }
  720. return errors;
  721. }
  722. std::string minItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  723. {
  724. if (data.Vector().size() < schema.Float())
  725. return validator.makeErrorMessage((boost::format("Length is smaller than %d") % schema.Float()).str());
  726. return "";
  727. }
  728. std::string maxItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  729. {
  730. if (data.Vector().size() > schema.Float())
  731. return validator.makeErrorMessage((boost::format("Length is bigger than %d") % schema.Float()).str());
  732. return "";
  733. }
  734. std::string uniqueItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  735. {
  736. if (schema.Bool())
  737. {
  738. for (auto itA = schema.Vector().begin(); itA != schema.Vector().end(); itA++)
  739. {
  740. auto itB = itA;
  741. while (++itB != schema.Vector().end())
  742. {
  743. if (*itA == *itB)
  744. return validator.makeErrorMessage("List must consist from unique items");
  745. }
  746. }
  747. }
  748. return "";
  749. }
  750. }
  751. namespace Struct
  752. {
  753. std::string maxPropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  754. {
  755. if (data.Struct().size() > schema.Float())
  756. return validator.makeErrorMessage((boost::format("Number of entries is bigger than %d") % schema.Float()).str());
  757. return "";
  758. }
  759. std::string minPropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  760. {
  761. if (data.Struct().size() < schema.Float())
  762. return validator.makeErrorMessage((boost::format("Number of entries is less than %d") % schema.Float()).str());
  763. return "";
  764. }
  765. std::string uniquePropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  766. {
  767. for (auto itA = data.Struct().begin(); itA != data.Struct().end(); itA++)
  768. {
  769. auto itB = itA;
  770. while (++itB != data.Struct().end())
  771. {
  772. if (itA->second == itB->second)
  773. return validator.makeErrorMessage("List must consist from unique items");
  774. }
  775. }
  776. return "";
  777. }
  778. std::string requiredCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  779. {
  780. std::string errors;
  781. for(auto & required : schema.Vector())
  782. {
  783. if (data[required.String()].isNull())
  784. errors += validator.makeErrorMessage("Required entry " + required.String() + " is missing");
  785. }
  786. return errors;
  787. }
  788. std::string dependenciesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  789. {
  790. std::string errors;
  791. for(auto & deps : schema.Struct())
  792. {
  793. if (!data[deps.first].isNull())
  794. {
  795. if (deps.second.getType() == JsonNode::JsonType::DATA_VECTOR)
  796. {
  797. JsonVector depList = deps.second.Vector();
  798. for(auto & depEntry : depList)
  799. {
  800. if (data[depEntry.String()].isNull())
  801. errors += validator.makeErrorMessage("Property " + depEntry.String() + " required for " + deps.first + " is missing");
  802. }
  803. }
  804. else
  805. {
  806. if (!check(deps.second, data, validator).empty())
  807. errors += validator.makeErrorMessage("Requirements for " + deps.first + " are not fulfilled");
  808. }
  809. }
  810. }
  811. return errors;
  812. }
  813. std::string propertyEntryCheck(Validation::ValidationData & validator, const JsonNode &node, const JsonNode & schema, std::string nodeName)
  814. {
  815. validator.currentPath.push_back(JsonNode());
  816. validator.currentPath.back().String() = nodeName;
  817. auto onExit = vstd::makeScopeGuard([&]()
  818. {
  819. validator.currentPath.pop_back();
  820. });
  821. // there is schema specifically for this item
  822. if (!schema.isNull())
  823. return check(schema, node, validator);
  824. return "";
  825. }
  826. std::string propertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  827. {
  828. std::string errors;
  829. for(auto & entry : data.Struct())
  830. errors += propertyEntryCheck(validator, entry.second, schema[entry.first], entry.first);
  831. return errors;
  832. }
  833. std::string additionalPropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  834. {
  835. std::string errors;
  836. for(auto & entry : data.Struct())
  837. {
  838. if (baseSchema["properties"].Struct().count(entry.first) == 0)
  839. {
  840. // try generic additionalItems schema
  841. if (schema.getType() == JsonNode::JsonType::DATA_STRUCT)
  842. errors += propertyEntryCheck(validator, entry.second, schema, entry.first);
  843. // or, additionalItems field can be bool which indicates if such items are allowed
  844. else if (!schema.isNull() && schema.Bool() == false) // present and set to false - error
  845. errors += validator.makeErrorMessage("Unknown entry found: " + entry.first);
  846. }
  847. }
  848. return errors;
  849. }
  850. }
  851. namespace Formats
  852. {
  853. bool testFilePresence(std::string scope, ResourceID resource)
  854. {
  855. std::set<std::string> allowedScopes;
  856. if (scope != "core" && scope != "") // all real mods may have dependencies
  857. {
  858. //NOTE: recursive dependencies are not allowed at the moment - update code if this changes
  859. allowedScopes = VLC->modh->getModData(scope).dependencies;
  860. allowedScopes.insert("core"); // all mods can use H3 files
  861. }
  862. allowedScopes.insert(scope); // mods can use their own files
  863. for (auto & entry : allowedScopes)
  864. {
  865. if (CResourceHandler::get(entry)->existsResource(resource))
  866. return true;
  867. }
  868. return false;
  869. }
  870. #define TEST_FILE(scope, prefix, file, type) \
  871. if (testFilePresence(scope, ResourceID(prefix + file, type))) \
  872. return ""
  873. std::string testAnimation(std::string path, std::string scope)
  874. {
  875. TEST_FILE(scope, "Sprites/", path, EResType::ANIMATION);
  876. TEST_FILE(scope, "Sprites/", path, EResType::TEXT);
  877. return "Animation file \"" + path + "\" was not found";
  878. }
  879. std::string textFile(const JsonNode & node)
  880. {
  881. TEST_FILE(node.meta, "", node.String(), EResType::TEXT);
  882. return "Text file \"" + node.String() + "\" was not found";
  883. }
  884. std::string musicFile(const JsonNode & node)
  885. {
  886. TEST_FILE(node.meta, "", node.String(), EResType::MUSIC);
  887. return "Music file \"" + node.String() + "\" was not found";
  888. }
  889. std::string soundFile(const JsonNode & node)
  890. {
  891. TEST_FILE(node.meta, "Sounds/", node.String(), EResType::SOUND);
  892. return "Sound file \"" + node.String() + "\" was not found";
  893. }
  894. std::string defFile(const JsonNode & node)
  895. {
  896. TEST_FILE(node.meta, "Sprites/", node.String(), EResType::ANIMATION);
  897. return "Def file \"" + node.String() + "\" was not found";
  898. }
  899. std::string animationFile(const JsonNode & node)
  900. {
  901. return testAnimation(node.String(), node.meta);
  902. }
  903. std::string imageFile(const JsonNode & node)
  904. {
  905. TEST_FILE(node.meta, "Data/", node.String(), EResType::IMAGE);
  906. TEST_FILE(node.meta, "Sprites/", node.String(), EResType::IMAGE);
  907. if (node.String().find(':') != std::string::npos)
  908. return testAnimation(node.String().substr(0, node.String().find(':')), node.meta);
  909. return "Image file \"" + node.String() + "\" was not found";
  910. }
  911. std::string videoFile(const JsonNode & node)
  912. {
  913. TEST_FILE(node.meta, "Video/", node.String(), EResType::VIDEO);
  914. return "Video file \"" + node.String() + "\" was not found";
  915. }
  916. #undef TEST_FILE
  917. }
  918. Validation::TValidatorMap createCommonFields()
  919. {
  920. Validation::TValidatorMap ret;
  921. ret["format"] = Common::formatCheck;
  922. ret["allOf"] = Common::allOfCheck;
  923. ret["anyOf"] = Common::anyOfCheck;
  924. ret["oneOf"] = Common::oneOfCheck;
  925. ret["enum"] = Common::enumCheck;
  926. ret["type"] = Common::typeCheck;
  927. ret["not"] = Common::notCheck;
  928. ret["$ref"] = Common::refCheck;
  929. // fields that don't need implementation
  930. ret["title"] = Common::emptyCheck;
  931. ret["$schema"] = Common::emptyCheck;
  932. ret["default"] = Common::emptyCheck;
  933. ret["description"] = Common::emptyCheck;
  934. ret["definitions"] = Common::emptyCheck;
  935. return ret;
  936. }
  937. Validation::TValidatorMap createStringFields()
  938. {
  939. Validation::TValidatorMap ret = createCommonFields();
  940. ret["maxLength"] = String::maxLengthCheck;
  941. ret["minLength"] = String::minLengthCheck;
  942. ret["pattern"] = Common::notImplementedCheck;
  943. return ret;
  944. }
  945. Validation::TValidatorMap createNumberFields()
  946. {
  947. Validation::TValidatorMap ret = createCommonFields();
  948. ret["maximum"] = Number::maximumCheck;
  949. ret["minimum"] = Number::minimumCheck;
  950. ret["multipleOf"] = Number::multipleOfCheck;
  951. ret["exclusiveMaximum"] = Common::emptyCheck;
  952. ret["exclusiveMinimum"] = Common::emptyCheck;
  953. return ret;
  954. }
  955. Validation::TValidatorMap createVectorFields()
  956. {
  957. Validation::TValidatorMap ret = createCommonFields();
  958. ret["items"] = Vector::itemsCheck;
  959. ret["minItems"] = Vector::minItemsCheck;
  960. ret["maxItems"] = Vector::maxItemsCheck;
  961. ret["uniqueItems"] = Vector::uniqueItemsCheck;
  962. ret["additionalItems"] = Vector::additionalItemsCheck;
  963. return ret;
  964. }
  965. Validation::TValidatorMap createStructFields()
  966. {
  967. Validation::TValidatorMap ret = createCommonFields();
  968. ret["additionalProperties"] = Struct::additionalPropertiesCheck;
  969. ret["uniqueProperties"] = Struct::uniquePropertiesCheck;
  970. ret["maxProperties"] = Struct::maxPropertiesCheck;
  971. ret["minProperties"] = Struct::minPropertiesCheck;
  972. ret["dependencies"] = Struct::dependenciesCheck;
  973. ret["properties"] = Struct::propertiesCheck;
  974. ret["required"] = Struct::requiredCheck;
  975. ret["patternProperties"] = Common::notImplementedCheck;
  976. return ret;
  977. }
  978. Validation::TFormatMap createFormatMap()
  979. {
  980. Validation::TFormatMap ret;
  981. ret["textFile"] = Formats::textFile;
  982. ret["musicFile"] = Formats::musicFile;
  983. ret["soundFile"] = Formats::soundFile;
  984. ret["defFile"] = Formats::defFile;
  985. ret["animationFile"] = Formats::animationFile;
  986. ret["imageFile"] = Formats::imageFile;
  987. ret["videoFile"] = Formats::videoFile;
  988. return ret;
  989. }
  990. }
  991. namespace Validation
  992. {
  993. std::string ValidationData::makeErrorMessage(const std::string &message)
  994. {
  995. std::string errors;
  996. errors += "At ";
  997. if (!currentPath.empty())
  998. {
  999. for(const JsonNode &path : currentPath)
  1000. {
  1001. errors += "/";
  1002. if (path.getType() == JsonNode::JsonType::DATA_STRING)
  1003. errors += path.String();
  1004. else
  1005. errors += boost::lexical_cast<std::string>(static_cast<unsigned>(path.Float()));
  1006. }
  1007. }
  1008. else
  1009. errors += "<root>";
  1010. errors += "\n\t Error: " + message + "\n";
  1011. return errors;
  1012. }
  1013. std::string check(std::string schemaName, const JsonNode & data)
  1014. {
  1015. ValidationData validator;
  1016. return check(schemaName, data, validator);
  1017. }
  1018. std::string check(std::string schemaName, const JsonNode & data, ValidationData & validator)
  1019. {
  1020. validator.usedSchemas.push_back(schemaName);
  1021. auto onscopeExit = vstd::makeScopeGuard([&]()
  1022. {
  1023. validator.usedSchemas.pop_back();
  1024. });
  1025. return check(JsonUtils::getSchema(schemaName), data, validator);
  1026. }
  1027. std::string check(const JsonNode & schema, const JsonNode & data, ValidationData & validator)
  1028. {
  1029. const TValidatorMap & knownFields = getKnownFieldsFor(data.getType());
  1030. std::string errors;
  1031. for(auto & entry : schema.Struct())
  1032. {
  1033. auto checker = knownFields.find(entry.first);
  1034. if (checker != knownFields.end())
  1035. errors += checker->second(validator, schema, entry.second, data);
  1036. //else
  1037. // errors += validator.makeErrorMessage("Unknown entry in schema " + entry.first);
  1038. }
  1039. return errors;
  1040. }
  1041. const TValidatorMap & getKnownFieldsFor(JsonNode::JsonType type)
  1042. {
  1043. static const TValidatorMap commonFields = createCommonFields();
  1044. static const TValidatorMap numberFields = createNumberFields();
  1045. static const TValidatorMap stringFields = createStringFields();
  1046. static const TValidatorMap vectorFields = createVectorFields();
  1047. static const TValidatorMap structFields = createStructFields();
  1048. switch (type)
  1049. {
  1050. case JsonNode::JsonType::DATA_FLOAT:
  1051. case JsonNode::JsonType::DATA_INTEGER:
  1052. return numberFields;
  1053. case JsonNode::JsonType::DATA_STRING: return stringFields;
  1054. case JsonNode::JsonType::DATA_VECTOR: return vectorFields;
  1055. case JsonNode::JsonType::DATA_STRUCT: return structFields;
  1056. default: return commonFields;
  1057. }
  1058. }
  1059. const TFormatMap & getKnownFormats()
  1060. {
  1061. static TFormatMap knownFormats = createFormatMap();
  1062. return knownFormats;
  1063. }
  1064. } // Validation namespace