You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2415 lines
56 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
7 years ago
​
7 years ago
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
7 years ago
​
​
7 years ago
​
​
​
​
7 years ago
​
7 years ago
​
7 years ago
​
7 years ago
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
7 years ago
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
  1. // Copyright 2007-2011 Baptiste Lepilleur and The JsonCpp Authors
  2. // Copyright (C) 2016 InfoTeCS JSC. All rights reserved.
  3. // Distributed under MIT license, or public domain if desired and
  4. // recognized in your jurisdiction.
  5. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  6. #if ! defined(JSON_IS_AMALGAMATION)
  7. #include "json_tool.h"
  8. #include <json/assertions.h>
  9. #include <json/reader.h>
  10. #include <json/value.h>
  11. #endif // if !defined(JSON_IS_AMALGAMATION)
  12. #include <cassert>
  13. #include <cstdio>
  14. #include <cstring>
  15. #include <istream>
  16. #include <limits>
  17. #include <memory>
  18. #include <set>
  19. #include <sstream>
  20. #include <utility>
  21. #if __cplusplus >= 201103L
  22. #if ! defined(sscanf)
  23. #define sscanf std::sscanf
  24. #endif
  25. #endif //__cplusplus
  26. #if defined(_MSC_VER)
  27. #if ! defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
  28. #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
  29. #endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
  30. #endif //_MSC_VER
  31. #if defined(_MSC_VER)
  32. // Disable warning about strdup being deprecated.
  33. #pragma warning(disable : 4996)
  34. #endif
  35. // Define JSONCPP_DEPRECATED_STACK_LIMIT as an appropriate integer at compile
  36. // time to change the stack limit
  37. #if ! defined(JSONCPP_DEPRECATED_STACK_LIMIT)
  38. #define JSONCPP_DEPRECATED_STACK_LIMIT 1000
  39. #endif
  40. static const size_t stackLimit_g = JSONCPP_DEPRECATED_STACK_LIMIT; // see readValue()
  41. namespace Json
  42. {
  43. #if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
  44. typedef std::unique_ptr<CharReader> CharReaderPtr;
  45. #else
  46. typedef std::auto_ptr<CharReader> CharReaderPtr;
  47. #endif
  48. // Implementation of class Features
  49. // ////////////////////////////////
  50. Features::Features() = default;
  51. Features Features::all()
  52. {
  53. return {};
  54. }
  55. Features Features::strictMode()
  56. {
  57. Features features;
  58. features.allowComments_ = false;
  59. features.strictRoot_ = true;
  60. features.allowDroppedNullPlaceholders_ = false;
  61. features.allowNumericKeys_ = false;
  62. return features;
  63. }
  64. // Implementation of class Reader
  65. // ////////////////////////////////
  66. bool Reader::containsNewLine(Reader::Location begin, Reader::Location end)
  67. {
  68. for (; begin < end; ++begin)
  69. {
  70. if (*begin == '\n' || *begin == '\r')
  71. {
  72. return true;
  73. }
  74. }
  75. return false;
  76. }
  77. // Class Reader
  78. // //////////////////////////////////////////////////////////////////
  79. Reader::Reader() :
  80. errors_(),
  81. document_(),
  82. commentsBefore_(),
  83. features_(Features::all())
  84. {
  85. }
  86. Reader::Reader(const Features & features) :
  87. errors_(),
  88. document_(),
  89. begin_(),
  90. end_(),
  91. current_(),
  92. lastValueEnd_(),
  93. lastValue_(),
  94. commentsBefore_(),
  95. features_(features),
  96. collectComments_()
  97. {
  98. }
  99. bool Reader::parse(const std::string & document, Value & root, bool collectComments)
  100. {
  101. document_.assign(document.begin(), document.end());
  102. const char * begin = document_.c_str();
  103. const char * end = begin + document_.length();
  104. return parse(begin, end, root, collectComments);
  105. }
  106. bool Reader::parse(std::istream & is, Value & root, bool collectComments)
  107. {
  108. // std::istream_iterator<char> begin(is);
  109. // std::istream_iterator<char> end;
  110. // Those would allow streamed input from a file, if parse() were a
  111. // template function.
  112. // Since String is reference-counted, this at least does not
  113. // create an extra copy.
  114. String doc;
  115. std::getline(is, doc, (char) EOF);
  116. return parse(doc.data(), doc.data() + doc.size(), root, collectComments);
  117. }
  118. bool Reader::parse(const char * beginDoc, const char * endDoc, Value & root, bool collectComments)
  119. {
  120. if (! features_.allowComments_)
  121. {
  122. collectComments = false;
  123. }
  124. begin_ = beginDoc;
  125. end_ = endDoc;
  126. collectComments_ = collectComments;
  127. current_ = begin_;
  128. lastValueEnd_ = nullptr;
  129. lastValue_ = nullptr;
  130. commentsBefore_.clear();
  131. errors_.clear();
  132. while (! nodes_.empty())
  133. {
  134. nodes_.pop();
  135. }
  136. nodes_.push(&root);
  137. bool successful = readValue();
  138. Token token;
  139. skipCommentTokens(token);
  140. if (collectComments_ && ! commentsBefore_.empty())
  141. {
  142. root.setComment(commentsBefore_, commentAfter);
  143. }
  144. if (features_.strictRoot_)
  145. {
  146. if (! root.isArray() && ! root.isObject())
  147. {
  148. // Set error location to start of doc, ideally should be first token found
  149. // in doc
  150. token.type_ = tokenError;
  151. token.start_ = beginDoc;
  152. token.end_ = endDoc;
  153. addError("A valid JSON document must be either an array or an object value.", token);
  154. return false;
  155. }
  156. }
  157. return successful;
  158. }
  159. bool Reader::readValue()
  160. {
  161. // readValue() may call itself only if it calls readObject() or ReadArray().
  162. // These methods execute nodes_.push() just before and nodes_.pop)() just
  163. // after calling readValue(). parse() executes one nodes_.push(), so > instead
  164. // of >=.
  165. if (nodes_.size() > stackLimit_g)
  166. {
  167. throwRuntimeError("Exceeded stackLimit in readValue().");
  168. }
  169. Token token;
  170. skipCommentTokens(token);
  171. bool successful = true;
  172. if (collectComments_ && ! commentsBefore_.empty())
  173. {
  174. currentValue().setComment(commentsBefore_, commentBefore);
  175. commentsBefore_.clear();
  176. }
  177. switch (token.type_)
  178. {
  179. case tokenObjectBegin:
  180. successful = readObject(token);
  181. currentValue().setOffsetLimit(current_ - begin_);
  182. break;
  183. case tokenArrayBegin:
  184. successful = readArray(token);
  185. currentValue().setOffsetLimit(current_ - begin_);
  186. break;
  187. case tokenNumber: successful = decodeNumber(token); break;
  188. case tokenString: successful = decodeString(token); break;
  189. case tokenTrue:
  190. {
  191. Value v(true);
  192. currentValue().swapPayload(v);
  193. currentValue().setOffsetStart(token.start_ - begin_);
  194. currentValue().setOffsetLimit(token.end_ - begin_);
  195. }
  196. break;
  197. case tokenFalse:
  198. {
  199. Value v(false);
  200. currentValue().swapPayload(v);
  201. currentValue().setOffsetStart(token.start_ - begin_);
  202. currentValue().setOffsetLimit(token.end_ - begin_);
  203. }
  204. break;
  205. case tokenNull:
  206. {
  207. Value v;
  208. currentValue().swapPayload(v);
  209. currentValue().setOffsetStart(token.start_ - begin_);
  210. currentValue().setOffsetLimit(token.end_ - begin_);
  211. }
  212. break;
  213. case tokenArraySeparator:
  214. case tokenObjectEnd:
  215. case tokenArrayEnd:
  216. if (features_.allowDroppedNullPlaceholders_)
  217. {
  218. // "Un-read" the current token and mark the current value as a null
  219. // token.
  220. current_--;
  221. Value v;
  222. currentValue().swapPayload(v);
  223. currentValue().setOffsetStart(current_ - begin_ - 1);
  224. currentValue().setOffsetLimit(current_ - begin_);
  225. break;
  226. } // Else, fall through...
  227. default:
  228. currentValue().setOffsetStart(token.start_ - begin_);
  229. currentValue().setOffsetLimit(token.end_ - begin_);
  230. return addError("Syntax error: value, object or array expected.", token);
  231. }
  232. if (collectComments_)
  233. {
  234. lastValueEnd_ = current_;
  235. lastValue_ = &currentValue();
  236. }
  237. return successful;
  238. }
  239. void Reader::skipCommentTokens(Token & token)
  240. {
  241. if (features_.allowComments_)
  242. {
  243. do
  244. {
  245. readToken(token);
  246. }
  247. while (token.type_ == tokenComment);
  248. }
  249. else
  250. {
  251. readToken(token);
  252. }
  253. }
  254. bool Reader::readToken(Token & token)
  255. {
  256. skipSpaces();
  257. token.start_ = current_;
  258. Char c = getNextChar();
  259. bool ok = true;
  260. switch (c)
  261. {
  262. case '{': token.type_ = tokenObjectBegin; break;
  263. case '}': token.type_ = tokenObjectEnd; break;
  264. case '[': token.type_ = tokenArrayBegin; break;
  265. case ']': token.type_ = tokenArrayEnd; break;
  266. case '"':
  267. token.type_ = tokenString;
  268. ok = readString();
  269. break;
  270. case '/':
  271. token.type_ = tokenComment;
  272. ok = readComment();
  273. break;
  274. case '0':
  275. case '1':
  276. case '2':
  277. case '3':
  278. case '4':
  279. case '5':
  280. case '6':
  281. case '7':
  282. case '8':
  283. case '9':
  284. case '-':
  285. token.type_ = tokenNumber;
  286. readNumber();
  287. break;
  288. case 't':
  289. token.type_ = tokenTrue;
  290. ok = match("rue", 3);
  291. break;
  292. case 'f':
  293. token.type_ = tokenFalse;
  294. ok = match("alse", 4);
  295. break;
  296. case 'n':
  297. token.type_ = tokenNull;
  298. ok = match("ull", 3);
  299. break;
  300. case ',': token.type_ = tokenArraySeparator; break;
  301. case ':': token.type_ = tokenMemberSeparator; break;
  302. case 0 : token.type_ = tokenEndOfStream; break;
  303. default : ok = false; break;
  304. }
  305. if (! ok)
  306. {
  307. token.type_ = tokenError;
  308. }
  309. token.end_ = current_;
  310. return true;
  311. }
  312. void Reader::skipSpaces()
  313. {
  314. while (current_ != end_)
  315. {
  316. Char c = *current_;
  317. if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
  318. {
  319. ++current_;
  320. }
  321. else
  322. {
  323. break;
  324. }
  325. }
  326. }
  327. bool Reader::match(Location pattern, int patternLength)
  328. {
  329. if (end_ - current_ < patternLength)
  330. {
  331. return false;
  332. }
  333. int index = patternLength;
  334. while (index--)
  335. {
  336. if (current_[index] != pattern[index])
  337. {
  338. return false;
  339. }
  340. }
  341. current_ += patternLength;
  342. return true;
  343. }
  344. bool Reader::readComment()
  345. {
  346. Location commentBegin = current_ - 1;
  347. Char c = getNextChar();
  348. bool successful = false;
  349. if (c == '*')
  350. {
  351. successful = readCStyleComment();
  352. }
  353. else if (c == '/')
  354. {
  355. successful = readCppStyleComment();
  356. }
  357. if (! successful)
  358. {
  359. return false;
  360. }
  361. if (collectComments_)
  362. {
  363. CommentPlacement placement = commentBefore;
  364. if (lastValueEnd_ && ! containsNewLine(lastValueEnd_, commentBegin))
  365. {
  366. if (c != '*' || ! containsNewLine(commentBegin, current_))
  367. {
  368. placement = commentAfterOnSameLine;
  369. }
  370. }
  371. addComment(commentBegin, current_, placement);
  372. }
  373. return true;
  374. }
  375. String Reader::normalizeEOL(Reader::Location begin, Reader::Location end)
  376. {
  377. String normalized;
  378. normalized.reserve(static_cast<size_t>(end - begin));
  379. Reader::Location current = begin;
  380. while (current != end)
  381. {
  382. char c = *current++;
  383. if (c == '\r')
  384. {
  385. if (current != end && *current == '\n')
  386. {
  387. // convert dos EOL
  388. ++current;
  389. }
  390. // convert Mac EOL
  391. normalized += '\n';
  392. }
  393. else
  394. {
  395. normalized += c;
  396. }
  397. }
  398. return normalized;
  399. }
  400. void Reader::addComment(Location begin, Location end, CommentPlacement placement)
  401. {
  402. assert(collectComments_);
  403. const String & normalized = normalizeEOL(begin, end);
  404. if (placement == commentAfterOnSameLine)
  405. {
  406. assert(lastValue_ != nullptr);
  407. lastValue_->setComment(normalized, placement);
  408. }
  409. else
  410. {
  411. commentsBefore_ += normalized;
  412. }
  413. }
  414. bool Reader::readCStyleComment()
  415. {
  416. while ((current_ + 1) < end_)
  417. {
  418. Char c = getNextChar();
  419. if (c == '*' && *current_ == '/')
  420. {
  421. break;
  422. }
  423. }
  424. return getNextChar() == '/';
  425. }
  426. bool Reader::readCppStyleComment()
  427. {
  428. while (current_ != end_)
  429. {
  430. Char c = getNextChar();
  431. if (c == '\n')
  432. {
  433. break;
  434. }
  435. if (c == '\r')
  436. {
  437. // Consume DOS EOL. It will be normalized in addComment.
  438. if (current_ != end_ && *current_ == '\n')
  439. {
  440. getNextChar();
  441. }
  442. // Break on Moc OS 9 EOL.
  443. break;
  444. }
  445. }
  446. return true;
  447. }
  448. void Reader::readNumber()
  449. {
  450. const char * p = current_;
  451. char c = '0'; // stopgap for already consumed character
  452. // integral part
  453. while (c >= '0' && c <= '9')
  454. {
  455. c = (current_ = p) < end_ ? *p++ : '\0';
  456. }
  457. // fractional part
  458. if (c == '.')
  459. {
  460. c = (current_ = p) < end_ ? *p++ : '\0';
  461. while (c >= '0' && c <= '9')
  462. {
  463. c = (current_ = p) < end_ ? *p++ : '\0';
  464. }
  465. }
  466. // exponential part
  467. if (c == 'e' || c == 'E')
  468. {
  469. c = (current_ = p) < end_ ? *p++ : '\0';
  470. if (c == '+' || c == '-')
  471. {
  472. c = (current_ = p) < end_ ? *p++ : '\0';
  473. }
  474. while (c >= '0' && c <= '9')
  475. {
  476. c = (current_ = p) < end_ ? *p++ : '\0';
  477. }
  478. }
  479. }
  480. bool Reader::readString()
  481. {
  482. Char c = '\0';
  483. while (current_ != end_)
  484. {
  485. c = getNextChar();
  486. if (c == '\\')
  487. {
  488. getNextChar();
  489. }
  490. else if (c == '"')
  491. {
  492. break;
  493. }
  494. }
  495. return c == '"';
  496. }
  497. bool Reader::readObject(Token & token)
  498. {
  499. Token tokenName;
  500. String name;
  501. Value init(objectValue);
  502. currentValue().swapPayload(init);
  503. currentValue().setOffsetStart(token.start_ - begin_);
  504. while (readToken(tokenName))
  505. {
  506. bool initialTokenOk = true;
  507. while (tokenName.type_ == tokenComment && initialTokenOk)
  508. {
  509. initialTokenOk = readToken(tokenName);
  510. }
  511. if (! initialTokenOk)
  512. {
  513. break;
  514. }
  515. if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
  516. {
  517. return true;
  518. }
  519. name.clear();
  520. if (tokenName.type_ == tokenString)
  521. {
  522. if (! decodeString(tokenName, name))
  523. {
  524. return recoverFromError(tokenObjectEnd);
  525. }
  526. }
  527. else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_)
  528. {
  529. Value numberName;
  530. if (! decodeNumber(tokenName, numberName))
  531. {
  532. return recoverFromError(tokenObjectEnd);
  533. }
  534. name = String(numberName.asCString());
  535. }
  536. else
  537. {
  538. break;
  539. }
  540. Token colon;
  541. if (! readToken(colon) || colon.type_ != tokenMemberSeparator)
  542. {
  543. return addErrorAndRecover("Missing ':' after object member name", colon, tokenObjectEnd);
  544. }
  545. Value & value = currentValue()[name];
  546. nodes_.push(&value);
  547. bool ok = readValue();
  548. nodes_.pop();
  549. if (! ok) // error already set
  550. {
  551. return recoverFromError(tokenObjectEnd);
  552. }
  553. Token comma;
  554. if (! readToken(comma) || (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment))
  555. {
  556. return addErrorAndRecover("Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
  557. }
  558. bool finalizeTokenOk = true;
  559. while (comma.type_ == tokenComment && finalizeTokenOk)
  560. {
  561. finalizeTokenOk = readToken(comma);
  562. }
  563. if (comma.type_ == tokenObjectEnd)
  564. {
  565. return true;
  566. }
  567. }
  568. return addErrorAndRecover("Missing '}' or object member name", tokenName, tokenObjectEnd);
  569. }
  570. bool Reader::readArray(Token & token)
  571. {
  572. Value init(arrayValue);
  573. currentValue().swapPayload(init);
  574. currentValue().setOffsetStart(token.start_ - begin_);
  575. skipSpaces();
  576. if (current_ != end_ && *current_ == ']') // empty array
  577. {
  578. Token endArray;
  579. readToken(endArray);
  580. return true;
  581. }
  582. int index = 0;
  583. for (;;)
  584. {
  585. Value & value = currentValue()[index++];
  586. nodes_.push(&value);
  587. bool ok = readValue();
  588. nodes_.pop();
  589. if (! ok) // error already set
  590. {
  591. return recoverFromError(tokenArrayEnd);
  592. }
  593. Token currentToken;
  594. // Accept Comment after last item in the array.
  595. ok = readToken(currentToken);
  596. while (currentToken.type_ == tokenComment && ok)
  597. {
  598. ok = readToken(currentToken);
  599. }
  600. bool badTokenType = (currentToken.type_ != tokenArraySeparator && currentToken.type_ != tokenArrayEnd);
  601. if (! ok || badTokenType)
  602. {
  603. return addErrorAndRecover("Missing ',' or ']' in array declaration", currentToken, tokenArrayEnd);
  604. }
  605. if (currentToken.type_ == tokenArrayEnd)
  606. {
  607. break;
  608. }
  609. }
  610. return true;
  611. }
  612. bool Reader::decodeNumber(Token & token)
  613. {
  614. Value decoded;
  615. if (! decodeNumber(token, decoded))
  616. {
  617. return false;
  618. }
  619. currentValue().swapPayload(decoded);
  620. currentValue().setOffsetStart(token.start_ - begin_);
  621. currentValue().setOffsetLimit(token.end_ - begin_);
  622. return true;
  623. }
  624. bool Reader::decodeNumber(Token & token, Value & decoded)
  625. {
  626. // Attempts to parse the number as an integer. If the number is
  627. // larger than the maximum supported value of an integer then
  628. // we decode the number as a double.
  629. Location current = token.start_;
  630. bool isNegative = *current == '-';
  631. if (isNegative)
  632. {
  633. ++current;
  634. }
  635. // TODO: Help the compiler do the div and mod at compile time or get rid of
  636. // them.
  637. Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1 : Value::maxLargestUInt;
  638. Value::LargestUInt threshold = maxIntegerValue / 10;
  639. Value::LargestUInt value = 0;
  640. while (current < token.end_)
  641. {
  642. Char c = *current++;
  643. if (c < '0' || c > '9')
  644. {
  645. return decodeDouble(token, decoded);
  646. }
  647. auto digit(static_cast<Value::UInt>(c - '0'));
  648. if (value >= threshold)
  649. {
  650. // We've hit or exceeded the max value divided by 10 (rounded down). If
  651. // a) we've only just touched the limit, b) this is the last digit, and
  652. // c) it's small enough to fit in that rounding delta, we're okay.
  653. // Otherwise treat this number as a double to avoid overflow.
  654. if (value > threshold || current != token.end_ || digit > maxIntegerValue % 10)
  655. {
  656. return decodeDouble(token, decoded);
  657. }
  658. }
  659. value = value * 10 + digit;
  660. }
  661. if (isNegative && value == maxIntegerValue)
  662. {
  663. decoded = Value::minLargestInt;
  664. }
  665. else if (isNegative)
  666. {
  667. decoded = -Value::LargestInt(value);
  668. }
  669. else if (value <= Value::LargestUInt(Value::maxInt))
  670. {
  671. decoded = Value::LargestInt(value);
  672. }
  673. else
  674. {
  675. decoded = value;
  676. }
  677. return true;
  678. }
  679. bool Reader::decodeDouble(Token & token)
  680. {
  681. Value decoded;
  682. if (! decodeDouble(token, decoded))
  683. {
  684. return false;
  685. }
  686. currentValue().swapPayload(decoded);
  687. currentValue().setOffsetStart(token.start_ - begin_);
  688. currentValue().setOffsetLimit(token.end_ - begin_);
  689. return true;
  690. }
  691. bool Reader::decodeDouble(Token & token, Value & decoded)
  692. {
  693. double value = 0;
  694. String buffer(token.start_, token.end_);
  695. IStringStream is(buffer);
  696. if (! (is >> value))
  697. {
  698. return addError("'" + String(token.start_, token.end_) + "' is not a number.", token);
  699. }
  700. decoded = value;
  701. return true;
  702. }
  703. bool Reader::decodeString(Token & token)
  704. {
  705. String decoded_string;
  706. if (! decodeString(token, decoded_string))
  707. {
  708. return false;
  709. }
  710. Value decoded(decoded_string);
  711. currentValue().swapPayload(decoded);
  712. currentValue().setOffsetStart(token.start_ - begin_);
  713. currentValue().setOffsetLimit(token.end_ - begin_);
  714. return true;
  715. }
  716. bool Reader::decodeString(Token & token, String & decoded)
  717. {
  718. decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
  719. Location current = token.start_ + 1; // skip '"'
  720. Location end = token.end_ - 1; // do not include '"'
  721. while (current != end)
  722. {
  723. Char c = *current++;
  724. if (c == '"')
  725. {
  726. break;
  727. }
  728. else if (c == '\\')
  729. {
  730. if (current == end)
  731. {
  732. return addError("Empty escape sequence in string", token, current);
  733. }
  734. Char escape = *current++;
  735. switch (escape)
  736. {
  737. case '"' : decoded += '"'; break;
  738. case '/' : decoded += '/'; break;
  739. case '\\': decoded += '\\'; break;
  740. case 'b' : decoded += '\b'; break;
  741. case 'f' : decoded += '\f'; break;
  742. case 'n' : decoded += '\n'; break;
  743. case 'r' : decoded += '\r'; break;
  744. case 't' : decoded += '\t'; break;
  745. case 'u':
  746. {
  747. unsigned int unicode;
  748. if (! decodeUnicodeCodePoint(token, current, end, unicode))
  749. {
  750. return false;
  751. }
  752. decoded += codePointToUTF8(unicode);
  753. }
  754. break;
  755. default: return addError("Bad escape sequence in string", token, current);
  756. }
  757. }
  758. else
  759. {
  760. decoded += c;
  761. }
  762. }
  763. return true;
  764. }
  765. bool Reader::decodeUnicodeCodePoint(Token & token, Location & current, Location end, unsigned int & unicode)
  766. {
  767. if (! decodeUnicodeEscapeSequence(token, current, end, unicode))
  768. {
  769. return false;
  770. }
  771. if (unicode >= 0xD800 && unicode <= 0xDBFF)
  772. {
  773. // surrogate pairs
  774. if (end - current < 6)
  775. {
  776. return addError("additional six characters expected to parse unicode surrogate pair.", token, current);
  777. }
  778. if (*(current++) == '\\' && *(current++) == 'u')
  779. {
  780. unsigned int surrogatePair;
  781. if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair))
  782. {
  783. unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
  784. }
  785. else
  786. {
  787. return false;
  788. }
  789. }
  790. else
  791. {
  792. return addError(
  793. "expecting another \\u token to begin the second half of "
  794. "a unicode surrogate pair",
  795. token, current);
  796. }
  797. }
  798. return true;
  799. }
  800. bool Reader::decodeUnicodeEscapeSequence(Token & token, Location & current, Location end, unsigned int & ret_unicode)
  801. {
  802. if (end - current < 4)
  803. {
  804. return addError("Bad unicode escape sequence in string: four digits expected.", token, current);
  805. }
  806. int unicode = 0;
  807. for (int index = 0; index < 4; ++index)
  808. {
  809. Char c = *current++;
  810. unicode *= 16;
  811. if (c >= '0' && c <= '9')
  812. {
  813. unicode += c - '0';
  814. }
  815. else if (c >= 'a' && c <= 'f')
  816. {
  817. unicode += c - 'a' + 10;
  818. }
  819. else if (c >= 'A' && c <= 'F')
  820. {
  821. unicode += c - 'A' + 10;
  822. }
  823. else
  824. {
  825. return addError("Bad unicode escape sequence in string: hexadecimal digit expected.", token, current);
  826. }
  827. }
  828. ret_unicode = static_cast<unsigned int>(unicode);
  829. return true;
  830. }
  831. bool Reader::addError(const String & message, Token & token, Location extra)
  832. {
  833. ErrorInfo info;
  834. info.token_ = token;
  835. info.message_ = message;
  836. info.extra_ = extra;
  837. errors_.push_back(info);
  838. return false;
  839. }
  840. bool Reader::recoverFromError(TokenType skipUntilToken)
  841. {
  842. const size_t errorCount = errors_.size();
  843. Token skip;
  844. for (;;)
  845. {
  846. if (! readToken(skip))
  847. {
  848. errors_.resize(errorCount); // discard errors caused by recovery
  849. }
  850. if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
  851. {
  852. break;
  853. }
  854. }
  855. errors_.resize(errorCount);
  856. return false;
  857. }
  858. bool Reader::addErrorAndRecover(const String & message, Token & token, TokenType skipUntilToken)
  859. {
  860. addError(message, token);
  861. return recoverFromError(skipUntilToken);
  862. }
  863. Value & Reader::currentValue()
  864. {
  865. return *(nodes_.top());
  866. }
  867. Reader::Char Reader::getNextChar()
  868. {
  869. if (current_ == end_)
  870. {
  871. return 0;
  872. }
  873. return *current_++;
  874. }
  875. void Reader::getLocationLineAndColumn(Location location, int & line, int & column) const
  876. {
  877. Location current = begin_;
  878. Location lastLineStart = current;
  879. line = 0;
  880. while (current < location && current != end_)
  881. {
  882. Char c = *current++;
  883. if (c == '\r')
  884. {
  885. if (*current == '\n')
  886. {
  887. ++current;
  888. }
  889. lastLineStart = current;
  890. ++line;
  891. }
  892. else if (c == '\n')
  893. {
  894. lastLineStart = current;
  895. ++line;
  896. }
  897. }
  898. // column & line start at 1
  899. column = int(location - lastLineStart) + 1;
  900. ++line;
  901. }
  902. String Reader::getLocationLineAndColumn(Location location) const
  903. {
  904. int line, column;
  905. getLocationLineAndColumn(location, line, column);
  906. char buffer[18 + 16 + 16 + 1];
  907. jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
  908. return buffer;
  909. }
  910. // Deprecated. Preserved for backward compatibility
  911. String Reader::getFormatedErrorMessages() const
  912. {
  913. return getFormattedErrorMessages();
  914. }
  915. String Reader::getFormattedErrorMessages() const
  916. {
  917. String formattedMessage;
  918. for (const auto & error : errors_)
  919. {
  920. formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
  921. formattedMessage += " " + error.message_ + "\n";
  922. if (error.extra_)
  923. {
  924. formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
  925. }
  926. }
  927. return formattedMessage;
  928. }
  929. std::vector<Reader::StructuredError> Reader::getStructuredErrors() const
  930. {
  931. std::vector<Reader::StructuredError> allErrors;
  932. for (const auto & error : errors_)
  933. {
  934. Reader::StructuredError structured;
  935. structured.offset_start = error.token_.start_ - begin_;
  936. structured.offset_limit = error.token_.end_ - begin_;
  937. structured.message = error.message_;
  938. allErrors.push_back(structured);
  939. }
  940. return allErrors;
  941. }
  942. bool Reader::pushError(const Value & value, const String & message)
  943. {
  944. const ptrdiff_t length = end_ - begin_;
  945. if (value.getOffsetStart() > length || value.getOffsetLimit() > length)
  946. {
  947. return false;
  948. }
  949. Token token;
  950. token.type_ = tokenError;
  951. token.start_ = begin_ + value.getOffsetStart();
  952. token.end_ = end_ + value.getOffsetLimit();
  953. ErrorInfo info;
  954. info.token_ = token;
  955. info.message_ = message;
  956. info.extra_ = nullptr;
  957. errors_.push_back(info);
  958. return true;
  959. }
  960. bool Reader::pushError(const Value & value, const String & message, const Value & extra)
  961. {
  962. const ptrdiff_t length = end_ - begin_;
  963. if (value.getOffsetStart() > length || value.getOffsetLimit() > length || extra.getOffsetLimit() > length)
  964. {
  965. return false;
  966. }
  967. Token token;
  968. token.type_ = tokenError;
  969. token.start_ = begin_ + value.getOffsetStart();
  970. token.end_ = begin_ + value.getOffsetLimit();
  971. ErrorInfo info;
  972. info.token_ = token;
  973. info.message_ = message;
  974. info.extra_ = begin_ + extra.getOffsetStart();
  975. errors_.push_back(info);
  976. return true;
  977. }
  978. bool Reader::good() const
  979. {
  980. return errors_.empty();
  981. }
  982. // exact copy of Features
  983. class OurFeatures
  984. {
  985. public:
  986. static OurFeatures all();
  987. bool allowComments_;
  988. bool strictRoot_;
  989. bool allowDroppedNullPlaceholders_;
  990. bool allowNumericKeys_;
  991. bool allowSingleQuotes_;
  992. bool failIfExtra_;
  993. bool rejectDupKeys_;
  994. bool allowSpecialFloats_;
  995. size_t stackLimit_;
  996. }; // OurFeatures
  997. // exact copy of Implementation of class Features
  998. // ////////////////////////////////
  999. OurFeatures OurFeatures::all()
  1000. {
  1001. return {};
  1002. }
  1003. // Implementation of class Reader
  1004. // ////////////////////////////////
  1005. // exact copy of Reader, renamed to OurReader
  1006. class OurReader
  1007. {
  1008. public:
  1009. typedef char Char;
  1010. typedef const Char * Location;
  1011. struct StructuredError
  1012. {
  1013. ptrdiff_t offset_start;
  1014. ptrdiff_t offset_limit;
  1015. String message;
  1016. };
  1017. OurReader(const OurFeatures & features);
  1018. bool parse(const char * beginDoc, const char * endDoc, Value & root, bool collectComments = true);
  1019. String getFormattedErrorMessages() const;
  1020. std::vector<StructuredError> getStructuredErrors() const;
  1021. bool pushError(const Value & value, const String & message);
  1022. bool pushError(const Value & value, const String & message, const Value & extra);
  1023. bool good() const;
  1024. private:
  1025. OurReader(const OurReader &); // no impl
  1026. void operator=(const OurReader &); // no impl
  1027. enum TokenType
  1028. {
  1029. tokenEndOfStream = 0,
  1030. tokenObjectBegin,
  1031. tokenObjectEnd,
  1032. tokenArrayBegin,
  1033. tokenArrayEnd,
  1034. tokenString,
  1035. tokenNumber,
  1036. tokenTrue,
  1037. tokenFalse,
  1038. tokenNull,
  1039. tokenNaN,
  1040. tokenPosInf,
  1041. tokenNegInf,
  1042. tokenArraySeparator,
  1043. tokenMemberSeparator,
  1044. tokenComment,
  1045. tokenError
  1046. };
  1047. class Token
  1048. {
  1049. public:
  1050. TokenType type_;
  1051. Location start_;
  1052. Location end_;
  1053. };
  1054. class ErrorInfo
  1055. {
  1056. public:
  1057. Token token_;
  1058. String message_;
  1059. Location extra_;
  1060. };
  1061. typedef std::deque<ErrorInfo> Errors;
  1062. bool readToken(Token & token);
  1063. void skipSpaces();
  1064. bool match(Location pattern, int patternLength);
  1065. bool readComment();
  1066. bool readCStyleComment();
  1067. bool readCppStyleComment();
  1068. bool readString();
  1069. bool readStringSingleQuote();
  1070. bool readNumber(bool checkInf);
  1071. bool readValue();
  1072. bool readObject(Token & token);
  1073. bool readArray(Token & token);
  1074. bool decodeNumber(Token & token);
  1075. bool decodeNumber(Token & token, Value & decoded);
  1076. bool decodeString(Token & token);
  1077. bool decodeString(Token & token, String & decoded);
  1078. bool decodeDouble(Token & token);
  1079. bool decodeDouble(Token & token, Value & decoded);
  1080. bool decodeUnicodeCodePoint(Token & token, Location & current, Location end, unsigned int & unicode);
  1081. bool decodeUnicodeEscapeSequence(Token & token, Location & current, Location end, unsigned int & unicode);
  1082. bool addError(const String & message, Token & token, Location extra = nullptr);
  1083. bool recoverFromError(TokenType skipUntilToken);
  1084. bool addErrorAndRecover(const String & message, Token & token, TokenType skipUntilToken);
  1085. void skipUntilSpace();
  1086. Value & currentValue();
  1087. Char getNextChar();
  1088. void getLocationLineAndColumn(Location location, int & line, int & column) const;
  1089. String getLocationLineAndColumn(Location location) const;
  1090. void addComment(Location begin, Location end, CommentPlacement placement);
  1091. void skipCommentTokens(Token & token);
  1092. static String normalizeEOL(Location begin, Location end);
  1093. static bool containsNewLine(Location begin, Location end);
  1094. typedef std::stack<Value *> Nodes;
  1095. Nodes nodes_;
  1096. Errors errors_;
  1097. String document_;
  1098. Location begin_;
  1099. Location end_;
  1100. Location current_;
  1101. Location lastValueEnd_;
  1102. Value * lastValue_;
  1103. String commentsBefore_;
  1104. const OurFeatures features_;
  1105. bool collectComments_;
  1106. }; // OurReader
  1107. // complete copy of Read impl, for OurReader
  1108. bool OurReader::containsNewLine(OurReader::Location begin, OurReader::Location end)
  1109. {
  1110. for (; begin < end; ++begin)
  1111. {
  1112. if (*begin == '\n' || *begin == '\r')
  1113. {
  1114. return true;
  1115. }
  1116. }
  1117. return false;
  1118. }
  1119. OurReader::OurReader(const OurFeatures & features) :
  1120. errors_(),
  1121. document_(),
  1122. begin_(),
  1123. end_(),
  1124. current_(),
  1125. lastValueEnd_(),
  1126. lastValue_(),
  1127. commentsBefore_(),
  1128. features_(features),
  1129. collectComments_()
  1130. {
  1131. }
  1132. bool OurReader::parse(const char * beginDoc, const char * endDoc, Value & root, bool collectComments)
  1133. {
  1134. if (! features_.allowComments_)
  1135. {
  1136. collectComments = false;
  1137. }
  1138. begin_ = beginDoc;
  1139. end_ = endDoc;
  1140. collectComments_ = collectComments;
  1141. current_ = begin_;
  1142. lastValueEnd_ = nullptr;
  1143. lastValue_ = nullptr;
  1144. commentsBefore_.clear();
  1145. errors_.clear();
  1146. while (! nodes_.empty())
  1147. {
  1148. nodes_.pop();
  1149. }
  1150. nodes_.push(&root);
  1151. bool successful = readValue();
  1152. Token token;
  1153. skipCommentTokens(token);
  1154. if (features_.failIfExtra_)
  1155. {
  1156. if ((features_.strictRoot_ || token.type_ != tokenError) && token.type_ != tokenEndOfStream)
  1157. {
  1158. addError("Extra non-whitespace after JSON value.", token);
  1159. return false;
  1160. }
  1161. }
  1162. if (collectComments_ && ! commentsBefore_.empty())
  1163. {
  1164. root.setComment(commentsBefore_, commentAfter);
  1165. }
  1166. if (features_.strictRoot_)
  1167. {
  1168. if (! root.isArray() && ! root.isObject())
  1169. {
  1170. // Set error location to start of doc, ideally should be first token found
  1171. // in doc
  1172. token.type_ = tokenError;
  1173. token.start_ = beginDoc;
  1174. token.end_ = endDoc;
  1175. addError("A valid JSON document must be either an array or an object value.", token);
  1176. return false;
  1177. }
  1178. }
  1179. return successful;
  1180. }
  1181. bool OurReader::readValue()
  1182. {
  1183. // To preserve the old behaviour we cast size_t to int.
  1184. if (nodes_.size() > features_.stackLimit_)
  1185. {
  1186. throwRuntimeError("Exceeded stackLimit in readValue().");
  1187. }
  1188. Token token;
  1189. skipCommentTokens(token);
  1190. bool successful = true;
  1191. if (collectComments_ && ! commentsBefore_.empty())
  1192. {
  1193. currentValue().setComment(commentsBefore_, commentBefore);
  1194. commentsBefore_.clear();
  1195. }
  1196. switch (token.type_)
  1197. {
  1198. case tokenObjectBegin:
  1199. successful = readObject(token);
  1200. currentValue().setOffsetLimit(current_ - begin_);
  1201. break;
  1202. case tokenArrayBegin:
  1203. successful = readArray(token);
  1204. currentValue().setOffsetLimit(current_ - begin_);
  1205. break;
  1206. case tokenNumber: successful = decodeNumber(token); break;
  1207. case tokenString: successful = decodeString(token); break;
  1208. case tokenTrue:
  1209. {
  1210. Value v(true);
  1211. currentValue().swapPayload(v);
  1212. currentValue().setOffsetStart(token.start_ - begin_);
  1213. currentValue().setOffsetLimit(token.end_ - begin_);
  1214. }
  1215. break;
  1216. case tokenFalse:
  1217. {
  1218. Value v(false);
  1219. currentValue().swapPayload(v);
  1220. currentValue().setOffsetStart(token.start_ - begin_);
  1221. currentValue().setOffsetLimit(token.end_ - begin_);
  1222. }
  1223. break;
  1224. case tokenNull:
  1225. {
  1226. Value v;
  1227. currentValue().swapPayload(v);
  1228. currentValue().setOffsetStart(token.start_ - begin_);
  1229. currentValue().setOffsetLimit(token.end_ - begin_);
  1230. }
  1231. break;
  1232. case tokenNaN:
  1233. {
  1234. Value v(std::numeric_limits<double>::quiet_NaN());
  1235. currentValue().swapPayload(v);
  1236. currentValue().setOffsetStart(token.start_ - begin_);
  1237. currentValue().setOffsetLimit(token.end_ - begin_);
  1238. }
  1239. break;
  1240. case tokenPosInf:
  1241. {
  1242. Value v(std::numeric_limits<double>::infinity());
  1243. currentValue().swapPayload(v);
  1244. currentValue().setOffsetStart(token.start_ - begin_);
  1245. currentValue().setOffsetLimit(token.end_ - begin_);
  1246. }
  1247. break;
  1248. case tokenNegInf:
  1249. {
  1250. Value v(-std::numeric_limits<double>::infinity());
  1251. currentValue().swapPayload(v);
  1252. currentValue().setOffsetStart(token.start_ - begin_);
  1253. currentValue().setOffsetLimit(token.end_ - begin_);
  1254. }
  1255. break;
  1256. case tokenArraySeparator:
  1257. case tokenObjectEnd:
  1258. case tokenArrayEnd:
  1259. if (features_.allowDroppedNullPlaceholders_)
  1260. {
  1261. // "Un-read" the current token and mark the current value as a null
  1262. // token.
  1263. current_--;
  1264. Value v;
  1265. currentValue().swapPayload(v);
  1266. currentValue().setOffsetStart(current_ - begin_ - 1);
  1267. currentValue().setOffsetLimit(current_ - begin_);
  1268. break;
  1269. } // else, fall through ...
  1270. default:
  1271. currentValue().setOffsetStart(token.start_ - begin_);
  1272. currentValue().setOffsetLimit(token.end_ - begin_);
  1273. return addError("Syntax error: value, object or array expected.", token);
  1274. }
  1275. if (collectComments_)
  1276. {
  1277. lastValueEnd_ = current_;
  1278. lastValue_ = &currentValue();
  1279. }
  1280. return successful;
  1281. }
  1282. void OurReader::skipCommentTokens(Token & token)
  1283. {
  1284. if (features_.allowComments_)
  1285. {
  1286. do
  1287. {
  1288. readToken(token);
  1289. }
  1290. while (token.type_ == tokenComment);
  1291. }
  1292. else
  1293. {
  1294. readToken(token);
  1295. }
  1296. }
  1297. bool OurReader::readToken(Token & token)
  1298. {
  1299. skipSpaces();
  1300. token.start_ = current_;
  1301. Char c = getNextChar();
  1302. bool ok = true;
  1303. switch (c)
  1304. {
  1305. case '{': token.type_ = tokenObjectBegin; break;
  1306. case '}': token.type_ = tokenObjectEnd; break;
  1307. case '[': token.type_ = tokenArrayBegin; break;
  1308. case ']': token.type_ = tokenArrayEnd; break;
  1309. case '"':
  1310. token.type_ = tokenString;
  1311. ok = readString();
  1312. break;
  1313. case '\'':
  1314. if (features_.allowSingleQuotes_)
  1315. {
  1316. token.type_ = tokenString;
  1317. ok = readStringSingleQuote();
  1318. break;
  1319. } // else fall through
  1320. case '/':
  1321. token.type_ = tokenComment;
  1322. ok = readComment();
  1323. break;
  1324. case '0':
  1325. case '1':
  1326. case '2':
  1327. case '3':
  1328. case '4':
  1329. case '5':
  1330. case '6':
  1331. case '7':
  1332. case '8':
  1333. case '9':
  1334. token.type_ = tokenNumber;
  1335. readNumber(false);
  1336. break;
  1337. case '-':
  1338. if (readNumber(true))
  1339. {
  1340. token.type_ = tokenNumber;
  1341. }
  1342. else
  1343. {
  1344. token.type_ = tokenNegInf;
  1345. ok = features_.allowSpecialFloats_ && match("nfinity", 7);
  1346. }
  1347. break;
  1348. case 't':
  1349. token.type_ = tokenTrue;
  1350. ok = match("rue", 3);
  1351. break;
  1352. case 'f':
  1353. token.type_ = tokenFalse;
  1354. ok = match("alse", 4);
  1355. break;
  1356. case 'n':
  1357. token.type_ = tokenNull;
  1358. ok = match("ull", 3);
  1359. break;
  1360. case 'N':
  1361. if (features_.allowSpecialFloats_)
  1362. {
  1363. token.type_ = tokenNaN;
  1364. ok = match("aN", 2);
  1365. }
  1366. else
  1367. {
  1368. ok = false;
  1369. }
  1370. break;
  1371. case 'I':
  1372. if (features_.allowSpecialFloats_)
  1373. {
  1374. token.type_ = tokenPosInf;
  1375. ok = match("nfinity", 7);
  1376. }
  1377. else
  1378. {
  1379. ok = false;
  1380. }
  1381. break;
  1382. case ',': token.type_ = tokenArraySeparator; break;
  1383. case ':': token.type_ = tokenMemberSeparator; break;
  1384. case 0 : token.type_ = tokenEndOfStream; break;
  1385. default : ok = false; break;
  1386. }
  1387. if (! ok)
  1388. {
  1389. token.type_ = tokenError;
  1390. }
  1391. token.end_ = current_;
  1392. return true;
  1393. }
  1394. void OurReader::skipSpaces()
  1395. {
  1396. while (current_ != end_)
  1397. {
  1398. Char c = *current_;
  1399. if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
  1400. {
  1401. ++current_;
  1402. }
  1403. else
  1404. {
  1405. break;
  1406. }
  1407. }
  1408. }
  1409. bool OurReader::match(Location pattern, int patternLength)
  1410. {
  1411. if (end_ - current_ < patternLength)
  1412. {
  1413. return false;
  1414. }
  1415. int index = patternLength;
  1416. while (index--)
  1417. {
  1418. if (current_[index] != pattern[index])
  1419. {
  1420. return false;
  1421. }
  1422. }
  1423. current_ += patternLength;
  1424. return true;
  1425. }
  1426. bool OurReader::readComment()
  1427. {
  1428. Location commentBegin = current_ - 1;
  1429. Char c = getNextChar();
  1430. bool successful = false;
  1431. if (c == '*')
  1432. {
  1433. successful = readCStyleComment();
  1434. }
  1435. else if (c == '/')
  1436. {
  1437. successful = readCppStyleComment();
  1438. }
  1439. if (! successful)
  1440. {
  1441. return false;
  1442. }
  1443. if (collectComments_)
  1444. {
  1445. CommentPlacement placement = commentBefore;
  1446. if (lastValueEnd_ && ! containsNewLine(lastValueEnd_, commentBegin))
  1447. {
  1448. if (c != '*' || ! containsNewLine(commentBegin, current_))
  1449. {
  1450. placement = commentAfterOnSameLine;
  1451. }
  1452. }
  1453. addComment(commentBegin, current_, placement);
  1454. }
  1455. return true;
  1456. }
  1457. String OurReader::normalizeEOL(OurReader::Location begin, OurReader::Location end)
  1458. {
  1459. String normalized;
  1460. normalized.reserve(static_cast<size_t>(end - begin));
  1461. OurReader::Location current = begin;
  1462. while (current != end)
  1463. {
  1464. char c = *current++;
  1465. if (c == '\r')
  1466. {
  1467. if (current != end && *current == '\n')
  1468. {
  1469. // convert dos EOL
  1470. ++current;
  1471. }
  1472. // convert Mac EOL
  1473. normalized += '\n';
  1474. }
  1475. else
  1476. {
  1477. normalized += c;
  1478. }
  1479. }
  1480. return normalized;
  1481. }
  1482. void OurReader::addComment(Location begin, Location end, CommentPlacement placement)
  1483. {
  1484. assert(collectComments_);
  1485. const String & normalized = normalizeEOL(begin, end);
  1486. if (placement == commentAfterOnSameLine)
  1487. {
  1488. assert(lastValue_ != nullptr);
  1489. lastValue_->setComment(normalized, placement);
  1490. }
  1491. else
  1492. {
  1493. commentsBefore_ += normalized;
  1494. }
  1495. }
  1496. bool OurReader::readCStyleComment()
  1497. {
  1498. while ((current_ + 1) < end_)
  1499. {
  1500. Char c = getNextChar();
  1501. if (c == '*' && *current_ == '/')
  1502. {
  1503. break;
  1504. }
  1505. }
  1506. return getNextChar() == '/';
  1507. }
  1508. bool OurReader::readCppStyleComment()
  1509. {
  1510. while (current_ != end_)
  1511. {
  1512. Char c = getNextChar();
  1513. if (c == '\n')
  1514. {
  1515. break;
  1516. }
  1517. if (c == '\r')
  1518. {
  1519. // Consume DOS EOL. It will be normalized in addComment.
  1520. if (current_ != end_ && *current_ == '\n')
  1521. {
  1522. getNextChar();
  1523. }
  1524. // Break on Moc OS 9 EOL.
  1525. break;
  1526. }
  1527. }
  1528. return true;
  1529. }
  1530. bool OurReader::readNumber(bool checkInf)
  1531. {
  1532. const char * p = current_;
  1533. if (checkInf && p != end_ && *p == 'I')
  1534. {
  1535. current_ = ++p;
  1536. return false;
  1537. }
  1538. char c = '0'; // stopgap for already consumed character
  1539. // integral part
  1540. while (c >= '0' && c <= '9')
  1541. {
  1542. c = (current_ = p) < end_ ? *p++ : '\0';
  1543. }
  1544. // fractional part
  1545. if (c == '.')
  1546. {
  1547. c = (current_ = p) < end_ ? *p++ : '\0';
  1548. while (c >= '0' && c <= '9')
  1549. {
  1550. c = (current_ = p) < end_ ? *p++ : '\0';
  1551. }
  1552. }
  1553. // exponential part
  1554. if (c == 'e' || c == 'E')
  1555. {
  1556. c = (current_ = p) < end_ ? *p++ : '\0';
  1557. if (c == '+' || c == '-')
  1558. {
  1559. c = (current_ = p) < end_ ? *p++ : '\0';
  1560. }
  1561. while (c >= '0' && c <= '9')
  1562. {
  1563. c = (current_ = p) < end_ ? *p++ : '\0';
  1564. }
  1565. }
  1566. return true;
  1567. }
  1568. bool OurReader::readString()
  1569. {
  1570. Char c = 0;
  1571. while (current_ != end_)
  1572. {
  1573. c = getNextChar();
  1574. if (c == '\\')
  1575. {
  1576. getNextChar();
  1577. }
  1578. else if (c == '"')
  1579. {
  1580. break;
  1581. }
  1582. }
  1583. return c == '"';
  1584. }
  1585. bool OurReader::readStringSingleQuote()
  1586. {
  1587. Char c = 0;
  1588. while (current_ != end_)
  1589. {
  1590. c = getNextChar();
  1591. if (c == '\\')
  1592. {
  1593. getNextChar();
  1594. }
  1595. else if (c == '\'')
  1596. {
  1597. break;
  1598. }
  1599. }
  1600. return c == '\'';
  1601. }
  1602. bool OurReader::readObject(Token & token)
  1603. {
  1604. Token tokenName;
  1605. String name;
  1606. Value init(objectValue);
  1607. currentValue().swapPayload(init);
  1608. currentValue().setOffsetStart(token.start_ - begin_);
  1609. while (readToken(tokenName))
  1610. {
  1611. bool initialTokenOk = true;
  1612. while (tokenName.type_ == tokenComment && initialTokenOk)
  1613. {
  1614. initialTokenOk = readToken(tokenName);
  1615. }
  1616. if (! initialTokenOk)
  1617. {
  1618. break;
  1619. }
  1620. if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
  1621. {
  1622. return true;
  1623. }
  1624. name.clear();
  1625. if (tokenName.type_ == tokenString)
  1626. {
  1627. if (! decodeString(tokenName, name))
  1628. {
  1629. return recoverFromError(tokenObjectEnd);
  1630. }
  1631. }
  1632. else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_)
  1633. {
  1634. Value numberName;
  1635. if (! decodeNumber(tokenName, numberName))
  1636. {
  1637. return recoverFromError(tokenObjectEnd);
  1638. }
  1639. name = numberName.asString();
  1640. }
  1641. else
  1642. {
  1643. break;
  1644. }
  1645. Token colon;
  1646. if (! readToken(colon) || colon.type_ != tokenMemberSeparator)
  1647. {
  1648. return addErrorAndRecover("Missing ':' after object member name", colon, tokenObjectEnd);
  1649. }
  1650. if (name.length() >= (1U << 30))
  1651. {
  1652. throwRuntimeError("keylength >= 2^30");
  1653. }
  1654. if (features_.rejectDupKeys_ && currentValue().isMember(name))
  1655. {
  1656. String msg = "Duplicate key: '" + name + "'";
  1657. return addErrorAndRecover(msg, tokenName, tokenObjectEnd);
  1658. }
  1659. Value & value = currentValue()[name];
  1660. nodes_.push(&value);
  1661. bool ok = readValue();
  1662. nodes_.pop();
  1663. if (! ok) // error already set
  1664. {
  1665. return recoverFromError(tokenObjectEnd);
  1666. }
  1667. Token comma;
  1668. if (! readToken(comma) || (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment))
  1669. {
  1670. return addErrorAndRecover("Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
  1671. }
  1672. bool finalizeTokenOk = true;
  1673. while (comma.type_ == tokenComment && finalizeTokenOk)
  1674. {
  1675. finalizeTokenOk = readToken(comma);
  1676. }
  1677. if (comma.type_ == tokenObjectEnd)
  1678. {
  1679. return true;
  1680. }
  1681. }
  1682. return addErrorAndRecover("Missing '}' or object member name", tokenName, tokenObjectEnd);
  1683. }
  1684. bool OurReader::readArray(Token & token)
  1685. {
  1686. Value init(arrayValue);
  1687. currentValue().swapPayload(init);
  1688. currentValue().setOffsetStart(token.start_ - begin_);
  1689. skipSpaces();
  1690. if (current_ != end_ && *current_ == ']') // empty array
  1691. {
  1692. Token endArray;
  1693. readToken(endArray);
  1694. return true;
  1695. }
  1696. int index = 0;
  1697. for (;;)
  1698. {
  1699. Value & value = currentValue()[index++];
  1700. nodes_.push(&value);
  1701. bool ok = readValue();
  1702. nodes_.pop();
  1703. if (! ok) // error already set
  1704. {
  1705. return recoverFromError(tokenArrayEnd);
  1706. }
  1707. Token currentToken;
  1708. // Accept Comment after last item in the array.
  1709. ok = readToken(currentToken);
  1710. while (currentToken.type_ == tokenComment && ok)
  1711. {
  1712. ok = readToken(currentToken);
  1713. }
  1714. bool badTokenType = (currentToken.type_ != tokenArraySeparator && currentToken.type_ != tokenArrayEnd);
  1715. if (! ok || badTokenType)
  1716. {
  1717. return addErrorAndRecover("Missing ',' or ']' in array declaration", currentToken, tokenArrayEnd);
  1718. }
  1719. if (currentToken.type_ == tokenArrayEnd)
  1720. {
  1721. break;
  1722. }
  1723. }
  1724. return true;
  1725. }
  1726. bool OurReader::decodeNumber(Token & token)
  1727. {
  1728. Value decoded;
  1729. if (! decodeNumber(token, decoded))
  1730. {
  1731. return false;
  1732. }
  1733. currentValue().swapPayload(decoded);
  1734. currentValue().setOffsetStart(token.start_ - begin_);
  1735. currentValue().setOffsetLimit(token.end_ - begin_);
  1736. return true;
  1737. }
  1738. bool OurReader::decodeNumber(Token & token, Value & decoded)
  1739. {
  1740. // Attempts to parse the number as an integer. If the number is
  1741. // larger than the maximum supported value of an integer then
  1742. // we decode the number as a double.
  1743. Location current = token.start_;
  1744. bool isNegative = *current == '-';
  1745. if (isNegative)
  1746. {
  1747. ++current;
  1748. }
  1749. // TODO: Help the compiler do the div and mod at compile time or get rid of
  1750. // them.
  1751. Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(Value::minLargestInt) : Value::maxLargestUInt;
  1752. Value::LargestUInt threshold = maxIntegerValue / 10;
  1753. Value::LargestUInt value = 0;
  1754. while (current < token.end_)
  1755. {
  1756. Char c = *current++;
  1757. if (c < '0' || c > '9')
  1758. {
  1759. return decodeDouble(token, decoded);
  1760. }
  1761. auto digit(static_cast<Value::UInt>(c - '0'));
  1762. if (value >= threshold)
  1763. {
  1764. // We've hit or exceeded the max value divided by 10 (rounded down). If
  1765. // a) we've only just touched the limit, b) this is the last digit, and
  1766. // c) it's small enough to fit in that rounding delta, we're okay.
  1767. // Otherwise treat this number as a double to avoid overflow.
  1768. if (value > threshold || current != token.end_ || digit > maxIntegerValue % 10)
  1769. {
  1770. return decodeDouble(token, decoded);
  1771. }
  1772. }
  1773. value = value * 10 + digit;
  1774. }
  1775. if (isNegative)
  1776. {
  1777. decoded = -Value::LargestInt(value);
  1778. }
  1779. else if (value <= Value::LargestUInt(Value::maxInt))
  1780. {
  1781. decoded = Value::LargestInt(value);
  1782. }
  1783. else
  1784. {
  1785. decoded = value;
  1786. }
  1787. return true;
  1788. }
  1789. bool OurReader::decodeDouble(Token & token)
  1790. {
  1791. Value decoded;
  1792. if (! decodeDouble(token, decoded))
  1793. {
  1794. return false;
  1795. }
  1796. currentValue().swapPayload(decoded);
  1797. currentValue().setOffsetStart(token.start_ - begin_);
  1798. currentValue().setOffsetLimit(token.end_ - begin_);
  1799. return true;
  1800. }
  1801. bool OurReader::decodeDouble(Token & token, Value & decoded)
  1802. {
  1803. double value = 0;
  1804. const int bufferSize = 32;
  1805. int count;
  1806. const ptrdiff_t length = token.end_ - token.start_;
  1807. // Sanity check to avoid buffer overflow exploits.
  1808. if (length < 0)
  1809. {
  1810. return addError("Unable to parse token length", token);
  1811. }
  1812. const auto ulength = static_cast<size_t>(length);
  1813. // Avoid using a string constant for the format control string given to
  1814. // sscanf, as this can cause hard to debug crashes on OS X. See here for more
  1815. // info:
  1816. //
  1817. // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
  1818. char format[] = "%lf";
  1819. if (length <= bufferSize)
  1820. {
  1821. Char buffer[bufferSize + 1];
  1822. memcpy(buffer, token.start_, ulength);
  1823. buffer[length] = 0;
  1824. fixNumericLocaleInput(buffer, buffer + length);
  1825. count = sscanf(buffer, format, &value);
  1826. }
  1827. else
  1828. {
  1829. String buffer(token.start_, token.end_);
  1830. count = sscanf(buffer.c_str(), format, &value);
  1831. }
  1832. if (count != 1)
  1833. {
  1834. return addError("'" + String(token.start_, token.end_) + "' is not a number.", token);
  1835. }
  1836. decoded = value;
  1837. return true;
  1838. }
  1839. bool OurReader::decodeString(Token & token)
  1840. {
  1841. String decoded_string;
  1842. if (! decodeString(token, decoded_string))
  1843. {
  1844. return false;
  1845. }
  1846. Value decoded(decoded_string);
  1847. currentValue().swapPayload(decoded);
  1848. currentValue().setOffsetStart(token.start_ - begin_);
  1849. currentValue().setOffsetLimit(token.end_ - begin_);
  1850. return true;
  1851. }
  1852. bool OurReader::decodeString(Token & token, String & decoded)
  1853. {
  1854. decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
  1855. Location current = token.start_ + 1; // skip '"'
  1856. Location end = token.end_ - 1; // do not include '"'
  1857. while (current != end)
  1858. {
  1859. Char c = *current++;
  1860. if (c == '"')
  1861. {
  1862. break;
  1863. }
  1864. else if (c == '\\')
  1865. {
  1866. if (current == end)
  1867. {
  1868. return addError("Empty escape sequence in string", token, current);
  1869. }
  1870. Char escape = *current++;
  1871. switch (escape)
  1872. {
  1873. case '"' : decoded += '"'; break;
  1874. case '/' : decoded += '/'; break;
  1875. case '\\': decoded += '\\'; break;
  1876. case 'b' : decoded += '\b'; break;
  1877. case 'f' : decoded += '\f'; break;
  1878. case 'n' : decoded += '\n'; break;
  1879. case 'r' : decoded += '\r'; break;
  1880. case 't' : decoded += '\t'; break;
  1881. case 'u':
  1882. {
  1883. unsigned int unicode;
  1884. if (! decodeUnicodeCodePoint(token, current, end, unicode))
  1885. {
  1886. return false;
  1887. }
  1888. decoded += codePointToUTF8(unicode);
  1889. }
  1890. break;
  1891. default: return addError("Bad escape sequence in string", token, current);
  1892. }
  1893. }
  1894. else
  1895. {
  1896. decoded += c;
  1897. }
  1898. }
  1899. return true;
  1900. }
  1901. bool OurReader::decodeUnicodeCodePoint(Token & token, Location & current, Location end, unsigned int & unicode)
  1902. {
  1903. if (! decodeUnicodeEscapeSequence(token, current, end, unicode))
  1904. {
  1905. return false;
  1906. }
  1907. if (unicode >= 0xD800 && unicode <= 0xDBFF)
  1908. {
  1909. // surrogate pairs
  1910. if (end - current < 6)
  1911. {
  1912. return addError("additional six characters expected to parse unicode surrogate pair.", token, current);
  1913. }
  1914. if (*(current++) == '\\' && *(current++) == 'u')
  1915. {
  1916. unsigned int surrogatePair;
  1917. if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair))
  1918. {
  1919. unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
  1920. }
  1921. else
  1922. {
  1923. return false;
  1924. }
  1925. }
  1926. else
  1927. {
  1928. return addError(
  1929. "expecting another \\u token to begin the second half of "
  1930. "a unicode surrogate pair",
  1931. token, current);
  1932. }
  1933. }
  1934. return true;
  1935. }
  1936. bool OurReader::decodeUnicodeEscapeSequence(Token & token, Location & current, Location end, unsigned int & ret_unicode)
  1937. {
  1938. if (end - current < 4)
  1939. {
  1940. return addError("Bad unicode escape sequence in string: four digits expected.", token, current);
  1941. }
  1942. int unicode = 0;
  1943. for (int index = 0; index < 4; ++index)
  1944. {
  1945. Char c = *current++;
  1946. unicode *= 16;
  1947. if (c >= '0' && c <= '9')
  1948. {
  1949. unicode += c - '0';
  1950. }
  1951. else if (c >= 'a' && c <= 'f')
  1952. {
  1953. unicode += c - 'a' + 10;
  1954. }
  1955. else if (c >= 'A' && c <= 'F')
  1956. {
  1957. unicode += c - 'A' + 10;
  1958. }
  1959. else
  1960. {
  1961. return addError("Bad unicode escape sequence in string: hexadecimal digit expected.", token, current);
  1962. }
  1963. }
  1964. ret_unicode = static_cast<unsigned int>(unicode);
  1965. return true;
  1966. }
  1967. bool OurReader::addError(const String & message, Token & token, Location extra)
  1968. {
  1969. ErrorInfo info;
  1970. info.token_ = token;
  1971. info.message_ = message;
  1972. info.extra_ = extra;
  1973. errors_.push_back(info);
  1974. return false;
  1975. }
  1976. bool OurReader::recoverFromError(TokenType skipUntilToken)
  1977. {
  1978. size_t errorCount = errors_.size();
  1979. Token skip;
  1980. for (;;)
  1981. {
  1982. if (! readToken(skip))
  1983. {
  1984. errors_.resize(errorCount); // discard errors caused by recovery
  1985. }
  1986. if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
  1987. {
  1988. break;
  1989. }
  1990. }
  1991. errors_.resize(errorCount);
  1992. return false;
  1993. }
  1994. bool OurReader::addErrorAndRecover(const String & message, Token & token, TokenType skipUntilToken)
  1995. {
  1996. addError(message, token);
  1997. return recoverFromError(skipUntilToken);
  1998. }
  1999. Value & OurReader::currentValue()
  2000. {
  2001. return *(nodes_.top());
  2002. }
  2003. OurReader::Char OurReader::getNextChar()
  2004. {
  2005. if (current_ == end_)
  2006. {
  2007. return 0;
  2008. }
  2009. return *current_++;
  2010. }
  2011. void OurReader::getLocationLineAndColumn(Location location, int & line, int & column) const
  2012. {
  2013. Location current = begin_;
  2014. Location lastLineStart = current;
  2015. line = 0;
  2016. while (current < location && current != end_)
  2017. {
  2018. Char c = *current++;
  2019. if (c == '\r')
  2020. {
  2021. if (*current == '\n')
  2022. {
  2023. ++current;
  2024. }
  2025. lastLineStart = current;
  2026. ++line;
  2027. }
  2028. else if (c == '\n')
  2029. {
  2030. lastLineStart = current;
  2031. ++line;
  2032. }
  2033. }
  2034. // column & line start at 1
  2035. column = int(location - lastLineStart) + 1;
  2036. ++line;
  2037. }
  2038. String OurReader::getLocationLineAndColumn(Location location) const
  2039. {
  2040. int line, column;
  2041. getLocationLineAndColumn(location, line, column);
  2042. char buffer[18 + 16 + 16 + 1];
  2043. jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
  2044. return buffer;
  2045. }
  2046. String OurReader::getFormattedErrorMessages() const
  2047. {
  2048. String formattedMessage;
  2049. for (const auto & error : errors_)
  2050. {
  2051. formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
  2052. formattedMessage += " " + error.message_ + "\n";
  2053. if (error.extra_)
  2054. {
  2055. formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
  2056. }
  2057. }
  2058. return formattedMessage;
  2059. }
  2060. std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const
  2061. {
  2062. std::vector<OurReader::StructuredError> allErrors;
  2063. for (const auto & error : errors_)
  2064. {
  2065. OurReader::StructuredError structured;
  2066. structured.offset_start = error.token_.start_ - begin_;
  2067. structured.offset_limit = error.token_.end_ - begin_;
  2068. structured.message = error.message_;
  2069. allErrors.push_back(structured);
  2070. }
  2071. return allErrors;
  2072. }
  2073. bool OurReader::pushError(const Value & value, const String & message)
  2074. {
  2075. ptrdiff_t length = end_ - begin_;
  2076. if (value.getOffsetStart() > length || value.getOffsetLimit() > length)
  2077. {
  2078. return false;
  2079. }
  2080. Token token;
  2081. token.type_ = tokenError;
  2082. token.start_ = begin_ + value.getOffsetStart();
  2083. token.end_ = end_ + value.getOffsetLimit();
  2084. ErrorInfo info;
  2085. info.token_ = token;
  2086. info.message_ = message;
  2087. info.extra_ = nullptr;
  2088. errors_.push_back(info);
  2089. return true;
  2090. }
  2091. bool OurReader::pushError(const Value & value, const String & message, const Value & extra)
  2092. {
  2093. ptrdiff_t length = end_ - begin_;
  2094. if (value.getOffsetStart() > length || value.getOffsetLimit() > length || extra.getOffsetLimit() > length)
  2095. {
  2096. return false;
  2097. }
  2098. Token token;
  2099. token.type_ = tokenError;
  2100. token.start_ = begin_ + value.getOffsetStart();
  2101. token.end_ = begin_ + value.getOffsetLimit();
  2102. ErrorInfo info;
  2103. info.token_ = token;
  2104. info.message_ = message;
  2105. info.extra_ = begin_ + extra.getOffsetStart();
  2106. errors_.push_back(info);
  2107. return true;
  2108. }
  2109. bool OurReader::good() const
  2110. {
  2111. return errors_.empty();
  2112. }
  2113. class OurCharReader : public CharReader
  2114. {
  2115. const bool collectComments_;
  2116. OurReader reader_;
  2117. public:
  2118. OurCharReader(bool collectComments, const OurFeatures & features) :
  2119. collectComments_(collectComments),
  2120. reader_(features)
  2121. {
  2122. }
  2123. bool parse(const char * beginDoc, const char * endDoc, Value * root, String * errs) override
  2124. {
  2125. bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
  2126. if (errs)
  2127. {
  2128. *errs = reader_.getFormattedErrorMessages();
  2129. }
  2130. return ok;
  2131. }
  2132. };
  2133. CharReaderBuilder::CharReaderBuilder()
  2134. {
  2135. setDefaults(&settings_);
  2136. }
  2137. CharReaderBuilder::~CharReaderBuilder() = default;
  2138. CharReader * CharReaderBuilder::newCharReader() const
  2139. {
  2140. bool collectComments = settings_["collectComments"].asBool();
  2141. OurFeatures features = OurFeatures::all();
  2142. features.allowComments_ = settings_["allowComments"].asBool();
  2143. features.strictRoot_ = settings_["strictRoot"].asBool();
  2144. features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
  2145. features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
  2146. features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
  2147. #if defined(JSON_HAS_INT64)
  2148. features.stackLimit_ = settings_["stackLimit"].asUInt64();
  2149. #else
  2150. features.stackLimit_ = settings_["stackLimit"].asUInt();
  2151. #endif
  2152. features.failIfExtra_ = settings_["failIfExtra"].asBool();
  2153. features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
  2154. features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
  2155. return new OurCharReader(collectComments, features);
  2156. }
  2157. static void getValidReaderKeys(std::set<String> * valid_keys)
  2158. {
  2159. valid_keys->clear();
  2160. valid_keys->insert("collectComments");
  2161. valid_keys->insert("allowComments");
  2162. valid_keys->insert("strictRoot");
  2163. valid_keys->insert("allowDroppedNullPlaceholders");
  2164. valid_keys->insert("allowNumericKeys");
  2165. valid_keys->insert("allowSingleQuotes");
  2166. valid_keys->insert("stackLimit");
  2167. valid_keys->insert("failIfExtra");
  2168. valid_keys->insert("rejectDupKeys");
  2169. valid_keys->insert("allowSpecialFloats");
  2170. }
  2171. bool CharReaderBuilder::validate(Json::Value * invalid) const
  2172. {
  2173. Json::Value my_invalid;
  2174. if (! invalid)
  2175. {
  2176. invalid = &my_invalid; // so we do not need to test for NULL
  2177. }
  2178. Json::Value & inv = *invalid;
  2179. std::set<String> valid_keys;
  2180. getValidReaderKeys(&valid_keys);
  2181. Value::Members keys = settings_.getMemberNames();
  2182. size_t n = keys.size();
  2183. for (size_t i = 0; i < n; ++i)
  2184. {
  2185. const String & key = keys[i];
  2186. if (valid_keys.find(key) == valid_keys.end())
  2187. {
  2188. inv[key] = settings_[key];
  2189. }
  2190. }
  2191. return inv.empty();
  2192. }
  2193. Value & CharReaderBuilder::operator[](const String & key)
  2194. {
  2195. return settings_[key];
  2196. }
  2197. // static
  2198. void CharReaderBuilder::strictMode(Json::Value * settings)
  2199. {
  2200. //! [CharReaderBuilderStrictMode]
  2201. (*settings)["allowComments"] = false;
  2202. (*settings)["strictRoot"] = true;
  2203. (*settings)["allowDroppedNullPlaceholders"] = false;
  2204. (*settings)["allowNumericKeys"] = false;
  2205. (*settings)["allowSingleQuotes"] = false;
  2206. (*settings)["stackLimit"] = 1000;
  2207. (*settings)["failIfExtra"] = true;
  2208. (*settings)["rejectDupKeys"] = true;
  2209. (*settings)["allowSpecialFloats"] = false;
  2210. //! [CharReaderBuilderStrictMode]
  2211. }
  2212. // static
  2213. void CharReaderBuilder::setDefaults(Json::Value * settings)
  2214. {
  2215. //! [CharReaderBuilderDefaults]
  2216. (*settings)["collectComments"] = true;
  2217. (*settings)["allowComments"] = true;
  2218. (*settings)["strictRoot"] = false;
  2219. (*settings)["allowDroppedNullPlaceholders"] = false;
  2220. (*settings)["allowNumericKeys"] = false;
  2221. (*settings)["allowSingleQuotes"] = false;
  2222. (*settings)["stackLimit"] = 1000;
  2223. (*settings)["failIfExtra"] = false;
  2224. (*settings)["rejectDupKeys"] = false;
  2225. (*settings)["allowSpecialFloats"] = false;
  2226. //! [CharReaderBuilderDefaults]
  2227. }
  2228. //////////////////////////////////
  2229. // global functions
  2230. bool parseFromStream(const CharReader::Factory & fact, IStream & sin, Value * root, String * errs)
  2231. {
  2232. OStringStream ssin;
  2233. ssin << sin.rdbuf();
  2234. String doc = ssin.str();
  2235. const char * begin = doc.data();
  2236. const char * end = begin + doc.size();
  2237. // Note that we do not actually need a null-terminator.
  2238. const CharReaderPtr reader(fact.newCharReader());
  2239. return reader->parse(begin, end, root, errs);
  2240. }
  2241. IStream & operator>>(IStream & sin, Value & root)
  2242. {
  2243. CharReaderBuilder b;
  2244. String errs;
  2245. bool ok = parseFromStream(b, sin, &root, &errs);
  2246. if (! ok)
  2247. {
  2248. throwRuntimeError(errs);
  2249. }
  2250. return sin;
  2251. }
  2252. } // namespace Json