JsonNode.cpp 37 KB

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