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.

2008 lines
57 KiB

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