2
0

JsonNode.cpp 21 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. template<typename Iterator>
  208. void JsonWriter::writeContainer(Iterator begin, Iterator end)
  209. {
  210. if (begin == end)
  211. return;
  212. prefix += '\t';
  213. end--;
  214. while (begin != end)
  215. {
  216. writeEntry(begin++);
  217. out<<",\n";
  218. }
  219. writeEntry(begin);
  220. out<<"\n";
  221. prefix.resize(prefix.size()-1);
  222. }
  223. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  224. {
  225. out << prefix;
  226. writeString(entry->first);
  227. out << " : ";
  228. writeNode(entry->second);
  229. }
  230. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  231. {
  232. out << prefix;
  233. writeNode(*entry);
  234. }
  235. void JsonWriter::writeString(const std::string &string)
  236. {
  237. static const std::string escaped = "\"\\/\b\f\n\r\t";
  238. out <<'\"';
  239. size_t pos=0, start=0;
  240. for (; pos<string.size(); pos++)
  241. {
  242. size_t escapedChar = escaped.find(string[pos]);
  243. if (escapedChar != std::string::npos)
  244. {
  245. out.write(string.data()+start, pos - start);
  246. out << '\\' << escaped[escapedChar];
  247. start = pos;
  248. }
  249. }
  250. out.write(string.data()+start, pos - start);
  251. out <<'\"';
  252. }
  253. void JsonWriter::writeNode(const JsonNode &node)
  254. {
  255. switch(node.getType())
  256. {
  257. break; case JsonNode::DATA_NULL:
  258. out << "null";
  259. break; case JsonNode::DATA_BOOL:
  260. if (node.Bool())
  261. out << "true";
  262. else
  263. out << "false";
  264. break; case JsonNode::DATA_FLOAT:
  265. out << node.Float();
  266. break; case JsonNode::DATA_STRING:
  267. writeString(node.String());
  268. break; case JsonNode::DATA_VECTOR:
  269. out << "[" << "\n";
  270. writeContainer(node.Vector().begin(), node.Vector().end());
  271. out << prefix << "]";
  272. break; case JsonNode::DATA_STRUCT:
  273. out << "{" << "\n";
  274. writeContainer(node.Struct().begin(), node.Struct().end());
  275. out << prefix << "}";
  276. }
  277. }
  278. JsonWriter::JsonWriter(std::ostream &output, const JsonNode &node):
  279. out(output)
  280. {
  281. writeNode(node);
  282. }
  283. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  284. {
  285. JsonWriter(out, node);
  286. return out << "\n";
  287. }
  288. ////////////////////////////////////////////////////////////////////////////////
  289. JsonParser::JsonParser(const char * inputString, size_t stringSize, JsonNode &root):
  290. input(inputString, stringSize),
  291. lineCount(1),
  292. lineStart(0),
  293. pos(0)
  294. {
  295. extractValue(root);
  296. extractWhitespace(false);
  297. //Warn if there are any non-whitespace symbols left
  298. if (pos < input.size())
  299. error("Not all file was parsed!", true);
  300. //TODO: better way to show errors (like printing file name as well)
  301. tlog3<<errors;
  302. }
  303. bool JsonParser::extractSeparator()
  304. {
  305. if (!extractWhitespace())
  306. return false;
  307. if ( input[pos] !=':')
  308. return error("Separator expected");
  309. pos++;
  310. return true;
  311. }
  312. bool JsonParser::extractValue(JsonNode &node)
  313. {
  314. if (!extractWhitespace())
  315. return false;
  316. switch (input[pos])
  317. {
  318. case '\"': return extractString(node);
  319. case 'n' : return extractNull(node);
  320. case 't' : return extractTrue(node);
  321. case 'f' : return extractFalse(node);
  322. case '{' : return extractStruct(node);
  323. case '[' : return extractArray(node);
  324. case '-' : return extractFloat(node);
  325. default:
  326. {
  327. if (input[pos] >= '0' && input[pos] <= '9')
  328. return extractFloat(node);
  329. return error("Value expected!");
  330. }
  331. }
  332. }
  333. bool JsonParser::extractWhitespace(bool verbose)
  334. {
  335. while (true)
  336. {
  337. while (pos < input.size() && (ui8)input[pos] <= ' ')
  338. {
  339. if (input[pos] == '\n')
  340. {
  341. lineCount++;
  342. lineStart = pos+1;
  343. }
  344. pos++;
  345. }
  346. if (pos >= input.size() || input[pos] != '/')
  347. break;
  348. pos++;
  349. if (pos == input.size())
  350. break;
  351. if (input[pos] == '/')
  352. pos++;
  353. else
  354. error("Comments must consist from two slashes!", true);
  355. while (pos < input.size() && input[pos] != '\n')
  356. pos++;
  357. }
  358. if (pos >= input.size() && verbose)
  359. return error("Unexpected end of file!");
  360. return true;
  361. }
  362. bool JsonParser::extractEscaping(std::string &str)
  363. {
  364. switch(input[pos++])
  365. {
  366. break; case '\"': str += '\"';
  367. break; case '\\': str += '\\';
  368. break; case '/': str += '/';
  369. break; case '\b': str += '\b';
  370. break; case '\f': str += '\f';
  371. break; case '\n': str += '\n';
  372. break; case '\r': str += '\r';
  373. break; case '\t': str += '\t';
  374. break; default: return error("Unknown escape sequence!", true);
  375. };
  376. return true;
  377. }
  378. bool JsonParser::extractString(std::string &str)
  379. {
  380. if (input[pos] != '\"')
  381. return error("String expected!");
  382. pos++;
  383. size_t first = pos;
  384. while (pos != input.size())
  385. {
  386. if (input[pos] == '\"') // Correct end of string
  387. {
  388. str.append( &input[first], pos-first);
  389. pos++;
  390. return true;
  391. }
  392. if (input[pos] == '\\') // Escaping
  393. {
  394. str.append( &input[first], pos-first);
  395. first = pos++;
  396. if (pos == input.size())
  397. break;
  398. extractEscaping(str);
  399. }
  400. if (input[pos] == '\n') // end-of-line
  401. {
  402. str.append( &input[first], pos-first);
  403. return error("Closing quote not found!", true);
  404. }
  405. if (input[pos] < ' ') // control character
  406. {
  407. str.append( &input[first], pos-first);
  408. first = pos+1;
  409. error("Illegal character in the string!", true);
  410. }
  411. pos++;
  412. }
  413. return error("Unterminated string!");
  414. }
  415. bool JsonParser::extractString(JsonNode &node)
  416. {
  417. std::string str;
  418. if (!extractString(str))
  419. return false;
  420. node.setType(JsonNode::DATA_STRING);
  421. node.String() = str;
  422. return true;
  423. }
  424. bool JsonParser::extractLiteral(const std::string &literal)
  425. {
  426. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  427. {
  428. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  429. || (input[pos]>'A' && input[pos]<'Z')))
  430. pos++;
  431. return error("Unknown literal found", true);
  432. }
  433. pos += literal.size();
  434. return true;
  435. }
  436. bool JsonParser::extractNull(JsonNode &node)
  437. {
  438. if (!extractLiteral("null"))
  439. return false;
  440. node.setType(JsonNode::DATA_NULL);
  441. return true;
  442. }
  443. bool JsonParser::extractTrue(JsonNode &node)
  444. {
  445. if (!extractLiteral("true"))
  446. return false;
  447. node.Bool() = true;
  448. return true;
  449. }
  450. bool JsonParser::extractFalse(JsonNode &node)
  451. {
  452. if (!extractLiteral("false"))
  453. return false;
  454. node.Bool() = false;
  455. return true;
  456. }
  457. bool JsonParser::extractStruct(JsonNode &node)
  458. {
  459. node.setType(JsonNode::DATA_STRUCT);
  460. pos++;
  461. if (!extractWhitespace())
  462. return false;
  463. //Empty struct found
  464. if (input[pos] == '}')
  465. {
  466. pos++;
  467. return true;
  468. }
  469. while (true)
  470. {
  471. if (!extractWhitespace())
  472. return false;
  473. std::string key;
  474. if (!extractString(key))
  475. return false;
  476. if (node.Struct().find(key) != node.Struct().end())
  477. error("Dublicated element encountered!", true);
  478. if (!extractSeparator())
  479. return false;
  480. if (!extractElement(node.Struct()[key], '}'))
  481. return false;
  482. if (input[pos] == '}')
  483. {
  484. pos++;
  485. return true;
  486. }
  487. }
  488. }
  489. bool JsonParser::extractArray(JsonNode &node)
  490. {
  491. pos++;
  492. node.setType(JsonNode::DATA_VECTOR);
  493. if (!extractWhitespace())
  494. return false;
  495. //Empty array found
  496. if (input[pos] == ']')
  497. {
  498. pos++;
  499. return true;
  500. }
  501. while (true)
  502. {
  503. //NOTE: currently 50% of time is this vector resizing.
  504. //May be useful to use list during parsing and then swap() all items to vector
  505. node.Vector().resize(node.Vector().size()+1);
  506. if (!extractElement(node.Vector().back(), ']'))
  507. return false;
  508. if (input[pos] == ']')
  509. {
  510. pos++;
  511. return true;
  512. }
  513. }
  514. }
  515. bool JsonParser::extractElement(JsonNode &node, char terminator)
  516. {
  517. if (!extractValue(node))
  518. return false;
  519. if (!extractWhitespace())
  520. return false;
  521. bool comma = (input[pos] == ',');
  522. if (comma )
  523. {
  524. pos++;
  525. if (!extractWhitespace())
  526. return false;
  527. }
  528. if (input[pos] == terminator)
  529. return true;
  530. if (!comma)
  531. error("Comma expected!", true);
  532. return true;
  533. }
  534. bool JsonParser::extractFloat(JsonNode &node)
  535. {
  536. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  537. bool negative=false;
  538. double result=0;
  539. if (input[pos] == '-')
  540. {
  541. pos++;
  542. negative = true;
  543. }
  544. if (input[pos] < '0' || input[pos] > '9')
  545. return error("Number expected!");
  546. //Extract integer part
  547. while (input[pos] >= '0' && input[pos] <= '9')
  548. {
  549. result = result*10+(input[pos]-'0');
  550. pos++;
  551. }
  552. if (input[pos] == '.')
  553. {
  554. //extract fractional part
  555. pos++;
  556. double fractMult = 0.1;
  557. if (input[pos] < '0' || input[pos] > '9')
  558. return error("Decimal part expected!");
  559. while (input[pos] >= '0' && input[pos] <= '9')
  560. {
  561. result = result + fractMult*(input[pos]-'0');
  562. fractMult /= 10;
  563. pos++;
  564. }
  565. }
  566. //TODO: exponential part
  567. if (negative)
  568. result = -result;
  569. node.setType(JsonNode::DATA_FLOAT);
  570. node.Float() = result;
  571. return true;
  572. }
  573. bool JsonParser::error(const std::string &message, bool warning)
  574. {
  575. std::ostringstream stream;
  576. std::string type(warning?" warning: ":" error: ");
  577. stream << "At line " << lineCount << ", position "<<pos-lineStart
  578. << type << message <<"\n";
  579. errors += stream.str();
  580. return warning;
  581. }
  582. static const std::map<std::string, JsonNode::JsonType> stringToType =
  583. boost::assign::map_list_of
  584. ("null", JsonNode::DATA_NULL) ("bool", JsonNode::DATA_BOOL)
  585. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  586. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  587. //Check current schema entry for validness and converts "type" string to JsonType
  588. bool JsonValidator::validateSchema(JsonNode::JsonType &type, const JsonNode &schema)
  589. {
  590. if (schema.isNull())
  591. return addMessage("Missing schema for current entry!");
  592. const JsonNode &nodeType = schema["type"];
  593. if (nodeType.isNull())
  594. return addMessage("Entry type is not defined in schema!");
  595. if (nodeType.getType() != JsonNode::DATA_STRING)
  596. return addMessage("Entry type must be string!");
  597. std::map<std::string, JsonNode::JsonType>::const_iterator iter = stringToType.find(nodeType.String());
  598. if (iter == stringToType.end())
  599. return addMessage("Unknown entry type found!");
  600. type = iter->second;
  601. return true;
  602. }
  603. //Replaces node with default value if needed and calls type-specific validators
  604. bool JsonValidator::validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type)
  605. {
  606. if (node.isNull())
  607. {
  608. const JsonNode & defaultValue = schema["default"];
  609. if (defaultValue.isNull())
  610. return addMessage("Null entry without default entry!");
  611. else
  612. node = defaultValue;
  613. }
  614. if (minimize && node == schema["default"])
  615. {
  616. node.setType(JsonNode::DATA_NULL);
  617. return false;
  618. }
  619. if (type != node.getType())
  620. {
  621. node.setType(JsonNode::DATA_NULL);
  622. return addMessage("Type mismatch!");
  623. }
  624. if (type == JsonNode::DATA_VECTOR)
  625. return validateItems(node, schema["items"]);
  626. if (type == JsonNode::DATA_STRUCT)
  627. return validateProperties(node, schema["properties"]);
  628. return true;
  629. }
  630. // Basic checks common for any nodes
  631. bool JsonValidator::validateNode(JsonNode &node, const JsonNode &schema, const std::string &name)
  632. {
  633. currentPath.push_back(name);
  634. JsonNode::JsonType type = JsonNode::DATA_NULL;
  635. if (!validateSchema(type, schema)
  636. || !validateType(node, schema, type))
  637. {
  638. node.setType(JsonNode::DATA_NULL);
  639. currentPath.pop_back();
  640. return false;
  641. }
  642. currentPath.pop_back();
  643. return true;
  644. }
  645. //Checks "items" entry from schema (type-specific check for Vector)
  646. bool JsonValidator::validateItems(JsonNode &node, const JsonNode &schema)
  647. {
  648. JsonNode::JsonType type = JsonNode::DATA_NULL;
  649. if (!validateSchema(type, schema))
  650. return false;
  651. bool result = true;
  652. BOOST_FOREACH(JsonNode &entry, node.Vector())
  653. {
  654. if (!validateType(entry, schema, type))
  655. {
  656. result = false;
  657. entry.setType(JsonNode::DATA_NULL);
  658. }
  659. }
  660. return result;
  661. }
  662. //Checks "propertries" entry from schema (type-specific check for Struct)
  663. //Function is similar to merging of two sorted lists - check every entry that present in one of the input nodes
  664. bool JsonValidator::validateProperties(JsonNode &node, const JsonNode &schema)
  665. {
  666. if (schema.isNull())
  667. return addMessage("Properties entry is missing for struct in schema");
  668. JsonMap::iterator nodeIter = node.Struct().begin();
  669. JsonMap::const_iterator schemaIter = schema.Struct().begin();
  670. while (nodeIter != node.Struct().end() && schemaIter != schema.Struct().end())
  671. {
  672. if (nodeIter->first < schemaIter->first) //No schema for entry
  673. {
  674. validateNode(nodeIter->second, JsonNode::nullNode, nodeIter->first);
  675. JsonMap::iterator toRemove = nodeIter++;
  676. node.Struct().erase(toRemove);
  677. }
  678. else
  679. if (schemaIter->first < nodeIter->first) //No entry
  680. {
  681. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  682. node.Struct().erase(schemaIter->first);
  683. schemaIter++;
  684. }
  685. else //both entry and schema are present
  686. {
  687. JsonMap::iterator current = nodeIter++;
  688. if (!validateNode(current->second, schemaIter->second, current->first))
  689. node.Struct().erase(current);
  690. schemaIter++;
  691. }
  692. }
  693. while (nodeIter != node.Struct().end())
  694. {
  695. validateNode(nodeIter->second, JsonNode::nullNode, nodeIter->first);
  696. JsonMap::iterator toRemove = nodeIter++;
  697. node.Struct().erase(toRemove);
  698. }
  699. while (schemaIter != schema.Struct().end())
  700. {
  701. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  702. node.Struct().erase(schemaIter->first);
  703. schemaIter++;
  704. }
  705. return true;
  706. }
  707. bool JsonValidator::addMessage(const std::string &message)
  708. {
  709. std::ostringstream stream;
  710. stream << "At ";
  711. BOOST_FOREACH(const std::string &path, currentPath)
  712. stream << path<<"/";
  713. stream << "\t Error: " << message <<"\n";
  714. errors += stream.str();
  715. return false;
  716. }
  717. JsonValidator::JsonValidator(JsonNode &root, bool Minimize):
  718. minimize(Minimize)
  719. {
  720. JsonNode schema;
  721. schema.swap(root["schema"]);
  722. root.Struct().erase("schema");
  723. if (!schema.isNull())
  724. {
  725. validateProperties(root, schema);
  726. }
  727. //This message is quite annoying now - most files do not have schemas. May be re-enabled later
  728. //else
  729. // addMessage("Schema not found!", true);
  730. //TODO: better way to show errors (like printing file name as well)
  731. tlog3<<errors;
  732. }
  733. JsonValidator::JsonValidator(JsonNode &root, const JsonNode &schema, bool Minimize):
  734. minimize(Minimize)
  735. {
  736. validateProperties(root, schema);
  737. if (schema.isNull())
  738. addMessage("Schema not found!");
  739. tlog3<<errors;
  740. }
  741. Bonus * ParseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  742. {
  743. Bonus * b = new Bonus();
  744. std::string type = ability_vec[0].String();
  745. auto it = bonusNameMap.find(type);
  746. if (it == bonusNameMap.end())
  747. {
  748. tlog1 << "Error: invalid ability type " << type << " in creatures.txt" << std::endl;
  749. return b;
  750. }
  751. b->type = it->second;
  752. b->val = ability_vec[1].Float();
  753. b->subtype = ability_vec[2].Float();
  754. b->additionalInfo = ability_vec[3].Float();
  755. b->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  756. b->turnsRemain = 0;
  757. return b;
  758. }
  759. Bonus * ParseBonus (const JsonNode &ability)
  760. {
  761. Bonus * b = new Bonus();
  762. const JsonNode *value;
  763. std::string type = ability["type"].String();
  764. auto it = bonusNameMap.find(type);
  765. if (it == bonusNameMap.end())
  766. {
  767. tlog1 << "Error: invalid ability type " << type << std::endl;
  768. return b;
  769. }
  770. b->type = it->second;
  771. value = &ability["subtype"];
  772. if (!value->isNull())
  773. b->subtype = value->Float();
  774. value = &ability["val"];
  775. if (!value->isNull())
  776. b->val = value->Float();
  777. value = &ability["valueType"];
  778. if (!value->isNull())
  779. {
  780. std::string type = value->String();
  781. auto it = bonusValueMap.find(type);
  782. if (it == bonusValueMap.end())
  783. {
  784. tlog1 << "Error: invalid value type " << type << std::endl;
  785. }
  786. else
  787. {
  788. b->valType = it->second;
  789. }
  790. }
  791. value = &ability["additionalInfo"];
  792. if (!value->isNull())
  793. b->additionalInfo = value->Float();
  794. value = &ability["turns"];
  795. if (!value->isNull())
  796. b->turnsRemain = value->Float();
  797. value = &ability["sourceID"];
  798. if (!value->isNull())
  799. b->sid = value->Float();
  800. value = &ability["description"];
  801. if (!value->isNull())
  802. b->description = value->String();
  803. value = &ability["effectRange"];
  804. if (!value->isNull())
  805. {
  806. std::string type = value->String();
  807. auto it = bonusLimitEffect.find(type);
  808. if (it == bonusLimitEffect.end())
  809. {
  810. tlog1 << "Error: invalid effect range " << type << std::endl;
  811. }
  812. else
  813. {
  814. b->effectRange = it->second;
  815. }
  816. }
  817. value = &ability["duration"];
  818. if (!value->isNull())
  819. {
  820. std::string type = value->String();
  821. auto it = bonusDurationMap.find(type);
  822. if (it == bonusDurationMap.end())
  823. {
  824. tlog1 << "Error: invalid duration type " << type << std::endl;
  825. }
  826. else
  827. {
  828. b->duration = it->second;
  829. }
  830. }
  831. value = &ability["source"];
  832. if (!value->isNull())
  833. {
  834. std::string type = value->String();
  835. auto it = bonusSourceMap.find(type);
  836. if (it == bonusSourceMap.end())
  837. {
  838. tlog1 << "Error: invalid source type " << type << std::endl;
  839. }
  840. else
  841. {
  842. b->source = it->second;
  843. }
  844. }
  845. //TODO:
  846. //value = &ability["limiter"];
  847. //if (!value->isNull())
  848. // b->limiter = value->Float();
  849. //value = &ability["propagator"];
  850. //if (!value->isNull())
  851. // b->propagator = value->Float();
  852. return b;
  853. }