JsonNode.cpp 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. if (!val->isNull())
  792. {
  793. std::string type = val->String();
  794. auto it = map.find(type);
  795. if (it == map.end())
  796. {
  797. tlog1 << "Error: invalid " << err << type << std::endl;
  798. return T();
  799. }
  800. else
  801. {
  802. return it->second;
  803. }
  804. }
  805. };
  806. Bonus * ParseBonus (const JsonNode &ability)
  807. {
  808. Bonus * b = new Bonus();
  809. const JsonNode *value;
  810. std::string type = ability["type"].String();
  811. auto it = bonusNameMap.find(type);
  812. if (it == bonusNameMap.end())
  813. {
  814. tlog1 << "Error: invalid ability type " << type << std::endl;
  815. return b;
  816. }
  817. b->type = it->second;
  818. value = &ability["subtype"];
  819. if (!value->isNull())
  820. b->subtype = value->Float();
  821. value = &ability["val"];
  822. if (!value->isNull())
  823. b->val = value->Float();
  824. b->valType = parseByMap(bonusValueMap, &ability["valueType"], "value type ");
  825. value = &ability["additionalInfo"];
  826. if (!value->isNull())
  827. b->additionalInfo = value->Float();
  828. value = &ability["turns"];
  829. if (!value->isNull())
  830. b->turnsRemain = value->Float();
  831. value = &ability["sourceID"];
  832. if (!value->isNull())
  833. b->sid = value->Float();
  834. value = &ability["description"];
  835. if (!value->isNull())
  836. b->description = value->String();
  837. b->effectRange = parseByMap(bonusLimitEffect, &ability["effectRange"], "effect range ");
  838. b->duration = parseByMap(bonusDurationMap, &ability["duration"], "duration type ");
  839. b->source = parseByMap(bonusSourceMap, &ability["source"], "source type ");
  840. // value = &ability["limiter"];
  841. // if (!value->isNull())
  842. // b->limiter = parseByMap(bonusLimiterMap, value, "limiter type ");
  843. //
  844. //
  845. // value = &ability["propagator"];
  846. // if (!value->isNull())
  847. // b->propagator = parseByMap(bonusLimiterMap, value, "propagator type ");
  848. return b;
  849. }
  850. DLL_LINKAGE void UnparseBonus( JsonNode &node, const Bonus * bonus )
  851. {
  852. auto reverseMap = [](const int & val, const std::map<std::string, int> map) -> std::string
  853. {
  854. BOOST_FOREACH(auto it, map)
  855. {
  856. if(it.second == val)
  857. {
  858. return it.first;
  859. }
  860. }
  861. };
  862. node["type"].String() = reverseMap(bonus->type, bonusNameMap);
  863. node["subtype"].Float() = bonus->subtype;
  864. node["val"].Float() = bonus->val;
  865. node["valueType"].String() = reverseMap(bonus->valType, bonusValueMap);
  866. node["additionalInfo"].Float() = bonus->additionalInfo;
  867. node["turns"].Float() = bonus->turnsRemain;
  868. node["sourceID"].Float() = bonus->source;
  869. node["description"].String() = bonus->description;
  870. node["effectRange"].String() = reverseMap(bonus->effectRange, bonusLimitEffect);
  871. node["duration"].String() = reverseMap(bonus->duration, bonusDurationMap);
  872. node["source"].String() = reverseMap(bonus->source, bonusSourceMap);
  873. }