JsonDetail.cpp 35 KB

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