JsonNode.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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. return true;
  592. if (!comma)
  593. error("Comma expected!", true);
  594. return true;
  595. }
  596. bool JsonParser::extractFloat(JsonNode &node)
  597. {
  598. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  599. bool negative=false;
  600. double result=0;
  601. if (input[pos] == '-')
  602. {
  603. pos++;
  604. negative = true;
  605. }
  606. if (input[pos] < '0' || input[pos] > '9')
  607. return error("Number expected!");
  608. //Extract integer part
  609. while (input[pos] >= '0' && input[pos] <= '9')
  610. {
  611. result = result*10+(input[pos]-'0');
  612. pos++;
  613. }
  614. if (input[pos] == '.')
  615. {
  616. //extract fractional part
  617. pos++;
  618. double fractMult = 0.1;
  619. if (input[pos] < '0' || input[pos] > '9')
  620. return error("Decimal part expected!");
  621. while (input[pos] >= '0' && input[pos] <= '9')
  622. {
  623. result = result + fractMult*(input[pos]-'0');
  624. fractMult /= 10;
  625. pos++;
  626. }
  627. }
  628. //TODO: exponential part
  629. if (negative)
  630. result = -result;
  631. node.setType(JsonNode::DATA_FLOAT);
  632. node.Float() = result;
  633. return true;
  634. }
  635. bool JsonParser::error(const std::string &message, bool warning)
  636. {
  637. std::ostringstream stream;
  638. std::string type(warning?" warning: ":" error: ");
  639. stream << "At line " << lineCount << ", position "<<pos-lineStart
  640. << type << message <<"\n";
  641. errors += stream.str();
  642. return warning;
  643. }
  644. static const std::map<std::string, JsonNode::JsonType> stringToType =
  645. boost::assign::map_list_of
  646. ("null", JsonNode::DATA_NULL) ("boolean", JsonNode::DATA_BOOL)
  647. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  648. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  649. std::string JsonValidator::validateEnum(const JsonNode &node, const JsonVector &enumeration)
  650. {
  651. for(auto & enumEntry : enumeration)
  652. {
  653. if (node == enumEntry)
  654. return "";
  655. }
  656. return fail("Key must have one of predefined values");
  657. }
  658. std::string JsonValidator::validatesSchemaList(const JsonNode &node, const JsonNode &schemas, std::string errorMsg, std::function<bool(size_t)> isValid)
  659. {
  660. if (!schemas.isNull())
  661. {
  662. std::string errors = "<tested schemas>\n";
  663. size_t result = 0;
  664. for(auto & schema : schemas.Vector())
  665. {
  666. std::string error = validateNode(node, schema);
  667. if (error.empty())
  668. {
  669. result++;
  670. }
  671. else
  672. {
  673. errors += error;
  674. errors += "<end of schema>\n";
  675. }
  676. }
  677. if (isValid(result))
  678. {
  679. return "";
  680. }
  681. return fail(errorMsg) + errors;
  682. }
  683. return "";
  684. }
  685. std::string JsonValidator::validateNodeType(const JsonNode &node, const JsonNode &schema)
  686. {
  687. std::string errors;
  688. // data must be valid against all schemas in the list
  689. errors += validatesSchemaList(node, schema["allOf"], "Failed to pass all schemas", [&](size_t count)
  690. {
  691. return count == schema["allOf"].Vector().size();
  692. });
  693. // data must be valid against any non-zero number of schemas in the list
  694. errors += validatesSchemaList(node, schema["anyOf"], "Failed to pass any schema", [&](size_t count)
  695. {
  696. return count > 0;
  697. });
  698. // data must be valid against one and only one schema
  699. errors += validatesSchemaList(node, schema["oneOf"], "Failed to pass one and only one schema", [&](size_t count)
  700. {
  701. return count == 1;
  702. });
  703. // data must NOT be valid against schema
  704. if (!schema["not"].isNull())
  705. {
  706. if (validateNode(node, schema["not"]).empty())
  707. errors += fail("Successful validation against negative check");
  708. }
  709. return errors;
  710. }
  711. // Basic checks common for any nodes
  712. std::string JsonValidator::validateNode(const JsonNode &node, const JsonNode &schema)
  713. {
  714. std::string errors;
  715. assert(!schema.isNull()); // can this error be triggered?
  716. if (node.isNull())
  717. return ""; // node not present. consider to be "valid"
  718. if (!schema["$ref"].isNull())
  719. {
  720. std::string URI = schema["$ref"].String();
  721. //node must be validated using schema pointed by this reference and not by data here
  722. //Local reference. Turn it into more easy to handle remote ref
  723. if (boost::algorithm::starts_with(URI, "#"))
  724. URI = usedSchemas.back() + URI;
  725. return validateRoot(node, URI);
  726. }
  727. // basic schema check
  728. auto & typeNode = schema["type"];
  729. if ( !typeNode.isNull())
  730. {
  731. JsonNode::JsonType type = stringToType.find(typeNode.String())->second;
  732. if(type != node.getType())
  733. return errors + fail("Type mismatch!"); // different type. Any other checks are useless
  734. }
  735. errors += validateNodeType(node, schema);
  736. // enumeration - data must be equeal to one of items in list
  737. if (!schema["enum"].isNull())
  738. errors += validateEnum(node, schema["enum"].Vector());
  739. // try to run any type-specific checks
  740. if (node.getType() == JsonNode::DATA_VECTOR) errors += validateVector(node, schema);
  741. if (node.getType() == JsonNode::DATA_STRUCT) errors += validateStruct(node, schema);
  742. if (node.getType() == JsonNode::DATA_STRING) errors += validateString(node, schema);
  743. if (node.getType() == JsonNode::DATA_FLOAT) errors += validateNumber(node, schema);
  744. return errors;
  745. }
  746. std::string JsonValidator::validateVectorItem(const JsonVector items, const JsonNode & schema, const JsonNode & additional, size_t index)
  747. {
  748. currentPath.push_back(JsonNode());
  749. currentPath.back().Float() = index;
  750. auto onExit = vstd::makeScopeGuard([&]
  751. {
  752. currentPath.pop_back();
  753. });
  754. if (!schema.isNull())
  755. {
  756. // case 1: schema is vector. Validate items agaist corresponding items in vector
  757. if (schema.getType() == JsonNode::DATA_VECTOR)
  758. {
  759. if (schema.Vector().size() > index)
  760. return validateNode(items[index], schema.Vector()[index]);
  761. }
  762. else // case 2: schema has to be struct. Apply it to all items, completely ignore additionalItems
  763. {
  764. return validateNode(items[index], schema);
  765. }
  766. }
  767. // othervice check against schema in additional items field
  768. if (additional.getType() == JsonNode::DATA_STRUCT)
  769. return validateNode(items[index], additional);
  770. // or, additionalItems field can be bool which indicates if such items are allowed
  771. if (!additional.isNull() && additional.Bool() == false) // present and set to false - error
  772. return fail("Unknown entry found");
  773. // by default - additional items are allowed
  774. return "";
  775. }
  776. //Checks "items" entry from schema (type-specific check for Vector)
  777. std::string JsonValidator::validateVector(const JsonNode &node, const JsonNode &schema)
  778. {
  779. std::string errors;
  780. auto & vector = node.Vector();
  781. {
  782. auto & items = schema["items"];
  783. auto & additional = schema["additionalItems"];
  784. for (size_t i=0; i<vector.size(); i++)
  785. errors += validateVectorItem(vector, items, additional, i);
  786. }
  787. if (vstd::contains(schema.Struct(), "maxItems") && vector.size() > schema["maxItems"].Float())
  788. errors += fail("Too many items in the list!");
  789. if (vstd::contains(schema.Struct(), "minItems") && vector.size() < schema["minItems"].Float())
  790. errors += fail("Too few items in the list");
  791. if (schema["uniqueItems"].Bool())
  792. {
  793. for (auto itA = vector.begin(); itA != vector.end(); itA++)
  794. {
  795. auto itB = itA;
  796. while (++itB != vector.end())
  797. {
  798. if (*itA == *itB)
  799. errors += fail("List must consist from unique items");
  800. }
  801. }
  802. }
  803. return errors;
  804. }
  805. std::string JsonValidator::validateStructItem(const JsonNode &node, const JsonNode & schema, const JsonNode & additional, std::string nodeName)
  806. {
  807. currentPath.push_back(JsonNode());
  808. currentPath.back().String() = nodeName;
  809. auto onExit = vstd::makeScopeGuard([&]
  810. {
  811. currentPath.pop_back();
  812. });
  813. // there is schema specifically for this item
  814. if (!schema[nodeName].isNull())
  815. return validateNode(node, schema[nodeName]);
  816. // try generic additionalItems schema
  817. if (additional.getType() == JsonNode::DATA_STRUCT)
  818. return validateNode(node, additional);
  819. // or, additionalItems field can be bool which indicates if such items are allowed
  820. if (!additional.isNull() && additional.Bool() == false) // present and set to false - error
  821. return fail("Unknown entry found: " + nodeName);
  822. // by default - additional items are allowed
  823. return "";
  824. }
  825. //Checks "properties" entry from schema (type-specific check for Struct)
  826. std::string JsonValidator::validateStruct(const JsonNode &node, const JsonNode &schema)
  827. {
  828. std::string errors;
  829. auto & map = node.Struct();
  830. {
  831. auto & properties = schema["properties"];
  832. auto & additional = schema["additionalProperties"];
  833. for(auto & entry : map)
  834. errors += validateStructItem(entry.second, properties, additional, entry.first);
  835. }
  836. for(auto & required : schema["required"].Vector())
  837. {
  838. if (node[required.String()].isNull())
  839. errors += fail("Required entry " + required.String() + " is missing");
  840. }
  841. //Copy-paste from vector code. yay!
  842. if (vstd::contains(schema.Struct(), "maxProperties") && map.size() > schema["maxProperties"].Float())
  843. errors += fail("Too many items in the list!");
  844. if (vstd::contains(schema.Struct(), "minItems") && map.size() < schema["minItems"].Float())
  845. errors += fail("Too few items in the list");
  846. if (schema["uniqueItems"].Bool())
  847. {
  848. for (auto itA = map.begin(); itA != map.end(); itA++)
  849. {
  850. auto itB = itA;
  851. while (++itB != map.end())
  852. {
  853. if (itA->second == itB->second)
  854. errors += fail("List must consist from unique items");
  855. }
  856. }
  857. }
  858. // dependencies. Format is object/struct where key is the name of key in data
  859. // and value is either:
  860. // a) array of fields that must be present
  861. // b) struct with schema against which data should be valid
  862. // These checks are triggered only if key is present
  863. for(auto & deps : schema["dependencies"].Struct())
  864. {
  865. if (vstd::contains(map, deps.first))
  866. {
  867. if (deps.second.getType() == JsonNode::DATA_VECTOR)
  868. {
  869. JsonVector depList = deps.second.Vector();
  870. for(auto & depEntry : depList)
  871. {
  872. if (!vstd::contains(map, depEntry.String()))
  873. errors += fail("Property " + depEntry.String() + " required for " + deps.first + " is missing");
  874. }
  875. }
  876. else
  877. {
  878. if (!validateNode(node, deps.second).empty())
  879. errors += fail("Requirements for " + deps.first + " are not fulfilled");
  880. }
  881. }
  882. }
  883. // TODO: missing fields from draft v4
  884. // patternProperties
  885. return errors;
  886. }
  887. std::string JsonValidator::validateString(const JsonNode &node, const JsonNode &schema)
  888. {
  889. std::string errors;
  890. auto & string = node.String();
  891. if (vstd::contains(schema.Struct(), "maxLength") && string.size() > schema["maxLength"].Float())
  892. errors += fail("String too long");
  893. if (vstd::contains(schema.Struct(), "minLength") && string.size() < schema["minLength"].Float())
  894. errors += fail("String too short");
  895. // TODO: missing fields from draft v4
  896. // pattern
  897. return errors;
  898. }
  899. std::string JsonValidator::validateNumber(const JsonNode &node, const JsonNode &schema)
  900. {
  901. std::string errors;
  902. auto & value = node.Float();
  903. if (vstd::contains(schema.Struct(), "maximum"))
  904. {
  905. if (schema["exclusiveMaximum"].Bool())
  906. {
  907. if (value >= schema["maximum"].Float())
  908. errors += fail("Value is too large");
  909. }
  910. else
  911. {
  912. if (value > schema["maximum"].Float())
  913. errors += fail("Value is too large");
  914. }
  915. }
  916. if (vstd::contains(schema.Struct(), "minimum"))
  917. {
  918. if (schema["exclusiveMinimum"].Bool())
  919. {
  920. if (value <= schema["minimum"].Float())
  921. errors += fail("Value is too small");
  922. }
  923. else
  924. {
  925. if (value < schema["minimum"].Float())
  926. errors += fail("Value is too small");
  927. }
  928. }
  929. if (vstd::contains(schema.Struct(), "multipleOf"))
  930. {
  931. double result = value / schema["multipleOf"].Float();
  932. if (floor(result) != result)
  933. errors += ("Value is not divisible");
  934. }
  935. return errors;
  936. }
  937. //basic schema validation (like checking $schema entry).
  938. std::string JsonValidator::validateRoot(const JsonNode &node, std::string schemaName)
  939. {
  940. const JsonNode & schema = JsonUtils::getSchema(schemaName);
  941. usedSchemas.push_back(schemaName.substr(0, schemaName.find('#')));
  942. auto onExit = vstd::makeScopeGuard([&]
  943. {
  944. usedSchemas.pop_back();
  945. });
  946. if (!schema.isNull())
  947. return validateNode(node, schema);
  948. else
  949. return fail("Schema not found!");
  950. }
  951. std::string JsonValidator::fail(const std::string &message)
  952. {
  953. std::string errors;
  954. errors += "At ";
  955. if (!currentPath.empty())
  956. {
  957. for(const JsonNode &path : currentPath)
  958. {
  959. errors += "/";
  960. if (path.getType() == JsonNode::DATA_STRING)
  961. errors += path.String();
  962. else
  963. errors += boost::lexical_cast<std::string>(static_cast<unsigned>(path.Float()));
  964. }
  965. }
  966. else
  967. errors += "<root>";
  968. errors += "\n\t Error: " + message + "\n";
  969. return errors;
  970. }
  971. bool JsonValidator::validate(const JsonNode &root, std::string schemaName, std::string name)
  972. {
  973. std::string errors = validateRoot(root, schemaName);
  974. if (!errors.empty())
  975. {
  976. logGlobal->warnStream() << "Data in " << name << " is invalid!";
  977. logGlobal->warnStream() << errors;
  978. }
  979. return errors.empty();
  980. }
  981. ///JsonUtils
  982. void JsonUtils::parseTypedBonusShort(const JsonVector& source, Bonus *dest)
  983. {
  984. dest->val = source[1].Float();
  985. resolveIdentifier(source[2],dest->subtype);
  986. dest->additionalInfo = source[3].Float();
  987. dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  988. dest->turnsRemain = 0;
  989. }
  990. Bonus * JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  991. {
  992. auto b = new Bonus();
  993. std::string type = ability_vec[0].String();
  994. auto it = bonusNameMap.find(type);
  995. if (it == bonusNameMap.end())
  996. {
  997. logGlobal->errorStream() << "Error: invalid ability type " << type;
  998. return b;
  999. }
  1000. b->type = it->second;
  1001. parseTypedBonusShort(ability_vec, b);
  1002. return b;
  1003. }
  1004. template <typename T>
  1005. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  1006. {
  1007. static T defaultValue = T();
  1008. if (!val->isNull())
  1009. {
  1010. std::string type = val->String();
  1011. auto it = map.find(type);
  1012. if (it == map.end())
  1013. {
  1014. logGlobal->errorStream() << "Error: invalid " << err << type;
  1015. return defaultValue;
  1016. }
  1017. else
  1018. {
  1019. return it->second;
  1020. }
  1021. }
  1022. else
  1023. return defaultValue;
  1024. }
  1025. void JsonUtils::resolveIdentifier (si32 &var, const JsonNode &node, std::string name)
  1026. {
  1027. const JsonNode &value = node[name];
  1028. if (!value.isNull())
  1029. {
  1030. switch (value.getType())
  1031. {
  1032. case JsonNode::DATA_FLOAT:
  1033. var = value.Float();
  1034. break;
  1035. case JsonNode::DATA_STRING:
  1036. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  1037. {
  1038. var = identifier;
  1039. });
  1040. break;
  1041. default:
  1042. logGlobal->errorStream() << "Error! Wrong indentifier used for value of " << name;
  1043. }
  1044. }
  1045. }
  1046. void JsonUtils::resolveIdentifier (const JsonNode &node, si32 &var)
  1047. {
  1048. switch (node.getType())
  1049. {
  1050. case JsonNode::DATA_FLOAT:
  1051. var = node.Float();
  1052. break;
  1053. case JsonNode::DATA_STRING:
  1054. VLC->modh->identifiers.requestIdentifier (node, [&](si32 identifier)
  1055. {
  1056. var = identifier;
  1057. });
  1058. break;
  1059. default:
  1060. logGlobal->errorStream() << "Error! Wrong indentifier used for identifier!";
  1061. }
  1062. }
  1063. Bonus * JsonUtils::parseBonus (const JsonNode &ability)
  1064. {
  1065. auto b = new Bonus();
  1066. const JsonNode *value;
  1067. std::string type = ability["type"].String();
  1068. auto it = bonusNameMap.find(type);
  1069. if (it == bonusNameMap.end())
  1070. {
  1071. logGlobal->errorStream() << "Error: invalid ability type " << type;
  1072. return b;
  1073. }
  1074. b->type = it->second;
  1075. resolveIdentifier (b->subtype, ability, "subtype");
  1076. b->val = ability["val"].Float();
  1077. value = &ability["valueType"];
  1078. if (!value->isNull())
  1079. b->valType = static_cast<Bonus::ValueType>(parseByMap(bonusValueMap, value, "value type "));
  1080. resolveIdentifier (b->additionalInfo, ability, "addInfo");
  1081. b->turnsRemain = ability["turns"].Float();
  1082. b->sid = ability["sourceID"].Float();
  1083. b->description = ability["description"].String();
  1084. value = &ability["effectRange"];
  1085. if (!value->isNull())
  1086. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMap(bonusLimitEffect, value, "effect range "));
  1087. value = &ability["duration"];
  1088. if (!value->isNull())
  1089. {
  1090. switch (value->getType())
  1091. {
  1092. case JsonNode::DATA_STRING:
  1093. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  1094. break;
  1095. case JsonNode::DATA_VECTOR:
  1096. {
  1097. ui16 dur = 0;
  1098. for (const JsonNode & d : value->Vector())
  1099. {
  1100. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  1101. }
  1102. b->duration = dur;
  1103. }
  1104. break;
  1105. default:
  1106. logGlobal->errorStream() << "Error! Wrong bonus duration format.";
  1107. }
  1108. }
  1109. value = &ability["source"];
  1110. if (!value->isNull())
  1111. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  1112. value = &ability["limiters"];
  1113. if (!value->isNull())
  1114. {
  1115. for (const JsonNode & limiter : value->Vector())
  1116. {
  1117. switch (limiter.getType())
  1118. {
  1119. case JsonNode::DATA_STRING: //pre-defined limiters
  1120. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  1121. break;
  1122. case JsonNode::DATA_STRUCT: //customizable limiters
  1123. {
  1124. shared_ptr<ILimiter> l;
  1125. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  1126. {
  1127. shared_ptr<CCreatureTypeLimiter> l2 = make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  1128. const JsonVector vec = limiter["parameters"].Vector();
  1129. VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature)
  1130. {
  1131. l2->setCreature (CreatureID(creature));
  1132. });
  1133. if (vec.size() > 1)
  1134. {
  1135. l2->includeUpgrades = vec[1].Bool();
  1136. }
  1137. else
  1138. l2->includeUpgrades = false;
  1139. l = l2;
  1140. }
  1141. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  1142. {
  1143. shared_ptr<HasAnotherBonusLimiter> l2 = make_shared<HasAnotherBonusLimiter>();
  1144. const JsonVector vec = limiter["parameters"].Vector();
  1145. std::string anotherBonusType = vec[0].String();
  1146. auto it = bonusNameMap.find (anotherBonusType);
  1147. if (it == bonusNameMap.end())
  1148. {
  1149. logGlobal->errorStream() << "Error: invalid ability type " << anotherBonusType;
  1150. continue;
  1151. }
  1152. l2->type = it->second;
  1153. if (vec.size() > 1 )
  1154. {
  1155. resolveIdentifier (vec[1], l2->subtype);
  1156. l2->isSubtypeRelevant = true;
  1157. }
  1158. l = l2;
  1159. }
  1160. b->addLimiter(l);
  1161. }
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. value = &ability["propagator"];
  1167. if (!value->isNull())
  1168. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  1169. return b;
  1170. }
  1171. //returns first Key with value equal to given one
  1172. template<class Key, class Val>
  1173. Key reverseMapFirst(const Val & val, const std::map<Key, Val> map)
  1174. {
  1175. for(auto it : map)
  1176. {
  1177. if(it.second == val)
  1178. {
  1179. return it.first;
  1180. }
  1181. }
  1182. assert(0);
  1183. return "";
  1184. }
  1185. void JsonUtils::unparseBonus( JsonNode &node, const Bonus * bonus )
  1186. {
  1187. node["type"].String() = reverseMapFirst<std::string, Bonus::BonusType>(bonus->type, bonusNameMap);
  1188. node["subtype"].Float() = bonus->subtype;
  1189. node["val"].Float() = bonus->val;
  1190. node["valueType"].String() = reverseMapFirst<std::string, Bonus::ValueType>(bonus->valType, bonusValueMap);
  1191. node["additionalInfo"].Float() = bonus->additionalInfo;
  1192. node["turns"].Float() = bonus->turnsRemain;
  1193. node["sourceID"].Float() = bonus->source;
  1194. node["description"].String() = bonus->description;
  1195. node["effectRange"].String() = reverseMapFirst<std::string, Bonus::LimitEffect>(bonus->effectRange, bonusLimitEffect);
  1196. node["duration"].String() = reverseMapFirst<std::string, ui16>(bonus->duration, bonusDurationMap);
  1197. node["source"].String() = reverseMapFirst<std::string, Bonus::BonusSource>(bonus->source, bonusSourceMap);
  1198. if(bonus->limiter)
  1199. {
  1200. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  1201. }
  1202. if(bonus->propagator)
  1203. {
  1204. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  1205. }
  1206. }
  1207. void minimizeNode(JsonNode & node, const JsonNode & schema)
  1208. {
  1209. if (schema["type"].String() == "object")
  1210. {
  1211. std::set<std::string> foundEntries;
  1212. for(auto & entry : schema["required"].Vector())
  1213. {
  1214. std::string name = entry.String();
  1215. foundEntries.insert(name);
  1216. minimizeNode(node[name], schema["properties"][name]);
  1217. if (vstd::contains(node.Struct(), name) &&
  1218. node[name] == schema["properties"][name]["default"])
  1219. {
  1220. node.Struct().erase(name);
  1221. }
  1222. }
  1223. // erase all unhandled entries
  1224. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  1225. {
  1226. if (!vstd::contains(foundEntries, it->first))
  1227. it = node.Struct().erase(it);
  1228. else
  1229. it++;
  1230. }
  1231. }
  1232. }
  1233. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  1234. {
  1235. minimizeNode(node, getSchema(schemaName));
  1236. }
  1237. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  1238. void maximizeNode(JsonNode & node, const JsonNode & schema)
  1239. {
  1240. // "required" entry can only be found in object/struct
  1241. if (schema["type"].String() == "object")
  1242. {
  1243. std::set<std::string> foundEntries;
  1244. // check all required entries that have default version
  1245. for(auto & entry : schema["required"].Vector())
  1246. {
  1247. std::string name = entry.String();
  1248. foundEntries.insert(name);
  1249. if (node[name].isNull() &&
  1250. !schema["properties"][name]["default"].isNull())
  1251. {
  1252. node[name] = schema["properties"][name]["default"];
  1253. }
  1254. maximizeNode(node[name], schema["properties"][name]);
  1255. }
  1256. // erase all unhandled entries
  1257. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  1258. {
  1259. if (!vstd::contains(foundEntries, it->first))
  1260. it = node.Struct().erase(it);
  1261. else
  1262. it++;
  1263. }
  1264. }
  1265. }
  1266. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  1267. {
  1268. maximizeNode(node, getSchema(schemaName));
  1269. }
  1270. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  1271. {
  1272. JsonValidator validator;
  1273. return validator.validate(node, schemaName, dataName);
  1274. }
  1275. const JsonNode & getSchemaByName(std::string name)
  1276. {
  1277. // cached schemas to avoid loading json data multiple times
  1278. static std::map<std::string, JsonNode> loadedSchemas;
  1279. if (vstd::contains(loadedSchemas, name))
  1280. return loadedSchemas[name];
  1281. std::string filename = "config/schemas/" + name + ".json";
  1282. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  1283. {
  1284. loadedSchemas[name] = JsonNode(ResourceID(filename));
  1285. return loadedSchemas[name];
  1286. }
  1287. logGlobal->errorStream() << "Error: missing schema with name " << name << "!";
  1288. assert(0);
  1289. return nullNode;
  1290. }
  1291. const JsonNode & JsonUtils::getSchema(std::string URI)
  1292. {
  1293. std::vector<std::string> segments;
  1294. size_t posColon = URI.find(':');
  1295. size_t posHash = URI.find('#');
  1296. assert(posColon != std::string::npos);
  1297. std::string protocolName = URI.substr(0, posColon);
  1298. std::string filename = URI.substr(posColon + 1, posHash - posColon - 1);
  1299. if (protocolName != "vcmi")
  1300. {
  1301. logGlobal->errorStream() << "Error: unsupported URI protocol for schema: " << segments[0];
  1302. return nullNode;
  1303. }
  1304. // check if json pointer if present (section after hash in string)
  1305. if (posHash == std::string::npos || posHash == URI.size() - 1)
  1306. return getSchemaByName(filename);
  1307. else
  1308. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  1309. }
  1310. void JsonUtils::merge(JsonNode & dest, JsonNode & source)
  1311. {
  1312. if (dest.getType() == JsonNode::DATA_NULL)
  1313. {
  1314. std::swap(dest, source);
  1315. return;
  1316. }
  1317. switch (source.getType())
  1318. {
  1319. case JsonNode::DATA_NULL:
  1320. {
  1321. dest.clear();
  1322. break;
  1323. }
  1324. case JsonNode::DATA_BOOL:
  1325. case JsonNode::DATA_FLOAT:
  1326. case JsonNode::DATA_STRING:
  1327. {
  1328. std::swap(dest, source);
  1329. break;
  1330. }
  1331. case JsonNode::DATA_VECTOR:
  1332. {
  1333. size_t total = std::min(source.Vector().size(), dest.Vector().size());
  1334. for (size_t i=0; i< total; i++)
  1335. merge(dest.Vector()[i], source.Vector()[i]);
  1336. if (dest.Vector().size() < source.Vector().size())
  1337. {
  1338. //reserve place and *move* remaining data from source to dest
  1339. source.Vector().reserve(source.Vector().size() + dest.Vector().size());
  1340. std::move(source.Vector().begin() + total, source.Vector().end(),
  1341. std::back_inserter(dest.Vector()));
  1342. }
  1343. break;
  1344. }
  1345. case JsonNode::DATA_STRUCT:
  1346. {
  1347. //recursively merge all entries from struct
  1348. for(auto & node : source.Struct())
  1349. merge(dest[node.first], node.second);
  1350. }
  1351. }
  1352. }
  1353. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source)
  1354. {
  1355. // uses copy created in stack to safely merge two nodes
  1356. merge(dest, source);
  1357. }
  1358. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  1359. {
  1360. JsonNode result;
  1361. for(std::string file : files)
  1362. {
  1363. JsonNode section(ResourceID(file, EResType::TEXT));
  1364. merge(result, section);
  1365. }
  1366. return result;
  1367. }
  1368. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  1369. {
  1370. JsonNode result;
  1371. ResourceID resID(filename, EResType::TEXT);
  1372. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  1373. {
  1374. // FIXME: some way to make this code more readable
  1375. auto stream = loader->load(resID);
  1376. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1377. stream->read(textData.get(), stream->getSize());
  1378. JsonNode section((char*)textData.get(), stream->getSize());
  1379. merge(result, section);
  1380. }
  1381. return result;
  1382. }