JsonNode.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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(bonusValueMap, value, "effect range ");
  845. value = &ability["duration"];
  846. if (!value->isNull())
  847. b->valType = parseByMap(bonusValueMap, value, "duration type ");
  848. value = &ability["source"];
  849. if (!value->isNull())
  850. b->valType = parseByMap(bonusValueMap, value, "source type ");
  851. // value = &ability["limiter"];
  852. // if (!value->isNull())
  853. // b->limiter = parseByMap(bonusLimiterMap, value, "limiter type ");
  854. //
  855. //
  856. // value = &ability["propagator"];
  857. // if (!value->isNull())
  858. // b->propagator = parseByMap(bonusLimiterMap, value, "propagator type ");
  859. return b;
  860. }
  861. DLL_LINKAGE void UnparseBonus( JsonNode &node, const Bonus * bonus )
  862. {
  863. auto reverseMap = [](const int & val, const std::map<std::string, int> map) -> std::string
  864. {
  865. BOOST_FOREACH(auto it, map)
  866. {
  867. if(it.second == val)
  868. {
  869. return it.first;
  870. }
  871. }
  872. assert(0);
  873. return "";
  874. };
  875. node["type"].String() = reverseMap(bonus->type, bonusNameMap);
  876. node["subtype"].Float() = bonus->subtype;
  877. node["val"].Float() = bonus->val;
  878. node["valueType"].String() = reverseMap(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() = reverseMap(bonus->effectRange, bonusLimitEffect);
  884. node["duration"].String() = reverseMap(bonus->duration, bonusDurationMap);
  885. node["source"].String() = reverseMap(bonus->source, bonusSourceMap);
  886. }