JsonDetail.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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, "Music/", node.String(), EResType::MUSIC);
  899. TEST_FILE(node.meta, "", node.String(), EResType::MUSIC);
  900. return "Music file \"" + node.String() + "\" was not found";
  901. }
  902. std::string soundFile(const JsonNode & node)
  903. {
  904. TEST_FILE(node.meta, "Sounds/", node.String(), EResType::SOUND);
  905. return "Sound file \"" + node.String() + "\" was not found";
  906. }
  907. std::string defFile(const JsonNode & node)
  908. {
  909. return testAnimation(node.String(), node.meta);
  910. }
  911. std::string animationFile(const JsonNode & node)
  912. {
  913. return testAnimation(node.String(), node.meta);
  914. }
  915. std::string imageFile(const JsonNode & node)
  916. {
  917. TEST_FILE(node.meta, "Data/", node.String(), EResType::IMAGE);
  918. TEST_FILE(node.meta, "Sprites/", node.String(), EResType::IMAGE);
  919. if (node.String().find(':') != std::string::npos)
  920. return testAnimation(node.String().substr(0, node.String().find(':')), node.meta);
  921. return "Image file \"" + node.String() + "\" was not found";
  922. }
  923. std::string videoFile(const JsonNode & node)
  924. {
  925. TEST_FILE(node.meta, "Video/", node.String(), EResType::VIDEO);
  926. return "Video file \"" + node.String() + "\" was not found";
  927. }
  928. #undef TEST_FILE
  929. }
  930. Validation::TValidatorMap createCommonFields()
  931. {
  932. Validation::TValidatorMap ret;
  933. ret["format"] = Common::formatCheck;
  934. ret["allOf"] = Common::allOfCheck;
  935. ret["anyOf"] = Common::anyOfCheck;
  936. ret["oneOf"] = Common::oneOfCheck;
  937. ret["enum"] = Common::enumCheck;
  938. ret["type"] = Common::typeCheck;
  939. ret["not"] = Common::notCheck;
  940. ret["$ref"] = Common::refCheck;
  941. // fields that don't need implementation
  942. ret["title"] = Common::emptyCheck;
  943. ret["$schema"] = Common::emptyCheck;
  944. ret["default"] = Common::emptyCheck;
  945. ret["description"] = Common::emptyCheck;
  946. ret["definitions"] = Common::emptyCheck;
  947. return ret;
  948. }
  949. Validation::TValidatorMap createStringFields()
  950. {
  951. Validation::TValidatorMap ret = createCommonFields();
  952. ret["maxLength"] = String::maxLengthCheck;
  953. ret["minLength"] = String::minLengthCheck;
  954. ret["pattern"] = Common::notImplementedCheck;
  955. return ret;
  956. }
  957. Validation::TValidatorMap createNumberFields()
  958. {
  959. Validation::TValidatorMap ret = createCommonFields();
  960. ret["maximum"] = Number::maximumCheck;
  961. ret["minimum"] = Number::minimumCheck;
  962. ret["multipleOf"] = Number::multipleOfCheck;
  963. ret["exclusiveMaximum"] = Common::emptyCheck;
  964. ret["exclusiveMinimum"] = Common::emptyCheck;
  965. return ret;
  966. }
  967. Validation::TValidatorMap createVectorFields()
  968. {
  969. Validation::TValidatorMap ret = createCommonFields();
  970. ret["items"] = Vector::itemsCheck;
  971. ret["minItems"] = Vector::minItemsCheck;
  972. ret["maxItems"] = Vector::maxItemsCheck;
  973. ret["uniqueItems"] = Vector::uniqueItemsCheck;
  974. ret["additionalItems"] = Vector::additionalItemsCheck;
  975. return ret;
  976. }
  977. Validation::TValidatorMap createStructFields()
  978. {
  979. Validation::TValidatorMap ret = createCommonFields();
  980. ret["additionalProperties"] = Struct::additionalPropertiesCheck;
  981. ret["uniqueProperties"] = Struct::uniquePropertiesCheck;
  982. ret["maxProperties"] = Struct::maxPropertiesCheck;
  983. ret["minProperties"] = Struct::minPropertiesCheck;
  984. ret["dependencies"] = Struct::dependenciesCheck;
  985. ret["properties"] = Struct::propertiesCheck;
  986. ret["required"] = Struct::requiredCheck;
  987. ret["patternProperties"] = Common::notImplementedCheck;
  988. return ret;
  989. }
  990. Validation::TFormatMap createFormatMap()
  991. {
  992. Validation::TFormatMap ret;
  993. ret["textFile"] = Formats::textFile;
  994. ret["musicFile"] = Formats::musicFile;
  995. ret["soundFile"] = Formats::soundFile;
  996. ret["defFile"] = Formats::defFile;
  997. ret["animationFile"] = Formats::animationFile;
  998. ret["imageFile"] = Formats::imageFile;
  999. ret["videoFile"] = Formats::videoFile;
  1000. return ret;
  1001. }
  1002. }
  1003. namespace Validation
  1004. {
  1005. std::string ValidationData::makeErrorMessage(const std::string &message)
  1006. {
  1007. std::string errors;
  1008. errors += "At ";
  1009. if (!currentPath.empty())
  1010. {
  1011. for(const JsonNode &path : currentPath)
  1012. {
  1013. errors += "/";
  1014. if (path.getType() == JsonNode::JsonType::DATA_STRING)
  1015. errors += path.String();
  1016. else
  1017. errors += std::to_string(static_cast<unsigned>(path.Float()));
  1018. }
  1019. }
  1020. else
  1021. errors += "<root>";
  1022. errors += "\n\t Error: " + message + "\n";
  1023. return errors;
  1024. }
  1025. std::string check(const std::string & schemaName, const JsonNode & data)
  1026. {
  1027. ValidationData validator;
  1028. return check(schemaName, data, validator);
  1029. }
  1030. std::string check(const std::string & schemaName, const JsonNode & data, ValidationData & validator)
  1031. {
  1032. validator.usedSchemas.push_back(schemaName);
  1033. auto onscopeExit = vstd::makeScopeGuard([&]()
  1034. {
  1035. validator.usedSchemas.pop_back();
  1036. });
  1037. return check(JsonUtils::getSchema(schemaName), data, validator);
  1038. }
  1039. std::string check(const JsonNode & schema, const JsonNode & data, ValidationData & validator)
  1040. {
  1041. const TValidatorMap & knownFields = getKnownFieldsFor(data.getType());
  1042. std::string errors;
  1043. for(const auto & entry : schema.Struct())
  1044. {
  1045. auto checker = knownFields.find(entry.first);
  1046. if (checker != knownFields.end())
  1047. errors += checker->second(validator, schema, entry.second, data);
  1048. //else
  1049. // errors += validator.makeErrorMessage("Unknown entry in schema " + entry.first);
  1050. }
  1051. return errors;
  1052. }
  1053. const TValidatorMap & getKnownFieldsFor(JsonNode::JsonType type)
  1054. {
  1055. static const TValidatorMap commonFields = createCommonFields();
  1056. static const TValidatorMap numberFields = createNumberFields();
  1057. static const TValidatorMap stringFields = createStringFields();
  1058. static const TValidatorMap vectorFields = createVectorFields();
  1059. static const TValidatorMap structFields = createStructFields();
  1060. switch (type)
  1061. {
  1062. case JsonNode::JsonType::DATA_FLOAT:
  1063. case JsonNode::JsonType::DATA_INTEGER:
  1064. return numberFields;
  1065. case JsonNode::JsonType::DATA_STRING: return stringFields;
  1066. case JsonNode::JsonType::DATA_VECTOR: return vectorFields;
  1067. case JsonNode::JsonType::DATA_STRUCT: return structFields;
  1068. default: return commonFields;
  1069. }
  1070. }
  1071. const TFormatMap & getKnownFormats()
  1072. {
  1073. static TFormatMap knownFormats = createFormatMap();
  1074. return knownFormats;
  1075. }
  1076. } // Validation namespace
  1077. VCMI_LIB_NAMESPACE_END