JsonNode.cpp 39 KB

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