JsonNode.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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. end--;
  220. while (begin != end)
  221. {
  222. writeEntry(begin++);
  223. out<<",\n";
  224. }
  225. writeEntry(begin);
  226. out<<"\n";
  227. prefix.resize(prefix.size()-1);
  228. }
  229. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  230. {
  231. out << prefix;
  232. writeString(entry->first);
  233. out << " : ";
  234. writeNode(entry->second);
  235. }
  236. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  237. {
  238. out << prefix;
  239. writeNode(*entry);
  240. }
  241. void JsonWriter::writeString(const std::string &string)
  242. {
  243. static const std::string escaped = "\"\\/\b\f\n\r\t";
  244. out <<'\"';
  245. size_t pos=0, start=0;
  246. for (; pos<string.size(); pos++)
  247. {
  248. size_t escapedChar = escaped.find(string[pos]);
  249. if (escapedChar != std::string::npos)
  250. {
  251. out.write(string.data()+start, pos - start);
  252. out << '\\' << escaped[escapedChar];
  253. start = pos;
  254. }
  255. }
  256. out.write(string.data()+start, pos - start);
  257. out <<'\"';
  258. }
  259. void JsonWriter::writeNode(const JsonNode &node)
  260. {
  261. switch(node.getType())
  262. {
  263. break; case JsonNode::DATA_NULL:
  264. out << "null";
  265. break; case JsonNode::DATA_BOOL:
  266. if (node.Bool())
  267. out << "true";
  268. else
  269. out << "false";
  270. break; case JsonNode::DATA_FLOAT:
  271. out << node.Float();
  272. break; case JsonNode::DATA_STRING:
  273. writeString(node.String());
  274. break; case JsonNode::DATA_VECTOR:
  275. out << "[" << "\n";
  276. writeContainer(node.Vector().begin(), node.Vector().end());
  277. out << prefix << "]";
  278. break; case JsonNode::DATA_STRUCT:
  279. out << "{" << "\n";
  280. writeContainer(node.Struct().begin(), node.Struct().end());
  281. out << prefix << "}";
  282. }
  283. }
  284. JsonWriter::JsonWriter(std::ostream &output, const JsonNode &node):
  285. out(output)
  286. {
  287. writeNode(node);
  288. }
  289. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  290. {
  291. JsonWriter(out, node);
  292. return out << "\n";
  293. }
  294. ////////////////////////////////////////////////////////////////////////////////
  295. JsonParser::JsonParser(const char * inputString, size_t stringSize, JsonNode &root):
  296. input(inputString, stringSize),
  297. lineCount(1),
  298. lineStart(0),
  299. pos(0)
  300. {
  301. extractValue(root);
  302. extractWhitespace(false);
  303. //Warn if there are any non-whitespace symbols left
  304. if (pos < input.size())
  305. error("Not all file was parsed!", true);
  306. //TODO: better way to show errors (like printing file name as well)
  307. tlog3<<errors;
  308. }
  309. bool JsonParser::extractSeparator()
  310. {
  311. if (!extractWhitespace())
  312. return false;
  313. if ( input[pos] !=':')
  314. return error("Separator expected");
  315. pos++;
  316. return true;
  317. }
  318. bool JsonParser::extractValue(JsonNode &node)
  319. {
  320. if (!extractWhitespace())
  321. return false;
  322. switch (input[pos])
  323. {
  324. case '\"': return extractString(node);
  325. case 'n' : return extractNull(node);
  326. case 't' : return extractTrue(node);
  327. case 'f' : return extractFalse(node);
  328. case '{' : return extractStruct(node);
  329. case '[' : return extractArray(node);
  330. case '-' : return extractFloat(node);
  331. default:
  332. {
  333. if (input[pos] >= '0' && input[pos] <= '9')
  334. return extractFloat(node);
  335. return error("Value expected!");
  336. }
  337. }
  338. }
  339. bool JsonParser::extractWhitespace(bool verbose)
  340. {
  341. while (true)
  342. {
  343. while (pos < input.size() && (ui8)input[pos] <= ' ')
  344. {
  345. if (input[pos] == '\n')
  346. {
  347. lineCount++;
  348. lineStart = pos+1;
  349. }
  350. pos++;
  351. }
  352. if (pos >= input.size() || input[pos] != '/')
  353. break;
  354. pos++;
  355. if (pos == input.size())
  356. break;
  357. if (input[pos] == '/')
  358. pos++;
  359. else
  360. error("Comments must consist from two slashes!", true);
  361. while (pos < input.size() && input[pos] != '\n')
  362. pos++;
  363. }
  364. if (pos >= input.size() && verbose)
  365. return error("Unexpected end of file!");
  366. return true;
  367. }
  368. bool JsonParser::extractEscaping(std::string &str)
  369. {
  370. switch(input[pos])
  371. {
  372. break; case '\"': str += '\"';
  373. break; case '\\': str += '\\';
  374. break; case '/': str += '/';
  375. break; case 'b': str += '\b';
  376. break; case 'f': str += '\f';
  377. break; case 'n': str += '\n';
  378. break; case 'r': str += '\r';
  379. break; case 't': str += '\t';
  380. break; default: return error("Unknown escape sequence!", true);
  381. };
  382. return true;
  383. }
  384. bool JsonParser::extractString(std::string &str)
  385. {
  386. if (input[pos] != '\"')
  387. return error("String expected!");
  388. pos++;
  389. size_t first = pos;
  390. while (pos != input.size())
  391. {
  392. if (input[pos] == '\"') // Correct end of string
  393. {
  394. str.append( &input[first], pos-first);
  395. pos++;
  396. return true;
  397. }
  398. if (input[pos] == '\\') // Escaping
  399. {
  400. str.append( &input[first], pos-first);
  401. pos++;
  402. if (pos == input.size())
  403. break;
  404. extractEscaping(str);
  405. first = pos + 1;
  406. }
  407. if (input[pos] == '\n') // end-of-line
  408. {
  409. str.append( &input[first], pos-first);
  410. return error("Closing quote not found!", true);
  411. }
  412. if ((unsigned char)(input[pos]) < ' ') // control character
  413. {
  414. str.append( &input[first], pos-first);
  415. first = pos+1;
  416. error("Illegal character in the string!", true);
  417. }
  418. pos++;
  419. }
  420. return error("Unterminated string!");
  421. }
  422. bool JsonParser::extractString(JsonNode &node)
  423. {
  424. std::string str;
  425. if (!extractString(str))
  426. return false;
  427. node.setType(JsonNode::DATA_STRING);
  428. node.String() = str;
  429. return true;
  430. }
  431. bool JsonParser::extractLiteral(const std::string &literal)
  432. {
  433. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  434. {
  435. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  436. || (input[pos]>'A' && input[pos]<'Z')))
  437. pos++;
  438. return error("Unknown literal found", true);
  439. }
  440. pos += literal.size();
  441. return true;
  442. }
  443. bool JsonParser::extractNull(JsonNode &node)
  444. {
  445. if (!extractLiteral("null"))
  446. return false;
  447. node.setType(JsonNode::DATA_NULL);
  448. return true;
  449. }
  450. bool JsonParser::extractTrue(JsonNode &node)
  451. {
  452. if (!extractLiteral("true"))
  453. return false;
  454. node.Bool() = true;
  455. return true;
  456. }
  457. bool JsonParser::extractFalse(JsonNode &node)
  458. {
  459. if (!extractLiteral("false"))
  460. return false;
  461. node.Bool() = false;
  462. return true;
  463. }
  464. bool JsonParser::extractStruct(JsonNode &node)
  465. {
  466. node.setType(JsonNode::DATA_STRUCT);
  467. pos++;
  468. if (!extractWhitespace())
  469. return false;
  470. //Empty struct found
  471. if (input[pos] == '}')
  472. {
  473. pos++;
  474. return true;
  475. }
  476. while (true)
  477. {
  478. if (!extractWhitespace())
  479. return false;
  480. std::string key;
  481. if (!extractString(key))
  482. return false;
  483. if (node.Struct().find(key) != node.Struct().end())
  484. error("Dublicated element encountered!", true);
  485. if (!extractSeparator())
  486. return false;
  487. if (!extractElement(node.Struct()[key], '}'))
  488. return false;
  489. if (input[pos] == '}')
  490. {
  491. pos++;
  492. return true;
  493. }
  494. }
  495. }
  496. bool JsonParser::extractArray(JsonNode &node)
  497. {
  498. pos++;
  499. node.setType(JsonNode::DATA_VECTOR);
  500. if (!extractWhitespace())
  501. return false;
  502. //Empty array found
  503. if (input[pos] == ']')
  504. {
  505. pos++;
  506. return true;
  507. }
  508. while (true)
  509. {
  510. //NOTE: currently 50% of time is this vector resizing.
  511. //May be useful to use list during parsing and then swap() all items to vector
  512. node.Vector().resize(node.Vector().size()+1);
  513. if (!extractElement(node.Vector().back(), ']'))
  514. return false;
  515. if (input[pos] == ']')
  516. {
  517. pos++;
  518. return true;
  519. }
  520. }
  521. }
  522. bool JsonParser::extractElement(JsonNode &node, char terminator)
  523. {
  524. if (!extractValue(node))
  525. return false;
  526. if (!extractWhitespace())
  527. return false;
  528. bool comma = (input[pos] == ',');
  529. if (comma )
  530. {
  531. pos++;
  532. if (!extractWhitespace())
  533. return false;
  534. }
  535. if (input[pos] == terminator)
  536. return true;
  537. if (!comma)
  538. error("Comma expected!", true);
  539. return true;
  540. }
  541. bool JsonParser::extractFloat(JsonNode &node)
  542. {
  543. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  544. bool negative=false;
  545. double result=0;
  546. if (input[pos] == '-')
  547. {
  548. pos++;
  549. negative = true;
  550. }
  551. if (input[pos] < '0' || input[pos] > '9')
  552. return error("Number expected!");
  553. //Extract integer part
  554. while (input[pos] >= '0' && input[pos] <= '9')
  555. {
  556. result = result*10+(input[pos]-'0');
  557. pos++;
  558. }
  559. if (input[pos] == '.')
  560. {
  561. //extract fractional part
  562. pos++;
  563. double fractMult = 0.1;
  564. if (input[pos] < '0' || input[pos] > '9')
  565. return error("Decimal part expected!");
  566. while (input[pos] >= '0' && input[pos] <= '9')
  567. {
  568. result = result + fractMult*(input[pos]-'0');
  569. fractMult /= 10;
  570. pos++;
  571. }
  572. }
  573. //TODO: exponential part
  574. if (negative)
  575. result = -result;
  576. node.setType(JsonNode::DATA_FLOAT);
  577. node.Float() = result;
  578. return true;
  579. }
  580. bool JsonParser::error(const std::string &message, bool warning)
  581. {
  582. std::ostringstream stream;
  583. std::string type(warning?" warning: ":" error: ");
  584. stream << "At line " << lineCount << ", position "<<pos-lineStart
  585. << type << message <<"\n";
  586. errors += stream.str();
  587. return warning;
  588. }
  589. static const std::map<std::string, JsonNode::JsonType> stringToType =
  590. boost::assign::map_list_of
  591. ("null", JsonNode::DATA_NULL) ("bool", JsonNode::DATA_BOOL)
  592. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  593. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  594. //Check current schema entry for validness and converts "type" string to JsonType
  595. bool JsonValidator::validateSchema(JsonNode::JsonType &type, const JsonNode &schema)
  596. {
  597. if (schema.isNull())
  598. return addMessage("Missing schema for current entry!");
  599. const JsonNode &nodeType = schema["type"];
  600. if (nodeType.isNull())
  601. return addMessage("Entry type is not defined in schema!");
  602. if (nodeType.getType() != JsonNode::DATA_STRING)
  603. return addMessage("Entry type must be string!");
  604. std::map<std::string, JsonNode::JsonType>::const_iterator iter = stringToType.find(nodeType.String());
  605. if (iter == stringToType.end())
  606. return addMessage("Unknown entry type found!");
  607. type = iter->second;
  608. return true;
  609. }
  610. //Replaces node with default value if needed and calls type-specific validators
  611. bool JsonValidator::validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type)
  612. {
  613. if (node.isNull())
  614. {
  615. const JsonNode & defaultValue = schema["default"];
  616. if (defaultValue.isNull())
  617. return addMessage("Null entry without default entry!");
  618. else
  619. node = defaultValue;
  620. }
  621. if (minimize && node == schema["default"])
  622. {
  623. node.setType(JsonNode::DATA_NULL);
  624. return false;
  625. }
  626. if (type != node.getType())
  627. {
  628. node.setType(JsonNode::DATA_NULL);
  629. return addMessage("Type mismatch!");
  630. }
  631. if (type == JsonNode::DATA_VECTOR)
  632. return validateItems(node, schema["items"]);
  633. if (type == JsonNode::DATA_STRUCT)
  634. return validateProperties(node, schema["properties"]);
  635. return true;
  636. }
  637. // Basic checks common for any nodes
  638. bool JsonValidator::validateNode(JsonNode &node, const JsonNode &schema, const std::string &name)
  639. {
  640. currentPath.push_back(name);
  641. JsonNode::JsonType type = JsonNode::DATA_NULL;
  642. if (!validateSchema(type, schema)
  643. || !validateType(node, schema, type))
  644. {
  645. node.setType(JsonNode::DATA_NULL);
  646. currentPath.pop_back();
  647. return false;
  648. }
  649. currentPath.pop_back();
  650. return true;
  651. }
  652. //Checks "items" entry from schema (type-specific check for Vector)
  653. bool JsonValidator::validateItems(JsonNode &node, const JsonNode &schema)
  654. {
  655. JsonNode::JsonType type = JsonNode::DATA_NULL;
  656. if (!validateSchema(type, schema))
  657. return false;
  658. bool result = true;
  659. BOOST_FOREACH(JsonNode &entry, node.Vector())
  660. {
  661. if (!validateType(entry, schema, type))
  662. {
  663. result = false;
  664. entry.setType(JsonNode::DATA_NULL);
  665. }
  666. }
  667. return result;
  668. }
  669. //Checks "propertries" entry from schema (type-specific check for Struct)
  670. //Function is similar to merging of two sorted lists - check every entry that present in one of the input nodes
  671. bool JsonValidator::validateProperties(JsonNode &node, const JsonNode &schema)
  672. {
  673. if (schema.isNull())
  674. return addMessage("Properties entry is missing for struct in schema");
  675. JsonMap::iterator nodeIter = node.Struct().begin();
  676. JsonMap::const_iterator schemaIter = schema.Struct().begin();
  677. while (nodeIter != node.Struct().end() && schemaIter != schema.Struct().end())
  678. {
  679. if (nodeIter->first < schemaIter->first) //No schema for entry
  680. {
  681. validateNode(nodeIter->second, nullNode, nodeIter->first);
  682. JsonMap::iterator toRemove = nodeIter++;
  683. node.Struct().erase(toRemove);
  684. }
  685. else
  686. if (schemaIter->first < nodeIter->first) //No entry
  687. {
  688. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  689. node.Struct().erase(schemaIter->first);
  690. schemaIter++;
  691. }
  692. else //both entry and schema are present
  693. {
  694. JsonMap::iterator current = nodeIter++;
  695. if (!validateNode(current->second, schemaIter->second, current->first))
  696. node.Struct().erase(current);
  697. schemaIter++;
  698. }
  699. }
  700. while (nodeIter != node.Struct().end())
  701. {
  702. validateNode(nodeIter->second, nullNode, nodeIter->first);
  703. JsonMap::iterator toRemove = nodeIter++;
  704. node.Struct().erase(toRemove);
  705. }
  706. while (schemaIter != schema.Struct().end())
  707. {
  708. if (!validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first))
  709. node.Struct().erase(schemaIter->first);
  710. schemaIter++;
  711. }
  712. return true;
  713. }
  714. bool JsonValidator::addMessage(const std::string &message)
  715. {
  716. std::ostringstream stream;
  717. stream << "At ";
  718. BOOST_FOREACH(const std::string &path, currentPath)
  719. stream << path<<"/";
  720. stream << "\t Error: " << message <<"\n";
  721. errors += stream.str();
  722. return false;
  723. }
  724. JsonValidator::JsonValidator(JsonNode &root, bool Minimize):
  725. minimize(Minimize)
  726. {
  727. if (root.getType() != JsonNode::DATA_STRUCT)
  728. return;
  729. JsonNode schema;
  730. schema.swap(root["schema"]);
  731. root.Struct().erase("schema");
  732. if (!schema.isNull())
  733. {
  734. validateProperties(root, schema);
  735. }
  736. //This message is quite annoying now - most files do not have schemas. May be re-enabled later
  737. //else
  738. // addMessage("Schema not found!", true);
  739. //TODO: better way to show errors (like printing file name as well)
  740. tlog3<<errors;
  741. }
  742. JsonValidator::JsonValidator(JsonNode &root, const JsonNode &schema, bool Minimize):
  743. minimize(Minimize)
  744. {
  745. validateProperties(root, schema);
  746. if (schema.isNull())
  747. addMessage("Schema not found!");
  748. tlog3<<errors;
  749. }
  750. Bonus * JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  751. {
  752. Bonus * b = new Bonus();
  753. std::string type = ability_vec[0].String();
  754. auto it = bonusNameMap.find(type);
  755. if (it == bonusNameMap.end())
  756. {
  757. tlog1 << "Error: invalid ability type " << type << " in creatures.txt" << std::endl;
  758. return b;
  759. }
  760. b->type = it->second;
  761. b->val = ability_vec[1].Float();
  762. b->subtype = ability_vec[2].Float();
  763. b->additionalInfo = ability_vec[3].Float();
  764. b->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  765. b->turnsRemain = 0;
  766. return b;
  767. }
  768. template <typename T>
  769. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  770. {
  771. static T defaultValue;
  772. if (!val->isNull())
  773. {
  774. std::string type = val->String();
  775. auto it = map.find(type);
  776. if (it == map.end())
  777. {
  778. tlog1 << "Error: invalid " << err << type << std::endl;
  779. return defaultValue;
  780. }
  781. else
  782. {
  783. return it->second;
  784. }
  785. }
  786. else
  787. return defaultValue;
  788. };
  789. void JsonUtils::resolveIdentifier (si32 &var, const JsonNode &node, std::string name)
  790. {
  791. const JsonNode *value;
  792. value = &node[name];
  793. if (!value->isNull())
  794. {
  795. switch (value->getType())
  796. {
  797. case JsonNode::DATA_FLOAT:
  798. var = value->Float();
  799. break;
  800. case JsonNode::DATA_STRING:
  801. VLC->modh->identifiers.requestIdentifier (value->String(), [&](si32 identifier)
  802. {
  803. var = identifier;
  804. });
  805. break;
  806. default:
  807. tlog2 << "Error! Wrong indentifier used for value of " << name;
  808. }
  809. }
  810. }
  811. void JsonUtils::resolveIdentifier (const JsonNode &node, si32 &var)
  812. {
  813. switch (node.getType())
  814. {
  815. case JsonNode::DATA_FLOAT:
  816. var = node.Float();
  817. break;
  818. case JsonNode::DATA_STRING:
  819. VLC->modh->identifiers.requestIdentifier (node.String(), [&](si32 identifier)
  820. {
  821. var = identifier;
  822. });
  823. break;
  824. default:
  825. tlog2 << "Error! Wrong indentifier used for identifier!";
  826. }
  827. }
  828. Bonus * JsonUtils::parseBonus (const JsonNode &ability)
  829. {
  830. Bonus * b = new Bonus();
  831. const JsonNode *value;
  832. std::string type = ability["type"].String();
  833. auto it = bonusNameMap.find(type);
  834. if (it == bonusNameMap.end())
  835. {
  836. tlog1 << "Error: invalid ability type " << type << std::endl;
  837. return b;
  838. }
  839. b->type = it->second;
  840. resolveIdentifier (b->subtype, ability, "subtype");
  841. value = &ability["val"];
  842. if (!value->isNull())
  843. b->val = value->Float();
  844. value = &ability["valueType"];
  845. if (!value->isNull())
  846. b->valType = parseByMap(bonusValueMap, value, "value type ");
  847. value = &ability["additionalInfo"];
  848. if (!value->isNull())
  849. b->additionalInfo = value->Float();
  850. value = &ability["turns"];
  851. if (!value->isNull())
  852. b->turnsRemain = value->Float();
  853. value = &ability["sourceID"];
  854. if (!value->isNull())
  855. b->sid = value->Float();
  856. value = &ability["description"];
  857. if (!value->isNull())
  858. b->description = value->String();
  859. value = &ability["effectRange"];
  860. if (!value->isNull())
  861. b->effectRange = parseByMap(bonusLimitEffect, value, "effect range ");
  862. value = &ability["duration"];
  863. if (!value->isNull())
  864. {
  865. switch (value->getType())
  866. {
  867. case JsonNode::DATA_STRING:
  868. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  869. break;
  870. case JsonNode::DATA_VECTOR:
  871. {
  872. ui16 dur = 0;
  873. BOOST_FOREACH (const JsonNode & d, value->Vector())
  874. {
  875. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  876. }
  877. b->duration = dur;
  878. }
  879. break;
  880. default:
  881. tlog2 << "Error! Wrong bonus duration format.";
  882. }
  883. }
  884. value = &ability["source"];
  885. if (!value->isNull())
  886. b->source = parseByMap(bonusSourceMap, value, "source type ");
  887. value = &ability["limiters"];
  888. if (!value->isNull())
  889. {
  890. BOOST_FOREACH (const JsonNode & limiter, value->Vector())
  891. {
  892. switch (limiter.getType())
  893. {
  894. case JsonNode::DATA_STRING: //pre-defined limiters
  895. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  896. break;
  897. case JsonNode::DATA_STRUCT: //customizable limiters
  898. {
  899. shared_ptr<ILimiter> l;
  900. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  901. {
  902. shared_ptr<CCreatureTypeLimiter> l2 = make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  903. const JsonVector vec = limiter["parameters"].Vector();
  904. VLC->modh->identifiers.requestIdentifier(std::string("creature.") + vec[0].String(), [=](si32 creature)
  905. {
  906. l2->setCreature (creature);
  907. });
  908. if (vec.size() > 1)
  909. {
  910. l2->includeUpgrades = vec[1].Bool();
  911. }
  912. else
  913. l2->includeUpgrades = false;
  914. }
  915. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  916. {
  917. shared_ptr<HasAnotherBonusLimiter> l2 = make_shared<HasAnotherBonusLimiter>();
  918. const JsonVector vec = limiter["parameters"].Vector();
  919. std::string anotherBonusType = vec[0].String();
  920. auto it = bonusNameMap.find (anotherBonusType);
  921. if (it == bonusNameMap.end())
  922. {
  923. tlog1 << "Error: invalid ability type " << anotherBonusType << std::endl;
  924. continue;
  925. }
  926. l2->type = it->second;
  927. if (vec.size() > 1 )
  928. {
  929. resolveIdentifier (vec[1], l2->subtype);
  930. l2->isSubtypeRelevant = true;
  931. }
  932. l = l2;
  933. }
  934. b->addLimiter(l);
  935. }
  936. break;
  937. }
  938. }
  939. }
  940. value = &ability["propagator"];
  941. if (!value->isNull())
  942. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  943. return b;
  944. }
  945. //returns first Key with value equal to given one
  946. template<class Key, class Val>
  947. Key reverseMapFirst(const Val & val, const std::map<Key, Val> map)
  948. {
  949. BOOST_FOREACH(auto it, map)
  950. {
  951. if(it.second == val)
  952. {
  953. return it.first;
  954. }
  955. }
  956. assert(0);
  957. return "";
  958. }
  959. void JsonUtils::unparseBonus( JsonNode &node, const Bonus * bonus )
  960. {
  961. node["type"].String() = reverseMapFirst<std::string, int>(bonus->type, bonusNameMap);
  962. node["subtype"].Float() = bonus->subtype;
  963. node["val"].Float() = bonus->val;
  964. node["valueType"].String() = reverseMapFirst<std::string, int>(bonus->valType, bonusValueMap);
  965. node["additionalInfo"].Float() = bonus->additionalInfo;
  966. node["turns"].Float() = bonus->turnsRemain;
  967. node["sourceID"].Float() = bonus->source;
  968. node["description"].String() = bonus->description;
  969. node["effectRange"].String() = reverseMapFirst<std::string, int>(bonus->effectRange, bonusLimitEffect);
  970. node["duration"].String() = reverseMapFirst<std::string, int>(bonus->duration, bonusDurationMap);
  971. node["source"].String() = reverseMapFirst<std::string, int>(bonus->source, bonusSourceMap);
  972. if(bonus->limiter)
  973. {
  974. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  975. }
  976. if(bonus->propagator)
  977. {
  978. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  979. }
  980. }
  981. void JsonUtils::minimize(JsonNode & node, const JsonNode& schema)
  982. {
  983. JsonValidator validator(node, schema, true);
  984. }
  985. void JsonUtils::validate(JsonNode & node, const JsonNode& schema)
  986. {
  987. JsonValidator validator(node, schema, false);
  988. }
  989. void JsonUtils::merge(JsonNode & dest, JsonNode & source)
  990. {
  991. if (dest.getType() == JsonNode::DATA_NULL)
  992. {
  993. std::swap(dest, source);
  994. return;
  995. }
  996. switch (source.getType())
  997. {
  998. break; case JsonNode::DATA_NULL: dest.setType(JsonNode::DATA_NULL);
  999. break; case JsonNode::DATA_BOOL: std::swap(dest.Bool(), source.Bool());
  1000. break; case JsonNode::DATA_FLOAT: std::swap(dest.Float(), source.Float());
  1001. break; case JsonNode::DATA_STRING: std::swap(dest.String(), source.String());
  1002. break; case JsonNode::DATA_VECTOR:
  1003. {
  1004. size_t total = std::min(source.Vector().size(), dest.Vector().size());
  1005. for (size_t i=0; i< total; i++)
  1006. merge(dest.Vector()[i], source.Vector()[i]);
  1007. if (source.Vector().size() < dest.Vector().size())
  1008. {
  1009. //reserve place and *move* data from source to dest
  1010. source.Vector().reserve(source.Vector().size() + dest.Vector().size());
  1011. std::move(source.Vector().begin(), source.Vector().end(),
  1012. std::back_inserter(dest.Vector()));
  1013. }
  1014. }
  1015. break; case JsonNode::DATA_STRUCT:
  1016. {
  1017. //recursively merge all entries from struct
  1018. BOOST_FOREACH(auto & node, source.Struct())
  1019. merge(dest[node.first], node.second);
  1020. }
  1021. }
  1022. }
  1023. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source)
  1024. {
  1025. // uses copy created in stack to safely merge two nodes
  1026. merge(dest, source);
  1027. }
  1028. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  1029. {
  1030. JsonNode result;
  1031. BOOST_FOREACH(std::string file, files)
  1032. {
  1033. JsonNode section(ResourceID(file, EResType::TEXT));
  1034. merge(result, section);
  1035. }
  1036. return result;
  1037. }