JsonNode.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. /*
  2. * JsonNode.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 "JsonNode.h"
  12. #include "ScopeGuard.h"
  13. #include "HeroBonus.h"
  14. #include "filesystem/Filesystem.h"
  15. #include "VCMI_Lib.h" //for identifier resolution
  16. #include "CModHandler.h"
  17. using namespace JsonDetail;
  18. class LibClasses;
  19. class CModHandler;
  20. static const JsonNode nullNode;
  21. JsonNode::JsonNode(JsonType Type):
  22. type(DATA_NULL)
  23. {
  24. setType(Type);
  25. }
  26. JsonNode::JsonNode(const char *data, size_t datasize):
  27. type(DATA_NULL)
  28. {
  29. JsonParser parser(data, datasize);
  30. *this = parser.parse("<unknown>");
  31. }
  32. JsonNode::JsonNode(ResourceID && fileURI):
  33. type(DATA_NULL)
  34. {
  35. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  36. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  37. *this = parser.parse(fileURI.getName());
  38. }
  39. JsonNode::JsonNode(const JsonNode &copy):
  40. type(DATA_NULL)
  41. {
  42. meta = copy.meta;
  43. setType(copy.getType());
  44. switch(type)
  45. {
  46. break; case DATA_NULL:
  47. break; case DATA_BOOL: Bool() = copy.Bool();
  48. break; case DATA_FLOAT: Float() = copy.Float();
  49. break; case DATA_STRING: String() = copy.String();
  50. break; case DATA_VECTOR: Vector() = copy.Vector();
  51. break; case DATA_STRUCT: Struct() = copy.Struct();
  52. }
  53. }
  54. JsonNode::~JsonNode()
  55. {
  56. setType(DATA_NULL);
  57. }
  58. void JsonNode::swap(JsonNode &b)
  59. {
  60. using std::swap;
  61. swap(meta, b.meta);
  62. swap(data, b.data);
  63. swap(type, b.type);
  64. }
  65. JsonNode & JsonNode::operator =(JsonNode node)
  66. {
  67. swap(node);
  68. return *this;
  69. }
  70. bool JsonNode::operator == (const JsonNode &other) const
  71. {
  72. if (getType() == other.getType())
  73. {
  74. switch(type)
  75. {
  76. break; case DATA_NULL: return true;
  77. break; case DATA_BOOL: return Bool() == other.Bool();
  78. break; case DATA_FLOAT: return Float() == other.Float();
  79. break; case DATA_STRING: return String() == other.String();
  80. break; case DATA_VECTOR: return Vector() == other.Vector();
  81. break; case DATA_STRUCT: return Struct() == other.Struct();
  82. }
  83. }
  84. return false;
  85. }
  86. bool JsonNode::operator != (const JsonNode &other) const
  87. {
  88. return !(*this == other);
  89. }
  90. JsonNode::JsonType JsonNode::getType() const
  91. {
  92. return type;
  93. }
  94. void JsonNode::setMeta(std::string metadata, bool recursive)
  95. {
  96. meta = metadata;
  97. if (recursive)
  98. {
  99. switch (type)
  100. {
  101. break; case DATA_VECTOR:
  102. {
  103. for(auto & node : Vector())
  104. {
  105. node.setMeta(metadata);
  106. }
  107. }
  108. break; case DATA_STRUCT:
  109. {
  110. for(auto & node : Struct())
  111. {
  112. node.second.setMeta(metadata);
  113. }
  114. }
  115. }
  116. }
  117. }
  118. void JsonNode::setType(JsonType Type)
  119. {
  120. if (type == Type)
  121. return;
  122. //Reset node to nullptr
  123. if (Type != DATA_NULL)
  124. setType(DATA_NULL);
  125. switch (type)
  126. {
  127. break; case DATA_STRING: delete data.String;
  128. break; case DATA_VECTOR: delete data.Vector;
  129. break; case DATA_STRUCT: delete data.Struct;
  130. break; default:
  131. break;
  132. }
  133. //Set new node type
  134. type = Type;
  135. switch(type)
  136. {
  137. break; case DATA_NULL:
  138. break; case DATA_BOOL: data.Bool = false;
  139. break; case DATA_FLOAT: data.Float = 0;
  140. break; case DATA_STRING: data.String = new std::string();
  141. break; case DATA_VECTOR: data.Vector = new JsonVector();
  142. break; case DATA_STRUCT: data.Struct = new JsonMap();
  143. }
  144. }
  145. bool JsonNode::isNull() const
  146. {
  147. return type == DATA_NULL;
  148. }
  149. void JsonNode::clear()
  150. {
  151. setType(DATA_NULL);
  152. }
  153. bool & JsonNode::Bool()
  154. {
  155. setType(DATA_BOOL);
  156. return data.Bool;
  157. }
  158. double & JsonNode::Float()
  159. {
  160. setType(DATA_FLOAT);
  161. return data.Float;
  162. }
  163. std::string & JsonNode::String()
  164. {
  165. setType(DATA_STRING);
  166. return *data.String;
  167. }
  168. JsonVector & JsonNode::Vector()
  169. {
  170. setType(DATA_VECTOR);
  171. return *data.Vector;
  172. }
  173. JsonMap & JsonNode::Struct()
  174. {
  175. setType(DATA_STRUCT);
  176. return *data.Struct;
  177. }
  178. const bool boolDefault = false;
  179. const bool & JsonNode::Bool() const
  180. {
  181. if (type == DATA_NULL)
  182. return boolDefault;
  183. assert(type == DATA_BOOL);
  184. return data.Bool;
  185. }
  186. const double floatDefault = 0;
  187. const double & JsonNode::Float() const
  188. {
  189. if (type == DATA_NULL)
  190. return floatDefault;
  191. assert(type == DATA_FLOAT);
  192. return data.Float;
  193. }
  194. const std::string stringDefault = std::string();
  195. const std::string & JsonNode::String() const
  196. {
  197. if (type == DATA_NULL)
  198. return stringDefault;
  199. assert(type == DATA_STRING);
  200. return *data.String;
  201. }
  202. const JsonVector vectorDefault = JsonVector();
  203. const JsonVector & JsonNode::Vector() const
  204. {
  205. if (type == DATA_NULL)
  206. return vectorDefault;
  207. assert(type == DATA_VECTOR);
  208. return *data.Vector;
  209. }
  210. const JsonMap mapDefault = JsonMap();
  211. const JsonMap & JsonNode::Struct() const
  212. {
  213. if (type == DATA_NULL)
  214. return mapDefault;
  215. assert(type == DATA_STRUCT);
  216. return *data.Struct;
  217. }
  218. JsonNode & JsonNode::operator[](std::string child)
  219. {
  220. return Struct()[child];
  221. }
  222. const JsonNode & JsonNode::operator[](std::string child) const
  223. {
  224. auto it = Struct().find(child);
  225. if (it != Struct().end())
  226. return it->second;
  227. return nullNode;
  228. }
  229. // to avoid duplicating const and non-const code
  230. template<typename Node>
  231. Node & resolvePointer(Node & in, const std::string & pointer)
  232. {
  233. if (pointer.empty())
  234. return in;
  235. assert(pointer[0] == '/');
  236. size_t splitPos = pointer.find('/', 1);
  237. std::string entry = pointer.substr(1, splitPos -1);
  238. std::string remainer = splitPos == std::string::npos ? "" : pointer.substr(splitPos);
  239. if (in.getType() == JsonNode::DATA_VECTOR)
  240. {
  241. if (entry.find_first_not_of("0123456789") != std::string::npos) // non-numbers in string
  242. throw std::runtime_error("Invalid Json pointer");
  243. if (entry.size() > 1 && entry[0] == '0') // leading zeros are not allowed
  244. throw std::runtime_error("Invalid Json pointer");
  245. size_t index = boost::lexical_cast<size_t>(entry);
  246. if (in.Vector().size() > index)
  247. return in.Vector()[index].resolvePointer(remainer);
  248. }
  249. return in[entry].resolvePointer(remainer);
  250. }
  251. const JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer) const
  252. {
  253. return ::resolvePointer(*this, jsonPointer);
  254. }
  255. JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer)
  256. {
  257. return ::resolvePointer(*this, jsonPointer);
  258. }
  259. ////////////////////////////////////////////////////////////////////////////////
  260. template<typename Iterator>
  261. void JsonWriter::writeContainer(Iterator begin, Iterator end)
  262. {
  263. if (begin == end)
  264. return;
  265. prefix += '\t';
  266. writeEntry(begin++);
  267. while (begin != end)
  268. {
  269. out<<",\n";
  270. writeEntry(begin++);
  271. }
  272. out<<"\n";
  273. prefix.resize(prefix.size()-1);
  274. }
  275. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  276. {
  277. out << prefix;
  278. writeString(entry->first);
  279. out << " : ";
  280. writeNode(entry->second);
  281. }
  282. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  283. {
  284. out << prefix;
  285. writeNode(*entry);
  286. }
  287. void JsonWriter::writeString(const std::string &string)
  288. {
  289. static const std::string escaped = "\"\\\b\f\n\r\t";
  290. out <<'\"';
  291. size_t pos=0, start=0;
  292. for (; pos<string.size(); pos++)
  293. {
  294. size_t escapedChar = escaped.find(string[pos]);
  295. if (escapedChar != std::string::npos)
  296. {
  297. out.write(string.data()+start, pos - start);
  298. out << '\\' << escaped[escapedChar];
  299. start = pos;
  300. }
  301. }
  302. out.write(string.data()+start, pos - start);
  303. out <<'\"';
  304. }
  305. void JsonWriter::writeNode(const JsonNode &node)
  306. {
  307. switch(node.getType())
  308. {
  309. break; case JsonNode::DATA_NULL:
  310. out << "null";
  311. break; case JsonNode::DATA_BOOL:
  312. if (node.Bool())
  313. out << "true";
  314. else
  315. out << "false";
  316. break; case JsonNode::DATA_FLOAT:
  317. out << node.Float();
  318. break; case JsonNode::DATA_STRING:
  319. writeString(node.String());
  320. break; case JsonNode::DATA_VECTOR:
  321. out << "[" << "\n";
  322. writeContainer(node.Vector().begin(), node.Vector().end());
  323. out << prefix << "]";
  324. break; case JsonNode::DATA_STRUCT:
  325. out << "{" << "\n";
  326. writeContainer(node.Struct().begin(), node.Struct().end());
  327. out << prefix << "}";
  328. }
  329. if (!node.meta.empty()) // write metainf as comment
  330. out << " //" << node.meta;
  331. }
  332. JsonWriter::JsonWriter(std::ostream &output, const JsonNode &node):
  333. out(output)
  334. {
  335. writeNode(node);
  336. }
  337. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  338. {
  339. JsonWriter(out, node);
  340. return out << "\n";
  341. }
  342. ////////////////////////////////////////////////////////////////////////////////
  343. JsonParser::JsonParser(const char * inputString, size_t stringSize):
  344. input(inputString, stringSize),
  345. lineCount(1),
  346. lineStart(0),
  347. pos(0)
  348. {
  349. }
  350. JsonNode JsonParser::parse(std::string fileName)
  351. {
  352. JsonNode root;
  353. extractValue(root);
  354. extractWhitespace(false);
  355. //Warn if there are any non-whitespace symbols left
  356. if (pos < input.size())
  357. error("Not all file was parsed!", true);
  358. if (!errors.empty())
  359. {
  360. logGlobal->warnStream()<<"File " << fileName << " is not a valid JSON file!";
  361. logGlobal->warnStream()<<errors;
  362. }
  363. return root;
  364. }
  365. bool JsonParser::extractSeparator()
  366. {
  367. if (!extractWhitespace())
  368. return false;
  369. if ( input[pos] !=':')
  370. return error("Separator expected");
  371. pos++;
  372. return true;
  373. }
  374. bool JsonParser::extractValue(JsonNode &node)
  375. {
  376. if (!extractWhitespace())
  377. return false;
  378. switch (input[pos])
  379. {
  380. case '\"': return extractString(node);
  381. case 'n' : return extractNull(node);
  382. case 't' : return extractTrue(node);
  383. case 'f' : return extractFalse(node);
  384. case '{' : return extractStruct(node);
  385. case '[' : return extractArray(node);
  386. case '-' : return extractFloat(node);
  387. default:
  388. {
  389. if (input[pos] >= '0' && input[pos] <= '9')
  390. return extractFloat(node);
  391. return error("Value expected!");
  392. }
  393. }
  394. }
  395. bool JsonParser::extractWhitespace(bool verbose)
  396. {
  397. while (true)
  398. {
  399. while (pos < input.size() && (ui8)input[pos] <= ' ')
  400. {
  401. if (input[pos] == '\n')
  402. {
  403. lineCount++;
  404. lineStart = pos+1;
  405. }
  406. pos++;
  407. }
  408. if (pos >= input.size() || input[pos] != '/')
  409. break;
  410. pos++;
  411. if (pos == input.size())
  412. break;
  413. if (input[pos] == '/')
  414. pos++;
  415. else
  416. error("Comments must consist from two slashes!", true);
  417. while (pos < input.size() && input[pos] != '\n')
  418. pos++;
  419. }
  420. if (pos >= input.size() && verbose)
  421. return error("Unexpected end of file!");
  422. return true;
  423. }
  424. bool JsonParser::extractEscaping(std::string &str)
  425. {
  426. switch(input[pos])
  427. {
  428. break; case '\"': str += '\"';
  429. break; case '\\': str += '\\';
  430. break; case 'b': str += '\b';
  431. break; case 'f': str += '\f';
  432. break; case 'n': str += '\n';
  433. break; case 'r': str += '\r';
  434. break; case 't': str += '\t';
  435. break; default: return error("Unknown escape sequence!", true);
  436. };
  437. return true;
  438. }
  439. bool JsonParser::extractString(std::string &str)
  440. {
  441. if (input[pos] != '\"')
  442. return error("String expected!");
  443. pos++;
  444. size_t first = pos;
  445. while (pos != input.size())
  446. {
  447. if (input[pos] == '\"') // Correct end of string
  448. {
  449. str.append( &input[first], pos-first);
  450. pos++;
  451. return true;
  452. }
  453. if (input[pos] == '\\') // Escaping
  454. {
  455. str.append( &input[first], pos-first);
  456. pos++;
  457. if (pos == input.size())
  458. break;
  459. extractEscaping(str);
  460. first = pos + 1;
  461. }
  462. if (input[pos] == '\n') // end-of-line
  463. {
  464. str.append( &input[first], pos-first);
  465. return error("Closing quote not found!", true);
  466. }
  467. if ((unsigned char)(input[pos]) < ' ') // control character
  468. {
  469. str.append( &input[first], pos-first);
  470. first = pos+1;
  471. error("Illegal character in the string!", true);
  472. }
  473. pos++;
  474. }
  475. return error("Unterminated string!");
  476. }
  477. bool JsonParser::extractString(JsonNode &node)
  478. {
  479. std::string str;
  480. if (!extractString(str))
  481. return false;
  482. node.setType(JsonNode::DATA_STRING);
  483. node.String() = str;
  484. return true;
  485. }
  486. bool JsonParser::extractLiteral(const std::string &literal)
  487. {
  488. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  489. {
  490. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  491. || (input[pos]>'A' && input[pos]<'Z')))
  492. pos++;
  493. return error("Unknown literal found", true);
  494. }
  495. pos += literal.size();
  496. return true;
  497. }
  498. bool JsonParser::extractNull(JsonNode &node)
  499. {
  500. if (!extractLiteral("null"))
  501. return false;
  502. node.clear();
  503. return true;
  504. }
  505. bool JsonParser::extractTrue(JsonNode &node)
  506. {
  507. if (!extractLiteral("true"))
  508. return false;
  509. node.Bool() = true;
  510. return true;
  511. }
  512. bool JsonParser::extractFalse(JsonNode &node)
  513. {
  514. if (!extractLiteral("false"))
  515. return false;
  516. node.Bool() = false;
  517. return true;
  518. }
  519. bool JsonParser::extractStruct(JsonNode &node)
  520. {
  521. node.setType(JsonNode::DATA_STRUCT);
  522. pos++;
  523. if (!extractWhitespace())
  524. return false;
  525. //Empty struct found
  526. if (input[pos] == '}')
  527. {
  528. pos++;
  529. return true;
  530. }
  531. while (true)
  532. {
  533. if (!extractWhitespace())
  534. return false;
  535. std::string key;
  536. if (!extractString(key))
  537. return false;
  538. if (node.Struct().find(key) != node.Struct().end())
  539. error("Dublicated element encountered!", true);
  540. if (!extractSeparator())
  541. return false;
  542. if (!extractElement(node.Struct()[key], '}'))
  543. return false;
  544. if (input[pos] == '}')
  545. {
  546. pos++;
  547. return true;
  548. }
  549. }
  550. }
  551. bool JsonParser::extractArray(JsonNode &node)
  552. {
  553. pos++;
  554. node.setType(JsonNode::DATA_VECTOR);
  555. if (!extractWhitespace())
  556. return false;
  557. //Empty array found
  558. if (input[pos] == ']')
  559. {
  560. pos++;
  561. return true;
  562. }
  563. while (true)
  564. {
  565. //NOTE: currently 50% of time is this vector resizing.
  566. //May be useful to use list during parsing and then swap() all items to vector
  567. node.Vector().resize(node.Vector().size()+1);
  568. if (!extractElement(node.Vector().back(), ']'))
  569. return false;
  570. if (input[pos] == ']')
  571. {
  572. pos++;
  573. return true;
  574. }
  575. }
  576. }
  577. bool JsonParser::extractElement(JsonNode &node, char terminator)
  578. {
  579. if (!extractValue(node))
  580. return false;
  581. if (!extractWhitespace())
  582. return false;
  583. bool comma = (input[pos] == ',');
  584. if (comma )
  585. {
  586. pos++;
  587. if (!extractWhitespace())
  588. return false;
  589. }
  590. if (input[pos] == terminator)
  591. {
  592. //FIXME: MOD COMPATIBILITY: Too many of these right now, re-enable later
  593. //if (comma)
  594. //error("Extra comma found!", true);
  595. return true;
  596. }
  597. if (!comma)
  598. error("Comma expected!", true);
  599. return true;
  600. }
  601. bool JsonParser::extractFloat(JsonNode &node)
  602. {
  603. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  604. bool negative=false;
  605. double result=0;
  606. if (input[pos] == '-')
  607. {
  608. pos++;
  609. negative = true;
  610. }
  611. if (input[pos] < '0' || input[pos] > '9')
  612. return error("Number expected!");
  613. //Extract integer part
  614. while (input[pos] >= '0' && input[pos] <= '9')
  615. {
  616. result = result*10+(input[pos]-'0');
  617. pos++;
  618. }
  619. if (input[pos] == '.')
  620. {
  621. //extract fractional part
  622. pos++;
  623. double fractMult = 0.1;
  624. if (input[pos] < '0' || input[pos] > '9')
  625. return error("Decimal part expected!");
  626. while (input[pos] >= '0' && input[pos] <= '9')
  627. {
  628. result = result + fractMult*(input[pos]-'0');
  629. fractMult /= 10;
  630. pos++;
  631. }
  632. }
  633. //TODO: exponential part
  634. if (negative)
  635. result = -result;
  636. node.setType(JsonNode::DATA_FLOAT);
  637. node.Float() = result;
  638. return true;
  639. }
  640. bool JsonParser::error(const std::string &message, bool warning)
  641. {
  642. std::ostringstream stream;
  643. std::string type(warning?" warning: ":" error: ");
  644. stream << "At line " << lineCount << ", position "<<pos-lineStart
  645. << type << message <<"\n";
  646. errors += stream.str();
  647. return warning;
  648. }
  649. static const std::map<std::string, JsonNode::JsonType> stringToType =
  650. boost::assign::map_list_of
  651. ("null", JsonNode::DATA_NULL) ("boolean", JsonNode::DATA_BOOL)
  652. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  653. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  654. std::string JsonValidator::validateEnum(const JsonNode &node, const JsonVector &enumeration)
  655. {
  656. for(auto & enumEntry : enumeration)
  657. {
  658. if (node == enumEntry)
  659. return "";
  660. }
  661. return fail("Key must have one of predefined values");
  662. }
  663. std::string JsonValidator::validatesSchemaList(const JsonNode &node, const JsonNode &schemas, std::string errorMsg, std::function<bool(size_t)> isValid)
  664. {
  665. if (!schemas.isNull())
  666. {
  667. std::string errors = "<tested schemas>\n";
  668. size_t result = 0;
  669. for(auto & schema : schemas.Vector())
  670. {
  671. std::string error = validateNode(node, schema);
  672. if (error.empty())
  673. {
  674. result++;
  675. }
  676. else
  677. {
  678. errors += error;
  679. errors += "<end of schema>\n";
  680. }
  681. }
  682. if (isValid(result))
  683. {
  684. return "";
  685. }
  686. return fail(errorMsg) + errors;
  687. }
  688. return "";
  689. }
  690. std::string JsonValidator::validateNodeType(const JsonNode &node, const JsonNode &schema)
  691. {
  692. std::string errors;
  693. // data must be valid against all schemas in the list
  694. errors += validatesSchemaList(node, schema["allOf"], "Failed to pass all schemas", [&](size_t count)
  695. {
  696. return count == schema["allOf"].Vector().size();
  697. });
  698. // data must be valid against any non-zero number of schemas in the list
  699. errors += validatesSchemaList(node, schema["anyOf"], "Failed to pass any schema", [&](size_t count)
  700. {
  701. return count > 0;
  702. });
  703. // data must be valid against one and only one schema
  704. errors += validatesSchemaList(node, schema["oneOf"], "Failed to pass one and only one schema", [&](size_t count)
  705. {
  706. return count == 1;
  707. });
  708. // data must NOT be valid against schema
  709. if (!schema["not"].isNull())
  710. {
  711. if (validateNode(node, schema["not"]).empty())
  712. errors += fail("Successful validation against negative check");
  713. }
  714. return errors;
  715. }
  716. // Basic checks common for any nodes
  717. std::string JsonValidator::validateNode(const JsonNode &node, const JsonNode &schema)
  718. {
  719. std::string errors;
  720. assert(!schema.isNull()); // can this error be triggered?
  721. if (node.isNull())
  722. return ""; // node not present. consider to be "valid"
  723. if (!schema["$ref"].isNull())
  724. {
  725. std::string URI = schema["$ref"].String();
  726. //node must be validated using schema pointed by this reference and not by data here
  727. //Local reference. Turn it into more easy to handle remote ref
  728. if (boost::algorithm::starts_with(URI, "#"))
  729. URI = usedSchemas.back() + URI;
  730. return validateRoot(node, URI);
  731. }
  732. // basic schema check
  733. auto & typeNode = schema["type"];
  734. if ( !typeNode.isNull())
  735. {
  736. JsonNode::JsonType type = stringToType.find(typeNode.String())->second;
  737. if(type != node.getType())
  738. return errors + fail("Type mismatch!"); // different type. Any other checks are useless
  739. }
  740. errors += validateNodeType(node, schema);
  741. // enumeration - data must be equeal to one of items in list
  742. if (!schema["enum"].isNull())
  743. errors += validateEnum(node, schema["enum"].Vector());
  744. // try to run any type-specific checks
  745. if (node.getType() == JsonNode::DATA_VECTOR) errors += validateVector(node, schema);
  746. if (node.getType() == JsonNode::DATA_STRUCT) errors += validateStruct(node, schema);
  747. if (node.getType() == JsonNode::DATA_STRING) errors += validateString(node, schema);
  748. if (node.getType() == JsonNode::DATA_FLOAT) errors += validateNumber(node, schema);
  749. return errors;
  750. }
  751. std::string JsonValidator::validateVectorItem(const JsonVector items, const JsonNode & schema, const JsonNode & additional, size_t index)
  752. {
  753. currentPath.push_back(JsonNode());
  754. currentPath.back().Float() = index;
  755. auto onExit = vstd::makeScopeGuard([&]
  756. {
  757. currentPath.pop_back();
  758. });
  759. if (!schema.isNull())
  760. {
  761. // case 1: schema is vector. Validate items agaist corresponding items in vector
  762. if (schema.getType() == JsonNode::DATA_VECTOR)
  763. {
  764. if (schema.Vector().size() > index)
  765. return validateNode(items[index], schema.Vector()[index]);
  766. }
  767. else // case 2: schema has to be struct. Apply it to all items, completely ignore additionalItems
  768. {
  769. return validateNode(items[index], schema);
  770. }
  771. }
  772. // othervice check against schema in additional items field
  773. if (additional.getType() == JsonNode::DATA_STRUCT)
  774. return validateNode(items[index], additional);
  775. // or, additionalItems field can be bool which indicates if such items are allowed
  776. if (!additional.isNull() && additional.Bool() == false) // present and set to false - error
  777. return fail("Unknown entry found");
  778. // by default - additional items are allowed
  779. return "";
  780. }
  781. //Checks "items" entry from schema (type-specific check for Vector)
  782. std::string JsonValidator::validateVector(const JsonNode &node, const JsonNode &schema)
  783. {
  784. std::string errors;
  785. auto & vector = node.Vector();
  786. {
  787. auto & items = schema["items"];
  788. auto & additional = schema["additionalItems"];
  789. for (size_t i=0; i<vector.size(); i++)
  790. errors += validateVectorItem(vector, items, additional, i);
  791. }
  792. if (vstd::contains(schema.Struct(), "maxItems") && vector.size() > schema["maxItems"].Float())
  793. errors += fail("Too many items in the list!");
  794. if (vstd::contains(schema.Struct(), "minItems") && vector.size() < schema["minItems"].Float())
  795. errors += fail("Too few items in the list");
  796. if (schema["uniqueItems"].Bool())
  797. {
  798. for (auto itA = vector.begin(); itA != vector.end(); itA++)
  799. {
  800. auto itB = itA;
  801. while (++itB != vector.end())
  802. {
  803. if (*itA == *itB)
  804. errors += fail("List must consist from unique items");
  805. }
  806. }
  807. }
  808. return errors;
  809. }
  810. std::string JsonValidator::validateStructItem(const JsonNode &node, const JsonNode & schema, const JsonNode & additional, std::string nodeName)
  811. {
  812. currentPath.push_back(JsonNode());
  813. currentPath.back().String() = nodeName;
  814. auto onExit = vstd::makeScopeGuard([&]
  815. {
  816. currentPath.pop_back();
  817. });
  818. // there is schema specifically for this item
  819. if (!schema[nodeName].isNull())
  820. return validateNode(node, schema[nodeName]);
  821. // try generic additionalItems schema
  822. if (additional.getType() == JsonNode::DATA_STRUCT)
  823. return validateNode(node, additional);
  824. // or, additionalItems field can be bool which indicates if such items are allowed
  825. if (!additional.isNull() && additional.Bool() == false) // present and set to false - error
  826. return fail("Unknown entry found: " + nodeName);
  827. // by default - additional items are allowed
  828. return "";
  829. }
  830. //Checks "properties" entry from schema (type-specific check for Struct)
  831. std::string JsonValidator::validateStruct(const JsonNode &node, const JsonNode &schema)
  832. {
  833. std::string errors;
  834. auto & map = node.Struct();
  835. {
  836. auto & properties = schema["properties"];
  837. auto & additional = schema["additionalProperties"];
  838. for(auto & entry : map)
  839. errors += validateStructItem(entry.second, properties, additional, entry.first);
  840. }
  841. for(auto & required : schema["required"].Vector())
  842. {
  843. if (node[required.String()].isNull())
  844. errors += fail("Required entry " + required.String() + " is missing");
  845. }
  846. //Copy-paste from vector code. yay!
  847. if (vstd::contains(schema.Struct(), "maxProperties") && map.size() > schema["maxProperties"].Float())
  848. errors += fail("Too many items in the list!");
  849. if (vstd::contains(schema.Struct(), "minItems") && map.size() < schema["minItems"].Float())
  850. errors += fail("Too few items in the list");
  851. if (schema["uniqueItems"].Bool())
  852. {
  853. for (auto itA = map.begin(); itA != map.end(); itA++)
  854. {
  855. auto itB = itA;
  856. while (++itB != map.end())
  857. {
  858. if (itA->second == itB->second)
  859. errors += fail("List must consist from unique items");
  860. }
  861. }
  862. }
  863. // dependencies. Format is object/struct where key is the name of key in data
  864. // and value is either:
  865. // a) array of fields that must be present
  866. // b) struct with schema against which data should be valid
  867. // These checks are triggered only if key is present
  868. for(auto & deps : schema["dependencies"].Struct())
  869. {
  870. if (vstd::contains(map, deps.first))
  871. {
  872. if (deps.second.getType() == JsonNode::DATA_VECTOR)
  873. {
  874. JsonVector depList = deps.second.Vector();
  875. for(auto & depEntry : depList)
  876. {
  877. if (!vstd::contains(map, depEntry.String()))
  878. errors += fail("Property " + depEntry.String() + " required for " + deps.first + " is missing");
  879. }
  880. }
  881. else
  882. {
  883. if (!validateNode(node, deps.second).empty())
  884. errors += fail("Requirements for " + deps.first + " are not fulfilled");
  885. }
  886. }
  887. }
  888. // TODO: missing fields from draft v4
  889. // patternProperties
  890. return errors;
  891. }
  892. std::string JsonValidator::validateString(const JsonNode &node, const JsonNode &schema)
  893. {
  894. std::string errors;
  895. auto & string = node.String();
  896. if (vstd::contains(schema.Struct(), "maxLength") && string.size() > schema["maxLength"].Float())
  897. errors += fail("String too long");
  898. if (vstd::contains(schema.Struct(), "minLength") && string.size() < schema["minLength"].Float())
  899. errors += fail("String too short");
  900. // TODO: missing fields from draft v4
  901. // pattern
  902. return errors;
  903. }
  904. std::string JsonValidator::validateNumber(const JsonNode &node, const JsonNode &schema)
  905. {
  906. std::string errors;
  907. auto & value = node.Float();
  908. if (vstd::contains(schema.Struct(), "maximum"))
  909. {
  910. if (schema["exclusiveMaximum"].Bool())
  911. {
  912. if (value >= schema["maximum"].Float())
  913. errors += fail("Value is too large");
  914. }
  915. else
  916. {
  917. if (value > schema["maximum"].Float())
  918. errors += fail("Value is too large");
  919. }
  920. }
  921. if (vstd::contains(schema.Struct(), "minimum"))
  922. {
  923. if (schema["exclusiveMinimum"].Bool())
  924. {
  925. if (value <= schema["minimum"].Float())
  926. errors += fail("Value is too small");
  927. }
  928. else
  929. {
  930. if (value < schema["minimum"].Float())
  931. errors += fail("Value is too small");
  932. }
  933. }
  934. if (vstd::contains(schema.Struct(), "multipleOf"))
  935. {
  936. double result = value / schema["multipleOf"].Float();
  937. if (floor(result) != result)
  938. errors += ("Value is not divisible");
  939. }
  940. return errors;
  941. }
  942. //basic schema validation (like checking $schema entry).
  943. std::string JsonValidator::validateRoot(const JsonNode &node, std::string schemaName)
  944. {
  945. const JsonNode & schema = JsonUtils::getSchema(schemaName);
  946. usedSchemas.push_back(schemaName.substr(0, schemaName.find('#')));
  947. auto onExit = vstd::makeScopeGuard([&]
  948. {
  949. usedSchemas.pop_back();
  950. });
  951. if (!schema.isNull())
  952. return validateNode(node, schema);
  953. else
  954. return fail("Schema not found!");
  955. }
  956. std::string JsonValidator::fail(const std::string &message)
  957. {
  958. std::string errors;
  959. errors += "At ";
  960. if (!currentPath.empty())
  961. {
  962. for(const JsonNode &path : currentPath)
  963. {
  964. errors += "/";
  965. if (path.getType() == JsonNode::DATA_STRING)
  966. errors += path.String();
  967. else
  968. errors += boost::lexical_cast<std::string>(static_cast<unsigned>(path.Float()));
  969. }
  970. }
  971. else
  972. errors += "<root>";
  973. errors += "\n\t Error: " + message + "\n";
  974. return errors;
  975. }
  976. bool JsonValidator::validate(const JsonNode &root, std::string schemaName, std::string name)
  977. {
  978. std::string errors = validateRoot(root, schemaName);
  979. if (!errors.empty())
  980. {
  981. logGlobal->warnStream() << "Data in " << name << " is invalid!";
  982. logGlobal->warnStream() << errors;
  983. }
  984. return errors.empty();
  985. }
  986. ///JsonUtils
  987. void JsonUtils::parseTypedBonusShort(const JsonVector& source, Bonus *dest)
  988. {
  989. dest->val = source[1].Float();
  990. resolveIdentifier(source[2],dest->subtype);
  991. dest->additionalInfo = source[3].Float();
  992. dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  993. dest->turnsRemain = 0;
  994. }
  995. Bonus * JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  996. {
  997. auto b = new Bonus();
  998. std::string type = ability_vec[0].String();
  999. auto it = bonusNameMap.find(type);
  1000. if (it == bonusNameMap.end())
  1001. {
  1002. logGlobal->errorStream() << "Error: invalid ability type " << type;
  1003. return b;
  1004. }
  1005. b->type = it->second;
  1006. parseTypedBonusShort(ability_vec, b);
  1007. return b;
  1008. }
  1009. template <typename T>
  1010. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  1011. {
  1012. static T defaultValue = T();
  1013. if (!val->isNull())
  1014. {
  1015. std::string type = val->String();
  1016. auto it = map.find(type);
  1017. if (it == map.end())
  1018. {
  1019. logGlobal->errorStream() << "Error: invalid " << err << type;
  1020. return defaultValue;
  1021. }
  1022. else
  1023. {
  1024. return it->second;
  1025. }
  1026. }
  1027. else
  1028. return defaultValue;
  1029. }
  1030. void JsonUtils::resolveIdentifier (si32 &var, const JsonNode &node, std::string name)
  1031. {
  1032. const JsonNode &value = node[name];
  1033. if (!value.isNull())
  1034. {
  1035. switch (value.getType())
  1036. {
  1037. case JsonNode::DATA_FLOAT:
  1038. var = value.Float();
  1039. break;
  1040. case JsonNode::DATA_STRING:
  1041. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  1042. {
  1043. var = identifier;
  1044. });
  1045. break;
  1046. default:
  1047. logGlobal->errorStream() << "Error! Wrong indentifier used for value of " << name;
  1048. }
  1049. }
  1050. }
  1051. void JsonUtils::resolveIdentifier (const JsonNode &node, si32 &var)
  1052. {
  1053. switch (node.getType())
  1054. {
  1055. case JsonNode::DATA_FLOAT:
  1056. var = node.Float();
  1057. break;
  1058. case JsonNode::DATA_STRING:
  1059. VLC->modh->identifiers.requestIdentifier (node, [&](si32 identifier)
  1060. {
  1061. var = identifier;
  1062. });
  1063. break;
  1064. default:
  1065. logGlobal->errorStream() << "Error! Wrong indentifier used for identifier!";
  1066. }
  1067. }
  1068. Bonus * JsonUtils::parseBonus (const JsonNode &ability)
  1069. {
  1070. auto b = new Bonus();
  1071. const JsonNode *value;
  1072. std::string type = ability["type"].String();
  1073. auto it = bonusNameMap.find(type);
  1074. if (it == bonusNameMap.end())
  1075. {
  1076. logGlobal->errorStream() << "Error: invalid ability type " << type;
  1077. return b;
  1078. }
  1079. b->type = it->second;
  1080. resolveIdentifier (b->subtype, ability, "subtype");
  1081. b->val = ability["val"].Float();
  1082. value = &ability["valueType"];
  1083. if (!value->isNull())
  1084. b->valType = static_cast<Bonus::ValueType>(parseByMap(bonusValueMap, value, "value type "));
  1085. resolveIdentifier (b->additionalInfo, ability, "addInfo");
  1086. b->turnsRemain = ability["turns"].Float();
  1087. b->sid = ability["sourceID"].Float();
  1088. b->description = ability["description"].String();
  1089. value = &ability["effectRange"];
  1090. if (!value->isNull())
  1091. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMap(bonusLimitEffect, value, "effect range "));
  1092. value = &ability["duration"];
  1093. if (!value->isNull())
  1094. {
  1095. switch (value->getType())
  1096. {
  1097. case JsonNode::DATA_STRING:
  1098. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  1099. break;
  1100. case JsonNode::DATA_VECTOR:
  1101. {
  1102. ui16 dur = 0;
  1103. for (const JsonNode & d : value->Vector())
  1104. {
  1105. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  1106. }
  1107. b->duration = dur;
  1108. }
  1109. break;
  1110. default:
  1111. logGlobal->errorStream() << "Error! Wrong bonus duration format.";
  1112. }
  1113. }
  1114. value = &ability["source"];
  1115. if (!value->isNull())
  1116. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  1117. value = &ability["limiters"];
  1118. if (!value->isNull())
  1119. {
  1120. for (const JsonNode & limiter : value->Vector())
  1121. {
  1122. switch (limiter.getType())
  1123. {
  1124. case JsonNode::DATA_STRING: //pre-defined limiters
  1125. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  1126. break;
  1127. case JsonNode::DATA_STRUCT: //customizable limiters
  1128. {
  1129. shared_ptr<ILimiter> l;
  1130. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  1131. {
  1132. shared_ptr<CCreatureTypeLimiter> l2 = make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  1133. const JsonVector vec = limiter["parameters"].Vector();
  1134. VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature)
  1135. {
  1136. l2->setCreature (CreatureID(creature));
  1137. });
  1138. if (vec.size() > 1)
  1139. {
  1140. l2->includeUpgrades = vec[1].Bool();
  1141. }
  1142. else
  1143. l2->includeUpgrades = false;
  1144. l = l2;
  1145. }
  1146. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  1147. {
  1148. shared_ptr<HasAnotherBonusLimiter> l2 = make_shared<HasAnotherBonusLimiter>();
  1149. const JsonVector vec = limiter["parameters"].Vector();
  1150. std::string anotherBonusType = vec[0].String();
  1151. auto it = bonusNameMap.find (anotherBonusType);
  1152. if (it == bonusNameMap.end())
  1153. {
  1154. logGlobal->errorStream() << "Error: invalid ability type " << anotherBonusType;
  1155. continue;
  1156. }
  1157. l2->type = it->second;
  1158. if (vec.size() > 1 )
  1159. {
  1160. resolveIdentifier (vec[1], l2->subtype);
  1161. l2->isSubtypeRelevant = true;
  1162. }
  1163. l = l2;
  1164. }
  1165. b->addLimiter(l);
  1166. }
  1167. break;
  1168. }
  1169. }
  1170. }
  1171. value = &ability["propagator"];
  1172. if (!value->isNull())
  1173. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  1174. return b;
  1175. }
  1176. //returns first Key with value equal to given one
  1177. template<class Key, class Val>
  1178. Key reverseMapFirst(const Val & val, const std::map<Key, Val> map)
  1179. {
  1180. for(auto it : map)
  1181. {
  1182. if(it.second == val)
  1183. {
  1184. return it.first;
  1185. }
  1186. }
  1187. assert(0);
  1188. return "";
  1189. }
  1190. void JsonUtils::unparseBonus( JsonNode &node, const Bonus * bonus )
  1191. {
  1192. node["type"].String() = reverseMapFirst<std::string, Bonus::BonusType>(bonus->type, bonusNameMap);
  1193. node["subtype"].Float() = bonus->subtype;
  1194. node["val"].Float() = bonus->val;
  1195. node["valueType"].String() = reverseMapFirst<std::string, Bonus::ValueType>(bonus->valType, bonusValueMap);
  1196. node["additionalInfo"].Float() = bonus->additionalInfo;
  1197. node["turns"].Float() = bonus->turnsRemain;
  1198. node["sourceID"].Float() = bonus->source;
  1199. node["description"].String() = bonus->description;
  1200. node["effectRange"].String() = reverseMapFirst<std::string, Bonus::LimitEffect>(bonus->effectRange, bonusLimitEffect);
  1201. node["duration"].String() = reverseMapFirst<std::string, ui16>(bonus->duration, bonusDurationMap);
  1202. node["source"].String() = reverseMapFirst<std::string, Bonus::BonusSource>(bonus->source, bonusSourceMap);
  1203. if(bonus->limiter)
  1204. {
  1205. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  1206. }
  1207. if(bonus->propagator)
  1208. {
  1209. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  1210. }
  1211. }
  1212. void minimizeNode(JsonNode & node, const JsonNode & schema)
  1213. {
  1214. if (schema["type"].String() == "object")
  1215. {
  1216. std::set<std::string> foundEntries;
  1217. for(auto & entry : schema["required"].Vector())
  1218. {
  1219. std::string name = entry.String();
  1220. foundEntries.insert(name);
  1221. minimizeNode(node[name], schema["properties"][name]);
  1222. if (vstd::contains(node.Struct(), name) &&
  1223. node[name] == schema["properties"][name]["default"])
  1224. {
  1225. node.Struct().erase(name);
  1226. }
  1227. }
  1228. // erase all unhandled entries
  1229. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  1230. {
  1231. if (!vstd::contains(foundEntries, it->first))
  1232. it = node.Struct().erase(it);
  1233. else
  1234. it++;
  1235. }
  1236. }
  1237. }
  1238. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  1239. {
  1240. minimizeNode(node, getSchema(schemaName));
  1241. }
  1242. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  1243. void maximizeNode(JsonNode & node, const JsonNode & schema)
  1244. {
  1245. // "required" entry can only be found in object/struct
  1246. if (schema["type"].String() == "object")
  1247. {
  1248. std::set<std::string> foundEntries;
  1249. // check all required entries that have default version
  1250. for(auto & entry : schema["required"].Vector())
  1251. {
  1252. std::string name = entry.String();
  1253. foundEntries.insert(name);
  1254. if (node[name].isNull() &&
  1255. !schema["properties"][name]["default"].isNull())
  1256. {
  1257. node[name] = schema["properties"][name]["default"];
  1258. }
  1259. maximizeNode(node[name], schema["properties"][name]);
  1260. }
  1261. // erase all unhandled entries
  1262. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  1263. {
  1264. if (!vstd::contains(foundEntries, it->first))
  1265. it = node.Struct().erase(it);
  1266. else
  1267. it++;
  1268. }
  1269. }
  1270. }
  1271. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  1272. {
  1273. maximizeNode(node, getSchema(schemaName));
  1274. }
  1275. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  1276. {
  1277. JsonValidator validator;
  1278. return validator.validate(node, schemaName, dataName);
  1279. }
  1280. const JsonNode & getSchemaByName(std::string name)
  1281. {
  1282. // cached schemas to avoid loading json data multiple times
  1283. static std::map<std::string, JsonNode> loadedSchemas;
  1284. if (vstd::contains(loadedSchemas, name))
  1285. return loadedSchemas[name];
  1286. std::string filename = "config/schemas/" + name + ".json";
  1287. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  1288. {
  1289. loadedSchemas[name] = JsonNode(ResourceID(filename));
  1290. return loadedSchemas[name];
  1291. }
  1292. logGlobal->errorStream() << "Error: missing schema with name " << name << "!";
  1293. assert(0);
  1294. return nullNode;
  1295. }
  1296. const JsonNode & JsonUtils::getSchema(std::string URI)
  1297. {
  1298. std::vector<std::string> segments;
  1299. size_t posColon = URI.find(':');
  1300. size_t posHash = URI.find('#');
  1301. assert(posColon != std::string::npos);
  1302. std::string protocolName = URI.substr(0, posColon);
  1303. std::string filename = URI.substr(posColon + 1, posHash - posColon - 1);
  1304. if (protocolName != "vcmi")
  1305. {
  1306. logGlobal->errorStream() << "Error: unsupported URI protocol for schema: " << segments[0];
  1307. return nullNode;
  1308. }
  1309. // check if json pointer if present (section after hash in string)
  1310. if (posHash == std::string::npos || posHash == URI.size() - 1)
  1311. return getSchemaByName(filename);
  1312. else
  1313. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  1314. }
  1315. void JsonUtils::merge(JsonNode & dest, JsonNode & source)
  1316. {
  1317. if (dest.getType() == JsonNode::DATA_NULL)
  1318. {
  1319. std::swap(dest, source);
  1320. return;
  1321. }
  1322. switch (source.getType())
  1323. {
  1324. case JsonNode::DATA_NULL:
  1325. {
  1326. dest.clear();
  1327. break;
  1328. }
  1329. case JsonNode::DATA_BOOL:
  1330. case JsonNode::DATA_FLOAT:
  1331. case JsonNode::DATA_STRING:
  1332. {
  1333. std::swap(dest, source);
  1334. break;
  1335. }
  1336. case JsonNode::DATA_VECTOR:
  1337. {
  1338. size_t total = std::min(source.Vector().size(), dest.Vector().size());
  1339. for (size_t i=0; i< total; i++)
  1340. merge(dest.Vector()[i], source.Vector()[i]);
  1341. if (dest.Vector().size() < source.Vector().size())
  1342. {
  1343. //reserve place and *move* remaining data from source to dest
  1344. source.Vector().reserve(source.Vector().size() + dest.Vector().size());
  1345. std::move(source.Vector().begin() + total, source.Vector().end(),
  1346. std::back_inserter(dest.Vector()));
  1347. }
  1348. break;
  1349. }
  1350. case JsonNode::DATA_STRUCT:
  1351. {
  1352. //recursively merge all entries from struct
  1353. for(auto & node : source.Struct())
  1354. merge(dest[node.first], node.second);
  1355. }
  1356. }
  1357. }
  1358. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source)
  1359. {
  1360. // uses copy created in stack to safely merge two nodes
  1361. merge(dest, source);
  1362. }
  1363. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  1364. {
  1365. JsonNode result;
  1366. for(std::string file : files)
  1367. {
  1368. JsonNode section(ResourceID(file, EResType::TEXT));
  1369. merge(result, section);
  1370. }
  1371. return result;
  1372. }
  1373. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  1374. {
  1375. JsonNode result;
  1376. ResourceID resID(filename, EResType::TEXT);
  1377. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  1378. {
  1379. // FIXME: some way to make this code more readable
  1380. auto stream = loader->load(resID);
  1381. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1382. stream->read(textData.get(), stream->getSize());
  1383. JsonNode section((char*)textData.get(), stream->getSize());
  1384. merge(result, section);
  1385. }
  1386. return result;
  1387. }