JsonParser.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * JsonParser.h, 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. #pragma once
  11. #include "JsonNode.h"
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. //Tiny string class that uses const char* as data for speed, members are private
  14. //for ease of debugging and some compatibility with std::string
  15. class constString
  16. {
  17. const char *data;
  18. const size_t datasize;
  19. public:
  20. constString(const char * inputString, size_t stringSize):
  21. data(inputString),
  22. datasize(stringSize)
  23. {
  24. }
  25. inline size_t size() const
  26. {
  27. return datasize;
  28. };
  29. inline const char& operator[] (size_t position)
  30. {
  31. assert (position < datasize);
  32. return data[position];
  33. }
  34. };
  35. //Internal class for string -> JsonNode conversion
  36. class JsonParser
  37. {
  38. std::string errors; // Contains description of all encountered errors
  39. constString input; // Input data
  40. ui32 lineCount; // Currently parsed line, starting from 1
  41. size_t lineStart; // Position of current line start
  42. size_t pos; // Current position of parser
  43. //Helpers
  44. bool extractEscaping(std::string &str);
  45. bool extractLiteral(const std::string &literal);
  46. bool extractString(std::string &string);
  47. bool extractWhitespace(bool verbose = true);
  48. bool extractSeparator();
  49. bool extractElement(JsonNode &node, char terminator);
  50. //Methods for extracting JSON data
  51. bool extractArray(JsonNode &node);
  52. bool extractFalse(JsonNode &node);
  53. bool extractFloat(JsonNode &node);
  54. bool extractNull(JsonNode &node);
  55. bool extractString(JsonNode &node);
  56. bool extractStruct(JsonNode &node);
  57. bool extractTrue(JsonNode &node);
  58. bool extractValue(JsonNode &node);
  59. //Add error\warning message to list
  60. bool error(const std::string &message, bool warning=false);
  61. public:
  62. JsonParser(const char * inputString, size_t stringSize);
  63. /// do actual parsing. filename is name of file that will printed to console if any errors were found
  64. JsonNode parse(const std::string & fileName);
  65. /// returns true if parsing was successful
  66. bool isValid();
  67. };
  68. VCMI_LIB_NAMESPACE_END