JsonNode.cpp 27 KB

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