JsonNode.cpp 17 KB

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