JsonDetail.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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. {
  425. {"null", JsonNode::DATA_NULL},
  426. {"boolean", JsonNode::DATA_BOOL},
  427. {"number", JsonNode::DATA_FLOAT},
  428. {"string", JsonNode::DATA_STRING},
  429. {"array", JsonNode::DATA_VECTOR},
  430. {"object", JsonNode::DATA_STRUCT}
  431. };
  432. namespace
  433. {
  434. namespace Common
  435. {
  436. std::string emptyCheck(Validation::ValidationData &, const JsonNode &, const JsonNode &, const JsonNode &)
  437. {
  438. // check is not needed - e.g. incorporated into another check
  439. return "";
  440. }
  441. std::string notImplementedCheck(Validation::ValidationData &, const JsonNode &, const JsonNode &, const JsonNode &)
  442. {
  443. return "Not implemented entry in schema";
  444. }
  445. std::string schemaListCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data,
  446. std::string errorMsg, std::function<bool(size_t)> isValid)
  447. {
  448. std::string errors = "<tested schemas>\n";
  449. size_t result = 0;
  450. for(auto & schemaEntry : schema.Vector())
  451. {
  452. std::string error = check(schemaEntry, data, validator);
  453. if (error.empty())
  454. {
  455. result++;
  456. }
  457. else
  458. {
  459. errors += error;
  460. errors += "<end of schema>\n";
  461. }
  462. }
  463. if (isValid(result))
  464. return "";
  465. else
  466. return validator.makeErrorMessage(errorMsg) + errors;
  467. }
  468. std::string allOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  469. {
  470. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass all schemas", [&](size_t count)
  471. {
  472. return count == schema.Vector().size();
  473. });
  474. }
  475. std::string anyOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  476. {
  477. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass any schema", [&](size_t count)
  478. {
  479. return count > 0;
  480. });
  481. }
  482. std::string oneOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  483. {
  484. return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass exactly one schema", [&](size_t count)
  485. {
  486. return count == 1;
  487. });
  488. }
  489. std::string notCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  490. {
  491. if (check(schema, data, validator).empty())
  492. return validator.makeErrorMessage("Successful validation against negative check");
  493. return "";
  494. }
  495. std::string enumCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  496. {
  497. for(auto & enumEntry : schema.Vector())
  498. {
  499. if (data == enumEntry)
  500. return "";
  501. }
  502. return validator.makeErrorMessage("Key must have one of predefined values");
  503. }
  504. std::string typeCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  505. {
  506. const auto typeName = schema.String();
  507. auto it = stringToType.find(typeName);
  508. if(it == stringToType.end())
  509. {
  510. return validator.makeErrorMessage("Unknown type in schema:" + typeName);
  511. }
  512. JsonNode::JsonType type = it->second;
  513. if(type != data.getType() && data.getType() != JsonNode::DATA_NULL)
  514. return validator.makeErrorMessage("Type mismatch! Expected " + schema.String());
  515. return "";
  516. }
  517. std::string refCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  518. {
  519. std::string URI = schema.String();
  520. //node must be validated using schema pointed by this reference and not by data here
  521. //Local reference. Turn it into more easy to handle remote ref
  522. if (boost::algorithm::starts_with(URI, "#"))
  523. URI = validator.usedSchemas.back() + URI;
  524. return check(URI, data, validator);
  525. }
  526. std::string formatCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  527. {
  528. auto formats = Validation::getKnownFormats();
  529. std::string errors;
  530. auto checker = formats.find(schema.String());
  531. if (checker != formats.end())
  532. {
  533. std::string result = checker->second(data);
  534. if (!result.empty())
  535. errors += validator.makeErrorMessage(result);
  536. }
  537. else
  538. errors += validator.makeErrorMessage("Unsupported format type: " + schema.String());
  539. return errors;
  540. }
  541. }
  542. namespace String
  543. {
  544. std::string maxLengthCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  545. {
  546. if (data.String().size() > schema.Float())
  547. return validator.makeErrorMessage((boost::format("String is longer than %d symbols") % schema.Float()).str());
  548. return "";
  549. }
  550. std::string minLengthCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  551. {
  552. if (data.String().size() < schema.Float())
  553. return validator.makeErrorMessage((boost::format("String is shorter than %d symbols") % schema.Float()).str());
  554. return "";
  555. }
  556. }
  557. namespace Number
  558. {
  559. std::string maximumCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  560. {
  561. if (baseSchema["exclusiveMaximum"].Bool())
  562. {
  563. if (data.Float() >= schema.Float())
  564. return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
  565. }
  566. else
  567. {
  568. if (data.Float() > schema.Float())
  569. return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
  570. }
  571. return "";
  572. }
  573. std::string minimumCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  574. {
  575. if (baseSchema["exclusiveMinimum"].Bool())
  576. {
  577. if (data.Float() <= schema.Float())
  578. return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
  579. }
  580. else
  581. {
  582. if (data.Float() < schema.Float())
  583. return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
  584. }
  585. return "";
  586. }
  587. std::string multipleOfCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  588. {
  589. double result = data.Float() / schema.Float();
  590. if (floor(result) != result)
  591. return validator.makeErrorMessage((boost::format("Value is not divisible by %d") % schema.Float()).str());
  592. return "";
  593. }
  594. }
  595. namespace Vector
  596. {
  597. std::string itemEntryCheck(Validation::ValidationData & validator, const JsonVector items, const JsonNode & schema, size_t index)
  598. {
  599. validator.currentPath.push_back(JsonNode());
  600. validator.currentPath.back().Float() = index;
  601. auto onExit = vstd::makeScopeGuard([&]
  602. {
  603. validator.currentPath.pop_back();
  604. });
  605. if (!schema.isNull())
  606. return check(schema, items[index], validator);
  607. return "";
  608. }
  609. std::string itemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  610. {
  611. std::string errors;
  612. for (size_t i=0; i<data.Vector().size(); i++)
  613. {
  614. if (schema.getType() == JsonNode::DATA_VECTOR)
  615. {
  616. if (schema.Vector().size() > i)
  617. errors += itemEntryCheck(validator, data.Vector(), schema.Vector()[i], i);
  618. }
  619. else
  620. {
  621. errors += itemEntryCheck(validator, data.Vector(), schema, i);
  622. }
  623. }
  624. return errors;
  625. }
  626. std::string additionalItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  627. {
  628. std::string errors;
  629. // "items" is struct or empty (defaults to empty struct) - validation always successful
  630. const JsonNode & items = baseSchema["items"];
  631. if (items.getType() != JsonNode::DATA_VECTOR)
  632. return "";
  633. for (size_t i=items.Vector().size(); i<data.Vector().size(); i++)
  634. {
  635. if (schema.getType() == JsonNode::DATA_STRUCT)
  636. errors += itemEntryCheck(validator, data.Vector(), schema, i);
  637. else if (!schema.isNull() && schema.Bool() == false)
  638. errors += validator.makeErrorMessage("Unknown entry found");
  639. }
  640. return errors;
  641. }
  642. std::string minItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  643. {
  644. if (data.Vector().size() < schema.Float())
  645. return validator.makeErrorMessage((boost::format("Length is smaller than %d") % schema.Float()).str());
  646. return "";
  647. }
  648. std::string maxItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  649. {
  650. if (data.Vector().size() > schema.Float())
  651. return validator.makeErrorMessage((boost::format("Length is bigger than %d") % schema.Float()).str());
  652. return "";
  653. }
  654. std::string uniqueItemsCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  655. {
  656. if (schema.Bool())
  657. {
  658. for (auto itA = schema.Vector().begin(); itA != schema.Vector().end(); itA++)
  659. {
  660. auto itB = itA;
  661. while (++itB != schema.Vector().end())
  662. {
  663. if (*itA == *itB)
  664. return validator.makeErrorMessage("List must consist from unique items");
  665. }
  666. }
  667. }
  668. return "";
  669. }
  670. }
  671. namespace Struct
  672. {
  673. std::string maxPropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  674. {
  675. if (data.Struct().size() > schema.Float())
  676. return validator.makeErrorMessage((boost::format("Number of entries is bigger than %d") % schema.Float()).str());
  677. return "";
  678. }
  679. std::string minPropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  680. {
  681. if (data.Struct().size() < schema.Float())
  682. return validator.makeErrorMessage((boost::format("Number of entries is less than %d") % schema.Float()).str());
  683. return "";
  684. }
  685. std::string uniquePropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  686. {
  687. for (auto itA = data.Struct().begin(); itA != data.Struct().end(); itA++)
  688. {
  689. auto itB = itA;
  690. while (++itB != data.Struct().end())
  691. {
  692. if (itA->second == itB->second)
  693. return validator.makeErrorMessage("List must consist from unique items");
  694. }
  695. }
  696. return "";
  697. }
  698. std::string requiredCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  699. {
  700. std::string errors;
  701. for(auto & required : schema.Vector())
  702. {
  703. if (data[required.String()].isNull())
  704. errors += validator.makeErrorMessage("Required entry " + required.String() + " is missing");
  705. }
  706. return errors;
  707. }
  708. std::string dependenciesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  709. {
  710. std::string errors;
  711. for(auto & deps : schema.Struct())
  712. {
  713. if (!data[deps.first].isNull())
  714. {
  715. if (deps.second.getType() == JsonNode::DATA_VECTOR)
  716. {
  717. JsonVector depList = deps.second.Vector();
  718. for(auto & depEntry : depList)
  719. {
  720. if (data[depEntry.String()].isNull())
  721. errors += validator.makeErrorMessage("Property " + depEntry.String() + " required for " + deps.first + " is missing");
  722. }
  723. }
  724. else
  725. {
  726. if (!check(deps.second, data, validator).empty())
  727. errors += validator.makeErrorMessage("Requirements for " + deps.first + " are not fulfilled");
  728. }
  729. }
  730. }
  731. return errors;
  732. }
  733. std::string propertyEntryCheck(Validation::ValidationData & validator, const JsonNode &node, const JsonNode & schema, std::string nodeName)
  734. {
  735. validator.currentPath.push_back(JsonNode());
  736. validator.currentPath.back().String() = nodeName;
  737. auto onExit = vstd::makeScopeGuard([&]
  738. {
  739. validator.currentPath.pop_back();
  740. });
  741. // there is schema specifically for this item
  742. if (!schema.isNull())
  743. return check(schema, node, validator);
  744. return "";
  745. }
  746. std::string propertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  747. {
  748. std::string errors;
  749. for(auto & entry : data.Struct())
  750. errors += propertyEntryCheck(validator, entry.second, schema[entry.first], entry.first);
  751. return errors;
  752. }
  753. std::string additionalPropertiesCheck(Validation::ValidationData & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
  754. {
  755. std::string errors;
  756. for(auto & entry : data.Struct())
  757. {
  758. if (baseSchema["properties"].Struct().count(entry.first) == 0)
  759. {
  760. // try generic additionalItems schema
  761. if (schema.getType() == JsonNode::DATA_STRUCT)
  762. errors += propertyEntryCheck(validator, entry.second, schema, entry.first);
  763. // or, additionalItems field can be bool which indicates if such items are allowed
  764. else if (!schema.isNull() && schema.Bool() == false) // present and set to false - error
  765. errors += validator.makeErrorMessage("Unknown entry found: " + entry.first);
  766. }
  767. }
  768. return errors;
  769. }
  770. }
  771. namespace Formats
  772. {
  773. bool testFilePresence(std::string scope, ResourceID resource)
  774. {
  775. std::set<std::string> allowedScopes;
  776. if (scope != "core" && scope != "") // all real mods may have dependencies
  777. {
  778. //NOTE: recursive dependencies are not allowed at the moment - update code if this changes
  779. allowedScopes = VLC->modh->getModData(scope).dependencies;
  780. allowedScopes.insert("core"); // all mods can use H3 files
  781. }
  782. allowedScopes.insert(scope); // mods can use their own files
  783. for (auto & entry : allowedScopes)
  784. {
  785. if (CResourceHandler::get(entry)->existsResource(resource))
  786. return true;
  787. }
  788. return false;
  789. }
  790. #define TEST_FILE(scope, prefix, file, type) \
  791. if (testFilePresence(scope, ResourceID(prefix + file, type))) \
  792. return ""
  793. std::string testAnimation(std::string path, std::string scope)
  794. {
  795. TEST_FILE(scope, "Sprites/", path, EResType::ANIMATION);
  796. TEST_FILE(scope, "Sprites/", path, EResType::TEXT);
  797. return "Animation file \"" + path + "\" was not found";
  798. }
  799. std::string textFile(const JsonNode & node)
  800. {
  801. TEST_FILE(node.meta, "", node.String(), EResType::TEXT);
  802. return "Text file \"" + node.String() + "\" was not found";
  803. }
  804. std::string musicFile(const JsonNode & node)
  805. {
  806. TEST_FILE(node.meta, "", node.String(), EResType::MUSIC);
  807. return "Music file \"" + node.String() + "\" was not found";
  808. }
  809. std::string soundFile(const JsonNode & node)
  810. {
  811. TEST_FILE(node.meta, "Sounds/", node.String(), EResType::SOUND);
  812. return "Sound file \"" + node.String() + "\" was not found";
  813. }
  814. std::string defFile(const JsonNode & node)
  815. {
  816. TEST_FILE(node.meta, "Sprites/", node.String(), EResType::ANIMATION);
  817. return "Def file \"" + node.String() + "\" was not found";
  818. }
  819. std::string animationFile(const JsonNode & node)
  820. {
  821. return testAnimation(node.String(), node.meta);
  822. }
  823. std::string imageFile(const JsonNode & node)
  824. {
  825. TEST_FILE(node.meta, "Data/", node.String(), EResType::IMAGE);
  826. TEST_FILE(node.meta, "Sprites/", node.String(), EResType::IMAGE);
  827. if (node.String().find(':') != std::string::npos)
  828. return testAnimation(node.String().substr(0, node.String().find(':')), node.meta);
  829. return "Image file \"" + node.String() + "\" was not found";
  830. }
  831. std::string videoFile(const JsonNode & node)
  832. {
  833. TEST_FILE(node.meta, "Video/", node.String(), EResType::VIDEO);
  834. return "Video file \"" + node.String() + "\" was not found";
  835. }
  836. #undef TEST_FILE
  837. }
  838. Validation::TValidatorMap createCommonFields()
  839. {
  840. Validation::TValidatorMap ret;
  841. ret["format"] = Common::formatCheck;
  842. ret["allOf"] = Common::allOfCheck;
  843. ret["anyOf"] = Common::anyOfCheck;
  844. ret["oneOf"] = Common::oneOfCheck;
  845. ret["enum"] = Common::enumCheck;
  846. ret["type"] = Common::typeCheck;
  847. ret["not"] = Common::notCheck;
  848. ret["$ref"] = Common::refCheck;
  849. // fields that don't need implementation
  850. ret["title"] = Common::emptyCheck;
  851. ret["$schema"] = Common::emptyCheck;
  852. ret["default"] = Common::emptyCheck;
  853. ret["description"] = Common::emptyCheck;
  854. ret["definitions"] = Common::emptyCheck;
  855. return ret;
  856. }
  857. Validation::TValidatorMap createStringFields()
  858. {
  859. Validation::TValidatorMap ret = createCommonFields();
  860. ret["maxLength"] = String::maxLengthCheck;
  861. ret["minLength"] = String::minLengthCheck;
  862. ret["pattern"] = Common::notImplementedCheck;
  863. return ret;
  864. }
  865. Validation::TValidatorMap createNumberFields()
  866. {
  867. Validation::TValidatorMap ret = createCommonFields();
  868. ret["maximum"] = Number::maximumCheck;
  869. ret["minimum"] = Number::minimumCheck;
  870. ret["multipleOf"] = Number::multipleOfCheck;
  871. ret["exclusiveMaximum"] = Common::emptyCheck;
  872. ret["exclusiveMinimum"] = Common::emptyCheck;
  873. return ret;
  874. }
  875. Validation::TValidatorMap createVectorFields()
  876. {
  877. Validation::TValidatorMap ret = createCommonFields();
  878. ret["items"] = Vector::itemsCheck;
  879. ret["minItems"] = Vector::minItemsCheck;
  880. ret["maxItems"] = Vector::maxItemsCheck;
  881. ret["uniqueItems"] = Vector::uniqueItemsCheck;
  882. ret["additionalItems"] = Vector::additionalItemsCheck;
  883. return ret;
  884. }
  885. Validation::TValidatorMap createStructFields()
  886. {
  887. Validation::TValidatorMap ret = createCommonFields();
  888. ret["additionalProperties"] = Struct::additionalPropertiesCheck;
  889. ret["uniqueProperties"] = Struct::uniquePropertiesCheck;
  890. ret["maxProperties"] = Struct::maxPropertiesCheck;
  891. ret["minProperties"] = Struct::minPropertiesCheck;
  892. ret["dependencies"] = Struct::dependenciesCheck;
  893. ret["properties"] = Struct::propertiesCheck;
  894. ret["required"] = Struct::requiredCheck;
  895. ret["patternProperties"] = Common::notImplementedCheck;
  896. return ret;
  897. }
  898. Validation::TFormatMap createFormatMap()
  899. {
  900. Validation::TFormatMap ret;
  901. ret["textFile"] = Formats::textFile;
  902. ret["musicFile"] = Formats::musicFile;
  903. ret["soundFile"] = Formats::soundFile;
  904. ret["defFile"] = Formats::defFile;
  905. ret["animationFile"] = Formats::animationFile;
  906. ret["imageFile"] = Formats::imageFile;
  907. ret["videoFile"] = Formats::videoFile;
  908. return ret;
  909. }
  910. }
  911. namespace Validation
  912. {
  913. std::string ValidationData::makeErrorMessage(const std::string &message)
  914. {
  915. std::string errors;
  916. errors += "At ";
  917. if (!currentPath.empty())
  918. {
  919. for(const JsonNode &path : currentPath)
  920. {
  921. errors += "/";
  922. if (path.getType() == JsonNode::DATA_STRING)
  923. errors += path.String();
  924. else
  925. errors += boost::lexical_cast<std::string>(static_cast<unsigned>(path.Float()));
  926. }
  927. }
  928. else
  929. errors += "<root>";
  930. errors += "\n\t Error: " + message + "\n";
  931. return errors;
  932. }
  933. std::string check(std::string schemaName, const JsonNode & data)
  934. {
  935. ValidationData validator;
  936. return check(schemaName, data, validator);
  937. }
  938. std::string check(std::string schemaName, const JsonNode & data, ValidationData & validator)
  939. {
  940. validator.usedSchemas.push_back(schemaName);
  941. auto onscopeExit = vstd::makeScopeGuard([&]()
  942. {
  943. validator.usedSchemas.pop_back();
  944. });
  945. return check(JsonUtils::getSchema(schemaName), data, validator);
  946. }
  947. std::string check(const JsonNode & schema, const JsonNode & data, ValidationData & validator)
  948. {
  949. const TValidatorMap & knownFields = getKnownFieldsFor(data.getType());
  950. std::string errors;
  951. for(auto & entry : schema.Struct())
  952. {
  953. auto checker = knownFields.find(entry.first);
  954. if (checker != knownFields.end())
  955. errors += checker->second(validator, schema, entry.second, data);
  956. //else
  957. // errors += validator.makeErrorMessage("Unknown entry in schema " + entry.first);
  958. }
  959. return errors;
  960. }
  961. const TValidatorMap & getKnownFieldsFor(JsonNode::JsonType type)
  962. {
  963. static const TValidatorMap commonFields = createCommonFields();
  964. static const TValidatorMap numberFields = createNumberFields();
  965. static const TValidatorMap stringFields = createStringFields();
  966. static const TValidatorMap vectorFields = createVectorFields();
  967. static const TValidatorMap structFields = createStructFields();
  968. switch (type)
  969. {
  970. case JsonNode::DATA_FLOAT: return numberFields;
  971. case JsonNode::DATA_STRING: return stringFields;
  972. case JsonNode::DATA_VECTOR: return vectorFields;
  973. case JsonNode::DATA_STRUCT: return structFields;
  974. default: return commonFields;
  975. }
  976. }
  977. const TFormatMap & getKnownFormats()
  978. {
  979. static TFormatMap knownFormats = createFormatMap();
  980. return knownFormats;
  981. }
  982. } // Validation namespace