JsonNode.cpp 38 KB

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