JsonDetail.cpp 32 KB

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