JsonDetail.cpp 34 KB

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