2
0

JsonNode.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. #define VCMI_DLL
  2. #include "JsonNode.h"
  3. #include <boost/assign.hpp>
  4. #include <boost/foreach.hpp>
  5. #include <assert.h>
  6. #include <fstream>
  7. #include <sstream>
  8. #include <iostream>
  9. const JsonNode JsonNode::nullNode;
  10. JsonNode::JsonNode(JsonType Type):
  11. type(DATA_NULL)
  12. {
  13. setType(Type);
  14. }
  15. JsonNode::JsonNode(const char *data, size_t datasize):
  16. type(DATA_NULL)
  17. {
  18. JsonParser parser(data, datasize, *this);
  19. JsonValidator validator(*this);
  20. }
  21. JsonNode::JsonNode(std::string filename):
  22. type(DATA_NULL)
  23. {
  24. FILE * file = fopen(filename.c_str(), "rb");
  25. if (!file)
  26. return;
  27. fseek(file, 0, SEEK_END);
  28. size_t datasize = ftell(file);
  29. fseek(file, 0, SEEK_SET);
  30. char *input = new char[datasize];
  31. datasize = fread((void*)input, 1, datasize, file);
  32. fclose(file);
  33. JsonParser parser(input, datasize, *this);
  34. JsonValidator validator(*this);
  35. delete [] input;
  36. }
  37. JsonNode::JsonNode(const JsonNode &copy):
  38. type(DATA_NULL)
  39. {
  40. setType(copy.getType());
  41. switch(type)
  42. {
  43. break; case DATA_NULL:
  44. break; case DATA_BOOL: Bool() = copy.Bool();
  45. break; case DATA_FLOAT: Float() = copy.Float();
  46. break; case DATA_STRING: String() = copy.String();
  47. break; case DATA_VECTOR: Vector() = copy.Vector();
  48. break; case DATA_STRUCT: Struct() = copy.Struct();
  49. }
  50. }
  51. JsonNode::~JsonNode()
  52. {
  53. setType(DATA_NULL);
  54. }
  55. void JsonNode::swap(JsonNode &b)
  56. {
  57. using std::swap;
  58. swap(data, b.data);
  59. swap(type, b.type);
  60. }
  61. JsonNode & JsonNode::operator =(JsonNode node)
  62. {
  63. swap(node);
  64. return *this;
  65. }
  66. JsonNode::JsonType JsonNode::getType() const
  67. {
  68. return type;
  69. }
  70. void JsonNode::setType(JsonType Type)
  71. {
  72. if (type == Type)
  73. return;
  74. //Reset node to NULL
  75. if (Type != DATA_NULL)
  76. setType(DATA_NULL);
  77. switch (type)
  78. {
  79. break; case DATA_STRING: delete data.String;
  80. break; case DATA_VECTOR: delete data.Vector;
  81. break; case DATA_STRUCT: delete data.Struct;
  82. break; default:
  83. break;
  84. }
  85. //Set new node type
  86. type = Type;
  87. switch(type)
  88. {
  89. break; case DATA_NULL:
  90. break; case DATA_BOOL: data.Bool = false;
  91. break; case DATA_FLOAT: data.Float = 0;
  92. break; case DATA_STRING: data.String = new std::string;
  93. break; case DATA_VECTOR: data.Vector = new JsonVector;
  94. break; case DATA_STRUCT: data.Struct = new JsonMap;
  95. }
  96. }
  97. bool JsonNode::isNull() const
  98. {
  99. return type == DATA_NULL;
  100. }
  101. bool & JsonNode::Bool()
  102. {
  103. setType(DATA_BOOL);
  104. return data.Bool;
  105. }
  106. float & JsonNode::Float()
  107. {
  108. setType(DATA_FLOAT);
  109. return data.Float;
  110. }
  111. std::string & JsonNode::String()
  112. {
  113. setType(DATA_STRING);
  114. return *data.String;
  115. }
  116. JsonVector & JsonNode::Vector()
  117. {
  118. setType(DATA_VECTOR);
  119. return *data.Vector;
  120. }
  121. JsonMap & JsonNode::Struct()
  122. {
  123. setType(DATA_STRUCT);
  124. return *data.Struct;
  125. }
  126. const bool boolDefault = false;
  127. const bool & JsonNode::Bool() const
  128. {
  129. if (type == DATA_NULL)
  130. return boolDefault;
  131. assert(type == DATA_BOOL);
  132. return data.Bool;
  133. }
  134. const float floatDefault = 0;
  135. const float & JsonNode::Float() const
  136. {
  137. if (type == DATA_NULL)
  138. return floatDefault;
  139. assert(type == DATA_FLOAT);
  140. return data.Float;
  141. }
  142. const std::string stringDefault = std::string();
  143. const std::string & JsonNode::String() const
  144. {
  145. if (type == DATA_NULL)
  146. return stringDefault;
  147. assert(type == DATA_STRING);
  148. return *data.String;
  149. }
  150. const JsonVector vectorDefault = JsonVector();
  151. const JsonVector & JsonNode::Vector() const
  152. {
  153. if (type == DATA_NULL)
  154. return vectorDefault;
  155. assert(type == DATA_VECTOR);
  156. return *data.Vector;
  157. }
  158. const JsonMap mapDefault = JsonMap();
  159. const JsonMap & JsonNode::Struct() const
  160. {
  161. if (type == DATA_NULL)
  162. return mapDefault;
  163. assert(type == DATA_STRUCT);
  164. return *data.Struct;
  165. }
  166. JsonNode & JsonNode::operator[](std::string child)
  167. {
  168. return Struct()[child];
  169. }
  170. const JsonNode & JsonNode::operator[](std::string child) const
  171. {
  172. JsonMap::const_iterator it = Struct().find(child);
  173. if (it != Struct().end())
  174. return it->second;
  175. return nullNode;
  176. }
  177. ////////////////////////////////////////////////////////////////////////////////
  178. template<typename Iterator>
  179. void JsonWriter::writeContainer(Iterator begin, Iterator end)
  180. {
  181. if (begin == end)
  182. return;
  183. prefix += '\t';
  184. end--;
  185. while (begin != end)
  186. {
  187. writeEntry(begin++);
  188. out<<",\n";
  189. }
  190. writeEntry(begin);
  191. out<<"\n";
  192. prefix.resize(prefix.size()-1);
  193. }
  194. void JsonWriter::writeEntry(JsonMap::const_iterator entry)
  195. {
  196. out << prefix;
  197. writeString(entry->first);
  198. out << " : ";
  199. writeNode(entry->second);
  200. }
  201. void JsonWriter::writeEntry(JsonVector::const_iterator entry)
  202. {
  203. out << prefix;
  204. writeNode(*entry);
  205. }
  206. void JsonWriter::writeString(const std::string &string)
  207. {
  208. static const std::string escaped = "\"\\/\b\f\n\r\t";
  209. out <<'\"';
  210. size_t pos=0, start=0;
  211. for (; pos<string.size(); pos++)
  212. {
  213. size_t escapedChar = escaped.find(string[pos]);
  214. if (escapedChar != std::string::npos)
  215. {
  216. out.write(string.data()+start, pos - start);
  217. out << '\\' << escaped[escapedChar];
  218. start = pos;
  219. }
  220. }
  221. out.write(string.data()+start, pos - start);
  222. out <<'\"';
  223. }
  224. void JsonWriter::writeNode(const JsonNode &node)
  225. {
  226. switch(node.getType())
  227. {
  228. break; case JsonNode::DATA_NULL:
  229. out << "null";
  230. break; case JsonNode::DATA_BOOL:
  231. if (node.Bool())
  232. out << "true";
  233. else
  234. out << "false";
  235. break; case JsonNode::DATA_FLOAT:
  236. out << node.Float();
  237. break; case JsonNode::DATA_STRING:
  238. writeString(node.String());
  239. break; case JsonNode::DATA_VECTOR:
  240. out << "[" << "\n";
  241. writeContainer(node.Vector().begin(), node.Vector().end());
  242. out << prefix << "]";
  243. break; case JsonNode::DATA_STRUCT:
  244. out << "{" << "\n";
  245. writeContainer(node.Struct().begin(), node.Struct().end());
  246. out << prefix << "}";
  247. }
  248. }
  249. JsonWriter::JsonWriter(std::ostream &output, const JsonNode &node):
  250. out(output)
  251. {
  252. writeNode(node);
  253. }
  254. std::ostream & operator<<(std::ostream &out, const JsonNode &node)
  255. {
  256. JsonWriter(out, node);
  257. return out << "\n";
  258. }
  259. ////////////////////////////////////////////////////////////////////////////////
  260. JsonParser::JsonParser(const char * inputString, size_t stringSize, JsonNode &root):
  261. input(inputString, stringSize),
  262. lineCount(1),
  263. lineStart(0),
  264. pos(0)
  265. {
  266. extractValue(root);
  267. extractWhitespace(false);
  268. //Warn if there are any non-whitespace symbols left
  269. if (pos < input.size())
  270. error("Not all file was parsed!", true);
  271. //TODO: better way to show errors (like printing file name as well)
  272. tlog3<<errors;
  273. }
  274. bool JsonParser::extractSeparator()
  275. {
  276. if (!extractWhitespace())
  277. return false;
  278. if ( input[pos] !=':')
  279. return error("Separator expected");
  280. pos++;
  281. return true;
  282. }
  283. bool JsonParser::extractValue(JsonNode &node)
  284. {
  285. if (!extractWhitespace())
  286. return false;
  287. switch (input[pos])
  288. {
  289. case '\"': return extractString(node);
  290. case 'n' : return extractNull(node);
  291. case 't' : return extractTrue(node);
  292. case 'f' : return extractFalse(node);
  293. case '{' : return extractStruct(node);
  294. case '[' : return extractArray(node);
  295. case '-' : return extractFloat(node);
  296. default:
  297. {
  298. if (input[pos] >= '0' && input[pos] <= '9')
  299. return extractFloat(node);
  300. return error("Value expected!");
  301. }
  302. }
  303. }
  304. bool JsonParser::extractWhitespace(bool verbose)
  305. {
  306. while (true)
  307. {
  308. while (pos < input.size() && (unsigned char)input[pos] <= ' ')
  309. {
  310. if (input[pos] == '\n')
  311. {
  312. lineCount++;
  313. lineStart = pos+1;
  314. }
  315. pos++;
  316. }
  317. if (pos >= input.size() || input[pos] != '/')
  318. break;
  319. pos++;
  320. if (pos == input.size())
  321. break;
  322. if (input[pos] == '/')
  323. pos++;
  324. else
  325. error("Comments must consist from two slashes!", true);
  326. while (pos < input.size() && input[pos] != '\n')
  327. pos++;
  328. }
  329. if (pos >= input.size() && verbose)
  330. return error("Unexpected end of file!");
  331. return true;
  332. }
  333. bool JsonParser::extractEscaping(std::string &str)
  334. {
  335. switch(input[pos++])
  336. {
  337. break; case '\"': str += '\"';
  338. break; case '\\': str += '\\';
  339. break; case '/': str += '/';
  340. break; case '\b': str += '\b';
  341. break; case '\f': str += '\f';
  342. break; case '\n': str += '\n';
  343. break; case '\r': str += '\r';
  344. break; case '\t': str += '\t';
  345. break; default: return error("Unknown escape sequence!", true);
  346. };
  347. return true;
  348. }
  349. bool JsonParser::extractString(std::string &str)
  350. {
  351. if (input[pos] != '\"')
  352. return error("String expected!");
  353. pos++;
  354. size_t first = pos;
  355. while (pos != input.size())
  356. {
  357. if (input[pos] == '\"') // Correct end of string
  358. {
  359. str.append( &input[first], pos-first);
  360. pos++;
  361. return true;
  362. }
  363. if (input[pos] == '\\') // Escaping
  364. {
  365. str.append( &input[first], pos-first);
  366. first = pos++;
  367. if (pos == input.size())
  368. break;
  369. extractEscaping(str);
  370. }
  371. if (input[pos] == '\n') // end-of-line
  372. {
  373. str.append( &input[first], pos-first);
  374. return error("Closing quote not found!", true);
  375. }
  376. if (input[pos] < ' ') // control character
  377. {
  378. str.append( &input[first], pos-first);
  379. first = pos+1;
  380. error("Illegal character in the string!", true);
  381. }
  382. pos++;
  383. }
  384. return error("Unterminated string!");
  385. }
  386. bool JsonParser::extractString(JsonNode &node)
  387. {
  388. std::string str;
  389. if (!extractString(str))
  390. return false;
  391. node.setType(JsonNode::DATA_STRING);
  392. node.String() = str;
  393. return true;
  394. }
  395. bool JsonParser::extractLiteral(const std::string &literal)
  396. {
  397. if (literal.compare(0, literal.size(), &input[pos], literal.size()) != 0)
  398. {
  399. while (pos < input.size() && ((input[pos]>'a' && input[pos]<'z')
  400. || (input[pos]>'A' && input[pos]<'Z')))
  401. pos++;
  402. return error("Unknown literal found", true);
  403. }
  404. pos += literal.size();
  405. return true;
  406. }
  407. bool JsonParser::extractNull(JsonNode &node)
  408. {
  409. if (!extractLiteral("null"))
  410. return false;
  411. node.setType(JsonNode::DATA_NULL);
  412. return true;
  413. }
  414. bool JsonParser::extractTrue(JsonNode &node)
  415. {
  416. if (!extractLiteral("true"))
  417. return false;
  418. node.Bool() = true;
  419. return true;
  420. }
  421. bool JsonParser::extractFalse(JsonNode &node)
  422. {
  423. if (!extractLiteral("false"))
  424. return false;
  425. node.Bool() = false;
  426. return true;
  427. }
  428. bool JsonParser::extractStruct(JsonNode &node)
  429. {
  430. node.setType(JsonNode::DATA_STRUCT);
  431. pos++;
  432. if (!extractWhitespace())
  433. return false;
  434. //Empty struct found
  435. if (input[pos] == '}')
  436. {
  437. pos++;
  438. return true;
  439. }
  440. while (true)
  441. {
  442. if (!extractWhitespace())
  443. return false;
  444. std::string key;
  445. if (!extractString(key))
  446. return false;
  447. if (node.Struct().find(key) != node.Struct().end())
  448. error("Dublicated element encountered!", true);
  449. if (!extractSeparator())
  450. return false;
  451. if (!extractElement(node.Struct()[key], '}'))
  452. return false;
  453. if (input[pos] == '}')
  454. {
  455. pos++;
  456. return true;
  457. }
  458. }
  459. }
  460. bool JsonParser::extractArray(JsonNode &node)
  461. {
  462. pos++;
  463. node.setType(JsonNode::DATA_VECTOR);
  464. if (!extractWhitespace())
  465. return false;
  466. //Empty array found
  467. if (input[pos] == ']')
  468. {
  469. pos++;
  470. return true;
  471. }
  472. while (true)
  473. {
  474. //NOTE: currently 50% of time is this vector resizing.
  475. //May be useful to use list during parsing and then swap() all items to vector
  476. node.Vector().resize(node.Vector().size()+1);
  477. if (!extractElement(node.Vector().back(), ']'))
  478. return false;
  479. if (input[pos] == ']')
  480. {
  481. pos++;
  482. return true;
  483. }
  484. }
  485. }
  486. bool JsonParser::extractElement(JsonNode &node, char terminator)
  487. {
  488. if (!extractValue(node))
  489. return false;
  490. if (!extractWhitespace())
  491. return false;
  492. bool comma = (input[pos] == ',');
  493. if (comma )
  494. {
  495. pos++;
  496. if (!extractWhitespace())
  497. return false;
  498. }
  499. if (input[pos] == terminator)
  500. return true;
  501. if (!comma)
  502. error("Comma expected!", true);
  503. return true;
  504. }
  505. bool JsonParser::extractFloat(JsonNode &node)
  506. {
  507. assert(input[pos] == '-' || (input[pos] >= '0' && input[pos] <= '9'));
  508. bool negative=false;
  509. float result=0;
  510. if (input[pos] == '-')
  511. {
  512. pos++;
  513. negative = true;
  514. }
  515. if (input[pos] < '0' || input[pos] > '9')
  516. return error("Number expected!");
  517. //Extract integer part
  518. while (input[pos] >= '0' && input[pos] <= '9')
  519. {
  520. result = result*10+(input[pos]-'0');
  521. pos++;
  522. }
  523. if (input[pos] == '.')
  524. {
  525. //extract fractional part
  526. pos++;
  527. float fractMult = 0.1;
  528. if (input[pos] < '0' || input[pos] > '9')
  529. return error("Decimal part expected!");
  530. while (input[pos] >= '0' && input[pos] <= '9')
  531. {
  532. result = result + fractMult*(input[pos]-'0');
  533. fractMult /= 10;
  534. pos++;
  535. }
  536. }
  537. //TODO: exponential part
  538. if (negative)
  539. result = -result;
  540. node.setType(JsonNode::DATA_FLOAT);
  541. node.Float() = result;
  542. return true;
  543. }
  544. bool JsonParser::error(const std::string &message, bool warning)
  545. {
  546. std::ostringstream stream;
  547. std::string type(warning?" warning: ":" error: ");
  548. stream << "At line " << lineCount << ", position "<<pos-lineStart
  549. << type << message <<"\n";
  550. errors += stream.str();
  551. return warning;
  552. }
  553. static const std::map<std::string, JsonNode::JsonType> stringToType =
  554. boost::assign::map_list_of
  555. ("null", JsonNode::DATA_NULL) ("bool", JsonNode::DATA_BOOL)
  556. ("number", JsonNode::DATA_FLOAT) ("string", JsonNode::DATA_STRING)
  557. ("array", JsonNode::DATA_VECTOR) ("object", JsonNode::DATA_STRUCT);
  558. //Check current schema entry for validness and converts "type" string to JsonType
  559. bool JsonValidator::validateSchema(JsonNode::JsonType &type, const JsonNode &schema)
  560. {
  561. if (schema.isNull())
  562. return addMessage("Missing schema for current entry!");
  563. const JsonNode &nodeType = schema["type"];
  564. if (nodeType.isNull())
  565. return addMessage("Entry type is not defined in schema!");
  566. if (nodeType.getType() != JsonNode::DATA_STRING)
  567. return addMessage("Entry type must be string!");
  568. std::map<std::string, JsonNode::JsonType>::const_iterator iter = stringToType.find(nodeType.String());
  569. if (iter == stringToType.end())
  570. return addMessage("Unknown entry type found!");
  571. type = iter->second;
  572. return true;
  573. }
  574. //Replaces node with default value if needed and calls type-specific validators
  575. bool JsonValidator::validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type)
  576. {
  577. if (node.isNull())
  578. {
  579. const JsonNode & defaultValue = schema["default"];
  580. if (defaultValue.isNull())
  581. return addMessage("Null entry without default entry!");
  582. else
  583. node = defaultValue;
  584. }
  585. if (type != node.getType())
  586. {
  587. node.setType(JsonNode::DATA_NULL);
  588. return addMessage("Type mismatch!");
  589. }
  590. if (type == JsonNode::DATA_VECTOR)
  591. return validateItems(node, schema["items"]);
  592. if (type == JsonNode::DATA_STRUCT)
  593. return validateProperties(node, schema["properties"]);
  594. return true;
  595. }
  596. // Basic checks common for any nodes
  597. bool JsonValidator::validateNode(JsonNode &node, const JsonNode &schema, const std::string &name)
  598. {
  599. currentPath.push_back(name);
  600. JsonNode::JsonType type = JsonNode::DATA_NULL;
  601. if (!validateSchema(type, schema))
  602. {
  603. currentPath.pop_back();
  604. return false;
  605. }
  606. if (!validateType(node, schema, type))
  607. {
  608. currentPath.pop_back();
  609. return false;
  610. }
  611. currentPath.pop_back();
  612. return true;
  613. }
  614. //Checks "items" entry from schema (type-specific check for Vector)
  615. bool JsonValidator::validateItems(JsonNode &node, const JsonNode &schema)
  616. {
  617. JsonNode::JsonType type = JsonNode::DATA_NULL;
  618. if (!validateSchema(type, schema))
  619. return false;
  620. BOOST_FOREACH(JsonNode &entry, node.Vector())
  621. {
  622. if (!validateType(entry, schema, type))
  623. return false;
  624. }
  625. return true;
  626. }
  627. //Checks "propertries" entry from schema (type-specific check for Struct)
  628. //Function is similar to merging of two sorted lists - check every entry that present in one of the input nodes
  629. bool JsonValidator::validateProperties(JsonNode &node, const JsonNode &schema)
  630. {
  631. if (schema.isNull())
  632. return addMessage("Properties entry is missing for struct in schema");
  633. JsonMap::iterator nodeIter = node.Struct().begin();
  634. JsonMap::const_iterator schemaIter = schema.Struct().begin();
  635. while (nodeIter != node.Struct().end() && schemaIter != schema.Struct().end())
  636. {
  637. std::string current = std::min(nodeIter->first, schemaIter->first);
  638. validateNode(node[current], schema[current], current);
  639. if (nodeIter->first < schemaIter->first)
  640. nodeIter++;
  641. else
  642. if (schemaIter->first < nodeIter->first)
  643. schemaIter++;
  644. else
  645. {
  646. nodeIter++;
  647. schemaIter++;
  648. }
  649. }
  650. while (nodeIter != node.Struct().end())
  651. {
  652. validateNode(nodeIter->second, JsonNode(), nodeIter->first);
  653. nodeIter++;
  654. }
  655. while (schemaIter != schema.Struct().end())
  656. {
  657. validateNode(node[schemaIter->first], schemaIter->second, schemaIter->first);
  658. schemaIter++;
  659. }
  660. return true;
  661. }
  662. bool JsonValidator::addMessage(const std::string &message)
  663. {
  664. std::ostringstream stream;
  665. stream << "At ";
  666. BOOST_FOREACH(const std::string &path, currentPath)
  667. stream << path<<"/";
  668. stream << "\t Error: " << message <<"\n";
  669. errors += stream.str();
  670. return false;
  671. }
  672. JsonValidator::JsonValidator(JsonNode &root)
  673. {
  674. JsonNode schema;
  675. schema.swap(root["schema"]);
  676. if (!schema.isNull())
  677. {
  678. root.Struct().erase("schema");
  679. validateProperties(root, schema);
  680. }
  681. //This message is quite annoying now - most files do not have schemas. May be re-enabled later
  682. //else
  683. // addMessage("Schema not found!", true);
  684. //TODO: better way to show errors (like printing file name as well)
  685. tlog3<<errors;
  686. }