JsonDetail.cpp 32 KB

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