JsonNode.cpp 16 KB

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