2
0

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