JsonDetail.cpp 30 KB

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