2
0

JsonNode.cpp 23 KB

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