JsonDetail.cpp 31 KB

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