JsonNode.cpp 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. #include "StdInc.h"
  2. #include "JsonNode.h"
  3. #include "HeroBonus.h"
  4. #include "Filesystem/CResourceLoader.h"
  5. const JsonNode JsonNode::nullNode;
  6. JsonNode::JsonNode(JsonType Type):
  7. type(DATA_NULL)
  8. {
  9. setType(Type);
  10. }
  11. JsonNode::JsonNode(const char *data, size_t datasize):
  12. type(DATA_NULL)
  13. {
  14. JsonParser parser(data, datasize, *this);
  15. JsonValidator validator(*this);
  16. }
  17. JsonNode::JsonNode(ResourceID && fileURI):
  18. type(DATA_NULL)
  19. {
  20. std::string filename = CResourceHandler::get()->getResourceName(fileURI);
  21. FILE * file = fopen(filename.c_str(), "rb");
  22. if (!file)
  23. {
  24. tlog1 << "Failed to open file " << filename << "\n";
  25. perror("Last system error was ");
  26. return;
  27. }
  28. fseek(file, 0, SEEK_END);
  29. size_t datasize = ftell(file);
  30. fseek(file, 0, SEEK_SET);
  31. char *input = new char[datasize];
  32. datasize = fread((void*)input, 1, datasize, file);
  33. fclose(file);
  34. JsonParser parser(input, datasize, *this);
  35. JsonValidator validator(*this);
  36. delete [] input;
  37. }
  38. JsonNode::JsonNode(const JsonNode &copy):
  39. type(DATA_NULL)
  40. {
  41. setType(copy.getType());
  42. switch(type)
  43. {
  44. break; case DATA_NULL:
  45. break; case DATA_BOOL: Bool() = copy.Bool();
  46. break; case DATA_FLOAT: Float() = copy.Float();
  47. break; case DATA_STRING: String() = copy.String();
  48. break; case DATA_VECTOR: Vector() = copy.Vector();
  49. break; case DATA_STRUCT: Struct() = copy.Struct();
  50. }
  51. }
  52. JsonNode::~JsonNode()
  53. {
  54. setType(DATA_NULL);
  55. }
  56. void JsonNode::swap(JsonNode &b)
  57. {
  58. using std::swap;
  59. swap(data, b.data);
  60. swap(type, b.type);
  61. }
  62. JsonNode & JsonNode::operator =(JsonNode node)
  63. {
  64. swap(node);
  65. return *this;
  66. }
  67. bool JsonNode::operator == (const JsonNode &other) const
  68. {
  69. if (getType() == other.getType())
  70. {
  71. switch(type)
  72. {
  73. break; case DATA_NULL: return true;
  74. break; case DATA_BOOL: return Bool() == other.Bool();
  75. break; case DATA_FLOAT: return Float() == other.Float();
  76. break; case DATA_STRING: return String() == other.String();
  77. break; case DATA_VECTOR: return Vector() == other.Vector();
  78. break; case DATA_STRUCT: return Struct() == other.Struct();
  79. }
  80. }
  81. return false;
  82. }
  83. bool JsonNode::operator != (const JsonNode &other) const
  84. {
  85. return !(*this == other);
  86. }
  87. void JsonNode::minimize(const JsonNode& schema)
  88. {
  89. JsonValidator validator(*this, schema, true);
  90. }
  91. void JsonNode::validate(const JsonNode& schema)
  92. {
  93. JsonValidator validator(*this, schema, false);
  94. }
  95. JsonNode::JsonType JsonNode::getType() const
  96. {
  97. return type;
  98. }
  99. void JsonNode::setType(JsonType Type)
  100. {
  101. if (type == Type)
  102. return;
  103. //Reset node to NULL
  104. if (Type != DATA_NULL)
  105. setType(DATA_NULL);
  106. switch (type)
  107. {
  108. break; case DATA_STRING: delete data.String;
  109. break; case DATA_VECTOR: delete data.Vector;
  110. break; case DATA_STRUCT: delete data.Struct;
  111. break; default:
  112. break;
  113. }
  114. //Set new node type
  115. type = Type;
  116. switch(type)
  117. {
  118. break; case DATA_NULL:
  119. break; case DATA_BOOL: data.Bool = false;
  120. break; case DATA_FLOAT: data.Float = 0;
  121. break; case DATA_STRING: data.String = new std::string;
  122. break; case DATA_VECTOR: data.Vector = new JsonVector;
  123. break; case DATA_STRUCT: data.Struct = new JsonMap;
  124. }
  125. }
  126. bool JsonNode::isNull() const
  127. {
  128. return type == DATA_NULL;
  129. }
  130. bool & JsonNode::Bool()
  131. {
  132. setType(DATA_BOOL);
  133. return data.Bool;
  134. }
  135. double & JsonNode::Float()
  136. {
  137. setType(DATA_FLOAT);
  138. return data.Float;
  139. }
  140. std::string & JsonNode::String()
  141. {
  142. setType(DATA_STRING);
  143. return *data.String;
  144. }
  145. JsonVector & JsonNode::Vector()
  146. {
  147. setType(DATA_VECTOR);
  148. return *data.Vector;
  149. }
  150. JsonMap & JsonNode::Struct()
  151. {
  152. setType(DATA_STRUCT);
  153. return *data.Struct;
  154. }
  155. const bool boolDefault = false;
  156. const bool & JsonNode::Bool() const
  157. {
  158. if (type == DATA_NULL)
  159. return boolDefault;
  160. assert(type == DATA_BOOL);
  161. return data.Bool;
  162. }
  163. const double floatDefault = 0;
  164. const double & JsonNode::Float() const
  165. {
  166. if (type == DATA_NULL)
  167. return floatDefault;
  168. assert(type == DATA_FLOAT);
  169. return data.Float;
  170. }
  171. const std::string stringDefault = std::string();
  172. const std::string & JsonNode::String() const
  173. {
  174. if (type == DATA_NULL)
  175. return stringDefault;
  176. assert(type == DATA_STRING);
  177. return *data.String;
  178. }
  179. const JsonVector vectorDefault = JsonVector();
  180. const JsonVector & JsonNode::Vector() const
  181. {
  182. if (type == DATA_NULL)
  183. return vectorDefault;
  184. assert(type == DATA_VECTOR);
  185. return *data.Vector;
  186. }
  187. const JsonMap mapDefault = JsonMap();
  188. const JsonMap & JsonNode::Struct() const
  189. {
  190. if (type == DATA_NULL)
  191. return mapDefault;
  192. assert(type == DATA_STRUCT);
  193. return *data.Struct;
  194. }
  195. JsonNode & JsonNode::operator[](std::string child)
  196. {
  197. return Struct()[child];
  198. }
  199. const JsonNode & JsonNode::operator[](std::string child) const
  200. {
  201. JsonMap::const_iterator it = Struct().find(child);
  202. if (it != Struct().end())
  203. return it->second;
  204. return nullNode;
  205. }
  206. ////////////////////////////////////////////////////////////////////////////////
  207. void JsonNode::merge(JsonNode & dest, JsonNode & source)
  208. {
  209. switch (source.getType())
  210. {
  211. break; case DATA_NULL: dest.setType(DATA_NULL);
  212. break; case DATA_BOOL: std::swap(dest.Bool(), source.Bool());
  213. break; case DATA_FLOAT: std::swap(dest.Float(), source.Float());
  214. break; case DATA_STRING: std::swap(dest.String(), source.String());
  215. break; case DATA_VECTOR:
  216. {
  217. //reserve place and *move* data from source to dest
  218. source.Vector().reserve(source.Vector().size() + dest.Vector().size());
  219. std::move(source.Vector().begin(), source.Vector().end(),
  220. std::back_inserter(dest.Vector()));
  221. }
  222. break; case DATA_STRUCT:
  223. {
  224. //recursively merge all entries from struct
  225. BOOST_FOREACH(auto & node, source.Struct())
  226. merge(dest[node.first], node.second);
  227. }
  228. }
  229. }
  230. void JsonNode::mergeCopy(JsonNode & dest, JsonNode source)
  231. {
  232. // uses copy created in stack to safely merge two nodes
  233. merge(dest, source);
  234. }
  235. ////////////////////////////////////////////////////////////////////////////////
  236. template<typename Iterator>
  237. void JsonWriter::writeContainer(Iterator begin, Iterator end)
  238. {
  239. if (begin == end)
  240. return;
  241. prefix += '\t';
  242. end--;
  243. while (begin != end)
  244. {
  245. writeEntry(begin++);
  246. out<<",\n";
  247. }
  248. writeEntry(begin);
  249. out<<"\n";
  250. prefix.resize(prefix.size()-1);
  251. }
  252. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  253. {
  254. out << prefix;
  255. writeString(entry->first);
  256. out << " : ";
  257. writeNode(entry->second);
  258. }
  259. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  260. {
  261. out << prefix;
  262. writeNode(*entry);
  263. }
  264. void JsonWriter::writeString(const std::string &string)
  265. {
  266. static const std::string escaped = "\"\\/\b\f\n\r\t";
  267. out <<'\"';
  268. size_t pos=0, start=0;
  269. for (; pos<string.size(); pos++)
  270. {
  271. size_t escapedChar = escaped.find(string[pos]);
  272. if (escapedChar != std::string::npos)
  273. {
  274. out.write(string.data()+start, pos - start);
  275. out << '\\' << escaped[escapedChar];
  276. start = pos;
  277. }
  278. }
  279. out.write(string.data()+start, pos - start);
  280. out <<'\"';
  281. }
  282. void JsonWriter::writeNode(const JsonNode &node)
  283. {
  284. switch(node.getType())
  285. {
  286. break; case JsonNode::DATA_NULL:
  287. out << "null";
  288. break; case JsonNode::DATA_BOOL:
  289. if (node.Bool())
  290. out << "true";
  291. else
  292. out << "false";
  293. break; case JsonNode::DATA_FLOAT:
  294. out << node.Float();
  295. break; case JsonNode::DATA_STRING:
  296. writeString(node.String());
  297. break; case JsonNode::DATA_VECTOR:
  298. out << "[" << "\n";
  299. writeContainer(node.Vector().begin(), node.Vector().end());
  300. out << prefix << "]";
  301. break; case JsonNode::DATA_STRUCT:
  302. out << "{" << "\n";
  303. writeContainer(node.Struct().begin(), node.Struct().end());
  304. out << prefix << "}";
  305. }
  306. }
  307. JsonWriter::JsonWriter(std::ostream &output, const JsonNode &node):
  308. out(output)
  309. {
  310. writeNode(node);
  311. }
  312. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  313. {
  314. JsonWriter(out, node);
  315. return out << "\n";
  316. }
  317. ////////////////////////////////////////////////////////////////////////////////
  318. JsonParser::JsonParser(const char * inputString, size_t stringSize, JsonNode &root):
  319. input(inputString, stringSize),
  320. lineCount(1),
  321. lineStart(0),
  322. pos(0)
  323. {
  324. extractValue(root);
  325. extractWhitespace(false);
  326. //Warn if there are any non-whitespace symbols left
  327. if (pos < input.size())
  328. error("Not all file was parsed!", true);
  329. //TODO: better way to show errors (like printing file name as well)
  330. tlog3<<errors;
  331. }
  332. bool JsonParser::extractSeparator()
  333. {
  334. if (!extractWhitespace())
  335. return false;
  336. if ( input[pos] !=':')
  337. return error("Separator expected");
  338. pos++;
  339. return true;
  340. }
  341. bool JsonParser::extractValue(JsonNode &node)
  342. {
  343. if (!extractWhitespace())
  344. return false;
  345. switch (input[pos])
  346. {
  347. case '\"': return extractString(node);
  348. case 'n' : return extractNull(node);
  349. case 't' : return extractTrue(node);
  350. case 'f' : return extractFalse(node);
  351. case '{' : return extractStruct(node);
  352. case '[' : return extractArray(node);
  353. case '-' : return extractFloat(node);
  354. default:
  355. {
  356. if (input[pos] >= '0' && input[pos] <= '9')
  357. return extractFloat(node);
  358. return error("Value expected!");
  359. }
  360. }
  361. }
  362. bool JsonParser::extractWhitespace(bool verbose)
  363. {
  364. while (true)
  365. {
  366. while (pos < input.size() && (ui8)input[pos] <= ' ')
  367. {
  368. if (input[pos] == '\n')
  369. {
  370. lineCount++;
  371. lineStart = pos+1;
  372. }
  373. pos++;
  374. }
  375. if (pos >= input.size() || input[pos] != '/')
  376. break;
  377. pos++;
  378. if (pos == input.size())
  379. break;
  380. if (input[pos] == '/')
  381. pos++;
  382. else
  383. error("Comments must consist from two slashes!", true);
  384. while (pos < input.size() && input[pos] != '\n')
  385. pos++;
  386. }
  387. if (pos >= input.size() && verbose)
  388. return error("Unexpected end of file!");
  389. return true;
  390. }
  391. bool JsonParser::extractEscaping(std::string &str)
  392. {
  393. switch(input[pos++])
  394. {
  395. break; case '\"': str += '\"';
  396. break; case '\\': str += '\\';
  397. break; case '/': str += '/';
  398. break; case '\b': str += '\b';
  399. break; case '\f': str += '\f';
  400. break; case '\n': str += '\n';
  401. break; case '\r': str += '\r';
  402. break; case '\t': str += '\t';
  403. break; default: return error("Unknown escape sequence!", true);
  404. };
  405. return true;
  406. }
  407. bool JsonParser::extractString(std::string &str)
  408. {
  409. if (input[pos] != '\"')
  410. return error("String expected!");
  411. pos++;
  412. size_t first = pos;
  413. while (pos != input.size())
  414. {
  415. if (input[pos] == '\"') // Correct end of string
  416. {
  417. str.append( &input[first], pos-first);
  418. pos++;
  419. return true;
  420. }
  421. if (input[pos] == '\\') // Escaping
  422. {
  423. str.append( &input[first], pos-first);
  424. first = pos++;
  425. if (pos == input.size())
  426. break;
  427. extractEscaping(str);
  428. }
  429. if (input[pos] == '\n') // end-of-line
  430. {
  431. str.append( &input[first], pos-first);
  432. return error("Closing quote not found!", true);
  433. }
  434. if ((unsigned char)(input[pos]) < ' ') // control character
  435. {
  436. str.append( &input[first], pos-first);
  437. first = pos+1;
  438. error("Illegal character in the string!", true);
  439. }
  440. pos++;
  441. }
  442. return error("Unterminated string!");
  443. }
  444. bool JsonParser::extractString(JsonNode &node)
  445. {
  446. std::string str;
  447. if (!extractString(str))
  448. return false;
  449. node.setType(JsonNode::DATA_STRING);
  450. node.String() = str;
  451. return true;
  452. }
  453. bool JsonParser::extractLiteral(const std::string &literal)
  454. {
  455. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  456. {
  457. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  458. || (input[pos]>'A' && input[pos]<'Z')))
  459. pos++;
  460. return error("Unknown literal found", true);
  461. }
  462. pos += literal.size();
  463. return true;
  464. }
  465. bool JsonParser::extractNull(JsonNode &node)
  466. {
  467. if (!extractLiteral("null"))
  468. return false;
  469. node.setType(JsonNode::DATA_NULL);
  470. return true;
  471. }
  472. bool JsonParser::extractTrue(JsonNode &node)
  473. {
  474. if (!extractLiteral("true"))
  475. return false;
  476. node.Bool() = true;
  477. return true;
  478. }
  479. bool JsonParser::extractFalse(JsonNode &node)
  480. {
  481. if (!extractLiteral("false"))
  482. return false;
  483. node.Bool() = false;
  484. return true;
  485. }
  486. bool JsonParser::extractStruct(JsonNode &node)
  487. {
  488. node.setType(JsonNode::DATA_STRUCT);
  489. pos++;
  490. if (!extractWhitespace())
  491. return false;
  492. //Empty struct found
  493. if (input[pos] == '}')
  494. {
  495. pos++;
  496. return true;
  497. }
  498. while (true)
  499. {
  500. if (!extractWhitespace())
  501. return false;
  502. std::string key;
  503. if (!extractString(key))
  504. return false;
  505. if (node.Struct().find(key) != node.Struct().end())
  506. error("Dublicated element encountered!", true);
  507. if (!extractSeparator())
  508. return false;
  509. if (!extractElement(node.Struct()[key], '}'))
  510. return false;
  511. if (input[pos] == '}')
  512. {
  513. pos++;
  514. return true;
  515. }
  516. }
  517. }
  518. bool JsonParser::extractArray(JsonNode &node)
  519. {
  520. pos++;
  521. node.setType(JsonNode::DATA_VECTOR);
  522. if (!extractWhitespace())
  523. return false;
  524. //Empty array found
  525. if (input[pos] == ']')
  526. {
  527. pos++;
  528. return true;
  529. }
  530. while (true)
  531. {
  532. //NOTE: currently 50% of time is this vector resizing.
  533. //May be useful to use list during parsing and then swap() all items to vector
  534. node.Vector().resize(node.Vector().size()+1);
  535. if (!extractElement(node.Vector().back(), ']'))
  536. return false;
  537. if (input[pos] == ']')
  538. {
  539. pos++;
  540. return true;
  541. }
  542. }
  543. }
  544. bool JsonParser::extractElement(JsonNode &node, char terminator)
  545. {
  546. if (!extractValue(node))
  547. return false;
  548. if (!extractWhitespace())
  549. return false;
  550. bool comma = (input[pos] == ',');
  551. if (comma )
  552. {
  553. pos++;
  554. if (!extractWhitespace())
  555. return false;
  556. }
  557. if (input[pos] == terminator)
  558. return true;
  559. if (!comma)
  560. error("Comma expected!", true);
  561. return true;
  562. }
  563. bool JsonParser::extractFloat(JsonNode &node)
  564. {
  565. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  566. bool negative=false;
  567. double result=0;
  568. if (input[pos] == '-')
  569. {
  570. pos++;
  571. negative = true;
  572. }
  573. if (input[pos] < '0' || input[pos] > '9')
  574. return error("Number expected!");
  575. //Extract integer part
  576. while (input[pos] >= '0' && input[pos] <= '9')
  577. {
  578. result = result*10+(input[pos]-'0');
  579. pos++;
  580. }
  581. if (input[pos] == '.')
  582. {
  583. //extract fractional part
  584. pos++;
  585. double fractMult = 0.1;
  586. if (input[pos] < '0' || input[pos] > '9')
  587. return error("Decimal part expected!");
  588. while (input[pos] >= '0' && input[pos] <= '9')
  589. {
  590. result = result + fractMult*(input[pos]-'0');
  591. fractMult /= 10;
  592. pos++;
  593. }
  594. }
  595. //TODO: exponential part
  596. if (negative)
  597. result = -result;
  598. node.setType(JsonNode::DATA_FLOAT);
  599. node.Float() = result;
  600. return true;
  601. }
  602. bool JsonParser::error(const std::string &message, bool warning)
  603. {
  604. std::ostringstream stream;
  605. std::string type(warning?" warning: ":" error: ");
  606. stream << "At line " << lineCount << ", position "<<pos-lineStart
  607. << type << message <<"\n";
  608. errors += stream.str();
  609. return warning;
  610. }
  611. static const std::map<std::string, JsonNode::JsonType> stringToType =
  612. boost::assign::map_list_of
  613. ("null", JsonNode::DATA_NULL) ("bool", JsonNode::DATA_BOOL)
  614. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  615. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  616. //Check current schema entry for validness and converts "type" string to JsonType
  617. bool JsonValidator::validateSchema(JsonNode::JsonType &type, const JsonNode &schema)
  618. {
  619. if (schema.isNull())
  620. return addMessage("Missing schema for current entry!");
  621. const JsonNode &nodeType = schema["type"];
  622. if (nodeType.isNull())
  623. return addMessage("Entry type is not defined in schema!");
  624. if (nodeType.getType() != JsonNode::DATA_STRING)
  625. return addMessage("Entry type must be string!");
  626. std::map<std::string, JsonNode::JsonType>::const_iterator iter = stringToType.find(nodeType.String());
  627. if (iter == stringToType.end())
  628. return addMessage("Unknown entry type found!");
  629. type = iter->second;
  630. return true;
  631. }
  632. //Replaces node with default value if needed and calls type-specific validators
  633. bool JsonValidator::validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type)
  634. {
  635. if (node.isNull())
  636. {
  637. const JsonNode & defaultValue = schema["default"];
  638. if (defaultValue.isNull())
  639. return addMessage("Null entry without default entry!");
  640. else
  641. node = defaultValue;
  642. }
  643. if (minimize && node == schema["default"])
  644. {
  645. node.setType(JsonNode::DATA_NULL);
  646. return false;
  647. }
  648. if (type != node.getType())
  649. {
  650. node.setType(JsonNode::DATA_NULL);
  651. return addMessage("Type mismatch!");
  652. }
  653. if (type == JsonNode::DATA_VECTOR)
  654. return validateItems(node, schema["items"]);
  655. if (type == JsonNode::DATA_STRUCT)
  656. return validateProperties(node, schema["properties"]);
  657. return true;
  658. }
  659. // Basic checks common for any nodes
  660. bool JsonValidator::validateNode(JsonNode &node, const JsonNode &schema, const std::string &name)
  661. {
  662. currentPath.push_back(name);
  663. JsonNode::JsonType type = JsonNode::DATA_NULL;
  664. if (!validateSchema(type, schema)
  665. || !validateType(node, schema, type))
  666. {
  667. node.setType(JsonNode::DATA_NULL);
  668. currentPath.pop_back();
  669. return false;
  670. }
  671. currentPath.pop_back();
  672. return true;
  673. }
  674. //Checks "items" entry from schema (type-specific check for Vector)
  675. bool JsonValidator::validateItems(JsonNode &node, const JsonNode &schema)
  676. {
  677. JsonNode::JsonType type = JsonNode::DATA_NULL;
  678. if (!validateSchema(type, schema))
  679. return false;
  680. bool result = true;
  681. BOOST_FOREACH(JsonNode &entry, node.Vector())
  682. {
  683. if (!validateType(entry, schema, type))
  684. {
  685. result = false;
  686. entry.setType(JsonNode::DATA_NULL);
  687. }
  688. }
  689. return result;
  690. }
  691. //Checks "propertries" entry from schema (type-specific check for Struct)
  692. //Function is similar to merging of two sorted lists - check every entry that present in one of the input nodes
  693. bool JsonValidator::validateProperties(JsonNode &node, const JsonNode &schema)
  694. {
  695. if (schema.isNull())
  696. return addMessage("Properties entry is missing for struct in schema");
  697. JsonMap::iterator nodeIter = node.Struct().begin();
  698. JsonMap::const_iterator schemaIter = schema.Struct().begin();
  699. while (nodeIter != node.Struct().end() && schemaIter != schema.Struct().end())
  700. {
  701. if (nodeIter->first < schemaIter->first) //No schema for entry
  702. {
  703. validateNode(nodeIter->second, JsonNode::nullNode, nodeIter->first);
  704. JsonMap::iterator toRemove = nodeIter++;
  705. node.Struct().erase(toRemove);
  706. }
  707. else
  708. if (schemaIter->first < nodeIter->first) //No entry
  709. {
  710. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  711. node.Struct().erase(schemaIter->first);
  712. schemaIter++;
  713. }
  714. else //both entry and schema are present
  715. {
  716. JsonMap::iterator current = nodeIter++;
  717. if (!validateNode(current->second, schemaIter->second, current->first))
  718. node.Struct().erase(current);
  719. schemaIter++;
  720. }
  721. }
  722. while (nodeIter != node.Struct().end())
  723. {
  724. validateNode(nodeIter->second, JsonNode::nullNode, nodeIter->first);
  725. JsonMap::iterator toRemove = nodeIter++;
  726. node.Struct().erase(toRemove);
  727. }
  728. while (schemaIter != schema.Struct().end())
  729. {
  730. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  731. node.Struct().erase(schemaIter->first);
  732. schemaIter++;
  733. }
  734. return true;
  735. }
  736. bool JsonValidator::addMessage(const std::string &message)
  737. {
  738. std::ostringstream stream;
  739. stream << "At ";
  740. BOOST_FOREACH(const std::string &path, currentPath)
  741. stream << path<<"/";
  742. stream << "\t Error: " << message <<"\n";
  743. errors += stream.str();
  744. return false;
  745. }
  746. JsonValidator::JsonValidator(JsonNode &root, bool Minimize):
  747. minimize(Minimize)
  748. {
  749. JsonNode schema;
  750. schema.swap(root["schema"]);
  751. root.Struct().erase("schema");
  752. if (!schema.isNull())
  753. {
  754. validateProperties(root, schema);
  755. }
  756. //This message is quite annoying now - most files do not have schemas. May be re-enabled later
  757. //else
  758. // addMessage("Schema not found!", true);
  759. //TODO: better way to show errors (like printing file name as well)
  760. tlog3<<errors;
  761. }
  762. JsonValidator::JsonValidator(JsonNode &root, const JsonNode &schema, bool Minimize):
  763. minimize(Minimize)
  764. {
  765. validateProperties(root, schema);
  766. if (schema.isNull())
  767. addMessage("Schema not found!");
  768. tlog3<<errors;
  769. }
  770. Bonus * ParseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  771. {
  772. Bonus * b = new Bonus();
  773. std::string type = ability_vec[0].String();
  774. auto it = bonusNameMap.find(type);
  775. if (it == bonusNameMap.end())
  776. {
  777. tlog1 << "Error: invalid ability type " << type << " in creatures.txt" << std::endl;
  778. return b;
  779. }
  780. b->type = it->second;
  781. b->val = ability_vec[1].Float();
  782. b->subtype = ability_vec[2].Float();
  783. b->additionalInfo = ability_vec[3].Float();
  784. b->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  785. b->turnsRemain = 0;
  786. return b;
  787. }
  788. template <typename T>
  789. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  790. {
  791. static T defaultValue;
  792. if (!val->isNull())
  793. {
  794. std::string type = val->String();
  795. auto it = map.find(type);
  796. if (it == map.end())
  797. {
  798. tlog1 << "Error: invalid " << err << type << std::endl;
  799. return defaultValue;
  800. }
  801. else
  802. {
  803. return it->second;
  804. }
  805. }
  806. else
  807. return defaultValue;
  808. };
  809. Bonus * ParseBonus (const JsonNode &ability)
  810. {
  811. Bonus * b = new Bonus();
  812. const JsonNode *value;
  813. std::string type = ability["type"].String();
  814. auto it = bonusNameMap.find(type);
  815. if (it == bonusNameMap.end())
  816. {
  817. tlog1 << "Error: invalid ability type " << type << std::endl;
  818. return b;
  819. }
  820. b->type = it->second;
  821. value = &ability["subtype"];
  822. if (!value->isNull())
  823. b->subtype = value->Float();
  824. value = &ability["val"];
  825. if (!value->isNull())
  826. b->val = value->Float();
  827. value = &ability["valueType"];
  828. if (!value->isNull())
  829. b->valType = parseByMap(bonusValueMap, value, "value type ");
  830. value = &ability["additionalInfo"];
  831. if (!value->isNull())
  832. b->additionalInfo = value->Float();
  833. value = &ability["turns"];
  834. if (!value->isNull())
  835. b->turnsRemain = value->Float();
  836. value = &ability["sourceID"];
  837. if (!value->isNull())
  838. b->sid = value->Float();
  839. value = &ability["description"];
  840. if (!value->isNull())
  841. b->description = value->String();
  842. value = &ability["effectRange"];
  843. if (!value->isNull())
  844. b->valType = parseByMap(bonusLimitEffect, value, "effect range ");
  845. value = &ability["duration"];
  846. if (!value->isNull())
  847. b->valType = parseByMap(bonusDurationMap, value, "duration type ");
  848. value = &ability["source"];
  849. if (!value->isNull())
  850. b->valType = parseByMap(bonusSourceMap, value, "source type ");
  851. value = &ability["limiter"];
  852. if (!value->isNull())
  853. b->limiter = parseByMap(bonusLimiterMap, value, "limiter type ");
  854. value = &ability["propagator"];
  855. if (!value->isNull())
  856. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  857. return b;
  858. }
  859. //returns first Key with value equal to given one
  860. template<class Key, class Val>
  861. Key reverseMapFirst(const Val & val, const std::map<Key, Val> map)
  862. {
  863. BOOST_FOREACH(auto it, map)
  864. {
  865. if(it.second == val)
  866. {
  867. return it.first;
  868. }
  869. }
  870. assert(0);
  871. return "";
  872. }
  873. DLL_LINKAGE void UnparseBonus( JsonNode &node, const Bonus * bonus )
  874. {
  875. node["type"].String() = reverseMapFirst<std::string, int>(bonus->type, bonusNameMap);
  876. node["subtype"].Float() = bonus->subtype;
  877. node["val"].Float() = bonus->val;
  878. node["valueType"].String() = reverseMapFirst<std::string, int>(bonus->valType, bonusValueMap);
  879. node["additionalInfo"].Float() = bonus->additionalInfo;
  880. node["turns"].Float() = bonus->turnsRemain;
  881. node["sourceID"].Float() = bonus->source;
  882. node["description"].String() = bonus->description;
  883. node["effectRange"].String() = reverseMapFirst<std::string, int>(bonus->effectRange, bonusLimitEffect);
  884. node["duration"].String() = reverseMapFirst<std::string, int>(bonus->duration, bonusDurationMap);
  885. node["source"].String() = reverseMapFirst<std::string, int>(bonus->source, bonusSourceMap);
  886. if(bonus->limiter != nullptr)
  887. {
  888. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  889. }
  890. if(bonus->propagator != nullptr)
  891. {
  892. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  893. }
  894. }