JsonNode.cpp 39 KB

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