7#if !defined(JSON_IS_AMALGAMATION)
29#if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
30#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
36#pragma warning(disable : 4996)
41#if !defined(JSONCPP_DEPRECATED_STACK_LIMIT)
42#define JSONCPP_DEPRECATED_STACK_LIMIT 256
72 return std::any_of(begin, end, [](
char b) {
return b ==
'\n' || b ==
'\r'; });
83 bool collectComments) {
84 document_.assign(document.begin(), document.end());
85 const char* begin = document_.c_str();
86 const char* end = begin + document_.length();
87 return parse(begin, end, root, collectComments);
91 document_.assign(std::istreambuf_iterator<char>(is),
92 std::istreambuf_iterator<char>());
93 return parse(document_.data(), document_.data() + document_.size(), root,
98 bool collectComments) {
99 if (!features_.allowComments_) {
100 collectComments =
false;
105 collectComments_ = collectComments;
107 lastValueEnd_ =
nullptr;
108 lastValue_ =
nullptr;
109 commentsBefore_.clear();
111 while (!nodes_.empty())
115 bool successful = readValue();
117 readTokenSkippingComments(token);
118 if (collectComments_ && !commentsBefore_.empty())
120 if (features_.strictRoot_) {
124 token.type_ = tokenError;
125 token.start_ = beginDoc;
128 "A valid JSON document must be either an array or an object value.",
136bool Reader::readValue() {
142#if JSON_USE_EXCEPTION
150 readTokenSkippingComments(token);
151 bool successful =
true;
153 if (collectComments_ && !commentsBefore_.empty()) {
155 commentsBefore_.clear();
158 switch (token.type_) {
159 case tokenObjectBegin:
160 successful = readObject(token);
163 case tokenArrayBegin:
164 successful = readArray(token);
168 successful = decodeNumber(token);
171 successful = decodeString(token);
181 currentValue().swapPayload(v);
182 currentValue().setOffsetStart(token.start_ - begin_);
183 currentValue().setOffsetLimit(token.end_ - begin_);
187 currentValue().swapPayload(v);
188 currentValue().setOffsetStart(token.start_ - begin_);
189 currentValue().setOffsetLimit(token.end_ - begin_);
191 case tokenArraySeparator:
194 if (features_.allowDroppedNullPlaceholders_) {
199 currentValue().swapPayload(v);
200 currentValue().setOffsetStart(current_ - begin_ - 1);
201 currentValue().setOffsetLimit(current_ - begin_);
205 currentValue().setOffsetStart(token.start_ - begin_);
206 currentValue().setOffsetLimit(token.end_ - begin_);
207 return addError(
"Syntax error: value, object or array expected.", token);
210 if (collectComments_) {
211 lastValueEnd_ = current_;
212 lastValue_ = ¤tValue();
218bool Reader::readTokenSkippingComments(Token& token) {
219 bool success = readToken(token);
220 if (features_.allowComments_) {
221 while (success && token.type_ == tokenComment) {
222 success = readToken(token);
228bool Reader::readToken(Token& token) {
230 token.start_ = current_;
231 Char c = getNextChar();
235 token.type_ = tokenObjectBegin;
238 token.type_ = tokenObjectEnd;
241 token.type_ = tokenArrayBegin;
244 token.type_ = tokenArrayEnd;
247 token.type_ = tokenString;
251 token.type_ = tokenComment;
265 token.type_ = tokenNumber;
269 token.type_ = tokenTrue;
270 ok = match(
"rue", 3);
273 token.type_ = tokenFalse;
274 ok = match(
"alse", 4);
277 token.type_ = tokenNull;
278 ok = match(
"ull", 3);
281 token.type_ = tokenArraySeparator;
284 token.type_ = tokenMemberSeparator;
287 token.type_ = tokenEndOfStream;
294 token.type_ = tokenError;
295 token.end_ = current_;
299void Reader::skipSpaces() {
300 while (current_ != end_) {
302 if (c ==
' ' || c ==
'\t' || c ==
'\r' || c ==
'\n')
309bool Reader::match(
const Char* pattern,
int patternLength) {
310 if (end_ - current_ < patternLength)
312 int index = patternLength;
314 if (current_[index] != pattern[index])
316 current_ += patternLength;
320bool Reader::readComment() {
321 Location commentBegin = current_ - 1;
322 Char c = getNextChar();
323 bool successful =
false;
325 successful = readCStyleComment();
327 successful = readCppStyleComment();
331 if (collectComments_) {
333 if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
334 if (c !=
'*' || !containsNewLine(commentBegin, current_))
338 addComment(commentBegin, current_, placement);
345 normalized.reserve(
static_cast<size_t>(end - begin));
347 while (current != end) {
350 if (current != end && *current ==
'\n')
362void Reader::addComment(Location begin, Location end,
364 assert(collectComments_);
365 const String& normalized = normalizeEOL(begin, end);
367 assert(lastValue_ !=
nullptr);
368 lastValue_->setComment(normalized, placement);
370 commentsBefore_ += normalized;
374bool Reader::readCStyleComment() {
375 while ((current_ + 1) < end_) {
376 Char c = getNextChar();
377 if (c ==
'*' && *current_ ==
'/')
380 return getNextChar() ==
'/';
383bool Reader::readCppStyleComment() {
384 while (current_ != end_) {
385 Char c = getNextChar();
390 if (current_ != end_ && *current_ ==
'\n')
399void Reader::readNumber() {
403 while (c >=
'0' && c <=
'9')
404 c = (current_ = p) < end_ ? *p++ :
'\0';
407 c = (current_ = p) < end_ ? *p++ :
'\0';
408 while (c >=
'0' && c <=
'9')
409 c = (current_ = p) < end_ ? *p++ :
'\0';
412 if (c ==
'e' || c ==
'E') {
413 c = (current_ = p) < end_ ? *p++ :
'\0';
414 if (c ==
'+' || c ==
'-')
415 c = (current_ = p) < end_ ? *p++ :
'\0';
416 while (c >=
'0' && c <=
'9')
417 c = (current_ = p) < end_ ? *p++ :
'\0';
421bool Reader::readString() {
423 while (current_ != end_) {
433bool Reader::readObject(Token& token) {
437 currentValue().swapPayload(init);
438 currentValue().setOffsetStart(token.start_ - begin_);
439 while (readTokenSkippingComments(tokenName)) {
440 if (tokenName.type_ == tokenObjectEnd && name.empty())
443 if (tokenName.type_ == tokenString) {
444 if (!decodeString(tokenName, name))
445 return recoverFromError(tokenObjectEnd);
446 }
else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
448 if (!decodeNumber(tokenName, numberName))
449 return recoverFromError(tokenObjectEnd);
450 name = numberName.asString();
456 if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
457 return addErrorAndRecover(
"Missing ':' after object member name", colon,
460 Value& value = currentValue()[name];
462 bool ok = readValue();
465 return recoverFromError(tokenObjectEnd);
468 if (!readTokenSkippingComments(comma) ||
469 (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator)) {
470 return addErrorAndRecover(
"Missing ',' or '}' in object declaration",
471 comma, tokenObjectEnd);
473 if (comma.type_ == tokenObjectEnd)
476 return addErrorAndRecover(
"Missing '}' or object member name", tokenName,
480bool Reader::readArray(Token& token) {
482 currentValue().swapPayload(init);
483 currentValue().setOffsetStart(token.start_ - begin_);
485 if (current_ != end_ && *current_ ==
']')
493 Value& value = currentValue()[index++];
495 bool ok = readValue();
498 return recoverFromError(tokenArrayEnd);
502 ok = readTokenSkippingComments(currentToken);
503 bool badTokenType = (currentToken.type_ != tokenArraySeparator &&
504 currentToken.type_ != tokenArrayEnd);
505 if (!ok || badTokenType) {
506 return addErrorAndRecover(
"Missing ',' or ']' in array declaration",
507 currentToken, tokenArrayEnd);
509 if (currentToken.type_ == tokenArrayEnd)
515bool Reader::decodeNumber(Token& token) {
517 if (!decodeNumber(token, decoded))
519 currentValue().swapPayload(decoded);
520 currentValue().setOffsetStart(token.start_ - begin_);
521 currentValue().setOffsetLimit(token.end_ - begin_);
525bool Reader::decodeNumber(Token& token,
Value& decoded) {
530 bool isNegative = *current ==
'-';
540 while (current < token.end_) {
542 if (c <
'0' || c >
'9')
543 return decodeDouble(token, decoded);
545 if (value >= threshold) {
550 if (value > threshold || current != token.end_ ||
551 digit > maxIntegerValue % 10) {
552 return decodeDouble(token, decoded);
555 value = value * 10 + digit;
557 if (isNegative && value == maxIntegerValue)
568bool Reader::decodeDouble(Token& token) {
570 if (!decodeDouble(token, decoded))
572 currentValue().swapPayload(decoded);
573 currentValue().setOffsetStart(token.start_ - begin_);
574 currentValue().setOffsetLimit(token.end_ - begin_);
578bool Reader::decodeDouble(Token& token,
Value& decoded) {
581 is.imbue(std::locale::classic());
582 if (!(is >> value)) {
583 if (value == std::numeric_limits<double>::max())
584 value = std::numeric_limits<double>::infinity();
585 else if (value == std::numeric_limits<double>::lowest())
586 value = -std::numeric_limits<double>::infinity();
593 else if (!std::isinf(value) && std::fpclassify(value) != FP_SUBNORMAL)
595 "'" +
String(token.start_, token.end_) +
"' is not a number.", token);
601bool Reader::decodeString(Token& token) {
603 if (!decodeString(token, decoded_string))
605 Value decoded(decoded_string);
606 currentValue().swapPayload(decoded);
607 currentValue().setOffsetStart(token.start_ - begin_);
608 currentValue().setOffsetLimit(token.end_ - begin_);
612bool Reader::decodeString(Token& token,
String& decoded) {
613 decoded.reserve(
static_cast<size_t>(token.end_ - token.start_ - 2));
614 Location current = token.start_ + 1;
616 while (current != end) {
622 return addError(
"Empty escape sequence in string", token, current);
623 Char escape = *current++;
650 unsigned int unicode;
651 if (!decodeUnicodeCodePoint(token, current, end, unicode))
653 decoded += codePointToUTF8(unicode);
656 return addError(
"Bad escape sequence in string", token, current);
659 if (
static_cast<unsigned char>(c) < 0x20)
660 return addError(
"Control character in string", token, current - 1);
667bool Reader::decodeUnicodeCodePoint(Token& token, Location& current,
668 Location end,
unsigned int& unicode) {
670 if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
672 if (unicode >= 0xD800 && unicode <= 0xDBFF) {
674 if (end - current < 6)
676 "additional six characters expected to parse unicode surrogate pair.",
678 if (*(current++) ==
'\\' && *(current++) ==
'u') {
679 unsigned int surrogatePair;
680 if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
681 unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
685 return addError(
"expecting another \\u token to begin the second half of "
686 "a unicode surrogate pair",
692bool Reader::decodeUnicodeEscapeSequence(Token& token, Location& current,
694 unsigned int& ret_unicode) {
695 if (end - current < 4)
697 "Bad unicode escape sequence in string: four digits expected.", token,
700 for (
int index = 0; index < 4; ++index) {
703 if (c >=
'0' && c <=
'9')
705 else if (c >=
'a' && c <=
'f')
706 unicode += c -
'a' + 10;
707 else if (c >=
'A' && c <=
'F')
708 unicode += c -
'A' + 10;
711 "Bad unicode escape sequence in string: hexadecimal digit expected.",
714 ret_unicode =
static_cast<unsigned int>(unicode);
718bool Reader::addError(
const String& message, Token& token, Location extra) {
721 info.message_ = message;
723 errors_.push_back(info);
727bool Reader::recoverFromError(TokenType skipUntilToken) {
728 size_t const errorCount = errors_.size();
731 if (!readToken(skip))
732 errors_.resize(errorCount);
733 if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
736 errors_.resize(errorCount);
740bool Reader::addErrorAndRecover(
const String& message, Token& token,
741 TokenType skipUntilToken) {
742 addError(message, token);
743 return recoverFromError(skipUntilToken);
746Value& Reader::currentValue() {
return *(nodes_.top()); }
749 if (current_ == end_)
754void Reader::getLocationLineAndColumn(Location location,
int& line,
759 while (current < location && current != end_) {
762 if (current != end_ && *current ==
'\n')
764 lastLineStart = current;
766 }
else if (c ==
'\n') {
767 lastLineStart = current;
772 column = int(location - lastLineStart) + 1;
776String Reader::getLocationLineAndColumn(Location location)
const {
778 getLocationLineAndColumn(location, line, column);
779 char buffer[18 + 16 + 16 + 1];
780 jsoncpp_snprintf(buffer,
sizeof(buffer),
"Line %d, Column %d", line, column);
791 for (
const auto& error : errors_) {
793 "* " + getLocationLineAndColumn(error.token_.start_) +
"\n";
794 formattedMessage +=
" " + error.message_ +
"\n";
797 "See " + getLocationLineAndColumn(error.extra_) +
" for detail.\n";
799 return formattedMessage;
803 std::vector<Reader::StructuredError> allErrors;
804 for (
const auto& error : errors_) {
808 structured.
message = error.message_;
809 allErrors.push_back(structured);
815 ptrdiff_t
const length = end_ - begin_;
819 token.type_ = tokenError;
824 info.message_ = message;
825 info.extra_ =
nullptr;
826 errors_.push_back(info);
831 const Value& extra) {
832 ptrdiff_t
const length = end_ - begin_;
837 token.type_ = tokenError;
842 info.message_ = message;
844 errors_.push_back(info);
854 static OurFeatures all();
856 bool allowTrailingCommas_;
858 bool allowDroppedNullPlaceholders_;
859 bool allowNumericKeys_;
860 bool allowSingleQuotes_;
863 bool allowSpecialFloats_;
868OurFeatures OurFeatures::all() {
return {}; }
878 using Location =
const Char*;
880 explicit OurReader(OurFeatures
const& features);
881 bool parse(
const char* beginDoc,
const char* endDoc, Value& root,
882 bool collectComments =
true);
883 String getFormattedErrorMessages()
const;
884 std::vector<CharReader::StructuredError> getStructuredErrors()
const;
887 OurReader(OurReader
const&);
888 void operator=(OurReader
const&);
891 tokenEndOfStream = 0,
905 tokenMemberSeparator,
924 using Errors = std::deque<ErrorInfo>;
926 bool readToken(Token& token);
927 bool readTokenSkippingComments(Token& token);
929 void skipCommentTokens();
930 void skipBom(
bool skipBom);
931 bool match(
const Char* pattern,
int patternLength);
933 bool readCStyleComment(
bool* containsNewLineResult);
934 bool readCppStyleComment();
936 bool readStringSingleQuote();
937 bool readNumber(
bool checkInf);
939 bool readObject(Token& token);
940 bool readArray(Token& token);
941 bool decodeNumber(Token& token);
942 bool decodeNumber(Token& token, Value& decoded);
943 bool decodeString(Token& token);
944 bool decodeString(Token& token,
String& decoded);
945 bool decodeDouble(Token& token);
946 bool decodeDouble(Token& token, Value& decoded);
947 bool decodeUnicodeCodePoint(Token& token, Location& current, Location end,
948 unsigned int& unicode);
949 bool decodeUnicodeEscapeSequence(Token& token, Location& current,
950 Location end,
unsigned int& unicode);
951 bool addError(
const String& message, Token& token, Location extra =
nullptr);
952 bool recoverFromError(TokenType skipUntilToken);
953 bool addErrorAndRecover(
const String& message, Token& token,
954 TokenType skipUntilToken);
955 void skipUntilSpace();
956 Value& currentValue();
958 void getLocationLineAndColumn(Location location,
int& line,
960 String getLocationLineAndColumn(Location location)
const;
963 static String normalizeEOL(Location begin, Location end);
964 static bool containsNewLine(Location begin, Location end);
966 using Nodes = std::stack<Value*>;
971 Location begin_ =
nullptr;
972 Location end_ =
nullptr;
973 Location current_ =
nullptr;
974 Location lastValueEnd_ =
nullptr;
975 Value* lastValue_ =
nullptr;
976 bool lastValueHasAComment_ =
false;
979 OurFeatures
const features_;
980 bool collectComments_ =
false;
992 static thread_local size_t count = 0;
996bool OurReader::containsNewLine(OurReader::Location begin,
997 OurReader::Location end) {
999 return std::any_of(begin, end, [](
char b) {
return b ==
'\n' || b ==
'\r'; });
1002OurReader::OurReader(OurFeatures
const& features) : features_(features) {}
1004bool OurReader::parse(
const char* beginDoc,
const char* endDoc, Value& root,
1005 bool collectComments) {
1006 if (!features_.allowComments_) {
1007 collectComments =
false;
1012 collectComments_ = collectComments;
1014 lastValueEnd_ =
nullptr;
1015 lastValue_ =
nullptr;
1016 commentsBefore_.clear();
1018 while (!nodes_.empty())
1023 skipBom(features_.skipBom_);
1024 bool successful = readValue();
1027 readTokenSkippingComments(token);
1028 if (features_.failIfExtra_ && (token.type_ != tokenEndOfStream)) {
1029 addError(
"Extra non-whitespace after JSON value.", token);
1032 if (collectComments_ && !commentsBefore_.empty())
1033 root.setComment(commentsBefore_, commentAfter);
1034 if (features_.strictRoot_) {
1035 if (!root.isArray() && !root.isObject()) {
1038 token.type_ = tokenError;
1039 token.start_ = beginDoc;
1040 token.end_ = endDoc;
1042 "A valid JSON document must be either an array or an object value.",
1050bool OurReader::readValue() {
1052 if (nodes_.size() > features_.stackLimit_) {
1053#if JSON_USE_EXCEPTION
1057 token.start_ = current_;
1058 token.end_ = current_;
1059 token.type_ = tokenError;
1061 "Exceeded stackLimit for nested object and/or array values.", token);
1064 readTokenSkippingComments(token);
1065 bool successful =
true;
1067 if (collectComments_ && !commentsBefore_.empty()) {
1068 currentValue().setComment(commentsBefore_, commentBefore);
1069 commentsBefore_.clear();
1072 switch (token.type_) {
1073 case tokenObjectBegin:
1074 successful = readObject(token);
1075 currentValue().setOffsetLimit(current_ - begin_);
1077 case tokenArrayBegin:
1078 successful = readArray(token);
1079 currentValue().setOffsetLimit(current_ - begin_);
1082 successful = decodeNumber(token);
1085 successful = decodeString(token);
1089 currentValue().swapPayload(v);
1090 currentValue().setOffsetStart(token.start_ - begin_);
1091 currentValue().setOffsetLimit(token.end_ - begin_);
1095 currentValue().swapPayload(v);
1096 currentValue().setOffsetStart(token.start_ - begin_);
1097 currentValue().setOffsetLimit(token.end_ - begin_);
1101 currentValue().swapPayload(v);
1102 currentValue().setOffsetStart(token.start_ - begin_);
1103 currentValue().setOffsetLimit(token.end_ - begin_);
1106 Value v(std::numeric_limits<double>::quiet_NaN());
1107 currentValue().swapPayload(v);
1108 currentValue().setOffsetStart(token.start_ - begin_);
1109 currentValue().setOffsetLimit(token.end_ - begin_);
1112 Value v(std::numeric_limits<double>::infinity());
1113 currentValue().swapPayload(v);
1114 currentValue().setOffsetStart(token.start_ - begin_);
1115 currentValue().setOffsetLimit(token.end_ - begin_);
1118 Value v(-std::numeric_limits<double>::infinity());
1119 currentValue().swapPayload(v);
1120 currentValue().setOffsetStart(token.start_ - begin_);
1121 currentValue().setOffsetLimit(token.end_ - begin_);
1123 case tokenArraySeparator:
1124 case tokenObjectEnd:
1126 if (features_.allowDroppedNullPlaceholders_) {
1131 currentValue().swapPayload(v);
1132 currentValue().setOffsetStart(current_ - begin_ - 1);
1133 currentValue().setOffsetLimit(current_ - begin_);
1137 currentValue().setOffsetStart(token.start_ - begin_);
1138 currentValue().setOffsetLimit(token.end_ - begin_);
1139 return addError(
"Syntax error: value, object or array expected.", token);
1142 if (collectComments_) {
1143 lastValueEnd_ = current_;
1144 lastValueHasAComment_ =
false;
1145 lastValue_ = ¤tValue();
1151bool OurReader::readTokenSkippingComments(Token& token) {
1152 bool success = readToken(token);
1153 if (features_.allowComments_) {
1154 while (success && token.type_ == tokenComment) {
1155 success = readToken(token);
1161bool OurReader::readToken(Token& token) {
1163 token.start_ = current_;
1164 Char c = getNextChar();
1168 token.type_ = tokenObjectBegin;
1171 token.type_ = tokenObjectEnd;
1174 token.type_ = tokenArrayBegin;
1177 token.type_ = tokenArrayEnd;
1180 token.type_ = tokenString;
1184 if (features_.allowSingleQuotes_) {
1185 token.type_ = tokenString;
1186 ok = readStringSingleQuote();
1193 token.type_ = tokenComment;
1206 token.type_ = tokenNumber;
1210 if (readNumber(
true)) {
1211 token.type_ = tokenNumber;
1213 token.type_ = tokenNegInf;
1214 ok = features_.allowSpecialFloats_ && match(
"nfinity", 7);
1218 if (readNumber(
true)) {
1219 token.type_ = tokenNumber;
1221 token.type_ = tokenPosInf;
1222 ok = features_.allowSpecialFloats_ && match(
"nfinity", 7);
1226 token.type_ = tokenTrue;
1227 ok = match(
"rue", 3);
1230 token.type_ = tokenFalse;
1231 ok = match(
"alse", 4);
1234 token.type_ = tokenNull;
1235 ok = match(
"ull", 3);
1238 if (features_.allowSpecialFloats_) {
1239 token.type_ = tokenNaN;
1240 ok = match(
"aN", 2);
1246 if (features_.allowSpecialFloats_) {
1247 token.type_ = tokenPosInf;
1248 ok = match(
"nfinity", 7);
1254 token.type_ = tokenArraySeparator;
1257 token.type_ = tokenMemberSeparator;
1260 token.type_ = tokenEndOfStream;
1267 token.type_ = tokenError;
1268 token.end_ = current_;
1272void OurReader::skipSpaces() {
1273 while (current_ != end_) {
1275 if (c ==
' ' || c ==
'\t' || c ==
'\r' || c ==
'\n')
1287void OurReader::skipCommentTokens() {
1289 if (!features_.allowComments_)
1291 while (current_ != end_ && *current_ ==
'/' && (current_ + 1) != end_ &&
1292 (current_[1] ==
'/' || current_[1] ==
'*')) {
1294 if (!readToken(comment))
1300void OurReader::skipBom(
bool skipBom) {
1303 if ((end_ - begin_) >= 3 && strncmp(begin_,
"\xEF\xBB\xBF", 3) == 0) {
1310bool OurReader::match(
const Char* pattern,
int patternLength) {
1311 if (end_ - current_ < patternLength)
1313 int index = patternLength;
1315 if (current_[index] != pattern[index])
1317 current_ += patternLength;
1321bool OurReader::readComment() {
1322 const Location commentBegin = current_ - 1;
1323 const Char c = getNextChar();
1324 bool successful =
false;
1325 bool cStyleWithEmbeddedNewline =
false;
1327 const bool isCStyleComment = (c ==
'*');
1328 const bool isCppStyleComment = (c ==
'/');
1329 if (isCStyleComment) {
1330 successful = readCStyleComment(&cStyleWithEmbeddedNewline);
1331 }
else if (isCppStyleComment) {
1332 successful = readCppStyleComment();
1338 if (collectComments_) {
1341 if (!lastValueHasAComment_) {
1342 if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
1343 if (isCppStyleComment || !cStyleWithEmbeddedNewline) {
1351 lastValueHasAComment_ =
true;
1354 addComment(commentBegin, current_, placement);
1359String OurReader::normalizeEOL(OurReader::Location begin,
1360 OurReader::Location end) {
1362 normalized.reserve(
static_cast<size_t>(end - begin));
1363 OurReader::Location current = begin;
1364 while (current != end) {
1365 char c = *current++;
1367 if (current != end && *current ==
'\n')
1379void OurReader::addComment(Location begin, Location end,
1380 CommentPlacement placement) {
1381 assert(collectComments_);
1382 const String& normalized = normalizeEOL(begin, end);
1383 if (placement == commentAfterOnSameLine) {
1384 assert(lastValue_ !=
nullptr);
1385 lastValue_->setComment(normalized, placement);
1387 commentsBefore_ += normalized;
1391bool OurReader::readCStyleComment(
bool* containsNewLineResult) {
1392 *containsNewLineResult =
false;
1394 while ((current_ + 1) < end_) {
1395 Char c = getNextChar();
1396 if (c ==
'*' && *current_ ==
'/')
1399 *containsNewLineResult =
true;
1402 return getNextChar() ==
'/';
1405bool OurReader::readCppStyleComment() {
1406 while (current_ != end_) {
1407 Char c = getNextChar();
1412 if (current_ != end_ && *current_ ==
'\n')
1421bool OurReader::readNumber(
bool checkInf) {
1422 Location p = current_;
1423 if (checkInf && p != end_ && *p ==
'I') {
1429 while (c >=
'0' && c <=
'9')
1430 c = (current_ = p) < end_ ? *p++ :
'\0';
1433 c = (current_ = p) < end_ ? *p++ :
'\0';
1434 while (c >=
'0' && c <=
'9')
1435 c = (current_ = p) < end_ ? *p++ :
'\0';
1438 if (c ==
'e' || c ==
'E') {
1439 c = (current_ = p) < end_ ? *p++ :
'\0';
1440 if (c ==
'+' || c ==
'-')
1441 c = (current_ = p) < end_ ? *p++ :
'\0';
1442 while (c >=
'0' && c <=
'9')
1443 c = (current_ = p) < end_ ? *p++ :
'\0';
1447bool OurReader::readString() {
1449 while (current_ != end_) {
1459bool OurReader::readStringSingleQuote() {
1461 while (current_ != end_) {
1471bool OurReader::readObject(Token& token) {
1474 Value init(objectValue);
1475 currentValue().swapPayload(init);
1476 currentValue().setOffsetStart(token.start_ - begin_);
1477 while (readTokenSkippingComments(tokenName)) {
1478 if (tokenName.type_ == tokenObjectEnd &&
1480 features_.allowTrailingCommas_))
1483 if (tokenName.type_ == tokenString) {
1484 if (!decodeString(tokenName, name))
1485 return recoverFromError(tokenObjectEnd);
1486 }
else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
1488 if (!decodeNumber(tokenName, numberName))
1489 return recoverFromError(tokenObjectEnd);
1490 name = numberName.asString();
1494 if (name.length() >= (1U << 30))
1496 if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
1497 String msg =
"Duplicate key: '" + name +
"'";
1498 return addErrorAndRecover(msg, tokenName, tokenObjectEnd);
1502 if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
1503 return addErrorAndRecover(
"Missing ':' after object member name", colon,
1506 Value& value = currentValue()[name];
1507 nodes_.push(&value);
1508 bool ok = readValue();
1511 return recoverFromError(tokenObjectEnd);
1514 if (!readTokenSkippingComments(comma) ||
1515 (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator)) {
1516 return addErrorAndRecover(
"Missing ',' or '}' in object declaration",
1517 comma, tokenObjectEnd);
1519 if (comma.type_ == tokenObjectEnd)
1522 return addErrorAndRecover(
"Missing '}' or object member name", tokenName,
1526bool OurReader::readArray(Token& token) {
1527 Value init(arrayValue);
1528 currentValue().swapPayload(init);
1529 currentValue().setOffsetStart(token.start_ - begin_);
1535 skipCommentTokens();
1536 if (current_ != end_ && *current_ ==
']' &&
1538 (features_.allowTrailingCommas_ &&
1539 !features_.allowDroppedNullPlaceholders_)))
1543 readToken(endArray);
1546 Value& value = currentValue()[index++];
1547 nodes_.push(&value);
1548 bool ok = readValue();
1551 return recoverFromError(tokenArrayEnd);
1555 ok = readTokenSkippingComments(currentToken);
1556 bool badTokenType = (currentToken.type_ != tokenArraySeparator &&
1557 currentToken.type_ != tokenArrayEnd);
1558 if (!ok || badTokenType) {
1559 return addErrorAndRecover(
"Missing ',' or ']' in array declaration",
1560 currentToken, tokenArrayEnd);
1562 if (currentToken.type_ == tokenArrayEnd)
1568bool OurReader::decodeNumber(Token& token) {
1570 if (!decodeNumber(token, decoded))
1572 currentValue().swapPayload(decoded);
1573 currentValue().setOffsetStart(token.start_ - begin_);
1574 currentValue().setOffsetLimit(token.end_ - begin_);
1578bool OurReader::decodeNumber(Token& token, Value& decoded) {
1582 Location current = token.start_;
1583 const bool isNegative = *current ==
'-';
1591 static_assert(Value::maxLargestInt <= Value::maxLargestUInt,
1592 "Int must be smaller than UInt");
1598 static_assert(Value::minLargestInt <= -Value::maxLargestInt,
1599 "The absolute value of minLargestInt must be greater than or "
1600 "equal to maxLargestInt");
1601 static_assert(Value::minLargestInt / 10 >= -Value::maxLargestInt,
1602 "The absolute value of minLargestInt must be only 1 magnitude "
1603 "larger than maxLargest Int");
1605 static constexpr Value::LargestUInt positive_threshold =
1606 Value::maxLargestUInt / 10;
1607 static constexpr Value::UInt positive_last_digit = Value::maxLargestUInt % 10;
1614 static constexpr auto negative_threshold =
1615 Value::LargestUInt(-(Value::minLargestInt / 10));
1616 static constexpr auto negative_last_digit =
1617 Value::UInt(-(Value::minLargestInt % 10));
1619 const Value::LargestUInt threshold =
1620 isNegative ? negative_threshold : positive_threshold;
1621 const Value::UInt max_last_digit =
1622 isNegative ? negative_last_digit : positive_last_digit;
1624 Value::LargestUInt value = 0;
1625 while (current < token.end_) {
1626 Char c = *current++;
1627 if (c <
'0' || c >
'9')
1628 return decodeDouble(token, decoded);
1630 const auto digit(
static_cast<Value::UInt
>(c -
'0'));
1631 if (value >= threshold) {
1637 if (value > threshold || current != token.end_ ||
1638 digit > max_last_digit) {
1639 return decodeDouble(token, decoded);
1642 value = value * 10 + digit;
1647 const auto last_digit =
static_cast<Value::UInt
>(value % 10);
1648 decoded = -Value::LargestInt(value / 10) * 10 - last_digit;
1649 }
else if (value <= Value::LargestUInt(Value::maxLargestInt)) {
1650 decoded = Value::LargestInt(value);
1658bool OurReader::decodeDouble(Token& token) {
1660 if (!decodeDouble(token, decoded))
1662 currentValue().swapPayload(decoded);
1663 currentValue().setOffsetStart(token.start_ - begin_);
1664 currentValue().setOffsetLimit(token.end_ - begin_);
1668bool OurReader::decodeDouble(Token& token, Value& decoded) {
1671 is.imbue(std::locale::classic());
1672 if (!(is >> value)) {
1673 if (value == std::numeric_limits<double>::max())
1674 value = std::numeric_limits<double>::infinity();
1675 else if (value == std::numeric_limits<double>::lowest())
1676 value = -std::numeric_limits<double>::infinity();
1683 else if (!std::isinf(value) && std::fpclassify(value) != FP_SUBNORMAL)
1685 "'" +
String(token.start_, token.end_) +
"' is not a number.", token);
1691bool OurReader::decodeString(Token& token) {
1693 if (!decodeString(token, decoded_string))
1695 Value decoded(decoded_string);
1696 currentValue().swapPayload(decoded);
1697 currentValue().setOffsetStart(token.start_ - begin_);
1698 currentValue().setOffsetLimit(token.end_ - begin_);
1702bool OurReader::decodeString(Token& token, String& decoded) {
1703 decoded.reserve(
static_cast<size_t>(token.end_ - token.start_ - 2));
1704 Location current = token.start_ + 1;
1705 Location end = token.end_ - 1;
1706 while (current != end) {
1707 Char c = *current++;
1712 return addError(
"Empty escape sequence in string", token, current);
1713 Char escape = *current++;
1740 unsigned int unicode;
1741 if (!decodeUnicodeCodePoint(token, current, end, unicode))
1743 decoded += codePointToUTF8(unicode);
1746 return addError(
"Bad escape sequence in string", token, current);
1749 if (
static_cast<unsigned char>(c) < 0x20)
1750 return addError(
"Control character in string", token, current - 1);
1757bool OurReader::decodeUnicodeCodePoint(Token& token, Location& current,
1758 Location end,
unsigned int& unicode) {
1760 if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
1762 if (unicode >= 0xD800 && unicode <= 0xDBFF) {
1764 if (end - current < 6)
1766 "additional six characters expected to parse unicode surrogate pair.",
1768 if (*(current++) ==
'\\' && *(current++) ==
'u') {
1769 unsigned int surrogatePair;
1770 if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
1771 unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
1775 return addError(
"expecting another \\u token to begin the second half of "
1776 "a unicode surrogate pair",
1782bool OurReader::decodeUnicodeEscapeSequence(Token& token, Location& current,
1784 unsigned int& ret_unicode) {
1785 if (end - current < 4)
1787 "Bad unicode escape sequence in string: four digits expected.", token,
1790 for (
int index = 0; index < 4; ++index) {
1791 Char c = *current++;
1793 if (c >=
'0' && c <=
'9')
1795 else if (c >=
'a' && c <=
'f')
1796 unicode += c -
'a' + 10;
1797 else if (c >=
'A' && c <=
'F')
1798 unicode += c -
'A' + 10;
1801 "Bad unicode escape sequence in string: hexadecimal digit expected.",
1804 ret_unicode =
static_cast<unsigned int>(unicode);
1808bool OurReader::addError(
const String& message, Token& token, Location extra) {
1810 info.token_ = token;
1811 info.message_ = message;
1812 info.extra_ = extra;
1813 errors_.push_back(info);
1817bool OurReader::recoverFromError(TokenType skipUntilToken) {
1818 size_t errorCount = errors_.size();
1821 if (!readToken(skip))
1822 errors_.resize(errorCount);
1823 if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
1826 errors_.resize(errorCount);
1830bool OurReader::addErrorAndRecover(
const String& message, Token& token,
1831 TokenType skipUntilToken) {
1832 addError(message, token);
1833 return recoverFromError(skipUntilToken);
1836Value& OurReader::currentValue() {
return *(nodes_.top()); }
1838OurReader::Char OurReader::getNextChar() {
1839 if (current_ == end_)
1844void OurReader::getLocationLineAndColumn(Location location,
int& line,
1845 int& column)
const {
1846 Location current = begin_;
1847 Location lastLineStart = current;
1849 while (current < location && current != end_) {
1850 Char c = *current++;
1852 if (current != end_ && *current ==
'\n')
1854 lastLineStart = current;
1856 }
else if (c ==
'\n') {
1857 lastLineStart = current;
1862 column = int(location - lastLineStart) + 1;
1866String OurReader::getLocationLineAndColumn(Location location)
const {
1868 getLocationLineAndColumn(location, line, column);
1869 char buffer[18 + 16 + 16 + 1];
1870 jsoncpp_snprintf(buffer,
sizeof(buffer),
"Line %d, Column %d", line, column);
1874String OurReader::getFormattedErrorMessages()
const {
1876 for (
const auto& error : errors_) {
1878 "* " + getLocationLineAndColumn(error.token_.start_) +
"\n";
1879 formattedMessage +=
" " + error.message_ +
"\n";
1882 "See " + getLocationLineAndColumn(error.extra_) +
" for detail.\n";
1884 return formattedMessage;
1887std::vector<CharReader::StructuredError>
1888OurReader::getStructuredErrors()
const {
1889 std::vector<CharReader::StructuredError> allErrors;
1890 for (
const auto& error : errors_) {
1891 CharReader::StructuredError structured;
1892 structured.offset_start = error.token_.start_ - begin_;
1893 structured.offset_limit = error.token_.end_ - begin_;
1894 structured.message = error.message_;
1895 allErrors.push_back(structured);
1900class OurCharReader :
public CharReader {
1903 OurCharReader(
bool collectComments, OurFeatures
const& features)
1905 std::unique_ptr<OurImpl>(new OurImpl(collectComments, features))) {}
1908 class OurImpl :
public Impl {
1910 OurImpl(
bool collectComments, OurFeatures
const& features)
1911 : collectComments_(collectComments), reader_(features) {}
1913 bool parse(
char const* beginDoc,
char const* endDoc, Value* root,
1914 String* errs)
override {
1915 bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
1917 *errs = reader_.getFormattedErrorMessages();
1922 std::vector<CharReader::StructuredError>
1923 getStructuredErrors()
const override {
1924 return reader_.getStructuredErrors();
1928 bool const collectComments_;
1936 bool collectComments =
settings_[
"collectComments"].asBool();
1937 OurFeatures features = OurFeatures::all();
1938 features.allowComments_ =
settings_[
"allowComments"].asBool();
1939 features.allowTrailingCommas_ =
settings_[
"allowTrailingCommas"].asBool();
1940 features.strictRoot_ =
settings_[
"strictRoot"].asBool();
1941 features.allowDroppedNullPlaceholders_ =
1942 settings_[
"allowDroppedNullPlaceholders"].asBool();
1943 features.allowNumericKeys_ =
settings_[
"allowNumericKeys"].asBool();
1944 features.allowSingleQuotes_ =
settings_[
"allowSingleQuotes"].asBool();
1948 features.stackLimit_ =
static_cast<size_t>(
settings_[
"stackLimit"].asUInt());
1949 features.failIfExtra_ =
settings_[
"failIfExtra"].asBool();
1950 features.rejectDupKeys_ =
settings_[
"rejectDupKeys"].asBool();
1951 features.allowSpecialFloats_ =
settings_[
"allowSpecialFloats"].asBool();
1952 features.skipBom_ =
settings_[
"skipBom"].asBool();
1953 return new OurCharReader(collectComments, features);
1957 static const auto& valid_keys = *
new std::set<String>{
1960 "allowTrailingCommas",
1962 "allowDroppedNullPlaceholders",
1964 "allowSingleQuotes",
1968 "allowSpecialFloats",
1972 auto key = si.name();
1973 if (valid_keys.count(key))
1976 (*invalid)[key] = *si;
1980 return invalid ? invalid->
empty() :
true;
1989 (*settings)[
"allowComments"] =
false;
1990 (*settings)[
"allowTrailingCommas"] =
false;
1991 (*settings)[
"strictRoot"] =
true;
1992 (*settings)[
"allowDroppedNullPlaceholders"] =
false;
1993 (*settings)[
"allowNumericKeys"] =
false;
1994 (*settings)[
"allowSingleQuotes"] =
false;
1995 (*settings)[
"stackLimit"] = 256;
1996 (*settings)[
"failIfExtra"] =
true;
1997 (*settings)[
"rejectDupKeys"] =
true;
1998 (*settings)[
"allowSpecialFloats"] =
false;
1999 (*settings)[
"skipBom"] =
true;
2005 (*settings)[
"collectComments"] =
true;
2006 (*settings)[
"allowComments"] =
true;
2007 (*settings)[
"allowTrailingCommas"] =
true;
2008 (*settings)[
"strictRoot"] =
false;
2009 (*settings)[
"allowDroppedNullPlaceholders"] =
false;
2010 (*settings)[
"allowNumericKeys"] =
false;
2011 (*settings)[
"allowSingleQuotes"] =
false;
2012 (*settings)[
"stackLimit"] = 256;
2013 (*settings)[
"failIfExtra"] =
false;
2014 (*settings)[
"rejectDupKeys"] =
false;
2015 (*settings)[
"allowSpecialFloats"] =
false;
2016 (*settings)[
"skipBom"] =
true;
2022 (*settings)[
"allowComments"] =
false;
2023 (*settings)[
"allowTrailingCommas"] =
false;
2024 (*settings)[
"strictRoot"] =
false;
2025 (*settings)[
"allowDroppedNullPlaceholders"] =
false;
2026 (*settings)[
"allowNumericKeys"] =
false;
2027 (*settings)[
"allowSingleQuotes"] =
false;
2028 (*settings)[
"stackLimit"] = 256;
2029 (*settings)[
"failIfExtra"] =
true;
2030 (*settings)[
"rejectDupKeys"] =
false;
2031 (*settings)[
"allowSpecialFloats"] =
false;
2032 (*settings)[
"skipBom"] =
false;
2036std::vector<CharReader::StructuredError>
2038 return _impl->getStructuredErrors();
2043 return _impl->parse(beginDoc, endDoc, root, errs);
2052 ssin << sin.rdbuf();
2053 String doc = std::move(ssin).str();
2054 char const* begin = doc.data();
2055 char const* end = begin + doc.size();
2058 return reader->parse(begin, end, root, errs);
virtual CharReader * newCharReader() const =0
Allocate a CharReader via operator new().
Build a CharReader implementation.
static void setDefaults(Json::Value *settings)
Called by ctor, but you can use this to reset settings_.
static void ecma404Mode(Json::Value *settings)
ECMA-404 mode.
Value & operator[](const String &key)
A simple way to update a specific setting.
CharReader * newCharReader() const override
Allocate a CharReader via operator new().
static void strictMode(Json::Value *settings)
Same as old Features::strictMode().
Json::Value settings_
Configuration of this builder.
~CharReaderBuilder() override
bool validate(Json::Value *invalid) const
Interface for reading JSON from a char array.
std::vector< StructuredError > getStructuredErrors() const
Returns a vector of structured errors encountered while parsing.
virtual bool parse(char const *beginDoc, char const *endDoc, Value *root, String *errs)
Read a Value from a JSON document.
Configuration passed to reader and writer.
bool strictRoot_
true if root must be either an array or an object value.
bool allowComments_
true if comments are allowed. Default: true.
bool allowDroppedNullPlaceholders_
true if dropped null placeholders are allowed. Default: false.
static Features all()
A configuration that allows all features and assumes all strings are UTF-8.
Features()
Initialize the configuration like JsonConfig::allFeatures;.
static Features strictMode()
A configuration that is strictly compatible with the JSON specification.
bool allowNumericKeys_
true if numeric object key are allowed. Default: false.
Reader()
Constructs a Reader allowing all features for parsing.
bool pushError(const Value &value, const String &message)
Add a semantic error message.
bool good() const
Return whether there are any errors.
std::vector< StructuredError > getStructuredErrors() const
Returns a vector of structured errors encountered while parsing.
String getFormatedErrorMessages() const
Returns a user friendly string that list errors in the parsed document.
bool parse(const std::string &document, Value &root, bool collectComments=true)
Read a Value from a JSON document.
String getFormattedErrorMessages() const
Returns a user friendly string that list errors in the parsed document.
bool empty() const
Return true if empty array, empty object, or null; otherwise, false.
static constexpr LargestInt maxLargestInt
Maximum signed integer value that can be stored in a Json::Value.
void setComment(const char *comment, CommentPlacement placement)
ptrdiff_t getOffsetLimit() const
void swapPayload(Value &other)
Swap values but leave comments and source offsets in place.
void setOffsetLimit(ptrdiff_t limit)
Json::LargestInt LargestInt
Json::LargestUInt LargestUInt
void setOffsetStart(ptrdiff_t start)
static constexpr Int maxInt
Maximum signed int value that can be stored in a Json::Value.
static constexpr LargestUInt maxLargestUInt
Maximum unsigned integer value that can be stored in a Json::Value.
static constexpr LargestInt minLargestInt
Minimum signed integer value that can be stored in a Json::Value.
ptrdiff_t getOffsetStart() const
#define jsoncpp_snprintf
If defined, indicates that the source file is amalgamated to prevent private header inclusion.
#define JSONCPP_DEPRECATED_STACK_LIMIT
static size_t const stackLimit_g
JSON (JavaScript Object Notation).
size_t & newlineScanByteCountForTesting()
@ commentAfterOnSameLine
a comment just after a value on the same line
@ commentBefore
a comment placed on the line before a value
@ commentAfter
a comment on the line after a value (only make sense for
std::basic_istringstream< String::value_type, String::traits_type, String::allocator_type > IStringStream
std::unique_ptr< CharReader > CharReaderPtr
@ arrayValue
array value (ordered list)
@ objectValue
object value (collection of name/value pairs).
void throwRuntimeError(String const &msg)
used internally
std::basic_string< char, std::char_traits< char >, Allocator< char > > String
IStream & operator>>(IStream &, Value &)
Read from 'sin' into 'root'.
bool parseFromStream(CharReader::Factory const &, IStream &, Value *root, String *errs)
Consume entire stream and use its begin/end.
std::basic_ostringstream< String::value_type, String::traits_type, String::allocator_type > OStringStream
An error tagged with where in the JSON text it was encountered.