JsonDetail.cpp 34 KB

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